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.

✨ feat: server implement

arvinxx685a6cd5a578
diff --git a/src/features/ChatInput/ActionBar/AgentMode/index.tsx b/src/features/ChatInput/ActionBar/AgentMode/index.tsx
new file mode 100644
index 00000000000..499dfc9d08c
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/AgentMode/index.tsx
@@ -0,0 +1,38 @@
+import { ActionIcon } from '@lobehub/ui';
+import { Bot } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+
+const AgentModeToggle = memo(() => {
+ const { t } = useTranslation('chat');
+ const agentId = useAgentId();
+ const [enableAgentMode, updateAgentConfigById] = useAgentStore((s) => [
+ agentByIdSelectors.getAgentEnableModeById(agentId)(s),
+ s.updateAgentConfigById,
+ ]);
+
+ const handleToggle = (checked: boolean) => {
+ updateAgentConfigById(agentId, { enableAgentMode: checked });
+ };
+
+ return (
+ <ActionIcon
+ icon={Bot}
+ onClick={() => {
+ handleToggle(!enableAgentMode);
+ }}
+ style={{
+ color: enableAgentMode ? 'var(--colorPrimary)' : undefined,
+ }}
+ title={t('agentMode.title', { defaultValue: 'Agent Mode' })}
+ />
+ );
+});
+
+AgentModeToggle.displayName = 'AgentModeToggle';
+
+export default AgentModeToggle;
diff --git a/src/features/ChatInput/ActionBar/History/Controls.tsx b/src/features/ChatInput/ActionBar/History/Controls.tsx
index 34d8ab5458b..20c83d99ffb 100644
--- a/src/features/ChatInput/ActionBar/History/Controls.tsx
+++ b/src/features/ChatInput/ActionBar/History/Controls.tsx
@@ -1,11 +1,14 @@
import { Form, type FormItemProps, SliderWithInput } from '@lobehub/ui';
-import { Switch, Form as AntdForm } from 'antd';
-import { debounce } from 'lodash-es';
+import { Form as AntdForm, Switch } from 'antd';
+import { debounce } from 'es-toolkit/compat';
import { memo, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useAgentStore } from '@/store/agent';
-import { agentChatConfigSelectors } from '@/store/agent/selectors';
+import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
interface ControlsProps {
setUpdating: (updating: boolean) => void;
@@ -14,14 +17,13 @@ interface ControlsProps {
const Controls = memo<ControlsProps>(({ updating, setUpdating }) => {
const { t } = useTranslation('setting');
const [form] = AntdForm.useForm();
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
- const [historyCount, enableHistoryCount, updateAgentConfig] = useAgentStore((s) => {
- return [
- agentChatConfigSelectors.historyCount(s),
- agentChatConfigSelectors.enableHistoryCount(s),
- s.updateAgentChatConfig,
- ];
- });
+ const [historyCount, enableHistoryCount] = useAgentStore((s) => [
+ chatConfigByIdSelectors.getHistoryCountById(agentId)(s),
+ chatConfigByIdSelectors.getEnableHistoryCountById(agentId)(s),
+ ]);
// Sync external store updates to the form without remounting to keep Switch animation
useEffect(() => {
@@ -73,7 +75,7 @@ const Controls = memo<ControlsProps>(({ updating, setUpdating }) => {
itemsType={'flat'}
onValuesChange={debounce(async (values) => {
setUpdating(true);
- await updateAgentConfig(values);
+ await updateAgentChatConfig(values);
setUpdating(false);
}, 500)}
styles={{
diff --git a/src/features/ChatInput/ActionBar/History/index.tsx b/src/features/ChatInput/ActionBar/History/index.tsx
index 7253968933f..78eb7c030b6 100644
--- a/src/features/ChatInput/ActionBar/History/index.tsx
+++ b/src/features/ChatInput/ActionBar/History/index.tsx
@@ -2,18 +2,21 @@ import { Timer, TimerOff } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useAgentStore } from '@/store/agent';
-import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';
import { useIsMobile } from '@/hooks/useIsMobile';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
+import { useAgentId } from '../../hooks/useAgentId';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
import Action from '../components/Action';
import Controls from './Controls';
const History = memo(() => {
- const [isLoading, chatConfig, updateAgentChatConfig] = useAgentStore((s) => [
- agentSelectors.isAgentConfigLoading(s),
- agentChatConfigSelectors.currentChatConfig(s),
- s.updateAgentChatConfig,
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const [isLoading, chatConfig] = useAgentStore((s) => [
+ agentByIdSelectors.isAgentConfigLoadingById(agentId)(s),
+ chatConfigByIdSelectors.getChatConfigById(agentId)(s),
]);
const [updating, setUpdating] = useState(false);
const { t } = useTranslation('setting');
@@ -21,8 +24,8 @@ const History = memo(() => {
const [historyCount, enableHistoryCount] = useAgentStore((s) => {
return [
- agentChatConfigSelectors.historyCount(s),
- agentChatConfigSelectors.enableHistoryCount(s),
+ chatConfigByIdSelectors.getHistoryCountById(agentId)(s),
+ chatConfigByIdSelectors.getEnableHistoryCountById(agentId)(s),
];
});
@@ -43,11 +46,11 @@ const History = memo(() => {
isMobile
? undefined
: async (e) => {
- e?.preventDefault?.();
- e?.stopPropagation?.();
- const next = !Boolean(chatConfig.enableHistoryCount);
- await updateAgentChatConfig({ enableHistoryCount: next });
- }
+ e?.preventDefault?.();
+ e?.stopPropagation?.();
+ const next = !Boolean(chatConfig.enableHistoryCount);
+ await updateAgentChatConfig({ enableHistoryCount: next });
+ }
}
popover={{
content: <Controls setUpdating={setUpdating} updating={updating} />,
diff --git a/src/features/ChatInput/ActionBar/Knowledge/index.tsx b/src/features/ChatInput/ActionBar/Knowledge/index.tsx
index b16c6966e1d..3e5b95ebd92 100644
--- a/src/features/ChatInput/ActionBar/Knowledge/index.tsx
+++ b/src/features/ChatInput/ActionBar/Knowledge/index.tsx
@@ -4,7 +4,7 @@ import { Suspense, memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import TipGuide from '@/components/TipGuide';
-import { AttachKnowledgeModal } from '@/features/KnowledgeBaseModal';
+import { AttachKnowledgeModal } from '@/features/LibraryModal';
import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useUserStore } from '@/store/user';
import { preferenceSelectors } from '@/store/user/selectors';
diff --git a/src/features/ChatInput/ActionBar/Knowledge/useControls.tsx b/src/features/ChatInput/ActionBar/Knowledge/useControls.tsx
index e3262677bf4..b2237498006 100644
--- a/src/features/ChatInput/ActionBar/Knowledge/useControls.tsx
+++ b/src/features/ChatInput/ActionBar/Knowledge/useControls.tsx
@@ -4,10 +4,11 @@ import { ArrowRight, LibraryBig } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import FileIcon from '@/components/FileIcon';
-import RepoIcon from '@/components/RepoIcon';
+import RepoIcon from '@/components/LibIcon';
import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+import { useAgentId } from '../../hooks/useAgentId';
import CheckboxItem from '../components/CheckbokWithLoading';
export const useControls = ({
@@ -18,9 +19,13 @@ export const useControls = ({
setUpdating: (updating: boolean) => void;
}) => {
const { t } = useTranslation('chat');
+ const agentId = useAgentId();
- const files = useAgentStore(agentSelectors.currentAgentFiles, isEqual);
- const knowledgeBases = useAgentStore(agentSelectors.currentAgentKnowledgeBases, isEqual);
+ const files = useAgentStore((s) => agentByIdSelectors.getAgentFilesById(agentId)(s), isEqual);
+ const knowledgeBases = useAgentStore(
+ (s) => agentByIdSelectors.getAgentKnowledgeBasesById(agentId)(s),
+ isEqual,
+ );
const [toggleFile, toggleKnowledgeBase] = useAgentStore((s) => [
s.toggleFile,
@@ -38,7 +43,7 @@ export const useControls = ({
// {
// icon: <RepoIcon />,
// key: 'allRepos',
- // label: <KnowledgeBaseItem id={'all'} label={t('knowledgeBase.allKnowledgeBases')} />,
+ // label: <KnowledgeBaseItem id={'all'} label={t('knowledgeBase.allLibraries')} />,
// },
// ],
// key: 'all',
@@ -88,8 +93,8 @@ export const useControls = ({
),
})),
],
- key: 'relativeFilesOrKnowledgeBases',
- label: t('knowledgeBase.relativeFilesOrKnowledgeBases'),
+ key: 'relativeFilesOrLibraries',
+ label: t('knowledgeBase.relativeFilesOrLibraries'),
type: 'group',
},
{
diff --git a/src/features/ChatInput/ActionBar/Mention/index.tsx b/src/features/ChatInput/ActionBar/Mention/index.tsx
index a3eba97481d..d5c2f8359f0 100644
--- a/src/features/ChatInput/ActionBar/Mention/index.tsx
+++ b/src/features/ChatInput/ActionBar/Mention/index.tsx
@@ -30,7 +30,7 @@ const Mention = memo(() => {
<Avatar
avatar={agent.avatar}
background={agent.backgroundColor ?? undefined}
- shape="circle"
+ shape={'square'}
size={24}
/>
),
diff --git a/src/features/ChatInput/ActionBar/Model/ControlsForm.tsx b/src/features/ChatInput/ActionBar/Model/ControlsForm.tsx
index 0f2701d1ecd..36fe7cdf796 100644
--- a/src/features/ChatInput/ActionBar/Model/ControlsForm.tsx
+++ b/src/features/ChatInput/ActionBar/Model/ControlsForm.tsx
@@ -7,9 +7,11 @@ import { memo } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { useAgentStore } from '@/store/agent';
-import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';
+import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
+import { useAgentId } from '../../hooks/useAgentId';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
import ContextCachingSwitch from './ContextCachingSwitch';
import GPT5ReasoningEffortSlider from './GPT5ReasoningEffortSlider';
import GPT51ReasoningEffortSlider from './GPT51ReasoningEffortSlider';
@@ -24,15 +26,19 @@ import ThinkingSlider from './ThinkingSlider';
const ControlsForm = memo(() => {
const { t } = useTranslation('chat');
- const [model, provider, updateAgentChatConfig] = useAgentStore((s) => [
- agentSelectors.currentAgentModel(s),
- agentSelectors.currentAgentModelProvider(s),
- s.updateAgentChatConfig,
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const [model, provider] = useAgentStore((s) => [
+ agentByIdSelectors.getAgentModelById(agentId)(s),
+ agentByIdSelectors.getAgentModelProviderById(agentId)(s),
]);
const [form] = Form.useForm();
const enableReasoning = AntdForm.useWatch(['enableReasoning'], form);
- const config = useAgentStore(agentChatConfigSelectors.currentChatConfig, isEqual);
+ const config = useAgentStore(
+ (s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s),
+ isEqual,
+ );
const modelExtendParams = useAiInfraStore(aiModelSelectors.modelExtendParams(model, provider));
diff --git a/src/features/ChatInput/ActionBar/Model/GPT51ReasoningEffortSlider.tsx b/src/features/ChatInput/ActionBar/Model/GPT51ReasoningEffortSlider.tsx
index fed0e87d618..3fba79cad83 100644
--- a/src/features/ChatInput/ActionBar/Model/GPT51ReasoningEffortSlider.tsx
+++ b/src/features/ChatInput/ActionBar/Model/GPT51ReasoningEffortSlider.tsx
@@ -3,13 +3,15 @@ import { memo, useCallback } from 'react';
import { Flexbox } from 'react-layout-kit';
import { useAgentStore } from '@/store/agent';
-import { agentChatConfigSelectors } from '@/store/agent/selectors';
+import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
const GPT51ReasoningEffortSlider = memo(() => {
- const [config, updateAgentChatConfig] = useAgentStore((s) => [
- agentChatConfigSelectors.currentChatConfig(s),
- s.updateAgentChatConfig,
- ]);
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
const gpt5_1ReasoningEffort = config.gpt5_1ReasoningEffort || 'none'; // Default to 'none' if not set
diff --git a/src/features/ChatInput/ActionBar/Model/GPT5ReasoningEffortSlider.tsx b/src/features/ChatInput/ActionBar/Model/GPT5ReasoningEffortSlider.tsx
index bfcaa44ac97..f4a14a6d29d 100644
--- a/src/features/ChatInput/ActionBar/Model/GPT5ReasoningEffortSlider.tsx
+++ b/src/features/ChatInput/ActionBar/Model/GPT5ReasoningEffortSlider.tsx
@@ -3,13 +3,15 @@ import { memo, useCallback } from 'react';
import { Flexbox } from 'react-layout-kit';
import { useAgentStore } from '@/store/agent';
-import { agentChatConfigSelectors } from '@/store/agent/selectors';
+import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
const GPT5ReasoningEffortSlider = memo(() => {
- const [config, updateAgentChatConfig] = useAgentStore((s) => [
- agentChatConfigSelectors.currentChatConfig(s),
- s.updateAgentChatConfig,
- ]);
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
const gpt5ReasoningEffort = config.gpt5ReasoningEffort || 'medium'; // Default to 'medium' if not set
diff --git a/src/features/ChatInput/ActionBar/Model/ImageAspectRatioSelect.tsx b/src/features/ChatInput/ActionBar/Model/ImageAspectRatioSelect.tsx
index 18c8213b2e5..69f65fe7881 100644
--- a/src/features/ChatInput/ActionBar/Model/ImageAspectRatioSelect.tsx
+++ b/src/features/ChatInput/ActionBar/Model/ImageAspectRatioSelect.tsx
@@ -2,7 +2,10 @@ import { Select } from 'antd';
import { memo, useCallback, useMemo } from 'react';
import { useAgentStore } from '@/store/agent';
-import { agentChatConfigSelectors } from '@/store/agent/selectors';
+import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
const NANO_BANANA_ASPECT_RATIOS = [
'1:1', // 1024x1024 / 2048x2048 / 4096x4096
@@ -18,10 +21,9 @@ const NANO_BANANA_ASPECT_RATIOS = [
];
const ImageAspectRatioSelect = memo(() => {
- const [config, updateAgentChatConfig] = useAgentStore((s) => [
- agentChatConfigSelectors.currentChatConfig(s),
- s.updateAgentChatConfig,
- ]);
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
const imageAspectRatio = config.imageAspectRatio || '1:1';
diff --git a/src/features/ChatInput/ActionBar/Model/ImageResolutionSlider.tsx b/src/features/ChatInput/ActionBar/Model/ImageResolutionSlider.tsx
index 86f4b8575de..b7822b101a2 100644
--- a/src/features/ChatInput/ActionBar/Model/ImageResolutionSlider.tsx
+++ b/src/features/ChatInput/ActionBar/Model/ImageResolutionSlider.tsx
@@ -3,16 +3,18 @@ import { memo, useCallback } from 'react';
import { Flexbox } from 'react-layout-kit';
import { useAgentStore } from '@/store/agent';
-import { agentChatConfigSelectors } from '@/store/agent/selectors';
+import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
const IMAGE_RESOLUTIONS = ['1K', '2K', '4K'] as const;
type ImageResolution = (typeof IMAGE_RESOLUTIONS)[number];
const ImageResolutionSlider = memo(() => {
- const [config, updateAgentChatConfig] = useAgentStore((s) => [
- agentChatConfigSelectors.currentChatConfig(s),
- s.updateAgentChatConfig,
- ]);
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
const imageResolution = (config.imageResolution as ImageResolution) || '1K';
diff --git a/src/features/ChatInput/ActionBar/Model/ReasoningEffortSlider.tsx b/src/features/ChatInput/ActionBar/Model/ReasoningEffortSlider.tsx
index de494fab0b7..b132d006751 100644
--- a/src/features/ChatInput/ActionBar/Model/ReasoningEffortSlider.tsx
+++ b/src/features/ChatInput/ActionBar/Model/ReasoningEffortSlider.tsx
@@ -3,13 +3,15 @@ import { memo, useCallback } from 'react';
import { Flexbox } from 'react-layout-kit';
import { useAgentStore } from '@/store/agent';
-import { agentChatConfigSelectors } from '@/store/agent/selectors';
+import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
const ReasoningEffortSlider = memo(() => {
- const [config, updateAgentChatConfig] = useAgentStore((s) => [
- agentChatConfigSelectors.currentChatConfig(s),
- s.updateAgentChatConfig,
- ]);
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
const reasoningEffort = config.reasoningEffort || 'medium'; // Default to 'medium' if not set
diff --git a/src/features/ChatInput/ActionBar/Model/TextVerbositySlider.tsx b/src/features/ChatInput/ActionBar/Model/TextVerbositySlider.tsx
index 9790c1de931..c008b10c740 100644
--- a/src/features/ChatInput/ActionBar/Model/TextVerbositySlider.tsx
+++ b/src/features/ChatInput/ActionBar/Model/TextVerbositySlider.tsx
@@ -3,13 +3,15 @@ import { memo, useCallback } from 'react';
import { Flexbox } from 'react-layout-kit';
import { useAgentStore } from '@/store/agent';
-import { agentChatConfigSelectors } from '@/store/agent/selectors';
+import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
const TextVerbositySlider = memo(() => {
- const [config, updateAgentChatConfig] = useAgentStore((s) => [
- agentChatConfigSelectors.currentChatConfig(s),
- s.updateAgentChatConfig,
- ]);
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
const textVerbosity = config.textVerbosity || 'medium'; // Default to 'medium' if not set
diff --git a/src/features/ChatInput/ActionBar/Model/ThinkingLevelSlider.tsx b/src/features/ChatInput/ActionBar/Model/ThinkingLevelSlider.tsx
index 0e9463f1503..ea53cd80aa4 100644
--- a/src/features/ChatInput/ActionBar/Model/ThinkingLevelSlider.tsx
+++ b/src/features/ChatInput/ActionBar/Model/ThinkingLevelSlider.tsx
@@ -3,13 +3,15 @@ import { memo, useCallback } from 'react';
import { Flexbox } from 'react-layout-kit';
import { useAgentStore } from '@/store/agent';
-import { agentChatConfigSelectors } from '@/store/agent/selectors';
+import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
const ThinkingLevelSlider = memo(() => {
- const [config, updateAgentChatConfig] = useAgentStore((s) => [
- agentChatConfigSelectors.currentChatConfig(s),
- s.updateAgentChatConfig,
- ]);
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
const thinkingLevel = config.thinkingLevel || 'high'; // Default to 'high' if not set
diff --git a/src/features/ChatInput/ActionBar/Model/ThinkingSlider.tsx b/src/features/ChatInput/ActionBar/Model/ThinkingSlider.tsx
index a25ff483ceb..64d24a349cd 100644
--- a/src/features/ChatInput/ActionBar/Model/ThinkingSlider.tsx
+++ b/src/features/ChatInput/ActionBar/Model/ThinkingSlider.tsx
@@ -3,13 +3,15 @@ import { memo, useCallback } from 'react';
import { Flexbox } from 'react-layout-kit';
import { useAgentStore } from '@/store/agent';
-import { agentChatConfigSelectors } from '@/store/agent/selectors';
+import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
const ThinkingSlider = memo(() => {
- const [config, updateAgentChatConfig] = useAgentStore((s) => [
- agentChatConfigSelectors.currentChatConfig(s),
- s.updateAgentChatConfig,
- ]);
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
const thinking = config.thinking || 'auto'; // Default to 'auto' if not set
diff --git a/src/features/ChatInput/ActionBar/Model/index.tsx b/src/features/ChatInput/ActionBar/Model/index.tsx
index 578564eae04..98f51edac5b 100644
--- a/src/features/ChatInput/ActionBar/Model/index.tsx
+++ b/src/features/ChatInput/ActionBar/Model/index.tsx
@@ -1,16 +1,18 @@
import { ModelIcon } from '@lobehub/icons';
import { createStyles } from 'antd-style';
import { Settings2Icon } from 'lucide-react';
-import { memo } from 'react';
+import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Center, Flexbox } from 'react-layout-kit';
import ModelSwitchPanel from '@/features/ModelSwitchPanel';
import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
+import { agentByIdSelectors } from '@/store/agent/selectors';
import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
+import { useAgentId } from '../../hooks/useAgentId';
import Action from '../components/Action';
+import { useActionBarContext } from '../context';
import ControlsForm from './ControlsForm';
const useStyles = createStyles(({ css, token, cx }) => ({
@@ -55,19 +57,34 @@ const useStyles = createStyles(({ css, token, cx }) => ({
const ModelSwitch = memo(() => {
const { t } = useTranslation('chat');
const { styles, cx } = useStyles();
+ const { dropdownPlacement } = useActionBarContext();
- const [model, provider] = useAgentStore((s) => [
- agentSelectors.currentAgentModel(s),
- agentSelectors.currentAgentModelProvider(s),
+ const agentId = useAgentId();
+ const [model, provider, updateAgentConfigById] = useAgentStore((s) => [
+ agentByIdSelectors.getAgentModelById(agentId)(s),
+ agentByIdSelectors.getAgentModelProviderById(agentId)(s),
+ s.updateAgentConfigById,
]);
const isModelHasExtendParams = useAiInfraStore(
aiModelSelectors.isModelHasExtendParams(model, provider),
);
+ const handleModelChange = useCallback(
+ async (params: { model: string; provider: string }) => {
+ await updateAgentConfigById(agentId, params);
+ },
+ [agentId, updateAgentConfigById],
+ );
+
return (
<Flexbox align={'center'} className={isModelHasExtendParams ? styles.container : ''} horizontal>
- <ModelSwitchPanel>
+ <ModelSwitchPanel
+ model={model}
+ onModelChange={handleModelChange}
+ placement={dropdownPlacement}
+ provider={provider}
+ >
<Center
className={cx(styles.model, isModelHasExtendParams && styles.modelWithControl)}
height={36}
diff --git a/src/features/ChatInput/ActionBar/Params/Controls.tsx b/src/features/ChatInput/ActionBar/Params/Controls.tsx
index 8d065408c87..363bd1b5db2 100644
--- a/src/features/ChatInput/ActionBar/Params/Controls.tsx
+++ b/src/features/ChatInput/ActionBar/Params/Controls.tsx
@@ -1,8 +1,8 @@
import { Form, type FormItemProps, Tag } from '@lobehub/ui';
import { Form as AntdForm, Checkbox } from 'antd';
import { createStyles } from 'antd-style';
+import { debounce } from 'es-toolkit/compat';
import isEqual from 'fast-deep-equal';
-import { debounce } from 'lodash-es';
import { memo, useCallback, useEffect, useRef } from 'react';
import type { ComponentType } from 'react';
import { useTranslation } from 'react-i18next';
@@ -16,9 +16,12 @@ import {
TopP,
} from '@/features/ModelParamsControl';
import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
+import { agentByIdSelectors } from '@/store/agent/selectors';
import { useServerConfigStore } from '@/store/serverConfig';
+import { useAgentId } from '../../hooks/useAgentId';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
+
interface ControlsProps {
setUpdating: (updating: boolean) => void;
updating: boolean;
@@ -142,10 +145,11 @@ const PARAM_CONFIG = {
const Controls = memo<ControlsProps>(({ setUpdating }) => {
const { t } = useTranslation('setting');
const mobile = useServerConfigStore((s) => s.isMobile);
- const updateAgentConfig = useAgentStore((s) => s.updateAgentConfig);
+ const agentId = useAgentId();
+ const { updateAgentConfig } = useUpdateAgentConfig();
const { styles } = useStyles();
- const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);
+ const config = useAgentStore((s) => agentByIdSelectors.getAgentConfigById(agentId)(s), isEqual);
const [form] = Form.useForm();
const { frequency_penalty, presence_penalty, temperature, top_p } = config.params ?? {};
diff --git a/src/features/ChatInput/ActionBar/Params/index.tsx b/src/features/ChatInput/ActionBar/Params/index.tsx
index be9aec815ab..f3ea97e331c 100644
--- a/src/features/ChatInput/ActionBar/Params/index.tsx
+++ b/src/features/ChatInput/ActionBar/Params/index.tsx
@@ -3,13 +3,17 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/slices/chat';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+import { useAgentId } from '../../hooks/useAgentId';
import Action from '../components/Action';
import Controls from './Controls';
const Params = memo(() => {
- const [isLoading] = useAgentStore((s) => [agentSelectors.isAgentConfigLoading(s)]);
+ const agentId = useAgentId();
+ const [isLoading] = useAgentStore((s) => [
+ agentByIdSelectors.isAgentConfigLoadingById(agentId)(s),
+ ]);
const [updating, setUpdating] = useState(false);
const { t } = useTranslation('setting');
diff --git a/src/features/ChatInput/ActionBar/STT/browser.tsx b/src/features/ChatInput/ActionBar/STT/browser.tsx
index 08fa615e7be..dca6c65a9e1 100644
--- a/src/features/ChatInput/ActionBar/STT/browser.tsx
+++ b/src/features/ChatInput/ActionBar/STT/browser.tsx
@@ -7,7 +7,7 @@ import { useTranslation } from 'react-i18next';
import { SWRConfiguration } from 'swr';
import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/slices/chat';
+import { agentByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
import { useGlobalStore } from '@/store/global';
@@ -15,6 +15,7 @@ import { globalGeneralSelectors } from '@/store/global/selectors';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
+import { useAgentId } from '../../hooks/useAgentId';
import CommonSTT from './common';
interface STTConfig extends SWRConfiguration {
@@ -23,7 +24,11 @@ interface STTConfig extends SWRConfiguration {
const useBrowserSTT = (config: STTConfig) => {
const ttsSettings = useUserStore(settingsSelectors.currentTTS, isEqual);
- const ttsAgentSettings = useAgentStore(agentSelectors.currentAgentTTS, isEqual);
+ const agentId = useAgentId();
+ const ttsAgentSettings = useAgentStore(
+ (s) => agentByIdSelectors.getAgentTTSById(agentId)(s),
+ isEqual,
+ );
const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
const autoStop = ttsSettings.sttAutoStop;
diff --git a/src/features/ChatInput/ActionBar/STT/openai.tsx b/src/features/ChatInput/ActionBar/STT/openai.tsx
index 2538d7d074b..1ddbbf52157 100644
--- a/src/features/ChatInput/ActionBar/STT/openai.tsx
+++ b/src/features/ChatInput/ActionBar/STT/openai.tsx
@@ -10,7 +10,7 @@ import { SWRConfiguration } from 'swr';
import { createHeaderWithOpenAI } from '@/services/_header';
import { API_ENDPOINTS } from '@/services/_url';
import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
+import { agentByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
import { useGlobalStore } from '@/store/global';
@@ -18,6 +18,7 @@ import { globalGeneralSelectors } from '@/store/global/selectors';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
+import { useAgentId } from '../../hooks/useAgentId';
import CommonSTT from './common';
interface STTConfig extends SWRConfiguration {
@@ -26,7 +27,11 @@ interface STTConfig extends SWRConfiguration {
const useOpenaiSTT = (config: STTConfig) => {
const ttsSettings = useUserStore(settingsSelectors.currentTTS, isEqual);
- const ttsAgentSettings = useAgentStore(agentSelectors.currentAgentTTS, isEqual);
+ const agentId = useAgentId();
+ const ttsAgentSettings = useAgentStore(
+ (s) => agentByIdSelectors.getAgentTTSById(agentId)(s),
+ isEqual,
+ );
const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
const autoStop = ttsSettings.sttAutoStop;
diff --git a/src/features/ChatInput/ActionBar/Search/Controls.tsx b/src/features/ChatInput/ActionBar/Search/Controls.tsx
index 5e30c270092..aead2050149 100644
--- a/src/features/ChatInput/ActionBar/Search/Controls.tsx
+++ b/src/features/ChatInput/ActionBar/Search/Controls.tsx
@@ -8,10 +8,12 @@ import { useTranslation } from 'react-i18next';
import { Center, Flexbox } from 'react-layout-kit';
import { useAgentStore } from '@/store/agent';
-import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/slices/chat';
+import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { aiModelSelectors, aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
import { SearchMode } from '@/types/search';
+import { useAgentId } from '../../hooks/useAgentId';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
import FCSearchModel from './FCSearchModel';
import ModelBuiltinSearch from './ModelBuiltinSearch';
@@ -64,10 +66,9 @@ interface NetworkOption {
const Item = memo<NetworkOption>(({ value, description, icon, label }) => {
const { cx, styles } = useStyles();
- const [mode, updateAgentChatConfig] = useAgentStore((s) => [
- agentChatConfigSelectors.agentSearchMode(s),
- s.updateAgentChatConfig,
- ]);
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const mode = useAgentStore((s) => chatConfigByIdSelectors.getSearchModeById(agentId)(s));
return (
<Flexbox
@@ -93,12 +94,14 @@ const Item = memo<NetworkOption>(({ value, description, icon, label }) => {
const Controls = memo(() => {
const { t } = useTranslation('chat');
- const [model, provider, useModelBuiltinSearch, searchMode, updateAgentChatConfig] = useAgentStore((s) => [
- agentSelectors.currentAgentModel(s),
- agentSelectors.currentAgentModelProvider(s),
- agentChatConfigSelectors.useModelBuiltinSearch(s),
- agentChatConfigSelectors.currentChatConfig(s).searchMode,
- s.updateAgentChatConfig,
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+
+ const [model, provider, useModelBuiltinSearch, searchMode] = useAgentStore((s) => [
+ agentByIdSelectors.getAgentModelById(agentId)(s),
+ agentByIdSelectors.getAgentModelProviderById(agentId)(s),
+ chatConfigByIdSelectors.getUseModelBuiltinSearchById(agentId)(s),
+ chatConfigByIdSelectors.getChatConfigById(agentId)(s).searchMode,
]);
const supportFC = useAiInfraStore(aiModelSelectors.isModelSupportToolUse(model, provider));
@@ -111,7 +114,9 @@ const Controls = memo(() => {
const isModelBuiltinSearchInternal = useAiInfraStore(
aiModelSelectors.isModelBuiltinSearchInternal(model, provider),
);
- const modelBuiltinSearchImpl = useAiInfraStore(aiModelSelectors.modelBuiltinSearchImpl(model, provider));
+ const modelBuiltinSearchImpl = useAiInfraStore(
+ aiModelSelectors.modelBuiltinSearchImpl(model, provider),
+ );
useEffect(() => {
if (isModelBuiltinSearchInternal && (searchMode ?? 'off') === 'off') {
@@ -121,33 +126,35 @@ const Controls = memo(() => {
const options: NetworkOption[] = isModelBuiltinSearchInternal
? [
- {
- description: t('search.mode.auto.desc'),
- icon: SparkleIcon,
- label: t('search.mode.auto.title'),
- value: 'auto',
- },
- ]
+ {
+ description: t('search.mode.auto.desc'),
+ icon: SparkleIcon,
+ label: t('search.mode.auto.title'),
+ value: 'auto',
+ },
+ ]
: [
- {
- description: t('search.mode.off.desc'),
- icon: GlobeOffIcon,
- label: t('search.mode.off.title'),
- value: 'off',
- },
- {
- description: t('search.mode.auto.desc'),
- icon: SparkleIcon,
- label: t('search.mode.auto.title'),
- value: 'auto',
- },
- ];
-
- const showModelBuiltinSearch = !isModelBuiltinSearchInternal &&
+ {
+ description: t('search.mode.off.desc'),
+ icon: GlobeOffIcon,
+ label: t('search.mode.off.title'),
+ value: 'off',
+ },
+ {
+ description: t('search.mode.auto.desc'),
+ icon: SparkleIcon,
+ label: t('search.mode.auto.title'),
+ value: 'auto',
+ },
+ ];
+
+ const showModelBuiltinSearch =
+ !isModelBuiltinSearchInternal &&
(isModelHasBuiltinSearchConfig || isProviderHasBuiltinSearchConfig);
const showFCSearchModel =
- !supportFC && (!modelBuiltinSearchImpl || (!isModelBuiltinSearchInternal && !useModelBuiltinSearch));
+ !supportFC &&
+ (!modelBuiltinSearchImpl || (!isModelBuiltinSearchInternal && !useModelBuiltinSearch));
const showDivider = showModelBuiltinSearch || showFCSearchModel;
diff --git a/src/features/ChatInput/ActionBar/Search/FCSearchModel.tsx b/src/features/ChatInput/ActionBar/Search/FCSearchModel.tsx
index 8424163cca0..bcd4a062d27 100644
--- a/src/features/ChatInput/ActionBar/Search/FCSearchModel.tsx
+++ b/src/features/ChatInput/ActionBar/Search/FCSearchModel.tsx
@@ -5,8 +5,10 @@ import { Flexbox } from 'react-layout-kit';
import InfoTooltip from '@/components/InfoTooltip';
import { useAgentStore } from '@/store/agent';
-import { agentChatConfigSelectors } from '@/store/agent/slices/chat';
+import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+import { useAgentId } from '../../hooks/useAgentId';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
import FunctionCallingModelSelect from './FunctionCallingModelSelect';
const useStyles = createStyles(({ css, token }) => ({
@@ -34,10 +36,11 @@ const useStyles = createStyles(({ css, token }) => ({
const FCSearchModel = memo(() => {
const { t } = useTranslation('chat');
const { styles } = useStyles();
- const [searchFCModel, updateAgentChatConfig] = useAgentStore((s) => [
- agentChatConfigSelectors.searchFCModel(s),
- s.updateAgentChatConfig,
- ]);
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const searchFCModel = useAgentStore((s) =>
+ chatConfigByIdSelectors.getSearchFCModelById(agentId)(s),
+ );
return (
<Flexbox distribution={'space-between'} gap={16} horizontal padding={8}>
<Flexbox align={'center'} gap={4} horizontal>
diff --git a/src/features/ChatInput/ActionBar/Search/ModelBuiltinSearch.tsx b/src/features/ChatInput/ActionBar/Search/ModelBuiltinSearch.tsx
index e4bd28a33de..f077a7624e6 100644
--- a/src/features/ChatInput/ActionBar/Search/ModelBuiltinSearch.tsx
+++ b/src/features/ChatInput/ActionBar/Search/ModelBuiltinSearch.tsx
@@ -7,9 +7,12 @@ import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
import { useAgentStore } from '@/store/agent';
-import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';
+import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
+import { useAgentId } from '../../hooks/useAgentId';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
+
interface SearchEngineIconProps {
icon?: string;
}
@@ -32,11 +35,12 @@ const SearchEngineIcon = ({ icon }: SearchEngineIconProps) => {
const ModelBuiltinSearch = memo(() => {
const { t } = useTranslation('chat');
- const [model, provider, checked, updateAgentChatConfig] = useAgentStore((s) => [
- agentSelectors.currentAgentModel(s),
- agentSelectors.currentAgentModelProvider(s),
- agentChatConfigSelectors.useModelBuiltinSearch(s),
- s.updateAgentChatConfig,
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const [model, provider, checked] = useAgentStore((s) => [
+ agentByIdSelectors.getAgentModelById(agentId)(s),
+ agentByIdSelectors.getAgentModelProviderById(agentId)(s),
+ chatConfigByIdSelectors.getUseModelBuiltinSearchById(agentId)(s),
]);
const [isLoading, setLoading] = useState(false);
diff --git a/src/features/ChatInput/ActionBar/Search/index.tsx b/src/features/ChatInput/ActionBar/Search/index.tsx
index 477c282dcd5..8fe0ff5b49e 100644
--- a/src/features/ChatInput/ActionBar/Search/index.tsx
+++ b/src/features/ChatInput/ActionBar/Search/index.tsx
@@ -4,21 +4,23 @@ import { Globe } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useAgentEnableSearch } from '@/hooks/useAgentEnableSearch';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
-import { agentChatConfigSelectors } from '@/store/agent/slices/chat';
+import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
+import { useAgentEnableSearch } from '../../hooks/useAgentEnableSearch';
+import { useAgentId } from '../../hooks/useAgentId';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
import Action from '../components/Action';
import Controls from './Controls';
const Search = memo(() => {
const { t } = useTranslation('chat');
- const [isLoading, mode, updateAgentChatConfig] = useAgentStore((s) => [
- agentSelectors.isAgentConfigLoading(s),
- agentChatConfigSelectors.agentSearchMode(s),
- s.updateAgentChatConfig,
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const [isLoading, mode] = useAgentStore((s) => [
+ agentByIdSelectors.isAgentConfigLoadingById(agentId)(s),
+ chatConfigByIdSelectors.getSearchModeById(agentId)(s),
]);
const isAgentEnableSearch = useAgentEnableSearch();
const theme = useTheme();
diff --git a/src/features/ChatInput/ActionBar/Token/TokenTag.tsx b/src/features/ChatInput/ActionBar/Token/TokenTag.tsx
index 66ce4f612ca..08227555e67 100644
--- a/src/features/ChatInput/ActionBar/Token/TokenTag.tsx
+++ b/src/features/ChatInput/ActionBar/Token/TokenTag.tsx
@@ -11,12 +11,13 @@ import { useModelContextWindowTokens } from '@/hooks/useModelContextWindowTokens
import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';
import { useTokenCount } from '@/hooks/useTokenCount';
import { useAgentStore } from '@/store/agent';
-import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';
+import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { dbMessageSelectors, topicSelectors } from '@/store/chat/selectors';
import { useToolStore } from '@/store/tool';
import { toolSelectors } from '@/store/tool/selectors';
+import { useAgentId } from '../../hooks/useAgentId';
import ActionPopover from '../components/ActionPopover';
import TokenProgress from './TokenProgress';
@@ -32,29 +33,30 @@ const Token = memo<TokenTagProps>(({ total: messageString }) => {
topicSelectors.currentActiveTopicSummary(s)?.content || '',
]);
+ const agentId = useAgentId();
const [systemRole, model, provider] = useAgentStore((s) => {
return [
- agentSelectors.currentAgentSystemRole(s),
- agentSelectors.currentAgentModel(s) as string,
- agentSelectors.currentAgentModelProvider(s) as string,
+ agentByIdSelectors.getAgentSystemRoleById(agentId)(s),
+ agentByIdSelectors.getAgentModelById(agentId)(s),
+ agentByIdSelectors.getAgentModelProviderById(agentId)(s),
// add these two params to enable the component to re-render
- agentChatConfigSelectors.historyCount(s),
- agentChatConfigSelectors.enableHistoryCount(s),
+ chatConfigByIdSelectors.getHistoryCountById(agentId)(s),
+ chatConfigByIdSelectors.getEnableHistoryCountById(agentId)(s),
];
});
const [historyCount, enableHistoryCount] = useAgentStore((s) => [
- agentChatConfigSelectors.historyCount(s),
- agentChatConfigSelectors.enableHistoryCount(s),
+ chatConfigByIdSelectors.getHistoryCountById(agentId)(s),
+ chatConfigByIdSelectors.getEnableHistoryCountById(agentId)(s),
// need to re-render by search mode
- agentChatConfigSelectors.isAgentEnableSearch(s),
+ chatConfigByIdSelectors.isEnableSearchById(agentId)(s),
]);
const maxTokens = useModelContextWindowTokens(model, provider);
// Tool usage token
const canUseTool = useModelSupportToolUse(model, provider);
- const pluginIds = useAgentStore(agentSelectors.currentAgentPlugins);
+ const pluginIds = useAgentStore((s) => agentByIdSelectors.getAgentPluginsById(agentId)(s));
const toolsString = useToolStore((s) => {
const toolsEngine = createAgentToolsEngine({ model, provider });
diff --git a/src/features/ChatInput/ActionBar/Token/TokenTagForGroupChat.tsx b/src/features/ChatInput/ActionBar/Token/TokenTagForGroupChat.tsx
index 317cd3d39cf..ca69a8bb580 100644
--- a/src/features/ChatInput/ActionBar/Token/TokenTagForGroupChat.tsx
+++ b/src/features/ChatInput/ActionBar/Token/TokenTagForGroupChat.tsx
@@ -12,12 +12,12 @@ import { useModelContextWindowTokens } from '@/hooks/useModelContextWindowTokens
import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';
import { useTokenCount } from '@/hooks/useTokenCount';
import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+import { useAgentGroupStore } from '@/store/agentGroup/store';
import { useChatStore } from '@/store/chat';
import { chatSelectors } from '@/store/chat/selectors';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-import { chatGroupSelectors } from '@/store/chatGroup/selectors';
-import { useChatGroupStore } from '@/store/chatGroup/store';
import { useSessionStore } from '@/store/session';
import { sessionSelectors } from '@/store/session/selectors';
import { useToolStore } from '@/store/tool';
@@ -25,6 +25,7 @@ import { toolSelectors } from '@/store/tool/selectors';
import { userProfileSelectors } from '@/store/user/selectors';
import { getUserStoreState } from '@/store/user/store';
+import { useAgentId } from '../../hooks/useAgentId';
import ActionPopover from '../components/ActionPopover';
import TokenProgress from './TokenProgress';
@@ -39,19 +40,22 @@ const TokenTagForGroupChat = memo<TokenTagForGroupChatProps>(({ total: messageSt
const input = useChatStore((s) => s.inputMessage);
const activeTopicId = useChatStore((s) => s.activeTopicId);
+ const agentId = useAgentId();
const [model, provider] = useAgentStore((s) => {
return [
- agentSelectors.currentAgentModel(s) as string,
- agentSelectors.currentAgentModelProvider(s) as string,
+ agentByIdSelectors.getAgentModelById(agentId)(s),
+ agentByIdSelectors.getAgentModelProviderById(agentId)(s),
];
});
// Group chat specific data
const groupAgents = useSessionStore(sessionSelectors.currentGroupAgents);
const activeSessionId = useSessionStore((s) => s.activeId);
- const groupConfig = useChatGroupStore(chatGroupSelectors.currentGroupConfig);
+ const groupConfig = useAgentGroupStore(agentGroupSelectors.currentGroupConfig);
const supervisorTodos = useChatStore((s) =>
- activeSessionId ? s.supervisorTodos[messageMapKey(activeSessionId, activeTopicId)] || [] : [],
+ activeSessionId
+ ? s.supervisorTodos[messageMapKey({ agentId: activeSessionId, topicId: activeTopicId })] || []
+ : [],
);
const maxTokens = useModelContextWindowTokens(model, provider);
diff --git a/src/features/ChatInput/ActionBar/Tools/KlavisServerItem.tsx b/src/features/ChatInput/ActionBar/Tools/KlavisServerItem.tsx
index d8076a7bbf6..a3c072aae25 100644
--- a/src/features/ChatInput/ActionBar/Tools/KlavisServerItem.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/KlavisServerItem.tsx
@@ -327,6 +327,7 @@ const KlavisServerItem = memo<KlavisServerItemProps>(
return (
<Flexbox
+ align={'center'}
gap={24}
horizontal
justify={'space-between'}
diff --git a/src/features/ChatInput/ActionBar/Tools/index.tsx b/src/features/ChatInput/ActionBar/Tools/index.tsx
index abafc6dab63..5542ab9f83c 100644
--- a/src/features/ChatInput/ActionBar/Tools/index.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/index.tsx
@@ -1,4 +1,5 @@
import { Segmented } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
import { Blocks } from 'lucide-react';
import { Suspense, memo, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -6,20 +7,45 @@ import { useTranslation } from 'react-i18next';
import PluginStore from '@/features/PluginStore';
import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';
import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
-import {
- featureFlagsSelectors,
- serverConfigSelectors,
- useServerConfigStore,
-} from '@/store/serverConfig';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
+import { useAgentId } from '../../hooks/useAgentId';
import Action from '../components/Action';
import { useControls } from './useControls';
type TabType = 'all' | 'installed';
+const useStyles = createStyles(({ css, prefixCls, token }) => ({
+ dropdown: css`
+ overflow: hidden;
+
+ width: 100%;
+ border: 1px solid ${token.colorBorderSecondary};
+ border-radius: ${token.borderRadiusLG}px;
+
+ background: ${token.colorBgElevated};
+ box-shadow: ${token.boxShadowSecondary};
+
+ .${prefixCls}-dropdown-menu {
+ border-radius: 0 !important;
+ background: transparent !important;
+ box-shadow: none !important;
+ }
+ `,
+ header: css`
+ padding: ${token.paddingXS}px;
+ border-block-end: 1px solid ${token.colorBorderSecondary};
+ background: transparent;
+ `,
+ scroller: css`
+ overflow: hidden auto;
+ `,
+}));
+
const Tools = memo(() => {
const { t } = useTranslation('setting');
+ const { styles } = useStyles();
const [modalOpen, setModalOpen] = useState(false);
const [updating, setUpdating] = useState(false);
const [activeTab, setActiveTab] = useState<TabType | null>(null);
@@ -27,7 +53,7 @@ const Tools = memo(() => {
setModalOpen,
setUpdating,
});
- const { enablePlugins } = useServerConfigStore(featureFlagsSelectors);
+
const enableKlavis = useServerConfigStore(serverConfigSelectors.enableKlavis);
const isInitializedRef = useRef(false);
@@ -39,12 +65,12 @@ const Tools = memo(() => {
}
}, [installedPluginItems.length]);
- const model = useAgentStore(agentSelectors.currentAgentModel);
- const provider = useAgentStore(agentSelectors.currentAgentModelProvider);
+ const agentId = useAgentId();
+ const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));
+ const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));
const enableFC = useModelSupportToolUse(model, provider);
- if (!enablePlugins) return null;
if (!enableFC)
return <Action disabled icon={Blocks} showTooltip={true} title={t('tools.disabled')} />;
@@ -56,37 +82,48 @@ const Tools = memo(() => {
<Suspense fallback={<Action disabled icon={Blocks} title={t('tools.title')} />}>
<Action
dropdown={{
- maxHeight: 500,
- maxWidth: 480,
+ maxWidth: 320,
menu: {
- items: [
- {
- key: 'tabs',
- label: (
- <Segmented
- block
- onChange={(v) => setActiveTab(v as TabType)}
- options={[
- {
- label: t('tools.tabs.all', { defaultValue: 'all' }),
- value: 'all',
- },
- {
- label: t('tools.tabs.installed', { defaultValue: 'Installed' }),
- value: 'installed',
- },
- ]}
- size="small"
- value={effectiveTab}
- />
- ),
- type: 'group',
- },
- ...currentItems,
- ],
+ items: [...currentItems],
+ style: {
+ // let only the custom scroller scroll
+ maxHeight: 'unset',
+ overflowY: 'visible',
+ },
},
minHeight: enableKlavis ? 500 : undefined,
minWidth: 320,
+ popupRender: (menu) => (
+ <div className={styles.dropdown}>
+ <div className={styles.header}>
+ <Segmented
+ block
+ onChange={(v) => setActiveTab(v as TabType)}
+ options={[
+ {
+ label: t('tools.tabs.all', { defaultValue: 'all' }),
+ value: 'all',
+ },
+ {
+ label: t('tools.tabs.installed', { defaultValue: 'Installed' }),
+ value: 'installed',
+ },
+ ]}
+ size="small"
+ value={effectiveTab}
+ />
+ </div>
+ <div
+ className={styles.scroller}
+ style={{
+ maxHeight: 500,
+ minHeight: enableKlavis ? 500 : undefined,
+ }}
+ >
+ {menu}
+ </div>
+ </div>
+ ),
}}
icon={Blocks}
loading={updating}
diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.tsx b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
index 7da6cc101d3..77e239ee963 100644
--- a/src/features/ChatInput/ActionBar/Tools/useControls.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
@@ -1,9 +1,8 @@
import { KLAVIS_SERVER_TYPES, KlavisServerType } from '@lobechat/const';
-import { Avatar, Icon, ItemType } from '@lobehub/ui';
+import { Avatar, Icon, Image, ItemType } from '@lobehub/ui';
import { useTheme } from 'antd-style';
import isEqual from 'fast-deep-equal';
import { ArrowRight, Store, ToyBrick } from 'lucide-react';
-import Image from 'next/image';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
@@ -12,7 +11,7 @@ import PluginAvatar from '@/components/Plugins/PluginAvatar';
import { useCheckPluginsIsInstalled } from '@/hooks/useCheckPluginsIsInstalled';
import { useFetchInstalledPlugins } from '@/hooks/useFetchInstalledPlugins';
import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
+import { agentByIdSelectors } from '@/store/agent/selectors';
import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useToolStore } from '@/store/tool';
import {
@@ -21,6 +20,7 @@ import {
pluginSelectors,
} from '@/store/tool/selectors';
+import { useAgentId } from '../../hooks/useAgentId';
import KlavisServerItem from './KlavisServerItem';
import ToolItem from './ToolItem';
@@ -33,9 +33,7 @@ const KlavisIcon = memo<Pick<KlavisServerType, 'icon' | 'label'>>(({ icon, label
const theme = useTheme();
if (typeof icon === 'string') {
- return (
- <Image alt={label} height={18} src={icon} style={{ flex: 'none' }} unoptimized width={18} />
- );
+ return <Image alt={label} height={18} src={icon} style={{ flex: 'none' }} width={18} />;
}
// 使用主题色填充,在深色模式下自动适应
@@ -52,19 +50,20 @@ export const useControls = ({
setUpdating: (updating: boolean) => void;
}) => {
const { t } = useTranslation('setting');
+ const agentId = useAgentId();
const list = useToolStore(pluginSelectors.installedPluginMetaList, isEqual);
const [checked, togglePlugin] = useAgentStore((s) => [
- agentSelectors.currentAgentPlugins(s),
+ agentByIdSelectors.getAgentPluginsById(agentId)(s),
s.togglePlugin,
]);
const builtinList = useToolStore(builtinToolSelectors.metaList, isEqual);
const enablePluginCount = useAgentStore(
(s) =>
- agentSelectors
- .currentAgentPlugins(s)
+ agentByIdSelectors
+ .getAgentPluginsById(agentId)(s)
.filter((i) => !builtinList.some((b) => b.identifier === i)).length,
);
- const plugins = useAgentStore((s) => agentSelectors.currentAgentPlugins(s));
+ const plugins = useAgentStore((s) => agentByIdSelectors.getAgentPluginsById(agentId)(s));
// Klavis 相关状态
const allKlavisServers = useToolStore(klavisStoreSelectors.getServers, isEqual);
@@ -127,7 +126,9 @@ export const useControls = ({
() => [
// 原有的 builtin 工具
...filteredBuiltinList.map((item) => ({
- icon: <Avatar avatar={item.meta.avatar} size={20} style={{ flex: 'none' }} />,
+ icon: (
+ <Avatar avatar={item.meta.avatar} shape={'square'} size={20} style={{ flex: 'none' }} />
+ ),
key: item.identifier,
label: (
<ToolItem
@@ -212,7 +213,9 @@ export const useControls = ({
const enabledBuiltinItems = filteredBuiltinList
.filter((item) => checked.includes(item.identifier))
.map((item) => ({
- icon: <Avatar avatar={item.meta.avatar} size={20} style={{ flex: 'none' }} />,
+ icon: (
+ <Avatar avatar={item.meta.avatar} shape={'square'} size={20} style={{ flex: 'none' }} />
+ ),
key: item.identifier,
label: (
<ToolItem
diff --git a/src/features/ChatInput/ActionBar/Upload/ServerMode.tsx b/src/features/ChatInput/ActionBar/Upload/ServerMode.tsx
index 11fef3023a2..4eaca9760cd 100644
--- a/src/features/ChatInput/ActionBar/Upload/ServerMode.tsx
+++ b/src/features/ChatInput/ActionBar/Upload/ServerMode.tsx
@@ -9,9 +9,10 @@ import { useTranslation } from 'react-i18next';
import { message } from '@/components/AntdStaticMethods';
import { useModelSupportVision } from '@/hooks/useModelSupportVision';
import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
+import { agentByIdSelectors } from '@/store/agent/selectors';
import { useFileStore } from '@/store/file';
+import { useAgentId } from '../../hooks/useAgentId';
import Action from '../components/Action';
const hotArea = css`
@@ -28,8 +29,9 @@ const FileUpload = memo(() => {
const upload = useFileStore((s) => s.uploadChatFiles);
- const model = useAgentStore(agentSelectors.currentAgentModel);
- const provider = useAgentStore(agentSelectors.currentAgentModelProvider);
+ const agentId = useAgentId();
+ const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));
+ const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));
const canUploadImage = useModelSupportVision(model, provider);
diff --git a/src/features/ChatInput/ActionBar/components/Action.tsx b/src/features/ChatInput/ActionBar/components/Action.tsx
index 029b2a1d7f1..05d02f4cd25 100644
--- a/src/features/ChatInput/ActionBar/components/Action.tsx
+++ b/src/features/ChatInput/ActionBar/components/Action.tsx
@@ -1,12 +1,13 @@
'use client';
import { ActionIcon, type ActionIconProps } from '@lobehub/ui';
-import { isUndefined } from 'lodash-es';
+import { isUndefined } from 'es-toolkit/compat';
import { memo } from 'react';
import useMergeState from 'use-merge-value';
import { useServerConfigStore } from '@/store/serverConfig';
+import { useActionBarContext } from '../context';
import ActionDropdown, { ActionDropdownProps } from './ActionDropdown';
import ActionPopover, { ActionPopoverProps } from './ActionPopover';
@@ -39,6 +40,7 @@ const Action = memo<ActionProps>(
value: open,
});
const mobile = useServerConfigStore((s) => s.isMobile);
+ const { dropdownPlacement } = useActionBarContext();
const iconNode = (
<ActionIcon
disabled={disabled}
@@ -72,7 +74,7 @@ const Action = memo<ActionProps>(
trigger={trigger}
{...dropdown}
minWidth={mobile ? '100%' : dropdown.minWidth}
- placement={mobile ? 'top' : dropdown.placement}
+ placement={mobile ? 'top' : (dropdownPlacement ?? dropdown.placement)}
>
{iconNode}
</ActionDropdown>
@@ -85,7 +87,7 @@ const Action = memo<ActionProps>(
trigger={trigger}
{...popover}
minWidth={mobile ? '100%' : popover.minWidth}
- placement={mobile ? 'top' : popover.placement}
+ placement={mobile ? 'top' : (dropdownPlacement ?? popover.placement)}
>
{iconNode}
</ActionPopover>
diff --git a/src/features/ChatInput/ActionBar/components/CheckbokWithLoading.tsx b/src/features/ChatInput/ActionBar/components/CheckbokWithLoading.tsx
index 9283a088ee7..ace19e98f23 100644
--- a/src/features/ChatInput/ActionBar/components/CheckbokWithLoading.tsx
+++ b/src/features/ChatInput/ActionBar/components/CheckbokWithLoading.tsx
@@ -22,6 +22,7 @@ const CheckboxItem = memo<CheckboxItemProps>(({ id, onUpdate, label, checked })
return (
<Flexbox
+ align={'center'}
gap={24}
horizontal
justify={'space-between'}
diff --git a/src/features/ChatInput/ActionBar/config.ts b/src/features/ChatInput/ActionBar/config.ts
index 208fa78d057..137dbfdd7e4 100644
--- a/src/features/ChatInput/ActionBar/config.ts
+++ b/src/features/ChatInput/ActionBar/config.ts
@@ -1,3 +1,4 @@
+import AgentMode from './AgentMode';
import Clear from './Clear';
import History from './History';
import Knowledge from './Knowledge';
@@ -13,6 +14,7 @@ import Typo from './Typo';
import Upload from './Upload';
export const actionMap = {
+ agentMode: AgentMode,
clear: Clear,
fileUpload: Upload,
groupChatToken: GroupChatToken,
diff --git a/src/features/ChatInput/ActionBar/context.ts b/src/features/ChatInput/ActionBar/context.ts
new file mode 100644
index 00000000000..c960b07f674
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/context.ts
@@ -0,0 +1,18 @@
+'use client';
+
+import { createContext, useContext } from 'react';
+
+/**
+ * Common placement values supported by both Dropdown and Popover
+ */
+type DropdownPlacement = 'bottom' | 'bottomLeft' | 'bottomRight' | 'top' | 'topLeft' | 'topRight';
+
+export interface ActionBarContextValue {
+ dropdownPlacement?: DropdownPlacement;
+}
+
+export const ActionBarContext = createContext<ActionBarContextValue>({});
+
+export const useActionBarContext = () => useContext(ActionBarContext);
+
+export type { DropdownPlacement };
diff --git a/src/features/ChatInput/ActionBar/index.tsx b/src/features/ChatInput/ActionBar/index.tsx
index d344f000ef2..e967460cb62 100644
--- a/src/features/ChatInput/ActionBar/index.tsx
+++ b/src/features/ChatInput/ActionBar/index.tsx
@@ -8,6 +8,7 @@ import { labPreferSelectors } from '@/store/user/slices/preference/selectors';
import { ActionKeys, actionMap } from '../ActionBar/config';
import { useChatInputStore } from '../store';
+import { ActionBarContext, type DropdownPlacement } from './context';
const mapActionsToItems = (keys: ActionKeys[]): ChatInputActionsProps['items'] =>
keys.map((actionKey, index) => {
@@ -39,7 +40,11 @@ const mapActionsToItems = (keys: ActionKeys[]): ChatInputActionsProps['items'] =
}
});
-const ActionToolbar = memo(() => {
+export interface ActionToolbarProps {
+ dropdownPlacement?: DropdownPlacement;
+}
+
+const ActionToolbar = memo<ActionToolbarProps>(({ dropdownPlacement }) => {
const [expandInputActionbar, toggleExpandInputActionbar] = useGlobalStore((s) => [
systemStatusSelectors.expandInputActionbar(s),
s.toggleExpandInputActionbar,
@@ -54,16 +59,20 @@ const ActionToolbar = memo(() => {
const items = useMemo(() => mapActionsToItems(leftActions), [leftActions]);
+ const contextValue = useMemo(() => ({ dropdownPlacement }), [dropdownPlacement]);
+
return (
- <ChatInputActions
- collapseOffset={mobile ? 48 : 80}
- defaultGroupCollapse={true}
- groupCollapse={!expandInputActionbar}
- items={items}
- onGroupCollapseChange={(v) => {
- toggleExpandInputActionbar(!v);
- }}
- />
+ <ActionBarContext.Provider value={contextValue}>
+ <ChatInputActions
+ collapseOffset={mobile ? 48 : 80}
+ defaultGroupCollapse={true}
+ groupCollapse={!expandInputActionbar}
+ items={items}
+ onGroupCollapseChange={(v) => {
+ toggleExpandInputActionbar(!v);
+ }}
+ />
+ </ActionBarContext.Provider>
);
});
diff --git a/src/features/ChatInput/ChatInputProvider.tsx b/src/features/ChatInput/ChatInputProvider.tsx
index 90cc392fe2d..a0eee10524a 100644
--- a/src/features/ChatInput/ChatInputProvider.tsx
+++ b/src/features/ChatInput/ChatInputProvider.tsx
@@ -10,6 +10,7 @@ interface ChatInputProviderProps extends StoreUpdaterProps {
export const ChatInputProvider = memo<ChatInputProviderProps>(
({
+ agentId,
children,
leftActions,
rightActions,
@@ -40,6 +41,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(
}
>
<StoreUpdater
+ agentId={agentId}
chatInputEditorRef={chatInputEditorRef}
leftActions={leftActions}
mentionItems={mentionItems}
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/Content.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/Content.tsx
new file mode 100644
index 00000000000..c6558d3b9d8
--- /dev/null
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/Content.tsx
@@ -0,0 +1,44 @@
+import { Image } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { memo } from 'react';
+
+import FileIcon from '@/components/FileIcon';
+import { UploadFileItem } from '@/types/files/upload';
+
+const useStyles = createStyles(({ css }) => ({
+ image: css`
+ width: 100%;
+ height: 100%;
+ margin-block: 0 !important;
+ box-shadow: none;
+
+ img {
+ width: 100%;
+ height: 100%;
+ border-radius: 4px;
+ object-fit: cover;
+ }
+ `,
+ video: css`
+ overflow: hidden;
+ width: 100%;
+ height: 100%;
+ border-radius: 4px;
+ `,
+}));
+
+const Content = memo<UploadFileItem>(({ file, previewUrl }) => {
+ const { styles } = useStyles();
+
+ if (file.type.startsWith('image')) {
+ return <Image alt={file.name} src={previewUrl} wrapperClassName={styles.image} />;
+ }
+
+ if (file.type.startsWith('video')) {
+ return <video className={styles.video} src={previewUrl} />;
+ }
+
+ return <FileIcon fileName={file.name} fileType={file.type} size={16} />;
+});
+
+export default Content;
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx
new file mode 100644
index 00000000000..f4f6e60d0ba
--- /dev/null
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx
@@ -0,0 +1,68 @@
+import { Tag, Tooltip } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { useFileStore } from '@/store/file';
+import { UploadFileItem } from '@/types/files/upload';
+
+import Content from './Content';
+import { getFileBasename } from './utils';
+
+const useStyles = createStyles(({ css, token }) => ({
+ closeBtn: css`
+ flex-shrink: 0;
+ color: ${token.colorTextTertiary};
+
+ &:hover {
+ color: ${token.colorError};
+ background: ${token.colorErrorBg};
+ }
+ `,
+ icon: css`
+ flex-shrink: 0;
+ width: 18px;
+ height: 18px;
+ border-radius: 4px;
+
+ img,
+ video {
+ width: 100%;
+ height: 100%;
+ border-radius: 4px;
+ object-fit: cover;
+ }
+ `,
+ name: css`
+ overflow: hidden;
+ flex: 1;
+
+ min-width: 0;
+
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+}));
+
+type FileItemProps = UploadFileItem;
+
+const ContextItem = memo<FileItemProps>((props) => {
+ const { file, id } = props;
+ const { styles } = useStyles();
+ const [removeChatUploadFile] = useFileStore((s) => [s.removeChatUploadFile]);
+
+ const basename = getFileBasename(file.name);
+
+ return (
+ <Tag closable onClose={() => removeChatUploadFile(id)} size={'large'}>
+ <Flexbox className={styles.icon}>
+ <Content {...props} />
+ </Flexbox>
+ <Tooltip title={file.name}>
+ <span className={styles.name}>{basename}</span>
+ </Tooltip>
+ </Tag>
+ );
+});
+
+export default ContextItem;
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/utils.ts b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/utils.ts
new file mode 100644
index 00000000000..cb8504edc9d
--- /dev/null
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/utils.ts
@@ -0,0 +1,34 @@
+export const getFileBasename = (filename: string): string => {
+ const lastDotIndex = filename.lastIndexOf('.');
+ if (lastDotIndex <= 0) return filename;
+ return filename.slice(0, lastDotIndex);
+};
+
+export const getHarmoniousSize = (
+ inputWidth: number,
+ inputHeight: number,
+ {
+ spacing = 24,
+ containerWidth,
+ containerHeight,
+ }: { containerHeight: number; containerWidth: number; spacing: number },
+) => {
+ let width = String(inputWidth);
+ let height = String(inputHeight);
+
+ const maxWidth = containerWidth - spacing;
+ const maxHeight = containerHeight - spacing;
+
+ if (inputHeight >= inputWidth && inputHeight >= maxHeight) {
+ height = maxHeight + 'px';
+ width = 'auto';
+ } else if (inputWidth >= inputHeight && inputWidth >= maxWidth) {
+ height = 'auto';
+ width = maxWidth + 'px';
+ } else {
+ width = width + 'px';
+ height = height + 'px';
+ }
+
+ return { height, width };
+};
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx
new file mode 100644
index 00000000000..a51da455056
--- /dev/null
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx
@@ -0,0 +1,64 @@
+import { ScrollShadow } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { memo, useEffect, useRef } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { fileChatSelectors, useFileStore } from '@/store/file';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import ContextItem from './ContextItem';
+import SelectionItem from './SelectionItem';
+
+const useStyles = createStyles(({ css }) => ({
+ container: css`
+ overflow-x: scroll;
+ width: 100%;
+ `,
+}));
+
+const ContextList = memo(() => {
+ const agentId = useAgentId();
+ const prevAgentIdRef = useRef<string | undefined>(undefined);
+ const inputFilesList = useFileStore(fileChatSelectors.chatUploadFileList);
+ const showFileList = useFileStore(fileChatSelectors.chatUploadFileListHasItem);
+ const rawSelectionList = useFileStore(fileChatSelectors.chatContextSelections);
+ const showSelectionList = useFileStore(fileChatSelectors.chatContextSelectionHasItem);
+ const clearChatContextSelections = useFileStore((s) => s.clearChatContextSelections);
+ const { styles } = useStyles();
+
+ // Clear selections only when agentId changes (not on initial mount)
+ useEffect(() => {
+ if (prevAgentIdRef.current !== undefined && prevAgentIdRef.current !== agentId) {
+ clearChatContextSelections();
+ }
+ prevAgentIdRef.current = agentId;
+ }, [agentId, clearChatContextSelections]);
+
+ // Filter duplicates based on preview content
+ const selectionList = rawSelectionList.filter(
+ (item, index, self) => index === self.findIndex((t) => t.preview === item.preview),
+ );
+
+ if ((!inputFilesList.length || !showFileList) && !showSelectionList) return null;
+
+ return (
+ <ScrollShadow
+ className={styles.container}
+ hideScrollBar
+ horizontal
+ orientation={'horizontal'}
+ size={8}
+ >
+ <Flexbox gap={4} horizontal paddingInline={0} style={{ paddingBlockStart: 8 }} wrap={'wrap'}>
+ {selectionList.map((item) => (
+ <SelectionItem key={item.id} {...item} />
+ ))}
+ {inputFilesList.map((item) => (
+ <ContextItem key={item.id} {...item} />
+ ))}
+ </Flexbox>
+ </ScrollShadow>
+ );
+});
+
+export default ContextList;
diff --git a/src/features/ChatInput/Desktop/ContextContainer/SelectionItem.tsx b/src/features/ChatInput/Desktop/ContextContainer/SelectionItem.tsx
new file mode 100644
index 00000000000..f710d91f979
--- /dev/null
+++ b/src/features/ChatInput/Desktop/ContextContainer/SelectionItem.tsx
@@ -0,0 +1,53 @@
+import { ChatContextContent } from '@lobechat/types';
+import { Tag, Tooltip } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { TextIcon } from 'lucide-react';
+import { memo, useMemo } from 'react';
+
+import { useFileStore } from '@/store/file';
+
+const useStyles = createStyles(({ css }) => ({
+ name: css`
+ overflow: hidden;
+ flex: 1;
+
+ min-width: 0;
+
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+}));
+
+const MAX_PREVIEW_LENGTH = 8;
+
+const getPreviewText = (content?: string, fallback?: string) => {
+ const source = content || fallback || '';
+ if (!source) return 'Text selection';
+
+ const plain = source
+ .replaceAll(/<[^>]*>/g, ' ')
+ .replaceAll(/\s+/g, ' ')
+ .trim();
+ if (!plain) return 'Text selection';
+
+ return plain.length > MAX_PREVIEW_LENGTH ? `${plain.slice(0, MAX_PREVIEW_LENGTH)}...` : plain;
+};
+
+const SelectionItem = memo<ChatContextContent>(({ preview, id }) => {
+ const { styles } = useStyles();
+ const [removeSelection] = useFileStore((s) => [s.removeChatContextSelection]);
+
+ const displayText = useMemo(() => getPreviewText(preview), [preview]);
+
+ return (
+ <Tag closable icon={<TextIcon size={16} />} onClose={() => removeSelection(id)} size={'large'}>
+ <Tooltip title={preview}>
+ <span className={styles.name}>{displayText}</span>
+ </Tooltip>
+ </Tag>
+ );
+});
+
+SelectionItem.displayName = 'SelectionItem';
+
+export default SelectionItem;
diff --git a/src/features/ChatInput/Desktop/ContextContainer/index.tsx b/src/features/ChatInput/Desktop/ContextContainer/index.tsx
new file mode 100644
index 00000000000..0c4ba40eee1
--- /dev/null
+++ b/src/features/ChatInput/Desktop/ContextContainer/index.tsx
@@ -0,0 +1,46 @@
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import DragUpload from '@/components/DragUpload';
+import { useModelSupportVision } from '@/hooks/useModelSupportVision';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+import { useFileStore } from '@/store/file';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import ContextList from './ContextList';
+
+/**
+ * Contains the context item to be attached, such as file, image, text, etc.
+ */
+const ContextContainer = memo(() => {
+ const agentId = useAgentId();
+ const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));
+ const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));
+
+ const canUploadImage = useModelSupportVision(model, provider);
+
+ const [uploadFiles] = useFileStore((s) => [s.uploadChatFiles]);
+
+ const upload = async (fileList: FileList | File[] | undefined) => {
+ if (!fileList || fileList.length === 0) return;
+
+ // Filter out files that are not images if the model does not support image uploads
+ const files = Array.from(fileList).filter((file) => {
+ if (canUploadImage) return true;
+
+ return !file.type.startsWith('image');
+ });
+
+ uploadFiles(files);
+ };
+
+ return (
+ <Flexbox paddingInline={8}>
+ <DragUpload onUploadFiles={upload} />
+ <ContextList />
+ </Flexbox>
+ );
+});
+
+export default ContextContainer;
diff --git a/src/features/ChatInput/Desktop/ContextItem/FileItem/utils.ts b/src/features/ChatInput/Desktop/ContextItem/FileItem/utils.ts
new file mode 100644
index 00000000000..cb8504edc9d
--- /dev/null
+++ b/src/features/ChatInput/Desktop/ContextItem/FileItem/utils.ts
@@ -0,0 +1,34 @@
+export const getFileBasename = (filename: string): string => {
+ const lastDotIndex = filename.lastIndexOf('.');
+ if (lastDotIndex <= 0) return filename;
+ return filename.slice(0, lastDotIndex);
+};
+
+export const getHarmoniousSize = (
+ inputWidth: number,
+ inputHeight: number,
+ {
+ spacing = 24,
+ containerWidth,
+ containerHeight,
+ }: { containerHeight: number; containerWidth: number; spacing: number },
+) => {
+ let width = String(inputWidth);
+ let height = String(inputHeight);
+
+ const maxWidth = containerWidth - spacing;
+ const maxHeight = containerHeight - spacing;
+
+ if (inputHeight >= inputWidth && inputHeight >= maxHeight) {
+ height = maxHeight + 'px';
+ width = 'auto';
+ } else if (inputWidth >= inputHeight && inputWidth >= maxWidth) {
+ height = 'auto';
+ width = maxWidth + 'px';
+ } else {
+ width = width + 'px';
+ height = height + 'px';
+ }
+
+ return { height, width };
+};
diff --git a/src/features/ChatInput/Desktop/FilePreview/index.tsx b/src/features/ChatInput/Desktop/FilePreview/index.tsx
index 13f54bb0774..9ec4a2d6126 100644
--- a/src/features/ChatInput/Desktop/FilePreview/index.tsx
+++ b/src/features/ChatInput/Desktop/FilePreview/index.tsx
@@ -3,14 +3,16 @@ import { memo } from 'react';
import DragUpload from '@/components/DragUpload';
import { useModelSupportVision } from '@/hooks/useModelSupportVision';
import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/slices/chat';
+import { agentByIdSelectors } from '@/store/agent/selectors';
import { useFileStore } from '@/store/file';
+import { useAgentId } from '../../hooks/useAgentId';
import FileItemList from './FileList';
const FilePreview = memo(() => {
- const model = useAgentStore(agentSelectors.currentAgentModel);
- const provider = useAgentStore(agentSelectors.currentAgentModelProvider);
+ const agentId = useAgentId();
+ const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));
+ const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));
const canUploadImage = useModelSupportVision(model, provider);
diff --git a/src/features/ChatInput/Desktop/MentionedUsers/MentionedUserItem.tsx b/src/features/ChatInput/Desktop/MentionedUsers/MentionedUserItem.tsx
index 859c902c69c..8c1247afe2b 100644
--- a/src/features/ChatInput/Desktop/MentionedUsers/MentionedUserItem.tsx
+++ b/src/features/ChatInput/Desktop/MentionedUsers/MentionedUserItem.tsx
@@ -63,7 +63,12 @@ const MentionedUserItem = memo<MentionedUserItemProps>(({ agent }) => {
return (
<Flexbox align={'center'} className={styles.container} horizontal>
<Center flex={1} height={64} padding={4} style={{ maxWidth: 64 }}>
- <Avatar avatar={agent.avatar} background={agent.backgroundColor} shape="circle" size={48} />
+ <Avatar
+ avatar={agent.avatar}
+ background={agent.backgroundColor}
+ shape={'square'}
+ size={48}
+ />
</Center>
<Flexbox flex={1} gap={4} style={{ paddingBottom: 4, paddingInline: 4 }}>
<Text ellipsis={{ tooltip: true }} style={{ fontSize: 12, maxWidth: 100 }}>
diff --git a/src/features/ChatInput/Desktop/index.tsx b/src/features/ChatInput/Desktop/index.tsx
index 7a2da8ec0f0..ff8fe0b40a0 100644
--- a/src/features/ChatInput/Desktop/index.tsx
+++ b/src/features/ChatInput/Desktop/index.tsx
@@ -1,28 +1,27 @@
'use client';
-import { ChatInput, ChatInputActionBar } from '@lobehub/editor/react';
+import { ChatInput, ChatInputActionBar, ChatInputProps } from '@lobehub/editor/react';
import { Text } from '@lobehub/ui';
import { createStyles } from 'antd-style';
-import { memo, useEffect } from 'react';
+import { ReactNode, memo, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Center, Flexbox } from 'react-layout-kit';
import { useChatInputStore } from '@/features/ChatInput/store';
import { useChatStore } from '@/store/chat';
import { chatSelectors } from '@/store/chat/selectors';
+import { fileChatSelectors, useFileStore } from '@/store/file';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
-import ActionBar from '../ActionBar';
+import ActionBar, { type ActionToolbarProps } from '../ActionBar';
import InputEditor from '../InputEditor';
import SendArea from '../SendArea';
import TypoBar from '../TypoBar';
-import FilePreview from './FilePreview';
+import ContextContainer from './ContextContainer';
-const useStyles = createStyles(({ css, token }) => ({
+const useStyles = createStyles(({ css }) => ({
container: css`
- margin-block-start: -5px;
-
.show-on-hover {
opacity: 0;
}
@@ -43,50 +42,60 @@ const useStyles = createStyles(({ css, token }) => ({
width: 100%;
height: 100%;
- padding: 12px;
-
- background: ${token.colorBgContainerSecondary};
+ margin-block-start: 0;
+ `,
+ inputFullscreen: css`
+ border: none;
+ border-radius: 0 !important;
`,
}));
-const DesktopChatInput = memo<{ showFootnote?: boolean }>(({ showFootnote }) => {
- const { t } = useTranslation('chat');
- const [chatInputHeight, updateSystemStatus] = useGlobalStore((s) => [
- systemStatusSelectors.chatInputHeight(s),
- s.updateSystemStatus,
- ]);
- const [slashMenuRef, expand, showTypoBar, editor, leftActions] = useChatInputStore((s) => [
- s.slashMenuRef,
- s.expand,
- s.showTypoBar,
- s.editor,
- s.leftActions,
- ]);
-
- const { styles, cx } = useStyles();
-
- const chatKey = useChatStore(chatSelectors.currentChatKey);
-
- useEffect(() => {
- if (editor) editor.focus();
- }, [chatKey, editor]);
-
- const fileNode = leftActions.flat().includes('fileUpload') && <FilePreview />;
-
- return (
- <>
- {!expand && fileNode}
+interface DesktopChatInputProps extends ActionToolbarProps {
+ extenHeaderContent?: ReactNode;
+ inputContainerProps?: ChatInputProps;
+ showFootnote?: boolean;
+}
+
+const DesktopChatInput = memo<DesktopChatInputProps>(
+ ({ showFootnote, inputContainerProps, extenHeaderContent, dropdownPlacement }) => {
+ const { t } = useTranslation('chat');
+ const [chatInputHeight, updateSystemStatus] = useGlobalStore((s) => [
+ systemStatusSelectors.chatInputHeight(s),
+ s.updateSystemStatus,
+ ]);
+ const hasContextSelections = useFileStore(fileChatSelectors.chatContextSelectionHasItem);
+ const hasFiles = useFileStore(fileChatSelectors.chatUploadFileListHasItem);
+ const [slashMenuRef, expand, showTypoBar, editor, leftActions] = useChatInputStore((s) => [
+ s.slashMenuRef,
+ s.expand,
+ s.showTypoBar,
+ s.editor,
+ s.leftActions,
+ ]);
+
+ const { styles, cx } = useStyles();
+
+ const chatKey = useChatStore(chatSelectors.currentChatKey);
+
+ useEffect(() => {
+ if (editor) editor.focus();
+ }, [chatKey, editor]);
+
+ const shouldShowContextContainer =
+ leftActions.flat().includes('fileUpload') || hasContextSelections || hasFiles;
+ const contextContainerNode = shouldShowContextContainer && <ContextContainer />;
+
+ return (
<Flexbox
className={cx(styles.container, expand && styles.fullscreen)}
gap={8}
- paddingBlock={showFootnote ? '0 8px' : '0 12px'}
- paddingInline={12}
+ paddingBlock={expand ? 0 : showFootnote ? '0 12px' : '0 16px'}
>
<ChatInput
defaultHeight={chatInputHeight || 32}
footer={
<ChatInputActionBar
- left={<ActionBar />}
+ left={<ActionBar dropdownPlacement={dropdownPlacement} />}
right={<SendArea />}
style={{
paddingRight: 8,
@@ -94,7 +103,13 @@ const DesktopChatInput = memo<{ showFootnote?: boolean }>(({ showFootnote }) =>
/>
}
fullscreen={expand}
- header={showTypoBar && <TypoBar />}
+ header={
+ <Flexbox gap={0}>
+ {extenHeaderContent}
+ {showTypoBar && <TypoBar />}
+ {contextContainerNode}
+ </Flexbox>
+ }
maxHeight={320}
minHeight={36}
onSizeChange={(height) => {
@@ -102,8 +117,9 @@ const DesktopChatInput = memo<{ showFootnote?: boolean }>(({ showFootnote }) =>
}}
resize={true}
slashMenuRef={slashMenuRef}
+ {...inputContainerProps}
+ className={cx(expand && styles.inputFullscreen, inputContainerProps?.className)}
>
- {expand && fileNode}
<InputEditor />
</ChatInput>
{showFootnote && !expand && (
@@ -114,9 +130,9 @@ const DesktopChatInput = memo<{ showFootnote?: boolean }>(({ showFootnote }) =>
</Center>
)}
</Flexbox>
- </>
- );
-});
+ );
+ },
+);
DesktopChatInput.displayName = 'DesktopChatInput';
diff --git a/src/features/ChatInput/InputEditor/Placeholder.tsx b/src/features/ChatInput/InputEditor/Placeholder.tsx
index 1ec336c65ff..4025340f0aa 100644
--- a/src/features/ChatInput/InputEditor/Placeholder.tsx
+++ b/src/features/ChatInput/InputEditor/Placeholder.tsx
@@ -1,37 +1,41 @@
import { KeyEnum } from '@lobechat/types';
import { Hotkey, combineKeys } from '@lobehub/ui';
import { memo } from 'react';
-import { Trans, useTranslation } from 'react-i18next';
+import { Trans } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
import { useUserStore } from '@/store/user';
import { preferenceSelectors } from '@/store/user/selectors';
const Placeholder = memo(() => {
- const { t } = useTranslation(['editor', 'chat']);
-
const useCmdEnterToSend = useUserStore(preferenceSelectors.useCmdEnterToSend);
const wrapperShortcut = useCmdEnterToSend
? KeyEnum.Enter
: combineKeys([KeyEnum.Mod, KeyEnum.Enter]);
return (
- <Flexbox align={'center'} as={'span'} gap={4} horizontal>
- {t('sendPlaceholder', { ns: 'chat' }).replace('...', ', ')}
+ <Flexbox align={'center'} as={'span'} gap={4} horizontal wrap={'wrap'}>
<Trans
- as={'span'}
components={{
- key: (
- <Hotkey
- as={'span'}
- keys={wrapperShortcut}
- style={{ color: 'inherit' }}
- styles={{ kbdStyle: { color: 'inhert' } }}
- variant={'borderless'}
+ hotkey: (
+ <Trans
+ components={{
+ key: (
+ <Hotkey
+ as={'span'}
+ keys={wrapperShortcut}
+ style={{ color: 'inherit' }}
+ styles={{ kbdStyle: { color: 'inhert' } }}
+ variant={'borderless'}
+ />
+ ),
+ }}
+ i18nKey={'input.warpWithKey'}
+ ns={'chat'}
/>
),
}}
- i18nKey={'input.warpWithKey'}
+ i18nKey={'sendPlaceholder'}
ns={'chat'}
/>
{'...'}
diff --git a/src/features/ChatInput/StoreUpdater.tsx b/src/features/ChatInput/StoreUpdater.tsx
index 9f8b4984c73..5aae13a2aae 100644
--- a/src/features/ChatInput/StoreUpdater.tsx
+++ b/src/features/ChatInput/StoreUpdater.tsx
@@ -12,6 +12,7 @@ export interface StoreUpdaterProps extends Partial<PublicState> {
const StoreUpdater = memo<StoreUpdaterProps>(
({
+ agentId,
chatInputEditorRef,
mobile,
sendButtonProps,
@@ -26,6 +27,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(
const useStoreUpdater = createStoreUpdater(storeApi);
const editor = useChatInputEditor();
+ useStoreUpdater('agentId', agentId);
useStoreUpdater('mobile', mobile!);
useStoreUpdater('sendMenu', sendMenu!);
useStoreUpdater('mentionItems', mentionItems);
diff --git a/src/features/ChatInput/hooks/useAgentEnableSearch.ts b/src/features/ChatInput/hooks/useAgentEnableSearch.ts
new file mode 100644
index 00000000000..d08e183546e
--- /dev/null
+++ b/src/features/ChatInput/hooks/useAgentEnableSearch.ts
@@ -0,0 +1,28 @@
+'use client';
+
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
+import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
+
+import { useAgentId } from './useAgentId';
+
+/**
+ * Hook to check if search is enabled for the current agent context.
+ * Uses agentId from ChatInput store if provided, otherwise falls back to activeAgentId.
+ */
+export const useAgentEnableSearch = () => {
+ const agentId = useAgentId();
+ const [model, provider, agentSearchMode] = useAgentStore((s) => [
+ agentByIdSelectors.getAgentModelById(agentId)(s),
+ agentByIdSelectors.getAgentModelProviderById(agentId)(s),
+ chatConfigByIdSelectors.getSearchModeById(agentId)(s),
+ ]);
+
+ const searchImpl = useAiInfraStore(aiModelSelectors.modelBuiltinSearchImpl(model, provider));
+
+ // 只要是内置的搜索实现,一定可以联网搜索
+ if (searchImpl === 'internal') return true;
+
+ // 如果是关闭状态,一定不能联网搜索
+ return agentSearchMode !== 'off';
+};
diff --git a/src/features/ChatInput/hooks/useAgentId.ts b/src/features/ChatInput/hooks/useAgentId.ts
new file mode 100644
index 00000000000..a633e335f17
--- /dev/null
+++ b/src/features/ChatInput/hooks/useAgentId.ts
@@ -0,0 +1,22 @@
+'use client';
+
+import { useAgentStore } from '@/store/agent';
+
+import { useChatInputStore } from '../store';
+
+/**
+ * Hook to get the effective agentId for ChatInput components.
+ * Returns agentId from ChatInput store if provided (including empty string),
+ * otherwise falls back to activeAgentId.
+ *
+ * Note: Empty string is a valid value (e.g., when Group's supervisorAgentId is not loaded yet),
+ * so we only fallback when agentId is undefined (not provided).
+ */
+export const useAgentId = () => {
+ const agentIdFromChatInput = useChatInputStore((s) => s.agentId);
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+
+ // Only fallback to activeAgentId when agentIdFromChatInput is undefined (not provided)
+ // Empty string is a valid value and should NOT trigger fallback
+ return agentIdFromChatInput !== undefined ? agentIdFromChatInput : activeAgentId || '';
+};
diff --git a/src/features/ChatInput/hooks/useUpdateAgentConfig.ts b/src/features/ChatInput/hooks/useUpdateAgentConfig.ts
new file mode 100644
index 00000000000..486001bbb8f
--- /dev/null
+++ b/src/features/ChatInput/hooks/useUpdateAgentConfig.ts
@@ -0,0 +1,35 @@
+'use client';
+
+import { useCallback } from 'react';
+import type { PartialDeep } from 'type-fest';
+
+import { useAgentStore } from '@/store/agent';
+import { LobeAgentChatConfig, LobeAgentConfig } from '@/types/agent';
+
+import { useAgentId } from './useAgentId';
+
+/**
+ * Hook to get update functions that work with the current agentId context.
+ * Uses agentId from ChatInput store if provided, otherwise falls back to activeAgentId.
+ */
+export const useUpdateAgentConfig = () => {
+ const agentId = useAgentId();
+ const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
+ const updateAgentChatConfigById = useAgentStore((s) => s.updateAgentChatConfigById);
+
+ const updateAgentConfig = useCallback(
+ (config: PartialDeep<LobeAgentConfig>) => {
+ return updateAgentConfigById(agentId, config);
+ },
+ [agentId, updateAgentConfigById],
+ );
+
+ const updateAgentChatConfig = useCallback(
+ (config: Partial<LobeAgentChatConfig>) => {
+ return updateAgentChatConfigById(agentId, config);
+ },
+ [agentId, updateAgentChatConfigById],
+ );
+
+ return { updateAgentChatConfig, updateAgentConfig };
+};
diff --git a/src/features/ChatInput/store/initialState.ts b/src/features/ChatInput/store/initialState.ts
index 329dd22236f..f584f1b607f 100644
--- a/src/features/ChatInput/store/initialState.ts
+++ b/src/features/ChatInput/store/initialState.ts
@@ -24,6 +24,7 @@ export const initialSendButtonState: SendButtonProps = {
};
export interface PublicState {
+ agentId?: string;
allowExpand?: boolean;
expand?: boolean;
leftActions: ActionKeys[];
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
new file mode 100644
index 00000000000..1b5a10e3332
--- /dev/null
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -0,0 +1,169 @@
+'use client';
+
+import type { SlashOptions } from '@lobehub/editor';
+import { Alert } from '@lobehub/ui';
+import type { MenuProps } from '@lobehub/ui/es/Menu';
+import { type ReactNode, memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { type ActionKeys, ChatInputProvider, DesktopChatInput } from '@/features/ChatInput';
+import type { SendButtonHandler, SendButtonProps } from '@/features/ChatInput/store/initialState';
+import { useChatStore } from '@/store/chat';
+import { fileChatSelectors, useFileStore } from '@/store/file';
+
+import WideScreenContainer from '../../WideScreenContainer';
+import { messageStateSelectors, useConversationStore } from '../store';
+
+export interface ChatInputProps {
+ /**
+ * Custom children to render instead of default Desktop component.
+ * Use this to add custom UI like error alerts, MessageFromUrl, etc.
+ */
+ children?: ReactNode;
+ /**
+ * Left action buttons configuration
+ */
+ leftActions?: ActionKeys[];
+ /**
+ * Mention items for @ mentions (for group chat)
+ */
+ mentionItems?: SlashOptions['items'];
+ /**
+ * Callback when editor instance is ready
+ */
+ onEditorReady?: (editor: any) => void;
+ /**
+ * Right action buttons configuration
+ */
+ rightActions?: ActionKeys[];
+ /**
+ * Custom send button props override
+ */
+ sendButtonProps?: Partial<SendButtonProps>;
+ /**
+ * Send menu configuration (for send options like Enter/Cmd+Enter, Add AI/User message)
+ */
+ sendMenu?: MenuProps;
+}
+
+/**
+ * ChatInput component for Conversation
+ *
+ * Uses ConversationStore for state management instead of global ChatStore.
+ * Reuses the UI components from @/features/ChatInput.
+ */
+const ChatInput = memo<ChatInputProps>(
+ ({
+ leftActions = [],
+ rightActions = [],
+ children,
+ mentionItems,
+ sendMenu,
+ sendButtonProps: customSendButtonProps,
+ onEditorReady,
+ }) => {
+ const { t } = useTranslation('chat');
+
+ // ConversationStore state
+ const [agentId, inputMessage, sendMessage, stopGenerating] = useConversationStore((s) => [
+ s.context.agentId,
+ s.inputMessage,
+ s.sendMessage,
+ s.stopGenerating,
+ ]);
+ const updateInputMessage = useConversationStore((s) => s.updateInputMessage);
+ const setEditor = useConversationStore((s) => s.setEditor);
+
+ // Generation state from ConversationStore (bridged from ChatStore)
+ const isAIGenerating = useConversationStore(messageStateSelectors.isAIGenerating);
+
+ // Send message error from ConversationStore
+ const sendMessageErrorMsg = useConversationStore(messageStateSelectors.sendMessageError);
+ const clearSendMessageError = useChatStore((s) => s.clearSendMessageError);
+
+ // File store - for UI state only (disabled button, etc.)
+ const fileList = useFileStore(fileChatSelectors.chatUploadFileList);
+ const contextList = useFileStore(fileChatSelectors.chatContextSelections);
+ const isUploadingFiles = useFileStore(fileChatSelectors.isUploadingFiles);
+
+ // Computed state
+ const isInputEmpty = !inputMessage.trim() && fileList.length === 0 && contextList.length === 0;
+ const disabled = isInputEmpty || isUploadingFiles || isAIGenerating;
+
+ // Send handler - gets message, clears editor immediately, then sends
+ const handleSend: SendButtonHandler = useCallback(
+ async ({ clearContent, getMarkdownContent }) => {
+ // Get instant values from stores at trigger time
+ const fileStore = useFileStore.getState();
+ const currentFileList = fileChatSelectors.chatUploadFileList(fileStore);
+ const currentIsUploading = fileChatSelectors.isUploadingFiles(fileStore);
+ const currentContextList = fileChatSelectors.chatContextSelections(fileStore);
+
+ if (currentIsUploading || isAIGenerating) return;
+
+ // Get content before clearing
+ const message = getMarkdownContent();
+ if (!message.trim() && currentFileList.length === 0 && currentContextList.length === 0)
+ return;
+
+ // Clear content immediately for responsive UX
+ clearContent();
+ fileStore.clearChatUploadFileList();
+ fileStore.clearChatContextSelections();
+
+ // Fire and forget - send with captured message
+ await sendMessage({ contexts: currentContextList, files: currentFileList, message });
+ },
+ [isAIGenerating, sendMessage],
+ );
+
+ const sendButtonProps: SendButtonProps = {
+ disabled,
+ generating: isAIGenerating,
+ onStop: stopGenerating,
+ ...customSendButtonProps,
+ };
+
+ const defaultContent = (
+ <WideScreenContainer>
+ {sendMessageErrorMsg && (
+ <Flexbox paddingBlock={'0 6px'} paddingInline={12}>
+ <Alert
+ closable
+ message={t('input.errorMsg', { errorMsg: sendMessageErrorMsg })}
+ onClose={clearSendMessageError}
+ type={'secondary'}
+ />
+ </Flexbox>
+ )}
+ <DesktopChatInput />
+ </WideScreenContainer>
+ );
+
+ return (
+ <ChatInputProvider
+ agentId={agentId}
+ chatInputEditorRef={(instance) => {
+ if (instance) {
+ setEditor(instance);
+ onEditorReady?.(instance);
+ }
+ }}
+ leftActions={leftActions}
+ mentionItems={mentionItems}
+ onMarkdownContentChange={updateInputMessage}
+ onSend={handleSend}
+ rightActions={rightActions}
+ sendButtonProps={sendButtonProps}
+ sendMenu={sendMenu}
+ >
+ {children ?? defaultContent}
+ </ChatInputProvider>
+ );
+ },
+);
+
+ChatInput.displayName = 'ConversationChatInput';
+
+export default ChatInput;
diff --git a/src/features/Conversation/ChatItem/ChatItem.tsx b/src/features/Conversation/ChatItem/ChatItem.tsx
new file mode 100644
index 00000000000..bdaab0b0a9f
--- /dev/null
+++ b/src/features/Conversation/ChatItem/ChatItem.tsx
@@ -0,0 +1,129 @@
+'use client';
+
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import Actions from './components/Actions';
+import Avatar from './components/Avatar';
+import ErrorContent from './components/ErrorContent';
+import MessageContent from './components/MessageContent';
+import Title from './components/Title';
+import { useStyles } from './style';
+import { ChatItemProps } from './type';
+
+const ChatItem = memo<ChatItemProps>(
+ ({
+ onAvatarClick,
+ avatarProps,
+ actions,
+ className,
+ loading,
+ message,
+ placeholderMessage = '...',
+ placement = 'left',
+ avatar,
+ error,
+ showTitle,
+ time,
+ editing,
+ messageExtra,
+ children,
+ customErrorRender,
+ onDoubleClick,
+ aboveMessage,
+ belowMessage,
+ showAvatar = true,
+ titleAddon,
+ disabled = false,
+ id,
+ style,
+ newScreen,
+ ...rest
+ }) => {
+ const { cx, styles } = useStyles({
+ disabled,
+ placement,
+ });
+
+ const isUser = placement === 'right';
+ const isEmptyMessage =
+ !message || String(message).trim() === '' || message === placeholderMessage;
+ const errorContent = error && (
+ <ErrorContent customErrorRender={customErrorRender} error={error} id={id} />
+ );
+
+ return (
+ <Flexbox
+ align={isUser ? 'flex-end' : 'flex-start'}
+ className={cx(
+ 'message-wrapper',
+ styles.container,
+ newScreen && styles.newScreen,
+ className,
+ )}
+ gap={8}
+ paddingBlock={8}
+ style={{
+ paddingInlineStart: isUser ? 36 : 0,
+ ...style,
+ }}
+ {...rest}
+ >
+ <Flexbox
+ align={'center'}
+ className={'message-header'}
+ direction={isUser ? 'horizontal-reverse' : 'horizontal'}
+ gap={8}
+ >
+ {showAvatar && (
+ <Avatar
+ alt={avatarProps?.alt || avatar.title || 'avatar'}
+ loading={loading}
+ onClick={onAvatarClick}
+ shape={'square'}
+ {...avatarProps}
+ avatar={avatar}
+ />
+ )}
+ <Title avatar={avatar} showTitle={showTitle} time={time} titleAddon={titleAddon} />
+ </Flexbox>
+ <Flexbox
+ className={'message-body'}
+ gap={8}
+ style={{
+ maxWidth: '100%',
+ overflow: 'hidden',
+ position: 'relative',
+ width: isUser ? undefined : '100%',
+ }}
+ >
+ {aboveMessage}
+ {error && isEmptyMessage ? (
+ errorContent
+ ) : (
+ <MessageContent
+ disabled={disabled}
+ editing={editing}
+ id={id!}
+ message={message}
+ messageExtra={
+ <>
+ {errorContent}
+ {messageExtra}
+ </>
+ }
+ onDoubleClick={onDoubleClick}
+ variant={isUser ? 'bubble' : undefined}
+ >
+ {children}
+ </MessageContent>
+ )}
+ {belowMessage}
+ </Flexbox>
+ {actions && <Actions actions={actions} placement={placement} />}
+ </Flexbox>
+ );
+ },
+);
+
+export default ChatItem;
diff --git a/src/features/Conversation/ChatItem/components/Actions.tsx b/src/features/Conversation/ChatItem/components/Actions.tsx
new file mode 100644
index 00000000000..208941500f2
--- /dev/null
+++ b/src/features/Conversation/ChatItem/components/Actions.tsx
@@ -0,0 +1,28 @@
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { ChatItemProps } from '../type';
+
+export interface ActionsProps {
+ actions: ChatItemProps['actions'];
+ placement?: ChatItemProps['placement'];
+}
+
+const Actions = memo<ActionsProps>(({ placement, actions }) => {
+ const isUser = placement === 'right';
+ return (
+ <Flexbox
+ align={'center'}
+ direction={'horizontal'}
+ gap={8}
+ role="menubar"
+ style={{
+ alignSelf: isUser ? 'flex-end' : 'flex-start',
+ }}
+ >
+ {actions}
+ </Flexbox>
+ );
+});
+
+export default Actions;
diff --git a/src/features/Conversation/ChatItem/components/Avatar.tsx b/src/features/Conversation/ChatItem/components/Avatar.tsx
new file mode 100644
index 00000000000..4ee9147c925
--- /dev/null
+++ b/src/features/Conversation/ChatItem/components/Avatar.tsx
@@ -0,0 +1,35 @@
+import { Avatar as A } from '@lobehub/ui';
+import { type CSSProperties, memo } from 'react';
+
+import type { ChatItemProps } from '../type';
+
+export interface AvatarProps {
+ alt?: string;
+ avatar: ChatItemProps['avatar'];
+ loading?: boolean;
+ onClick?: ChatItemProps['onAvatarClick'];
+ size?: number;
+ style?: CSSProperties;
+ unoptimized?: boolean;
+}
+
+const Avatar = memo<AvatarProps>(
+ ({ loading, avatar, unoptimized, onClick, size = 28, style, alt }) => {
+ return (
+ <A
+ alt={alt || avatar.title}
+ animation={loading}
+ avatar={avatar.avatar}
+ background={avatar.backgroundColor}
+ onClick={onClick}
+ shape={'square'}
+ size={size}
+ style={style}
+ title={avatar.title}
+ unoptimized={unoptimized}
+ />
+ );
+ },
+);
+
+export default Avatar;
diff --git a/src/features/Conversation/ChatItem/components/ErrorContent.tsx b/src/features/Conversation/ChatItem/components/ErrorContent.tsx
new file mode 100644
index 00000000000..aec67023f93
--- /dev/null
+++ b/src/features/Conversation/ChatItem/components/ErrorContent.tsx
@@ -0,0 +1,45 @@
+import { Alert , Skeleton } from '@lobehub/ui';
+import { Suspense, memo } from 'react';
+
+import { useConversationStore } from '@/features/Conversation';
+
+import { ChatItemProps } from '../type';
+
+export interface ErrorContentProps {
+ customErrorRender?: ChatItemProps['customErrorRender'];
+ error: ChatItemProps['error'];
+ id?: string;
+}
+
+const ErrorContent = memo<ErrorContentProps>(({ customErrorRender, error, id }) => {
+ const [deleteMessage] = useConversationStore((s) => [s.deleteMessage]);
+
+ if (!error) return;
+
+ if (customErrorRender) {
+ return (
+ <Suspense fallback={<Skeleton.Button active block />}>{customErrorRender(error)}</Suspense>
+ );
+ }
+
+ return (
+ <Alert
+ afterClose={() => {
+ if (id) {
+ deleteMessage(id);
+ }
+ }}
+ closable
+ showIcon
+ style={{
+ overflow: 'hidden',
+ position: 'relative',
+ width: '100%',
+ }}
+ type={'secondary'}
+ {...error}
+ />
+ );
+});
+
+export default ErrorContent;
diff --git a/src/features/ChatItem/components/Loading.tsx b/src/features/Conversation/ChatItem/components/Loading.tsx
similarity index 93%
rename from src/features/ChatItem/components/Loading.tsx
rename to src/features/Conversation/ChatItem/components/Loading.tsx
index 06b2c9eec06..46f8ada5c15 100644
--- a/src/features/ChatItem/components/Loading.tsx
+++ b/src/features/Conversation/ChatItem/components/Loading.tsx
@@ -4,7 +4,7 @@ import { memo } from 'react';
import { Flexbox } from 'react-layout-kit';
import { useStyles } from '../style';
-import { ChatItemProps } from '../type';
+import type { ChatItemProps } from '../type';
export interface LoadingProps {
loading?: ChatItemProps['loading'];
diff --git a/src/features/Conversation/ChatItem/components/MessageContent/EditableModal.tsx b/src/features/Conversation/ChatItem/components/MessageContent/EditableModal.tsx
new file mode 100644
index 00000000000..a190afbdca2
--- /dev/null
+++ b/src/features/Conversation/ChatItem/components/MessageContent/EditableModal.tsx
@@ -0,0 +1,121 @@
+import {
+ ReactCodePlugin,
+ ReactCodeblockPlugin,
+ ReactHRPlugin,
+ ReactLinkHighlightPlugin,
+ ReactListPlugin,
+ ReactMathPlugin,
+ ReactTablePlugin,
+} from '@lobehub/editor';
+import { Editor, useEditor } from '@lobehub/editor/react';
+import { Modal } from '@lobehub/ui';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/slices/preference/selectors';
+
+import TypoBar from './Typobar';
+
+interface EditableMessageProps {
+ editing?: boolean;
+ onChange?: (value: string) => void;
+ onEditingChange?: (editing: boolean) => void;
+ value?: string;
+}
+
+const EditableMessage = memo<EditableMessageProps>(
+ ({ editing, onEditingChange, onChange, value }) => {
+ const { t } = useTranslation('common');
+ const editor = useEditor();
+
+ const enableRichRender = useUserStore(labPreferSelectors.enableInputMarkdown);
+
+ const richRenderProps = useMemo(
+ () =>
+ !enableRichRender
+ ? {
+ enablePasteMarkdown: false,
+ markdownOption: {
+ bold: false,
+ code: false,
+ header: false,
+ italic: false,
+ quote: false,
+ strikethrough: false,
+ underline: false,
+ underlineStrikethrough: false,
+ },
+ }
+ : {
+ plugins: [
+ ReactListPlugin,
+ ReactCodePlugin,
+ ReactCodeblockPlugin,
+ ReactHRPlugin,
+ ReactLinkHighlightPlugin,
+ ReactTablePlugin,
+ ReactMathPlugin,
+ ],
+ },
+ [enableRichRender],
+ );
+
+ return (
+ <Modal
+ cancelText={t('cancel')}
+ closable={false}
+ destroyOnClose
+ destroyOnHidden
+ okText={t('ok')}
+ onCancel={() => onEditingChange?.(false)}
+ onOk={() => {
+ if (!editor) return;
+ const newValue = editor.getDocument('markdown') as unknown as string;
+ onChange?.(newValue);
+ onEditingChange?.(false);
+ }}
+ open={editing}
+ styles={{
+ body: {
+ overflow: 'hidden',
+ padding: 0,
+ },
+ }}
+ title={null}
+ width={'min(90vw, 960px)'}
+ >
+ <TypoBar editor={editor} />
+ <Flexbox
+ onClick={() => {
+ editor.focus();
+ }}
+ paddingBlock={16}
+ paddingInline={48}
+ style={{ cursor: 'text', maxHeight: '80vh', minHeight: '50vh', overflowY: 'auto' }}
+ >
+ <Editor
+ autoFocus
+ content={''}
+ editor={editor}
+ onInit={(editor) => {
+ if (!editor) return;
+ try {
+ editor?.setDocument('markdown', value);
+ } catch {}
+ }}
+ style={{
+ paddingBottom: 120,
+ }}
+ type={'text'}
+ variant={'chat'}
+ {...richRenderProps}
+ />
+ </Flexbox>
+ </Modal>
+ );
+ },
+);
+
+export default EditableMessage;
diff --git a/src/features/Conversation/ChatItem/components/MessageContent/Typobar.tsx b/src/features/Conversation/ChatItem/components/MessageContent/Typobar.tsx
new file mode 100644
index 00000000000..cb6500bcf85
--- /dev/null
+++ b/src/features/Conversation/ChatItem/components/MessageContent/Typobar.tsx
@@ -0,0 +1,151 @@
+import { HotkeyEnum, IEditor, getHotkeyById } from '@lobehub/editor';
+import { useEditorState } from '@lobehub/editor/react';
+import {
+ ChatInputActionBar,
+ ChatInputActions,
+ type ChatInputActionsProps,
+ CodeLanguageSelect,
+} from '@lobehub/editor/react';
+import { useTheme } from 'antd-style';
+import {
+ BoldIcon,
+ CodeXmlIcon,
+ ItalicIcon,
+ ListIcon,
+ ListOrderedIcon,
+ ListTodoIcon,
+ MessageSquareQuote,
+ SigmaIcon,
+ SquareDashedBottomCodeIcon,
+ StrikethroughIcon,
+ UnderlineIcon,
+} from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const TypoBar = memo<{ editor?: IEditor }>(({ editor }) => {
+ const { t } = useTranslation('editor');
+ const editorState = useEditorState(editor);
+ const theme = useTheme();
+
+ const items: ChatInputActionsProps['items'] = useMemo(
+ () =>
+ [
+ {
+ active: editorState.isBold,
+ icon: BoldIcon,
+ key: 'bold',
+ label: t('typobar.bold'),
+ onClick: editorState.bold,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Bold).keys },
+ },
+ {
+ active: editorState.isItalic,
+ icon: ItalicIcon,
+ key: 'italic',
+ label: t('typobar.italic'),
+ onClick: editorState.italic,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Italic).keys },
+ },
+ {
+ active: editorState.isUnderline,
+ icon: UnderlineIcon,
+ key: 'underline',
+ label: t('typobar.underline'),
+ onClick: editorState.underline,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Underline).keys },
+ },
+ {
+ active: editorState.isStrikethrough,
+ icon: StrikethroughIcon,
+ key: 'strikethrough',
+ label: t('typobar.strikethrough'),
+ onClick: editorState.strikethrough,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Strikethrough).keys },
+ },
+ {
+ type: 'divider',
+ },
+
+ {
+ icon: ListIcon,
+ key: 'bulletList',
+ label: t('typobar.bulletList'),
+ onClick: editorState.bulletList,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.BulletList).keys },
+ },
+ {
+ icon: ListOrderedIcon,
+ key: 'numberlist',
+ label: t('typobar.numberList'),
+ onClick: editorState.numberList,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.NumberList).keys },
+ },
+ {
+ icon: ListTodoIcon,
+ key: 'tasklist',
+ label: t('typobar.taskList'),
+ onClick: editorState.checkList,
+ },
+ {
+ type: 'divider',
+ },
+ {
+ active: editorState.isBlockquote,
+ icon: MessageSquareQuote,
+ key: 'blockquote',
+ label: t('typobar.blockquote'),
+ onClick: editorState.blockquote,
+ },
+ {
+ type: 'divider',
+ },
+ {
+ icon: SigmaIcon,
+ key: 'math',
+ label: t('typobar.tex'),
+ onClick: editorState.insertMath,
+ },
+ {
+ active: editorState.isCode,
+ icon: CodeXmlIcon,
+ key: 'code',
+ label: t('typobar.code'),
+ onClick: editorState.code,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.CodeInline).keys },
+ },
+ {
+ icon: SquareDashedBottomCodeIcon,
+ key: 'codeblock',
+ label: t('typobar.codeblock'),
+ onClick: editorState.codeblock,
+ },
+ editorState.isCodeblock && {
+ children: (
+ <CodeLanguageSelect
+ onSelect={(value) => editorState.updateCodeblockLang(value)}
+ value={editorState.codeblockLang}
+ />
+ ),
+ disabled: !editorState.isCodeblock,
+ key: 'codeblockLang',
+ },
+ ].filter(Boolean) as ChatInputActionsProps['items'],
+ [editorState],
+ );
+
+ return (
+ <ChatInputActionBar
+ left={<ChatInputActions items={items} />}
+ style={{
+ background: theme.colorFillQuaternary,
+ borderTopLeftRadius: 8,
+ borderTopRightRadius: 8,
+ }}
+ />
+ );
+});
+
+TypoBar.displayName = 'TypoBar';
+
+export default TypoBar;
diff --git a/src/features/Conversation/ChatItem/components/MessageContent/index.tsx b/src/features/Conversation/ChatItem/components/MessageContent/index.tsx
new file mode 100644
index 00000000000..679f31ff652
--- /dev/null
+++ b/src/features/Conversation/ChatItem/components/MessageContent/index.tsx
@@ -0,0 +1,107 @@
+import { createStyles } from 'antd-style';
+import dynamic from 'next/dynamic';
+import { type ReactNode, Suspense, memo, useCallback } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { useConversationStore } from '@/features/Conversation/store';
+
+import { ChatItemProps } from '../../type';
+
+const EditableModal = dynamic(() => import('./EditableModal'), { ssr: false });
+
+export const MSG_CONTENT_CLASSNAME = 'msg_content_flag';
+
+export const useStyles = createStyles(({ css, token }) => {
+ return {
+ bubble: css`
+ padding-block: 8px;
+ padding-inline: 12px;
+ border-radius: ${token.borderRadiusLG}px;
+ background-color: ${token.colorFillTertiary};
+ `,
+ disabled: css`
+ user-select: ${'none'};
+ color: ${token.colorTextSecondary};
+ `,
+ message: css`
+ position: relative;
+ overflow: hidden;
+ max-width: 100%;
+ `,
+ };
+});
+
+export interface MessageContentProps {
+ children?: ReactNode;
+ className?: string;
+ disabled?: ChatItemProps['disabled'];
+ editing?: ChatItemProps['editing'];
+ id: string;
+ message?: ReactNode;
+ messageExtra?: ChatItemProps['messageExtra'];
+ onDoubleClick?: ChatItemProps['onDoubleClick'];
+ variant?: 'bubble' | 'default';
+}
+
+const MessageContent = memo<MessageContentProps>(
+ ({
+ editing,
+ id,
+ message,
+ messageExtra,
+ children,
+ onDoubleClick,
+ disabled,
+ className,
+ variant,
+ }) => {
+ const { cx, styles } = useStyles();
+ const [toggleMessageEditing, updateMessageContent] = useConversationStore((s) => [
+ s.toggleMessageEditing,
+ s.updateMessageContent,
+ ]);
+
+ const onChange = useCallback(
+ (value: string) => {
+ updateMessageContent(id, value);
+ },
+ [id, updateMessageContent],
+ );
+
+ const onEditingChange = useCallback(
+ (edit: boolean) => toggleMessageEditing(id, edit),
+ [id, toggleMessageEditing],
+ );
+
+ return (
+ <>
+ <Flexbox
+ className={cx(
+ MSG_CONTENT_CLASSNAME,
+ styles.message,
+ variant === 'bubble' && styles.bubble,
+ disabled && styles.disabled,
+ className,
+ )}
+ gap={16}
+ onDoubleClick={onDoubleClick}
+ >
+ {children || message}
+ {messageExtra}
+ </Flexbox>
+ <Suspense fallback={null}>
+ {editing && (
+ <EditableModal
+ editing={editing}
+ onChange={onChange}
+ onEditingChange={onEditingChange}
+ value={message ? String(message) : ''}
+ />
+ )}
+ </Suspense>
+ </>
+ );
+ },
+);
+
+export default MessageContent;
diff --git a/src/features/Conversation/ChatItem/components/Title.tsx b/src/features/Conversation/ChatItem/components/Title.tsx
new file mode 100644
index 00000000000..5ee33d99230
--- /dev/null
+++ b/src/features/Conversation/ChatItem/components/Title.tsx
@@ -0,0 +1,38 @@
+import { Text } from '@lobehub/ui';
+import dayjs from 'dayjs';
+import { memo } from 'react';
+
+import { ChatItemProps } from '../type';
+
+export interface TitleProps {
+ avatar: ChatItemProps['avatar'];
+ showTitle?: ChatItemProps['showTitle'];
+ time?: ChatItemProps['time'];
+ titleAddon?: ChatItemProps['titleAddon'];
+}
+
+const Title = memo<TitleProps>(({ showTitle, time, avatar, titleAddon }) => {
+ return (
+ <>
+ {showTitle && avatar.title && (
+ <Text fontSize={14} weight={500}>
+ {avatar.title}
+ </Text>
+ )}
+ {showTitle ? titleAddon : undefined}
+ {time && (
+ <Text
+ aria-label="published-date"
+ as={'time'}
+ fontSize={12}
+ title={dayjs(time).format('YYYY-MM-DD HH:mm:ss')}
+ type={'secondary'}
+ >
+ {dayjs(time).fromNow()}
+ </Text>
+ )}
+ </>
+ );
+});
+
+export default Title;
diff --git a/src/features/ChatItem/index.ts b/src/features/Conversation/ChatItem/index.ts
similarity index 52%
rename from src/features/ChatItem/index.ts
rename to src/features/Conversation/ChatItem/index.ts
index e5eca5e3127..c86e7d3644b 100644
--- a/src/features/ChatItem/index.ts
+++ b/src/features/Conversation/ChatItem/index.ts
@@ -1,2 +1,2 @@
export { default as ChatItem } from './ChatItem';
-export type * from './type';
+export type { ChatItemProps } from './type';
diff --git a/src/features/Conversation/ChatItem/style.ts b/src/features/Conversation/ChatItem/style.ts
new file mode 100644
index 00000000000..c2aefbe4b89
--- /dev/null
+++ b/src/features/Conversation/ChatItem/style.ts
@@ -0,0 +1,51 @@
+import { createStyles } from 'antd-style';
+
+export const useStyles = createStyles(({ css, token }) => {
+ return {
+ container: css`
+ position: relative;
+ max-width: 100%;
+
+ time,
+ div[role='menubar'] {
+ pointer-events: none;
+ opacity: 0;
+ transition: opacity 200ms ${token.motionEaseOut};
+ }
+
+ time {
+ display: inline-block;
+ white-space: nowrap;
+ }
+
+ div[role='menubar'] {
+ display: flex;
+ }
+
+ &:hover {
+ time,
+ div[role='menubar'] {
+ pointer-events: unset;
+ opacity: 1;
+ }
+ }
+ `,
+ loading: css`
+ position: absolute;
+ inset-block-end: 0;
+ inset-inline-start: -4px;
+ inset-inline-end: unset;
+
+ width: 16px;
+ height: 16px;
+ border-radius: 50%;
+
+ color: ${token.colorBgLayout};
+
+ background: ${token.colorPrimary};
+ `,
+ newScreen: css`
+ min-height: calc(-300px + 100dvh);
+ `,
+ };
+});
diff --git a/src/features/ChatItem/type.ts b/src/features/Conversation/ChatItem/type.ts
similarity index 76%
rename from src/features/ChatItem/type.ts
rename to src/features/Conversation/ChatItem/type.ts
index c45389bcaaa..f81361ef94e 100644
--- a/src/features/ChatItem/type.ts
+++ b/src/features/Conversation/ChatItem/type.ts
@@ -1,4 +1,4 @@
-import { AlertProps, AvatarProps, DivProps, MarkdownProps } from '@lobehub/ui';
+import { AlertProps, AvatarProps, DivProps } from '@lobehub/ui';
import { EditableMessageProps, MetaData } from '@lobehub/ui/chat';
import { ReactNode } from 'react';
import { FlexboxProps } from 'react-layout-kit';
@@ -8,9 +8,10 @@ export interface ChatItemProps extends Omit<FlexboxProps, 'children' | 'onChange
actions?: ReactNode;
actionsWrapWidth?: number;
avatar: MetaData;
- avatarAddon?: ReactNode;
avatarProps?: AvatarProps;
belowMessage?: ReactNode;
+ children?: ReactNode;
+ customErrorRender?: (error: AlertProps) => ReactNode;
/**
* @description Whether the chat item is disabled
* @default false
@@ -24,18 +25,17 @@ export interface ChatItemProps extends Omit<FlexboxProps, 'children' | 'onChange
* @description Props for Error render
*/
error?: AlertProps;
- errorMessage?: ReactNode;
fontSize?: number;
/**
* @description Whether the chat item is in loading state
*/
loading?: boolean;
- markdownProps?: Omit<MarkdownProps, 'className' | 'style' | 'children'>;
/**
* @description The message content of the chat item
*/
message?: ReactNode;
messageExtra?: ReactNode;
+ newScreen?: boolean;
onAvatarClick?: () => void;
onDoubleClick?: DivProps['onDoubleClick'];
/**
@@ -47,11 +47,6 @@ export interface ChatItemProps extends Omit<FlexboxProps, 'children' | 'onChange
* @default 'left'
*/
placement?: 'left' | 'right';
- /**
- * @description Whether the chat item is primary
- */
- primary?: boolean;
- renderMessage?: (content: ReactNode) => ReactNode;
/**
* @description Whether to hide the avatar
* @default false
@@ -67,9 +62,4 @@ export interface ChatItemProps extends Omit<FlexboxProps, 'children' | 'onChange
*/
time?: number;
titleAddon?: ReactNode;
- /**
- * @description The type of the chat item
- * @default 'bubble'
- */
- variant?: 'bubble' | 'docs';
}
diff --git a/src/features/Conversation/ChatList/components/AutoScroll.tsx b/src/features/Conversation/ChatList/components/AutoScroll.tsx
new file mode 100644
index 00000000000..bf8e30e2ef3
--- /dev/null
+++ b/src/features/Conversation/ChatList/components/AutoScroll.tsx
@@ -0,0 +1,31 @@
+'use client';
+
+import { memo, useEffect } from 'react';
+
+import { useConversationStore, virtuaListSelectors } from '../../store';
+import BackBottom from './BackBottom';
+
+interface AutoScrollProps {
+ /**
+ * Whether AI is generating (for auto-scroll during generation)
+ */
+ isGenerating?: boolean;
+}
+
+const AutoScroll = memo<AutoScrollProps>(({ isGenerating }) => {
+ const atBottom = useConversationStore(virtuaListSelectors.atBottom);
+ const isScrolling = useConversationStore(virtuaListSelectors.isScrolling);
+ const scrollToBottom = useConversationStore((s) => s.scrollToBottom);
+
+ useEffect(() => {
+ if (atBottom && isGenerating && !isScrolling) {
+ scrollToBottom(false);
+ }
+ }, [atBottom, isGenerating, isScrolling, scrollToBottom]);
+
+ return <BackBottom onScrollToBottom={() => scrollToBottom(true)} visible={!atBottom} />;
+});
+
+AutoScroll.displayName = 'ConversationAutoScroll';
+
+export default AutoScroll;
diff --git a/src/features/ChatList/components/BackBottom/index.tsx b/src/features/Conversation/ChatList/components/BackBottom/index.tsx
similarity index 63%
rename from src/features/ChatList/components/BackBottom/index.tsx
rename to src/features/Conversation/ChatList/components/BackBottom/index.tsx
index 248a16aa0b3..0f81de6ae8e 100644
--- a/src/features/ChatList/components/BackBottom/index.tsx
+++ b/src/features/Conversation/ChatList/components/BackBottom/index.tsx
@@ -1,5 +1,5 @@
-import { Button, Icon } from '@lobehub/ui';
-import { ListEnd } from 'lucide-react';
+import { ActionIcon } from '@lobehub/ui';
+import { ArrowDownIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -16,14 +16,19 @@ const BackBottom = memo<BackBottomProps>(({ visible, onScrollToBottom }) => {
const { t } = useTranslation('chat');
return (
- <Button
+ <ActionIcon
className={cx(styles.container, visible && styles.visible)}
- icon={<Icon icon={ListEnd} />}
+ glass
+ icon={ArrowDownIcon}
onClick={onScrollToBottom}
- size={'small'}
- >
- {t('backToBottom', { defaultValue: 'Back to bottom' })}
- </Button>
+ size={{
+ blockSize: 36,
+ borderRadius: 36,
+ size: 18,
+ }}
+ title={t('backToBottom')}
+ variant={'outlined'}
+ />
);
});
diff --git a/src/features/ChatList/components/BackBottom/style.ts b/src/features/Conversation/ChatList/components/BackBottom/style.ts
similarity index 54%
rename from src/features/ChatList/components/BackBottom/style.ts
rename to src/features/Conversation/ChatList/components/BackBottom/style.ts
index ed4d5afc06b..c8faf3c6e08 100644
--- a/src/features/ChatList/components/BackBottom/style.ts
+++ b/src/features/Conversation/ChatList/components/BackBottom/style.ts
@@ -1,7 +1,7 @@
import { createStyles } from 'antd-style';
import { rgba } from 'polished';
-export const useStyles = createStyles(({ token, css, stylish, cx, responsive }) => ({
+export const useStyles = createStyles(({ token, css, stylish, cx }) => ({
container: cx(
stylish.blur,
css`
@@ -13,19 +13,8 @@ export const useStyles = createStyles(({ token, css, stylish, cx, responsive })
inset-inline-end: 16px;
transform: translateY(16px);
- padding-inline: 12px !important;
- border-color: ${token.colorFillTertiary} !important;
- border-radius: 16px !important;
-
opacity: 0;
- background: ${rgba(token.colorBgContainer, 0.5)};
-
- ${responsive.mobile} {
- inset-inline-end: 0;
- border-inline-end: none;
- border-start-end-radius: 0 !important;
- border-end-end-radius: 0 !important;
- }
+ background: ${rgba(token.colorBgElevated, 0.5)} !important;
`,
),
visible: css`
diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
new file mode 100644
index 00000000000..5495cbfd906
--- /dev/null
+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
@@ -0,0 +1,166 @@
+'use client';
+
+import isEqual from 'fast-deep-equal';
+import { ReactElement, type ReactNode, memo, useCallback, useEffect, useRef } from 'react';
+import { VList, VListHandle } from 'virtua';
+
+import WideScreenContainer from '../../../WideScreenContainer';
+import { useConversationStore, virtuaListSelectors } from '../../store';
+import AutoScroll from './AutoScroll';
+
+interface VirtualizedListProps {
+ dataSource: string[];
+ /**
+ * Whether AI is generating (for auto-scroll)
+ */
+ isGenerating?: boolean;
+ itemContent: (index: number, data: string) => ReactNode;
+}
+
+/**
+ * VirtualizedList for Conversation
+ *
+ * Based on ConversationStore data flow, no dependency on global ChatStore.
+ */
+const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent, isGenerating }) => {
+ const virtuaRef = useRef<VListHandle>(null);
+ const prevDataLengthRef = useRef(dataSource.length);
+ const scrollEndTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const atBottomThreshold = 200;
+
+ // Store actions
+ const registerVirtuaScrollMethods = useConversationStore((s) => s.registerVirtuaScrollMethods);
+ const setScrollState = useConversationStore((s) => s.setScrollState);
+ const resetVisibleItems = useConversationStore((s) => s.resetVisibleItems);
+ const scrollToBottom = useConversationStore((s) => s.scrollToBottom);
+ const atBottom = useConversationStore(virtuaListSelectors.atBottom);
+
+ // Check if at bottom based on scroll position
+ const checkAtBottom = useCallback(() => {
+ const ref = virtuaRef.current;
+ if (!ref) return false;
+
+ const scrollOffset = ref.scrollOffset;
+ const scrollSize = ref.scrollSize;
+ const viewportSize = ref.viewportSize;
+
+ return scrollSize - scrollOffset - viewportSize <= atBottomThreshold;
+ }, [atBottomThreshold]);
+
+ // Handle scroll events
+ const handleScroll = useCallback(() => {
+ setScrollState({ isScrolling: true });
+
+ // Check if at bottom
+ const isAtBottom = checkAtBottom();
+ setScrollState({ atBottom: isAtBottom });
+
+ // Clear existing timer
+ if (scrollEndTimerRef.current) {
+ clearTimeout(scrollEndTimerRef.current);
+ }
+
+ // Set new timer for scroll end
+ scrollEndTimerRef.current = setTimeout(() => {
+ setScrollState({ isScrolling: false });
+ }, 150);
+ }, [checkAtBottom, setScrollState]);
+
+ const handleScrollEnd = useCallback(() => {
+ setScrollState({ isScrolling: false });
+ }, [setScrollState]);
+
+ // Register scroll methods to store on mount
+ useEffect(() => {
+ const ref = virtuaRef.current;
+ if (ref) {
+ registerVirtuaScrollMethods({
+ getScrollOffset: () => ref.scrollOffset,
+ getScrollSize: () => ref.scrollSize,
+ getViewportSize: () => ref.viewportSize,
+ scrollToIndex: (index, options) => ref.scrollToIndex(index, options),
+ });
+ }
+
+ return () => {
+ registerVirtuaScrollMethods(null);
+ };
+ }, [registerVirtuaScrollMethods]);
+
+ // Cleanup on unmount
+ useEffect(() => {
+ return () => {
+ resetVisibleItems();
+ if (scrollEndTimerRef.current) {
+ clearTimeout(scrollEndTimerRef.current);
+ }
+ };
+ }, [resetVisibleItems]);
+
+ // Auto scroll to bottom when new messages arrive
+ useEffect(() => {
+ const shouldScroll = dataSource.length > prevDataLengthRef.current;
+ prevDataLengthRef.current = dataSource.length;
+
+ if (shouldScroll && virtuaRef.current) {
+ virtuaRef.current.scrollToIndex(dataSource.length - 2, { align: 'start', smooth: true });
+ }
+ }, [dataSource.length]);
+
+ // Scroll to bottom on initial render
+ useEffect(() => {
+ if (virtuaRef.current && dataSource.length > 0) {
+ virtuaRef.current.scrollToIndex(dataSource.length - 1, { align: 'end' });
+ }
+ }, []);
+
+ return (
+ <>
+ <VList
+ bufferSize={typeof window !== 'undefined' ? window.innerHeight : 0}
+ data={dataSource}
+ onScroll={handleScroll}
+ onScrollEnd={handleScrollEnd}
+ ref={virtuaRef}
+ reverse
+ style={{ height: '100%', paddingBottom: 24 }}
+ >
+ {(messageId, index): ReactElement => {
+ const isAgentCouncil = messageId.includes('agentCouncil');
+ const content = itemContent(index, messageId);
+
+ if (isAgentCouncil) {
+ // AgentCouncil needs full width for horizontal scroll
+ return (
+ <div key={messageId} style={{ position: 'relative', width: '100%' }}>
+ {content}
+ </div>
+ );
+ }
+
+ return (
+ <WideScreenContainer key={messageId} style={{ position: 'relative' }}>
+ {content}
+ </WideScreenContainer>
+ );
+ }}
+ </VList>
+ <WideScreenContainer
+ onChange={() => {
+ if (!atBottom) return;
+ setTimeout(() => scrollToBottom(true), 100);
+ }}
+ style={{
+ position: 'relative',
+ }}
+ >
+ <AutoScroll isGenerating={isGenerating} />
+ </WideScreenContainer>
+ </>
+ );
+}, isEqual);
+
+VirtualizedList.displayName = 'ConversationVirtualizedList';
+
+export default VirtualizedList;
diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsx
new file mode 100644
index 00000000000..0fb6d25afe2
--- /dev/null
+++ b/src/features/Conversation/ChatList/index.tsx
@@ -0,0 +1,82 @@
+'use client';
+
+import { type ReactNode, memo, useCallback } from 'react';
+
+import WideScreenContainer from '../../WideScreenContainer';
+import MessageItem from '../Messages';
+import { MessageActionProvider } from '../Messages/Contexts/MessageActionProvider';
+import SkeletonList from '../components/SkeletonList';
+import { dataSelectors, useConversationStore } from '../store';
+import VirtualizedList from './components/VirtualizedList';
+
+export interface ChatListProps {
+ /**
+ * Custom item renderer. If not provided, uses default ChatItem.
+ */
+ itemContent?: (index: number, id: string) => ReactNode;
+ /**
+ * Welcome component to display when there are no messages
+ */
+ welcome?: ReactNode;
+}
+/**
+ * ChatList component for Conversation
+ *
+ * Uses ConversationStore for message data and fetching.
+ */
+const ChatList = memo<ChatListProps>(({ welcome, itemContent }) => {
+ // Fetch messages (SWR key is null when skipFetch is true)
+ const context = useConversationStore((s) => s.context);
+ const [skipFetch, useFetchMessages] = useConversationStore((s) => [
+ dataSelectors.skipFetch(s),
+ s.useFetchMessages,
+ ]);
+ useFetchMessages(context, skipFetch);
+
+ // Use selectors for data
+
+ const displayMessageIds = useConversationStore(dataSelectors.displayMessageIds);
+
+ const defaultItemContent = useCallback(
+ (index: number, id: string) => {
+ const isLatestItem = displayMessageIds.length === index + 1;
+ return <MessageItem id={id} index={index} isLatestItem={isLatestItem} />;
+ },
+ [displayMessageIds.length],
+ );
+ const messagesInit = useConversationStore(dataSelectors.messagesInit);
+
+ if (!messagesInit) {
+ return <SkeletonList />;
+ }
+
+ if (displayMessageIds.length === 0) {
+ return (
+ <WideScreenContainer
+ style={{
+ height: '100%',
+ }}
+ wrapperStyle={{
+ minHeight: '100%',
+ overflowY: 'auto',
+ }}
+ >
+ {welcome}
+ </WideScreenContainer>
+ );
+ }
+
+ return (
+ <MessageActionProvider withSingletonActionsBar>
+ <VirtualizedList
+ dataSource={displayMessageIds}
+ // isGenerating={isGenerating}
+ itemContent={itemContent ?? defaultItemContent}
+ />
+ </MessageActionProvider>
+ );
+});
+
+ChatList.displayName = 'ConversationChatList';
+
+export default ChatList;
diff --git a/src/features/Conversation/ConversationProvider.tsx b/src/features/Conversation/ConversationProvider.tsx
new file mode 100644
index 00000000000..e5996b98998
--- /dev/null
+++ b/src/features/Conversation/ConversationProvider.tsx
@@ -0,0 +1,96 @@
+'use client';
+
+import type { UIChatMessage } from '@lobechat/types';
+import isEqual from 'fast-deep-equal';
+import { type ReactNode, memo } from 'react';
+
+import StoreUpdater from './StoreUpdater';
+import { Provider, createStore } from './store';
+import type {
+ ActionsBarConfig,
+ ConversationContext,
+ ConversationHooks,
+ OperationState,
+} from './types';
+
+export interface ConversationProviderProps {
+ /**
+ * Actions bar configuration by message type
+ */
+ actionsBar?: ActionsBarConfig;
+ children: ReactNode;
+ /**
+ * Conversation context (data coordinates)
+ */
+ context: ConversationContext;
+ /**
+ * Whether external messages have been initialized
+ * When false, ChatList will show skeleton loading state
+ */
+ hasInitMessages?: boolean;
+ /**
+ * Lifecycle hooks for external behavior injection
+ */
+ hooks?: ConversationHooks;
+ /**
+ * External messages to sync into the store
+ * When provided, these messages will be used as the source of truth
+ */
+ messages?: UIChatMessage[];
+ /**
+ * Callback when messages are fetched or changed internally
+ * Use this to sync messages back to external state (e.g., ChatStore)
+ *
+ * @param messages - The updated messages array
+ */
+ onMessagesChange?: (messages: UIChatMessage[]) => void;
+ /**
+ * External operation state (from ChatStore)
+ *
+ * This state is managed by the global ChatStore and passed down for reactivity.
+ * Operations are kept global to support multiple agents/topics running in parallel.
+ *
+ * When provided, this will be synced into the store for reactive updates.
+ */
+ operationState?: OperationState;
+ skipFetch?: boolean;
+}
+
+/**
+ * ConversationProvider
+ *
+ * Creates an isolated ConversationStore instance for a specific conversation context.
+ * This enables multiple independent conversations to run simultaneously.
+ */
+export const ConversationProvider = memo<ConversationProviderProps>(
+ ({
+ actionsBar,
+ children,
+ context,
+ hooks = {},
+ hasInitMessages,
+ messages,
+ onMessagesChange,
+ operationState,
+ skipFetch,
+ }) => {
+ return (
+ <Provider createStore={() => createStore({ context, hooks, skipFetch })}>
+ <StoreUpdater
+ actionsBar={actionsBar}
+ context={context}
+ hasInitMessages={hasInitMessages}
+ hooks={hooks}
+ messages={messages}
+ onMessagesChange={onMessagesChange}
+ operationState={operationState}
+ skipFetch={skipFetch}
+ />
+ {children}
+ </Provider>
+ );
+ },
+ isEqual,
+);
+
+ConversationProvider.displayName = 'ConversationProvider';
diff --git a/src/features/Conversation/Error/BaseErrorForm.tsx b/src/features/Conversation/Error/BaseErrorForm.tsx
new file mode 100644
index 00000000000..f349463dfee
--- /dev/null
+++ b/src/features/Conversation/Error/BaseErrorForm.tsx
@@ -0,0 +1,40 @@
+import { Block, Text } from '@lobehub/ui';
+import { ReactNode, memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+interface BaseErrorFormProps {
+ action?: ReactNode;
+ avatar?: ReactNode;
+ desc?: ReactNode;
+ title?: ReactNode;
+}
+const BaseErrorForm = memo<BaseErrorFormProps>(({ title, desc, action, avatar }) => {
+ return (
+ <Block
+ align={'center'}
+ gap={8}
+ horizontal
+ justify={'space-between'}
+ padding={16}
+ style={{
+ overflow: 'hidden',
+ position: 'relative',
+ width: '100%',
+ }}
+ variant={'outlined'}
+ >
+ <Flexbox align="center" gap={12} horizontal>
+ {avatar}
+ <Flexbox gap={2}>
+ <Text weight={500}>{title}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {desc}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ {action}
+ </Block>
+ );
+});
+
+export default BaseErrorForm;
diff --git a/src/features/Conversation/Error/ChatInvalidApiKey.tsx b/src/features/Conversation/Error/ChatInvalidApiKey.tsx
new file mode 100644
index 00000000000..36e55485e44
--- /dev/null
+++ b/src/features/Conversation/Error/ChatInvalidApiKey.tsx
@@ -0,0 +1,52 @@
+import { ProviderIcon } from '@lobehub/icons';
+import { Button } from '@lobehub/ui';
+import { ModelProvider } from 'model-bank';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+import urlJoin from 'url-join';
+
+import { useProviderName } from '@/hooks/useProviderName';
+import { GlobalLLMProviderKey } from '@/types/user/settings/modelProvider';
+
+import { useConversationStore } from '../store';
+import BaseErrorForm from './BaseErrorForm';
+
+interface ChatInvalidAPIKeyProps {
+ id: string;
+ provider?: string;
+}
+const ChatInvalidAPIKey = memo<ChatInvalidAPIKeyProps>(({ id, provider }) => {
+ const { t } = useTranslation(['modelProvider', 'error']);
+ const navigate = useNavigate();
+ const [deleteMessage] = useConversationStore((s) => [s.deleteMessage]);
+ const providerName = useProviderName(provider as GlobalLLMProviderKey);
+
+ return (
+ <BaseErrorForm
+ action={
+ <Button
+ onClick={() => {
+ navigate(urlJoin('/settings/provider', provider || 'all'));
+ deleteMessage(id);
+ }}
+ type={'primary'}
+ >
+ {t('unlock.goToSettings', { ns: 'error' })}
+ </Button>
+ }
+ avatar={<ProviderIcon provider={provider} shape={'square'} size={40} />}
+ desc={
+ provider === ModelProvider.Bedrock
+ ? t('bedrock.unlock.description')
+ : t(`unlock.apiKey.description`, {
+ name: providerName,
+ ns: 'error',
+ })
+ }
+ title={t(`unlock.apiKey.title`, { name: providerName, ns: 'error' })}
+ />
+ );
+});
+
+export default ChatInvalidAPIKey;
diff --git a/src/features/ChatList/Error/OllamaBizError/InvalidOllamaModel.tsx b/src/features/Conversation/Error/OllamaBizError/InvalidOllamaModel.tsx
similarity index 87%
rename from src/features/ChatList/Error/OllamaBizError/InvalidOllamaModel.tsx
rename to src/features/Conversation/Error/OllamaBizError/InvalidOllamaModel.tsx
index 9cd6e846e7b..4b93e96636f 100644
--- a/src/features/ChatList/Error/OllamaBizError/InvalidOllamaModel.tsx
+++ b/src/features/Conversation/Error/OllamaBizError/InvalidOllamaModel.tsx
@@ -3,8 +3,8 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import OllamaModelDownloader from '@/features/OllamaModelDownloader';
-import { useChatStore } from '@/store/chat';
+import { useConversationStore } from '../../store';
import { ErrorActionContainer } from '../style';
interface InvalidOllamaModelProps {
@@ -15,7 +15,7 @@ interface InvalidOllamaModelProps {
const InvalidOllamaModel = memo<InvalidOllamaModelProps>(({ id, model }) => {
const { t } = useTranslation('error');
- const [delAndRegenerateMessage, deleteMessage] = useChatStore((s) => [
+ const [delAndRegenerateMessage, deleteMessage] = useConversationStore((s) => [
s.delAndRegenerateMessage,
s.deleteMessage,
]);
diff --git a/src/features/ChatList/Error/OllamaBizError/index.tsx b/src/features/Conversation/Error/OllamaBizError/index.tsx
similarity index 73%
rename from src/features/ChatList/Error/OllamaBizError/index.tsx
rename to src/features/Conversation/Error/OllamaBizError/index.tsx
index ef6748731d7..c6627762599 100644
--- a/src/features/ChatList/Error/OllamaBizError/index.tsx
+++ b/src/features/Conversation/Error/OllamaBizError/index.tsx
@@ -1,13 +1,13 @@
import { ChatMessageError } from '@lobechat/types';
-import { Skeleton } from 'antd';
+import { AlertProps , Skeleton } from '@lobehub/ui';
import dynamic from 'next/dynamic';
import { memo } from 'react';
-import ErrorJsonViewer from '../ErrorJsonViewer';
+import ErrorContent from '@/features/Conversation/ChatItem/components/ErrorContent';
const loading = () => <Skeleton active style={{ width: 300 }} />;
-const SetupGuide = dynamic(() => import('@/features/OllamaSetupGuide'), { loading, ssr: false });
+const SetupGuide = dynamic(() => import('../OllamaSetupGuide'), { loading, ssr: false });
const InvalidModel = dynamic(() => import('./InvalidOllamaModel'), { loading, ssr: false });
@@ -25,11 +25,12 @@ interface OllamaErrorResponse {
const UNRESOLVED_MODEL_REGEXP = /model "([\w+,-_]+)" not found/;
interface OllamaBizErrorProps {
+ alertError?: AlertProps;
error?: ChatMessageError | null;
id: string;
}
-const OllamaBizError = memo<OllamaBizErrorProps>(({ error, id }) => {
+const OllamaBizError = memo<OllamaBizErrorProps>(({ alertError, error, id }) => {
const errorBody: OllamaErrorResponse = (error as any)?.body;
const errorMessage = errorBody.error?.message;
@@ -45,7 +46,7 @@ const OllamaBizError = memo<OllamaBizErrorProps>(({ error, id }) => {
return <SetupGuide id={id} />;
}
- return <ErrorJsonViewer error={error} id={id} />;
+ return <ErrorContent error={alertError} id={id} />;
});
export default OllamaBizError;
diff --git a/src/features/Conversation/Error/OllamaSetupGuide/Desktop.tsx b/src/features/Conversation/Error/OllamaSetupGuide/Desktop.tsx
new file mode 100644
index 00000000000..2fb060c392d
--- /dev/null
+++ b/src/features/Conversation/Error/OllamaSetupGuide/Desktop.tsx
@@ -0,0 +1,41 @@
+import { Ollama } from '@lobehub/icons';
+import { Button } from '@lobehub/ui';
+import Link from 'next/link';
+import { memo } from 'react';
+import { Trans, useTranslation } from 'react-i18next';
+
+import { useConversationStore } from '@/features/Conversation/store';
+
+import BaseErrorForm from '../BaseErrorForm';
+
+// TODO: 优化 Ollama setup 的流程,isDesktop 模式下可以直接做到端到端检测
+const OllamaDesktopSetupGuide = memo<{ id?: string }>(({ id }) => {
+ const { t } = useTranslation('components');
+
+ const [delAndRegenerateMessage] = useConversationStore((s) => [s.delAndRegenerateMessage]);
+
+ return (
+ <BaseErrorForm
+ action={
+ <Button
+ onClick={() => {
+ if (id) delAndRegenerateMessage(id);
+ }}
+ type={'primary'}
+ >
+ {t('OllamaSetupGuide.action.start')}
+ </Button>
+ }
+ avatar={<Ollama.Avatar shape={'square'} size={40} />}
+ desc={
+ <Trans i18nKey={'OllamaSetupGuide.install.description'} ns={'components'}>
+ 请确认你已经开启 Ollama ,如果没有安装 Ollama ,请前往官网
+ <Link href={'https://ollama.com/download'}>下载</Link>
+ </Trans>
+ }
+ title={t('OllamaSetupGuide.install.title')}
+ />
+ );
+});
+
+export default OllamaDesktopSetupGuide;
diff --git a/src/features/Conversation/Error/OllamaSetupGuide/index.tsx b/src/features/Conversation/Error/OllamaSetupGuide/index.tsx
new file mode 100644
index 00000000000..a6ec02679e3
--- /dev/null
+++ b/src/features/Conversation/Error/OllamaSetupGuide/index.tsx
@@ -0,0 +1,27 @@
+import { Block } from '@lobehub/ui';
+import { memo } from 'react';
+
+import OllamaSetupGuide from '@/components/OllamaSetupGuide';
+import { isDesktop } from '@/const/version';
+
+import OllamaDesktopSetupGuide from './Desktop';
+
+const SetupGuide = memo<{ id?: string }>(({ id }) => {
+ return (
+ <Block
+ align={'center'}
+ gap={8}
+ padding={16}
+ style={{
+ overflow: 'hidden',
+ position: 'relative',
+ width: '100%',
+ }}
+ variant={'outlined'}
+ >
+ {isDesktop ? <OllamaDesktopSetupGuide id={id} /> : <OllamaSetupGuide />}
+ </Block>
+ );
+});
+
+export default SetupGuide;
diff --git a/src/features/ChatList/Error/index.tsx b/src/features/Conversation/Error/index.tsx
similarity index 75%
rename from src/features/ChatList/Error/index.tsx
rename to src/features/Conversation/Error/index.tsx
index b9ae317b4d7..52d4c9becd6 100644
--- a/src/features/ChatList/Error/index.tsx
+++ b/src/features/Conversation/Error/index.tsx
@@ -1,29 +1,39 @@
import { AgentRuntimeErrorType, ILobeAgentRuntimeErrorType } from '@lobechat/model-runtime';
import { ChatErrorType, ChatMessageError, ErrorType } from '@lobechat/types';
import { IPluginErrorType } from '@lobehub/chat-plugin-sdk';
-import type { AlertProps } from '@lobehub/ui';
-import { Skeleton } from 'antd';
+import { AlertProps, Block , Skeleton } from '@lobehub/ui';
import dynamic from 'next/dynamic';
-import { Suspense, memo, useMemo } from 'react';
+import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import ErrorContent from '@/features/Conversation/ChatItem/components/ErrorContent';
import { useProviderName } from '@/hooks/useProviderName';
import ChatInvalidAPIKey from './ChatInvalidApiKey';
-import ClerkLogin from './ClerkLogin';
-import ErrorJsonViewer from './ErrorJsonViewer';
-import { ErrorActionContainer } from './style';
interface ErrorMessageData {
error?: ChatMessageError | null;
id: string;
}
-const loading = () => <Skeleton active />;
+const loading = () => (
+ <Block
+ align={'center'}
+ padding={16}
+ style={{
+ overflow: 'hidden',
+ position: 'relative',
+ width: '100%',
+ }}
+ variant={'outlined'}
+ >
+ <Skeleton.Button active block />
+ </Block>
+);
const OllamaBizError = dynamic(() => import('./OllamaBizError'), { loading, ssr: false });
-const OllamaSetupGuide = dynamic(() => import('@/features/OllamaSetupGuide'), {
+const OllamaSetupGuide = dynamic(() => import('./OllamaSetupGuide'), {
loading,
ssr: false,
});
@@ -37,7 +47,7 @@ const getErrorAlertConfig = (
return {
extraDefaultExpand: true,
extraIsolate: true,
- type: 'warning',
+ type: 'secondary',
};
/* ↓ cloud slot ↓ */
@@ -53,7 +63,7 @@ const getErrorAlertConfig = (
case AgentRuntimeErrorType.ExceededContextWindow:
case AgentRuntimeErrorType.LocationNotSupportError: {
return {
- type: 'warning',
+ type: 'secondary',
};
}
@@ -64,7 +74,7 @@ const getErrorAlertConfig = (
return {
extraDefaultExpand: true,
extraIsolate: true,
- type: 'warning',
+ type: 'secondary',
};
}
@@ -92,11 +102,11 @@ export const useErrorContent = (error: any) => {
};
interface ErrorExtraProps {
- block?: boolean;
data: ErrorMessageData;
+ error?: AlertProps;
}
-const ErrorMessageExtra = memo<ErrorExtraProps>(({ data, block }) => {
+const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data }) => {
const error = data.error as ChatMessageError;
if (!error?.type) return;
@@ -113,10 +123,6 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(({ data, block }) => {
/* ↑ cloud slot ↑ */
- case ChatErrorType.InvalidClerkUser: {
- return <ClerkLogin id={data.id} />;
- }
-
case AgentRuntimeErrorType.NoOpenAIAPIKey: {
{
return <ChatInvalidAPIKey id={data.id} provider={data.error?.body?.provider} />;
@@ -128,17 +134,7 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(({ data, block }) => {
return <ChatInvalidAPIKey id={data.id} provider={data.error?.body?.provider} />;
}
- return <ErrorJsonViewer block={block} error={data.error} id={data.id} />;
+ return <ErrorContent error={alertError} id={data.id} />;
});
-export default memo<ErrorExtraProps>(({ data, block }) => (
- <Suspense
- fallback={
- <ErrorActionContainer>
- <Skeleton active style={{ width: '100%' }} />
- </ErrorActionContainer>
- }
- >
- <ErrorMessageExtra block={block} data={data} />
- </Suspense>
-));
+export default ErrorMessageExtra;
diff --git a/src/features/ChatList/Error/style.tsx b/src/features/Conversation/Error/style.tsx
similarity index 98%
rename from src/features/ChatList/Error/style.tsx
rename to src/features/Conversation/Error/style.tsx
index f1d59f89e1c..840538e4df6 100644
--- a/src/features/ChatList/Error/style.tsx
+++ b/src/features/Conversation/Error/style.tsx
@@ -65,6 +65,7 @@ export const FormAction = memo<
avatar={avatar}
background={background ?? theme.colorFillContent}
gap={12}
+ shape={'square'}
size={80}
/>
<Flexbox gap={8} width={'100%'}>
diff --git a/src/features/Conversation/Markdown/index.tsx b/src/features/Conversation/Markdown/index.tsx
new file mode 100644
index 00000000000..3c52e66eaa5
--- /dev/null
+++ b/src/features/Conversation/Markdown/index.tsx
@@ -0,0 +1,32 @@
+import { Markdown, MarkdownProps } from '@lobehub/ui';
+import { memo } from 'react';
+
+import { useUserStore } from '@/store/user';
+import { userGeneralSettingsSelectors } from '@/store/user/selectors';
+
+const MarkdownMessage = memo<MarkdownProps>(({ children, componentProps, ...rest }) => {
+ const { highlighterTheme, mermaidTheme, fontSize } = useUserStore(
+ userGeneralSettingsSelectors.config,
+ );
+
+ return (
+ <Markdown
+ componentProps={{
+ ...componentProps,
+ highlight: {
+ fullFeatured: true,
+ theme: highlighterTheme,
+ ...componentProps?.highlight,
+ },
+ mermaid: { fullFeatured: false, theme: mermaidTheme, ...componentProps?.mermaid },
+ }}
+ fontSize={fontSize}
+ variant={'chat'}
+ {...rest}
+ >
+ {children}
+ </Markdown>
+ );
+});
+
+export default MarkdownMessage;
diff --git a/src/features/ChatList/MarkdownElements/LobeArtifact/Render/Icon.tsx b/src/features/Conversation/Markdown/plugins/LobeArtifact/Render/Icon.tsx
similarity index 100%
rename from src/features/ChatList/MarkdownElements/LobeArtifact/Render/Icon.tsx
rename to src/features/Conversation/Markdown/plugins/LobeArtifact/Render/Icon.tsx
diff --git a/src/features/ChatList/MarkdownElements/LobeArtifact/Render/index.tsx b/src/features/Conversation/Markdown/plugins/LobeArtifact/Render/index.tsx
similarity index 90%
rename from src/features/ChatList/MarkdownElements/LobeArtifact/Render/index.tsx
rename to src/features/Conversation/Markdown/plugins/LobeArtifact/Render/index.tsx
index 8b70b1c5689..21442b297b4 100644
--- a/src/features/ChatList/MarkdownElements/LobeArtifact/Render/index.tsx
+++ b/src/features/Conversation/Markdown/plugins/LobeArtifact/Render/index.tsx
@@ -1,8 +1,7 @@
import { Icon } from '@lobehub/ui';
-import { App } from 'antd';
import { createStyles } from 'antd-style';
import { Loader2 } from 'lucide-react';
-import { memo, useContext, useEffect } from 'react';
+import { memo, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Center, Flexbox } from 'react-layout-kit';
@@ -10,7 +9,6 @@ import { useChatStore } from '@/store/chat';
import { chatPortalSelectors, messageStateSelectors } from '@/store/chat/selectors';
import { dotLoading } from '@/styles/loading';
-import { InPortalThreadContext } from '../../../context/InPortalThreadContext';
import { MarkdownElementProps } from '../../type';
import ArtifactIcon from './Icon';
@@ -62,8 +60,6 @@ const Render = memo<ArtifactProps>(({ identifier, title, type, language, childre
const hasChildren = !!children;
const str = ((children as string) || '').toString?.();
- const inThread = useContext(InPortalThreadContext);
- const { message } = App.useApp();
const [isGenerating, isArtifactTagClosed, openArtifact, closeArtifact] = useChatStore((s) => {
return [
messageStateSelectors.isMessageGenerating(id)(s),
@@ -94,10 +90,6 @@ const Render = memo<ArtifactProps>(({ identifier, title, type, language, childre
if (currentArtifactMessageId === id) {
closeArtifact();
} else {
- if (inThread) {
- message.info(t('artifact.inThread'));
- return;
- }
openArtifactUI();
}
}}
diff --git a/src/features/ChatList/MarkdownElements/LobeArtifact/index.ts b/src/features/Conversation/Markdown/plugins/LobeArtifact/index.ts
similarity index 100%
rename from src/features/ChatList/MarkdownElements/LobeArtifact/index.ts
rename to src/features/Conversation/Markdown/plugins/LobeArtifact/index.ts
diff --git a/src/features/ChatList/MarkdownElements/LobeArtifact/rehypePlugin.test.ts b/src/features/Conversation/Markdown/plugins/LobeArtifact/rehypePlugin.test.ts
similarity index 100%
rename from src/features/ChatList/MarkdownElements/LobeArtifact/rehypePlugin.test.ts
rename to src/features/Conversation/Markdown/plugins/LobeArtifact/rehypePlugin.test.ts
diff --git a/src/features/ChatList/MarkdownElements/LobeArtifact/rehypePlugin.ts b/src/features/Conversation/Markdown/plugins/LobeArtifact/rehypePlugin.ts
similarity index 100%
rename from src/features/ChatList/MarkdownElements/LobeArtifact/rehypePlugin.ts
rename to src/features/Conversation/Markdown/plugins/LobeArtifact/rehypePlugin.ts
diff --git a/src/features/ChatList/MarkdownElements/LobeThinking/Render.tsx b/src/features/Conversation/Markdown/plugins/LobeThinking/Render.tsx
similarity index 73%
rename from src/features/ChatList/MarkdownElements/LobeThinking/Render.tsx
rename to src/features/Conversation/Markdown/plugins/LobeThinking/Render.tsx
index c21802ce5a1..5cd7224cfa8 100644
--- a/src/features/ChatList/MarkdownElements/LobeThinking/Render.tsx
+++ b/src/features/Conversation/Markdown/plugins/LobeThinking/Render.tsx
@@ -1,18 +1,17 @@
-import { ARTIFACT_THINKING_TAG } from '@lobechat/const';
import { memo } from 'react';
import Thinking from '@/components/Thinking';
-import { useChatStore } from '@/store/chat';
-import { dbMessageSelectors } from '@/store/chat/selectors';
+import { ARTIFACT_THINKING_TAG } from '@/const/index';
import { useUserStore } from '@/store/user';
import { userGeneralSettingsSelectors } from '@/store/user/selectors';
+import { dataSelectors, useConversationStore } from '../../../store';
import { MarkdownElementProps } from '../type';
import { isTagClosed } from '../utils';
const Render = memo<MarkdownElementProps>(({ children, id }) => {
- const [isGenerating] = useChatStore((s) => {
- const message = dbMessageSelectors.getDbMessageById(id)(s);
+ const [isGenerating] = useConversationStore((s) => {
+ const message = dataSelectors.getDbMessageById(id)(s);
return [!isTagClosed(ARTIFACT_THINKING_TAG, message?.content)];
});
const transitionMode = useUserStore(userGeneralSettingsSelectors.transitionMode);
diff --git a/src/features/ChatList/MarkdownElements/LobeThinking/index.ts b/src/features/Conversation/Markdown/plugins/LobeThinking/index.ts
similarity index 100%
rename from src/features/ChatList/MarkdownElements/LobeThinking/index.ts
rename to src/features/Conversation/Markdown/plugins/LobeThinking/index.ts
diff --git a/src/features/ChatList/MarkdownElements/LocalFile/Render/index.tsx b/src/features/Conversation/Markdown/plugins/LocalFile/Render/index.tsx
similarity index 100%
rename from src/features/ChatList/MarkdownElements/LocalFile/Render/index.tsx
rename to src/features/Conversation/Markdown/plugins/LocalFile/Render/index.tsx
diff --git a/src/features/ChatList/MarkdownElements/LocalFile/index.ts b/src/features/Conversation/Markdown/plugins/LocalFile/index.ts
similarity index 100%
rename from src/features/ChatList/MarkdownElements/LocalFile/index.ts
rename to src/features/Conversation/Markdown/plugins/LocalFile/index.ts
diff --git a/src/features/ChatList/MarkdownElements/Mention/Render.tsx b/src/features/Conversation/Markdown/plugins/Mention/Render.tsx
similarity index 97%
rename from src/features/ChatList/MarkdownElements/Mention/Render.tsx
rename to src/features/Conversation/Markdown/plugins/Mention/Render.tsx
index 32540677d4d..26e7e3f16c1 100644
--- a/src/features/ChatList/MarkdownElements/Mention/Render.tsx
+++ b/src/features/Conversation/Markdown/plugins/Mention/Render.tsx
@@ -1,6 +1,5 @@
'use client';
-import { DEFAULT_AVATAR } from '@lobechat/const';
import { Avatar, Text } from '@lobehub/ui';
import { Popover } from 'antd';
import { createStyles } from 'antd-style';
@@ -9,6 +8,7 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
+import { DEFAULT_AVATAR } from '@/const/index';
import { useSessionStore } from '@/store/session';
import { sessionSelectors } from '@/store/session/selectors';
@@ -84,6 +84,7 @@ const Render = memo<MarkdownElementProps<MentionProps>>(({ children, node }) =>
<Avatar
avatar={member.avatar || DEFAULT_AVATAR}
background={member.backgroundColor ?? undefined}
+ shape={'square'}
style={{ flex: 'none' }}
/>
<Flexbox style={{ overflow: 'hidden' }}>
diff --git a/src/features/ChatList/MarkdownElements/Mention/index.ts b/src/features/Conversation/Markdown/plugins/Mention/index.ts
similarity index 100%
rename from src/features/ChatList/MarkdownElements/Mention/index.ts
rename to src/features/Conversation/Markdown/plugins/Mention/index.ts
diff --git a/src/features/ChatList/MarkdownElements/Thinking/Render.tsx b/src/features/Conversation/Markdown/plugins/Thinking/Render.tsx
similarity index 74%
rename from src/features/ChatList/MarkdownElements/Thinking/Render.tsx
rename to src/features/Conversation/Markdown/plugins/Thinking/Render.tsx
index 4de2c644985..51f9118d3ed 100644
--- a/src/features/ChatList/MarkdownElements/Thinking/Render.tsx
+++ b/src/features/Conversation/Markdown/plugins/Thinking/Render.tsx
@@ -1,11 +1,10 @@
import { memo } from 'react';
import Thinking from '@/components/Thinking';
-import { useChatStore } from '@/store/chat';
-import { dbMessageSelectors } from '@/store/chat/selectors';
import { useUserStore } from '@/store/user';
import { userGeneralSettingsSelectors } from '@/store/user/selectors';
+import { dataSelectors, useConversationStore } from '../../../store';
import { MarkdownElementProps } from '../type';
const isThinkingClosed = (input: string = '') => {
@@ -16,12 +15,12 @@ const isThinkingClosed = (input: string = '') => {
};
const Render = memo<MarkdownElementProps>(({ children, id }) => {
- const [isGenerating] = useChatStore((s) => {
- const message = dbMessageSelectors.getDbMessageById(id)(s);
+ const [isGenerating] = useConversationStore((s) => {
+ const message = dataSelectors.getDbMessageById(id)(s);
return [!isThinkingClosed(message?.content)];
});
- const citations = useChatStore((s) => {
- const message = dbMessageSelectors.getDbMessageById(id)(s);
+ const citations = useConversationStore((s) => {
+ const message = dataSelectors.getDbMessageById(id)(s);
return message?.search?.citations;
});
diff --git a/src/features/ChatList/MarkdownElements/Thinking/index.ts b/src/features/Conversation/Markdown/plugins/Thinking/index.ts
similarity index 100%
rename from src/features/ChatList/MarkdownElements/Thinking/index.ts
rename to src/features/Conversation/Markdown/plugins/Thinking/index.ts
diff --git a/src/features/ChatList/MarkdownElements/index.ts b/src/features/Conversation/Markdown/plugins/index.ts
similarity index 88%
rename from src/features/ChatList/MarkdownElements/index.ts
rename to src/features/Conversation/Markdown/plugins/index.ts
index 014ab7698ea..b9325368e7d 100644
--- a/src/features/ChatList/MarkdownElements/index.ts
+++ b/src/features/Conversation/Markdown/plugins/index.ts
@@ -5,6 +5,8 @@ import Mention from './Mention';
import Thinking from './Thinking';
import { MarkdownElement } from './type';
+export type { MarkdownElement } from './type';
+
export const markdownElements: MarkdownElement[] = [
Thinking,
LobeArtifact,
diff --git a/src/features/ChatList/MarkdownElements/remarkPlugins/__snapshots__/createRemarkSelfClosingTagPlugin.test.ts.snap b/src/features/Conversation/Markdown/plugins/remarkPlugins/__snapshots__/createRemarkSelfClosingTagPlugin.test.ts.snap
similarity index 100%
rename from src/features/ChatList/MarkdownElements/remarkPlugins/__snapshots__/createRemarkSelfClosingTagPlugin.test.ts.snap
rename to src/features/Conversation/Markdown/plugins/remarkPlugins/__snapshots__/createRemarkSelfClosingTagPlugin.test.ts.snap
diff --git a/src/features/ChatList/MarkdownElements/remarkPlugins/createRemarkCustomTagPlugin.ts b/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkCustomTagPlugin.ts
similarity index 100%
rename from src/features/ChatList/MarkdownElements/remarkPlugins/createRemarkCustomTagPlugin.ts
rename to src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkCustomTagPlugin.ts
diff --git a/src/features/ChatList/MarkdownElements/remarkPlugins/createRemarkCustomTagWithAttributesPlugin.ts b/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkCustomTagWithAttributesPlugin.ts
similarity index 100%
rename from src/features/ChatList/MarkdownElements/remarkPlugins/createRemarkCustomTagWithAttributesPlugin.ts
rename to src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkCustomTagWithAttributesPlugin.ts
diff --git a/src/features/ChatList/MarkdownElements/remarkPlugins/createRemarkSelfClosingTagPlugin.test.ts b/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkSelfClosingTagPlugin.test.ts
similarity index 75%
rename from src/features/ChatList/MarkdownElements/remarkPlugins/createRemarkSelfClosingTagPlugin.test.ts
rename to src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkSelfClosingTagPlugin.test.ts
index 46781a07ecf..680f5d6b3c6 100644
--- a/src/features/ChatList/MarkdownElements/remarkPlugins/createRemarkSelfClosingTagPlugin.test.ts
+++ b/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkSelfClosingTagPlugin.test.ts
@@ -15,6 +15,18 @@ const processMarkdown = (markdown: string, tagName: string) => {
describe('createRemarkSelfClosingTagPlugin', () => {
const tagName = 'localFile';
+ const collectNodesByType = (tree: any, type: string) => {
+ const nodes: any[] = [];
+ const walk = (node: any) => {
+ if (!node || typeof node !== 'object') return;
+ if (node.type === type) nodes.push(node);
+ const children = (node as any).children;
+ if (Array.isArray(children)) for (const child of children) walk(child);
+ };
+ walk(tree);
+ return nodes;
+ };
+
it('should replace a single self-closing tag (parsed as HTML) with a custom node', () => {
const markdown = `<${tagName} name="test.txt" path="/path/to/test.txt" />`;
const tree = processMarkdown(markdown, tagName);
@@ -202,6 +214,64 @@ describe('createRemarkSelfClosingTagPlugin', () => {
expect(tree).toMatchSnapshot();
});
+ it('should parse attributes containing spaces and @ (real-world screenshot file name)', () => {
+ const markdown = `<${tagName} name="CleanShot 2025-12-17 at [email protected]" path="/Users/innei/Desktop/CleanShot 2025-12-17 at [email protected]" />`;
+ const tree = processMarkdown(markdown, tagName);
+
+ expect(tree.children).toHaveLength(1);
+ const node = tree.children[0];
+ expect(node.type).toBe(tagName);
+ expect(node.data?.hName).toBe(tagName);
+ expect(node.data?.hProperties).toEqual({
+ name: 'CleanShot 2025-12-17 at [email protected]',
+ path: '/Users/innei/Desktop/CleanShot 2025-12-17 at [email protected]',
+ });
+ });
+
+ it('should handle multiple consecutive tags parsed as a single html block node', () => {
+ const markdown = [
+ '以下是桌面(`<localFile name="Desktop" path="/Users/innei/Desktop" isDirectory />`)下的文件列表:',
+ '',
+ '<localFile name="CleanShot 2025-12-17 at [email protected]" path="/Users/innei/Desktop/CleanShot 2025-12-17 at [email protected]" />',
+ '<localFile name="CleanShot 2025-12-17 at [email protected]" path="/Users/innei/Desktop/CleanShot 2025-12-17 at [email protected]" />',
+ '<localFile name="CleanShot 2025-12-17 at [email protected]" path="/Users/innei/Desktop/CleanShot 2025-12-17 at [email protected]" />',
+ '<localFile name="CleanShot 2025-12-17 at [email protected]" path="/Users/innei/Desktop/CleanShot 2025-12-17 at [email protected]" />',
+ '<localFile name="CleanShot 2025-12-17 at [email protected]" path="/Users/innei/Desktop/CleanShot 2025-12-17 at [email protected]" />',
+ '<localFile name="CleanShot 2025-12-17 at 22.39.37.mp4" path="/Users/innei/Desktop/CleanShot 2025-12-17 at 22.39.37.mp4" />',
+ '<localFile name="CleanShot 2025-12-18 at [email protected]" path="/Users/innei/Desktop/CleanShot 2025-12-18 at [email protected]" />',
+ '',
+ '如果你想查看其他目录或进一步筛选文件,请告诉我!',
+ ].join('\n');
+
+ const tree = processMarkdown(markdown, tagName);
+ const localFiles = collectNodesByType(tree, tagName);
+
+ expect(localFiles).toHaveLength(8);
+ expect(localFiles.map((n) => n.data?.hProperties?.name)).toEqual([
+ 'Desktop',
+ 'CleanShot 2025-12-17 at [email protected]',
+ 'CleanShot 2025-12-17 at [email protected]',
+ 'CleanShot 2025-12-17 at [email protected]',
+ 'CleanShot 2025-12-17 at [email protected]',
+ 'CleanShot 2025-12-17 at [email protected]',
+ 'CleanShot 2025-12-17 at 22.39.37.mp4',
+ 'CleanShot 2025-12-18 at [email protected]',
+ ]);
+ });
+
+ it('should match tag name in a case-insensitive way (HTML tag names are case-insensitive)', () => {
+ const markdown = `<localfile name="a.txt" path="/tmp/a.txt" />`;
+ const tree = processMarkdown(markdown, tagName);
+
+ expect(tree.children).toHaveLength(1);
+ const node = tree.children[0];
+ expect(node.type).toBe(tagName);
+ expect(node.data?.hProperties).toEqual({
+ name: 'a.txt',
+ path: '/tmp/a.txt',
+ });
+ });
+
it('should handle multiple tags in unordered list with directories and files', () => {
const markdown = [
'我已查看了你桌面上 test 文件夹的目录,里面包含以下项目:',
diff --git a/src/features/ChatList/MarkdownElements/remarkPlugins/createRemarkSelfClosingTagPlugin.ts b/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkSelfClosingTagPlugin.ts
similarity index 67%
rename from src/features/ChatList/MarkdownElements/remarkPlugins/createRemarkSelfClosingTagPlugin.ts
rename to src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkSelfClosingTagPlugin.ts
index 9b14f7d34ca..db6eb77ee91 100644
--- a/src/features/ChatList/MarkdownElements/remarkPlugins/createRemarkSelfClosingTagPlugin.ts
+++ b/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkSelfClosingTagPlugin.ts
@@ -5,6 +5,8 @@ import { SKIP, visit } from 'unist-util-visit';
// 创建 debugger 实例
const log = debug('lobe-markdown:remark-plugin:self-closing');
+const escapeRegExp = (str: string) => str.replaceAll(/[$()*+.?[\\\]^{|}]/g, '\\$&');
+
// Regex to parse attributes from a string
// Handles keys, keys with quoted values (double or single), and boolean keys
const attributeRegex = /([\w-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
@@ -26,9 +28,11 @@ export const createRemarkSelfClosingTagPlugin =
() => {
// Regex for the specific tag, ensure it matches the entire string for HTML check
// Allow trailing whitespace after /> to handle cases where markdown parsers include it
- const exactTagRegex = new RegExp(`^<${tagName}(\\s+[^>]*?)?\\s*\\/>\\s*$`);
+ // Tag names are case-insensitive in HTML, and some upstream processors may normalize casing.
+ const escapedTagName = escapeRegExp(tagName);
+ const exactTagRegex = new RegExp(`^<${escapedTagName}(\\s+[^>]*?)?\\s*\\/>\\s*$`, 'i');
// Regex for finding tags within text
- const textTagRegex = new RegExp(`<${tagName}(\\s+[^>]*?)?\\s*\\/>`, 'g');
+ const textTagRegex = new RegExp(`<${escapedTagName}(\\s+[^>]*?)?\\s*\\/>`, 'gi');
return (tree) => {
// --- DEBUG LOG START (Before Visit) ---
@@ -73,6 +77,55 @@ export const createRemarkSelfClosingTagPlugin =
parent.children.splice(index, 1, newNode);
return [SKIP, index + 1]; // Skip the node we just inserted
}
+
+ // Handle the common case where remark parses multiple consecutive HTML tags as a single `html` node
+ // e.g.
+ // <localFile ... />
+ // <localFile ... />
+ if (
+ parent &&
+ typeof index === 'number' &&
+ typeof node.value === 'string' &&
+ node.value.toLowerCase().includes(`<${tagName.toLowerCase()}`)
+ ) {
+ const html = node.value;
+ const newChildren: any[] = [];
+ let lastIndex = 0;
+ let textMatch: RegExpExecArray | null;
+
+ textTagRegex.lastIndex = 0;
+ while ((textMatch = textTagRegex.exec(html)) !== null) {
+ const [fullMatch, attributesString] = textMatch;
+ const matchIndex = textMatch.index;
+
+ // Preserve any non-tag fragments as `html` nodes (flow content), so we don't create invalid root-level `text`.
+ if (matchIndex > lastIndex) {
+ const fragment = html.slice(lastIndex, matchIndex);
+ if (fragment) newChildren.push({ type: 'html', value: fragment });
+ }
+
+ const properties = attributesString ? parseAttributes(attributesString.trim()) : {};
+ newChildren.push({
+ data: { hName: tagName, hProperties: properties },
+ type: tagName,
+ });
+
+ lastIndex = matchIndex + fullMatch.length;
+ }
+
+ if (newChildren.length > 0) {
+ if (lastIndex < html.length) {
+ const fragment = html.slice(lastIndex);
+ if (fragment) newChildren.push({ type: 'html', value: fragment });
+ }
+
+ // Only replace when we actually produced at least one tag node
+ if (newChildren.some((n) => n?.type === tagName)) {
+ parent.children.splice(index, 1, ...newChildren);
+ return [SKIP, index + newChildren.length];
+ }
+ }
+ }
});
// 2. Visit Text nodes for inline matches
@@ -80,7 +133,12 @@ export const createRemarkSelfClosingTagPlugin =
visit(tree, 'text', (node: any, index: number, parent) => {
log('>>> Visiting Text node: "%s"', node.value);
- if (!parent || typeof index !== 'number' || !node.value?.includes(`<${tagName}`)) {
+ if (
+ !parent ||
+ typeof index !== 'number' ||
+ typeof node.value !== 'string' ||
+ !node.value.toLowerCase().includes(`<${tagName.toLowerCase()}`)
+ ) {
return; // Quick exit if tag isn't possibly present
}
@@ -136,7 +194,12 @@ export const createRemarkSelfClosingTagPlugin =
visit(tree, 'inlineCode', (node: any, index: number, parent) => {
log('>>> Visiting inlineCode node: "%s"', node.value);
- if (!parent || typeof index !== 'number' || !node.value?.includes(`<${tagName}`)) {
+ if (
+ !parent ||
+ typeof index !== 'number' ||
+ typeof node.value !== 'string' ||
+ !node.value.toLowerCase().includes(`<${tagName.toLowerCase()}`)
+ ) {
return;
}
diff --git a/src/features/ChatList/MarkdownElements/remarkPlugins/getNodeContent.test.ts b/src/features/Conversation/Markdown/plugins/remarkPlugins/getNodeContent.test.ts
similarity index 100%
rename from src/features/ChatList/MarkdownElements/remarkPlugins/getNodeContent.test.ts
rename to src/features/Conversation/Markdown/plugins/remarkPlugins/getNodeContent.test.ts
diff --git a/src/features/ChatList/MarkdownElements/remarkPlugins/getNodeContent.ts b/src/features/Conversation/Markdown/plugins/remarkPlugins/getNodeContent.ts
similarity index 100%
rename from src/features/ChatList/MarkdownElements/remarkPlugins/getNodeContent.ts
rename to src/features/Conversation/Markdown/plugins/remarkPlugins/getNodeContent.ts
diff --git a/src/features/ChatList/MarkdownElements/type.ts b/src/features/Conversation/Markdown/plugins/type.ts
similarity index 100%
rename from src/features/ChatList/MarkdownElements/type.ts
rename to src/features/Conversation/Markdown/plugins/type.ts
diff --git a/src/features/ChatList/MarkdownElements/utils.ts b/src/features/Conversation/Markdown/plugins/utils.ts
similarity index 100%
rename from src/features/ChatList/MarkdownElements/utils.ts
rename to src/features/Conversation/Markdown/plugins/utils.ts
diff --git a/src/features/Conversation/Messages/AgentCouncil/CouncilMember.tsx b/src/features/Conversation/Messages/AgentCouncil/CouncilMember.tsx
new file mode 100644
index 00000000000..2edeb9f523d
--- /dev/null
+++ b/src/features/Conversation/Messages/AgentCouncil/CouncilMember.tsx
@@ -0,0 +1,111 @@
+'use client';
+
+import { createStyles } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import Avatar from '@/features/Conversation/ChatItem/components/Avatar';
+import Title from '@/features/Conversation/ChatItem/components/Title';
+import type { UIChatMessage } from '@/types/index';
+
+import { useAgentMeta } from '../../hooks';
+import { messageStateSelectors, useConversationStore } from '../../store';
+import MessageContent from '../Assistant/components/MessageContent';
+import Usage from '../components/Extras/Usage';
+import type { DisplayMode } from './index';
+
+const useStyles = createStyles(({ css, token, responsive }) => ({
+ cardHorizontal: css`
+ scroll-snap-align: start;
+
+ overflow: hidden;
+ flex: 0 0 auto;
+
+ width: 480px;
+ padding: 12px;
+ border: 1px solid ${token.colorBorderSecondary};
+ border-radius: ${token.borderRadiusLG}px;
+
+ background: ${token.colorBgContainer};
+
+ ${responsive.mobile} {
+ width: 85vw;
+ max-width: 360px;
+ }
+ `,
+ // Tab mode: full width, no border
+ cardTab: css`
+ overflow: hidden;
+
+ width: 100%;
+ padding: 12px;
+ border: 1px solid ${token.colorBorderSecondary};
+ border-radius: ${token.borderRadiusLG}px;
+
+ background: ${token.colorBgContainer};
+ `,
+ // Vertical mode: full width with border
+ cardVertical: css`
+ overflow: hidden;
+
+ width: 100%;
+ padding: 12px;
+ border: 1px solid ${token.colorBorderSecondary};
+ border-radius: ${token.borderRadiusLG}px;
+
+ background: ${token.colorBgContainer};
+ `,
+ content: css`
+ overflow: auto;
+ flex: 1;
+ `,
+}));
+
+interface CouncilMemberProps {
+ index: number;
+ message: UIChatMessage;
+ mode?: DisplayMode;
+}
+
+/**
+ * CouncilMember - Renders a single agent's response in the council grid
+ *
+ * Handles both:
+ * - assistantGroup: Agent response with tool calls
+ * - assistant: Simple agent response without tools
+ */
+const CouncilMember = memo<CouncilMemberProps>(({ message, mode = 'horizontal' }) => {
+ const { styles, cx } = useStyles();
+
+ const { agentId, performance, model, provider, usage, createdAt, id } = message;
+ const avatar = useAgentMeta(agentId);
+
+ const creating = useConversationStore(messageStateSelectors.isMessageCreating(id));
+
+ const cardClassName = cx({
+ [styles.cardHorizontal]: mode === 'horizontal',
+ [styles.cardTab]: mode === 'tab',
+ [styles.cardVertical]: mode === 'vertical',
+ });
+
+ return (
+ <Flexbox className={cardClassName} gap={12}>
+ <Flexbox align={'center'} gap={4} horizontal>
+ <Avatar avatar={avatar} loading={creating} />
+ <Title avatar={avatar} showTitle time={createdAt} />
+ </Flexbox>
+
+ <Flexbox className={styles.content} gap={8}>
+ <MessageContent {...message} />
+ {model && (
+ <Usage model={model} performance={performance} provider={provider!} usage={usage} />
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+}, isEqual);
+
+CouncilMember.displayName = 'CouncilMember';
+
+export default CouncilMember;
diff --git a/src/features/Conversation/Messages/AgentCouncil/TaskInstruction.tsx b/src/features/Conversation/Messages/AgentCouncil/TaskInstruction.tsx
new file mode 100644
index 00000000000..99b4bb06a22
--- /dev/null
+++ b/src/features/Conversation/Messages/AgentCouncil/TaskInstruction.tsx
@@ -0,0 +1,32 @@
+'use client';
+
+import { Text } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { memo } from 'react';
+
+const useStyles = createStyles(({ css, token }) => ({
+ content: css`
+ padding-block: 16px;
+ padding-inline: 16px;
+ border-radius: 8px;
+ background: ${token.colorFillQuaternary};
+ `,
+}));
+
+interface TaskInstructionProps {
+ instruction: string;
+}
+
+const TaskInstruction = memo<TaskInstructionProps>(({ instruction }) => {
+ const { styles } = useStyles();
+
+ return (
+ <Text className={styles.content} style={{ margin: 0 }}>
+ {instruction}
+ </Text>
+ );
+});
+
+TaskInstruction.displayName = 'TaskInstruction';
+
+export default TaskInstruction;
diff --git a/src/features/Conversation/Messages/AgentCouncil/index.tsx b/src/features/Conversation/Messages/AgentCouncil/index.tsx
new file mode 100644
index 00000000000..80798ad3172
--- /dev/null
+++ b/src/features/Conversation/Messages/AgentCouncil/index.tsx
@@ -0,0 +1,183 @@
+'use client';
+
+import { UIChatMessage } from '@lobechat/types';
+import { Segmented } from 'antd';
+import { createStyles } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { Columns2, Layers, StretchHorizontal } from 'lucide-react';
+import { memo, useState } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import WideScreenContainer from '@/features/WideScreenContainer';
+
+import { dataSelectors, useConversationStore } from '../../store';
+import CouncilMember from './CouncilMember';
+
+export type DisplayMode = 'horizontal' | 'tab' | 'vertical';
+
+const useStyles = createStyles(({ css, token, responsive }) => ({
+ container: css`
+ overflow: visible;
+ width: calc(100% + 32px);
+ margin-inline: -16px;
+ padding-inline: 16px;
+ `,
+ header: css`
+ display: flex;
+ justify-content: flex-end;
+ margin-block-end: 8px;
+ `,
+ horizontalScroll: css`
+ scroll-behavior: smooth;
+ scrollbar-color: ${token.colorBorderSecondary} transparent;
+ scrollbar-width: thin;
+ scroll-snap-type: x mandatory;
+
+ overflow: auto hidden;
+ display: flex;
+ gap: ${token.paddingMD}px;
+
+ padding-block: 4px;
+
+ &::-webkit-scrollbar {
+ height: 6px;
+ }
+
+ &::-webkit-scrollbar-track {
+ background: transparent;
+ }
+
+ &::-webkit-scrollbar-thumb {
+ border-radius: 3px;
+ background: ${token.colorBorderSecondary};
+
+ &:hover {
+ background: ${token.colorBorder};
+ }
+ }
+
+ ${responsive.mobile} {
+ scrollbar-width: none;
+
+ &::-webkit-scrollbar {
+ display: none;
+ }
+ }
+ `,
+ tabContent: css`
+ width: 100%;
+ `,
+ tabSelector: css`
+ margin-block-end: 12px;
+ `,
+ verticalStack: css`
+ display: flex;
+ flex-direction: column;
+ gap: ${token.paddingMD}px;
+ `,
+}));
+
+interface AgentCouncilMessageProps {
+ id: string;
+ index: number;
+ isLatestItem?: boolean;
+}
+
+/**
+ * AgentCouncilMessage - Renders multiple agent responses with switchable layouts
+ *
+ * Display modes:
+ * - horizontal: Side by side with horizontal scroll (default)
+ * - tab: Tabbed view with one agent per tab
+ * - vertical: Stacked vertically for comparison
+ */
+const AgentCouncilMessage = memo<AgentCouncilMessageProps>(({ id }) => {
+ const { styles } = useStyles();
+ const [displayMode, setDisplayMode] = useState<DisplayMode>('horizontal');
+ const [activeTab, setActiveTab] = useState(0);
+
+ const item = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual)!;
+ const members = (item as UIChatMessage)?.members as UIChatMessage[] | undefined;
+
+ if (!members || members.length === 0) {
+ return null;
+ }
+
+ const renderContent = () => {
+ switch (displayMode) {
+ case 'tab': {
+ const activeMember = members[activeTab];
+ if (!activeMember) return null;
+
+ return (
+ <WideScreenContainer>
+ <Flexbox className={styles.tabContent}>
+ <div>
+ <Segmented
+ className={styles.tabSelector}
+ onChange={(value) => setActiveTab(Number(value))}
+ options={members.map((member, idx) => ({
+ label: `Agent ${idx + 1}`,
+ value: idx,
+ }))}
+ value={activeTab}
+ />
+ </div>
+ <CouncilMember index={activeTab} message={activeMember} mode="tab" />
+ </Flexbox>
+ </WideScreenContainer>
+ );
+ }
+
+ case 'vertical': {
+ return (
+ <WideScreenContainer>
+ <div className={styles.verticalStack}>
+ {members.map((member, idx) => {
+ if (!member) return null;
+ return (
+ <CouncilMember index={idx} key={member.id} message={member} mode="vertical" />
+ );
+ })}
+ </div>
+ </WideScreenContainer>
+ );
+ }
+
+ default: {
+ return (
+ <div className={styles.horizontalScroll}>
+ {members.map((member, idx) => {
+ if (!member) return null;
+ return (
+ <CouncilMember index={idx} key={member.id} message={member} mode="horizontal" />
+ );
+ })}
+ </div>
+ );
+ }
+ }
+ };
+
+ return (
+ <Flexbox className={styles.container}>
+ <WideScreenContainer>
+ <div className={styles.header}>
+ <Segmented
+ onChange={(value) => setDisplayMode(value as DisplayMode)}
+ options={[
+ { icon: <StretchHorizontal size={14} />, value: 'horizontal' },
+ { icon: <Layers size={14} />, value: 'tab' },
+ { icon: <Columns2 size={14} />, value: 'vertical' },
+ ]}
+ size="small"
+ value={displayMode}
+ />
+ </div>
+ </WideScreenContainer>
+ {renderContent()}
+ </Flexbox>
+ );
+}, isEqual);
+
+export default AgentCouncilMessage;
diff --git a/src/features/Conversation/Messages/Assistant/Actions/Error.tsx b/src/features/Conversation/Messages/Assistant/Actions/Error.tsx
new file mode 100644
index 00000000000..cbba06fdb95
--- /dev/null
+++ b/src/features/Conversation/Messages/Assistant/Actions/Error.tsx
@@ -0,0 +1,26 @@
+import { ActionIconGroup } from '@lobehub/ui';
+import type { ActionIconGroupEvent } from '@lobehub/ui';
+import { memo } from 'react';
+
+import type { AssistantActions } from './useAssistantActions';
+
+interface ErrorActionsBarProps {
+ actions: AssistantActions;
+ onActionClick: (event: ActionIconGroupEvent) => void;
+}
+
+export const ErrorActionsBar = memo<ErrorActionsBarProps>(({ actions, onActionClick }) => {
+ const { regenerate, copy, edit, del, divider } = actions;
+
+ return (
+ <ActionIconGroup
+ items={[regenerate, del]}
+ menu={{
+ items: [edit, copy, divider, del],
+ }}
+ onActionClick={onActionClick}
+ />
+ );
+});
+
+ErrorActionsBar.displayName = 'ErrorActionsBar';
diff --git a/src/features/Conversation/Messages/Assistant/Actions/index.tsx b/src/features/Conversation/Messages/Assistant/Actions/index.tsx
new file mode 100644
index 00000000000..b8aafc94e8f
--- /dev/null
+++ b/src/features/Conversation/Messages/Assistant/Actions/index.tsx
@@ -0,0 +1,191 @@
+import { UIChatMessage } from '@lobechat/types';
+import { ActionIconGroup } from '@lobehub/ui';
+import type { ActionIconGroupEvent, ActionIconGroupItemType } from '@lobehub/ui';
+import { memo, useCallback, useMemo, useState } from 'react';
+
+import ShareMessageModal from '../../../components/ShareMessageModal';
+import { messageStateSelectors, useConversationStore } from '../../../store';
+import type {
+ MessageActionItem,
+ MessageActionItemOrDivider,
+ MessageActionsConfig,
+} from '../../../types';
+import { ErrorActionsBar } from './Error';
+import { useAssistantActions } from './useAssistantActions';
+
+// Helper to strip handleClick from action items before passing to ActionIconGroup
+const stripHandleClick = (item: MessageActionItemOrDivider): ActionIconGroupItemType => {
+ if ('type' in item && item.type === 'divider') return item as unknown as ActionIconGroupItemType;
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const { handleClick, children, ...rest } = item as MessageActionItem;
+ if (children) {
+ return {
+ ...rest,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ children: children.map(({ handleClick: _, ...child }) => child),
+ } as ActionIconGroupItemType;
+ }
+ return rest as ActionIconGroupItemType;
+};
+
+// Build action items map for handleAction lookup
+const buildActionsMap = (items: MessageActionItemOrDivider[]): Map<string, MessageActionItem> => {
+ const map = new Map<string, MessageActionItem>();
+ for (const item of items) {
+ if ('key' in item && item.key) {
+ map.set(String(item.key), item as MessageActionItem);
+ // Also index children for submenu items
+ if ('children' in item && item.children) {
+ for (const child of item.children) {
+ if (child.key) {
+ map.set(`${item.key}.${child.key}`, child as unknown as MessageActionItem);
+ }
+ }
+ }
+ }
+ }
+ return map;
+};
+
+interface AssistantActionsBarProps {
+ actionsConfig?: MessageActionsConfig;
+ data: UIChatMessage;
+ id: string;
+ index: number;
+}
+
+export const AssistantActionsBar = memo<AssistantActionsBarProps>(
+ ({ actionsConfig, id, data, index }) => {
+ const { error, tools } = data;
+ const [showShareModal, setShareModal] = useState(false);
+
+ const isCollapsed = useConversationStore(messageStateSelectors.isMessageCollapsed(id));
+
+ const defaultActions = useAssistantActions({
+ data,
+ id,
+ index,
+ onOpenShareModal: () => setShareModal(true),
+ });
+
+ const hasTools = !!tools;
+
+ // Get collapse/expand action based on current state
+ const collapseAction = isCollapsed ? defaultActions.expand : defaultActions.collapse;
+
+ // Create extra actions from factory functions
+ const extraBarItems = useMemo(() => {
+ if (!actionsConfig?.extraBarActions) return [];
+ return actionsConfig.extraBarActions
+ .map((factory) => factory(id))
+ .filter((item): item is NonNullable<typeof item> => item !== null);
+ }, [actionsConfig?.extraBarActions, id]);
+
+ const extraMenuItems = useMemo(() => {
+ if (!actionsConfig?.extraMenuActions) return [];
+ return actionsConfig.extraMenuActions
+ .map((factory) => factory(id))
+ .filter((item): item is NonNullable<typeof item> => item !== null);
+ }, [actionsConfig?.extraMenuActions, id]);
+
+ // Use external config if provided, otherwise use defaults
+ // Append extra actions from factories
+ const barItems = useMemo(() => {
+ const base =
+ actionsConfig?.bar ??
+ (hasTools
+ ? [defaultActions.delAndRegenerate, defaultActions.copy]
+ : [defaultActions.edit, defaultActions.copy]);
+ return [...base, ...extraBarItems];
+ }, [
+ actionsConfig?.bar,
+ hasTools,
+ defaultActions.delAndRegenerate,
+ defaultActions.copy,
+ defaultActions.edit,
+ extraBarItems,
+ ]);
+
+ const menuItems = useMemo(() => {
+ const base = actionsConfig?.menu ?? [
+ defaultActions.edit,
+ defaultActions.copy,
+ collapseAction,
+ defaultActions.divider,
+ defaultActions.tts,
+ defaultActions.translate,
+ defaultActions.divider,
+ defaultActions.share,
+ defaultActions.divider,
+ defaultActions.regenerate,
+ defaultActions.delAndRegenerate,
+ defaultActions.del,
+ ];
+ return [...base, ...extraMenuItems];
+ }, [
+ actionsConfig?.menu,
+ defaultActions.edit,
+ defaultActions.copy,
+ collapseAction,
+ defaultActions.divider,
+ defaultActions.tts,
+ defaultActions.translate,
+ defaultActions.share,
+ defaultActions.regenerate,
+ defaultActions.delAndRegenerate,
+ defaultActions.del,
+ extraMenuItems,
+ ]);
+
+ // Strip handleClick for DOM safety
+ const items = useMemo(
+ () =>
+ barItems
+ .filter((item) => item && !('disabled' in item && item.disabled))
+ .map(stripHandleClick),
+ [barItems],
+ );
+ const menu = useMemo(() => menuItems.map(stripHandleClick), [menuItems]);
+
+ // Build actions map for click handling
+ const allActions = useMemo(
+ () => buildActionsMap([...barItems, ...menuItems]),
+ [barItems, menuItems],
+ );
+
+ const handleAction = useCallback(
+ (event: ActionIconGroupEvent) => {
+ // Handle submenu items (e.g., translate -> zh-CN)
+ if (event.keyPath && event.keyPath.length > 1) {
+ const parentKey = event.keyPath.at(-1);
+ const childKey = event.keyPath[0];
+ const parent = allActions.get(parentKey!);
+ if (parent && 'children' in parent && parent.children) {
+ const child = parent.children.find((c) => c.key === childKey);
+ child?.handleClick?.();
+ return;
+ }
+ }
+
+ // Handle regular actions
+ const action = allActions.get(event.key);
+ action?.handleClick?.();
+ },
+ [allActions],
+ );
+
+ const shareOnCancel = useCallback(() => {
+ setShareModal(false);
+ }, []);
+ if (error) return <ErrorActionsBar actions={defaultActions} onActionClick={handleAction} />;
+
+ return (
+ <>
+ <ActionIconGroup items={items} menu={{ items: menu }} onActionClick={handleAction} />
+ <ShareMessageModal message={data} onCancel={shareOnCancel} open={showShareModal} />
+ </>
+ );
+ },
+);
+
+AssistantActionsBar.displayName = 'AssistantActionsBar';
diff --git a/src/features/Conversation/Messages/Assistant/Actions/useAssistantActions.ts b/src/features/Conversation/Messages/Assistant/Actions/useAssistantActions.ts
new file mode 100644
index 00000000000..3e6ecf5c4f1
--- /dev/null
+++ b/src/features/Conversation/Messages/Assistant/Actions/useAssistantActions.ts
@@ -0,0 +1,190 @@
+import type { ActionIconGroupItemType } from '@lobehub/ui';
+import { copyToClipboard } from '@lobehub/ui';
+import { App } from 'antd';
+import { css, cx } from 'antd-style';
+import {
+ Copy,
+ Edit,
+ LanguagesIcon,
+ ListChevronsDownUp,
+ ListChevronsUpDown,
+ ListRestart,
+ Play,
+ RotateCcw,
+ Share2,
+ Trash,
+} from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { localeOptions } from '@/locales/resources';
+import { UIChatMessage } from '@/types/index';
+
+import { messageStateSelectors, useConversationStore } from '../../../store';
+
+const translateStyle = css`
+ .ant-dropdown-menu-sub {
+ overflow-y: scroll;
+ max-height: 400px;
+ }
+`;
+
+export interface ActionItem extends ActionIconGroupItemType {
+ children?: Array<{ handleClick?: () => void; key: string; label: string }>;
+ handleClick?: () => void | Promise<void>;
+}
+
+export interface AssistantActions {
+ collapse: ActionItem;
+ copy: ActionItem;
+ del: ActionItem;
+ delAndRegenerate: ActionItem;
+ divider: { type: 'divider' };
+ edit: ActionItem;
+ expand: ActionItem;
+ regenerate: ActionItem;
+ share: ActionItem;
+ translate: ActionItem;
+ tts: ActionItem;
+}
+
+interface UseAssistantActionsParams {
+ data: UIChatMessage;
+ id: string;
+ index: number;
+ onOpenShareModal?: () => void;
+}
+
+export const useAssistantActions = ({
+ id,
+ data,
+ onOpenShareModal,
+}: UseAssistantActionsParams): AssistantActions => {
+ const { t } = useTranslation(['common', 'chat']);
+ const { message } = App.useApp();
+
+ // Get state from ConversationStore
+ const isCollapsed = useConversationStore(messageStateSelectors.isMessageCollapsed(id));
+ const isRegenerating = useConversationStore(messageStateSelectors.isMessageRegenerating(id));
+
+ // Get actions from ConversationStore
+ const [
+ toggleMessageEditing,
+ toggleMessageCollapsed,
+ deleteMessage,
+ regenerateAssistantMessage,
+ translateMessage,
+ ttsMessage,
+ delAndRegenerateMessage,
+ ] = useConversationStore((s) => [
+ s.toggleMessageEditing,
+ s.toggleMessageCollapsed,
+ s.deleteMessage,
+ s.regenerateAssistantMessage,
+ s.translateMessage,
+ s.ttsMessage,
+ s.delAndRegenerateMessage,
+ ]);
+
+ return useMemo<AssistantActions>(
+ () => ({
+ collapse: {
+ handleClick: () => toggleMessageCollapsed(id),
+ icon: ListChevronsDownUp,
+ key: 'collapse',
+ label: t('messageAction.collapse', { ns: 'chat' }),
+ },
+ copy: {
+ handleClick: async () => {
+ await copyToClipboard(data.content);
+ message.success(t('copySuccess'));
+ },
+ icon: Copy,
+ key: 'copy',
+ label: t('copy'),
+ },
+ del: {
+ danger: true,
+ handleClick: () => deleteMessage(id),
+ icon: Trash,
+ key: 'del',
+ label: t('delete'),
+ },
+ delAndRegenerate: {
+ disabled: isRegenerating,
+ handleClick: () => delAndRegenerateMessage(id),
+ icon: ListRestart,
+ key: 'delAndRegenerate',
+ label: t('messageAction.delAndRegenerate', { ns: 'chat' }),
+ },
+ divider: {
+ type: 'divider',
+ },
+ edit: {
+ handleClick: () => {
+ toggleMessageEditing(id, true);
+ },
+ icon: Edit,
+ key: 'edit',
+ label: t('edit'),
+ },
+ expand: {
+ handleClick: () => toggleMessageCollapsed(id),
+ icon: ListChevronsUpDown,
+ key: 'expand',
+ label: t('messageAction.expand', { ns: 'chat' }),
+ },
+ regenerate: {
+ disabled: isRegenerating,
+ handleClick: () => {
+ regenerateAssistantMessage(id);
+ if (data.error) deleteMessage(id);
+ },
+ icon: RotateCcw,
+ key: 'regenerate',
+ label: t('regenerate'),
+ spin: isRegenerating || undefined,
+ },
+ share: {
+ handleClick: onOpenShareModal,
+ icon: Share2,
+ key: 'share',
+ label: t('share'),
+ },
+ translate: {
+ children: localeOptions.map((i) => ({
+ handleClick: () => translateMessage(id, i.value),
+ key: i.value,
+ label: t(`lang.${i.value}`),
+ })),
+ icon: LanguagesIcon,
+ key: 'translate',
+ label: t('translate.action', { ns: 'chat' }),
+ popupClassName: cx(translateStyle),
+ },
+ tts: {
+ handleClick: () => ttsMessage(id),
+ icon: Play,
+ key: 'tts',
+ label: t('tts.action', { ns: 'chat' }),
+ },
+ }),
+ [
+ t,
+ id,
+ data.content,
+ data.error,
+ isRegenerating,
+ isCollapsed,
+ toggleMessageEditing,
+ deleteMessage,
+ regenerateAssistantMessage,
+ translateMessage,
+ ttsMessage,
+ delAndRegenerateMessage,
+ toggleMessageCollapsed,
+ onOpenShareModal,
+ message,
+ ],
+ );
+};
diff --git a/src/features/ChatList/Messages/Assistant/Extra/index.tsx b/src/features/Conversation/Messages/Assistant/Extra/index.tsx
similarity index 73%
rename from src/features/ChatList/Messages/Assistant/Extra/index.tsx
rename to src/features/Conversation/Messages/Assistant/Extra/index.tsx
index 28dbbf55866..8b178693429 100644
--- a/src/features/ChatList/Messages/Assistant/Extra/index.tsx
+++ b/src/features/Conversation/Messages/Assistant/Extra/index.tsx
@@ -3,13 +3,11 @@ import { ModelPerformance, ModelUsage } from '@lobechat/types';
import { memo } from 'react';
import { Flexbox } from 'react-layout-kit';
-import { useChatStore } from '@/store/chat';
-import { messageStateSelectors } from '@/store/chat/selectors';
-
-import ExtraContainer from '../../../components/Extras/ExtraContainer';
-import TTS from '../../../components/Extras/TTS';
-import Translate from '../../../components/Extras/Translate';
-import Usage from '../../../components/Extras/Usage';
+import { messageStateSelectors, useConversationStore } from '../../../store';
+import ExtraContainer from '../../components/Extras/ExtraContainer';
+import TTS from '../../components/Extras/TTS';
+import Translate from '../../components/Extras/Translate';
+import Usage from '../../components/Extras/Usage';
interface AssistantMessageExtraProps {
content: string;
@@ -24,7 +22,7 @@ interface AssistantMessageExtraProps {
export const AssistantMessageExtra = memo<AssistantMessageExtraProps>(
({ extra, id, content, performance, usage, tools, provider, model }) => {
- const loading = useChatStore(messageStateSelectors.isMessageGenerating(id));
+ const loading = useConversationStore(messageStateSelectors.isMessageGenerating(id));
return (
<Flexbox gap={8} style={{ marginTop: !!tools?.length ? 8 : 4 }}>
diff --git a/src/features/Conversation/Messages/Assistant/components/MessageContent.tsx b/src/features/Conversation/Messages/Assistant/components/MessageContent.tsx
new file mode 100644
index 00000000000..25c827ddabc
--- /dev/null
+++ b/src/features/Conversation/Messages/Assistant/components/MessageContent.tsx
@@ -0,0 +1,67 @@
+import { LOADING_FLAT } from '@lobechat/const';
+import { UIChatMessage } from '@lobechat/types';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { messageStateSelectors, useConversationStore } from '../../../store';
+import { CollapsedMessage } from '../../AssistantGroup/components/CollapsedMessage';
+import DisplayContent from '../../components/DisplayContent';
+import FileChunks from '../../components/FileChunks';
+import ImageFileListViewer from '../../components/ImageFileListViewer';
+import IntentUnderstanding from '../../components/IntentUnderstanding';
+import Reasoning from '../../components/Reasoning';
+import SearchGrounding from '../../components/SearchGrounding';
+import { useMarkdown } from '../useMarkdown';
+
+const MessageContent = memo<UIChatMessage>(
+ ({ id, tools, content, chunksList, search, imageList, metadata, ...props }) => {
+ const markdownProps = useMarkdown(id);
+ // Use ConversationStore instead of ChatStore
+ const generating = useConversationStore(messageStateSelectors.isMessageGenerating(id));
+ const isCollapsed = useConversationStore(messageStateSelectors.isMessageCollapsed(id));
+ const isReasoning = useConversationStore(messageStateSelectors.isMessageInReasoning(id));
+
+ const isToolCallGenerating = generating && (content === LOADING_FLAT || !content) && !!tools;
+
+ // TODO: Need to implement isIntentUnderstanding selector in ConversationStore if needed
+ const isIntentUnderstanding = false;
+
+ const showSearch = !!search && !!search.citations?.length;
+ const showImageItems = !!imageList && imageList.length > 0;
+
+ // remove \n to avoid empty content
+ // refs: https://github.com/lobehub/lobe-chat/pull/6153
+ const showReasoning =
+ (!!props.reasoning && props.reasoning.content?.trim() !== '') ||
+ (!props.reasoning && isReasoning);
+
+ const showFileChunks = !!chunksList && chunksList.length > 0;
+
+ if (isCollapsed) return <CollapsedMessage content={content} id={id} />;
+
+ return (
+ <Flexbox gap={8} id={id}>
+ {showSearch && (
+ <SearchGrounding citations={search?.citations} searchQueries={search?.searchQueries} />
+ )}
+ {showFileChunks && <FileChunks data={chunksList} />}
+ {showReasoning && <Reasoning {...props.reasoning} id={id} />}
+ {isIntentUnderstanding ? (
+ <IntentUnderstanding />
+ ) : (
+ <DisplayContent
+ content={content}
+ hasImages={showImageItems}
+ isMultimodal={metadata?.isMultimodal}
+ isToolCallGenerating={isToolCallGenerating}
+ markdownProps={markdownProps}
+ tempDisplayContent={metadata?.tempDisplayContent}
+ />
+ )}
+ {showImageItems && <ImageFileListViewer items={imageList} />}
+ </Flexbox>
+ );
+ },
+);
+
+export default MessageContent;
diff --git a/src/features/Conversation/Messages/Assistant/index.tsx b/src/features/Conversation/Messages/Assistant/index.tsx
new file mode 100644
index 00000000000..ce9c04d7453
--- /dev/null
+++ b/src/features/Conversation/Messages/Assistant/index.tsx
@@ -0,0 +1,184 @@
+'use client';
+
+import { LOADING_FLAT } from '@lobechat/const';
+import { Tag } from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
+import { type MouseEventHandler, memo, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { MESSAGE_ACTION_BAR_PORTAL_ATTRIBUTES } from '@/const/messageActionPortal';
+import { ChatItem } from '@/features/Conversation/ChatItem';
+import { useNewScreen } from '@/features/Conversation/Messages/components/useNewScreen';
+import { useOpenChatSettings } from '@/hooks/useInterceptingRoutes';
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
+import { agentGroupSelectors, useAgentGroupStore } from '@/store/agentGroup';
+import { useGlobalStore } from '@/store/global';
+import { useSessionStore } from '@/store/session';
+import { sessionSelectors } from '@/store/session/selectors';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+import ErrorMessageExtra, { useErrorContent } from '../../Error';
+import { useAgentMeta, useDoubleClickEdit } from '../../hooks';
+import { dataSelectors, messageStateSelectors, useConversationStore } from '../../store';
+import { normalizeThinkTags, processWithArtifact } from '../../utils/markdown';
+import {
+ useSetMessageItemActionElementPortialContext,
+ useSetMessageItemActionTypeContext,
+} from '../Contexts/message-action-context';
+import MessageBranch from '../components/MessageBranch';
+import { AssistantMessageExtra } from './Extra';
+import MessageContent from './components/MessageContent';
+
+const actionBarHolder = (
+ <div {...{ [MESSAGE_ACTION_BAR_PORTAL_ATTRIBUTES.assistant]: '' }} style={{ height: '28px' }} />
+);
+interface AssistantMessageProps {
+ disableEditing?: boolean;
+ id: string;
+ index: number;
+ isLatestItem?: boolean;
+}
+
+const AssistantMessage = memo<AssistantMessageProps>(
+ ({ id, index, disableEditing, isLatestItem }) => {
+ // Get message and actionsConfig from ConversationStore
+ const item = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual)!;
+
+ const {
+ agentId,
+ branch,
+ error,
+ role,
+ content,
+ createdAt,
+ tools,
+ extra,
+ model,
+ provider,
+ targetId,
+ performance,
+ usage,
+ metadata,
+ } = item;
+
+ const avatar = useAgentMeta(agentId);
+ const { t } = useTranslation('chat');
+
+ // Get editing and generating state from ConversationStore
+ const editing = useConversationStore(messageStateSelectors.isMessageEditing(id));
+ const generating = useConversationStore(messageStateSelectors.isMessageGenerating(id));
+ const creating = useConversationStore(messageStateSelectors.isMessageCreating(id));
+ const newScreen = useNewScreen({ creating, isLatestItem });
+
+ const errorContent = useErrorContent(error);
+
+ // remove line breaks in artifact tag to make the ast transform easier
+ const message = !editing ? normalizeThinkTags(processWithArtifact(content)) : content;
+
+ const isGroupSession = useSessionStore(sessionSelectors.isCurrentSessionGroupSession);
+ const groupConfig = useAgentGroupStore(agentGroupSelectors.currentGroupConfig);
+
+ const reducted =
+ isGroupSession && targetId !== null && targetId !== 'user' && !groupConfig?.revealDM;
+
+ // Get target name for DM indicator
+ const userName = useUserStore(userProfileSelectors.nickName) || 'User';
+ const agents = useSessionStore(sessionSelectors.currentGroupAgents);
+
+ const dmIndicator = useMemo(() => {
+ if (!targetId) return undefined;
+
+ let targetName = targetId;
+ if (targetId === 'user') {
+ targetName = t('dm.you');
+ } else {
+ const targetAgent = agents?.find((agent) => agent.id === targetId);
+ targetName = targetAgent?.title || targetId;
+ }
+
+ return <Tag>{t('dm.visibleTo', { target: targetName })}</Tag>;
+ }, [targetId, userName, agents, t]);
+
+ const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
+ const [toggleSystemRole] = useGlobalStore((s) => [s.toggleSystemRole]);
+ const openChatSettings = useOpenChatSettings();
+
+ const onAvatarClick = useCallback(() => {
+ if (!isInbox) {
+ toggleSystemRole(true);
+ } else {
+ openChatSettings();
+ }
+ }, [isInbox]);
+
+ const onDoubleClick = useDoubleClickEdit({ disableEditing, error, id, role });
+ const setMessageItemActionElementPortialContext =
+ useSetMessageItemActionElementPortialContext();
+ const setMessageItemActionTypeContext = useSetMessageItemActionTypeContext();
+
+ const onMouseEnter: MouseEventHandler<HTMLDivElement> = useCallback(
+ (e) => {
+ setMessageItemActionElementPortialContext(e.currentTarget);
+ setMessageItemActionTypeContext({ id, index, type: 'assistant' });
+ },
+ [id, index, setMessageItemActionElementPortialContext, setMessageItemActionTypeContext],
+ );
+
+ return (
+ <ChatItem
+ aboveMessage={null}
+ actions={
+ <>
+ {branch && (
+ <MessageBranch
+ activeBranchIndex={branch.activeBranchIndex}
+ count={branch.count}
+ messageId={id}
+ />
+ )}
+
+ {actionBarHolder}
+ </>
+ }
+ avatar={avatar}
+ customErrorRender={(error) => <ErrorMessageExtra data={item} error={error} />}
+ editing={editing}
+ error={
+ errorContent && error && (message === LOADING_FLAT || !message) ? errorContent : undefined
+ }
+ id={id}
+ loading={generating}
+ message={reducted ? `*${t('hideForYou')}*` : message}
+ messageExtra={
+ <AssistantMessageExtra
+ content={content}
+ extra={extra}
+ id={id}
+ model={model!}
+ performance={performance! || metadata}
+ provider={provider!}
+ tools={tools}
+ usage={usage! || metadata}
+ />
+ }
+ newScreen={newScreen}
+ onAvatarClick={onAvatarClick}
+ onDoubleClick={onDoubleClick}
+ onMouseEnter={onMouseEnter}
+ placement={'left'}
+ showTitle
+ time={createdAt}
+ titleAddon={dmIndicator}
+ >
+ <MessageContent {...item} />
+ </ChatItem>
+ );
+ },
+ isEqual,
+);
+
+AssistantMessage.displayName = 'AssistantMessage';
+
+export default AssistantMessage;
diff --git a/src/features/Conversation/Messages/Assistant/useMarkdown.tsx b/src/features/Conversation/Messages/Assistant/useMarkdown.tsx
new file mode 100644
index 00000000000..fdd5048980f
--- /dev/null
+++ b/src/features/Conversation/Messages/Assistant/useMarkdown.tsx
@@ -0,0 +1,75 @@
+'use client';
+
+import { MarkdownProps } from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
+import { useMemo } from 'react';
+
+import { HtmlPreviewAction } from '@/components/HtmlPreview';
+import { useUserStore } from '@/store/user';
+import { userGeneralSettingsSelectors } from '@/store/user/selectors';
+
+import { markdownElements } from '../../Markdown/plugins';
+import { dataSelectors, messageStateSelectors, useConversationStore } from '../../store';
+
+const rehypePlugins = markdownElements.map((element) => element.rehypePlugin).filter(Boolean);
+const remarkPlugins = markdownElements.map((element) => element.remarkPlugin).filter(Boolean);
+
+const isHtmlCode = (content: string, language: string) => {
+ return (
+ language === 'html' ||
+ (language === '' && content.includes('<html>')) ||
+ (language === '' && content.includes('<!DOCTYPE html>'))
+ );
+};
+
+export const useMarkdown = (id: string): Partial<MarkdownProps> => {
+ const item = useConversationStore(dataSelectors.getDbMessageById(id), isEqual)!;
+ const { role, search } = item;
+ const { transitionMode } = useUserStore(userGeneralSettingsSelectors.config);
+ const generating = useConversationStore(messageStateSelectors.isMessageGenerating(id));
+ const animated = transitionMode === 'fadeIn' && generating;
+
+ const components = useMemo(
+ () =>
+ Object.fromEntries(
+ markdownElements.map((element) => {
+ const Component = element.Component;
+ return [element.tag, (props: any) => <Component {...props} id={id} />];
+ }),
+ ),
+ [id],
+ );
+
+ return useMemo(
+ () =>
+ ({
+ animated,
+ citations: search?.citations,
+ componentProps: {
+ highlight: {
+ actionsRender: ({ content, actionIconSize, language, originalNode }: any) => {
+ const showHtmlPreview = isHtmlCode(content, language);
+ return (
+ <>
+ {showHtmlPreview && <HtmlPreviewAction content={content} size={actionIconSize} />}
+ {originalNode}
+ </>
+ );
+ },
+ },
+ },
+ components,
+ enableCustomFootnotes: true,
+ enableStream: true,
+ rehypePlugins,
+ remarkPlugins,
+ showFootnotes:
+ search?.citations &&
+ // if the citations are all empty, we should not show the citations
+ search?.citations.length > 0 &&
+ // if the citations's url and title are all the same, we should not show the citations
+ search?.citations.every((item) => item.title !== item.url),
+ }) satisfies Partial<MarkdownProps>,
+ [animated, components, role, search],
+ );
+};
diff --git a/src/features/Conversation/Messages/AssistantGroup/Actions/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Actions/index.tsx
new file mode 100644
index 00000000000..88809863dea
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/Actions/index.tsx
@@ -0,0 +1,202 @@
+import { AssistantContentBlock, UIChatMessage } from '@lobechat/types';
+import { ActionIconGroup } from '@lobehub/ui';
+import type { ActionIconGroupEvent, ActionIconGroupItemType } from '@lobehub/ui';
+import { memo, useCallback, useMemo, useState } from 'react';
+
+import ShareMessageModal from '../../../components/ShareMessageModal';
+import { messageStateSelectors, useConversationStore } from '../../../store';
+import type {
+ MessageActionItem,
+ MessageActionItemOrDivider,
+ MessageActionsConfig,
+} from '../../../types';
+import { useGroupActions } from './useGroupActions';
+
+// Helper to strip handleClick from action items before passing to ActionIconGroup
+const stripHandleClick = (item: MessageActionItemOrDivider): ActionIconGroupItemType => {
+ if ('type' in item && item.type === 'divider') return item as unknown as ActionIconGroupItemType;
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const { handleClick, children, ...rest } = item as MessageActionItem;
+ if (children) {
+ return {
+ ...rest,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ children: children.map(({ handleClick: _, ...child }) => child),
+ } as ActionIconGroupItemType;
+ }
+ return rest as ActionIconGroupItemType;
+};
+
+// Build action items map for handleAction lookup
+const buildActionsMap = (items: MessageActionItemOrDivider[]): Map<string, MessageActionItem> => {
+ const map = new Map<string, MessageActionItem>();
+ for (const item of items) {
+ if ('key' in item && item.key) {
+ map.set(String(item.key), item as MessageActionItem);
+ // Also index children for submenu items
+ if ('children' in item && item.children) {
+ for (const child of item.children) {
+ if (child.key) {
+ map.set(`${item.key}.${child.key}`, child as unknown as MessageActionItem);
+ }
+ }
+ }
+ }
+ }
+ return map;
+};
+
+interface GroupActionsProps {
+ actionsConfig?: MessageActionsConfig;
+ contentBlock?: AssistantContentBlock;
+ contentId?: string;
+ data: UIChatMessage;
+ id: string;
+}
+
+/**
+ * Actions bar for group messages with content (has assistant message content)
+ */
+const WithContentId = memo<GroupActionsProps>(({ actionsConfig, id, data, contentBlock }) => {
+ const { tools } = data;
+ const [showShareModal, setShareModal] = useState(false);
+
+ const isCollapsed = useConversationStore(messageStateSelectors.isMessageCollapsed(id));
+
+ const defaultActions = useGroupActions({
+ contentBlock,
+ data,
+ id,
+ onOpenShareModal: () => setShareModal(true),
+ });
+
+ const hasTools = !!tools;
+
+ // Get collapse/expand action based on current state
+ const collapseAction = isCollapsed ? defaultActions.expand : defaultActions.collapse;
+
+ // Use external config if provided, otherwise use defaults
+ const barItems =
+ actionsConfig?.bar ??
+ (hasTools
+ ? [defaultActions.delAndRegenerate, defaultActions.copy]
+ : [defaultActions.edit, defaultActions.copy]);
+
+ const menuItems = actionsConfig?.menu ?? [
+ defaultActions.edit,
+ defaultActions.copy,
+ collapseAction,
+ defaultActions.divider,
+ defaultActions.share,
+ defaultActions.divider,
+ defaultActions.regenerate,
+ defaultActions.del,
+ ];
+
+ // Strip handleClick for DOM safety
+ const items = useMemo(
+ () =>
+ barItems
+ .filter((item) => item && !('disabled' in item && item.disabled))
+ .map(stripHandleClick),
+ [barItems],
+ );
+ const menu = useMemo(() => menuItems.map(stripHandleClick), [menuItems]);
+
+ // Build actions map for click handling
+ const allActions = useMemo(
+ () => buildActionsMap([...barItems, ...menuItems]),
+ [barItems, menuItems],
+ );
+
+ const handleAction = useCallback(
+ (event: ActionIconGroupEvent) => {
+ // Handle submenu items (e.g., translate -> zh-CN)
+ if (event.keyPath && event.keyPath.length > 1) {
+ const parentKey = event.keyPath.at(-1);
+ const childKey = event.keyPath[0];
+ const parent = allActions.get(parentKey!);
+ if (parent && 'children' in parent && parent.children) {
+ const child = parent.children.find((c) => c.key === childKey);
+ child?.handleClick?.();
+ return;
+ }
+ }
+
+ // Handle regular actions
+ const action = allActions.get(event.key);
+ action?.handleClick?.();
+ },
+ [allActions],
+ );
+
+ return (
+ <>
+ <ActionIconGroup items={items} menu={{ items: menu }} onActionClick={handleAction} />
+ <ShareMessageModal
+ message={data}
+ onCancel={() => setShareModal(false)}
+ open={showShareModal}
+ />
+ </>
+ );
+});
+
+WithContentId.displayName = 'GroupActionsWithContentId';
+
+/**
+ * Actions bar for group messages without content (empty assistant response)
+ */
+const WithoutContentId = memo<Omit<GroupActionsProps, 'contentBlock' | 'contentId'>>(
+ ({ actionsConfig, id, data }) => {
+ const defaultActions = useGroupActions({
+ data,
+ id,
+ });
+
+ // Use external config if provided, otherwise use defaults
+ const barItems = actionsConfig?.bar ?? [
+ defaultActions.continueGeneration,
+ defaultActions.delAndRegenerate,
+ defaultActions.del,
+ ];
+
+ // Strip handleClick for DOM safety
+ const items = useMemo(() => barItems.map(stripHandleClick), [barItems]);
+
+ // Build actions map for click handling
+ const allActions = useMemo(() => buildActionsMap(barItems), [barItems]);
+
+ const handleAction = useCallback(
+ (event: ActionIconGroupEvent) => {
+ const action = allActions.get(event.key);
+ action?.handleClick?.();
+ },
+ [allActions],
+ );
+
+ return <ActionIconGroup items={items} onActionClick={handleAction} />;
+ },
+);
+
+WithoutContentId.displayName = 'GroupActionsWithoutContentId';
+
+/**
+ * Main GroupActionsBar component that renders appropriate variant
+ */
+export const GroupActionsBar = memo<GroupActionsProps>(
+ ({ actionsConfig, id, data, contentBlock, contentId }) => {
+ if (!contentId) return <WithoutContentId actionsConfig={actionsConfig} data={data} id={id} />;
+
+ return (
+ <WithContentId
+ actionsConfig={actionsConfig}
+ contentBlock={contentBlock}
+ data={data}
+ id={id}
+ />
+ );
+ },
+);
+
+GroupActionsBar.displayName = 'GroupActionsBar';
diff --git a/src/features/Conversation/Messages/AssistantGroup/Actions/useGroupActions.ts b/src/features/Conversation/Messages/AssistantGroup/Actions/useGroupActions.ts
new file mode 100644
index 00000000000..5dd9c1dc49c
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/Actions/useGroupActions.ts
@@ -0,0 +1,194 @@
+import type { ActionIconGroupItemType } from '@lobehub/ui';
+import { copyToClipboard } from '@lobehub/ui';
+import { App } from 'antd';
+import {
+ Copy,
+ Edit,
+ LanguagesIcon,
+ ListChevronsDownUp,
+ ListChevronsUpDown,
+ ListRestart,
+ RotateCcw,
+ Share2,
+ StepForward,
+ Trash,
+} from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { localeOptions } from '@/locales/resources';
+import { AssistantContentBlock, UIChatMessage } from '@/types/index';
+
+import { dataSelectors, messageStateSelectors, useConversationStore } from '../../../store';
+
+export interface ActionItem extends ActionIconGroupItemType {
+ children?: Array<{ handleClick?: () => void; key: string; label: string }>;
+ handleClick?: () => void | Promise<void>;
+}
+
+export interface GroupActions {
+ collapse: ActionItem;
+ continueGeneration: ActionItem;
+ copy: ActionItem;
+ del: ActionItem;
+ delAndRegenerate: ActionItem;
+ divider: { type: 'divider' };
+ edit: ActionItem;
+ expand: ActionItem;
+ regenerate: ActionItem;
+ share: ActionItem;
+ translate: ActionItem;
+}
+
+interface UseGroupActionsParams {
+ contentBlock?: AssistantContentBlock;
+ data: UIChatMessage;
+ id: string;
+ onOpenShareModal?: () => void;
+}
+
+export const useGroupActions = ({
+ id,
+ data,
+ contentBlock,
+ onOpenShareModal,
+}: UseGroupActionsParams): GroupActions => {
+ const { t } = useTranslation(['common', 'chat']);
+ const { message } = App.useApp();
+
+ // Get state from ConversationStore
+ const isCollapsed = useConversationStore(messageStateSelectors.isMessageCollapsed(id));
+ const isRegenerating = useConversationStore(messageStateSelectors.isMessageRegenerating(id));
+ const lastBlockId = useConversationStore(dataSelectors.findLastMessageId(id));
+ const isContinuing = useConversationStore((s) =>
+ lastBlockId ? messageStateSelectors.isMessageContinuing(lastBlockId)(s) : false,
+ );
+
+ // Get actions from ConversationStore
+ const [
+ toggleMessageEditing,
+ toggleMessageCollapsed,
+ deleteMessage,
+ regenerateAssistantMessage,
+ translateMessage,
+ delAndRegenerateMessage,
+ continueGenerationMessage,
+ ] = useConversationStore((s) => [
+ s.toggleMessageEditing,
+ s.toggleMessageCollapsed,
+ s.deleteMessage,
+ s.regenerateAssistantMessage,
+ s.translateMessage,
+ s.delAndRegenerateMessage,
+ s.continueGenerationMessage,
+ ]);
+
+ return useMemo<GroupActions>(
+ () => ({
+ collapse: {
+ handleClick: () => toggleMessageCollapsed(id),
+ icon: ListChevronsDownUp,
+ key: 'collapse',
+ label: t('messageAction.collapse', { ns: 'chat' }),
+ },
+ continueGeneration: {
+ disabled: isContinuing,
+ handleClick: () => {
+ if (!lastBlockId) return;
+ continueGenerationMessage(lastBlockId, id);
+ },
+ icon: StepForward,
+ key: 'continueGeneration',
+ label: t('messageAction.continueGeneration', { ns: 'chat' }),
+ spin: isContinuing || undefined,
+ },
+ copy: {
+ handleClick: async () => {
+ if (!contentBlock) return;
+ await copyToClipboard(contentBlock.content);
+ message.success(t('copySuccess'));
+ },
+ icon: Copy,
+ key: 'copy',
+ label: t('copy'),
+ },
+ del: {
+ danger: true,
+ handleClick: () => deleteMessage(id),
+ icon: Trash,
+ key: 'del',
+ label: t('delete'),
+ },
+ delAndRegenerate: {
+ disabled: isRegenerating,
+ handleClick: () => delAndRegenerateMessage(id),
+ icon: ListRestart,
+ key: 'delAndRegenerate',
+ label: t('messageAction.delAndRegenerate', { ns: 'chat' }),
+ },
+ divider: {
+ type: 'divider',
+ },
+ edit: {
+ handleClick: () => {
+ toggleMessageEditing(id, true);
+ },
+ icon: Edit,
+ key: 'edit',
+ label: t('edit'),
+ },
+ expand: {
+ handleClick: () => toggleMessageCollapsed(id),
+ icon: ListChevronsUpDown,
+ key: 'expand',
+ label: t('messageAction.expand', { ns: 'chat' }),
+ },
+ regenerate: {
+ disabled: isRegenerating,
+ handleClick: () => {
+ regenerateAssistantMessage(id);
+ if (data.error) deleteMessage(id);
+ },
+ icon: RotateCcw,
+ key: 'regenerate',
+ label: t('regenerate'),
+ spin: isRegenerating || undefined,
+ },
+ share: {
+ handleClick: onOpenShareModal,
+ icon: Share2,
+ key: 'share',
+ label: t('share'),
+ },
+ translate: {
+ children: localeOptions.map((i) => ({
+ handleClick: () => translateMessage(id, i.value),
+ key: i.value,
+ label: t(`lang.${i.value}`),
+ })),
+ icon: LanguagesIcon,
+ key: 'translate',
+ label: t('translate.action', { ns: 'chat' }),
+ },
+ }),
+ [
+ t,
+ id,
+ contentBlock,
+ data.error,
+ isRegenerating,
+ isContinuing,
+ isCollapsed,
+ lastBlockId,
+ toggleMessageEditing,
+ deleteMessage,
+ regenerateAssistantMessage,
+ translateMessage,
+ delAndRegenerateMessage,
+ toggleMessageCollapsed,
+ continueGenerationMessage,
+ onOpenShareModal,
+ message,
+ ],
+ );
+};
diff --git a/src/features/ChatList/Messages/Group/Tool/Inspector/BuiltinPluginTitle.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/BuiltinPluginTitle.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Group/Tool/Inspector/BuiltinPluginTitle.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/BuiltinPluginTitle.tsx
diff --git a/src/features/ChatList/Messages/Group/Tool/Inspector/Debug.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/Debug.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Group/Tool/Inspector/Debug.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/Debug.tsx
diff --git a/src/features/ChatList/Messages/Group/Tool/Inspector/PluginResult.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/PluginResult.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Group/Tool/Inspector/PluginResult.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/PluginResult.tsx
diff --git a/src/features/ChatList/Messages/Group/Tool/Inspector/PluginState.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/PluginState.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Group/Tool/Inspector/PluginState.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/PluginState.tsx
diff --git a/src/features/ChatList/Messages/Group/Tool/Inspector/Settings.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/Settings.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Group/Tool/Inspector/Settings.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/Settings.tsx
diff --git a/src/features/ChatList/Messages/Group/Tool/Inspector/StatusIndicator.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/StatusIndicator.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Group/Tool/Inspector/StatusIndicator.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/StatusIndicator.tsx
diff --git a/src/features/ChatList/Messages/Group/Tool/Inspector/ToolTitle.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Group/Tool/Inspector/ToolTitle.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx
diff --git a/src/features/ChatList/Messages/Group/Tool/Inspector/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/index.tsx
similarity index 77%
rename from src/features/ChatList/Messages/Group/Tool/Inspector/index.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/index.tsx
index b52bf1e44d2..bf4a1fe76bd 100644
--- a/src/features/ChatList/Messages/Group/Tool/Inspector/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/index.tsx
@@ -1,4 +1,4 @@
-import { ToolIntervention } from '@lobechat/types';
+import { RenderDisplayControl, ToolIntervention } from '@lobechat/types';
import { ActionIcon } from '@lobehub/ui';
import { createStyles } from 'antd-style';
import { LayoutPanelTop, LogsIcon, LucideBug, LucideBugOff, Trash2 } from 'lucide-react';
@@ -7,10 +7,9 @@ import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
import { LOADING_FLAT } from '@/const/message';
-import { useChatStore } from '@/store/chat';
-import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';
import { shinyTextStylish } from '@/styles/loading';
+import { dataSelectors, useConversationStore } from '../../../../store';
import Debug from './Debug';
import Settings from './Settings';
import StatusIndicator from './StatusIndicator';
@@ -72,6 +71,13 @@ interface InspectorProps {
identifier: string;
index: number;
intervention?: ToolIntervention;
+ /**
+ * Control the render display behavior
+ * - 'collapsed': Default collapsed, user can expand (default)
+ * - 'expand': Default expanded, user can collapse
+ * - 'alwaysExpand': Always expanded, user cannot collapse
+ */
+ renderDisplayControl?: RenderDisplayControl;
result?: { content: string | null; error?: any; state?: any };
setShowPluginRender: (show: boolean) => void;
setShowRender: (show: boolean) => void;
@@ -98,14 +104,15 @@ const Inspectors = memo<InspectorProps>(
type,
intervention,
toolMessageId,
+ renderDisplayControl = 'collapsed',
}) => {
const { t } = useTranslation('plugin');
const { styles } = useStyles();
const [showDebug, setShowDebug] = useState(false);
- const [isHovered, setIsHovered] = useState(false);
- const [deleteAssistantMessage, toggleInspectExpanded] = useChatStore((s) => [
+ // Use ConversationStore for actions
+ const [deleteAssistantMessage, toggleInspectExpanded] = useConversationStore((s) => [
s.deleteAssistantMessage,
s.toggleInspectExpanded,
]);
@@ -120,22 +127,27 @@ const Inspectors = memo<InspectorProps>(
const isAbort = intervention?.status === 'aborted';
const isTitleLoading = !hasResult && !isPending;
- const isPersistentExpanded = useChatStore((s) => {
- if (!toolMessageId) return undefined;
+ // Calculate default expanded state based on renderDisplayControl
+ const defaultExpanded = renderDisplayControl !== 'collapsed';
- const message = dbMessageSelectors.getDbMessageById(toolMessageId)(s);
- return message?.metadata?.inspectExpanded;
+ // Use ConversationStore for reading message data
+ const isExpanded = useConversationStore((s) => {
+ if (!toolMessageId) return defaultExpanded;
+
+ const message = dataSelectors.getDbMessageById(toolMessageId)(s);
+ // Use metadata value if set, otherwise use default from renderDisplayControl
+ return message?.metadata?.inspectExpanded ?? defaultExpanded;
});
- // Compute actual render state based on persistent expanded or hovered
- const shouldShowRender = isPersistentExpanded || isHovered;
+ // Check if user can toggle the expand state
+ const canToggle = renderDisplayControl !== 'alwaysExpand';
// Sync with parent state
useEffect(() => {
- setShowRender(shouldShowRender);
- }, [shouldShowRender, setShowRender]);
+ setShowRender(isExpanded);
+ }, [isExpanded, setShowRender]);
- const showCustomPluginRender = shouldShowRender && !isPending && !isReject && !isAbort;
+ const showCustomPluginRender = isExpanded && !isPending && !isReject && !isAbort;
return (
<Flexbox className={styles.container} gap={4}>
<Flexbox align={'center'} distribution={'space-between'} gap={8} horizontal>
@@ -145,25 +157,16 @@ const Inspectors = memo<InspectorProps>(
gap={8}
horizontal
onClick={() => {
- if (toolMessageId) toggleInspectExpanded(toolMessageId);
- }}
- onMouseEnter={() => {
- if (!isPersistentExpanded) {
- setIsHovered(true);
- }
- }}
- onMouseLeave={() => {
- if (!isPersistentExpanded) {
- setIsHovered(false);
- }
+ if (canToggle && toolMessageId) toggleInspectExpanded(toolMessageId);
}}
paddingInline={4}
+ style={{ cursor: canToggle ? 'pointer' : 'default' }}
>
<ToolTitle
apiName={apiName}
identifier={identifier}
index={index}
- isExpanded={isPersistentExpanded}
+ isExpanded={isExpanded}
isLoading={isTitleLoading}
messageId={assistantMessageId}
toolCallId={id}
diff --git a/src/features/ChatList/Messages/Group/Tool/Render/AbortResponse.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/AbortResponse.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Group/Tool/Render/AbortResponse.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Render/AbortResponse.tsx
diff --git a/src/features/ChatList/Messages/Group/Tool/Render/Arguments/ObjectEntity.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/Arguments/ObjectEntity.tsx
similarity index 89%
rename from src/features/ChatList/Messages/Group/Tool/Render/Arguments/ObjectEntity.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Render/Arguments/ObjectEntity.tsx
index a7f9e954119..37406123e94 100644
--- a/src/features/ChatList/Messages/Group/Tool/Render/Arguments/ObjectEntity.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/Arguments/ObjectEntity.tsx
@@ -1,7 +1,6 @@
import { createStyles } from 'antd-style';
import { memo } from 'react';
-import { useIsMobile } from '@/hooks/useIsMobile';
import { shinyTextStylish } from '@/styles/loading';
import ValueCell from './ValueCell';
@@ -55,15 +54,11 @@ interface ObjectEntityProps {
const ObjectEntity = memo<ObjectEntityProps>(({ hasMinWidth, shine, value, objectKey }) => {
const { styles, cx } = useStyles();
- const isMobile = useIsMobile();
const formatedValue = formatValue(value);
return (
<div className={styles.row}>
- <span
- className={styles.key}
- style={{ minWidth: hasMinWidth ? (isMobile ? 60 : 140) : undefined }}
- >
+ <span className={styles.key} style={{ minWidth: hasMinWidth ? 140 : undefined }}>
{objectKey}
</span>
<span className={styles.colon}>:</span>
diff --git a/src/features/ChatList/Messages/Group/Tool/Render/Arguments/ValueCell.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/Arguments/ValueCell.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Group/Tool/Render/Arguments/ValueCell.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Render/Arguments/ValueCell.tsx
diff --git a/src/features/ChatList/Messages/Group/Tool/Render/Arguments/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/Arguments/index.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Group/Tool/Render/Arguments/index.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Render/Arguments/index.tsx
diff --git a/src/features/ChatList/Messages/Group/Tool/Render/CustomRender.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/CustomRender.tsx
similarity index 82%
rename from src/features/ChatList/Messages/Group/Tool/Render/CustomRender.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Render/CustomRender.tsx
index 2cbdb14de4d..47e421b2f43 100644
--- a/src/features/ChatList/Messages/Group/Tool/Render/CustomRender.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/CustomRender.tsx
@@ -9,12 +9,19 @@ import Arguments from './Arguments';
interface CustomRenderProps {
content: string;
- id: string;
+ /**
+ * The real message ID (tool message ID)
+ */
+ messageId?: string;
plugin?: ChatPluginPayload;
pluginState?: any;
requestArgs?: string;
setShowPluginRender: (value: boolean) => void;
showPluginRender: boolean;
+ /**
+ * The tool call ID from the assistant message
+ */
+ toolCallId: string;
}
/**
@@ -26,7 +33,16 @@ interface CustomRenderProps {
* - Results are directly available in content prop
*/
const CustomRender = memo<CustomRenderProps>(
- ({ id, content, pluginState, plugin, requestArgs, showPluginRender, setShowPluginRender }) => {
+ ({
+ toolCallId,
+ messageId,
+ content,
+ pluginState,
+ plugin,
+ requestArgs,
+ showPluginRender,
+ setShowPluginRender,
+ }) => {
// Determine if plugin UI should be shown based on plugin type
useEffect(() => {
if (!plugin?.type) return;
@@ -50,15 +66,16 @@ const CustomRender = memo<CustomRenderProps>(
// Show plugin custom UI if applicable
if (showPluginRender) {
return (
- <Flexbox gap={12} id={id} width={'100%'}>
+ <Flexbox gap={12} id={toolCallId} width={'100%'}>
<PluginRender
arguments={plugin?.arguments}
content={content}
- id={id}
identifier={plugin?.identifier}
loading={false}
+ messageId={messageId}
payload={plugin}
pluginState={pluginState}
+ toolCallId={toolCallId}
type={plugin?.type}
/>
</Flexbox>
@@ -67,7 +84,7 @@ const CustomRender = memo<CustomRenderProps>(
// Default render: show arguments and result
return (
- <Flexbox gap={12} id={id} width={'100%'}>
+ <Flexbox gap={12} id={toolCallId} width={'100%'}>
<Arguments arguments={requestArgs} />
{content && (
<Highlighter
diff --git a/src/features/ChatList/Messages/Group/Tool/Render/ErrorResponse.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/ErrorResponse.tsx
similarity index 97%
rename from src/features/ChatList/Messages/Group/Tool/Render/ErrorResponse.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Render/ErrorResponse.tsx
index f56cf6be657..207f1126ff5 100644
--- a/src/features/ChatList/Messages/Group/Tool/Render/ErrorResponse.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/ErrorResponse.tsx
@@ -28,7 +28,7 @@ const ErrorResponse = memo<ErrorResponseProps>(({ id, type, body, message, plugi
}
message={t(`response.${type}` as any)}
showIcon
- type={'error'}
+ type={'secondary'}
/>
);
});
diff --git a/src/features/ChatList/Messages/Group/Tool/Render/Intervention/ApprovalActions.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/Intervention/ApprovalActions.tsx
similarity index 74%
rename from src/features/ChatList/Messages/Group/Tool/Render/Intervention/ApprovalActions.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Render/Intervention/ApprovalActions.tsx
index 70d272d9611..3fd8b7d63d6 100644
--- a/src/features/ChatList/Messages/Group/Tool/Render/Intervention/ApprovalActions.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/Intervention/ApprovalActions.tsx
@@ -5,10 +5,10 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
-import { useChatStore } from '@/store/chat';
import { useUserStore } from '@/store/user';
-import { useGroupMessage } from '../../../GroupContext';
+import { useConversationStore } from '../../../../../store';
+import { useGroupMessage } from '../../../components/GroupContext';
import { ApprovalMode } from './index';
interface ApprovalActionsProps {
@@ -16,31 +16,41 @@ interface ApprovalActionsProps {
approvalMode: ApprovalMode;
identifier: string;
messageId: string;
+ /**
+ * Callback to be called before approve action
+ * Used to flush pending saves (e.g., debounced saves) from intervention components
+ */
+ onBeforeApprove?: () => void | Promise<void>;
toolCallId: string;
}
const ApprovalActions = memo<ApprovalActionsProps>(
- ({ approvalMode, messageId, identifier, apiName }) => {
+ ({ approvalMode, messageId, identifier, apiName, onBeforeApprove }) => {
const { t } = useTranslation(['chat', 'common']);
const [rejectReason, setRejectReason] = useState('');
const [rejectPopoverOpen, setRejectPopoverOpen] = useState(false);
const [rejectLoading, setRejectLoading] = useState(false);
const [approveLoading, setApproveLoading] = useState(false);
+ // Disable actions while message is still being created (temp ID)
+ const isMessageCreating = messageId.startsWith('tmp_');
+
const { assistantGroupId } = useGroupMessage();
- const [approveToolIntervention, rejectToolIntervention, rejectAndContinueToolIntervention] =
- useChatStore((s) => [
- s.approveToolCalling,
- s.rejectToolCalling,
- s.rejectAndContinueToolCalling,
- ]);
+ const [approveToolCall, rejectToolCall, rejectAndContinueToolCall] = useConversationStore(
+ (s) => [s.approveToolCall, s.rejectToolCall, s.rejectAndContinueToolCall],
+ );
const addToolToAllowList = useUserStore((s) => s.addToolToAllowList);
const handleApprove = async (remember?: boolean) => {
setApproveLoading(true);
try {
+ // 0. Flush pending saves from intervention components (e.g., debounced saves)
+ if (onBeforeApprove) {
+ await onBeforeApprove();
+ }
+
// 1. Update intervention status
- await approveToolIntervention(messageId, assistantGroupId);
+ await approveToolCall(messageId, assistantGroupId);
// 2. If remembered, add to allowList
if (remember) {
@@ -54,7 +64,7 @@ const ApprovalActions = memo<ApprovalActionsProps>(
const handleReject = async (reason?: string) => {
setRejectLoading(true);
- await rejectToolIntervention(messageId, reason);
+ await rejectToolCall(messageId, reason);
setRejectLoading(false);
setRejectPopoverOpen(false);
setRejectReason('');
@@ -62,7 +72,7 @@ const ApprovalActions = memo<ApprovalActionsProps>(
const handleRejectAndContinue = async (reason?: string) => {
setRejectLoading(true);
- await rejectAndContinueToolIntervention(messageId, reason);
+ await rejectAndContinueToolCall(messageId, reason);
setRejectLoading(false);
setRejectPopoverOpen(false);
setRejectReason('');
@@ -116,7 +126,12 @@ const ApprovalActions = memo<ApprovalActionsProps>(
placement="bottomRight"
trigger="click"
>
- <Button color={'default'} size="small" variant={'filled'}>
+ <Button
+ color={'default'}
+ disabled={isMessageCreating}
+ size="small"
+ variant={'filled'}
+ >
{t('tool.intervention.reject')}
</Button>
</Popover>
@@ -124,6 +139,7 @@ const ApprovalActions = memo<ApprovalActionsProps>(
{approvalMode === 'allow-list' ? (
<Space.Compact>
<Button
+ disabled={isMessageCreating}
loading={approveLoading}
onClick={() => handleApprove(true)}
size="small"
@@ -135,7 +151,7 @@ const ApprovalActions = memo<ApprovalActionsProps>(
menu={{
items: [
{
- disabled: approveLoading,
+ disabled: approveLoading || isMessageCreating,
key: 'once',
label: t('tool.intervention.approveOnce'),
onClick: () => handleApprove(false),
@@ -143,11 +159,17 @@ const ApprovalActions = memo<ApprovalActionsProps>(
],
}}
>
- <Button disabled={approveLoading} icon={ChevronDown} size="small" type="primary" />
+ <Button
+ disabled={approveLoading || isMessageCreating}
+ icon={ChevronDown}
+ size="small"
+ type="primary"
+ />
</Dropdown>
</Space.Compact>
) : (
<Button
+ disabled={isMessageCreating}
loading={approveLoading}
onClick={() => handleApprove()}
size="small"
diff --git a/src/features/ChatList/Messages/Group/Tool/Render/Intervention/Fallback.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/Intervention/Fallback.tsx
similarity index 89%
rename from src/features/ChatList/Messages/Group/Tool/Render/Intervention/Fallback.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Render/Intervention/Fallback.tsx
index 34201e41ed4..ef6d1f4ab67 100644
--- a/src/features/ChatList/Messages/Group/Tool/Render/Intervention/Fallback.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/Intervention/Fallback.tsx
@@ -5,10 +5,10 @@ import { Suspense, memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
-import { useChatStore } from '@/store/chat';
import { useUserStore } from '@/store/user';
import { toolInterventionSelectors } from '@/store/user/selectors';
+import { useConversationStore } from '../../../../../store';
import Arguments from '../Arguments';
import ApprovalActions from './ApprovalActions';
import KeyValueEditor from './KeyValueEditor';
@@ -27,9 +27,7 @@ const FallbackIntervention = memo<FallbackInterventionProps>(
const { t } = useTranslation('chat');
const approvalMode = useUserStore(toolInterventionSelectors.approvalMode);
const [isEditing, setIsEditing] = useState(false);
- const [optimisticUpdatePluginArguments] = useChatStore((s) => [
- s.optimisticUpdatePluginArguments,
- ]);
+ const updatePluginArguments = useConversationStore((s) => s.updatePluginArguments);
const handleCancel = useCallback(() => {
setIsEditing(false);
@@ -37,20 +35,20 @@ const FallbackIntervention = memo<FallbackInterventionProps>(
const handleFinish = useCallback(
async (editedObject: Record<string, any>) => {
- if (!id) return;
+ if (!toolCallId) return;
try {
const newArgsString = JSON.stringify(editedObject, null, 2);
if (newArgsString !== requestArgs) {
- await optimisticUpdatePluginArguments(id, editedObject, true);
+ await updatePluginArguments(toolCallId, editedObject, true);
}
setIsEditing(false);
} catch (error) {
console.error('Error stringifying arguments:', error);
}
},
- [requestArgs, id],
+ [requestArgs, toolCallId, updatePluginArguments],
);
if (isEditing)
diff --git a/src/features/ChatList/Messages/Group/Tool/Render/Intervention/KeyValueEditor.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/Intervention/KeyValueEditor.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Group/Tool/Render/Intervention/KeyValueEditor.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Render/Intervention/KeyValueEditor.tsx
diff --git a/src/features/ChatList/Messages/Group/Tool/Render/Intervention/ModeSelector.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/Intervention/ModeSelector.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Group/Tool/Render/Intervention/ModeSelector.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Render/Intervention/ModeSelector.tsx
diff --git a/src/features/ChatList/Messages/Group/Tool/Render/Intervention/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/Intervention/index.tsx
similarity index 59%
rename from src/features/ChatList/Messages/Group/Tool/Render/Intervention/index.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Render/Intervention/index.tsx
index ebae66fd6d0..3323389fe0a 100644
--- a/src/features/ChatList/Messages/Group/Tool/Render/Intervention/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/Intervention/index.tsx
@@ -1,12 +1,12 @@
import { safeParseJSON } from '@lobechat/utils';
-import { Suspense, memo, useCallback, useState } from 'react';
+import { Suspense, memo, useCallback, useRef, useState } from 'react';
import { Flexbox } from 'react-layout-kit';
-import { useChatStore } from '@/store/chat';
import { useUserStore } from '@/store/user';
import { toolInterventionSelectors } from '@/store/user/selectors';
import { getBuiltinIntervention } from '@/tools/interventions';
+import { useConversationStore } from '../../../../../store';
import Arguments from '../Arguments';
import ApprovalActions from './ApprovalActions';
import Fallback from './Fallback';
@@ -27,9 +27,29 @@ const Intervention = memo<InterventionProps>(
({ requestArgs, id, identifier, apiName, toolCallId }) => {
const approvalMode = useUserStore(toolInterventionSelectors.approvalMode);
const [isEditing, setIsEditing] = useState(false);
- const [optimisticUpdatePluginArguments] = useChatStore((s) => [
- s.optimisticUpdatePluginArguments,
- ]);
+ const updatePluginArguments = useConversationStore((s) => s.updatePluginArguments);
+
+ // Store beforeApprove callbacks from intervention components (support multiple registrations)
+ // Use Map with id as key for reliable cleanup
+ const beforeApproveCallbacksRef = useRef<Map<string, () => void | Promise<void>>>(new Map());
+
+ // Register a callback to be called before approval
+ const registerBeforeApprove = useCallback(
+ (callbackId: string, callback: () => void | Promise<void>) => {
+ beforeApproveCallbacksRef.current.set(callbackId, callback);
+ // Return cleanup function to unregister
+ return () => {
+ beforeApproveCallbacksRef.current.delete(callbackId);
+ };
+ },
+ [],
+ );
+
+ // Handler to be called before approve action - calls all registered callbacks
+ const handleBeforeApprove = useCallback(async () => {
+ const callbacks = Array.from(beforeApproveCallbacksRef.current.values());
+ await Promise.all(callbacks.map((cb) => cb()));
+ }, []);
const handleCancel = useCallback(() => {
setIsEditing(false);
@@ -37,21 +57,31 @@ const Intervention = memo<InterventionProps>(
const handleFinish = useCallback(
async (editedObject: Record<string, any>) => {
- if (!id) return;
+ if (!toolCallId) return;
try {
const newArgsString = JSON.stringify(editedObject, null, 2);
if (newArgsString !== requestArgs) {
- await optimisticUpdatePluginArguments(id, editedObject, true);
+ await updatePluginArguments(toolCallId, editedObject, true);
}
setIsEditing(false);
} catch (error) {
console.error('Error stringifying arguments:', error);
}
},
- [requestArgs, id],
+ [requestArgs, toolCallId, updatePluginArguments],
);
+
+ // Callback for builtin intervention components to update arguments
+ const handleArgsChange = useCallback(
+ async (newArgs: unknown) => {
+ if (!toolCallId) return;
+ await updatePluginArguments(toolCallId, newArgs, true);
+ },
+ [toolCallId, updatePluginArguments],
+ );
+
const BuiltinToolInterventionRender = getBuiltinIntervention(identifier, apiName);
if (BuiltinToolInterventionRender) {
@@ -73,6 +103,8 @@ const Intervention = memo<InterventionProps>(
args={safeParseJSON(requestArgs || '')}
identifier={identifier}
messageId={id}
+ onArgsChange={handleArgsChange}
+ registerBeforeApprove={registerBeforeApprove}
/>
<Flexbox horizontal justify={'space-between'}>
<ModeSelector />
@@ -81,6 +113,7 @@ const Intervention = memo<InterventionProps>(
approvalMode={approvalMode}
identifier={identifier}
messageId={id}
+ onBeforeApprove={handleBeforeApprove}
toolCallId={toolCallId}
/>
</Flexbox>
diff --git a/src/features/ChatList/Messages/Group/Tool/Render/LoadingPlaceholder/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/LoadingPlaceholder/index.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Group/Tool/Render/LoadingPlaceholder/index.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Render/LoadingPlaceholder/index.tsx
diff --git a/src/features/ChatList/Messages/Group/Tool/Render/PluginSettings.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/PluginSettings.tsx
similarity index 91%
rename from src/features/ChatList/Messages/Group/Tool/Render/PluginSettings.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Render/PluginSettings.tsx
index c5ac34abb35..c8958e6595a 100644
--- a/src/features/ChatList/Messages/Group/Tool/Render/PluginSettings.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/PluginSettings.tsx
@@ -8,11 +8,11 @@ import { useTranslation } from 'react-i18next';
import { Center, Flexbox } from 'react-layout-kit';
import PluginSettingsConfig from '@/features/PluginSettings';
-import { useChatStore } from '@/store/chat';
import { pluginHelpers, useToolStore } from '@/store/tool';
import { pluginSelectors } from '@/store/tool/selectors';
import { ErrorActionContainer, useStyles } from '../../../../Error/style';
+import { useConversationStore } from '../../../../store';
interface PluginSettingsProps {
id: string;
@@ -23,7 +23,10 @@ const PluginSettings = memo<PluginSettingsProps>(({ id, plugin }) => {
const { styles } = useStyles();
const { t } = useTranslation('error');
const theme = useTheme();
- const [resend, deleteMessage] = useChatStore((s) => [s.delAndRegenerateMessage, s.deleteMessage]);
+ const [resend, deleteMessage] = useConversationStore((s) => [
+ s.delAndRegenerateMessage,
+ s.deleteMessage,
+ ]);
const pluginIdentifier = plugin?.identifier as string;
const pluginMeta = useToolStore(pluginSelectors.getPluginMetaById(pluginIdentifier), isEqual);
const manifest = useToolStore(pluginSelectors.getToolManifestById(pluginIdentifier), isEqual);
@@ -36,6 +39,7 @@ const PluginSettings = memo<PluginSettingsProps>(({ id, plugin }) => {
avatar={pluginHelpers.getPluginAvatar(pluginMeta) || '⚙️'}
background={theme.colorFillContent}
gap={12}
+ shape={'square'}
size={80}
/>
<Flexbox style={{ fontSize: 20 }}>
diff --git a/src/features/ChatList/Messages/Group/Tool/Render/RejectedResponse.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/RejectedResponse.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Group/Tool/Render/RejectedResponse.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Render/RejectedResponse.tsx
diff --git a/src/features/ChatList/Messages/Group/Tool/Render/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/index.tsx
similarity index 97%
rename from src/features/ChatList/Messages/Group/Tool/Render/index.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Render/index.tsx
index a5603df657b..7a1c616daa8 100644
--- a/src/features/ChatList/Messages/Group/Tool/Render/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/index.tsx
@@ -109,7 +109,7 @@ const Render = memo<RenderProps>(
<Flexbox gap={8}>
<CustomRender
content={result.content || ''}
- id={toolCallId}
+ messageId={toolMessageId}
plugin={
type
? ({
@@ -124,6 +124,7 @@ const Render = memo<RenderProps>(
requestArgs={requestArgs}
setShowPluginRender={setShowPluginRender}
showPluginRender={showPluginRender}
+ toolCallId={toolCallId}
/>
<div>
<ModeSelector />
diff --git a/src/features/ChatList/Messages/Group/Tool/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx
similarity index 89%
rename from src/features/ChatList/Messages/Group/Tool/index.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx
index 24fdb3942c4..57e80958246 100644
--- a/src/features/ChatList/Messages/Group/Tool/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx
@@ -3,6 +3,8 @@ import { CSSProperties, memo, useEffect, useState } from 'react';
import { Flexbox } from 'react-layout-kit';
import AnimatedCollapsed from '@/components/AnimatedCollapsed';
+import { useToolStore } from '@/store/tool';
+import { toolSelectors } from '@/store/tool/selectors';
import Inspectors from './Inspector';
import Render from './Render';
@@ -44,8 +46,12 @@ const Tool = memo<GroupToolProps>(
type,
toolMessageId,
}) => {
- // Default to false since group messages are all completed
+ // Get renderDisplayControl from manifest
+ const renderDisplayControl = useToolStore(
+ toolSelectors.getRenderDisplayControl(identifier, apiName),
+ );
+ // Default to false since group messages are all completed
const [showToolContent, setShowToolDetail] = useState(false);
const [showCustomPluginUI, setShowCustomPluginUI] = useState(false);
@@ -65,6 +71,7 @@ const Tool = memo<GroupToolProps>(
identifier={identifier}
index={index}
intervention={intervention}
+ renderDisplayControl={renderDisplayControl}
result={result}
setShowPluginRender={setShowCustomPluginUI}
setShowRender={setShowToolDetail}
diff --git a/src/features/ChatList/Messages/Group/Tools.tsx b/src/features/Conversation/Messages/AssistantGroup/Tools.tsx
similarity index 63%
rename from src/features/ChatList/Messages/Group/Tools.tsx
rename to src/features/Conversation/Messages/AssistantGroup/Tools.tsx
index ecc0ae55ee9..1c69c0cf75f 100644
--- a/src/features/ChatList/Messages/Group/Tools.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tools.tsx
@@ -1,33 +1,25 @@
import { ChatToolPayloadWithResult } from '@lobechat/types';
-import { createStyles } from 'antd-style';
+import { Block } from '@lobehub/ui';
import { memo } from 'react';
-import { Flexbox } from 'react-layout-kit';
import Tool from './Tool';
-const useStyles = createStyles(({ css, token }) => {
- return {
- toolsContainer: css`
- padding-block: 6px;
- padding-inline: 12px;
- border: 1px solid ${token.colorBorderSecondary};
- border-radius: 8px;
- `,
- };
-});
-
interface ToolsRendererProps {
messageId: string;
tools: ChatToolPayloadWithResult[];
}
export const Tools = memo<ToolsRendererProps>(({ messageId, tools }) => {
- const { styles, cx } = useStyles();
-
if (!tools || tools.length === 0) return null;
return (
- <Flexbox className={cx(styles.toolsContainer, 'tool-blocks')} gap={8}>
+ <Block
+ className={'tool-blocks'}
+ gap={8}
+ paddingBlock={6}
+ paddingInline={12}
+ variant={'outlined'}
+ >
{tools.map((tool, index) => (
<Tool
apiName={tool.apiName}
@@ -43,6 +35,6 @@ export const Tools = memo<ToolsRendererProps>(({ messageId, tools }) => {
type={tool.type}
/>
))}
- </Flexbox>
+ </Block>
);
});
diff --git a/src/features/ChatList/Messages/Group/CollapsedMessage.tsx b/src/features/Conversation/Messages/AssistantGroup/components/CollapsedMessage.tsx
similarity index 67%
rename from src/features/ChatList/Messages/Group/CollapsedMessage.tsx
rename to src/features/Conversation/Messages/AssistantGroup/components/CollapsedMessage.tsx
index 48036276f4d..44828ec7e7c 100644
--- a/src/features/ChatList/Messages/Group/CollapsedMessage.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/CollapsedMessage.tsx
@@ -1,9 +1,11 @@
-import { Button, Markdown, MaskShadow } from '@lobehub/ui';
+import { Button, MaskShadow } from '@lobehub/ui';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
-import { useChatStore } from '@/store/chat';
+import MarkdownMessage from '@/features/Conversation/Markdown';
+
+import { useConversationStore } from '../../../store';
interface CollapsedMessageProps {
content: string;
@@ -12,12 +14,12 @@ interface CollapsedMessageProps {
export const CollapsedMessage = memo<CollapsedMessageProps>(({ id, content }) => {
const { t } = useTranslation('chat');
- const toggleMessageCollapsed = useChatStore((s) => s.toggleMessageCollapsed);
+ const toggleMessageCollapsed = useConversationStore((s) => s.toggleMessageCollapsed);
return (
<Flexbox>
<MaskShadow>
- <Markdown variant={'chat'}>{content?.slice(0, 300)}</Markdown>
+ <MarkdownMessage variant={'chat'}>{content?.slice(0, 300)}</MarkdownMessage>
</MaskShadow>
<Flexbox padding={4}>
<Button
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx
new file mode 100644
index 00000000000..b1558fafc32
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx
@@ -0,0 +1,53 @@
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { LOADING_FLAT } from '@/const/message';
+import { useErrorContent } from '@/features/Conversation/Error';
+import { AssistantContentBlock } from '@/types/index';
+
+import ErrorContent from '../../../ChatItem/components/ErrorContent';
+import { messageStateSelectors, useConversationStore } from '../../../store';
+import ImageFileListViewer from '../../components/ImageFileListViewer';
+import Reasoning from '../../components/Reasoning';
+import { Tools } from '../Tools';
+import MessageContent from './MessageContent';
+
+const ContentBlock = memo<AssistantContentBlock>(
+ ({ id, tools, content, imageList, reasoning, error }) => {
+ const errorContent = useErrorContent(error);
+ const showImageItems = !!imageList && imageList.length > 0;
+ const isReasoning = useConversationStore(messageStateSelectors.isMessageInReasoning(id));
+ const hasTools = tools && tools.length > 0;
+ const showReasoning =
+ (!!reasoning && reasoning.content?.trim() !== '') || (!reasoning && isReasoning);
+
+ if (error && (content === LOADING_FLAT || !content))
+ return (
+ <ErrorContent
+ error={
+ errorContent && error && (content === LOADING_FLAT || !content)
+ ? errorContent
+ : undefined
+ }
+ id={id}
+ />
+ );
+
+ return (
+ <Flexbox gap={8} id={id}>
+ {showReasoning && <Reasoning {...reasoning} id={id} />}
+
+ {/* Content - markdown text */}
+ <MessageContent content={content} hasTools={hasTools} id={id} />
+
+ {/* Image files */}
+ {showImageItems && <ImageFileListViewer items={imageList} />}
+
+ {/* Tools */}
+ {hasTools && <Tools messageId={id} tools={tools} />}
+ </Flexbox>
+ );
+ },
+);
+
+export default ContentBlock;
diff --git a/src/features/ChatList/Messages/Group/EditState.tsx b/src/features/Conversation/Messages/AssistantGroup/components/EditState.tsx
similarity index 88%
rename from src/features/ChatList/Messages/Group/EditState.tsx
rename to src/features/Conversation/Messages/AssistantGroup/components/EditState.tsx
index 76aa4539def..b161d57af29 100644
--- a/src/features/ChatList/Messages/Group/EditState.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/EditState.tsx
@@ -3,7 +3,7 @@ import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
-import { useChatStore } from '@/store/chat';
+import { useConversationStore } from '../../../store';
export interface EditStateProps {
content: string;
@@ -22,7 +22,7 @@ const EditState = memo<EditStateProps>(({ id, content }) => {
[],
);
- const [toggleMessageEditing, updateMessageContent] = useChatStore((s) => [
+ const [toggleMessageEditing, updateMessageContent] = useConversationStore((s) => [
s.toggleMessageEditing,
s.modifyMessageContent,
]);
diff --git a/src/features/ChatList/Messages/Group/Group.tsx b/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx
similarity index 79%
rename from src/features/ChatList/Messages/Group/Group.tsx
rename to src/features/Conversation/Messages/AssistantGroup/components/Group.tsx
index bc8c5b11d1a..3cb6b46d779 100644
--- a/src/features/ChatList/Messages/Group/Group.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx
@@ -1,12 +1,11 @@
-import { AssistantContentBlock } from '@lobechat/types';
import { createStyles } from 'antd-style';
import isEqual from 'fast-deep-equal';
import { memo, useMemo } from 'react';
import { Flexbox } from 'react-layout-kit';
-import { useChatStore } from '@/store/chat';
-import { messageStateSelectors } from '@/store/chat/slices/message/selectors';
+import { AssistantContentBlock } from '@/types/index';
+import { messageStateSelectors, useConversationStore } from '../../../store';
import { CollapsedMessage } from './CollapsedMessage';
import { GroupMessageContext } from './GroupContext';
import GroupItem from './GroupItem';
@@ -33,7 +32,7 @@ interface GroupChildrenProps {
const Group = memo<GroupChildrenProps>(
({ blocks, contentId, disableEditing, messageIndex, id, content }) => {
const { styles } = useStyles();
- const [isCollapsed] = useChatStore((s) => [messageStateSelectors.isMessageCollapsed(id)(s)]);
+ const isCollapsed = useConversationStore(messageStateSelectors.isMessageCollapsed(id));
const contextValue = useMemo(() => ({ assistantGroupId: id }), [id]);
if (isCollapsed) {
@@ -48,14 +47,13 @@ const Group = memo<GroupChildrenProps>(
return (
<GroupMessageContext value={contextValue}>
<Flexbox className={styles.container} gap={8}>
- {blocks.map((item, index) => {
+ {blocks.map((item) => {
return (
<GroupItem
{...item}
contentId={contentId}
disableEditing={disableEditing}
- index={index}
- key={`${id}_${index}`}
+ key={id + '.' + item.id}
messageIndex={messageIndex}
/>
);
diff --git a/src/features/ChatList/Messages/Group/GroupContext.ts b/src/features/Conversation/Messages/AssistantGroup/components/GroupContext.ts
similarity index 100%
rename from src/features/ChatList/Messages/Group/GroupContext.ts
rename to src/features/Conversation/Messages/AssistantGroup/components/GroupContext.ts
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/GroupItem.tsx b/src/features/Conversation/Messages/AssistantGroup/components/GroupItem.tsx
new file mode 100644
index 00000000000..58e24891022
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/components/GroupItem.tsx
@@ -0,0 +1,33 @@
+import isEqual from 'fast-deep-equal';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { AssistantContentBlock } from '@/types/index';
+
+import { useConversationStore } from '../../../store';
+import ContentBlock from './ContentBlock';
+
+interface GroupItemProps extends AssistantContentBlock {
+ contentId?: string;
+ disableEditing?: boolean;
+ messageIndex: number;
+}
+
+const GroupItem = memo<GroupItemProps>(({ contentId, disableEditing, error, ...item }) => {
+ const toggleMessageEditing = useConversationStore((s) => s.toggleMessageEditing);
+
+ return item.id === contentId ? (
+ <Flexbox
+ onDoubleClick={(e) => {
+ if (disableEditing || error || !e.altKey) return;
+ toggleMessageEditing(item.id, true);
+ }}
+ >
+ <ContentBlock {...item} error={error} />
+ </Flexbox>
+ ) : (
+ <ContentBlock {...item} error={error} />
+ );
+}, isEqual);
+
+export default GroupItem;
diff --git a/src/features/ChatList/Messages/Group/MessageContent.tsx b/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsx
similarity index 68%
rename from src/features/ChatList/Messages/Group/MessageContent.tsx
rename to src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsx
index fe1a1a72c56..600e4566a8b 100644
--- a/src/features/ChatList/Messages/Group/MessageContent.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsx
@@ -1,11 +1,12 @@
-import { Markdown, MarkdownProps } from '@lobehub/ui';
import { createStyles } from 'antd-style';
import { memo } from 'react';
import BubblesLoading from '@/components/BubblesLoading';
import { LOADING_FLAT } from '@/const/message';
+import MarkdownMessage from '@/features/Conversation/Markdown';
-import { normalizeThinkTags, processWithArtifact } from '../../utils/markdown';
+import { normalizeThinkTags, processWithArtifact } from '../../../utils/markdown';
+import { useMarkdown } from '../useMarkdown';
const useStyles = createStyles(({ css, token }) => {
return {
@@ -17,12 +18,12 @@ const useStyles = createStyles(({ css, token }) => {
interface ContentBlockProps {
content: string;
hasTools?: boolean;
- markdownProps?: Omit<MarkdownProps, 'className' | 'style' | 'children'>;
+ id: string;
}
-const MessageContent = memo<ContentBlockProps>(({ content, hasTools, markdownProps }) => {
+const MessageContent = memo<ContentBlockProps>(({ content, hasTools, id }) => {
const message = normalizeThinkTags(processWithArtifact(content));
-
+ const markdownProps = useMarkdown(id);
const { styles, cx } = useStyles();
if (!content && !hasTools) return <BubblesLoading />;
@@ -35,9 +36,9 @@ const MessageContent = memo<ContentBlockProps>(({ content, hasTools, markdownPro
return (
content && (
- <Markdown {...markdownProps} className={cx(hasTools && styles.pWithTool)} variant={'chat'}>
+ <MarkdownMessage {...markdownProps} className={cx(hasTools && styles.pWithTool)}>
{message}
- </Markdown>
+ </MarkdownMessage>
)
);
});
diff --git a/src/features/Conversation/Messages/AssistantGroup/index.tsx b/src/features/Conversation/Messages/AssistantGroup/index.tsx
new file mode 100644
index 00000000000..17933ad043b
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/index.tsx
@@ -0,0 +1,145 @@
+'use client';
+
+import isEqual from 'fast-deep-equal';
+import { type MouseEventHandler, memo, useCallback, useMemo } from 'react';
+
+import { MESSAGE_ACTION_BAR_PORTAL_ATTRIBUTES } from '@/const/messageActionPortal';
+import { ChatItem } from '@/features/Conversation/ChatItem';
+import { useNewScreen } from '@/features/Conversation/Messages/components/useNewScreen';
+import { useOpenChatSettings } from '@/hooks/useInterceptingRoutes';
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
+import { useGlobalStore } from '@/store/global';
+
+import { useAgentMeta } from '../../hooks';
+import { dataSelectors, messageStateSelectors, useConversationStore } from '../../store';
+import {
+ useSetMessageItemActionElementPortialContext,
+ useSetMessageItemActionTypeContext,
+} from '../Contexts/message-action-context';
+import FileListViewer from '../User/components/FileListViewer';
+import Usage from '../components/Extras/Usage';
+import MessageBranch from '../components/MessageBranch';
+import EditState from './components/EditState';
+import Group from './components/Group';
+
+const actionBarHolder = (
+ <div
+ {...{ [MESSAGE_ACTION_BAR_PORTAL_ATTRIBUTES.assistantGroup]: '' }}
+ style={{ height: '28px' }}
+ />
+);
+interface GroupMessageProps {
+ disableEditing?: boolean;
+ id: string;
+ index: number;
+ isLatestItem?: boolean;
+}
+
+const GroupMessage = memo<GroupMessageProps>(({ id, index, disableEditing, isLatestItem }) => {
+ // Get message and actionsConfig from ConversationStore
+ const item = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual)!;
+
+ const { agentId, usage, createdAt, children, performance, model, provider, branch } = item;
+ const avatar = useAgentMeta(agentId);
+
+ // Collect fileList from all children blocks
+ const aggregatedFileList = useMemo(() => {
+ if (!children || children.length === 0) return [];
+ return children.flatMap((child) => child.fileList || []);
+ }, [children]);
+
+ const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
+ const [toggleSystemRole] = useGlobalStore((s) => [s.toggleSystemRole]);
+ const openChatSettings = useOpenChatSettings();
+
+ // Get the latest message block from the group that doesn't contain tools
+ const lastAssistantMsg = useConversationStore(
+ dataSelectors.getGroupLatestMessageWithoutTools(id),
+ );
+
+ const contentId = lastAssistantMsg?.id;
+
+ // Get editing state from ConversationStore
+ const editing = useConversationStore(messageStateSelectors.isMessageEditing(contentId || ''));
+ const creating = useConversationStore(messageStateSelectors.isMessageCreating(id));
+ const newScreen = useNewScreen({ creating, isLatestItem });
+
+ const setMessageItemActionElementPortialContext = useSetMessageItemActionElementPortialContext();
+ const setMessageItemActionTypeContext = useSetMessageItemActionTypeContext();
+
+ const onMouseEnter: MouseEventHandler<HTMLDivElement> = useCallback(
+ (e) => {
+ if (disableEditing) return;
+ setMessageItemActionElementPortialContext(e.currentTarget);
+ setMessageItemActionTypeContext({ id, index, type: 'assistantGroup' });
+ },
+ [
+ disableEditing,
+ id,
+ index,
+ setMessageItemActionElementPortialContext,
+ setMessageItemActionTypeContext,
+ ],
+ );
+
+ const onAvatarClick = useCallback(() => {
+ if (!isInbox) {
+ toggleSystemRole(true);
+ } else {
+ openChatSettings();
+ }
+ }, [isInbox]);
+
+ // If editing, show edit state
+ if (editing && contentId) {
+ return <EditState content={lastAssistantMsg?.content} id={contentId} />;
+ }
+
+ return (
+ <ChatItem
+ actions={
+ !disableEditing && (
+ <>
+ {branch && (
+ <MessageBranch
+ activeBranchIndex={branch.activeBranchIndex}
+ count={branch.count}
+ messageId={id}
+ />
+ )}
+ {actionBarHolder}
+ </>
+ )
+ }
+ avatar={avatar}
+ newScreen={newScreen}
+ onAvatarClick={onAvatarClick}
+ onMouseEnter={onMouseEnter}
+ placement={'left'}
+ showTitle
+ time={createdAt}
+ >
+ {children && children.length > 0 && (
+ <Group
+ blocks={children}
+ content={lastAssistantMsg?.content}
+ contentId={contentId}
+ disableEditing={disableEditing}
+ id={id}
+ messageIndex={index}
+ />
+ )}
+ {aggregatedFileList.length > 0 && (
+ <div style={{ marginTop: 8 }}>
+ <FileListViewer items={aggregatedFileList} />
+ </div>
+ )}
+ {model && (
+ <Usage model={model} performance={performance} provider={provider!} usage={usage} />
+ )}
+ </ChatItem>
+ );
+}, isEqual);
+
+export default GroupMessage;
diff --git a/src/features/Conversation/Messages/AssistantGroup/useMarkdown.tsx b/src/features/Conversation/Messages/AssistantGroup/useMarkdown.tsx
new file mode 100644
index 00000000000..0280a4a08e1
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/useMarkdown.tsx
@@ -0,0 +1,46 @@
+import { MarkdownProps } from '@lobehub/ui';
+import { useMemo } from 'react';
+
+import { useUserStore } from '@/store/user';
+import { userGeneralSettingsSelectors } from '@/store/user/selectors';
+
+import { MarkdownElement, markdownElements } from '../../Markdown/plugins';
+import { messageStateSelectors, useConversationStore } from '../../store';
+
+const rehypePlugins = markdownElements
+ .map((element: MarkdownElement) => element.rehypePlugin)
+ .filter(Boolean);
+const remarkPlugins = markdownElements
+ .map((element: MarkdownElement) => element.remarkPlugin)
+ .filter(Boolean);
+
+export const useMarkdown = (id: string): Partial<MarkdownProps> => {
+ const { transitionMode } = useUserStore(userGeneralSettingsSelectors.config);
+ const generating = useConversationStore(messageStateSelectors.isMessageGenerating(id));
+
+ const animated = transitionMode === 'fadeIn' && generating;
+
+ const components = useMemo(
+ () =>
+ Object.fromEntries(
+ markdownElements.map((element: MarkdownElement) => {
+ const Component = element.Component;
+
+ return [element.tag, (props: any) => <Component {...props} id={id} />];
+ }),
+ ),
+ [id],
+ );
+ return useMemo(
+ () =>
+ ({
+ animated,
+ components,
+ enableCustomFootnotes: true,
+ enableStream: true,
+ rehypePlugins,
+ remarkPlugins,
+ }) satisfies Partial<MarkdownProps>,
+ [animated, components],
+ );
+};
diff --git a/src/features/Conversation/Messages/Contexts/MessageActionProvider.tsx b/src/features/Conversation/Messages/Contexts/MessageActionProvider.tsx
new file mode 100644
index 00000000000..ecd955befa6
--- /dev/null
+++ b/src/features/Conversation/Messages/Contexts/MessageActionProvider.tsx
@@ -0,0 +1,186 @@
+import { isEqual } from 'es-toolkit/compat';
+import { FC, type PropsWithChildren, memo, useEffect, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+
+import { MESSAGE_ACTION_BAR_PORTAL_SELECTORS } from '@/const/messageActionPortal';
+
+import { dataSelectors, useConversationStore } from '../../store';
+import { AssistantActionsBar } from '../Assistant/Actions';
+import { GroupActionsBar } from '../AssistantGroup/Actions';
+import { UserActionsBar } from '../User/Actions';
+import {
+ MessageActionType,
+ MessageItemActionElementPortialContext,
+ MessageItemActionTypeContext,
+ SetMessageItemActionElementPortialContext,
+ SetMessageItemActionTypeContext,
+ useMessageItemActionElementPortialContext,
+ useMessageItemActionTypeContext,
+} from './message-action-context';
+
+interface SingletonPortalProps {
+ id: string;
+ index: number;
+}
+
+const AssistantActionsRenderer: FC<SingletonPortalProps> = ({ id, index }) => {
+ const actionsConfig = useConversationStore((s) => s.actionsBar?.assistant);
+ const item = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual);
+
+ if (!item) return null;
+
+ return <AssistantActionsBar actionsConfig={actionsConfig} data={item} id={id} index={index} />;
+};
+
+const UserActionsRenderer: FC<SingletonPortalProps> = ({ id }) => {
+ const actionsConfig = useConversationStore((s) => s.actionsBar?.user);
+ const item = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual);
+
+ if (!item) return null;
+
+ return <UserActionsBar actionsConfig={actionsConfig} data={item} id={id} />;
+};
+
+const AssistantGroupActionsRenderer: FC<SingletonPortalProps> = ({ id }) => {
+ const actionsConfig = useConversationStore(
+ (s) => s.actionsBar?.assistantGroup ?? s.actionsBar?.assistant,
+ );
+ const item = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual);
+ const lastAssistantMsg = useConversationStore(
+ dataSelectors.getGroupLatestMessageWithoutTools(id),
+ );
+ const contentId = lastAssistantMsg?.id;
+
+ if (!item) return null;
+
+ return (
+ <GroupActionsBar
+ actionsConfig={actionsConfig}
+ contentBlock={lastAssistantMsg}
+ contentId={contentId}
+ data={item}
+ id={id}
+ />
+ );
+};
+
+const SingletonMessageActionsBar = memo(() => {
+ const portalElement = useMessageItemActionElementPortialContext();
+ const actionType = useMessageItemActionTypeContext();
+
+ const hostRef = useRef<HTMLDivElement | null>(null);
+ if (!hostRef.current && typeof document !== 'undefined') {
+ hostRef.current = document.createElement('div');
+ hostRef.current.dataset.singletonMessageActionBarHost = 'true';
+ }
+
+ // Keep the React tree mounted in a stable host element, and only move the host via DOM.
+ useEffect(() => {
+ const hostEl = hostRef.current;
+ if (!hostEl || typeof document === 'undefined') return;
+
+ // By default, keep it hidden but mounted.
+ let placeholderEl: HTMLDivElement | null = null;
+
+ if (portalElement && actionType) {
+ switch (actionType.type) {
+ case 'assistant': {
+ placeholderEl = portalElement.querySelector<HTMLDivElement>(
+ MESSAGE_ACTION_BAR_PORTAL_SELECTORS.assistant,
+ );
+ break;
+ }
+ case 'user': {
+ placeholderEl = portalElement.querySelector<HTMLDivElement>(
+ MESSAGE_ACTION_BAR_PORTAL_SELECTORS.user,
+ );
+ break;
+ }
+ case 'assistantGroup': {
+ placeholderEl = portalElement.querySelector<HTMLDivElement>(
+ MESSAGE_ACTION_BAR_PORTAL_SELECTORS.assistantGroup,
+ );
+ break;
+ }
+ }
+ }
+
+ if (placeholderEl) {
+ if (hostEl.parentElement !== placeholderEl) placeholderEl.append(hostEl);
+ hostEl.style.display = '';
+ return;
+ }
+
+ // No valid placeholder: attach to body to keep DOM owned, but hidden.
+ if (document.body && hostEl.parentElement !== document.body) document.body.append(hostEl);
+ hostEl.style.display = 'none';
+ }, [portalElement, actionType?.id, actionType?.index, actionType?.type]);
+
+ useEffect(() => {
+ const hostEl = hostRef.current;
+ if (!hostEl) return;
+
+ return () => {
+ hostEl.remove();
+ };
+ }, []);
+
+ const hostEl = hostRef.current;
+ if (!hostEl || !actionType) return null;
+
+ switch (actionType.type) {
+ case 'assistant': {
+ return createPortal(
+ <AssistantActionsRenderer id={actionType.id} index={actionType.index} />,
+ hostEl,
+ );
+ }
+ case 'user': {
+ return createPortal(
+ <UserActionsRenderer id={actionType.id} index={actionType.index} />,
+ hostEl,
+ );
+ }
+ case 'assistantGroup': {
+ return createPortal(
+ <AssistantGroupActionsRenderer id={actionType.id} index={actionType.index} />,
+ hostEl,
+ );
+ }
+ }
+
+ return null;
+});
+
+interface MessageActionProviderProps extends PropsWithChildren {
+ /**
+ * Whether to mount the singleton message actions portal renderer.
+ *
+ * NOTE: This renderer currently depends on `useConversationStore`, so it should only
+ * be enabled in Conversation message lists.
+ */
+ withSingletonActionsBar?: boolean;
+}
+
+export const MessageActionProvider: FC<MessageActionProviderProps> = ({
+ children,
+ withSingletonActionsBar,
+}) => {
+ const [messageItemActionElementPortialContext, setMessageItemActionElementPortialContext] =
+ useState<HTMLDivElement | null>(null);
+ const [messageItemActionTypeContext, setMessageItemActionTypeContext] =
+ useState<MessageActionType | null>(null);
+
+ return (
+ <MessageItemActionElementPortialContext value={messageItemActionElementPortialContext}>
+ <SetMessageItemActionElementPortialContext value={setMessageItemActionElementPortialContext}>
+ <SetMessageItemActionTypeContext value={setMessageItemActionTypeContext}>
+ <MessageItemActionTypeContext value={messageItemActionTypeContext}>
+ {withSingletonActionsBar && <SingletonMessageActionsBar />}
+ {children}
+ </MessageItemActionTypeContext>
+ </SetMessageItemActionTypeContext>
+ </SetMessageItemActionElementPortialContext>
+ </MessageItemActionElementPortialContext>
+ );
+};
diff --git a/src/features/Conversation/Messages/Contexts/message-action-context.ts b/src/features/Conversation/Messages/Contexts/message-action-context.ts
new file mode 100644
index 00000000000..a61730cbb7e
--- /dev/null
+++ b/src/features/Conversation/Messages/Contexts/message-action-context.ts
@@ -0,0 +1,50 @@
+import { type Dispatch, type SetStateAction, createContext, useContext } from 'react';
+
+export const MessageItemActionElementPortialContext = createContext<HTMLDivElement | null>(null);
+
+export const SetMessageItemActionElementPortialContext = createContext<
+ Dispatch<SetStateAction<HTMLDivElement | null>>
+>(() => {});
+
+export const useMessageItemActionElementPortialContext = () => {
+ return useContext(MessageItemActionElementPortialContext);
+};
+
+export const useSetMessageItemActionElementPortialContext = () => {
+ return useContext(SetMessageItemActionElementPortialContext);
+};
+
+type AssistantMessageActionType = {
+ id: string;
+
+ index: number;
+ type: 'assistant';
+};
+type UserMessageActionType = {
+ id: string;
+ index: number;
+ type: 'user';
+};
+type AssistantGroupMessageActionType = {
+ id: string;
+ index: number;
+ type: 'assistantGroup';
+};
+export type MessageActionType =
+ | AssistantMessageActionType
+ | UserMessageActionType
+ | AssistantGroupMessageActionType;
+
+export const MessageItemActionTypeContext = createContext<MessageActionType | null>(null);
+
+export const SetMessageItemActionTypeContext = createContext<
+ Dispatch<SetStateAction<MessageActionType | null>>
+>(() => {});
+
+export const useMessageItemActionTypeContext = () => {
+ return useContext(MessageItemActionTypeContext);
+};
+
+export const useSetMessageItemActionTypeContext = () => {
+ return useContext(SetMessageItemActionTypeContext);
+};
diff --git a/src/features/Conversation/Messages/Task/Actions/Error.tsx b/src/features/Conversation/Messages/Task/Actions/Error.tsx
new file mode 100644
index 00000000000..cbba06fdb95
--- /dev/null
+++ b/src/features/Conversation/Messages/Task/Actions/Error.tsx
@@ -0,0 +1,26 @@
+import { ActionIconGroup } from '@lobehub/ui';
+import type { ActionIconGroupEvent } from '@lobehub/ui';
+import { memo } from 'react';
+
+import type { AssistantActions } from './useAssistantActions';
+
+interface ErrorActionsBarProps {
+ actions: AssistantActions;
+ onActionClick: (event: ActionIconGroupEvent) => void;
+}
+
+export const ErrorActionsBar = memo<ErrorActionsBarProps>(({ actions, onActionClick }) => {
+ const { regenerate, copy, edit, del, divider } = actions;
+
+ return (
+ <ActionIconGroup
+ items={[regenerate, del]}
+ menu={{
+ items: [edit, copy, divider, del],
+ }}
+ onActionClick={onActionClick}
+ />
+ );
+});
+
+ErrorActionsBar.displayName = 'ErrorActionsBar';
diff --git a/src/features/Conversation/Messages/Task/Actions/index.tsx b/src/features/Conversation/Messages/Task/Actions/index.tsx
new file mode 100644
index 00000000000..1bcee27b68f
--- /dev/null
+++ b/src/features/Conversation/Messages/Task/Actions/index.tsx
@@ -0,0 +1,175 @@
+import { UIChatMessage } from '@lobechat/types';
+import { ActionIconGroup } from '@lobehub/ui';
+import type { ActionIconGroupEvent, ActionIconGroupItemType } from '@lobehub/ui';
+import { memo, useCallback, useMemo, useState } from 'react';
+
+import ShareMessageModal from '../../../components/ShareMessageModal';
+import type {
+ MessageActionItem,
+ MessageActionItemOrDivider,
+ MessageActionsConfig,
+} from '../../../types';
+import { ErrorActionsBar } from './Error';
+import { useAssistantActions } from './useAssistantActions';
+
+// Helper to strip handleClick from action items before passing to ActionIconGroup
+const stripHandleClick = (item: MessageActionItemOrDivider): ActionIconGroupItemType => {
+ if ('type' in item && item.type === 'divider') return item as unknown as ActionIconGroupItemType;
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const { handleClick, children, ...rest } = item as MessageActionItem;
+ if (children) {
+ return {
+ ...rest,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ children: children.map(({ handleClick: _, ...child }) => child),
+ } as ActionIconGroupItemType;
+ }
+ return rest as ActionIconGroupItemType;
+};
+
+// Build action items map for handleAction lookup
+const buildActionsMap = (items: MessageActionItemOrDivider[]): Map<string, MessageActionItem> => {
+ const map = new Map<string, MessageActionItem>();
+ for (const item of items) {
+ if ('key' in item && item.key) {
+ map.set(String(item.key), item as MessageActionItem);
+ // Also index children for submenu items
+ if ('children' in item && item.children) {
+ for (const child of item.children) {
+ if (child.key) {
+ map.set(`${item.key}.${child.key}`, child as unknown as MessageActionItem);
+ }
+ }
+ }
+ }
+ }
+ return map;
+};
+
+interface AssistantActionsBarProps {
+ actionsConfig?: MessageActionsConfig;
+ data: UIChatMessage;
+ id: string;
+ index: number;
+}
+
+export const AssistantActionsBar = memo<AssistantActionsBarProps>(
+ ({ actionsConfig, id, data, index }) => {
+ const { error, tools } = data;
+ const [showShareModal, setShareModal] = useState(false);
+
+ const defaultActions = useAssistantActions({
+ data,
+ id,
+ index,
+ onOpenShareModal: () => setShareModal(true),
+ });
+
+ const hasTools = !!tools;
+
+ // Get collapse/expand action based on current state
+ const collapseAction = defaultActions.collapse;
+
+ // Create extra actions from factory functions
+ const extraBarItems = useMemo(() => {
+ if (!actionsConfig?.extraBarActions) return [];
+ return actionsConfig.extraBarActions
+ .map((factory) => factory(id))
+ .filter((item): item is NonNullable<typeof item> => item !== null);
+ }, [actionsConfig?.extraBarActions, id]);
+
+ const extraMenuItems = useMemo(() => {
+ if (!actionsConfig?.extraMenuActions) return [];
+ return actionsConfig.extraMenuActions
+ .map((factory) => factory(id))
+ .filter((item): item is NonNullable<typeof item> => item !== null);
+ }, [actionsConfig?.extraMenuActions, id]);
+
+ // Use external config if provided, otherwise use defaults
+ // Append extra actions from factories
+ const barItems = useMemo(() => {
+ const base =
+ actionsConfig?.bar ??
+ (hasTools ? [defaultActions.copy] : [defaultActions.edit, defaultActions.copy]);
+ return [...base, ...extraBarItems];
+ }, [actionsConfig?.bar, hasTools, defaultActions.copy, defaultActions.edit, extraBarItems]);
+
+ const menuItems = useMemo(() => {
+ const base = actionsConfig?.menu ?? [
+ defaultActions.edit,
+ defaultActions.copy,
+ collapseAction,
+ defaultActions.divider,
+
+ defaultActions.divider,
+ defaultActions.share,
+ defaultActions.divider,
+ defaultActions.regenerate,
+ defaultActions.del,
+ ];
+ return [...base, ...extraMenuItems];
+ }, [
+ actionsConfig?.menu,
+ defaultActions.edit,
+ defaultActions.copy,
+ collapseAction,
+ defaultActions.divider,
+ defaultActions.share,
+ defaultActions.regenerate,
+ defaultActions.del,
+ extraMenuItems,
+ ]);
+
+ // Strip handleClick for DOM safety
+ const items = useMemo(
+ () =>
+ barItems
+ .filter((item) => item && !('disabled' in item && item.disabled))
+ .map(stripHandleClick),
+ [barItems],
+ );
+ const menu = useMemo(() => menuItems.map(stripHandleClick), [menuItems]);
+
+ // Build actions map for click handling
+ const allActions = useMemo(
+ () => buildActionsMap([...barItems, ...menuItems]),
+ [barItems, menuItems],
+ );
+
+ const handleAction = useCallback(
+ (event: ActionIconGroupEvent) => {
+ // Handle submenu items (e.g., translate -> zh-CN)
+ if (event.keyPath && event.keyPath.length > 1) {
+ const parentKey = event.keyPath.at(-1);
+ const childKey = event.keyPath[0];
+ const parent = allActions.get(parentKey!);
+ if (parent && 'children' in parent && parent.children) {
+ const child = parent.children.find((c) => c.key === childKey);
+ child?.handleClick?.();
+ return;
+ }
+ }
+
+ // Handle regular actions
+ const action = allActions.get(event.key);
+ action?.handleClick?.();
+ },
+ [allActions],
+ );
+
+ if (error) return <ErrorActionsBar actions={defaultActions} onActionClick={handleAction} />;
+
+ return (
+ <>
+ <ActionIconGroup items={items} menu={{ items: menu }} onActionClick={handleAction} />
+ <ShareMessageModal
+ message={data}
+ onCancel={() => setShareModal(false)}
+ open={showShareModal}
+ />
+ </>
+ );
+ },
+);
+
+AssistantActionsBar.displayName = 'AssistantActionsBar';
diff --git a/src/features/Conversation/Messages/Task/Actions/useAssistantActions.ts b/src/features/Conversation/Messages/Task/Actions/useAssistantActions.ts
new file mode 100644
index 00000000000..bb17b2f9b13
--- /dev/null
+++ b/src/features/Conversation/Messages/Task/Actions/useAssistantActions.ts
@@ -0,0 +1,151 @@
+import type { ActionIconGroupItemType } from '@lobehub/ui';
+import { copyToClipboard } from '@lobehub/ui';
+import { App } from 'antd';
+import {
+ Copy,
+ Edit,
+ ListChevronsDownUp,
+ ListRestart,
+ RotateCcw,
+ Share2,
+ Trash,
+} from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { UIChatMessage } from '@/types/index';
+
+import { messageStateSelectors, useConversationStore } from '../../../store';
+
+export interface ActionItem extends ActionIconGroupItemType {
+ children?: Array<{ handleClick?: () => void; key: string; label: string }>;
+ handleClick?: () => void | Promise<void>;
+}
+
+export interface AssistantActions {
+ collapse: ActionItem;
+ copy: ActionItem;
+ del: ActionItem;
+ divider: { type: 'divider' };
+ edit: ActionItem;
+ regenerate: ActionItem;
+ share: ActionItem;
+}
+
+interface UseAssistantActionsParams {
+ data: UIChatMessage;
+ id: string;
+ index: number;
+ onOpenShareModal?: () => void;
+}
+
+export const useAssistantActions = ({
+ id,
+ data,
+ onOpenShareModal,
+}: UseAssistantActionsParams): AssistantActions => {
+ const { t } = useTranslation(['common', 'chat']);
+ const { message } = App.useApp();
+
+ // Get state from ConversationStore
+ const isCollapsed = useConversationStore(messageStateSelectors.isMessageCollapsed(id));
+ const isRegenerating = useConversationStore(messageStateSelectors.isMessageRegenerating(id));
+
+ // Get actions from ConversationStore
+ const [
+ toggleMessageEditing,
+ toggleMessageCollapsed,
+ deleteMessage,
+ regenerateAssistantMessage,
+ translateMessage,
+ ttsMessage,
+ delAndRegenerateMessage,
+ ] = useConversationStore((s) => [
+ s.toggleMessageEditing,
+ s.toggleMessageCollapsed,
+ s.deleteMessage,
+ s.regenerateAssistantMessage,
+ s.translateMessage,
+ s.ttsMessage,
+ s.delAndRegenerateMessage,
+ ]);
+
+ return useMemo<AssistantActions>(
+ () => ({
+ collapse: {
+ handleClick: () => toggleMessageCollapsed(id),
+ icon: ListChevronsDownUp,
+ key: 'collapse',
+ label: t('messageAction.collapse', { ns: 'chat' }),
+ },
+ copy: {
+ handleClick: async () => {
+ await copyToClipboard(data.content);
+ message.success(t('copySuccess'));
+ },
+ icon: Copy,
+ key: 'copy',
+ label: t('copy'),
+ },
+ del: {
+ danger: true,
+ handleClick: () => deleteMessage(id),
+ icon: Trash,
+ key: 'del',
+ label: t('delete'),
+ },
+ delAndRegenerate: {
+ disabled: isRegenerating,
+ handleClick: () => delAndRegenerateMessage(id),
+ icon: ListRestart,
+ key: 'delAndRegenerate',
+ label: t('messageAction.delAndRegenerate', { ns: 'chat' }),
+ },
+ divider: {
+ type: 'divider',
+ },
+ edit: {
+ handleClick: () => {
+ toggleMessageEditing(id, true);
+ },
+ icon: Edit,
+ key: 'edit',
+ label: t('edit'),
+ },
+ regenerate: {
+ disabled: isRegenerating,
+ handleClick: () => {
+ regenerateAssistantMessage(id);
+ if (data.error) deleteMessage(id);
+ },
+ icon: RotateCcw,
+ key: 'regenerate',
+ label: t('regenerate'),
+ spin: isRegenerating || undefined,
+ },
+ share: {
+ handleClick: onOpenShareModal,
+ icon: Share2,
+ key: 'share',
+ label: t('share'),
+ },
+ }),
+ [
+ t,
+ id,
+ data.content,
+ data.error,
+ isRegenerating,
+ isCollapsed,
+ toggleMessageEditing,
+ deleteMessage,
+ regenerateAssistantMessage,
+ translateMessage,
+ ttsMessage,
+ delAndRegenerateMessage,
+ toggleMessageCollapsed,
+ onOpenShareModal,
+ message,
+ ],
+ );
+};
diff --git a/src/features/Conversation/Messages/Task/TaskDetailPanel/CompletedState.tsx b/src/features/Conversation/Messages/Task/TaskDetailPanel/CompletedState.tsx
new file mode 100644
index 00000000000..096f4fcbcef
--- /dev/null
+++ b/src/features/Conversation/Messages/Task/TaskDetailPanel/CompletedState.tsx
@@ -0,0 +1,156 @@
+'use client';
+
+import { Markdown } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { Check, Footprints, Timer, Wrench } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { TaskDetail } from '@/types/index';
+
+const useStyles = createStyles(({ css, token }) => ({
+ content: css`
+ padding-block: 12px;
+ padding-inline: 16px;
+ `,
+ footer: css`
+ padding-block: 8px;
+ padding-inline: 16px;
+ border-block-start: 1px solid ${token.colorBorderSecondary};
+ `,
+ metricItem: css`
+ display: flex;
+ gap: 4px;
+ align-items: center;
+
+ font-size: 12px;
+ color: ${token.colorTextTertiary};
+ `,
+ metricValue: css`
+ font-weight: 500;
+ color: ${token.colorTextSecondary};
+ `,
+ separator: css`
+ width: 3px;
+ height: 3px;
+ border-radius: 50%;
+ background: ${token.colorTextQuaternary};
+ `,
+ statusIcon: css`
+ display: flex;
+ flex-shrink: 0;
+ align-items: center;
+ justify-content: center;
+
+ width: 16px;
+ height: 16px;
+ border-radius: 50%;
+
+ color: ${token.colorSuccessText};
+
+ background: ${token.colorSuccessBg};
+ `,
+}));
+
+interface CompletedStateProps {
+ content?: string;
+ taskDetail: TaskDetail;
+}
+
+const CompletedState = memo<CompletedStateProps>(({ taskDetail, content }) => {
+ const { styles } = useStyles();
+ const { t } = useTranslation('chat');
+
+ const { duration, totalToolCalls, totalSteps, totalCost } = taskDetail;
+
+ // Format duration
+ const formattedDuration = useMemo(() => {
+ if (!duration) return null;
+ if (duration < 1000) return `${duration}ms`;
+ if (duration < 60_000) return `${(duration / 1000).toFixed(1)}s`;
+ const minutes = Math.floor(duration / 60_000);
+ const seconds = ((duration % 60_000) / 1000).toFixed(0);
+ return `${minutes}m ${seconds}s`;
+ }, [duration]);
+
+ // Format cost
+ const formattedCost = useMemo(() => {
+ if (!totalCost) return null;
+ if (totalCost < 0.01) return `$${totalCost.toFixed(4)}`;
+ return `$${totalCost.toFixed(2)}`;
+ }, [totalCost]);
+
+ const hasMetrics = formattedDuration || totalSteps || totalToolCalls || formattedCost;
+
+ return (
+ <Flexbox>
+ {/* Content */}
+ {content && (
+ <div className={styles.content}>
+ <Markdown>{content}</Markdown>
+ </div>
+ )}
+
+ {/* Footer with metrics */}
+ {hasMetrics && (
+ <Flexbox
+ align="center"
+ className={styles.footer}
+ gap={12}
+ horizontal
+ justify={'space-between'}
+ wrap="wrap"
+ >
+ <Flexbox align="center" gap={12} horizontal>
+ {/* Status Icon */}
+ <div className={styles.statusIcon}>
+ <Check size={10} strokeWidth={3} />
+ </div>
+ {/* Duration */}
+ {formattedDuration && (
+ <div className={styles.metricItem}>
+ <Timer size={12} />
+ <span className={styles.metricValue}>{formattedDuration}</span>
+ </div>
+ )}
+ </Flexbox>
+ <Flexbox align="center" gap={12} horizontal>
+ {/* Steps */}
+ {totalSteps !== undefined && totalSteps > 0 && (
+ <div className={styles.metricItem}>
+ <Footprints size={12} />
+ <span className={styles.metricValue}>{totalSteps}</span>
+ <span>{t('task.metrics.stepsShort', { defaultValue: '步' })}</span>
+ </div>
+ )}
+ {/* Tool Calls */}
+ {totalToolCalls !== undefined && totalToolCalls > 0 && (
+ <>
+ <div className={styles.separator} />
+ <div className={styles.metricItem}>
+ <Wrench size={12} />
+ <span className={styles.metricValue}>{totalToolCalls}</span>
+ <span>{t('task.metrics.toolCallsShort')}</span>
+ </div>
+ </>
+ )}
+ {/* Cost */}
+ {formattedCost && (
+ <>
+ <div className={styles.separator} />
+ <div className={styles.metricItem}>
+ <span className={styles.metricValue}>{formattedCost}</span>
+ </div>
+ </>
+ )}
+ </Flexbox>
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+});
+
+CompletedState.displayName = 'CompletedState';
+
+export default CompletedState;
diff --git a/src/features/Conversation/Messages/Task/TaskDetailPanel/ErrorState.tsx b/src/features/Conversation/Messages/Task/TaskDetailPanel/ErrorState.tsx
new file mode 100644
index 00000000000..e87c82e9541
--- /dev/null
+++ b/src/features/Conversation/Messages/Task/TaskDetailPanel/ErrorState.tsx
@@ -0,0 +1,168 @@
+'use client';
+
+import { createStyles } from 'antd-style';
+import { CircleX, MessageSquare, Timer, Wrench } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { TaskDetail, ThreadStatus } from '@/types/index';
+
+const useStyles = createStyles(({ css, token }) => ({
+ container: css`
+ padding-block: 12px;
+padding-inline: 16px;
+ `,
+ errorMessage: css`
+ font-size: 13px;
+ line-height: 1.6;
+ color: ${token.colorErrorText};
+ `,
+ footer: css`
+ padding-block: 8px;
+ padding-inline: 16px;
+ border-block-start: 1px solid ${token.colorBorderSecondary};
+ `,
+ metricItem: css`
+ display: flex;
+ gap: 4px;
+ align-items: center;
+
+ font-size: 12px;
+ color: ${token.colorTextTertiary};
+ `,
+ metricValue: css`
+ font-weight: 500;
+ color: ${token.colorTextSecondary};
+ `,
+ separator: css`
+ width: 3px;
+ height: 3px;
+ border-radius: 50%;
+ background: ${token.colorTextQuaternary};
+ `,
+ statusIcon: css`
+ display: flex;
+ flex-shrink: 0;
+ align-items: center;
+ justify-content: center;
+
+ width: 16px;
+ height: 16px;
+ border-radius: 50%;
+
+ color: ${token.colorErrorText};
+
+ background: ${token.colorErrorBg};
+ `,
+ statusRow: css`
+ font-size: 13px;
+ `,
+ statusText: css`
+ font-weight: 500;
+ color: ${token.colorErrorText};
+ `,
+}));
+
+interface ErrorStateProps {
+ taskDetail: TaskDetail;
+}
+
+const ErrorState = memo<ErrorStateProps>(({ taskDetail }) => {
+ const { styles } = useStyles();
+ const { t } = useTranslation('chat');
+
+ const { status, duration, totalToolCalls, totalMessages, totalCost, error } = taskDetail;
+
+ const isCancelled = status === ThreadStatus.Cancel;
+
+ // Format duration
+ const formattedDuration = useMemo(() => {
+ if (!duration) return null;
+ if (duration < 1000) return `${duration}ms`;
+ if (duration < 60_000) return `${(duration / 1000).toFixed(1)}s`;
+ const minutes = Math.floor(duration / 60_000);
+ const seconds = ((duration % 60_000) / 1000).toFixed(0);
+ return `${minutes}m ${seconds}s`;
+ }, [duration]);
+
+ // Format cost
+ const formattedCost = useMemo(() => {
+ if (!totalCost) return null;
+ if (totalCost < 0.01) return `$${totalCost.toFixed(4)}`;
+ return `$${totalCost.toFixed(2)}`;
+ }, [totalCost]);
+
+ const hasMetrics = formattedDuration || totalToolCalls || totalMessages || formattedCost;
+
+ return (
+ <Flexbox>
+ {/* Error Content */}
+ <Flexbox className={styles.container} gap={8}>
+ <Flexbox align="center" className={styles.statusRow} gap={8} horizontal>
+ <div className={styles.statusIcon}>
+ <CircleX size={10} />
+ </div>
+ <span className={styles.statusText}>
+ {isCancelled
+ ? t('task.status.cancelled', { defaultValue: 'Cancelled' })
+ : t('task.status.failed', { defaultValue: 'Failed' })}
+ </span>
+ </Flexbox>
+
+ {error && <span className={styles.errorMessage}>{error}</span>}
+ </Flexbox>
+
+ {/* Footer with metrics */}
+ {hasMetrics && (
+ <Flexbox align="center" className={styles.footer} gap={12} horizontal wrap="wrap">
+ {/* Duration */}
+ {formattedDuration && (
+ <div className={styles.metricItem}>
+ <Timer size={12} />
+ <span className={styles.metricValue}>{formattedDuration}</span>
+ </div>
+ )}
+
+ {/* Tool Calls */}
+ {totalToolCalls !== undefined && totalToolCalls > 0 && (
+ <>
+ <div className={styles.separator} />
+ <div className={styles.metricItem}>
+ <Wrench size={12} />
+ <span className={styles.metricValue}>{totalToolCalls}</span>
+ <span>{t('task.metrics.toolCallsShort', { defaultValue: 'tools' })}</span>
+ </div>
+ </>
+ )}
+
+ {/* Messages */}
+ {totalMessages !== undefined && totalMessages > 0 && (
+ <>
+ <div className={styles.separator} />
+ <div className={styles.metricItem}>
+ <MessageSquare size={12} />
+ <span className={styles.metricValue}>{totalMessages}</span>
+ <span>{t('task.metrics.messagesShort', { defaultValue: 'messages' })}</span>
+ </div>
+ </>
+ )}
+
+ {/* Cost */}
+ {formattedCost && (
+ <>
+ <div className={styles.separator} />
+ <div className={styles.metricItem}>
+ <span className={styles.metricValue}>{formattedCost}</span>
+ </div>
+ </>
+ )}
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+});
+
+ErrorState.displayName = 'ErrorState';
+
+export default ErrorState;
diff --git a/src/features/Conversation/Messages/Task/TaskDetailPanel/InitializingState.tsx b/src/features/Conversation/Messages/Task/TaskDetailPanel/InitializingState.tsx
new file mode 100644
index 00000000000..2a170ed10ae
--- /dev/null
+++ b/src/features/Conversation/Messages/Task/TaskDetailPanel/InitializingState.tsx
@@ -0,0 +1,93 @@
+'use client';
+
+import { createStyles } from 'antd-style';
+import { Loader2 } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+const useStyles = createStyles(({ css, token }) => ({
+ container: css`
+ padding-block: 12px;
+ padding-inline: 16px;
+ `,
+ progress: css`
+ position: relative;
+
+ overflow: hidden;
+
+ height: 3px;
+ border-radius: 2px;
+
+ background: ${token.colorFillSecondary};
+ `,
+ progressShimmer: css`
+ position: absolute;
+ inset-block-start: 0;
+ inset-inline-start: 0;
+
+ width: 100%;
+ height: 100%;
+
+ background: linear-gradient(90deg, transparent, ${token.colorPrimaryBgHover}, transparent);
+
+ animation: shimmer 2s infinite;
+
+ @keyframes shimmer {
+ 0% {
+ transform: translateX(-100%);
+ }
+
+ 100% {
+ transform: translateX(100%);
+ }
+ }
+ `,
+ spin: css`
+ animation: spin 1s linear infinite;
+
+ @keyframes spin {
+ from {
+ transform: rotate(0deg);
+ }
+
+ to {
+ transform: rotate(360deg);
+ }
+ }
+ `,
+ statusRow: css`
+ font-size: 13px;
+ color: ${token.colorTextSecondary};
+ `,
+ statusText: css`
+ font-weight: 500;
+ color: ${token.colorText};
+ `,
+}));
+
+const InitializingState = memo(() => {
+ const { styles } = useStyles();
+ const { t } = useTranslation('chat');
+
+ return (
+ <Flexbox className={styles.container} gap={12}>
+ {/* Status Row */}
+ <Flexbox align="center" className={styles.statusRow} gap={8} horizontal>
+ <Loader2 className={styles.spin} size={14} />
+ <span className={styles.statusText}>
+ {t('task.status.initializing', { defaultValue: 'Starting task...' })}
+ </span>
+ </Flexbox>
+
+ {/* Progress Bar (indeterminate) */}
+ <div className={styles.progress}>
+ <div className={styles.progressShimmer} />
+ </div>
+ </Flexbox>
+ );
+});
+
+InitializingState.displayName = 'InitializingState';
+
+export default InitializingState;
diff --git a/src/features/Conversation/Messages/Task/TaskDetailPanel/ProcessingState.tsx b/src/features/Conversation/Messages/Task/TaskDetailPanel/ProcessingState.tsx
new file mode 100644
index 00000000000..05062e1404d
--- /dev/null
+++ b/src/features/Conversation/Messages/Task/TaskDetailPanel/ProcessingState.tsx
@@ -0,0 +1,328 @@
+'use client';
+
+import { TaskCurrentActivity, TaskDetail } from '@lobechat/types';
+import { createStyles } from 'antd-style';
+import { Footprints, Loader2, Timer, Wrench } from 'lucide-react';
+import { memo, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { useChatStore } from '@/store/chat';
+
+const useStyles = createStyles(({ css, token }) => ({
+ activityContent: css`
+ overflow: hidden;
+
+ font-size: 12px;
+ color: ${token.colorTextSecondary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ activityRow: css`
+ display: flex;
+ gap: 8px;
+ align-items: center;
+
+ padding-block: 8px;
+ padding-inline: 16px;
+ `,
+ activityType: css`
+ display: flex;
+ flex-shrink: 0;
+ gap: 4px;
+ align-items: center;
+
+ font-size: 12px;
+ color: ${token.colorTextTertiary};
+ `,
+ footer: css`
+ padding-block: 8px;
+ padding-inline: 16px;
+ border-block-start: 1px solid ${token.colorBorderSecondary};
+ `,
+ metricItem: css`
+ display: flex;
+ gap: 4px;
+ align-items: center;
+
+ font-size: 12px;
+ color: ${token.colorTextTertiary};
+ `,
+ metricValue: css`
+ font-weight: 500;
+ color: ${token.colorTextSecondary};
+ `,
+ progress: css`
+ position: relative;
+
+ overflow: hidden;
+
+ height: 3px;
+ margin-block: 12px;
+ margin-inline: 16px;
+ border-radius: 2px;
+
+ background: ${token.colorFillSecondary};
+ `,
+ progressBar: css`
+ position: absolute;
+ inset-block-start: 0;
+ inset-inline-start: 0;
+
+ height: 100%;
+ border-radius: 2px;
+
+ background: linear-gradient(90deg, ${token.colorPrimary}, ${token.colorPrimaryHover});
+
+ transition: width 0.5s ease-out;
+ `,
+ progressShimmer: css`
+ position: absolute;
+ inset-block-start: 0;
+ inset-inline-start: 0;
+
+ width: 100%;
+ height: 100%;
+
+ background: linear-gradient(90deg, transparent, ${token.colorPrimaryBgHover}, transparent);
+
+ animation: shimmer 2s infinite;
+
+ @keyframes shimmer {
+ 0% {
+ transform: translateX(-100%);
+ }
+
+ 100% {
+ transform: translateX(100%);
+ }
+ }
+ `,
+ separator: css`
+ width: 3px;
+ height: 3px;
+ border-radius: 50%;
+ background: ${token.colorTextQuaternary};
+ `,
+ spin: css`
+ animation: spin 1s linear infinite;
+
+ @keyframes spin {
+ from {
+ transform: rotate(0deg);
+ }
+
+ to {
+ transform: rotate(360deg);
+ }
+ }
+ `,
+ statusIcon: css`
+ display: flex;
+ flex-shrink: 0;
+ align-items: center;
+ justify-content: center;
+
+ width: 16px;
+ height: 16px;
+ border-radius: 50%;
+
+ color: ${token.colorPrimaryText};
+
+ background: ${token.colorPrimaryBg};
+ `,
+}));
+
+interface ProcessingStateProps {
+ /**
+ * Message ID for updating task status in store
+ */
+ messageId: string;
+ taskDetail: TaskDetail;
+}
+
+// Progress increases by 5% every 30 seconds, max 95%
+const PROGRESS_INTERVAL = 30_000;
+const PROGRESS_INCREMENT = 5;
+const MAX_PROGRESS = 95;
+
+// Format elapsed time as mm:ss or hh:mm:ss
+const formatElapsedTime = (ms: number): string => {
+ const seconds = Math.floor(ms / 1000);
+ const minutes = Math.floor(seconds / 60);
+ const hours = Math.floor(minutes / 60);
+
+ if (hours > 0) {
+ return `${hours}:${String(minutes % 60).padStart(2, '0')}:${String(seconds % 60).padStart(2, '0')}`;
+ }
+ return `${minutes}:${String(seconds % 60).padStart(2, '0')}`;
+};
+
+// Format tool name from identifier and apiName
+const formatToolName = (activity: TaskCurrentActivity): string => {
+ if (activity.identifier && activity.apiName) {
+ return `${activity.identifier}/${activity.apiName}`;
+ }
+ return activity.identifier || activity.apiName || '';
+};
+
+const ProcessingState = memo<ProcessingStateProps>(({ taskDetail, messageId }) => {
+ const { styles } = useStyles();
+ const { t } = useTranslation('chat');
+ const [progress, setProgress] = useState(5);
+ const [elapsedTime, setElapsedTime] = useState(0);
+
+ // Get polling hook and check if there's an active operation polling
+ const [useEnablePollingTaskStatus, operations] = useChatStore((s) => [
+ s.useEnablePollingTaskStatus,
+ s.operations,
+ ]);
+
+ // Check if exec_async_task is already polling for this message
+ const hasActiveOperationPolling = Object.values(operations).some(
+ (op) =>
+ op.status === 'running' &&
+ op.type === 'execAgentRuntime' &&
+ op.context?.messageId === messageId,
+ );
+
+ // Enable polling only when no active operation is already polling
+ // This handles the case when user refreshes page and exec_async_task is no longer running
+ const { data } = useEnablePollingTaskStatus(
+ taskDetail.threadId,
+ messageId,
+ !hasActiveOperationPolling,
+ );
+
+ const currentActivity = data?.currentActivity;
+ const { totalToolCalls, totalSteps, startedAt } = taskDetail;
+
+ // Calculate initial progress and elapsed time based on startedAt
+ useEffect(() => {
+ if (startedAt) {
+ const startTime = new Date(startedAt).getTime();
+ const elapsed = Math.max(0, Date.now() - startTime);
+ const intervals = Math.floor(elapsed / PROGRESS_INTERVAL);
+ const initialProgress = Math.min(5 + intervals * PROGRESS_INCREMENT, MAX_PROGRESS);
+ setProgress(initialProgress);
+ setElapsedTime(elapsed);
+ }
+ }, [startedAt]);
+
+ // Timer for updating elapsed time every second
+ useEffect(() => {
+ if (!startedAt) return;
+
+ const timer = setInterval(() => {
+ const startTime = new Date(startedAt).getTime();
+ setElapsedTime(Math.max(0, Date.now() - startTime));
+ }, 1000);
+
+ return () => clearInterval(timer);
+ }, [startedAt]);
+
+ // Progress timer - increment every 30 seconds
+ useEffect(() => {
+ const timer = setInterval(() => {
+ setProgress((prev) => Math.min(prev + PROGRESS_INCREMENT, MAX_PROGRESS));
+ }, PROGRESS_INTERVAL);
+
+ return () => clearInterval(timer);
+ }, []);
+
+ const hasMetrics = totalSteps || totalToolCalls;
+
+ // Render current activity text
+ const renderActivityText = () => {
+ if (!currentActivity) return null;
+
+ switch (currentActivity.type) {
+ case 'tool_calling': {
+ const toolName = formatToolName(currentActivity);
+ return toolName ? t('task.activity.toolCalling', { toolName }) : t('task.activity.calling');
+ }
+ case 'tool_result': {
+ const toolName = formatToolName(currentActivity);
+ return toolName
+ ? t('task.activity.toolResult', { toolName })
+ : t('task.activity.gotResult');
+ }
+ case 'generating': {
+ return t('task.activity.generating');
+ }
+ default: {
+ return null;
+ }
+ }
+ };
+
+ return (
+ <Flexbox>
+ {/* Current Activity */}
+ {currentActivity && (
+ <div className={styles.activityRow}>
+ <div className={styles.activityType}>
+ <Loader2 className={styles.spin} size={12} />
+ <span>{renderActivityText()}</span>
+ </div>
+ {currentActivity.contentPreview && (
+ <span className={styles.activityContent}>{currentActivity.contentPreview}</span>
+ )}
+ </div>
+ )}
+
+ {/* Progress Bar */}
+ <div className={styles.progress}>
+ <div className={styles.progressBar} style={{ width: `${progress}%` }} />
+ <div className={styles.progressShimmer} />
+ </div>
+
+ {/* Footer with metrics */}
+ <Flexbox
+ align="center"
+ className={styles.footer}
+ gap={12}
+ horizontal
+ justify={'space-between'}
+ wrap="wrap"
+ >
+ <Flexbox align="center" gap={12} horizontal>
+ {/* Elapsed Time */}
+ {startedAt && (
+ <div className={styles.metricItem}>
+ <Timer size={12} />
+ <span className={styles.metricValue}>{formatElapsedTime(elapsedTime)}</span>
+ </div>
+ )}
+ </Flexbox>
+ <Flexbox align="center" gap={12} horizontal>
+ {/* Steps */}
+ {totalSteps !== undefined && totalSteps > 0 && (
+ <div className={styles.metricItem}>
+ <Footprints size={12} />
+ <span className={styles.metricValue}>{totalSteps}</span>
+ <span>{t('task.metrics.stepsShort')}</span>
+ </div>
+ )}
+ {/* Tool Calls */}
+ {totalToolCalls !== undefined && totalToolCalls > 0 && (
+ <>
+ {hasMetrics && totalSteps !== undefined && totalSteps > 0 && (
+ <div className={styles.separator} />
+ )}
+ <div className={styles.metricItem}>
+ <Wrench size={12} />
+ <span className={styles.metricValue}>{totalToolCalls}</span>
+ <span>{t('task.metrics.toolCallsShort')}</span>
+ </div>
+ </>
+ )}
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+ProcessingState.displayName = 'ProcessingState';
+
+export default ProcessingState;
diff --git a/src/features/Conversation/Messages/Task/TaskDetailPanel/StatusContent.tsx b/src/features/Conversation/Messages/Task/TaskDetailPanel/StatusContent.tsx
new file mode 100644
index 00000000000..a6258fcbb6f
--- /dev/null
+++ b/src/features/Conversation/Messages/Task/TaskDetailPanel/StatusContent.tsx
@@ -0,0 +1,54 @@
+'use client';
+
+import { memo } from 'react';
+
+import { TaskDetail, ThreadStatus } from '@/types/index';
+
+import CompletedState from './CompletedState';
+import ErrorState from './ErrorState';
+import InitializingState from './InitializingState';
+import ProcessingState from './ProcessingState';
+
+interface StatusContentProps {
+ content?: string;
+ messageId: string;
+ taskDetail?: TaskDetail;
+}
+
+const StatusContent = memo<StatusContentProps>(({ taskDetail, content, messageId }) => {
+ const status = taskDetail?.status;
+
+ // Initializing state: no status yet (task just created, waiting for backend)
+ if (!status) {
+ return <InitializingState />;
+ }
+
+ // Processing states: Processing, InReview, Pending, Active, Todo
+ const isProcessing =
+ status === ThreadStatus.Processing ||
+ status === ThreadStatus.InReview ||
+ status === ThreadStatus.Pending ||
+ status === ThreadStatus.Active ||
+ status === ThreadStatus.Todo;
+
+ if (isProcessing) {
+ return <ProcessingState messageId={messageId} taskDetail={taskDetail!} />;
+ }
+
+ // Completed state
+ if (status === ThreadStatus.Completed) {
+ return <CompletedState content={content} taskDetail={taskDetail!} />;
+ }
+
+ // Error states: Failed, Cancel
+ if (status === ThreadStatus.Failed || status === ThreadStatus.Cancel) {
+ return <ErrorState taskDetail={taskDetail!} />;
+ }
+
+ // Fallback to initializing state for unknown status
+ return <InitializingState />;
+});
+
+StatusContent.displayName = 'StatusContent';
+
+export default StatusContent;
diff --git a/src/features/Conversation/Messages/Task/TaskDetailPanel/index.tsx b/src/features/Conversation/Messages/Task/TaskDetailPanel/index.tsx
new file mode 100644
index 00000000000..ed2be8c6446
--- /dev/null
+++ b/src/features/Conversation/Messages/Task/TaskDetailPanel/index.tsx
@@ -0,0 +1,56 @@
+'use client';
+
+import { Block, Text } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { memo } from 'react';
+
+import { TaskDetail } from '@/types/index';
+
+import StatusContent from './StatusContent';
+
+const useStyles = createStyles(({ css, token }) => ({
+ instruction: css`
+ padding-block: 12px;
+ padding-inline: 16px;
+
+ font-size: 12px;
+ line-height: 1.6;
+ color: ${token.colorTextTertiary};
+ `,
+}));
+
+interface TaskDetailPanelProps {
+ content?: string;
+ instruction?: string;
+ /**
+ * Message ID for updating task status in store
+ */
+ messageId: string;
+ taskDetail?: TaskDetail;
+}
+
+const TaskDetailPanel = memo<TaskDetailPanelProps>(
+ ({ taskDetail, instruction, content, messageId }) => {
+ const { styles } = useStyles();
+
+ return (
+ <Block paddingBlock={8} paddingInline={12}>
+ {/* Instruction Header */}
+ {instruction && (
+ <Text className={styles.instruction} style={{ display: 'block' }}>
+ {instruction}
+ </Text>
+ )}
+
+ {/* Status Content */}
+ <Block variant="outlined">
+ <StatusContent content={content} messageId={messageId} taskDetail={taskDetail} />
+ </Block>
+ </Block>
+ );
+ },
+);
+
+TaskDetailPanel.displayName = 'TaskDetailPanel';
+
+export default TaskDetailPanel;
diff --git a/src/features/Conversation/Messages/Task/components/MessageContent.tsx b/src/features/Conversation/Messages/Task/components/MessageContent.tsx
new file mode 100644
index 00000000000..7e4e1950a08
--- /dev/null
+++ b/src/features/Conversation/Messages/Task/components/MessageContent.tsx
@@ -0,0 +1,67 @@
+import { LOADING_FLAT } from '@lobechat/const';
+import { UIChatMessage } from '@lobechat/types';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { messageStateSelectors, useConversationStore } from '../../../store';
+import { useMarkdown } from '../../Assistant/useMarkdown';
+import { CollapsedMessage } from '../../AssistantGroup/components/CollapsedMessage';
+import DisplayContent from '../../components/DisplayContent';
+import FileChunks from '../../components/FileChunks';
+import ImageFileListViewer from '../../components/ImageFileListViewer';
+import IntentUnderstanding from '../../components/IntentUnderstanding';
+import Reasoning from '../../components/Reasoning';
+import SearchGrounding from '../../components/SearchGrounding';
+
+const MessageContent = memo<UIChatMessage>(
+ ({ id, tools, content, chunksList, search, imageList, metadata, ...props }) => {
+ const markdownProps = useMarkdown(id);
+ // Use ConversationStore instead of ChatStore
+ const generating = useConversationStore(messageStateSelectors.isMessageGenerating(id));
+ const isCollapsed = useConversationStore(messageStateSelectors.isMessageCollapsed(id));
+ const isReasoning = useConversationStore(messageStateSelectors.isMessageInReasoning(id));
+
+ const isToolCallGenerating = generating && (content === LOADING_FLAT || !content) && !!tools;
+
+ // TODO: Need to implement isIntentUnderstanding selector in ConversationStore if needed
+ const isIntentUnderstanding = false;
+
+ const showSearch = !!search && !!search.citations?.length;
+ const showImageItems = !!imageList && imageList.length > 0;
+
+ // remove \n to avoid empty content
+ // refs: https://github.com/lobehub/lobe-chat/pull/6153
+ const showReasoning =
+ (!!props.reasoning && props.reasoning.content?.trim() !== '') ||
+ (!props.reasoning && isReasoning);
+
+ const showFileChunks = !!chunksList && chunksList.length > 0;
+
+ if (isCollapsed) return <CollapsedMessage content={content} id={id} />;
+
+ return (
+ <Flexbox gap={8} id={id}>
+ {showSearch && (
+ <SearchGrounding citations={search?.citations} searchQueries={search?.searchQueries} />
+ )}
+ {showFileChunks && <FileChunks data={chunksList} />}
+ {showReasoning && <Reasoning {...props.reasoning} id={id} />}
+ {isIntentUnderstanding ? (
+ <IntentUnderstanding />
+ ) : (
+ <DisplayContent
+ content={content}
+ hasImages={showImageItems}
+ isMultimodal={metadata?.isMultimodal}
+ isToolCallGenerating={isToolCallGenerating}
+ markdownProps={markdownProps}
+ tempDisplayContent={metadata?.tempDisplayContent}
+ />
+ )}
+ {showImageItems && <ImageFileListViewer items={imageList} />}
+ </Flexbox>
+ );
+ },
+);
+
+export default MessageContent;
diff --git a/src/features/Conversation/Messages/Task/index.tsx b/src/features/Conversation/Messages/Task/index.tsx
new file mode 100644
index 00000000000..e9e09df9d63
--- /dev/null
+++ b/src/features/Conversation/Messages/Task/index.tsx
@@ -0,0 +1,96 @@
+'use client';
+
+import { LOADING_FLAT } from '@lobechat/const';
+import isEqual from 'fast-deep-equal';
+import { memo, useCallback } from 'react';
+
+import { ChatItem } from '@/features/Conversation/ChatItem';
+import { useNewScreen } from '@/features/Conversation/Messages/components/useNewScreen';
+import { useOpenChatSettings } from '@/hooks/useInterceptingRoutes';
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
+import { useGlobalStore } from '@/store/global';
+
+import ErrorMessageExtra, { useErrorContent } from '../../Error';
+import { useAgentMeta, useDoubleClickEdit } from '../../hooks';
+import { dataSelectors, messageStateSelectors, useConversationStore } from '../../store';
+import { normalizeThinkTags, processWithArtifact } from '../../utils/markdown';
+import { AssistantActionsBar } from './Actions';
+import TaskDetailPanel from './TaskDetailPanel';
+
+interface TaskMessageProps {
+ disableEditing?: boolean;
+ id: string;
+ index: number;
+ isLatestItem?: boolean;
+}
+
+const AssistantMessage = memo<TaskMessageProps>(({ id, index, disableEditing, isLatestItem }) => {
+ // Get message and actionsConfig from ConversationStore
+ const item = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual)!;
+ const actionsConfig = useConversationStore((s) => s.actionsBar?.assistant);
+
+ const { agentId, error, role, content, createdAt, metadata, taskDetail } = item;
+
+ const avatar = useAgentMeta(agentId);
+
+ // Get editing and generating state from ConversationStore
+ const editing = useConversationStore(messageStateSelectors.isMessageEditing(id));
+ const generating = useConversationStore(messageStateSelectors.isMessageGenerating(id));
+ const creating = useConversationStore(messageStateSelectors.isMessageCreating(id));
+ const newScreen = useNewScreen({ creating, isLatestItem });
+
+ const errorContent = useErrorContent(error);
+
+ // remove line breaks in artifact tag to make the ast transform easier
+ const message = !editing ? normalizeThinkTags(processWithArtifact(content)) : content;
+
+ const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
+ const [toggleSystemRole] = useGlobalStore((s) => [s.toggleSystemRole]);
+ const openChatSettings = useOpenChatSettings();
+
+ const onAvatarClick = useCallback(() => {
+ if (!isInbox) {
+ toggleSystemRole(true);
+ } else {
+ openChatSettings();
+ }
+ }, [isInbox]);
+
+ const onDoubleClick = useDoubleClickEdit({ disableEditing, error, id, role });
+
+ return (
+ <ChatItem
+ aboveMessage={null}
+ actions={
+ <AssistantActionsBar actionsConfig={actionsConfig} data={item} id={id} index={index} />
+ }
+ avatar={avatar}
+ customErrorRender={(error) => <ErrorMessageExtra data={item} error={error} />}
+ editing={editing}
+ error={
+ errorContent && error && (message === LOADING_FLAT || !message) ? errorContent : undefined
+ }
+ id={id}
+ loading={generating}
+ message={message}
+ newScreen={newScreen}
+ onAvatarClick={onAvatarClick}
+ onDoubleClick={onDoubleClick}
+ placement={'left'}
+ showTitle
+ time={createdAt}
+ >
+ <TaskDetailPanel
+ content={content}
+ instruction={metadata?.instruction}
+ messageId={id}
+ taskDetail={taskDetail}
+ />
+ </ChatItem>
+ );
+}, isEqual);
+
+AssistantMessage.displayName = 'AssistantMessage';
+
+export default AssistantMessage;
diff --git a/src/features/ChatList/Messages/Tool/Inspector/BuiltinPluginTitle.tsx b/src/features/Conversation/Messages/Tool/Inspector/BuiltinPluginTitle.tsx
similarity index 90%
rename from src/features/ChatList/Messages/Tool/Inspector/BuiltinPluginTitle.tsx
rename to src/features/Conversation/Messages/Tool/Inspector/BuiltinPluginTitle.tsx
index 75b723def81..7c49458c728 100644
--- a/src/features/ChatList/Messages/Tool/Inspector/BuiltinPluginTitle.tsx
+++ b/src/features/Conversation/Messages/Tool/Inspector/BuiltinPluginTitle.tsx
@@ -4,10 +4,10 @@ import { ChevronRight } from 'lucide-react';
import { ReactNode, memo } from 'react';
import { Flexbox } from 'react-layout-kit';
-import { useChatStore } from '@/store/chat';
-import { messageStateSelectors } from '@/store/chat/selectors';
import { shinyTextStylish } from '@/styles/loading';
+import { messageStateSelectors, useConversationStore } from '../../../store';
+
export const useStyles = createStyles(({ css, token }) => ({
apiName: css`
overflow: hidden;
@@ -37,7 +37,7 @@ const BuiltinPluginTitle = memo<BuiltinPluginTitleProps>(
({ messageId, index, apiName, title, toolCallId }) => {
const { styles } = useStyles();
- const isLoading = useChatStore(
+ const isLoading = useConversationStore(
messageStateSelectors.isToolApiNameShining(messageId, index, toolCallId),
);
diff --git a/src/features/ChatList/Messages/Tool/Inspector/Debug.tsx b/src/features/Conversation/Messages/Tool/Inspector/Debug.tsx
similarity index 95%
rename from src/features/ChatList/Messages/Tool/Inspector/Debug.tsx
rename to src/features/Conversation/Messages/Tool/Inspector/Debug.tsx
index bdf3b7689bb..d89f4473817 100644
--- a/src/features/ChatList/Messages/Tool/Inspector/Debug.tsx
+++ b/src/features/Conversation/Messages/Tool/Inspector/Debug.tsx
@@ -45,7 +45,7 @@ const Debug = memo<DebugProps>(({ payload, requestArgs, toolCallId }) => {
label: t('debug.pluginState'),
},
]}
- style={{ display: 'grid', maxWidth: 800, minWidth: 400 }}
+ style={{ display: 'grid', maxWidth: 800 }}
/>
);
});
diff --git a/src/features/ChatList/Messages/Tool/Inspector/PluginResult.tsx b/src/features/Conversation/Messages/Tool/Inspector/PluginResult.tsx
similarity index 84%
rename from src/features/ChatList/Messages/Tool/Inspector/PluginResult.tsx
rename to src/features/Conversation/Messages/Tool/Inspector/PluginResult.tsx
index 63081c06db9..816384b4233 100644
--- a/src/features/ChatList/Messages/Tool/Inspector/PluginResult.tsx
+++ b/src/features/Conversation/Messages/Tool/Inspector/PluginResult.tsx
@@ -1,8 +1,7 @@
import { Highlighter } from '@lobehub/ui';
import { memo, useMemo } from 'react';
-import { useChatStore } from '@/store/chat';
-import { dbMessageSelectors } from '@/store/chat/selectors';
+import { dataSelectors, useConversationStore } from '../../../store';
export interface FunctionMessageProps {
toolCallId: string;
@@ -10,7 +9,7 @@ export interface FunctionMessageProps {
}
const PluginResult = memo<FunctionMessageProps>(({ toolCallId, variant }) => {
- const toolMessage = useChatStore(dbMessageSelectors.getDbMessageByToolCallId(toolCallId));
+ const toolMessage = useConversationStore(dataSelectors.getDbMessageByToolCallId(toolCallId));
const { data, language } = useMemo(() => {
try {
diff --git a/src/features/ChatList/Messages/Tool/Inspector/PluginState.tsx b/src/features/Conversation/Messages/Tool/Inspector/PluginState.tsx
similarity index 70%
rename from src/features/ChatList/Messages/Tool/Inspector/PluginState.tsx
rename to src/features/Conversation/Messages/Tool/Inspector/PluginState.tsx
index afbc9985ceb..8c18e34324a 100644
--- a/src/features/ChatList/Messages/Tool/Inspector/PluginState.tsx
+++ b/src/features/Conversation/Messages/Tool/Inspector/PluginState.tsx
@@ -1,15 +1,14 @@
import { Highlighter } from '@lobehub/ui';
import { memo } from 'react';
-import { useChatStore } from '@/store/chat';
-import { dbMessageSelectors } from '@/store/chat/selectors';
+import { dataSelectors, useConversationStore } from '../../../store';
export interface FunctionMessageProps {
toolCallId: string;
}
const PluginState = memo<FunctionMessageProps>(({ toolCallId }) => {
- const toolMessage = useChatStore(dbMessageSelectors.getDbMessageByToolCallId(toolCallId));
+ const toolMessage = useConversationStore(dataSelectors.getDbMessageByToolCallId(toolCallId));
return (
toolMessage?.pluginState && (
diff --git a/src/features/ChatList/Messages/Tool/Inspector/Settings.tsx b/src/features/Conversation/Messages/Tool/Inspector/Settings.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Tool/Inspector/Settings.tsx
rename to src/features/Conversation/Messages/Tool/Inspector/Settings.tsx
diff --git a/src/features/ChatList/Messages/Tool/Inspector/ToolTitle.tsx b/src/features/Conversation/Messages/Tool/Inspector/ToolTitle.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Tool/Inspector/ToolTitle.tsx
rename to src/features/Conversation/Messages/Tool/Inspector/ToolTitle.tsx
diff --git a/src/features/ChatList/Messages/Tool/Inspector/index.tsx b/src/features/Conversation/Messages/Tool/Inspector/index.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Tool/Inspector/index.tsx
rename to src/features/Conversation/Messages/Tool/Inspector/index.tsx
diff --git a/src/features/ChatList/Messages/Tool/Render/Arguments/ObjectEntity.tsx b/src/features/Conversation/Messages/Tool/Render/Arguments/ObjectEntity.tsx
similarity index 89%
rename from src/features/ChatList/Messages/Tool/Render/Arguments/ObjectEntity.tsx
rename to src/features/Conversation/Messages/Tool/Render/Arguments/ObjectEntity.tsx
index a7f9e954119..37406123e94 100644
--- a/src/features/ChatList/Messages/Tool/Render/Arguments/ObjectEntity.tsx
+++ b/src/features/Conversation/Messages/Tool/Render/Arguments/ObjectEntity.tsx
@@ -1,7 +1,6 @@
import { createStyles } from 'antd-style';
import { memo } from 'react';
-import { useIsMobile } from '@/hooks/useIsMobile';
import { shinyTextStylish } from '@/styles/loading';
import ValueCell from './ValueCell';
@@ -55,15 +54,11 @@ interface ObjectEntityProps {
const ObjectEntity = memo<ObjectEntityProps>(({ hasMinWidth, shine, value, objectKey }) => {
const { styles, cx } = useStyles();
- const isMobile = useIsMobile();
const formatedValue = formatValue(value);
return (
<div className={styles.row}>
- <span
- className={styles.key}
- style={{ minWidth: hasMinWidth ? (isMobile ? 60 : 140) : undefined }}
- >
+ <span className={styles.key} style={{ minWidth: hasMinWidth ? 140 : undefined }}>
{objectKey}
</span>
<span className={styles.colon}>:</span>
diff --git a/src/features/ChatList/Messages/Tool/Render/Arguments/ValueCell.tsx b/src/features/Conversation/Messages/Tool/Render/Arguments/ValueCell.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Tool/Render/Arguments/ValueCell.tsx
rename to src/features/Conversation/Messages/Tool/Render/Arguments/ValueCell.tsx
diff --git a/src/features/ChatList/Messages/Tool/Render/Arguments/index.tsx b/src/features/Conversation/Messages/Tool/Render/Arguments/index.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Tool/Render/Arguments/index.tsx
rename to src/features/Conversation/Messages/Tool/Render/Arguments/index.tsx
diff --git a/src/features/ChatList/Messages/Tool/Render/CustomRender.tsx b/src/features/Conversation/Messages/Tool/Render/CustomRender.tsx
similarity index 85%
rename from src/features/ChatList/Messages/Tool/Render/CustomRender.tsx
rename to src/features/Conversation/Messages/Tool/Render/CustomRender.tsx
index 0fe4a163ef6..f1836431b90 100644
--- a/src/features/ChatList/Messages/Tool/Render/CustomRender.tsx
+++ b/src/features/Conversation/Messages/Tool/Render/CustomRender.tsx
@@ -8,9 +8,8 @@ import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
import PluginRender from '@/features/PluginsUI/Render';
-import { useChatStore } from '@/store/chat';
-import { messageStateSelectors } from '@/store/chat/selectors';
+import { messageStateSelectors, useConversationStore } from '../../../store';
import PluginResult from '../Inspector/PluginResult';
import Arguments from './Arguments';
import KeyValueEditor from './KeyValueEditor';
@@ -43,11 +42,13 @@ const CustomRender = memo<CustomRenderProps>(
tool_call_id,
}) => {
const { t } = useTranslation(['tool', 'common']);
- const [loading] = useChatStore((s) => [messageStateSelectors.isPluginApiInvoking(id)(s)]);
+ // Use ConversationStore for state selectors
+ const loading = useConversationStore(messageStateSelectors.isPluginApiInvoking(id));
const [isEditing, setIsEditing] = useState(false);
const { message } = App.useApp();
- const [optimisticUpdatePluginArguments, reInvokeToolMessage] = useChatStore((s) => [
- s.optimisticUpdatePluginArguments,
+ // Get actions from ConversationStore
+ const [updatePluginArguments, reInvokeToolMessage] = useConversationStore((s) => [
+ s.updatePluginArguments,
s.reInvokeToolMessage,
]);
const handleCancel = useCallback(() => {
@@ -56,13 +57,13 @@ const CustomRender = memo<CustomRenderProps>(
const handleFinish = useCallback(
async (editedObject: Record<string, any>) => {
- if (!id) return;
+ if (!tool_call_id) return;
try {
const newArgsString = JSON.stringify(editedObject, null, 2);
if (newArgsString !== requestArgs) {
- await optimisticUpdatePluginArguments(id, editedObject, true);
+ await updatePluginArguments(tool_call_id, editedObject, true);
await reInvokeToolMessage(id);
}
setIsEditing(false);
@@ -71,7 +72,7 @@ const CustomRender = memo<CustomRenderProps>(
message.error(t('updateArgs.stringifyError'));
}
},
- [requestArgs, id],
+ [requestArgs, id, tool_call_id, updatePluginArguments, reInvokeToolMessage, message, t],
);
useEffect(() => {
@@ -88,12 +89,13 @@ const CustomRender = memo<CustomRenderProps>(
<PluginRender
arguments={plugin?.arguments}
content={content}
- id={id}
identifier={plugin?.identifier}
loading={loading}
+ messageId={id}
payload={plugin}
pluginError={pluginError}
pluginState={pluginState}
+ toolCallId={tool_call_id}
type={plugin?.type}
/>
</Flexbox>
diff --git a/src/features/ChatList/Messages/Tool/Render/ErrorResponse.tsx b/src/features/Conversation/Messages/Tool/Render/ErrorResponse.tsx
similarity index 97%
rename from src/features/ChatList/Messages/Tool/Render/ErrorResponse.tsx
rename to src/features/Conversation/Messages/Tool/Render/ErrorResponse.tsx
index f56cf6be657..207f1126ff5 100644
--- a/src/features/ChatList/Messages/Tool/Render/ErrorResponse.tsx
+++ b/src/features/Conversation/Messages/Tool/Render/ErrorResponse.tsx
@@ -28,7 +28,7 @@ const ErrorResponse = memo<ErrorResponseProps>(({ id, type, body, message, plugi
}
message={t(`response.${type}` as any)}
showIcon
- type={'error'}
+ type={'secondary'}
/>
);
});
diff --git a/src/features/ChatList/Messages/Tool/Render/KeyValueEditor.tsx b/src/features/Conversation/Messages/Tool/Render/KeyValueEditor.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Tool/Render/KeyValueEditor.tsx
rename to src/features/Conversation/Messages/Tool/Render/KeyValueEditor.tsx
diff --git a/src/features/ChatList/Messages/Tool/Render/PluginSettings.tsx b/src/features/Conversation/Messages/Tool/Render/PluginSettings.tsx
similarity index 92%
rename from src/features/ChatList/Messages/Tool/Render/PluginSettings.tsx
rename to src/features/Conversation/Messages/Tool/Render/PluginSettings.tsx
index 750d936efda..6b37a13c20a 100644
--- a/src/features/ChatList/Messages/Tool/Render/PluginSettings.tsx
+++ b/src/features/Conversation/Messages/Tool/Render/PluginSettings.tsx
@@ -7,12 +7,12 @@ import { useTranslation } from 'react-i18next';
import { Center, Flexbox } from 'react-layout-kit';
import PluginSettingsConfig from '@/features/PluginSettings';
-import { useChatStore } from '@/store/chat';
import { pluginHelpers, useToolStore } from '@/store/tool';
import { pluginSelectors } from '@/store/tool/selectors';
import { ChatPluginPayload } from '@/types/index';
import { ErrorActionContainer, useStyles } from '../../../Error/style';
+import { useConversationStore } from '../../../store';
interface PluginSettingsProps {
id: string;
@@ -23,9 +23,10 @@ const PluginSettings = memo<PluginSettingsProps>(({ id, plugin }) => {
const { styles } = useStyles();
const { t } = useTranslation('error');
const theme = useTheme();
- const [resend, deleteMessage] = useChatStore((s) => [
- s.regenerateAssistantMessage,
+ // Get actions from ConversationStore
+ const [deleteMessage, resend] = useConversationStore((s) => [
s.deleteMessage,
+ s.regenerateAssistantMessage,
]);
const pluginIdentifier = plugin?.identifier as string;
const pluginMeta = useToolStore(pluginSelectors.getPluginMetaById(pluginIdentifier), isEqual);
@@ -39,6 +40,7 @@ const PluginSettings = memo<PluginSettingsProps>(({ id, plugin }) => {
avatar={pluginHelpers.getPluginAvatar(pluginMeta) || '⚙️'}
background={theme.colorFillContent}
gap={12}
+ shape={'square'}
size={80}
/>
<Flexbox style={{ fontSize: 20 }}>
diff --git a/src/features/ChatList/Messages/Tool/Render/index.tsx b/src/features/Conversation/Messages/Tool/Render/index.tsx
similarity index 75%
rename from src/features/ChatList/Messages/Tool/Render/index.tsx
rename to src/features/Conversation/Messages/Tool/Render/index.tsx
index 5fff506fe38..32bdaedda2a 100644
--- a/src/features/ChatList/Messages/Tool/Render/index.tsx
+++ b/src/features/Conversation/Messages/Tool/Render/index.tsx
@@ -1,8 +1,6 @@
import { Suspense, memo } from 'react';
-import { useChatStore } from '@/store/chat';
-import { dbMessageSelectors, messageStateSelectors } from '@/store/chat/selectors';
-
+import { dataSelectors, messageStateSelectors, useConversationStore } from '../../../store';
import CustomRender from './CustomRender';
import ErrorResponse from './ErrorResponse';
@@ -17,8 +15,10 @@ interface RenderProps {
const Render = memo<RenderProps>(
({ toolCallId, toolIndex, messageId, requestArgs, showPluginRender, setShowPluginRender }) => {
- const loading = useChatStore(messageStateSelectors.isToolCallStreaming(messageId, toolIndex));
- const toolMessage = useChatStore(dbMessageSelectors.getDbMessageByToolCallId(toolCallId));
+ const loading = useConversationStore(
+ messageStateSelectors.isToolCallStreaming(messageId, toolIndex),
+ );
+ const toolMessage = useConversationStore(dataSelectors.getDbMessageByToolCallId(toolCallId));
if (loading || !toolMessage) return null;
diff --git a/src/features/ChatList/Messages/Tool/ToolItem.tsx b/src/features/Conversation/Messages/Tool/ToolItem.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Tool/ToolItem.tsx
rename to src/features/Conversation/Messages/Tool/ToolItem.tsx
diff --git a/src/features/ChatList/Messages/Tool/index.tsx b/src/features/Conversation/Messages/Tool/index.tsx
similarity index 74%
rename from src/features/ChatList/Messages/Tool/index.tsx
rename to src/features/Conversation/Messages/Tool/index.tsx
index af28aeb29d5..2a664e55a14 100644
--- a/src/features/ChatList/Messages/Tool/index.tsx
+++ b/src/features/Conversation/Messages/Tool/index.tsx
@@ -1,3 +1,4 @@
+import { UIChatMessage } from '@lobechat/types';
import { Alert } from '@lobehub/ui';
import { Button } from 'antd';
import isEqual from 'fast-deep-equal';
@@ -5,10 +6,7 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
-import { useChatStore } from '@/store/chat';
-import { dbMessageSelectors } from '@/store/chat/selectors';
-import { UIChatMessage } from '@/types/message';
-
+import { dataSelectors, useConversationStore } from '../../store';
import ToolItem from './ToolItem';
interface ToolMessageProps {
@@ -18,8 +16,8 @@ interface ToolMessageProps {
const Tool = memo<ToolMessageProps>(({ id, index }) => {
const { t } = useTranslation('plugin');
- const item = useChatStore(dbMessageSelectors.getDbMessageById(id), isEqual) as UIChatMessage;
- const deleteToolMessage = useChatStore((s) => s.deleteToolMessage);
+ const item = useConversationStore(dataSelectors.getDbMessageById(id), isEqual) as UIChatMessage;
+ const deleteToolMessage = useConversationStore((s) => s.deleteToolMessage);
const [loading, setLoading] = useState(false);
const handleDelete = async () => {
@@ -32,7 +30,7 @@ const Tool = memo<ToolMessageProps>(({ id, index }) => {
};
return (
- <Flexbox gap={4} paddingBlock={12} paddingInline={12}>
+ <Flexbox gap={4} paddingBlock={12}>
<Alert
action={
<Button loading={loading} onClick={handleDelete} size={'small'} type={'primary'}>
@@ -40,7 +38,7 @@ const Tool = memo<ToolMessageProps>(({ id, index }) => {
</Button>
}
message={t('inspector.orphanedToolCall')}
- type={'warning'}
+ type={'secondary'}
variant={'borderless'}
/>
{item.plugin && (
@@ -54,5 +52,6 @@ const Tool = memo<ToolMessageProps>(({ id, index }) => {
)}
</Flexbox>
);
-});
+}, isEqual);
+
export default Tool;
diff --git a/src/features/Conversation/Messages/User/Actions/index.tsx b/src/features/Conversation/Messages/User/Actions/index.tsx
new file mode 100644
index 00000000000..3671ae153d2
--- /dev/null
+++ b/src/features/Conversation/Messages/User/Actions/index.tsx
@@ -0,0 +1,178 @@
+import { UIChatMessage } from '@lobechat/types';
+import { ActionIconGroup } from '@lobehub/ui';
+import type { ActionIconGroupEvent, ActionIconGroupItemType } from '@lobehub/ui';
+import { memo, useCallback, useMemo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { MESSAGE_ACTION_BAR_PORTAL_ATTRIBUTES } from '@/const/messageActionPortal';
+
+import type {
+ MessageActionItem,
+ MessageActionItemOrDivider,
+ MessageActionsConfig,
+} from '../../../types';
+import MessageBranch from '../../components/MessageBranch';
+import { useUserActions } from './useUserActions';
+
+// Helper to strip handleClick from action items before passing to ActionIconGroup
+const stripHandleClick = (item: MessageActionItemOrDivider): ActionIconGroupItemType => {
+ if ('type' in item && item.type === 'divider') return item as unknown as ActionIconGroupItemType;
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const { handleClick, children, ...rest } = item as MessageActionItem;
+ if (children) {
+ return {
+ ...rest,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ children: children.map(({ handleClick: _, ...child }) => child),
+ } as ActionIconGroupItemType;
+ }
+ return rest as ActionIconGroupItemType;
+};
+
+// Build action items map for handleAction lookup
+const buildActionsMap = (items: MessageActionItemOrDivider[]): Map<string, MessageActionItem> => {
+ const map = new Map<string, MessageActionItem>();
+ for (const item of items) {
+ if ('key' in item && item.key) {
+ map.set(String(item.key), item as MessageActionItem);
+ // Also index children for submenu items
+ if ('children' in item && item.children) {
+ for (const child of item.children) {
+ if (child.key) {
+ map.set(`${item.key}.${child.key}`, child as unknown as MessageActionItem);
+ }
+ }
+ }
+ }
+ }
+ return map;
+};
+
+interface UserActionsProps {
+ actionsConfig?: MessageActionsConfig;
+ data: UIChatMessage;
+ disableEditing?: boolean;
+ id: string;
+}
+
+export const UserActionsBar = memo<UserActionsProps>(({ actionsConfig, id, data }) => {
+ // Get default actions from hook
+ const defaultActions = useUserActions({ data, id });
+
+ // Create extra actions from factory functions
+ const extraBarItems = useMemo(() => {
+ if (!actionsConfig?.extraBarActions) return [];
+ return actionsConfig.extraBarActions
+ .map((factory) => factory(id))
+ .filter((item): item is NonNullable<typeof item> => item !== null);
+ }, [actionsConfig?.extraBarActions, id]);
+
+ const extraMenuItems = useMemo(() => {
+ if (!actionsConfig?.extraMenuActions) return [];
+ return actionsConfig.extraMenuActions
+ .map((factory) => factory(id))
+ .filter((item): item is NonNullable<typeof item> => item !== null);
+ }, [actionsConfig?.extraMenuActions, id]);
+
+ // Use external config if provided, otherwise use defaults
+ // Append extra actions from factories
+ const barItems = useMemo(() => {
+ const base = actionsConfig?.bar ?? [defaultActions.regenerate, defaultActions.edit];
+ return [...base, ...extraBarItems];
+ }, [actionsConfig?.bar, defaultActions.regenerate, defaultActions.edit, extraBarItems]);
+
+ const menuItems = useMemo(() => {
+ const base = actionsConfig?.menu ?? [
+ defaultActions.edit,
+ defaultActions.copy,
+ defaultActions.divider,
+ defaultActions.tts,
+ defaultActions.translate,
+ defaultActions.divider,
+ defaultActions.regenerate,
+ defaultActions.del,
+ ];
+ return [...base, ...extraMenuItems];
+ }, [
+ actionsConfig?.menu,
+ defaultActions.edit,
+ defaultActions.copy,
+ defaultActions.divider,
+ defaultActions.tts,
+ defaultActions.translate,
+ defaultActions.regenerate,
+ defaultActions.del,
+ extraMenuItems,
+ ]);
+
+ // Strip handleClick for DOM safety
+ const items = useMemo(() => barItems.map(stripHandleClick), [barItems]);
+ const menu = useMemo(() => menuItems.map(stripHandleClick), [menuItems]);
+
+ // Build actions map for click handling
+ const allActions = useMemo(
+ () => buildActionsMap([...barItems, ...menuItems]),
+ [barItems, menuItems],
+ );
+
+ const handleAction = useCallback(
+ (event: ActionIconGroupEvent) => {
+ // Handle submenu items (e.g., translate -> zh-CN)
+ if (event.keyPath && event.keyPath.length > 1) {
+ const parentKey = event.keyPath.at(-1);
+ const childKey = event.keyPath[0];
+ const parent = allActions.get(parentKey!);
+ if (parent && 'children' in parent && parent.children) {
+ const child = parent.children.find((c) => c.key === childKey);
+ child?.handleClick?.();
+ return;
+ }
+ }
+
+ // Handle regular actions
+ const action = allActions.get(event.key);
+ action?.handleClick?.();
+ },
+ [allActions],
+ );
+
+ return <ActionIconGroup items={items} menu={{ items: menu }} onActionClick={handleAction} />;
+});
+
+UserActionsBar.displayName = 'UserActionsBar';
+
+interface ActionsProps {
+ actionsConfig?: MessageActionsConfig;
+ data: UIChatMessage;
+ disableEditing?: boolean;
+ id: string;
+ index: number;
+}
+
+const actionBarHolder = (
+ <div {...{ [MESSAGE_ACTION_BAR_PORTAL_ATTRIBUTES.user]: '' }} style={{ height: '28px' }} />
+);
+const Actions = memo<ActionsProps>(({ id, data, disableEditing }) => {
+ const { branch } = data;
+
+ return (
+ <Flexbox align={'center'} horizontal>
+ {!disableEditing && (
+ <Flexbox align={'flex-start'} role="menubar">
+ {actionBarHolder}
+ </Flexbox>
+ )}
+ {branch && (
+ <MessageBranch
+ activeBranchIndex={branch.activeBranchIndex}
+ count={branch.count}
+ messageId={id}
+ />
+ )}
+ </Flexbox>
+ );
+});
+
+Actions.displayName = 'UserActions';
+
+export default Actions;
diff --git a/src/features/Conversation/Messages/User/Actions/useUserActions.ts b/src/features/Conversation/Messages/User/Actions/useUserActions.ts
new file mode 100644
index 00000000000..ac6d63d35f7
--- /dev/null
+++ b/src/features/Conversation/Messages/User/Actions/useUserActions.ts
@@ -0,0 +1,121 @@
+import type { ActionIconGroupItemType } from '@lobehub/ui';
+import { copyToClipboard } from '@lobehub/ui';
+import { App } from 'antd';
+import { Copy, Edit, LanguagesIcon, Play, RotateCcw, Trash } from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { localeOptions } from '@/locales/resources';
+import { UIChatMessage } from '@/types/index';
+
+import { messageStateSelectors, useConversationStore } from '../../../store';
+
+export interface ActionItem extends ActionIconGroupItemType {
+ children?: Array<{ handleClick?: () => void; key: string; label: string }>;
+ handleClick?: () => void | Promise<void>;
+}
+
+export interface UserActions {
+ copy: ActionItem;
+ del: ActionItem;
+ divider: { type: 'divider' };
+ edit: ActionItem;
+ regenerate: ActionItem;
+ translate: ActionItem;
+ tts: ActionItem;
+}
+
+interface UseUserActionsParams {
+ data: UIChatMessage;
+ id: string;
+}
+
+export const useUserActions = ({ id, data }: UseUserActionsParams): UserActions => {
+ const { t } = useTranslation('common');
+ const { message } = App.useApp();
+
+ // Get state from ConversationStore
+ const isRegenerating = useConversationStore(messageStateSelectors.isMessageRegenerating(id));
+
+ // Get actions from ConversationStore
+ const [toggleMessageEditing, deleteMessage, regenerateUserMessage, translateMessage, ttsMessage] =
+ useConversationStore((s) => [
+ s.toggleMessageEditing,
+ s.deleteMessage,
+ s.regenerateUserMessage,
+ s.translateMessage,
+ s.ttsMessage,
+ ]);
+
+ return useMemo<UserActions>(
+ () => ({
+ copy: {
+ handleClick: async () => {
+ await copyToClipboard(data.content);
+ message.success(t('copySuccess'));
+ },
+ icon: Copy,
+ key: 'copy',
+ label: t('copy'),
+ },
+ del: {
+ danger: true,
+ handleClick: () => deleteMessage(id),
+ icon: Trash,
+ key: 'del',
+ label: t('delete'),
+ },
+ divider: {
+ type: 'divider',
+ },
+ edit: {
+ handleClick: () => {
+ toggleMessageEditing(id, true);
+ },
+ icon: Edit,
+ key: 'edit',
+ label: t('edit'),
+ },
+ regenerate: {
+ disabled: isRegenerating,
+ handleClick: () => {
+ regenerateUserMessage(id);
+ if (data.error) deleteMessage(id);
+ },
+ icon: RotateCcw,
+ key: 'regenerate',
+ label: t('regenerate'),
+ spin: isRegenerating || undefined,
+ },
+ translate: {
+ children: localeOptions.map((i) => ({
+ handleClick: () => translateMessage(id, i.value),
+ key: i.value,
+ label: t(`lang.${i.value}`),
+ })),
+ icon: LanguagesIcon,
+ key: 'translate',
+ label: t('translate.action', { ns: 'chat' }),
+ },
+ tts: {
+ handleClick: () => ttsMessage(id),
+ icon: Play,
+ key: 'tts',
+ label: t('tts.action', { ns: 'chat' }),
+ },
+ }),
+ [
+ t,
+ id,
+ data.content,
+ data.error,
+ isRegenerating,
+ toggleMessageEditing,
+ deleteMessage,
+ regenerateUserMessage,
+ translateMessage,
+ ttsMessage,
+ message,
+ ],
+ );
+};
diff --git a/src/features/ChatList/Messages/User/Extra.tsx b/src/features/Conversation/Messages/User/Extra.tsx
similarity index 66%
rename from src/features/ChatList/Messages/User/Extra.tsx
rename to src/features/Conversation/Messages/User/Extra.tsx
index a1f33787749..a50367b0469 100644
--- a/src/features/ChatList/Messages/User/Extra.tsx
+++ b/src/features/Conversation/Messages/User/Extra.tsx
@@ -1,19 +1,19 @@
import { memo } from 'react';
import { Flexbox } from 'react-layout-kit';
-import ExtraContainer from '@/features/ChatList/components/Extras/ExtraContainer';
-import TTS from '@/features/ChatList/components/Extras/TTS';
-import Translate from '@/features/ChatList/components/Extras/Translate';
-import { useChatStore } from '@/store/chat';
-import { messageStateSelectors } from '@/store/chat/selectors';
+import { messageStateSelectors, useConversationStore } from '../../store';
+import ExtraContainer from '../components/Extras/ExtraContainer';
+import TTS from '../components/Extras/TTS';
+import Translate from '../components/Extras/Translate';
interface UserMessageExtraProps {
content: string;
extra: any;
id: string;
}
+
export const UserMessageExtra = memo<UserMessageExtraProps>(({ extra, id, content }) => {
- const loading = useChatStore(messageStateSelectors.isMessageGenerating(id));
+ const loading = useConversationStore(messageStateSelectors.isMessageGenerating(id));
const showTranslate = !!extra?.translate;
const showTTS = !!extra?.tts;
diff --git a/src/features/ChatList/Messages/User/MarkdownRender/ContentPreview.tsx b/src/features/Conversation/Messages/User/components/ContentPreview.tsx
similarity index 81%
rename from src/features/ChatList/Messages/User/MarkdownRender/ContentPreview.tsx
rename to src/features/Conversation/Messages/User/components/ContentPreview.tsx
index a2685625f5b..8ba189923d9 100644
--- a/src/features/ChatList/Messages/User/MarkdownRender/ContentPreview.tsx
+++ b/src/features/Conversation/Messages/User/components/ContentPreview.tsx
@@ -1,12 +1,12 @@
-import { Button, Markdown, MaskShadow } from '@lobehub/ui';
+import { Button, MaskShadow } from '@lobehub/ui';
import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
+import MarkdownMessage from '@/features/Conversation/Markdown';
import { useChatStore } from '@/store/chat';
interface ContentPreviewProps {
content: string;
- displayMode: 'chat' | 'docs';
id: string;
}
@@ -18,7 +18,7 @@ const ContentPreview = ({ content, id }: ContentPreviewProps) => {
return (
<Flexbox>
<MaskShadow>
- <Markdown variant={'chat'}>{content.slice(0, 1000)}</Markdown>
+ <MarkdownMessage>{content.slice(0, 1000)}</MarkdownMessage>
</MaskShadow>
<Flexbox padding={4}>
<Button
diff --git a/src/features/ChatList/Messages/User/FileListViewer/Item.tsx b/src/features/Conversation/Messages/User/components/FileListViewer/Item.tsx
similarity index 96%
rename from src/features/ChatList/Messages/User/FileListViewer/Item.tsx
rename to src/features/Conversation/Messages/User/components/FileListViewer/Item.tsx
index 1509eac07e4..8301f5d9a74 100644
--- a/src/features/ChatList/Messages/User/FileListViewer/Item.tsx
+++ b/src/features/Conversation/Messages/User/components/FileListViewer/Item.tsx
@@ -1,4 +1,3 @@
-import { ChatFileItem } from '@lobechat/types';
import { Text } from '@lobehub/ui';
import { createStyles } from 'antd-style';
import { memo } from 'react';
@@ -6,6 +5,7 @@ import { Flexbox } from 'react-layout-kit';
import FileIcon from '@/components/FileIcon';
import { useChatStore } from '@/store/chat';
+import { ChatFileItem } from '@/types/index';
import { formatSize } from '@/utils/format';
const useStyles = createStyles(({ css, token, isDarkMode }) => ({
diff --git a/src/features/ChatList/Messages/User/FileListViewer/index.tsx b/src/features/Conversation/Messages/User/components/FileListViewer/index.tsx
similarity index 89%
rename from src/features/ChatList/Messages/User/FileListViewer/index.tsx
rename to src/features/Conversation/Messages/User/components/FileListViewer/index.tsx
index fc29516e1ce..6a1a5deca94 100644
--- a/src/features/ChatList/Messages/User/FileListViewer/index.tsx
+++ b/src/features/Conversation/Messages/User/components/FileListViewer/index.tsx
@@ -1,7 +1,8 @@
-import { ChatFileItem } from '@lobechat/types';
import { memo } from 'react';
import { Flexbox } from 'react-layout-kit';
+import { ChatFileItem } from '@/types/index';
+
import FileItem from './Item';
interface FileListViewerProps {
diff --git a/src/features/ChatList/Messages/User/ImageFileListViewer.tsx b/src/features/Conversation/Messages/User/components/ImageFileListViewer.tsx
similarity index 100%
rename from src/features/ChatList/Messages/User/ImageFileListViewer.tsx
rename to src/features/Conversation/Messages/User/components/ImageFileListViewer.tsx
diff --git a/src/features/Conversation/Messages/User/components/MessageContent.tsx b/src/features/Conversation/Messages/User/components/MessageContent.tsx
new file mode 100644
index 00000000000..8d40ec8beca
--- /dev/null
+++ b/src/features/Conversation/Messages/User/components/MessageContent.tsx
@@ -0,0 +1,30 @@
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import MarkdownMessage from '@/features/Conversation/Markdown';
+import { UIChatMessage } from '@/types/index';
+
+import { useMarkdown } from '../useMarkdown';
+import FileListViewer from './FileListViewer';
+import ImageFileListViewer from './ImageFileListViewer';
+import VideoFileListViewer from './VideoFileListViewer';
+
+const UserMessageContent = memo<UIChatMessage>(
+ ({ id, content, imageList, videoList, fileList }) => {
+ const markdownProps = useMarkdown(id);
+ return (
+ <Flexbox gap={8} id={id}>
+ <MarkdownMessage {...markdownProps}>{content}</MarkdownMessage>
+ {imageList && imageList?.length > 0 && <ImageFileListViewer items={imageList} />}
+ {videoList && videoList?.length > 0 && <VideoFileListViewer items={videoList} />}
+ {fileList && fileList?.length > 0 && (
+ <div style={{ marginTop: 8 }}>
+ <FileListViewer items={fileList} />
+ </div>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+export default UserMessageContent;
diff --git a/src/features/ChatList/Messages/User/VideoFileListViewer.tsx b/src/features/Conversation/Messages/User/components/VideoFileListViewer.tsx
similarity index 92%
rename from src/features/ChatList/Messages/User/VideoFileListViewer.tsx
rename to src/features/Conversation/Messages/User/components/VideoFileListViewer.tsx
index e151e3dd169..c0607e62e0e 100644
--- a/src/features/ChatList/Messages/User/VideoFileListViewer.tsx
+++ b/src/features/Conversation/Messages/User/components/VideoFileListViewer.tsx
@@ -1,7 +1,8 @@
-import { ChatVideoItem } from '@lobechat/types';
import { memo } from 'react';
import { Flexbox } from 'react-layout-kit';
+import { ChatVideoItem } from '@/types/index';
+
interface VideoFileListViewerProps {
items: ChatVideoItem[];
}
diff --git a/src/features/Conversation/Messages/User/index.tsx b/src/features/Conversation/Messages/User/index.tsx
new file mode 100644
index 00000000000..210372950f0
--- /dev/null
+++ b/src/features/Conversation/Messages/User/index.tsx
@@ -0,0 +1,108 @@
+import { Tag } from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
+import { type MouseEventHandler, memo, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { ChatItem } from '@/features/Conversation/ChatItem';
+import { useUserAvatar } from '@/hooks/useUserAvatar';
+import { useSessionStore } from '@/store/session';
+import { sessionSelectors } from '@/store/session/selectors';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+import { useDoubleClickEdit } from '../../hooks/useDoubleClickEdit';
+import { dataSelectors, messageStateSelectors, useConversationStore } from '../../store';
+import {
+ useSetMessageItemActionElementPortialContext,
+ useSetMessageItemActionTypeContext,
+} from '../Contexts/message-action-context';
+import Actions from './Actions';
+import { UserMessageExtra } from './Extra';
+import UserMessageContent from './components/MessageContent';
+
+interface UserMessageProps {
+ disableEditing?: boolean;
+ id: string;
+ index: number;
+}
+
+const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {
+ const item = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual)!;
+ const actionsConfig = useConversationStore((s) => s.actionsBar?.user);
+ const { content, createdAt, error, role, extra, targetId } = item;
+
+ const { t } = useTranslation('chat');
+ const avatar = useUserAvatar();
+ const title = useUserStore(userProfileSelectors.displayUserName);
+
+ // Get editing and loading state from ConversationStore
+ const editing = useConversationStore(messageStateSelectors.isMessageEditing(id));
+
+ // Get target name for DM indicator
+ const userName = useUserStore(userProfileSelectors.nickName) || 'User';
+ const agents = useSessionStore(sessionSelectors.currentGroupAgents);
+
+ const dmIndicator = useMemo(() => {
+ if (!targetId) return undefined;
+
+ let targetName = targetId;
+ if (targetId === 'user') {
+ targetName = userName;
+ } else {
+ const targetAgent = agents?.find((agent) => agent.id === targetId);
+ targetName = targetAgent?.title || targetId;
+ }
+
+ return <Tag>{t('dm.visibleTo', { target: targetName })}</Tag>;
+ }, [targetId, userName, agents, t]);
+
+ const onDoubleClick = useDoubleClickEdit({ disableEditing, error, id, role });
+
+ const setMessageItemActionElementPortialContext = useSetMessageItemActionElementPortialContext();
+ const setMessageItemActionTypeContext = useSetMessageItemActionTypeContext();
+
+ const onMouseEnter: MouseEventHandler<HTMLDivElement> = useCallback(
+ (e) => {
+ if (disableEditing) return;
+ setMessageItemActionElementPortialContext(e.currentTarget);
+ setMessageItemActionTypeContext({ id, index, type: 'user' });
+ },
+ [
+ disableEditing,
+ id,
+ index,
+ setMessageItemActionElementPortialContext,
+ setMessageItemActionTypeContext,
+ ],
+ );
+
+ return (
+ <ChatItem
+ actions={
+ <Actions
+ actionsConfig={actionsConfig}
+ data={item}
+ disableEditing={disableEditing}
+ id={id}
+ index={index}
+ />
+ }
+ avatar={{ avatar, title }}
+ editing={editing}
+ id={id}
+ message={content}
+ messageExtra={<UserMessageExtra content={content} extra={extra} id={id} />}
+ onDoubleClick={onDoubleClick}
+ onMouseEnter={onMouseEnter}
+ placement={'right'}
+ showAvatar={false}
+ showTitle={false}
+ time={createdAt}
+ titleAddon={dmIndicator}
+ >
+ <UserMessageContent {...item} />
+ </ChatItem>
+ );
+}, isEqual);
+
+export default UserMessage;
diff --git a/src/features/Conversation/Messages/User/useMarkdown.tsx b/src/features/Conversation/Messages/User/useMarkdown.tsx
new file mode 100644
index 00000000000..cb3dd094b00
--- /dev/null
+++ b/src/features/Conversation/Messages/User/useMarkdown.tsx
@@ -0,0 +1,48 @@
+import { MarkdownProps } from '@lobehub/ui';
+import { ReactNode, useMemo } from 'react';
+
+import { markdownElements } from '../../Markdown/plugins';
+import ContentPreview from './components/ContentPreview';
+
+const rehypePlugins = markdownElements
+ .filter((s) => s.scope !== 'assistant')
+ .map((element) => element.rehypePlugin)
+ .filter(Boolean);
+
+const remarkPlugins = markdownElements
+ .filter((s) => s.scope !== 'assistant')
+ .map((element) => element.remarkPlugin)
+ .filter(Boolean);
+
+export const useMarkdown = (id: string): Partial<MarkdownProps> => {
+ const components = useMemo(
+ () =>
+ Object.fromEntries(
+ markdownElements.map((element) => {
+ const Component = element.Component;
+ return [element.tag, (props: any) => <Component {...props} id={id} />];
+ }),
+ ),
+ [id],
+ );
+
+ return useMemo(
+ () =>
+ ({
+ components: Object.fromEntries(
+ markdownElements.map((element) => {
+ const Component = element.Component;
+ return [element.tag, (props: any) => <Component {...props} id={id} />];
+ }),
+ ),
+ customRender: (dom: ReactNode, { text }: { text: string }) => {
+ if (text.length > 30_000) return <ContentPreview content={text} id={id} />;
+ return dom;
+ },
+ enableStream: false,
+ rehypePlugins,
+ remarkPlugins,
+ }) satisfies Partial<MarkdownProps>,
+ [components],
+ );
+};
diff --git a/src/features/ChatList/Messages/Assistant/DisplayContent.tsx b/src/features/Conversation/Messages/components/DisplayContent.tsx
similarity index 71%
rename from src/features/ChatList/Messages/Assistant/DisplayContent.tsx
rename to src/features/Conversation/Messages/components/DisplayContent.tsx
index 3eb361e9b88..c6681c80935 100644
--- a/src/features/ChatList/Messages/Assistant/DisplayContent.tsx
+++ b/src/features/Conversation/Messages/components/DisplayContent.tsx
@@ -1,13 +1,15 @@
import { deserializeParts } from '@lobechat/utils';
-import { Markdown, MarkdownProps } from '@lobehub/ui';
+import { MarkdownProps } from '@lobehub/ui';
import { memo } from 'react';
import BubblesLoading from '@/components/BubblesLoading';
import { LOADING_FLAT } from '@/const/message';
-import { RichContentRenderer } from '@/features/ChatList/components/RichContentRenderer';
-import { normalizeThinkTags, processWithArtifact } from '@/features/ChatList/utils/markdown';
+import MarkdownMessage from '@/features/Conversation/Markdown';
-const MessageContent = memo<{
+import { normalizeThinkTags, processWithArtifact } from '../../utils/markdown';
+import { RichContentRenderer } from './RichContentRenderer';
+
+const DisplayContent = memo<{
addIdOnDOM?: boolean;
content: string;
hasImages?: boolean;
@@ -34,11 +36,9 @@ const MessageContent = memo<{
return contentParts ? (
<RichContentRenderer parts={contentParts} />
) : (
- <Markdown {...markdownProps} variant={'chat'}>
- {message}
- </Markdown>
+ <MarkdownMessage {...markdownProps}>{message}</MarkdownMessage>
);
},
);
-export default MessageContent;
+export default DisplayContent;
diff --git a/src/features/ChatList/components/Extras/ExtraContainer.tsx b/src/features/Conversation/Messages/components/Extras/ExtraContainer.tsx
similarity index 100%
rename from src/features/ChatList/components/Extras/ExtraContainer.tsx
rename to src/features/Conversation/Messages/components/Extras/ExtraContainer.tsx
diff --git a/src/features/ChatList/components/Extras/TTS/FilePlayer.tsx b/src/features/Conversation/Messages/components/Extras/TTS/FilePlayer.tsx
similarity index 83%
rename from src/features/ChatList/components/Extras/TTS/FilePlayer.tsx
rename to src/features/Conversation/Messages/components/Extras/TTS/FilePlayer.tsx
index 2e80b73c5fb..99b791399b2 100644
--- a/src/features/ChatList/components/Extras/TTS/FilePlayer.tsx
+++ b/src/features/Conversation/Messages/components/Extras/TTS/FilePlayer.tsx
@@ -1,21 +1,21 @@
import { useAudioPlayer } from '@lobehub/tts/react';
import { memo, useCallback } from 'react';
-import { useChatStore } from '@/store/chat';
import { useFileStore } from '@/store/file';
+import { useConversationStore } from '../../../../store';
import { TTSProps } from './InitPlayer';
import Player from './Player';
const FilePlayer = memo<TTSProps>(({ file, id }) => {
const useFetchTTSFile = useFileStore((s) => s.useFetchTTSFile);
- const [clearTTS] = useChatStore((s) => [s.clearTTS]);
+ const clearTTS = useConversationStore((s) => s.clearTTS);
const { data, isLoading: isFileLoading } = useFetchTTSFile(file || null);
const { isLoading, ...audio } = useAudioPlayer({ src: data ? data.url : '' });
const handleDelete = useCallback(() => {
clearTTS(id);
- }, [id]);
+ }, [id, clearTTS]);
if (!audio || isFileLoading) return;
diff --git a/src/features/ChatList/components/Extras/TTS/InitPlayer.tsx b/src/features/Conversation/Messages/components/Extras/TTS/InitPlayer.tsx
similarity index 92%
rename from src/features/ChatList/components/Extras/TTS/InitPlayer.tsx
rename to src/features/Conversation/Messages/components/Extras/TTS/InitPlayer.tsx
index 111ac065d20..07582915a42 100644
--- a/src/features/ChatList/components/Extras/TTS/InitPlayer.tsx
+++ b/src/features/Conversation/Messages/components/Extras/TTS/InitPlayer.tsx
@@ -4,9 +4,9 @@ import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useTTS } from '@/hooks/useTTS';
-import { useChatStore } from '@/store/chat';
import { useFileStore } from '@/store/file';
+import { useConversationStore } from '../../../../store';
import Player from './Player';
export interface TTSProps extends ChatTTS {
@@ -21,7 +21,7 @@ const InitPlayer = memo<TTSProps>(({ id, content, contentMd5, file }) => {
const uploadTTS = useFileStore((s) => s.uploadTTSByArrayBuffers);
const { t } = useTranslation('chat');
- const [ttsMessage, clearTTS] = useChatStore((s) => [s.ttsMessage, s.clearTTS]);
+ const [ttsMessage, clearTTS] = useConversationStore((s) => [s.ttsMessage, s.clearTTS]);
const setDefaultError = useCallback(
(err?: any) => {
@@ -64,7 +64,7 @@ const InitPlayer = memo<TTSProps>(({ id, content, contentMd5, file }) => {
const handleDelete = useCallback(() => {
stop();
clearTTS(id);
- }, [stop, id]);
+ }, [stop, id, clearTTS]);
const handleRetry = useCallback(() => {
setError(undefined);
diff --git a/src/features/ChatList/components/Extras/TTS/Player.tsx b/src/features/Conversation/Messages/components/Extras/TTS/Player.tsx
similarity index 100%
rename from src/features/ChatList/components/Extras/TTS/Player.tsx
rename to src/features/Conversation/Messages/components/Extras/TTS/Player.tsx
diff --git a/src/features/ChatList/components/Extras/TTS/index.tsx b/src/features/Conversation/Messages/components/Extras/TTS/index.tsx
similarity index 94%
rename from src/features/ChatList/components/Extras/TTS/index.tsx
rename to src/features/Conversation/Messages/components/Extras/TTS/index.tsx
index 4542ddc76ed..dc0e5d4e320 100644
--- a/src/features/ChatList/components/Extras/TTS/index.tsx
+++ b/src/features/Conversation/Messages/components/Extras/TTS/index.tsx
@@ -2,7 +2,7 @@ import { memo, useMemo } from 'react';
import { Md5 } from 'ts-md5';
import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/slices/chat';
+import { agentSelectors } from '@/store/agent/selectors';
import { useGlobalStore } from '@/store/global';
import { globalGeneralSelectors } from '@/store/global/selectors';
diff --git a/src/features/ChatList/components/Extras/Translate.tsx b/src/features/Conversation/Messages/components/Extras/Translate.tsx
similarity index 94%
rename from src/features/ChatList/components/Extras/Translate.tsx
rename to src/features/Conversation/Messages/components/Extras/Translate.tsx
index 288e180bcd0..5e324919d8b 100644
--- a/src/features/ChatList/components/Extras/Translate.tsx
+++ b/src/features/Conversation/Messages/components/Extras/Translate.tsx
@@ -8,7 +8,8 @@ import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
import BubblesLoading from '@/components/BubblesLoading';
-import { useChatStore } from '@/store/chat';
+
+import { useConversationStore } from '../../../store';
interface TranslateProps extends ChatTranslate {
id: string;
@@ -19,7 +20,7 @@ const Translate = memo<TranslateProps>(({ content = '', from, to, id, loading })
const theme = useTheme();
const { t } = useTranslation('common');
const [show, setShow] = useState(true);
- const clearTranslate = useChatStore((s) => s.clearTranslate);
+ const clearTranslate = useConversationStore((s) => s.clearTranslate);
const { message } = App.useApp();
return (
diff --git a/src/features/ChatList/components/Extras/Usage/UsageDetail/AnimatedNumber.tsx b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/AnimatedNumber.tsx
similarity index 100%
rename from src/features/ChatList/components/Extras/Usage/UsageDetail/AnimatedNumber.tsx
rename to src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/AnimatedNumber.tsx
diff --git a/src/features/ChatList/components/Extras/Usage/UsageDetail/ModelCard.tsx b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/ModelCard.tsx
similarity index 100%
rename from src/features/ChatList/components/Extras/Usage/UsageDetail/ModelCard.tsx
rename to src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/ModelCard.tsx
diff --git a/src/features/ChatList/components/Extras/Usage/UsageDetail/TokenProgress.tsx b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/TokenProgress.tsx
similarity index 100%
rename from src/features/ChatList/components/Extras/Usage/UsageDetail/TokenProgress.tsx
rename to src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/TokenProgress.tsx
diff --git a/src/features/ChatList/components/Extras/Usage/UsageDetail/index.tsx b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/index.tsx
similarity index 96%
rename from src/features/ChatList/components/Extras/Usage/UsageDetail/index.tsx
rename to src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/index.tsx
index f2f9b8c40ab..deaff40097f 100644
--- a/src/features/ChatList/components/Extras/Usage/UsageDetail/index.tsx
+++ b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/index.tsx
@@ -8,7 +8,6 @@ import { useTranslation } from 'react-i18next';
import { Center, Flexbox } from 'react-layout-kit';
import InfoTooltip from '@/components/InfoTooltip';
-import { useIsMobile } from '@/hooks/useIsMobile';
import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
@@ -29,7 +28,6 @@ interface TokenDetailProps {
const TokenDetail = memo<TokenDetailProps>(({ usage, performance, model, provider }) => {
const { t } = useTranslation('chat');
const theme = useTheme();
- const isMobile = useIsMobile();
// 使用 systemStatus 管理短格式显示状态
const isShortFormat = useGlobalStore(systemStatusSelectors.tokenDisplayFormatShort);
@@ -218,21 +216,18 @@ const TokenDetail = memo<TokenDetailProps>(({ usage, performance, model, provide
</Flexbox>
}
placement={'top'}
- trigger={isMobile ? ['click'] : ['hover']}
+ trigger={['hover']}
>
<Center
gap={2}
horizontal
onClick={(e) => {
- // 移动端:让 Popover 处理点击事件
- if (isMobile) return;
-
- // 桌面端:阻止 Popover 并切换格式
+ // 阻止 Popover 并切换格式
e.preventDefault();
e.stopPropagation();
updateSystemStatus({ tokenDisplayFormatShort: !isShortFormat });
}}
- style={{ cursor: isMobile ? 'default' : 'pointer' }}
+ style={{ cursor: 'pointer' }}
>
<Icon icon={isShowCredit ? BadgeCent : CoinsIcon} />
<AnimatedNumber
diff --git a/src/features/ChatList/components/Extras/Usage/UsageDetail/pricing.ts b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/pricing.ts
similarity index 100%
rename from src/features/ChatList/components/Extras/Usage/UsageDetail/pricing.ts
rename to src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/pricing.ts
diff --git a/src/features/ChatList/components/Extras/Usage/UsageDetail/tokens.ts b/src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/tokens.ts
similarity index 100%
rename from src/features/ChatList/components/Extras/Usage/UsageDetail/tokens.ts
rename to src/features/Conversation/Messages/components/Extras/Usage/UsageDetail/tokens.ts
diff --git a/src/features/ChatList/components/Extras/Usage/index.tsx b/src/features/Conversation/Messages/components/Extras/Usage/index.tsx
similarity index 100%
rename from src/features/ChatList/components/Extras/Usage/index.tsx
rename to src/features/Conversation/Messages/components/Extras/Usage/index.tsx
diff --git a/src/features/ChatList/Messages/Assistant/FileChunks/Item/index.tsx b/src/features/Conversation/Messages/components/FileChunks/ChunkItem.tsx
similarity index 74%
rename from src/features/ChatList/Messages/Assistant/FileChunks/Item/index.tsx
rename to src/features/Conversation/Messages/components/FileChunks/ChunkItem.tsx
index 511907c2e5c..49b1a672fcc 100644
--- a/src/features/ChatList/Messages/Assistant/FileChunks/Item/index.tsx
+++ b/src/features/Conversation/Messages/components/FileChunks/ChunkItem.tsx
@@ -4,7 +4,6 @@ import { memo } from 'react';
import { Center, Flexbox } from 'react-layout-kit';
import FileIcon from '@/components/FileIcon';
-import { useIsMobile } from '@/hooks/useIsMobile';
import { useChatStore } from '@/store/chat';
import { useStyles } from './style';
@@ -14,14 +13,14 @@ export interface ChunkItemProps extends ChatFileChunk {
}
const ChunkItem = memo<ChunkItemProps>(({ id, fileId, similarity, text, filename, fileType }) => {
- const { styles, cx } = useStyles();
+ const { styles } = useStyles();
+ // Note: openFilePreview is a portal action, kept in ChatStore as it's a global UI state
const openFilePreview = useChatStore((s) => s.openFilePreview);
- const isMobile = useIsMobile();
return (
<Flexbox
align={'center'}
- className={cx(styles.container, isMobile && styles.mobile)}
+ className={styles.container}
gap={4}
horizontal
key={id}
@@ -33,13 +32,6 @@ const ChunkItem = memo<ChunkItemProps>(({ id, fileId, similarity, text, filename
<FileIcon fileName={filename} fileType={fileType} size={20} variant={'raw'} />
<Flexbox gap={12} horizontal justify={'space-between'} style={{ maxWidth: 200 }}>
<Text ellipsis>{filename}</Text>
- {/*<Typography.Text*/}
- {/* ellipsis={{ suffix: '...' }}*/}
- {/* style={{ fontSize: 12, lineHeight: 1 }}*/}
- {/* type={'secondary'}*/}
- {/*>*/}
- {/* {text}*/}
- {/*</Typography.Text>*/}
{similarity && (
<Tooltip title={similarity}>
<Center className={styles.badge}>{similarity.toFixed(1)}</Center>
diff --git a/src/features/ChatList/Messages/Assistant/FileChunks/index.tsx b/src/features/Conversation/Messages/components/FileChunks/index.tsx
similarity index 98%
rename from src/features/ChatList/Messages/Assistant/FileChunks/index.tsx
rename to src/features/Conversation/Messages/components/FileChunks/index.tsx
index d38b1581edf..a9e8c274dfa 100644
--- a/src/features/ChatList/Messages/Assistant/FileChunks/index.tsx
+++ b/src/features/Conversation/Messages/components/FileChunks/index.tsx
@@ -6,7 +6,7 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
-import ChunkItem from './Item';
+import ChunkItem from './ChunkItem';
const useStyles = createStyles(({ css, token, isDarkMode }) => ({
container: css`
diff --git a/src/tools/knowledge-base/Render/SearchKnowledgeBase/Item/style.ts b/src/features/Conversation/Messages/components/FileChunks/style.ts
similarity index 100%
rename from src/tools/knowledge-base/Render/SearchKnowledgeBase/Item/style.ts
rename to src/features/Conversation/Messages/components/FileChunks/style.ts
diff --git a/src/features/Conversation/Messages/components/ImageFileListViewer.tsx b/src/features/Conversation/Messages/components/ImageFileListViewer.tsx
new file mode 100644
index 00000000000..9cc25765110
--- /dev/null
+++ b/src/features/Conversation/Messages/components/ImageFileListViewer.tsx
@@ -0,0 +1,27 @@
+import { PreviewGroup } from '@lobehub/ui';
+import { memo } from 'react';
+
+import GalleyGrid from '@/components/GalleyGrid';
+import ImageItem from '@/components/ImageItem';
+
+interface ImageFileItem {
+ alt?: string;
+ id: string;
+ loading?: boolean;
+ onRemove?: (id: string) => void;
+ url: string;
+}
+
+interface FileListProps {
+ items: ImageFileItem[];
+}
+
+const ImageFileListViewer = memo<FileListProps>(({ items }) => {
+ return (
+ <PreviewGroup>
+ <GalleyGrid items={items} renderItem={ImageItem} />
+ </PreviewGroup>
+ );
+});
+
+export default ImageFileListViewer;
diff --git a/src/features/ChatList/Messages/Assistant/IntentUnderstanding.tsx b/src/features/Conversation/Messages/components/IntentUnderstanding.tsx
similarity index 100%
rename from src/features/ChatList/Messages/Assistant/IntentUnderstanding.tsx
rename to src/features/Conversation/Messages/components/IntentUnderstanding.tsx
diff --git a/src/features/ChatList/Messages/User/Actions/MessageBranch.tsx b/src/features/Conversation/Messages/components/MessageBranch.tsx
similarity index 94%
rename from src/features/ChatList/Messages/User/Actions/MessageBranch.tsx
rename to src/features/Conversation/Messages/components/MessageBranch.tsx
index 91eb6824349..78726d6d6af 100644
--- a/src/features/ChatList/Messages/User/Actions/MessageBranch.tsx
+++ b/src/features/Conversation/Messages/components/MessageBranch.tsx
@@ -4,7 +4,7 @@ import { ChevronLeft, ChevronRight } from 'lucide-react';
import { memo } from 'react';
import { Center, Flexbox } from 'react-layout-kit';
-import { useChatStore } from '@/store/chat';
+import { useConversationStore } from '../../store';
const useStyles = createStyles(({ css, token, prefixCls }) => ({
button: css`
@@ -62,7 +62,7 @@ interface MessageBranchProps {
const MessageBranch = memo<MessageBranchProps>(({ activeBranchIndex, count, messageId }) => {
const { styles, cx, prefixCls } = useStyles();
- const switchMessageBranch = useChatStore((s) => s.switchMessageBranch);
+ const switchMessageBranch = useConversationStore((s) => s.switchMessageBranch);
const handlePrevious = () => {
if (activeBranchIndex > 0) {
diff --git a/src/features/ChatList/Messages/Assistant/Reasoning/index.tsx b/src/features/Conversation/Messages/components/Reasoning.tsx
similarity index 81%
rename from src/features/ChatList/Messages/Assistant/Reasoning/index.tsx
rename to src/features/Conversation/Messages/components/Reasoning.tsx
index 182572f7018..7cb4bd51379 100644
--- a/src/features/ChatList/Messages/Assistant/Reasoning/index.tsx
+++ b/src/features/Conversation/Messages/components/Reasoning.tsx
@@ -3,12 +3,11 @@ import { deserializeParts } from '@lobechat/utils';
import { memo } from 'react';
import Thinking from '@/components/Thinking';
-import { useChatStore } from '@/store/chat';
-import { aiChatSelectors } from '@/store/chat/selectors';
+import { RichContentRenderer } from './RichContentRenderer';
import { useUserStore } from '@/store/user';
import { userGeneralSettingsSelectors } from '@/store/user/selectors';
-import { RichContentRenderer } from '../../../components/RichContentRenderer';
+import { messageStateSelectors, useConversationStore } from '../../store';
interface ReasoningProps {
content?: string;
@@ -20,7 +19,7 @@ interface ReasoningProps {
const Reasoning = memo<ReasoningProps>(
({ content = '', duration, id, isMultimodal, tempDisplayContent }) => {
- const isReasoning = useChatStore(aiChatSelectors.isMessageInReasoning(id));
+ const isReasoning = useConversationStore(messageStateSelectors.isMessageInReasoning(id));
const transitionMode = useUserStore(userGeneralSettingsSelectors.transitionMode);
const parts = tempDisplayContent || deserializeParts(content);
diff --git a/src/features/ChatList/components/RichContentRenderer.tsx b/src/features/Conversation/Messages/components/RichContentRenderer.tsx
similarity index 100%
rename from src/features/ChatList/components/RichContentRenderer.tsx
rename to src/features/Conversation/Messages/components/RichContentRenderer.tsx
diff --git a/src/features/ChatList/Messages/Assistant/SearchGrounding.tsx b/src/features/Conversation/Messages/components/SearchGrounding.tsx
similarity index 98%
rename from src/features/ChatList/Messages/Assistant/SearchGrounding.tsx
rename to src/features/Conversation/Messages/components/SearchGrounding.tsx
index d036f60bad5..48f936a29a2 100644
--- a/src/features/ChatList/Messages/Assistant/SearchGrounding.tsx
+++ b/src/features/Conversation/Messages/components/SearchGrounding.tsx
@@ -1,7 +1,7 @@
import { Icon, SearchResultCards, Tag } from '@lobehub/ui';
import { createStyles } from 'antd-style';
-import { AnimatePresence, motion } from 'framer-motion';
import { ChevronDown, ChevronRight, Globe } from 'lucide-react';
+import { AnimatePresence, m as motion } from 'motion/react';
import Image from 'next/image';
import { rgba } from 'polished';
import { memo, useState } from 'react';
diff --git a/src/features/Conversation/Messages/components/useNewScreen.ts b/src/features/Conversation/Messages/components/useNewScreen.ts
new file mode 100644
index 00000000000..b747a96523e
--- /dev/null
+++ b/src/features/Conversation/Messages/components/useNewScreen.ts
@@ -0,0 +1,16 @@
+import { useEffect, useState } from 'react';
+
+export const useNewScreen = ({
+ isLatestItem,
+ creating,
+}: {
+ creating?: boolean;
+ isLatestItem?: boolean;
+}) => {
+ const [newScreen, setNewScreen] = useState(false);
+ useEffect(() => {
+ if (!isLatestItem) setNewScreen(false);
+ if (isLatestItem && creating) setNewScreen(true);
+ }, [isLatestItem, creating]);
+ return newScreen;
+};
diff --git a/src/features/ChatList/Messages/index.tsx b/src/features/Conversation/Messages/index.tsx
similarity index 54%
rename from src/features/ChatList/Messages/index.tsx
rename to src/features/Conversation/Messages/index.tsx
index 3247a19a9bf..c68fe5e4504 100644
--- a/src/features/ChatList/Messages/index.tsx
+++ b/src/features/Conversation/Messages/index.tsx
@@ -3,25 +3,34 @@
import { isDesktop } from '@lobechat/const';
import { createStyles } from 'antd-style';
import isEqual from 'fast-deep-equal';
-import { useSearchParams } from 'next/navigation';
-import { MouseEvent, ReactNode, memo, use, useCallback, useEffect, useRef } from 'react';
+import {
+ MouseEvent,
+ ReactNode,
+ RefObject,
+ Suspense,
+ memo,
+ useCallback,
+ useMemo,
+ useRef,
+} from 'react';
import { Flexbox } from 'react-layout-kit';
+import type { VListHandle } from 'virtua';
-import {
- VirtuaContext,
- removeVirtuaVisibleItem,
- upsertVirtuaVisibleItem,
-} from '@/features/ChatList/components/VirtualizedList/VirtuosoContext';
-import { getChatStoreState, useChatStore } from '@/store/chat';
-import { displayMessageSelectors, messageStateSelectors } from '@/store/chat/selectors';
+import BubblesLoading from '@/components/BubblesLoading';
import ContextMenu from '../components/ContextMenu';
import History from '../components/History';
-import { InPortalThreadContext } from '../context/InPortalThreadContext';
import { useChatItemContextMenu } from '../hooks/useChatItemContextMenu';
+import {
+ dataSelectors,
+ messageStateSelectors,
+ useConversationStore,
+ virtuaListSelectors,
+} from '../store';
+import AgentCouncilMessage from './AgentCouncil';
import AssistantMessage from './Assistant';
-import GroupMessage from './Group';
-import SupervisorMessage from './Supervisor';
+import AssistantGroupMessage from './AssistantGroup';
+import TaskMessage from './Task';
import ToolMessage from './Tool';
import UserMessage from './User';
@@ -38,7 +47,7 @@ const useStyles = createStyles(({ css, prefixCls }) => ({
`,
}));
-export interface ChatListItemProps {
+export interface MessageItemProps {
className?: string;
disableEditing?: boolean;
enableHistoryDivider?: boolean;
@@ -49,7 +58,7 @@ export interface ChatListItemProps {
isLatestItem?: boolean;
}
-const Item = memo<ChatListItemProps>(
+const MessageItem = memo<MessageItemProps>(
({
className,
enableHistoryDivider,
@@ -62,25 +71,24 @@ const Item = memo<ChatListItemProps>(
}) => {
const { styles, cx } = useStyles();
const containerRef = useRef<HTMLDivElement | null>(null);
- const virtuaRef = use(VirtuaContext);
- const searchParams = useSearchParams();
- const topic = searchParams.get('topic');
-
- const [role, editing, isMessageCreating] = useChatStore((s) => {
- const item = displayMessageSelectors.getDisplayMessageById(id)(s);
- return [
- item?.role,
- messageStateSelectors.isMessageEditing(id)(s),
- messageStateSelectors.isMessageCreating(id)(s),
- ];
- }, isEqual);
+
+ const topic = useConversationStore((s) => s.context.topicId);
+
+ // Get message and actionsBar from ConversationStore
+ const message = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual);
+ const actionsBar = useConversationStore((s) => s.actionsBar);
+ const role = message?.role;
+
+ const [editing, isMessageCreating] = useConversationStore((s) => [
+ messageStateSelectors.isMessageEditing(id)(s),
+ messageStateSelectors.isMessageCreating(id)(s),
+ ]);
const {
containerRef: contextMenuContainerRef,
contextMenuState,
handleContextMenu,
hideContextMenu,
- contextMenuMode,
} = useChatItemContextMenu({
editing,
onActionClick: () => {},
@@ -94,64 +102,20 @@ const Item = memo<ChatListItemProps>(
[contextMenuContainerRef],
);
- // ======================= Performance Optimization ======================= //
- useEffect(() => {
- if (typeof window === 'undefined' || typeof IntersectionObserver === 'undefined') return;
-
- const element = containerRef.current;
- if (!element) return;
-
- const root = element.closest('[data-virtuoso-scroller]');
- const thresholds = [0, 0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 1];
- const options: any = { threshold: thresholds };
-
- if (root instanceof Element) options.root = root;
-
- const observer = new IntersectionObserver((entries) => {
- entries.forEach((entry) => {
- if (entry.target !== element) return;
-
- if (entry.isIntersecting) {
- const { bottom, top } = entry.intersectionRect;
-
- upsertVirtuaVisibleItem(index, {
- bottom,
- ratio: entry.intersectionRatio,
- top,
- });
- } else {
- removeVirtuaVisibleItem(index);
- }
- });
- }, options);
-
- observer.observe(element);
-
- return () => {
- observer.disconnect();
- removeVirtuaVisibleItem(index);
- };
- }, [index]);
-
const onContextMenu = useCallback(
async (event: MouseEvent<HTMLDivElement>) => {
if (!role || (role !== 'user' && role !== 'assistant')) return;
- const item = displayMessageSelectors.getDisplayMessageById(id)(getChatStoreState());
- if (!item) return;
+ if (!message) return;
if (isDesktop) {
- if (contextMenuMode !== 'disabled') {
- handleContextMenu(event);
- return;
- }
const { electronSystemService } = await import('@/services/electron/system');
electronSystemService.showContextMenu('chat', {
- content: item.content,
- hasError: !!item.error,
+ content: message.content,
+ hasError: !!message.error,
messageId: id,
- role: item.role,
+ role: message.role,
});
return;
@@ -159,7 +123,16 @@ const Item = memo<ChatListItemProps>(
handleContextMenu(event);
},
- [handleContextMenu, id, role],
+ [handleContextMenu, id, role, message],
+ );
+ // Get virtuaScrollMethods from ConversationStore
+ const virtuaScrollMethods = useConversationStore(virtuaListSelectors.virtuaScrollMethods);
+
+ // Create a ref-like object for ContextMenu compatibility
+ // VirtuaScrollMethods is a subset of VListHandle with the methods ContextMenu needs
+ const virtuaRef = useMemo<RefObject<VListHandle | null>>(
+ () => ({ current: virtuaScrollMethods as VListHandle | null }),
+ [virtuaScrollMethods],
);
const renderContent = useCallback(() => {
@@ -181,7 +154,17 @@ const Item = memo<ChatListItemProps>(
case 'assistantGroup': {
return (
- <GroupMessage
+ <AssistantGroupMessage
+ disableEditing={disableEditing}
+ id={id}
+ index={index}
+ isLatestItem={isLatestItem}
+ />
+ );
+ }
+ case 'task': {
+ return (
+ <TaskMessage
disableEditing={disableEditing}
id={id}
index={index}
@@ -190,22 +173,22 @@ const Item = memo<ChatListItemProps>(
);
}
- case 'tool': {
- return <ToolMessage id={id} index={index} />;
+ case 'agentCouncil': {
+ return <AgentCouncilMessage id={id} index={index} />;
}
- case 'supervisor': {
- return <SupervisorMessage disableEditing={disableEditing} id={id} index={index} />;
+ case 'tool': {
+ return <ToolMessage id={id} index={index} />;
}
}
return null;
- }, [role, disableEditing, id, index, isLatestItem]);
+ }, [role, disableEditing, id, index, isLatestItem, actionsBar]);
if (!role) return;
return (
- <InPortalThreadContext.Provider value={inPortalThread}>
+ <>
{enableHistoryDivider && <History />}
<Flexbox
className={cx(styles.message, className, isMessageCreating && styles.loading)}
@@ -213,7 +196,7 @@ const Item = memo<ChatListItemProps>(
onContextMenu={onContextMenu}
ref={setContainerRef}
>
- {renderContent()}
+ <Suspense fallback={<BubblesLoading />}>{renderContent()}</Suspense>
{endRender}
</Flexbox>
<ContextMenu
@@ -227,12 +210,12 @@ const Item = memo<ChatListItemProps>(
virtuaRef={virtuaRef}
visible={contextMenuState.visible}
/>
- </InPortalThreadContext.Provider>
+ </>
);
},
isEqual,
);
-Item.displayName = 'ChatItem';
+MessageItem.displayName = 'MessageItem';
-export default Item;
+export default MessageItem;
diff --git a/src/features/Conversation/StoreUpdater.tsx b/src/features/Conversation/StoreUpdater.tsx
new file mode 100644
index 00000000000..8a8b0500ceb
--- /dev/null
+++ b/src/features/Conversation/StoreUpdater.tsx
@@ -0,0 +1,81 @@
+'use client';
+
+import type { UIChatMessage } from '@lobechat/types';
+import { memo, useEffect } from 'react';
+import { createStoreUpdater } from 'zustand-utils';
+
+import { useConversationStoreApi } from './store';
+import type {
+ ActionsBarConfig,
+ ConversationContext,
+ ConversationHooks,
+ OperationState,
+} from './types';
+
+export interface StoreUpdaterProps {
+ /**
+ * Actions bar configuration by message type
+ */
+ actionsBar?: ActionsBarConfig;
+ context: ConversationContext;
+ /**
+ * Whether external messages have been initialized
+ */
+ hasInitMessages?: boolean;
+ hooks?: ConversationHooks;
+ /**
+ * External messages to sync into the store
+ */
+ messages?: UIChatMessage[];
+ /**
+ * Callback when messages are fetched or changed internally
+ */
+ onMessagesChange?: (messages: UIChatMessage[]) => void;
+ /**
+ * External operation state (from ChatStore)
+ */
+ operationState?: OperationState;
+ /**
+ * Skip internal message fetching (when external messages are provided)
+ */
+ skipFetch?: boolean;
+}
+
+const StoreUpdater = memo<StoreUpdaterProps>(
+ ({
+ actionsBar,
+ context,
+ hasInitMessages,
+ hooks,
+ messages,
+ onMessagesChange,
+ operationState,
+ skipFetch,
+ }) => {
+ const storeApi = useConversationStoreApi();
+ const useStoreUpdater = createStoreUpdater(storeApi);
+
+ useStoreUpdater('actionsBar', actionsBar);
+ useStoreUpdater('context', context);
+ useStoreUpdater('hooks', hooks!);
+ useStoreUpdater('onMessagesChange', onMessagesChange);
+ useStoreUpdater('operationState', operationState!);
+ useStoreUpdater('skipFetch', skipFetch!);
+
+ // When external messages are provided, mark as initialized
+ useStoreUpdater('messagesInit', skipFetch ? true : (hasInitMessages ?? false));
+
+ // Sync external messages into store
+ useEffect(() => {
+ if (messages) {
+ storeApi.getState().replaceMessages(messages);
+ }
+ }, [messages, storeApi]);
+
+ return null;
+ },
+);
+
+StoreUpdater.displayName = 'ConversationStoreUpdater';
+
+export default StoreUpdater;
diff --git a/src/features/ChatList/components/ContextMenu.tsx b/src/features/Conversation/components/ContextMenu.tsx
similarity index 93%
rename from src/features/ChatList/components/ContextMenu.tsx
rename to src/features/Conversation/components/ContextMenu.tsx
index 7ba67941d7c..8ca53d9a741 100644
--- a/src/features/ChatList/components/ContextMenu.tsx
+++ b/src/features/Conversation/components/ContextMenu.tsx
@@ -21,16 +21,16 @@ import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
import type { VListHandle } from 'virtua';
-import { getChatStoreState, useChatStore } from '@/store/chat';
-import {
- displayMessageSelectors,
- messageStateSelectors,
- threadSelectors,
-} from '@/store/chat/selectors';
import { useSessionStore } from '@/store/session';
import { sessionSelectors } from '@/store/session/selectors';
import { useChatListActionsBar } from '../hooks/useChatListActionsBar';
+import {
+ dataSelectors,
+ messageStateSelectors,
+ useConversationStore,
+ useConversationStoreApi,
+} from '../store';
import ShareMessageModal from './ShareMessageModal';
interface ActionMenuItem extends ActionIconGroupItemType {
@@ -73,7 +73,7 @@ interface ContextMenuProps {
onClose: () => void;
position: { x: number; y: number };
selectedText?: string;
- topic: string | null;
+ topic?: string | null;
virtuaRef?: RefObject<VListHandle | null> | null;
visible: boolean;
}
@@ -86,18 +86,20 @@ const ContextMenu = memo<ContextMenuProps>(
const [shareMessage, setShareMessage] = useState<UIChatMessage | null>(null);
const [isShareModalOpen, setShareModalOpen] = useState(false);
- const [role, error, isCollapsed, hasThread, isRegenerating] = useChatStore((s) => {
- const item = displayMessageSelectors.getDisplayMessageById(id)(s);
+ const storeApi = useConversationStoreApi();
+
+ const [role, error, isCollapsed, hasThread, isRegenerating] = useConversationStore((s) => {
+ const item = dataSelectors.getDisplayMessageById(id)(s);
return [
item?.role,
item?.error,
messageStateSelectors.isMessageCollapsed(id)(s),
- threadSelectors.hasThreadBySourceMsgId(id)(s),
+ messageStateSelectors.hasThreadBySourceMsgId(id)(s),
messageStateSelectors.isMessageRegenerating(id)(s),
];
}, isEqual);
- const isThreadMode = useChatStore((s) => !!s.activeThreadId);
+ const isThreadMode = useConversationStore(messageStateSelectors.isThreadMode);
const isGroupSession = useSessionStore(sessionSelectors.isCurrentSessionGroupSession);
const actionsBar = useChatListActionsBar({ hasThread, isRegenerating });
const inThread = isThreadMode || inPortalThread;
@@ -115,7 +117,7 @@ const ContextMenu = memo<ContextMenuProps>(
resendThreadMessage,
delAndResendThreadMessage,
toggleMessageCollapsed,
- ] = useChatStore((s) => [
+ ] = useConversationStore((s) => [
s.toggleMessageEditing,
s.deleteMessage,
s.regenerateUserMessage,
@@ -131,8 +133,8 @@ const ContextMenu = memo<ContextMenuProps>(
]);
const getMessage = useCallback(
- () => displayMessageSelectors.getDisplayMessageById(id)(getChatStoreState()),
- [id],
+ () => dataSelectors.getDisplayMessageById(id)(storeApi.getState()),
+ [id, storeApi],
);
const menuItems = useMemo<MenuItem[]>(() => {
@@ -209,12 +211,11 @@ const ContextMenu = memo<ContextMenuProps>(
const item = getMessage();
if (!item) return;
- if (action.key === 'edit') {
- toggleMessageEditing(id, true);
- virtuaRef?.current?.scrollToIndex(index, { align: 'start' });
- }
-
switch (action.key) {
+ case 'edit': {
+ toggleMessageEditing(id, true);
+ break;
+ }
case 'copy': {
await copyMessage(id, item.content);
message.success(t('copySuccess'));
diff --git a/src/features/ChatList/components/History/HistoryDivider.tsx b/src/features/Conversation/components/History/HistoryDivider.tsx
similarity index 81%
rename from src/features/ChatList/components/History/HistoryDivider.tsx
rename to src/features/Conversation/components/History/HistoryDivider.tsx
index 4fa969ca2f7..de8ed8f77f8 100644
--- a/src/features/ChatList/components/History/HistoryDivider.tsx
+++ b/src/features/Conversation/components/History/HistoryDivider.tsx
@@ -15,9 +15,7 @@ const HistoryDivider = memo<HistoryDividerProps>(({ enable }) => {
return (
<div style={{ padding: '0 20px' }}>
<Divider style={{ margin: 0, padding: '20px 0' }}>
- <Tag icon={<Icon icon={Timer} />}>
- {t('historyRange', { defaultValue: 'History Message' })}
- </Tag>
+ <Tag icon={<Icon icon={Timer} />}>{t('historyRange')}</Tag>
</Divider>
</div>
);
diff --git a/src/features/ChatList/components/History/index.tsx b/src/features/Conversation/components/History/index.tsx
similarity index 90%
rename from src/features/ChatList/components/History/index.tsx
rename to src/features/Conversation/components/History/index.tsx
index 55414d43568..4393fc47cc4 100644
--- a/src/features/ChatList/components/History/index.tsx
+++ b/src/features/Conversation/components/History/index.tsx
@@ -8,9 +8,8 @@ import { Center, Flexbox } from 'react-layout-kit';
import { agentChatConfigSelectors } from '@/store/agent/selectors';
import { useAgentStore } from '@/store/agent/store';
-import { useChatStore } from '@/store/chat';
-import { topicSelectors } from '@/store/chat/selectors';
+import { dataSelectors, useConversationStore } from '../../store';
import HistoryDivider from './HistoryDivider';
const useStyles = createStyles(({ css, token }) => ({
@@ -31,8 +30,8 @@ const useStyles = createStyles(({ css, token }) => ({
const History = memo(() => {
const { styles, theme } = useStyles();
const { t } = useTranslation('chat');
- const [content, model] = useChatStore((s) => {
- const history = topicSelectors.currentActiveTopicSummary(s);
+ const [content, model] = useConversationStore(() => {
+ const history = dataSelectors.currentTopicSummary();
return [history?.content, history?.model];
});
diff --git a/src/features/ChatList/components/ShareMessageModal/ShareImage/Preview.tsx b/src/features/Conversation/components/ShareMessageModal/ShareImage/Preview.tsx
similarity index 74%
rename from src/features/ChatList/components/ShareMessageModal/ShareImage/Preview.tsx
rename to src/features/Conversation/components/ShareMessageModal/ShareImage/Preview.tsx
index 2b96a4c56f7..0a1eb29f590 100644
--- a/src/features/ChatList/components/ShareMessageModal/ShareImage/Preview.tsx
+++ b/src/features/Conversation/components/ShareMessageModal/ShareImage/Preview.tsx
@@ -8,13 +8,12 @@ import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
import { ProductLogo } from '@/components/Branding';
-import { ChatItem } from '@/features/ChatList';
+import { ChatItem } from '@/features/Conversation/ChatItem';
import PluginTag from '@/features/PluginTag';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
-import { useSessionStore } from '@/store/session';
-import { sessionMetaSelectors, sessionSelectors } from '@/store/session/selectors';
+import { useAgentMeta, useIsBuiltinAgent } from '../../../hooks';
import { useContainerStyles } from '../style';
import { useStyles } from './style';
import { FieldType } from './type';
@@ -32,19 +31,15 @@ const Preview = memo<PreviewProps>(
agentSelectors.displayableAgentPlugins(s),
]);
- const [isInbox, description, avatar, backgroundColor] = useSessionStore((s) => [
- sessionSelectors.isInboxSession(s),
- sessionMetaSelectors.currentAgentDescription(s),
- sessionMetaSelectors.currentAgentAvatar(s),
- sessionMetaSelectors.currentAgentBackgroundColor(s),
- ]);
+ const agentMeta = useAgentMeta(message.agentId);
+ const isBuiltinAgent = useIsBuiltinAgent();
const { t } = useTranslation('chat');
const { styles } = useStyles(withBackground);
const { styles: containerStyles } = useContainerStyles();
- const displayTitle = isInbox ? t('inbox.title') : title;
- const displayDesc = isInbox ? t('inbox.desc') : description;
+ const displayTitle = agentMeta.title || title;
+ const displayDesc = isBuiltinAgent ? t('inbox.desc') : agentMeta.description;
return (
<div className={containerStyles.preview}>
@@ -52,7 +47,13 @@ const Preview = memo<PreviewProps>(
<Flexbox className={styles.container} gap={16}>
<div className={styles.header}>
<Flexbox align={'flex-start'} gap={12} horizontal>
- <Avatar avatar={avatar} background={backgroundColor} size={40} title={title} />
+ <Avatar
+ avatar={agentMeta.avatar}
+ background={agentMeta.backgroundColor}
+ shape={'square'}
+ size={40}
+ title={displayTitle}
+ />
<ChatHeaderTitle
desc={displayDesc}
tag={
@@ -70,7 +71,14 @@ const Preview = memo<PreviewProps>(
style={{ paddingTop: 24, position: 'relative' }}
width={'100%'}
>
- <ChatItem id={message.id} index={0} />
+ <ChatItem
+ avatar={{
+ avatar: agentMeta.avatar,
+ backgroundColor: agentMeta.backgroundColor,
+ title: displayTitle,
+ }}
+ id={message.id}
+ />
</Flexbox>
{withFooter ? (
<Flexbox align={'center'} className={styles.footer} gap={4}>
diff --git a/src/features/ChatList/components/ShareMessageModal/ShareImage/index.tsx b/src/features/Conversation/components/ShareMessageModal/ShareImage/index.tsx
similarity index 93%
rename from src/features/ChatList/components/ShareMessageModal/ShareImage/index.tsx
rename to src/features/Conversation/components/ShareMessageModal/ShareImage/index.tsx
index 2ec3d464202..92d44d92063 100644
--- a/src/features/ChatList/components/ShareMessageModal/ShareImage/index.tsx
+++ b/src/features/Conversation/components/ShareMessageModal/ShareImage/index.tsx
@@ -10,8 +10,8 @@ import { FORM_STYLE } from '@/const/layoutTokens';
import { useImgToClipboard } from '@/hooks/useImgToClipboard';
import { useIsMobile } from '@/hooks/useIsMobile';
import { ImageType, imageTypeOptions, useScreenshot } from '@/hooks/useScreenshot';
-import { useSessionStore } from '@/store/session';
-import { sessionMetaSelectors } from '@/store/session/selectors';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
import { useStyles } from '../style';
import Preview from './Preview';
@@ -25,7 +25,7 @@ const DEFAULT_FIELD_VALUE: FieldType = {
const ShareImage = memo<{ message: UIChatMessage; mobile?: boolean; uniqueId?: string }>(
({ message, uniqueId }) => {
- const currentAgentTitle = useSessionStore(sessionMetaSelectors.currentAgentTitle);
+ const currentAgentTitle = useAgentStore(agentSelectors.currentAgentTitle);
const [fieldValue, setFieldValue] = useState<FieldType>(DEFAULT_FIELD_VALUE);
const { t } = useTranslation(['chat', 'common']);
const { styles } = useStyles();
@@ -36,7 +36,7 @@ const ShareImage = memo<{ message: UIChatMessage; mobile?: boolean; uniqueId?: s
const { loading, onDownload, title } = useScreenshot({
id: `#${previewId}`,
imageType: fieldValue.imageType,
- title: currentAgentTitle,
+ title: currentAgentTitle ?? undefined,
});
const { loading: copyLoading, onCopy } = useImgToClipboard({ id: `#${previewId}` });
const settings: FormItemProps[] = [
diff --git a/src/features/ChatList/components/ShareMessageModal/ShareImage/style.ts b/src/features/Conversation/components/ShareMessageModal/ShareImage/style.ts
similarity index 100%
rename from src/features/ChatList/components/ShareMessageModal/ShareImage/style.ts
rename to src/features/Conversation/components/ShareMessageModal/ShareImage/style.ts
diff --git a/src/features/ChatList/components/ShareMessageModal/ShareImage/type.ts b/src/features/Conversation/components/ShareMessageModal/ShareImage/type.ts
similarity index 100%
rename from src/features/ChatList/components/ShareMessageModal/ShareImage/type.ts
rename to src/features/Conversation/components/ShareMessageModal/ShareImage/type.ts
diff --git a/src/features/ChatList/components/ShareMessageModal/ShareText/Preview.tsx b/src/features/Conversation/components/ShareMessageModal/ShareText/Preview.tsx
similarity index 100%
rename from src/features/ChatList/components/ShareMessageModal/ShareText/Preview.tsx
rename to src/features/Conversation/components/ShareMessageModal/ShareText/Preview.tsx
diff --git a/src/features/ChatList/components/ShareMessageModal/ShareText/index.tsx b/src/features/Conversation/components/ShareMessageModal/ShareText/index.tsx
similarity index 95%
rename from src/features/ChatList/components/ShareMessageModal/ShareText/index.tsx
rename to src/features/Conversation/components/ShareMessageModal/ShareText/index.tsx
index fa1d48d81a2..89133223924 100644
--- a/src/features/ChatList/components/ShareMessageModal/ShareText/index.tsx
+++ b/src/features/Conversation/components/ShareMessageModal/ShareText/index.tsx
@@ -42,7 +42,7 @@ const ShareText = memo<ShareTextProps>(({ item }) => {
icon={CopyIcon}
onClick={async () => {
await copyToClipboard(content);
- message.success(t('copySuccess', { defaultValue: 'Copy Success', ns: 'common' }));
+ message.success(t('copySuccess', { ns: 'common' }));
}}
size={isMobile ? undefined : 'large'}
type={'primary'}
diff --git a/src/features/ChatList/components/ShareMessageModal/ShareText/template.test.ts b/src/features/Conversation/components/ShareMessageModal/ShareText/template.test.ts
similarity index 100%
rename from src/features/ChatList/components/ShareMessageModal/ShareText/template.test.ts
rename to src/features/Conversation/components/ShareMessageModal/ShareText/template.test.ts
diff --git a/src/features/ChatList/components/ShareMessageModal/ShareText/template.ts b/src/features/Conversation/components/ShareMessageModal/ShareText/template.ts
similarity index 91%
rename from src/features/ChatList/components/ShareMessageModal/ShareText/template.ts
rename to src/features/Conversation/components/ShareMessageModal/ShareText/template.ts
index 0a34190592c..64ff6cd57ab 100644
--- a/src/features/ChatList/components/ShareMessageModal/ShareText/template.ts
+++ b/src/features/Conversation/components/ShareMessageModal/ShareText/template.ts
@@ -1,5 +1,5 @@
import { UIChatMessage } from '@lobechat/types';
-import { template } from 'lodash-es';
+import { template } from 'es-toolkit/compat';
import { LOADING_FLAT } from '@/const/message';
diff --git a/src/features/ChatList/components/ShareMessageModal/ShareText/type.ts b/src/features/Conversation/components/ShareMessageModal/ShareText/type.ts
similarity index 100%
rename from src/features/ChatList/components/ShareMessageModal/ShareText/type.ts
rename to src/features/Conversation/components/ShareMessageModal/ShareText/type.ts
diff --git a/src/features/ChatList/components/ShareMessageModal/index.tsx b/src/features/Conversation/components/ShareMessageModal/index.tsx
similarity index 100%
rename from src/features/ChatList/components/ShareMessageModal/index.tsx
rename to src/features/Conversation/components/ShareMessageModal/index.tsx
diff --git a/src/features/ChatList/components/ShareMessageModal/style.ts b/src/features/Conversation/components/ShareMessageModal/style.ts
similarity index 100%
rename from src/features/ChatList/components/ShareMessageModal/style.ts
rename to src/features/Conversation/components/ShareMessageModal/style.ts
diff --git a/src/features/Conversation/components/SkeletonList.tsx b/src/features/Conversation/components/SkeletonList.tsx
new file mode 100644
index 00000000000..90951b49c47
--- /dev/null
+++ b/src/features/Conversation/components/SkeletonList.tsx
@@ -0,0 +1,60 @@
+'use client';
+
+import { Skeleton } from '@lobehub/ui';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import WideScreenContainer from '../../WideScreenContainer';
+
+const SkeletonList = memo(() => {
+ return (
+ <WideScreenContainer flex={1} gap={36} height={'100%'} padding={12} style={{ marginTop: 24 }}>
+ {/* User Message */}
+ <Flexbox
+ gap={8}
+ style={{
+ paddingLeft: '25%',
+ }}
+ width={'100%'}
+ >
+ <Skeleton.Paragraph
+ active
+ rows={3}
+ style={{
+ alignItems: 'flex-end',
+ }}
+ />
+ </Flexbox>
+
+ {/* Assistant Message */}
+ <Flexbox gap={8} width={'100%'}>
+ <Skeleton
+ active
+ avatar={{
+ shape: 'square',
+ size: 28,
+ }}
+ paragraph={false}
+ />
+ <Skeleton.Paragraph />
+ <Skeleton.Tags count={2} />
+ </Flexbox>
+
+ {/* Assistant Message */}
+ <Flexbox gap={8} width={'100%'}>
+ <Skeleton
+ active
+ avatar={{
+ shape: 'square',
+ size: 28,
+ }}
+ paragraph={false}
+ />
+ <Skeleton.Paragraph />
+ <Skeleton.Tags count={2} />
+ </Flexbox>
+ </WideScreenContainer>
+ );
+});
+
+export default SkeletonList;
diff --git a/src/features/Conversation/hooks/index.ts b/src/features/Conversation/hooks/index.ts
new file mode 100644
index 00000000000..6e431d016a5
--- /dev/null
+++ b/src/features/Conversation/hooks/index.ts
@@ -0,0 +1,2 @@
+export { useAgentMeta, useIsBuiltinAgent } from './useAgentMeta';
+export { useDoubleClickEdit } from './useDoubleClickEdit';
diff --git a/src/features/Conversation/hooks/useAgentMeta.test.ts b/src/features/Conversation/hooks/useAgentMeta.test.ts
new file mode 100644
index 00000000000..8cd09e81170
--- /dev/null
+++ b/src/features/Conversation/hooks/useAgentMeta.test.ts
@@ -0,0 +1,321 @@
+import { act, renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { useAgentStore } from '@/store/agent';
+
+import { useConversationStore } from '../store';
+import { useAgentMeta, useIsBuiltinAgent } from './useAgentMeta';
+
+vi.mock('zustand/traditional');
+
+// Mock the ConversationStore
+vi.mock('../store', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../store')>();
+ return {
+ ...actual,
+ useConversationStore: vi.fn(),
+ };
+});
+
+describe('useAgentMeta', () => {
+ it('should return agent meta for regular (non-builtin) agents', () => {
+ const mockAgentId = 'regular-agent-123';
+ const mockMeta = {
+ avatar: 'agent-avatar.png',
+ backgroundColor: '#ff0000',
+ title: 'My Custom Agent',
+ description: 'A custom agent',
+ };
+
+ // Mock ConversationStore to return agentId
+ vi.mocked(useConversationStore).mockImplementation((selector: any) => {
+ const state = { context: { agentId: mockAgentId } };
+ return selector(state);
+ });
+
+ // Mock AgentStore state
+ act(() => {
+ useAgentStore.setState({
+ agentMap: {
+ [mockAgentId]: mockMeta,
+ },
+ builtinAgentIdMap: {
+ inbox: 'inbox-agent-id',
+ pageAgent: 'page-agent-id',
+ },
+ });
+ });
+
+ const { result } = renderHook(() => useAgentMeta());
+
+ expect(result.current).toEqual(mockMeta);
+ expect(result.current.title).toBe('My Custom Agent');
+ expect(result.current.avatar).toBe('agent-avatar.png');
+ });
+
+ it('should return Lobe AI title for builtin inbox agent, preserving avatar from backend', () => {
+ const mockInboxAgentId = 'inbox-agent-id';
+ const mockMeta = {
+ avatar: '/icons/icon-lobe.png', // Avatar from backend (merged from builtin-agents package)
+ title: 'Original Inbox Title',
+ description: 'Inbox description',
+ };
+
+ // Mock ConversationStore to return inbox agentId
+ vi.mocked(useConversationStore).mockImplementation((selector: any) => {
+ const state = { context: { agentId: mockInboxAgentId } };
+ return selector(state);
+ });
+
+ // Mock AgentStore state with inbox as builtin agent
+ act(() => {
+ useAgentStore.setState({
+ agentMap: {
+ [mockInboxAgentId]: mockMeta,
+ },
+ builtinAgentIdMap: {
+ inbox: mockInboxAgentId,
+ pageAgent: 'page-agent-id',
+ },
+ });
+ });
+
+ const { result } = renderHook(() => useAgentMeta());
+
+ // Should override title with Lobe AI, but preserve avatar from backend
+ expect(result.current.avatar).toBe('/icons/icon-lobe.png');
+ expect(result.current.title).toBe('Lobe AI');
+ // Should preserve other properties
+ expect(result.current.description).toBe('Inbox description');
+ });
+
+ it('should return Lobe AI title for page agent (builtin), preserving avatar from backend', () => {
+ const mockPageAgentId = 'page-agent-id';
+ const mockMeta = {
+ avatar: '/icons/icon-lobe.png', // Avatar from backend (merged from builtin-agents package)
+ title: 'Page Agent Title',
+ };
+
+ vi.mocked(useConversationStore).mockImplementation((selector: any) => {
+ const state = { context: { agentId: mockPageAgentId } };
+ return selector(state);
+ });
+
+ act(() => {
+ useAgentStore.setState({
+ agentMap: {
+ [mockPageAgentId]: mockMeta,
+ },
+ builtinAgentIdMap: {
+ inbox: 'inbox-agent-id',
+ pageAgent: mockPageAgentId,
+ },
+ });
+ });
+
+ const { result } = renderHook(() => useAgentMeta());
+
+ // Should override title with Lobe AI, but preserve avatar from backend
+ expect(result.current.avatar).toBe('/icons/icon-lobe.png');
+ expect(result.current.title).toBe('Lobe AI');
+ });
+
+ it('should handle empty agentMap gracefully', () => {
+ const mockAgentId = 'non-existent-agent';
+
+ vi.mocked(useConversationStore).mockImplementation((selector: any) => {
+ const state = { context: { agentId: mockAgentId } };
+ return selector(state);
+ });
+
+ act(() => {
+ useAgentStore.setState({
+ agentMap: {},
+ builtinAgentIdMap: {},
+ });
+ });
+
+ const { result } = renderHook(() => useAgentMeta());
+
+ // Should return empty object or undefined properties
+ expect(result.current).toBeDefined();
+ });
+
+ it('should use messageAgentId when provided instead of context agentId', () => {
+ const contextAgentId = 'context-agent-123';
+ const messageAgentId = 'message-agent-456';
+ const contextMeta = {
+ avatar: 'context-avatar.png',
+ title: 'Context Agent',
+ };
+ const messageMeta = {
+ avatar: 'message-avatar.png',
+ title: 'Message Agent',
+ };
+
+ // Mock ConversationStore to return context agentId
+ vi.mocked(useConversationStore).mockImplementation((selector: any) => {
+ const state = { context: { agentId: contextAgentId } };
+ return selector(state);
+ });
+
+ // Mock AgentStore state with both agents
+ act(() => {
+ useAgentStore.setState({
+ agentMap: {
+ [contextAgentId]: contextMeta,
+ [messageAgentId]: messageMeta,
+ },
+ builtinAgentIdMap: {},
+ });
+ });
+
+ // When messageAgentId is provided, should use that agent's meta
+ const { result } = renderHook(() => useAgentMeta(messageAgentId));
+
+ expect(result.current).toMatchObject(messageMeta);
+ expect(result.current.title).toBe('Message Agent');
+ expect(result.current.avatar).toBe('message-avatar.png');
+ });
+
+ it('should fallback to context agentId when messageAgentId is null', () => {
+ const contextAgentId = 'context-agent-123';
+ const contextMeta = {
+ avatar: 'context-avatar.png',
+ title: 'Context Agent',
+ };
+
+ vi.mocked(useConversationStore).mockImplementation((selector: any) => {
+ const state = { context: { agentId: contextAgentId } };
+ return selector(state);
+ });
+
+ act(() => {
+ useAgentStore.setState({
+ agentMap: {
+ [contextAgentId]: contextMeta,
+ },
+ builtinAgentIdMap: {},
+ });
+ });
+
+ // When messageAgentId is null, should fallback to context agentId
+ const { result } = renderHook(() => useAgentMeta(null));
+
+ expect(result.current).toMatchObject(contextMeta);
+ expect(result.current.title).toBe('Context Agent');
+ });
+
+ it('should fallback to context agentId when messageAgentId is undefined', () => {
+ const contextAgentId = 'context-agent-123';
+ const contextMeta = {
+ avatar: 'context-avatar.png',
+ title: 'Context Agent',
+ };
+
+ vi.mocked(useConversationStore).mockImplementation((selector: any) => {
+ const state = { context: { agentId: contextAgentId } };
+ return selector(state);
+ });
+
+ act(() => {
+ useAgentStore.setState({
+ agentMap: {
+ [contextAgentId]: contextMeta,
+ },
+ builtinAgentIdMap: {},
+ });
+ });
+
+ // When messageAgentId is undefined, should fallback to context agentId
+ const { result } = renderHook(() => useAgentMeta(undefined));
+
+ expect(result.current).toMatchObject(contextMeta);
+ expect(result.current.title).toBe('Context Agent');
+ });
+});
+
+describe('useIsBuiltinAgent', () => {
+ it('should return true for inbox agent', () => {
+ const mockInboxAgentId = 'inbox-agent-id';
+
+ vi.mocked(useConversationStore).mockImplementation((selector: any) => {
+ const state = { context: { agentId: mockInboxAgentId } };
+ return selector(state);
+ });
+
+ act(() => {
+ useAgentStore.setState({
+ builtinAgentIdMap: {
+ inbox: mockInboxAgentId,
+ pageAgent: 'page-agent-id',
+ },
+ });
+ });
+
+ const { result } = renderHook(() => useIsBuiltinAgent());
+
+ expect(result.current).toBe(true);
+ });
+
+ it('should return true for page agent', () => {
+ const mockPageAgentId = 'page-agent-id';
+
+ vi.mocked(useConversationStore).mockImplementation((selector: any) => {
+ const state = { context: { agentId: mockPageAgentId } };
+ return selector(state);
+ });
+
+ act(() => {
+ useAgentStore.setState({
+ builtinAgentIdMap: {
+ inbox: 'inbox-agent-id',
+ pageAgent: mockPageAgentId,
+ },
+ });
+ });
+
+ const { result } = renderHook(() => useIsBuiltinAgent());
+
+ expect(result.current).toBe(true);
+ });
+
+ it('should return false for regular (non-builtin) agent', () => {
+ const mockRegularAgentId = 'regular-agent-123';
+
+ vi.mocked(useConversationStore).mockImplementation((selector: any) => {
+ const state = { context: { agentId: mockRegularAgentId } };
+ return selector(state);
+ });
+
+ act(() => {
+ useAgentStore.setState({
+ builtinAgentIdMap: {
+ inbox: 'inbox-agent-id',
+ pageAgent: 'page-agent-id',
+ },
+ });
+ });
+
+ const { result } = renderHook(() => useIsBuiltinAgent());
+
+ expect(result.current).toBe(false);
+ });
+
+ it('should return false when builtinAgentIdMap is empty', () => {
+ vi.mocked(useConversationStore).mockImplementation((selector: any) => {
+ const state = { context: { agentId: 'some-agent' } };
+ return selector(state);
+ });
+
+ act(() => {
+ useAgentStore.setState({
+ builtinAgentIdMap: {},
+ });
+ });
+
+ const { result } = renderHook(() => useIsBuiltinAgent());
+
+ expect(result.current).toBe(false);
+ });
+});
diff --git a/src/features/Conversation/hooks/useAgentMeta.ts b/src/features/Conversation/hooks/useAgentMeta.ts
new file mode 100644
index 00000000000..e891e5fc2a1
--- /dev/null
+++ b/src/features/Conversation/hooks/useAgentMeta.ts
@@ -0,0 +1,52 @@
+import { MetaData } from '@lobechat/types';
+import { useMemo } from 'react';
+
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+
+import { contextSelectors, useConversationStore } from '../store';
+
+const LOBE_AI_TITLE = 'Lobe AI';
+
+/**
+ * Hook to get agent meta data for a specific agent or the current conversation.
+ * Handles special cases for builtin agents (inbox, page agent, agent builder)
+ * by showing Lobe AI title instead of the agent's own meta.
+ * Avatar is now returned from the backend (merged from builtin-agents package).
+ *
+ * @param messageAgentId - Optional agent ID from the message. If provided, uses this agent's meta.
+ * Falls back to the current conversation's agent if not provided.
+ */
+export const useAgentMeta = (messageAgentId?: string | null): MetaData => {
+ const contextAgentId = useConversationStore(contextSelectors.agentId);
+ // Use message's agentId if provided, otherwise fallback to context agentId
+ const agentId = messageAgentId || contextAgentId;
+ const agentMeta = useAgentStore(agentSelectors.getAgentMetaById(agentId));
+ const builtinAgentIdMap = useAgentStore((s) => s.builtinAgentIdMap);
+
+ return useMemo(() => {
+ // Check if the current agent is a builtin agent
+ const builtinAgentIds = Object.values(builtinAgentIdMap);
+ const isBuiltinAgent = builtinAgentIds.includes(agentId);
+
+ if (isBuiltinAgent) {
+ // Use avatar from backend (merged from builtin-agents package), only override title
+ return { ...agentMeta, title: LOBE_AI_TITLE };
+ }
+
+ return agentMeta;
+ }, [agentId, agentMeta, builtinAgentIdMap]);
+};
+
+/**
+ * Hook to check if the current agent is a builtin agent
+ */
+export const useIsBuiltinAgent = (): boolean => {
+ const agentId = useConversationStore(contextSelectors.agentId);
+ const builtinAgentIdMap = useAgentStore((s) => s.builtinAgentIdMap);
+
+ return useMemo(() => {
+ const builtinAgentIds = Object.values(builtinAgentIdMap);
+ return builtinAgentIds.includes(agentId);
+ }, [agentId, builtinAgentIdMap]);
+};
diff --git a/src/features/ChatList/hooks/useChatItemContextMenu.tsx b/src/features/Conversation/hooks/useChatItemContextMenu.tsx
similarity index 95%
rename from src/features/ChatList/hooks/useChatItemContextMenu.tsx
rename to src/features/Conversation/hooks/useChatItemContextMenu.tsx
index a079886b78f..ca5ea3add5b 100644
--- a/src/features/ChatList/hooks/useChatItemContextMenu.tsx
+++ b/src/features/Conversation/hooks/useChatItemContextMenu.tsx
@@ -1,11 +1,10 @@
import { type ActionIconGroupEvent } from '@lobehub/ui';
import React, { useCallback, useEffect, useRef, useState } from 'react';
+import { MSG_CONTENT_CLASSNAME } from '@/features/Conversation/ChatItem/components/MessageContent';
import { useUserStore } from '@/store/user';
import { userGeneralSettingsSelectors } from '@/store/user/selectors';
-import { MessageContentClassName } from '../Messages/Default';
-
interface ContextMenuState {
position: { x: number; y: number };
selectedText?: string;
@@ -48,7 +47,7 @@ export const useChatItemContextMenu = ({
let hasMessageId = false;
while (target && target !== document.body) {
- if (target.className.includes(MessageContentClassName)) {
+ if (target.className.includes(MSG_CONTENT_CLASSNAME)) {
hasMessageId = true;
break;
}
diff --git a/src/features/ChatList/hooks/useChatListActionsBar.tsx b/src/features/Conversation/hooks/useChatListActionsBar.tsx
similarity index 98%
rename from src/features/ChatList/hooks/useChatListActionsBar.tsx
rename to src/features/Conversation/hooks/useChatListActionsBar.tsx
index 275a9e7f902..ed1ce4ba0c7 100644
--- a/src/features/ChatList/hooks/useChatListActionsBar.tsx
+++ b/src/features/Conversation/hooks/useChatListActionsBar.tsx
@@ -77,7 +77,7 @@ export const useChatListActionsBar = ({
copy: {
icon: Copy,
key: 'copy',
- label: t('copy', { defaultValue: 'Copy' }),
+ label: t('copy'),
},
del: {
danger: true,
diff --git a/src/features/ChatList/hooks/useDoubleClickEdit.ts b/src/features/Conversation/hooks/useDoubleClickEdit.ts
similarity index 54%
rename from src/features/ChatList/hooks/useDoubleClickEdit.ts
rename to src/features/Conversation/hooks/useDoubleClickEdit.ts
index c6541efb3fe..08f959134db 100644
--- a/src/features/ChatList/hooks/useDoubleClickEdit.ts
+++ b/src/features/Conversation/hooks/useDoubleClickEdit.ts
@@ -1,14 +1,11 @@
-import { MouseEventHandler, use, useCallback } from 'react';
+import { MouseEventHandler, useCallback } from 'react';
-import { useChatStore } from '@/store/chat';
-
-import { VirtuaContext } from '../components/VirtualizedList/VirtuosoContext';
+import { useConversationStore } from '../store';
interface UseDoubleClickEditProps {
disableEditing?: boolean;
error: any;
id: string;
- index: number;
role: string;
}
@@ -17,10 +14,8 @@ export const useDoubleClickEdit = ({
role,
error,
id,
- index,
}: UseDoubleClickEditProps) => {
- const [toggleMessageEditing] = useChatStore((s) => [s.toggleMessageEditing]);
- const virtuaRef = use(VirtuaContext);
+ const toggleMessageEditing = useConversationStore((s) => s.toggleMessageEditing);
return useCallback<MouseEventHandler<HTMLDivElement>>(
(e) => {
@@ -34,9 +29,7 @@ export const useDoubleClickEdit = ({
return;
toggleMessageEditing(id, true);
-
- virtuaRef?.current?.scrollToIndex(index, { align: 'start' });
},
- [role, disableEditing],
+ [role, disableEditing, toggleMessageEditing, id],
);
};
diff --git a/src/features/Conversation/index.ts b/src/features/Conversation/index.ts
new file mode 100644
index 00000000000..0d5f6b1aa8a
--- /dev/null
+++ b/src/features/Conversation/index.ts
@@ -0,0 +1,24 @@
+// Re-export types, provider, hooks, store, and components for convenience
+export { ConversationProvider, type ConversationProviderProps } from './ConversationProvider';
+export { useDoubleClickEdit } from './hooks';
+export {
+ conversationSelectors,
+ type ConversationStore,
+ createStore as createConversationStore,
+ useConversationStore,
+ useConversationStoreApi,
+} from './store';
+export type {
+ ActionsBarConfig,
+ ConversationContext,
+ ConversationHooks,
+ MessageActionItem,
+ MessageActionItemOrDivider,
+ MessageActionsConfig,
+ OperationState,
+} from './types';
+
+// Components
+export { default as ChatInput, type ChatInputProps } from './ChatInput';
+export { default as ChatList, type ChatListProps } from './ChatList';
+export { default as MessageItem, type MessageItemProps } from './Messages';
diff --git a/src/features/Conversation/store.test.ts b/src/features/Conversation/store.test.ts
new file mode 100644
index 00000000000..5fa392f1800
--- /dev/null
+++ b/src/features/Conversation/store.test.ts
@@ -0,0 +1,396 @@
+import { act } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createStore } from './store';
+import type { ConversationContext, ConversationHooks } from './types';
+
+// Mock dependencies
+vi.mock('@/store/chat', () => ({
+ useChatStore: {
+ getState: vi.fn(() => ({
+ messagesMap: {},
+ operations: {},
+ optimisticCreateMessage: vi.fn(),
+ optimisticCreateTmpMessage: vi.fn(),
+ internal_toggleMessageLoading: vi.fn(),
+ startOperation: vi.fn(() => ({
+ operationId: 'test-op-id',
+ abortController: new AbortController(),
+ })),
+ completeOperation: vi.fn(),
+ cancelOperation: vi.fn(),
+ cancelOperations: vi.fn(),
+ failOperation: vi.fn(),
+ deleteMessage: vi.fn(),
+ modifyMessageContent: vi.fn(),
+ copyMessage: vi.fn(),
+ toggleMessageEditing: vi.fn(),
+ regenerateUserMessage: vi.fn(),
+ regenerateAssistantMessage: vi.fn(),
+ continueGenerationMessage: vi.fn(),
+ approveToolCalling: vi.fn(),
+ rejectToolCalling: vi.fn(),
+ switchMessageBranch: vi.fn(),
+ updateOperationMetadata: vi.fn(),
+ associateMessageWithOperation: vi.fn(),
+ replaceMessages: vi.fn(),
+ internal_dispatchMessage: vi.fn(),
+ internal_dispatchTopic: vi.fn(),
+ internal_execAgentRuntime: vi.fn(),
+ switchTopic: vi.fn(),
+ summaryTopicTitle: vi.fn(),
+ internal_updateTopicLoading: vi.fn(),
+ })),
+ setState: vi.fn(),
+ },
+}));
+
+vi.mock('@/store/agent', () => ({
+ getAgentStoreState: vi.fn(() => ({
+ addFilesToAgent: vi.fn(),
+ })),
+ agentSelectors: {
+ currentAgentConfig: vi.fn(() => ({ model: 'gpt-4', provider: 'openai' })),
+ },
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentChatConfigSelectors: {
+ currentChatConfig: vi.fn(() => ({
+ enableAutoCreateTopic: false,
+ autoCreateTopicThreshold: 5,
+ })),
+ },
+ agentSelectors: {
+ currentAgentConfig: vi.fn(() => ({ model: 'gpt-4', provider: 'openai' })),
+ },
+}));
+
+vi.mock('@/store/chat/selectors', () => ({
+ displayMessageSelectors: {
+ lastDisplayMessageId: vi.fn(() => 'last-msg-id'),
+ getDisplayMessagesByKey: vi.fn(() => () => []),
+ findLastMessageId: vi.fn(() => () => 'parent-id'),
+ getDisplayMessageById: vi.fn(() => () => ({ content: 'original content' })),
+ },
+ dbMessageSelectors: {
+ dbUserFiles: vi.fn(() => []),
+ },
+ topicSelectors: {
+ getTopicById: vi.fn(() => () => null),
+ },
+}));
+
+vi.mock('@/store/file/store', () => ({
+ getFileStoreState: vi.fn(() => ({
+ chatUploadFileList: [],
+ })),
+}));
+
+vi.mock('@/store/session', () => ({
+ getSessionStoreState: vi.fn(() => ({
+ triggerSessionUpdate: vi.fn(),
+ })),
+}));
+
+vi.mock('@/services/aiChat', () => ({
+ aiChatService: {
+ sendMessageInServer: vi.fn(),
+ },
+}));
+
+vi.mock('@/store/chat/utils/messageMapKey', () => ({
+ messageMapKey: vi.fn((sessionId, topicId) => `${sessionId}-${topicId ?? ''}`),
+}));
+
+describe('ConversationStore', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ vi.clearAllTimers();
+ });
+
+ describe('createStore', () => {
+ it('should create a store with correct initial state', () => {
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: 'topic-1',
+ threadId: null,
+ };
+
+ const store = createStore({ context });
+ const state = store.getState();
+
+ expect(state.context).toEqual(context);
+ expect(state.inputMessage).toBe('');
+ expect(state.editor).toBeNull();
+ expect(state.hooks).toEqual({});
+ });
+
+ it('should create store with custom hooks', () => {
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+
+ const hooks: ConversationHooks = {
+ onBeforeSendMessage: vi.fn(),
+ onAfterSendMessage: vi.fn(),
+ };
+
+ const store = createStore({ context, hooks });
+ const state = store.getState();
+
+ expect(state.hooks).toBe(hooks);
+ expect(state.hooks.onBeforeSendMessage).toBeDefined();
+ expect(state.hooks.onAfterSendMessage).toBeDefined();
+ });
+
+ it('should create store with thread context', () => {
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: 'topic-1',
+ threadId: 'thread-1',
+ };
+
+ const store = createStore({ context });
+ const state = store.getState();
+
+ expect(state.context.threadId).toBe('thread-1');
+ });
+
+ it('should create store with group scope context', () => {
+ const context: ConversationContext = {
+ agentId: 'agent-1',
+ groupId: 'group-1',
+ topicId: 'topic-1',
+ threadId: null,
+ scope: 'group',
+ };
+
+ const store = createStore({ context });
+ const state = store.getState();
+
+ expect(state.context.scope).toBe('group');
+ expect(state.context.groupId).toBe('group-1');
+ expect(state.context.agentId).toBe('agent-1');
+ });
+
+ it('should create store with group_agent scope context', () => {
+ const context: ConversationContext = {
+ agentId: 'agent-1',
+ groupId: 'group-1',
+ topicId: 'topic-1',
+ threadId: 'agent-topic-1',
+ scope: 'group_agent',
+ };
+
+ const store = createStore({ context });
+ const state = store.getState();
+
+ expect(state.context.scope).toBe('group_agent');
+ expect(state.context.groupId).toBe('group-1');
+ expect(state.context.threadId).toBe('agent-topic-1');
+ });
+ });
+
+ describe('UI Actions', () => {
+ describe('updateInputMessage', () => {
+ it('should update input message', () => {
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+
+ const store = createStore({ context });
+
+ act(() => {
+ store.getState().updateInputMessage('Hello, world!');
+ });
+
+ expect(store.getState().inputMessage).toBe('Hello, world!');
+ });
+
+ it('should handle empty message', () => {
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+
+ const store = createStore({ context });
+
+ act(() => {
+ store.getState().updateInputMessage('Hello');
+ store.getState().updateInputMessage('');
+ });
+
+ expect(store.getState().inputMessage).toBe('');
+ });
+ });
+
+ describe('setEditor', () => {
+ it('should set editor instance', () => {
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+
+ const store = createStore({ context });
+ const mockEditor = { getJSONState: vi.fn() };
+
+ act(() => {
+ store.getState().setEditor(mockEditor);
+ });
+
+ expect(store.getState().editor).toBe(mockEditor);
+ });
+
+ it('should allow setting editor to null', () => {
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+
+ const store = createStore({ context });
+ const mockEditor = { getJSONState: vi.fn() };
+
+ act(() => {
+ store.getState().setEditor(mockEditor);
+ store.getState().setEditor(null);
+ });
+
+ expect(store.getState().editor).toBeNull();
+ });
+ });
+
+ describe('cleanupInput', () => {
+ it('should reset input state on cleanupInput', () => {
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+
+ const store = createStore({ context });
+ const mockEditor = { getJSONState: vi.fn() };
+
+ act(() => {
+ store.getState().updateInputMessage('Hello');
+ store.getState().setEditor(mockEditor);
+ });
+
+ expect(store.getState().inputMessage).toBe('Hello');
+ expect(store.getState().editor).toBe(mockEditor);
+
+ act(() => {
+ store.getState().cleanupInput();
+ });
+
+ expect(store.getState().inputMessage).toBe('');
+ expect(store.getState().editor).toBeNull();
+ });
+ });
+ });
+
+ describe('Store Isolation', () => {
+ it('should create independent store instances', () => {
+ const context1: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+
+ const context2: ConversationContext = {
+ agentId: 'session-2',
+ topicId: null,
+ threadId: null,
+ };
+
+ const store1 = createStore({ context: context1 });
+ const store2 = createStore({ context: context2 });
+
+ act(() => {
+ store1.getState().updateInputMessage('Message 1');
+ store2.getState().updateInputMessage('Message 2');
+ });
+
+ expect(store1.getState().inputMessage).toBe('Message 1');
+ expect(store2.getState().inputMessage).toBe('Message 2');
+ expect(store1.getState().context.agentId).toBe('session-1');
+ expect(store2.getState().context.agentId).toBe('session-2');
+ });
+
+ it('should isolate stores with different scopes', () => {
+ const mainContext: ConversationContext = {
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ threadId: null,
+ scope: 'main',
+ };
+
+ const groupContext: ConversationContext = {
+ agentId: 'agent-1',
+ groupId: 'group-1',
+ topicId: 'topic-1',
+ threadId: null,
+ scope: 'group',
+ };
+
+ const store1 = createStore({ context: mainContext });
+ const store2 = createStore({ context: groupContext });
+
+ act(() => {
+ store1.getState().updateInputMessage('Main message');
+ store2.getState().updateInputMessage('Group message');
+ });
+
+ expect(store1.getState().inputMessage).toBe('Main message');
+ expect(store2.getState().inputMessage).toBe('Group message');
+ expect(store1.getState().context.scope).toBe('main');
+ expect(store2.getState().context.scope).toBe('group');
+ expect(store2.getState().context.groupId).toBe('group-1');
+ });
+
+ it('should isolate group and group_agent stores', () => {
+ const groupContext: ConversationContext = {
+ agentId: 'agent-1',
+ groupId: 'group-1',
+ topicId: 'topic-1',
+ threadId: null,
+ scope: 'group',
+ };
+
+ const groupAgentContext: ConversationContext = {
+ agentId: 'agent-1',
+ groupId: 'group-1',
+ topicId: 'topic-1',
+ threadId: 'agent-topic-1',
+ scope: 'group_agent',
+ };
+
+ const store1 = createStore({ context: groupContext });
+ const store2 = createStore({ context: groupAgentContext });
+
+ act(() => {
+ store1.getState().updateInputMessage('Group main');
+ store2.getState().updateInputMessage('Group agent');
+ });
+
+ expect(store1.getState().inputMessage).toBe('Group main');
+ expect(store2.getState().inputMessage).toBe('Group agent');
+ expect(store1.getState().context.scope).toBe('group');
+ expect(store2.getState().context.scope).toBe('group_agent');
+ expect(store1.getState().context.groupId).toBe('group-1');
+ expect(store2.getState().context.groupId).toBe('group-1');
+ expect(store1.getState().context.threadId).toBeNull();
+ expect(store2.getState().context.threadId).toBe('agent-topic-1');
+ });
+ });
+});
diff --git a/src/features/Conversation/store/action.ts b/src/features/Conversation/store/action.ts
new file mode 100644
index 00000000000..1db5671cde3
--- /dev/null
+++ b/src/features/Conversation/store/action.ts
@@ -0,0 +1,61 @@
+import type { StateCreator } from 'zustand/vanilla';
+
+import type { ConversationContext, ConversationHooks } from '../types';
+import { type State, initialState } from './initialState';
+import type { DataAction } from './slices/data/action';
+import { dataSlice } from './slices/data/action';
+import type { GenerationAction } from './slices/generation/action';
+import { generationSlice } from './slices/generation/action';
+import type { InputAction } from './slices/input/action';
+import { inputSlice } from './slices/input/action';
+import type { MessageAction } from './slices/message/action';
+import { messageSlice } from './slices/message/action';
+import type { MessageEditingAction } from './slices/messageState/action';
+import { messageEditingSlice } from './slices/messageState/action';
+import type { ToolAction } from './slices/tool/action';
+import { toolSlice } from './slices/tool/action';
+import type { VirtuaListAction } from './slices/virtuaList/action';
+import { virtuaListSlice } from './slices/virtuaList/action';
+
+// ===== Combined Store Type =====
+
+export type Store = State &
+ DataAction &
+ GenerationAction &
+ InputAction &
+ MessageAction &
+ MessageEditingAction &
+ ToolAction &
+ VirtuaListAction;
+
+// Alias for backward compatibility
+export type ConversationStore = Store;
+
+// ===== Store Creator =====
+
+export interface CreateStoreParams {
+ context: ConversationContext;
+ hooks?: ConversationHooks;
+ skipFetch?: boolean;
+}
+
+type CreateStore = (
+ params: CreateStoreParams,
+) => StateCreator<Store, [['zustand/devtools', never]]>;
+
+export const createStoreAction: CreateStore =
+ ({ context, hooks = {}, skipFetch }) =>
+ (...params) => ({
+ ...initialState,
+ context,
+ hooks,
+ skipFetch,
+ // ===== Slices =====
+ ...dataSlice(...params),
+ ...generationSlice(...params),
+ ...inputSlice(...params),
+ ...messageSlice(...params),
+ ...messageEditingSlice(...params),
+ ...toolSlice(...params),
+ ...virtuaListSlice(...params),
+ });
diff --git a/src/features/Conversation/store/index.ts b/src/features/Conversation/store/index.ts
new file mode 100644
index 00000000000..a5742b4db83
--- /dev/null
+++ b/src/features/Conversation/store/index.ts
@@ -0,0 +1,32 @@
+'use client';
+
+import type { StoreApiWithSelector } from '@lobechat/types';
+import { createContext } from 'zustand-utils';
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn } from 'zustand/traditional';
+
+import { createDevtools } from '@/store/middleware/createDevtools';
+
+import { CreateStoreParams, type Store, createStoreAction } from './action';
+
+export type { Store as ConversationStore, ConversationStore as Store } from './action';
+export type { State } from './initialState';
+export {
+ contextSelectors,
+ conversationSelectors,
+ dataSelectors,
+ inputSelectors,
+ messageStateSelectors,
+ virtuaListSelectors,
+} from './selectors';
+
+const devtools = createDevtools('conversation');
+
+export const createStore = (params: CreateStoreParams) =>
+ createWithEqualityFn(devtools(createStoreAction(params)), shallow);
+
+export const {
+ Provider,
+ useStore: useConversationStore,
+ useStoreApi: useConversationStoreApi,
+} = createContext<StoreApiWithSelector<Store>>();
diff --git a/src/features/Conversation/store/initialState.ts b/src/features/Conversation/store/initialState.ts
new file mode 100644
index 00000000000..ee9079d0ad4
--- /dev/null
+++ b/src/features/Conversation/store/initialState.ts
@@ -0,0 +1,61 @@
+import type { UIChatMessage } from '@lobechat/types';
+
+import type {
+ ActionsBarConfig,
+ ConversationContext,
+ ConversationHooks,
+ OperationState,
+} from '../types';
+import { DEFAULT_OPERATION_STATE } from '../types/operation';
+import { type DataState, dataInitialState } from './slices/data/initialState';
+import { type InputState, inputInitialState } from './slices/input/initialState';
+import {
+ type MessageStateState,
+ messageStateInitialState,
+} from './slices/messageState/initialState';
+import { type VirtuaListState, virtuaListInitialState } from './slices/virtuaList/initialState';
+
+export interface State extends DataState, InputState, MessageStateState, VirtuaListState {
+ /**
+ * Actions bar configuration by message type
+ */
+ actionsBar?: ActionsBarConfig;
+
+ /**
+ * Conversation context (data coordinates)
+ */
+ context: ConversationContext;
+
+ /**
+ * Lifecycle hooks for external behavior injection
+ */
+ hooks: ConversationHooks;
+
+ /**
+ * Callback when messages are fetched or changed internally
+ */
+ onMessagesChange?: (messages: UIChatMessage[]) => void;
+
+ /**
+ * External operation state (from ChatStore)
+ * Used for reactive updates of operation-related UI
+ */
+ operationState: OperationState;
+}
+
+export const initialState: State = {
+ ...dataInitialState,
+ ...inputInitialState,
+ ...messageStateInitialState,
+ ...virtuaListInitialState,
+
+ actionsBar: undefined,
+ context: {
+ agentId: '',
+ threadId: null,
+ topicId: null,
+ },
+ hooks: {},
+ onMessagesChange: undefined,
+ operationState: DEFAULT_OPERATION_STATE,
+};
diff --git a/src/features/Conversation/store/selectors.test.ts b/src/features/Conversation/store/selectors.test.ts
new file mode 100644
index 00000000000..ca00f507f43
--- /dev/null
+++ b/src/features/Conversation/store/selectors.test.ts
@@ -0,0 +1,234 @@
+import { describe, expect, it } from 'vitest';
+
+import { DEFAULT_OPERATION_STATE } from '../types/operation';
+import type { State } from './initialState';
+import { conversationSelectors } from './selectors';
+
+// Helper to create a mock state
+const createMockState = (overrides: Partial<State> = {}): State => ({
+ // Input state
+ editor: null,
+ inputMessage: '',
+
+ // MessageState
+ messageEditingIds: [],
+ messageLoadingIds: [],
+ pendingArgsUpdates: new Map(),
+
+ // VirtuaList state
+ activeIndex: null,
+ atBottom: true,
+ isScrolling: false,
+ virtuaScrollMethods: null,
+ visibleItems: new Map(),
+
+ // Core state
+ context: {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ },
+ dbMessages: [],
+ displayMessages: [],
+ hooks: {},
+ messagesInit: false,
+ operationState: DEFAULT_OPERATION_STATE,
+ skipFetch: false,
+ ...overrides,
+});
+
+describe('conversationSelectors', () => {
+ describe('Context Selectors', () => {
+ describe('context', () => {
+ it('should return the full context', () => {
+ const store = createMockState({
+ context: {
+ agentId: 'session-1',
+ topicId: 'topic-1',
+ threadId: 'thread-1',
+ },
+ });
+
+ const result = conversationSelectors.context(store);
+
+ expect(result).toEqual({
+ agentId: 'session-1',
+ topicId: 'topic-1',
+ threadId: 'thread-1',
+ });
+ });
+ });
+
+ describe('sessionId', () => {
+ it('should return sessionId from context', () => {
+ const store = createMockState({
+ context: { agentId: 'my-session', topicId: null, threadId: null },
+ });
+
+ expect(conversationSelectors.agentId(store)).toBe('my-session');
+ });
+ });
+
+ describe('topicId', () => {
+ it('should return topicId when set', () => {
+ const store = createMockState({
+ context: { agentId: 'session-1', topicId: 'topic-123', threadId: null },
+ });
+
+ expect(conversationSelectors.topicId(store)).toBe('topic-123');
+ });
+
+ it('should return null when topicId is not set', () => {
+ const store = createMockState({
+ context: { agentId: 'session-1', topicId: null, threadId: null },
+ });
+
+ expect(conversationSelectors.topicId(store)).toBeNull();
+ });
+ });
+
+ describe('threadId', () => {
+ it('should return threadId when set', () => {
+ const store = createMockState({
+ context: { agentId: 'session-1', topicId: 'topic-1', threadId: 'thread-456' },
+ });
+
+ expect(conversationSelectors.threadId(store)).toBe('thread-456');
+ });
+
+ it('should return null when threadId is not set', () => {
+ const store = createMockState({
+ context: { agentId: 'session-1', topicId: null, threadId: null },
+ });
+
+ expect(conversationSelectors.threadId(store)).toBeNull();
+ });
+ });
+
+ describe('isThread', () => {
+ it('should return true when threadId is set', () => {
+ const store = createMockState({
+ context: { agentId: 'session-1', topicId: 'topic-1', threadId: 'thread-1' },
+ });
+
+ expect(conversationSelectors.isThread(store)).toBe(true);
+ });
+
+ it('should return false when threadId is null', () => {
+ const store = createMockState({
+ context: { agentId: 'session-1', topicId: 'topic-1', threadId: null },
+ });
+
+ expect(conversationSelectors.isThread(store)).toBe(false);
+ });
+ });
+
+ describe('isTopic', () => {
+ it('should return true when topicId is set', () => {
+ const store = createMockState({
+ context: { agentId: 'session-1', topicId: 'topic-1', threadId: null },
+ });
+
+ expect(conversationSelectors.isTopic(store)).toBe(true);
+ });
+
+ it('should return false when topicId is null', () => {
+ const store = createMockState({
+ context: { agentId: 'session-1', topicId: null, threadId: null },
+ });
+
+ expect(conversationSelectors.isTopic(store)).toBe(false);
+ });
+ });
+ });
+
+ describe('UI State Selectors', () => {
+ describe('editor', () => {
+ it('should return editor instance when set', () => {
+ const mockEditor = { getJSONState: () => ({}) };
+ const store = createMockState({ editor: mockEditor });
+
+ expect(conversationSelectors.editor(store)).toBe(mockEditor);
+ });
+
+ it('should return null when editor is not set', () => {
+ const store = createMockState({ editor: null });
+
+ expect(conversationSelectors.editor(store)).toBeNull();
+ });
+ });
+
+ describe('inputMessage', () => {
+ it('should return input message', () => {
+ const store = createMockState({ inputMessage: 'Hello, world!' });
+
+ expect(conversationSelectors.inputMessage(store)).toBe('Hello, world!');
+ });
+
+ it('should return empty string when no input', () => {
+ const store = createMockState({ inputMessage: '' });
+
+ expect(conversationSelectors.inputMessage(store)).toBe('');
+ });
+ });
+
+ describe('hasInput', () => {
+ it('should return true when input has content', () => {
+ const store = createMockState({ inputMessage: 'Hello' });
+
+ expect(conversationSelectors.hasInput(store)).toBe(true);
+ });
+
+ it('should return false when input is empty', () => {
+ const store = createMockState({ inputMessage: '' });
+
+ expect(conversationSelectors.hasInput(store)).toBe(false);
+ });
+
+ it('should return false when input has only whitespace', () => {
+ const store = createMockState({ inputMessage: ' ' });
+
+ expect(conversationSelectors.hasInput(store)).toBe(false);
+ });
+ });
+ });
+
+ describe('Hook Selectors', () => {
+ describe('hooks', () => {
+ it('should return hooks object', () => {
+ const mockHooks = {
+ onBeforeSendMessage: async () => true,
+ onAfterSendMessage: async () => {},
+ };
+ const store = createMockState({ hooks: mockHooks });
+
+ expect(conversationSelectors.hooks(store)).toBe(mockHooks);
+ });
+
+ it('should return empty object when no hooks', () => {
+ const store = createMockState({ hooks: {} });
+
+ expect(conversationSelectors.hooks(store)).toEqual({});
+ });
+ });
+
+ describe('hook', () => {
+ it('should return specific hook when exists', () => {
+ const onBeforeSendMessage = async () => true;
+ const store = createMockState({
+ hooks: { onBeforeSendMessage },
+ });
+
+ const hookSelector = conversationSelectors.hook('onBeforeSendMessage');
+ expect(hookSelector(store)).toBe(onBeforeSendMessage);
+ });
+
+ it('should return undefined when hook does not exist', () => {
+ const store = createMockState({ hooks: {} });
+
+ const hookSelector = conversationSelectors.hook('onBeforeSendMessage');
+ expect(hookSelector(store)).toBeUndefined();
+ });
+ });
+ });
+});
diff --git a/src/features/Conversation/store/selectors.ts b/src/features/Conversation/store/selectors.ts
new file mode 100644
index 00000000000..56e361d8046
--- /dev/null
+++ b/src/features/Conversation/store/selectors.ts
@@ -0,0 +1,19 @@
+import { contextSelectors } from './slices/context/selectors';
+import { dataSelectors } from './slices/data/selectors';
+import { inputSelectors } from './slices/input/selectors';
+import { messageStateSelectors } from './slices/messageState/selectors';
+import { virtuaListSelectors } from './slices/virtuaList/selectors';
+
+export { contextSelectors } from './slices/context/selectors';
+export { dataSelectors } from './slices/data/selectors';
+export { inputSelectors } from './slices/input/selectors';
+export { messageStateSelectors } from './slices/messageState/selectors';
+export { virtuaListSelectors } from './slices/virtuaList/selectors';
+
+export const conversationSelectors = {
+ ...contextSelectors,
+ ...dataSelectors,
+ ...inputSelectors,
+ ...messageStateSelectors,
+ ...virtuaListSelectors,
+};
diff --git a/src/features/Conversation/store/slices/context/selectors.ts b/src/features/Conversation/store/slices/context/selectors.ts
new file mode 100644
index 00000000000..68f7c671ec9
--- /dev/null
+++ b/src/features/Conversation/store/slices/context/selectors.ts
@@ -0,0 +1,22 @@
+import type { State } from '../../initialState';
+
+const context = (s: State) => s.context;
+const agentId = (s: State) => s.context.agentId;
+const topicId = (s: State) => s.context.topicId;
+const threadId = (s: State) => s.context.threadId;
+const isThread = (s: State) => !!s.context.threadId;
+const isTopic = (s: State) => !!s.context.topicId;
+
+const hooks = (s: State) => s.hooks;
+const hook = (hookName: keyof State['hooks']) => (s: State) => s.hooks[hookName];
+
+export const contextSelectors = {
+ agentId,
+ context,
+ hook,
+ hooks,
+ isThread,
+ isTopic,
+ threadId,
+ topicId,
+};
diff --git a/src/features/Conversation/store/slices/data/action.test.ts b/src/features/Conversation/store/slices/data/action.test.ts
new file mode 100644
index 00000000000..e6c0770ff3c
--- /dev/null
+++ b/src/features/Conversation/store/slices/data/action.test.ts
@@ -0,0 +1,766 @@
+import { UIChatMessage } from '@lobechat/types';
+import { act, waitFor } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { messageService } from '@/services/message';
+
+import { createStore } from '../../index';
+import { dataSelectors } from './selectors';
+
+// Mock conversation-flow parse function
+vi.mock('@lobechat/conversation-flow', () => ({
+ parse: (messages: UIChatMessage[]) => {
+ const messageMap: Record<string, UIChatMessage> = {};
+ for (const msg of messages) {
+ messageMap[msg.id] = msg;
+ }
+ // Sort by createdAt for flatList
+ const flatList = [...messages].sort((a, b) => a.createdAt - b.createdAt);
+ return { flatList, messageMap };
+ },
+}));
+
+// Mock messageService
+vi.mock('@/services/message', () => ({
+ messageService: {
+ getMessages: vi.fn(),
+ updateMessageMetadata: vi.fn().mockResolvedValue({ success: true, messages: [] }),
+ },
+}));
+
+// Mock SWR
+vi.mock('@/libs/swr', () => ({
+ useClientDataSWR: vi.fn((key, fetcher, options) => {
+ // Simulate SWR behavior for testing
+ if (key) {
+ // Execute fetcher and call onSuccess
+ fetcher?.(key).then((data: UIChatMessage[]) => {
+ options?.onSuccess?.(data);
+ });
+ }
+ return { data: undefined, isLoading: true };
+ }),
+}));
+
+// Create a test store
+const createTestStore = () =>
+ createStore({
+ context: { agentId: 'test-session', topicId: null, threadId: null },
+ });
+
+describe('DataSlice', () => {
+ describe('internal_dispatchMessage', () => {
+ it('should create a new message', () => {
+ const store = createTestStore();
+
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'msg-1',
+ value: {
+ content: 'Hello',
+ role: 'user',
+ agentId: 'session-1',
+ },
+ });
+
+ const state = store.getState();
+ expect(state.displayMessages).toHaveLength(1);
+ expect(state.displayMessages[0].id).toBe('msg-1');
+ expect(state.displayMessages[0].content).toBe('Hello');
+ expect(state.displayMessages[0].role).toBe('user');
+ });
+
+ it('should update an existing message', () => {
+ const store = createTestStore();
+
+ // First create a message
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'msg-1',
+ value: {
+ content: 'Hello',
+ role: 'user',
+ agentId: 'session-1',
+ },
+ });
+
+ // Then update it
+ store.getState().internal_dispatchMessage({
+ type: 'updateMessage',
+ id: 'msg-1',
+ value: { content: 'Updated Hello' },
+ });
+
+ const state = store.getState();
+ expect(state.displayMessages).toHaveLength(1);
+ expect(state.displayMessages[0].content).toBe('Updated Hello');
+ });
+
+ it('should delete a message', () => {
+ const store = createTestStore();
+
+ // Create two messages
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'msg-1',
+ value: { content: 'Message 1', role: 'user', sessionId: 'session-1' },
+ });
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'msg-2',
+ value: { content: 'Message 2', role: 'assistant', sessionId: 'session-1' },
+ });
+
+ expect(store.getState().displayMessages).toHaveLength(2);
+
+ // Delete one
+ store.getState().internal_dispatchMessage({
+ type: 'deleteMessage',
+ id: 'msg-1',
+ });
+
+ const state = store.getState();
+ expect(state.displayMessages).toHaveLength(1);
+ expect(state.displayMessages[0].id).toBe('msg-2');
+ });
+
+ it('should not update state if message does not exist', () => {
+ const store = createTestStore();
+
+ const initialMessages = store.getState().displayMessages;
+
+ store.getState().internal_dispatchMessage({
+ type: 'updateMessage',
+ id: 'nonexistent',
+ value: { content: 'Updated' },
+ });
+
+ // State should remain unchanged (same reference)
+ expect(store.getState().displayMessages).toBe(initialMessages);
+ });
+
+ it('should update message metadata', () => {
+ const store = createTestStore();
+
+ // Create a message
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'msg-1',
+ value: { content: 'Hello', role: 'user', sessionId: 'session-1' },
+ });
+
+ // Update metadata
+ store.getState().internal_dispatchMessage({
+ type: 'updateMessageMetadata',
+ id: 'msg-1',
+ value: { collapsed: true },
+ });
+
+ const state = store.getState();
+ // Check both dbMessages and displayMessages
+ const dbMsg = state.dbMessages.find((m) => m.id === 'msg-1');
+ expect(dbMsg?.metadata?.collapsed).toBe(true);
+ const displayMsg = state.displayMessages.find((m) => m.id === 'msg-1');
+ expect(displayMsg?.metadata?.collapsed).toBe(true);
+ });
+ });
+
+ describe('replaceMessages', () => {
+ it('should replace all messages with new data', () => {
+ const store = createTestStore();
+
+ // First add some messages
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'old-msg',
+ value: { content: 'Old', role: 'user', sessionId: 'session-1' },
+ });
+
+ expect(store.getState().displayMessages).toHaveLength(1);
+
+ // Replace with new messages
+ const newMessages: UIChatMessage[] = [
+ {
+ id: 'new-msg-1',
+ content: 'New 1',
+ role: 'user',
+ createdAt: 1000,
+ updatedAt: 1000,
+ meta: {},
+ },
+ {
+ id: 'new-msg-2',
+ content: 'New 2',
+ role: 'assistant',
+ createdAt: 2000,
+ updatedAt: 2000,
+ meta: {},
+ },
+ ];
+
+ store.getState().replaceMessages(newMessages);
+
+ const state = store.getState();
+ expect(state.displayMessages).toHaveLength(2);
+ expect(state.displayMessages[0].id).toBe('new-msg-1');
+ expect(state.displayMessages[1].id).toBe('new-msg-2');
+ expect(state.dbMessages.find((m) => m.id === 'old-msg')).toBeUndefined();
+ });
+
+ it('should handle empty messages array', () => {
+ const store = createTestStore();
+
+ // Add a message first
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'msg-1',
+ value: { content: 'Hello', role: 'user', sessionId: 'session-1' },
+ });
+
+ // Replace with empty
+ store.getState().replaceMessages([]);
+
+ const state = store.getState();
+ expect(state.displayMessages).toHaveLength(0);
+ expect(state.dbMessages).toHaveLength(0);
+ });
+ });
+
+ describe('selectors', () => {
+ it('displayMessages should return display messages array', () => {
+ const store = createTestStore();
+
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'msg-1',
+ value: { content: 'Hello', role: 'user', sessionId: 'session-1' },
+ });
+
+ const messages = dataSelectors.displayMessages(store.getState());
+ expect(messages).toHaveLength(1);
+ expect(messages[0].content).toBe('Hello');
+ });
+
+ it('displayMessageIds should return array of message IDs', () => {
+ const store = createTestStore();
+
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'msg-1',
+ value: { content: 'Hello', role: 'user', sessionId: 'session-1' },
+ });
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'msg-2',
+ value: { content: 'World', role: 'assistant', sessionId: 'session-1' },
+ });
+
+ const ids = dataSelectors.displayMessageIds(store.getState());
+ expect(ids).toContain('msg-1');
+ expect(ids).toContain('msg-2');
+ });
+
+ it('getDisplayMessageById should find message by ID', () => {
+ const store = createTestStore();
+
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'msg-1',
+ value: { content: 'Hello', role: 'user', sessionId: 'session-1' },
+ });
+
+ const message = dataSelectors.getDisplayMessageById('msg-1')(store.getState());
+ expect(message?.content).toBe('Hello');
+
+ const notFound = dataSelectors.getDisplayMessageById('nonexistent')(store.getState());
+ expect(notFound).toBeUndefined();
+ });
+
+ it('getDbMessageById should find message from dbMessages', () => {
+ const store = createTestStore();
+
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'msg-1',
+ value: { content: 'Hello', role: 'user', sessionId: 'session-1' },
+ });
+
+ const message = dataSelectors.getDbMessageById('msg-1')(store.getState());
+ expect(message?.content).toBe('Hello');
+ });
+
+ it('messagesInit should return initialization state', () => {
+ const store = createTestStore();
+
+ expect(dataSelectors.messagesInit(store.getState())).toBe(false);
+ });
+
+ describe('getGroupLatestMessageWithoutTools', () => {
+ it('should return undefined for non-existent message', () => {
+ const store = createTestStore();
+
+ const result = dataSelectors.getGroupLatestMessageWithoutTools('non-existent')(
+ store.getState(),
+ );
+ expect(result).toBeUndefined();
+ });
+
+ it('should return undefined for non-group message', () => {
+ const store = createTestStore();
+
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'msg-1',
+ value: { content: 'Hello', role: 'user', sessionId: 'session-1' },
+ });
+
+ const result = dataSelectors.getGroupLatestMessageWithoutTools('msg-1')(store.getState());
+ expect(result).toBeUndefined();
+ });
+
+ it('should return last child without tools from assistantGroup', () => {
+ const store = createTestStore();
+
+ // Create a group message with children
+ const groupMessage = {
+ id: 'group-1',
+ content: '',
+ role: 'assistantGroup' as const,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ children: [
+ { id: 'child-1', content: 'First response', role: 'assistant' as const },
+ { id: 'child-2', content: 'Second response', role: 'assistant' as const },
+ ],
+ };
+
+ store.getState().replaceMessages([groupMessage as any]);
+
+ const result = dataSelectors.getGroupLatestMessageWithoutTools('group-1')(store.getState());
+ expect(result?.id).toBe('child-2');
+ expect(result?.content).toBe('Second response');
+ });
+
+ it('should return undefined if last child has tools', () => {
+ const store = createTestStore();
+
+ const groupMessage = {
+ id: 'group-1',
+ content: '',
+ role: 'assistantGroup' as const,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ children: [
+ { id: 'child-1', content: 'First response', role: 'assistant' as const },
+ {
+ id: 'child-2',
+ content: 'Second response',
+ role: 'assistant' as const,
+ tools: [
+ {
+ id: 'tool-1',
+ type: 'default',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '',
+ },
+ ],
+ },
+ ],
+ };
+
+ store.getState().replaceMessages([groupMessage as any]);
+
+ const result = dataSelectors.getGroupLatestMessageWithoutTools('group-1')(store.getState());
+ expect(result).toBeUndefined();
+ });
+
+ it('should return undefined if last child has no content', () => {
+ const store = createTestStore();
+
+ const groupMessage = {
+ id: 'group-1',
+ content: '',
+ role: 'assistantGroup' as const,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ children: [
+ { id: 'child-1', content: 'First response', role: 'assistant' as const },
+ { id: 'child-2', content: '', role: 'assistant' as const },
+ ],
+ };
+
+ store.getState().replaceMessages([groupMessage as any]);
+
+ const result = dataSelectors.getGroupLatestMessageWithoutTools('group-1')(store.getState());
+ expect(result).toBeUndefined();
+ });
+
+ it('should return undefined for group with empty children', () => {
+ const store = createTestStore();
+
+ const groupMessage = {
+ id: 'group-1',
+ content: '',
+ role: 'assistantGroup' as const,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ children: [],
+ };
+
+ store.getState().replaceMessages([groupMessage as any]);
+
+ const result = dataSelectors.getGroupLatestMessageWithoutTools('group-1')(store.getState());
+ expect(result).toBeUndefined();
+ });
+ });
+ });
+
+ describe('useFetchMessages', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should pass threadId to messageService.getMessages', async () => {
+ const mockMessages: UIChatMessage[] = [
+ {
+ id: 'thread-msg-1',
+ content: 'Thread message',
+ role: 'user',
+ createdAt: 1000,
+ updatedAt: 1000,
+ meta: {},
+ },
+ ];
+
+ vi.mocked(messageService.getMessages).mockResolvedValue(mockMessages);
+
+ const store = createStore({
+ context: { agentId: 'test-session', topicId: 'test-topic', threadId: 'test-thread' },
+ });
+
+ // Call useFetchMessages - this triggers the SWR mock
+ store.getState().useFetchMessages({
+ agentId: 'test-session',
+ topicId: 'test-topic',
+ threadId: 'test-thread',
+ });
+
+ await waitFor(() => {
+ expect(messageService.getMessages).toHaveBeenCalledWith({
+ agentId: 'test-session',
+ threadId: 'test-thread',
+ topicId: 'test-topic',
+ });
+ });
+ });
+
+ it('should pass null threadId when provided as null', async () => {
+ const mockMessages: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ content: 'Regular message',
+ role: 'user',
+ createdAt: 1000,
+ updatedAt: 1000,
+ meta: {},
+ },
+ ];
+
+ vi.mocked(messageService.getMessages).mockResolvedValue(mockMessages);
+
+ const store = createStore({
+ context: { agentId: 'test-session', topicId: 'test-topic', threadId: null },
+ });
+
+ store.getState().useFetchMessages({
+ agentId: 'test-session',
+ topicId: 'test-topic',
+ threadId: null,
+ });
+
+ await waitFor(() => {
+ expect(messageService.getMessages).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'test-session',
+ topicId: 'test-topic',
+ }),
+ );
+ });
+ });
+
+ it('should not fetch when sessionId is empty', () => {
+ const store = createStore({
+ context: { agentId: '', topicId: null, threadId: null },
+ });
+
+ store.getState().useFetchMessages({
+ agentId: '',
+ topicId: null,
+ threadId: null,
+ });
+
+ // SWR should be called with null key (disabled)
+ expect(vi.mocked(useClientDataSWR)).toHaveBeenCalledWith(
+ null,
+ expect.any(Function),
+ expect.any(Object),
+ );
+ });
+
+ it('should use different SWR keys for different threadIds', () => {
+ const store1 = createStore({
+ context: { agentId: 'session-1', topicId: 'topic-1', threadId: 'thread-1' },
+ });
+
+ store1.getState().useFetchMessages({
+ agentId: 'session-1',
+ topicId: 'topic-1',
+ threadId: 'thread-1',
+ });
+
+ const firstCallKey = vi.mocked(useClientDataSWR).mock.calls[0][0];
+
+ const store2 = createStore({
+ context: { agentId: 'session-1', topicId: 'topic-1', threadId: 'thread-2' },
+ });
+
+ store2.getState().useFetchMessages({
+ agentId: 'session-1',
+ topicId: 'topic-1',
+ threadId: 'thread-2',
+ });
+
+ const secondCallKey = vi.mocked(useClientDataSWR).mock.calls[1][0];
+
+ // Keys should be different because threadIds are different
+ expect(firstCallKey).not.toEqual(secondCallKey);
+ expect((firstCallKey as any[])[1].threadId).toBe('thread-1');
+ expect((secondCallKey as any[])[1].threadId).toBe('thread-2');
+ });
+
+ it('should use same SWR key structure with Object containing sessionId, topicId, threadId', () => {
+ const store = createStore({
+ context: { agentId: 'test-session', topicId: 'test-topic', threadId: 'test-thread' },
+ });
+
+ store.getState().useFetchMessages({
+ agentId: 'test-session',
+ topicId: 'test-topic',
+ threadId: 'test-thread',
+ });
+
+ const swrKey = vi.mocked(useClientDataSWR).mock.calls[0][0] as any[];
+
+ // Key should be an array with prefix and context object
+ expect(Array.isArray(swrKey)).toBe(true);
+ expect(swrKey[0]).toBe('CONVERSATION_FETCH_MESSAGES');
+ expect(swrKey[1]).toEqual({
+ agentId: 'test-session',
+ topicId: 'test-topic',
+ threadId: 'test-thread',
+ });
+ });
+
+ it('should pass groupId to messageService.getMessages for group chat', async () => {
+ const mockMessages: UIChatMessage[] = [
+ {
+ id: 'group-msg-1',
+ content: 'Group message',
+ role: 'assistant',
+ createdAt: 1000,
+ updatedAt: 1000,
+ meta: {},
+ groupId: 'group-123',
+ agentId: 'worker-agent-1',
+ },
+ {
+ id: 'group-msg-2',
+ content: 'Another group message',
+ role: 'assistant',
+ createdAt: 2000,
+ updatedAt: 2000,
+ meta: {},
+ groupId: 'group-123',
+ agentId: 'worker-agent-2',
+ },
+ ];
+
+ vi.mocked(messageService.getMessages).mockResolvedValue(mockMessages);
+
+ const store = createStore({
+ context: {
+ agentId: 'supervisor-agent',
+ topicId: 'test-topic',
+ threadId: null,
+ groupId: 'group-123',
+ },
+ });
+
+ // Call useFetchMessages with groupId - this triggers the SWR mock
+ store.getState().useFetchMessages({
+ agentId: 'supervisor-agent',
+ topicId: 'test-topic',
+ threadId: null,
+ groupId: 'group-123',
+ });
+
+ await waitFor(() => {
+ expect(messageService.getMessages).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'supervisor-agent',
+ groupId: 'group-123',
+ topicId: 'test-topic',
+ }),
+ );
+ });
+ });
+
+ it('should not pass groupId when not in group context', async () => {
+ const mockMessages: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ content: 'Regular message',
+ role: 'user',
+ createdAt: 1000,
+ updatedAt: 1000,
+ meta: {},
+ },
+ ];
+
+ vi.mocked(messageService.getMessages).mockResolvedValue(mockMessages);
+
+ const store = createStore({
+ context: { agentId: 'test-session', topicId: 'test-topic', threadId: null },
+ });
+
+ store.getState().useFetchMessages({
+ agentId: 'test-session',
+ topicId: 'test-topic',
+ threadId: null,
+ });
+
+ await waitFor(() => {
+ expect(messageService.getMessages).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'test-session',
+ topicId: 'test-topic',
+ }),
+ );
+ });
+ });
+ });
+
+ describe('switchMessageBranch', () => {
+ it('should call updateMessageMetadata on parent message with branch index', async () => {
+ const store = createTestStore();
+
+ // Set up the message in the store's dbMessages array
+ store.setState({
+ dbMessages: [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ parentId: 'parent-msg-1',
+ content: 'test',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ },
+ ],
+ } as any);
+
+ const updateMessageMetadataSpy = vi.spyOn(store.getState(), 'updateMessageMetadata');
+
+ await act(async () => {
+ await store.getState().switchMessageBranch('msg-1', 2);
+ });
+
+ // Should update the parent's metadata, not the current message
+ expect(updateMessageMetadataSpy).toHaveBeenCalledWith('parent-msg-1', {
+ activeBranchIndex: 2,
+ });
+ });
+
+ it('should switch to branch index 0 on parent message', async () => {
+ const store = createTestStore();
+
+ // Set up the message in the store's dbMessages array
+ store.setState({
+ dbMessages: [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ parentId: 'parent-msg-1',
+ content: 'test',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ },
+ ],
+ } as any);
+
+ const updateMessageMetadataSpy = vi.spyOn(store.getState(), 'updateMessageMetadata');
+
+ await act(async () => {
+ await store.getState().switchMessageBranch('msg-1', 0);
+ });
+
+ // Should update the parent's metadata, not the current message
+ expect(updateMessageMetadataSpy).toHaveBeenCalledWith('parent-msg-1', {
+ activeBranchIndex: 0,
+ });
+ });
+
+ it('should not update metadata if message has no parentId', async () => {
+ const store = createTestStore();
+
+ // Set up a root message without parentId
+ store.setState({
+ dbMessages: [
+ {
+ id: 'msg-1',
+ role: 'user',
+ parentId: null,
+ content: 'test',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ },
+ ],
+ } as any);
+
+ const updateMessageMetadataSpy = vi.spyOn(store.getState(), 'updateMessageMetadata');
+
+ await act(async () => {
+ await store.getState().switchMessageBranch('msg-1', 2);
+ });
+
+ // Should not call updateMessageMetadata when there's no parent
+ expect(updateMessageMetadataSpy).not.toHaveBeenCalled();
+ });
+
+ it('should not update metadata if message does not exist', async () => {
+ const store = createTestStore();
+
+ // No messages in store
+ store.setState({
+ dbMessages: [],
+ } as any);
+
+ const updateMessageMetadataSpy = vi.spyOn(store.getState(), 'updateMessageMetadata');
+
+ await act(async () => {
+ await store.getState().switchMessageBranch('non-existent-msg', 2);
+ });
+
+ // Should not call updateMessageMetadata when message doesn't exist
+ expect(updateMessageMetadataSpy).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.ts
new file mode 100644
index 00000000000..b3f2a58dfe1
--- /dev/null
+++ b/src/features/Conversation/store/slices/data/action.ts
@@ -0,0 +1,133 @@
+import { parse } from '@lobechat/conversation-flow';
+import type { ConversationContext, UIChatMessage } from '@lobechat/types';
+import type { SWRResponse } from 'swr';
+import type { StateCreator } from 'zustand/vanilla';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { messageService } from '@/services/message';
+
+import type { Store as ConversationStore } from '../../action';
+import { type MessageDispatch, messagesReducer } from './reducer';
+import { dataSelectors } from './selectors';
+
+/**
+ * Data Actions
+ *
+ * Handles message fetching based on conversation context.
+ */
+export interface DataAction {
+ /**
+ * Dispatch message updates for optimistic UI updates
+ * This method updates the frontend state without persisting to database
+ */
+ internal_dispatchMessage: (payload: MessageDispatch) => void;
+
+ /**
+ * Replace all messages with new data
+ * Used for syncing after database operations (optimistic update pattern)
+ *
+ * @param messages - New messages array from database
+ */
+ replaceMessages: (messages: UIChatMessage[]) => void;
+
+ /**
+ * Switch message branch by updating the parent's activeBranchIndex
+ *
+ * @param messageId - The current message ID (with branch indicator)
+ * @param branchIndex - The new branch index to switch to
+ */
+ switchMessageBranch: (messageId: string, branchIndex: number) => Promise<void>;
+
+ /**
+ * Fetch messages for this conversation using SWR
+ *
+ * @param context - Conversation context with sessionId and topicId
+ * @param skipFetch - When true, SWR key is null and no fetch occurs
+ */
+ useFetchMessages: (
+ context: ConversationContext,
+ skipFetch?: boolean,
+ ) => SWRResponse<UIChatMessage[]>;
+}
+
+export const dataSlice: StateCreator<
+ ConversationStore,
+ [['zustand/devtools', never]],
+ [],
+ DataAction
+> = (set, get) => ({
+ internal_dispatchMessage: (payload) => {
+ const dbMessages = get().dbMessages;
+
+ // Apply array-based reducer - preserves message order
+ const newDbMessages = messagesReducer(dbMessages, payload);
+
+ // Check if anything changed
+ if (newDbMessages === dbMessages) return;
+
+ // Re-parse for display order and grouping
+ const { flatList } = parse(newDbMessages);
+
+ set({ dbMessages: newDbMessages, displayMessages: flatList }, false, {
+ payload,
+ type: `dispatchMessage/${payload.type}`,
+ });
+
+ // Sync changes to external store (ChatStore)
+ get().onMessagesChange?.(newDbMessages);
+ },
+
+ replaceMessages: (messages) => {
+ // Parse messages using conversation-flow
+ const { flatList } = parse(messages);
+
+ set({ dbMessages: messages, displayMessages: flatList }, false, 'replaceMessages');
+
+ // Sync changes to external store (ChatStore)
+ get().onMessagesChange?.(messages);
+ },
+
+ switchMessageBranch: async (messageId, branchIndex) => {
+ const state = get();
+
+ // Get the current message to find its parent
+ const message = dataSelectors.getDbMessageById(messageId)(state);
+ if (!message || !message.parentId) return;
+
+ // Update the parent's metadata.activeBranchIndex
+ // because the branch indicator is on the child message,
+ // but the activeBranchIndex is stored on the parent
+ await state.updateMessageMetadata(message.parentId, { activeBranchIndex: branchIndex });
+ },
+
+ useFetchMessages: (context, skipFetch) => {
+ // When skipFetch is true, SWR key is null - no fetch occurs
+ // This is used when external messages are provided (e.g., creating new thread)
+ const shouldFetch = !skipFetch && !!context.agentId;
+
+ return useClientDataSWR<UIChatMessage[]>(
+ shouldFetch ? ['CONVERSATION_FETCH_MESSAGES', context] : null,
+
+ async ([, key]: [string, ConversationContext]) => {
+ return messageService.getMessages(key as any);
+ },
+ {
+ onSuccess: (data) => {
+ if (!data) return;
+
+ // Parse messages using conversation-flow
+ const { flatList } = parse(data);
+
+ set({
+ dbMessages: data,
+ displayMessages: flatList,
+ messagesInit: true,
+ });
+
+ // Call onMessagesChange callback if provided
+ get().onMessagesChange?.(data);
+ },
+ },
+ );
+ },
+});
diff --git a/src/features/Conversation/store/slices/data/initialState.ts b/src/features/Conversation/store/slices/data/initialState.ts
new file mode 100644
index 00000000000..c10e0b2e343
--- /dev/null
+++ b/src/features/Conversation/store/slices/data/initialState.ts
@@ -0,0 +1,31 @@
+import type { UIChatMessage } from '@lobechat/types';
+
+export interface DataState {
+ /**
+ * Raw messages from DB (before parsing)
+ * Order is preserved from database fetch
+ */
+ dbMessages: UIChatMessage[];
+
+ /**
+ * Display messages array (parsed and sorted from conversation-flow)
+ * This is the source of truth for rendering
+ */
+ displayMessages: UIChatMessage[];
+
+ /**
+ * Whether messages have been initialized
+ */
+ messagesInit: boolean;
+
+ /**
+ * Skip internal message fetching (when external messages are provided)
+ */
+ skipFetch?: boolean;
+}
+
+export const dataInitialState: DataState = {
+ dbMessages: [],
+ displayMessages: [],
+ messagesInit: false,
+};
diff --git a/src/features/Conversation/store/slices/data/reducer.test.ts b/src/features/Conversation/store/slices/data/reducer.test.ts
new file mode 100644
index 00000000000..38ec6e0738c
--- /dev/null
+++ b/src/features/Conversation/store/slices/data/reducer.test.ts
@@ -0,0 +1,781 @@
+import { ChatToolPayload, UIChatMessage } from '@lobechat/types';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { MessageDispatch, messagesReducer } from './reducer';
+
+describe('messagesReducer', () => {
+ let initialState: UIChatMessage[];
+
+ beforeEach(() => {
+ initialState = [
+ {
+ id: 'message1',
+ content: 'Hello World',
+ createdAt: 1629264000000,
+ updatedAt: 1629264000000,
+ role: 'user',
+ meta: {},
+ },
+ {
+ id: 'message2',
+ content: 'How are you?',
+ createdAt: 1629264001000,
+ updatedAt: 1629264001000,
+ role: 'assistant',
+ meta: {},
+ tools: [
+ { identifier: 'tool1', apiName: 'calculator', id: 'abc', type: 'default', arguments: '' },
+ ],
+ },
+ ];
+ });
+
+ describe('updateMessage', () => {
+ it('should update the specified message with the provided value', () => {
+ const payload: MessageDispatch = {
+ type: 'updateMessage',
+ id: 'message1',
+ value: { content: 'Updated Message' },
+ };
+
+ const newState = messagesReducer(initialState, payload);
+
+ expect(newState[0]).toBeDefined();
+ expect(newState[0].content).toBe('Updated Message');
+ expect(newState[0].updatedAt).toBeGreaterThan(initialState[0].updatedAt);
+ });
+
+ it('should not modify the state if the specified message does not exist', () => {
+ const payload: MessageDispatch = {
+ type: 'updateMessage',
+ id: 'nonexistentMessage',
+ value: { content: 'Updated Message' },
+ };
+
+ const newState = messagesReducer(initialState, payload);
+
+ expect(newState).toBe(initialState);
+ });
+ });
+
+ describe('unimplemented type', () => {
+ it('should throw an error when an unimplemented type is provided', () => {
+ // @ts-ignore
+ const payload: MessageDispatch = { type: 'unimplementedType' };
+
+ expect(() => messagesReducer(initialState, payload)).toThrowError(
+ '未实现的 dispatch type,请检查 reducer',
+ );
+ });
+ });
+
+ describe('updateMessageExtra', () => {
+ it('should update the extra field of a message', () => {
+ const payload: MessageDispatch = {
+ type: 'updateMessageExtra',
+ id: 'message1',
+ key: 'testKey',
+ value: 'testValue',
+ };
+
+ const newState = messagesReducer(initialState, payload);
+
+ expect(newState[0].extra).toEqual({ testKey: 'testValue' });
+ expect(newState[0].updatedAt).toBeGreaterThan(initialState[0].updatedAt);
+ });
+
+ it('should update the extra field of a message if extra exist', () => {
+ const stateWithExtra: UIChatMessage[] = [
+ ...initialState,
+ {
+ id: 'data',
+ content: 'Hello World',
+ createdAt: 1629264000000,
+ updatedAt: 1629264000000,
+ role: 'user',
+ meta: {},
+ extra: { abc: '1' },
+ } as UIChatMessage,
+ ];
+
+ const payload: MessageDispatch = {
+ type: 'updateMessageExtra',
+ id: 'data',
+ key: 'abc',
+ value: '2',
+ };
+
+ const newState = messagesReducer(stateWithExtra, payload);
+
+ const dataMsg = newState.find((m) => m.id === 'data');
+ expect(dataMsg?.extra).toEqual({ abc: '2' });
+ expect(dataMsg?.updatedAt).toBeGreaterThan(1629264000000);
+ });
+
+ it('should not modify state if message is not found', () => {
+ const payload: MessageDispatch = {
+ type: 'updateMessageExtra',
+ id: 'nonexistent',
+ key: 'testKey',
+ value: 'testValue',
+ };
+
+ const newState = messagesReducer(initialState, payload);
+ expect(newState).toBe(initialState);
+ });
+ });
+
+ describe('updateMessageMetadata', () => {
+ it('should merge update the metadata field of a message', () => {
+ const payload: MessageDispatch = {
+ type: 'updateMessageMetadata',
+ id: 'message1',
+ value: { activeBranchIndex: 1 },
+ };
+
+ const newState = messagesReducer(initialState, payload);
+
+ expect(newState[0].metadata).toEqual({ activeBranchIndex: 1 });
+ expect(newState[0].updatedAt).toBeGreaterThan(initialState[0].updatedAt);
+ });
+
+ it('should merge update the metadata field if metadata already exists', () => {
+ const stateWithMetadata: UIChatMessage[] = [
+ {
+ ...initialState[0],
+ metadata: { activeBranchIndex: 0 },
+ },
+ initialState[1],
+ ];
+
+ const payload: MessageDispatch = {
+ type: 'updateMessageMetadata',
+ id: 'message1',
+ value: { activeBranchIndex: 2 },
+ };
+
+ const newState = messagesReducer(stateWithMetadata, payload);
+
+ expect(newState[0].metadata).toEqual({ activeBranchIndex: 2 });
+ expect(newState[0].updatedAt).toBeGreaterThan(stateWithMetadata[0].updatedAt);
+ });
+
+ it('should not modify state if message is not found', () => {
+ const payload: MessageDispatch = {
+ type: 'updateMessageMetadata',
+ id: 'nonexistent',
+ value: { activeBranchIndex: 1 },
+ };
+
+ const newState = messagesReducer(initialState, payload);
+ expect(newState).toBe(initialState);
+ });
+ });
+
+ describe('updatePluginState', () => {
+ it('should update the plugin state of a message', () => {
+ const payload: MessageDispatch = {
+ type: 'updatePluginState',
+ id: 'message1',
+ key: 'pluginKey',
+ value: 'pluginValue',
+ };
+
+ const newState = messagesReducer(initialState, payload);
+
+ expect(newState[0].pluginState).toEqual({ pluginKey: 'pluginValue' });
+ expect(newState[0].updatedAt).toBeGreaterThan(initialState[0].updatedAt);
+ });
+
+ it('should not modify state if message is not found', () => {
+ const payload: MessageDispatch = {
+ type: 'updatePluginState',
+ id: 'nonexistent',
+ key: 'pluginKey',
+ value: 'pluginValue',
+ };
+
+ const newState = messagesReducer(initialState, payload);
+ expect(newState).toBe(initialState);
+ });
+
+ it('should not modify state if new plugin state is equal to old state', () => {
+ const stateWithPluginState: UIChatMessage[] = [
+ {
+ ...initialState[0],
+ pluginState: { existingKey: 'existingValue' },
+ },
+ initialState[1],
+ ];
+
+ const payload: MessageDispatch = {
+ type: 'updatePluginState',
+ id: 'message1',
+ key: 'existingKey',
+ value: 'existingValue',
+ };
+
+ const newState = messagesReducer(stateWithPluginState, payload);
+ expect(newState).toBe(stateWithPluginState);
+ });
+ });
+
+ describe('updateMessagePlugin', () => {
+ it('should update the plugin of a tool message', () => {
+ const stateWithToolMessage: UIChatMessage[] = [
+ ...initialState,
+ {
+ id: 'toolMessage',
+ role: 'tool',
+ content: 'Tool content',
+ createdAt: 1629264000000,
+ updatedAt: 1629264000000,
+ meta: {},
+ plugin: {
+ identifier: 'tool1',
+ apiName: 'calculator',
+ type: 'default',
+ arguments: '',
+ },
+ tool_call_id: 'abc',
+ } as UIChatMessage,
+ ];
+
+ const payload: MessageDispatch = {
+ type: 'updateMessagePlugin',
+ id: 'toolMessage',
+ value: { identifier: 'newPlugin' },
+ };
+
+ const newState = messagesReducer(stateWithToolMessage, payload);
+
+ const toolMsg = newState.find((m) => m.id === 'toolMessage');
+ expect(toolMsg?.plugin).toEqual({
+ apiName: 'calculator',
+ arguments: '',
+ identifier: 'newPlugin',
+ type: 'default',
+ });
+ expect(toolMsg?.updatedAt).toBeGreaterThan(1629264000000);
+ });
+
+ it('should not modify state if message is not found or not a tool message', () => {
+ const payload: MessageDispatch = {
+ type: 'updateMessagePlugin',
+ id: 'message1', // This is a user message, not a tool message
+ value: { identifier: 'newPlugin' },
+ };
+
+ const newState = messagesReducer(initialState, payload);
+ expect(newState).toBe(initialState);
+ });
+ });
+
+ describe('updateMessageTools', () => {
+ it('should update a specific tool in an assistant message', () => {
+ const payload: MessageDispatch = {
+ type: 'updateMessageTools',
+ id: 'message2',
+ tool_call_id: 'abc',
+ value: { apiName: 'updatedCalculator' },
+ };
+
+ const newState = messagesReducer(initialState, payload);
+
+ expect(newState[1].tools?.[0]).toEqual({
+ apiName: 'updatedCalculator',
+ arguments: '',
+ id: 'abc',
+ identifier: 'tool1',
+ type: 'default',
+ });
+ expect(newState[1].updatedAt).toBeGreaterThan(initialState[1].updatedAt);
+ });
+
+ it('should not modify state if message is not found or not an assistant message', () => {
+ const payload: MessageDispatch = {
+ type: 'updateMessageTools',
+ id: 'message1', // This is a user message, not an assistant message
+ tool_call_id: 'tool1',
+ value: { identifier: 'updatedCalculator' },
+ };
+
+ const newState = messagesReducer(initialState, payload);
+ expect(newState).toBe(initialState);
+ });
+
+ it('should not modify state if tool is not found in the message', () => {
+ const payload: MessageDispatch = {
+ type: 'updateMessageTools',
+ id: 'message2',
+ tool_call_id: 'nonexistentTool',
+ value: { identifier: 'updatedCalculator' },
+ };
+
+ const newState = messagesReducer(initialState, payload);
+ expect(newState).toBe(initialState);
+ });
+ });
+
+ describe('addMessageTool', () => {
+ it('should add a tool to the specified assistant message if it does not have tools', () => {
+ const stateWithAssistant: UIChatMessage[] = [
+ ...initialState,
+ {
+ id: 'assistant1',
+ role: 'assistant',
+ content: '',
+ createdAt: 1629264000000,
+ updatedAt: 1629264000000,
+ meta: {},
+ } as UIChatMessage,
+ ];
+
+ const toolPayload: ChatToolPayload = {
+ id: 'tc_1',
+ type: 'default',
+ identifier: 'tool1',
+ apiName: 'testFunction',
+ arguments: '{"arg1": "value1"}',
+ };
+
+ const payload: MessageDispatch = {
+ type: 'addMessageTool',
+ id: 'assistant1',
+ value: toolPayload,
+ };
+
+ const newState = messagesReducer(stateWithAssistant, payload);
+
+ const assistant1 = newState.find((m) => m.id === 'assistant1');
+ expect(assistant1?.tools).toHaveLength(1);
+ expect(assistant1?.tools?.[0]).toEqual(toolPayload);
+ expect(assistant1?.updatedAt).toBeGreaterThan(1629264000000);
+ });
+
+ it('should add a tool to the specified assistant message', () => {
+ const toolPayload: ChatToolPayload = {
+ id: 'tc_1',
+ type: 'default',
+ identifier: 'tool1',
+ apiName: 'testFunction',
+ arguments: '{"arg1": "value1"}',
+ };
+
+ const payload: MessageDispatch = {
+ type: 'addMessageTool',
+ id: 'message2',
+ value: toolPayload,
+ };
+
+ const newState = messagesReducer(initialState, payload);
+
+ expect(newState[1].tools).toHaveLength(2);
+ expect(newState[1].tools?.[1]).toEqual(toolPayload);
+ });
+
+ it('should not modify the state if the message is not found', () => {
+ const toolPayload: ChatToolPayload = {
+ id: 'tc_1',
+ type: 'default',
+ identifier: 'tool1',
+ apiName: 'testFunction',
+ arguments: '{"arg1": "value1"}',
+ };
+
+ const payload: MessageDispatch = {
+ type: 'addMessageTool',
+ id: 'nonexistentMessage',
+ value: toolPayload,
+ };
+
+ const newState = messagesReducer(initialState, payload);
+ expect(newState).toBe(initialState);
+ });
+
+ it('should not add a tool if the message is not an assistant message', () => {
+ const toolPayload: ChatToolPayload = {
+ id: 'tc_1',
+ type: 'default',
+ identifier: 'tool1',
+ apiName: 'testFunction',
+ arguments: '{"arg1": "value1"}',
+ };
+
+ const payload: MessageDispatch = {
+ type: 'addMessageTool',
+ id: 'message1', // This is a user message
+ value: toolPayload,
+ };
+
+ const newState = messagesReducer(initialState, payload);
+ expect(newState).toBe(initialState);
+ });
+
+ it('should not add a tool if it already exists', () => {
+ const toolPayload: ChatToolPayload = {
+ id: 'abc', // Same id as existing tool
+ type: 'default',
+ identifier: 'tool1',
+ apiName: 'testFunction',
+ arguments: '{"arg1": "value1"}',
+ };
+
+ const payload: MessageDispatch = {
+ type: 'addMessageTool',
+ id: 'message2',
+ value: toolPayload,
+ };
+
+ const newState = messagesReducer(initialState, payload);
+ expect(newState).toBe(initialState);
+ });
+ });
+
+ describe('deleteMessageTool', () => {
+ it('should delete the specified tool from the message', () => {
+ const payload: MessageDispatch = {
+ type: 'deleteMessageTool',
+ id: 'message2',
+ tool_call_id: 'abc',
+ };
+
+ const newState = messagesReducer(initialState, payload);
+
+ expect(newState[1].tools).toHaveLength(0);
+ expect(newState[1].updatedAt).toBeGreaterThan(initialState[1].updatedAt);
+ });
+
+ it('should not modify the state if the message is not found', () => {
+ const payload: MessageDispatch = {
+ type: 'deleteMessageTool',
+ id: 'nonexistentMessage',
+ tool_call_id: 'tool1',
+ };
+
+ const newState = messagesReducer(initialState, payload);
+ expect(newState).toBe(initialState);
+ });
+
+ it('should not modify the state if the message has no tools', () => {
+ const payload: MessageDispatch = {
+ type: 'deleteMessageTool',
+ id: 'message1',
+ tool_call_id: 'nonexistentTool',
+ };
+
+ const newState = messagesReducer(initialState, payload);
+ expect(newState).toBe(initialState);
+ });
+
+ it('should not delete a tool if the message is not an assistant message', () => {
+ const payload: MessageDispatch = {
+ type: 'deleteMessageTool',
+ id: 'message1', // This is a user message
+ tool_call_id: 'tool1',
+ };
+
+ const newState = messagesReducer(initialState, payload);
+ expect(newState).toBe(initialState);
+ });
+ });
+
+ describe('createMessage', () => {
+ it('should add a new message to the state', () => {
+ const payload: MessageDispatch = {
+ type: 'createMessage',
+ id: 'newMessage',
+ value: {
+ content: 'New message content',
+ role: 'user',
+ sessionId: 'inbox',
+ },
+ };
+
+ const newState = messagesReducer(initialState, payload);
+
+ expect(newState.length).toBe(initialState.length + 1);
+ const newMsg = newState.find((m) => m.id === 'newMessage');
+ expect(newMsg).toBeDefined();
+ expect(newMsg?.content).toBe('New message content');
+ expect(newMsg?.role).toBe('user');
+ expect(newMsg?.createdAt).toBeDefined();
+ expect(newMsg?.updatedAt).toBeDefined();
+ expect(newMsg?.meta).toEqual({});
+ });
+ });
+
+ describe('deleteMessage', () => {
+ it('should remove a message from the state', () => {
+ const payload: MessageDispatch = {
+ type: 'deleteMessage',
+ id: 'message1',
+ };
+
+ const newState = messagesReducer(initialState, payload);
+
+ expect(newState.length).toBe(initialState.length - 1);
+ expect(newState.find((m) => m.id === 'message1')).toBeUndefined();
+ });
+
+ it('should not modify state if message to delete is not found', () => {
+ const payload: MessageDispatch = {
+ type: 'deleteMessage',
+ id: 'nonexistentMessage',
+ };
+
+ const newState = messagesReducer(initialState, payload);
+ expect(newState).toBe(initialState);
+ });
+ });
+
+ describe('deleteMessages', () => {
+ it('should remove multiple messages from the state', () => {
+ const payload: MessageDispatch = {
+ type: 'deleteMessages',
+ ids: ['message1', 'message2'],
+ };
+
+ const newState = messagesReducer(initialState, payload);
+
+ expect(newState.length).toBe(0);
+ expect(newState.find((m) => m.id === 'message1')).toBeUndefined();
+ expect(newState.find((m) => m.id === 'message2')).toBeUndefined();
+ });
+
+ it('should only delete existing messages', () => {
+ const payload: MessageDispatch = {
+ type: 'deleteMessages',
+ ids: ['message1', 'nonexistent'],
+ };
+
+ const newState = messagesReducer(initialState, payload);
+
+ expect(newState.length).toBe(1);
+ expect(newState.find((m) => m.id === 'message1')).toBeUndefined();
+ expect(newState.find((m) => m.id === 'message2')).toBeDefined();
+ });
+
+ it('should update child parentId when deleting parent chain', () => {
+ // Create a tree: A -> B -> C -> D
+ const treeState: UIChatMessage[] = [
+ {
+ id: 'A',
+ content: 'A',
+ role: 'user',
+ createdAt: 1,
+ updatedAt: 1,
+ meta: {},
+ parentId: undefined,
+ },
+ {
+ id: 'B',
+ content: 'B',
+ role: 'assistant',
+ createdAt: 2,
+ updatedAt: 2,
+ meta: {},
+ parentId: 'A',
+ },
+ {
+ id: 'C',
+ content: 'C',
+ role: 'tool',
+ createdAt: 3,
+ updatedAt: 3,
+ meta: {},
+ parentId: 'B',
+ },
+ {
+ id: 'D',
+ content: 'D',
+ role: 'user',
+ createdAt: 4,
+ updatedAt: 4,
+ meta: {},
+ parentId: 'C',
+ },
+ ];
+
+ // Delete B and C
+ const payload: MessageDispatch = {
+ type: 'deleteMessages',
+ ids: ['B', 'C'],
+ };
+
+ const newState = messagesReducer(treeState, payload);
+
+ // Should have A and D remaining
+ expect(newState.length).toBe(2);
+ expect(newState.find((m) => m.id === 'A')).toBeDefined();
+ expect(newState.find((m) => m.id === 'D')).toBeDefined();
+
+ // D's parentId should be updated to A (skipping deleted B and C)
+ const messageD = newState.find((m) => m.id === 'D');
+ expect(messageD?.parentId).toBe('A');
+ });
+
+ it('should set child parentId to undefined when deleting entire parent chain from root', () => {
+ // Create a tree: A -> B -> C -> D
+ const treeState: UIChatMessage[] = [
+ {
+ id: 'A',
+ content: 'A',
+ role: 'user',
+ createdAt: 1,
+ updatedAt: 1,
+ meta: {},
+ parentId: undefined,
+ },
+ {
+ id: 'B',
+ content: 'B',
+ role: 'assistant',
+ createdAt: 2,
+ updatedAt: 2,
+ meta: {},
+ parentId: 'A',
+ },
+ {
+ id: 'C',
+ content: 'C',
+ role: 'tool',
+ createdAt: 3,
+ updatedAt: 3,
+ meta: {},
+ parentId: 'B',
+ },
+ {
+ id: 'D',
+ content: 'D',
+ role: 'user',
+ createdAt: 4,
+ updatedAt: 4,
+ meta: {},
+ parentId: 'C',
+ },
+ ];
+
+ // Delete A, B, and C
+ const payload: MessageDispatch = {
+ type: 'deleteMessages',
+ ids: ['A', 'B', 'C'],
+ };
+
+ const newState = messagesReducer(treeState, payload);
+
+ // Should have only D remaining
+ expect(newState.length).toBe(1);
+ expect(newState[0].id).toBe('D');
+
+ // D's parentId should be undefined (all ancestors deleted)
+ expect(newState[0].parentId).toBeUndefined();
+ });
+
+ it('should handle multiple independent trees when batch deleting', () => {
+ // Tree 1: A -> B -> C, Tree 2: X -> Y -> Z
+ const treeState: UIChatMessage[] = [
+ {
+ id: 'A',
+ content: 'A',
+ role: 'user',
+ createdAt: 1,
+ updatedAt: 1,
+ meta: {},
+ parentId: undefined,
+ },
+ {
+ id: 'B',
+ content: 'B',
+ role: 'assistant',
+ createdAt: 2,
+ updatedAt: 2,
+ meta: {},
+ parentId: 'A',
+ },
+ {
+ id: 'C',
+ content: 'C',
+ role: 'user',
+ createdAt: 3,
+ updatedAt: 3,
+ meta: {},
+ parentId: 'B',
+ },
+ {
+ id: 'X',
+ content: 'X',
+ role: 'user',
+ createdAt: 4,
+ updatedAt: 4,
+ meta: {},
+ parentId: undefined,
+ },
+ {
+ id: 'Y',
+ content: 'Y',
+ role: 'assistant',
+ createdAt: 5,
+ updatedAt: 5,
+ meta: {},
+ parentId: 'X',
+ },
+ {
+ id: 'Z',
+ content: 'Z',
+ role: 'user',
+ createdAt: 6,
+ updatedAt: 6,
+ meta: {},
+ parentId: 'Y',
+ },
+ ];
+
+ // Delete B and Y
+ const payload: MessageDispatch = {
+ type: 'deleteMessages',
+ ids: ['B', 'Y'],
+ };
+
+ const newState = messagesReducer(treeState, payload);
+
+ // Should have A, C, X, Z remaining
+ expect(newState.length).toBe(4);
+
+ // C's parentId should be A
+ const messageC = newState.find((m) => m.id === 'C');
+ expect(messageC?.parentId).toBe('A');
+
+ // Z's parentId should be X
+ const messageZ = newState.find((m) => m.id === 'Z');
+ expect(messageZ?.parentId).toBe('X');
+ });
+ });
+
+ describe('updateMessages', () => {
+ it('should replace entire state with new messages', () => {
+ const newMessages: UIChatMessage[] = [
+ {
+ id: 'newMsg1',
+ content: 'New content',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ role: 'user',
+ meta: {},
+ },
+ ];
+
+ const payload: MessageDispatch = {
+ type: 'updateMessages',
+ value: newMessages,
+ };
+
+ const newState = messagesReducer(initialState, payload);
+
+ expect(newState).toEqual(newMessages);
+ expect(newState.find((m) => m.id === 'message1')).toBeUndefined();
+ expect(newState.find((m) => m.id === 'message2')).toBeUndefined();
+ expect(newState.find((m) => m.id === 'newMsg1')).toBeDefined();
+ });
+ });
+});
diff --git a/src/features/Conversation/store/slices/data/reducer.ts b/src/features/Conversation/store/slices/data/reducer.ts
new file mode 100644
index 00000000000..33d707ce31d
--- /dev/null
+++ b/src/features/Conversation/store/slices/data/reducer.ts
@@ -0,0 +1,313 @@
+import type {
+ ChatMessageExtra,
+ ChatToolPayload,
+ CreateMessageParams,
+ MessagePluginItem,
+ UIChatMessage,
+} from '@lobechat/types';
+import isEqual from 'fast-deep-equal';
+import { produce } from 'immer';
+
+import { merge } from '@/utils/merge';
+
+// ===== Dispatch Types =====
+
+interface UpdateMessages {
+ type: 'updateMessages';
+ value: UIChatMessage[];
+}
+
+interface UpdateMessage {
+ id: string;
+ type: 'updateMessage';
+ value: Partial<UIChatMessage>;
+}
+
+interface CreateMessage {
+ id: string;
+ type: 'createMessage';
+ value: CreateMessageParams;
+}
+
+interface DeleteMessage {
+ id: string;
+ type: 'deleteMessage';
+}
+
+interface DeleteMessages {
+ ids: string[];
+ type: 'deleteMessages';
+}
+
+interface UpdatePluginState {
+ id: string;
+ key: string;
+ type: 'updatePluginState';
+ value: any;
+}
+
+interface UpdateMessagePlugin {
+ id: string;
+ type: 'updateMessagePlugin';
+ value: Partial<MessagePluginItem>;
+}
+
+interface UpdateMessageTools {
+ id: string;
+ tool_call_id: string;
+ type: 'updateMessageTools';
+ value: Partial<ChatToolPayload>;
+}
+
+interface AddMessageTool {
+ id: string;
+ type: 'addMessageTool';
+ value: ChatToolPayload;
+}
+
+interface DeleteMessageTool {
+ id: string;
+ tool_call_id: string;
+ type: 'deleteMessageTool';
+}
+
+interface UpdateMessageExtra {
+ id: string;
+ key: string;
+ type: 'updateMessageExtra';
+ value: any;
+}
+
+interface UpdateMessageMetadata {
+ id: string;
+ type: 'updateMessageMetadata';
+ value: Partial<UIChatMessage['metadata']>;
+}
+
+export type MessageDispatch =
+ | CreateMessage
+ | UpdateMessage
+ | UpdateMessages
+ | UpdatePluginState
+ | UpdateMessageExtra
+ | UpdateMessageMetadata
+ | DeleteMessage
+ | UpdateMessagePlugin
+ | UpdateMessageTools
+ | AddMessageTool
+ | DeleteMessageTool
+ | DeleteMessages;
+
+// ===== Reducer =====
+
+/**
+ * Message reducer for array-based data structure
+ * Operates on UIChatMessage[] to preserve order
+ */
+export const messagesReducer = (
+ state: UIChatMessage[],
+ payload: MessageDispatch,
+): UIChatMessage[] => {
+ switch (payload.type) {
+ case 'updateMessage': {
+ const { id, value } = payload;
+ const index = state.findIndex((m) => m.id === id);
+ if (index < 0) return state;
+
+ return produce(state, (draft) => {
+ draft[index] = merge(draft[index], { ...value, updatedAt: Date.now() });
+ });
+ }
+
+ case 'updateMessageExtra': {
+ const { id, key, value } = payload;
+ const index = state.findIndex((m) => m.id === id);
+ if (index < 0) return state;
+
+ return produce(state, (draft) => {
+ const message = draft[index];
+ if (!message.extra) {
+ message.extra = { [key]: value } as ChatMessageExtra;
+ } else {
+ message.extra[key as keyof ChatMessageExtra] = value;
+ }
+ message.updatedAt = Date.now();
+ });
+ }
+
+ case 'updateMessageMetadata': {
+ const { id, value } = payload;
+ const index = state.findIndex((m) => m.id === id);
+ if (index < 0) return state;
+
+ return produce(state, (draft) => {
+ const message = draft[index];
+ message.metadata = merge(message.metadata, value);
+ message.updatedAt = Date.now();
+ });
+ }
+
+ case 'updatePluginState': {
+ const { id, key, value } = payload;
+ const index = state.findIndex((m) => m.id === id);
+ if (index < 0) return state;
+
+ const message = state[index];
+ const newPluginState = message.pluginState
+ ? merge(message.pluginState, { [key]: value })
+ : { [key]: value };
+
+ // Check if plugin state actually changed
+ if (isEqual(message.pluginState, newPluginState)) return state;
+
+ return produce(state, (draft) => {
+ draft[index].pluginState = newPluginState;
+ draft[index].updatedAt = Date.now();
+ });
+ }
+
+ case 'updateMessagePlugin': {
+ const { id, value } = payload;
+ const index = state.findIndex((m) => m.id === id);
+ if (index < 0) return state;
+
+ const message = state[index];
+ if (message.role !== 'tool') return state;
+
+ return produce(state, (draft) => {
+ draft[index].plugin = merge(draft[index].plugin, value);
+ draft[index].updatedAt = Date.now();
+ });
+ }
+
+ case 'addMessageTool': {
+ const { id, value } = payload;
+ const index = state.findIndex((m) => m.id === id);
+ if (index < 0) return state;
+
+ const message = state[index];
+ if (message.role !== 'assistant') return state;
+
+ const tools = message.tools || [];
+ // Check if tool already exists
+ if (tools.some((tool) => tool.id === value.id)) return state;
+
+ return produce(state, (draft) => {
+ if (!draft[index].tools) {
+ draft[index].tools = [value];
+ } else {
+ draft[index].tools!.push(value);
+ }
+ draft[index].updatedAt = Date.now();
+ });
+ }
+
+ case 'deleteMessageTool': {
+ const { id, tool_call_id } = payload;
+ const index = state.findIndex((m) => m.id === id);
+ if (index < 0) return state;
+
+ const message = state[index];
+ if (message.role !== 'assistant' || !message.tools) return state;
+
+ return produce(state, (draft) => {
+ draft[index].tools = draft[index].tools!.filter((tool) => tool.id !== tool_call_id);
+ draft[index].updatedAt = Date.now();
+ });
+ }
+
+ case 'updateMessageTools': {
+ const { id, value, tool_call_id } = payload;
+ const index = state.findIndex((m) => m.id === id);
+ if (index < 0) return state;
+
+ const message = state[index];
+ if (message.role !== 'assistant' || !message.tools) return state;
+
+ const toolIndex = message.tools.findIndex((tool) => tool.id === tool_call_id);
+ if (toolIndex < 0) return state;
+
+ return produce(state, (draft) => {
+ draft[index].tools![toolIndex] = merge(draft[index].tools![toolIndex], value);
+ draft[index].updatedAt = Date.now();
+ });
+ }
+
+ case 'createMessage': {
+ const { value, id } = payload;
+ const now = Date.now();
+
+ return produce(state, (draft) => {
+ draft.push({ ...value, createdAt: now, id, meta: {}, updatedAt: now } as UIChatMessage);
+ });
+ }
+
+ case 'updateMessages': {
+ return payload.value;
+ }
+
+ case 'deleteMessage': {
+ const { id } = payload;
+ const index = state.findIndex((m) => m.id === id);
+ if (index < 0) return state;
+
+ return produce(state, (draft) => {
+ draft.splice(index, 1);
+ });
+ }
+
+ case 'deleteMessages': {
+ const { ids } = payload;
+ const deleteSet = new Set(ids);
+
+ // Build parentId map for messages being deleted
+ const parentMap = new Map<string, string | null | undefined>();
+ for (const msg of state) {
+ if (deleteSet.has(msg.id)) {
+ parentMap.set(msg.id, msg.parentId);
+ }
+ }
+
+ // Find final ancestor (first ancestor not in deleteSet)
+ const finalAncestorMap = new Map<string, string | null | undefined>();
+ const findFinalAncestor = (id: string): string | null | undefined => {
+ if (finalAncestorMap.has(id)) return finalAncestorMap.get(id);
+
+ const parentId = parentMap.get(id);
+ if (parentId === null || parentId === undefined) {
+ finalAncestorMap.set(id, parentId);
+ return parentId;
+ }
+
+ if (!deleteSet.has(parentId)) {
+ finalAncestorMap.set(id, parentId);
+ return parentId;
+ }
+
+ const ancestor = findFinalAncestor(parentId);
+ finalAncestorMap.set(id, ancestor);
+ return ancestor;
+ };
+
+ for (const id of deleteSet) {
+ findFinalAncestor(id);
+ }
+
+ // Filter deleted messages and update parentId for remaining messages
+ return state
+ .filter((msg) => !deleteSet.has(msg.id))
+ .map((msg) => {
+ if (msg.parentId && deleteSet.has(msg.parentId)) {
+ const newParentId = finalAncestorMap.get(msg.parentId);
+ // Convert null to undefined to match UIChatMessage type
+ return { ...msg, parentId: newParentId ?? undefined };
+ }
+ return msg;
+ });
+ }
+
+ default: {
+ throw new Error('未实现的 dispatch type,请检查 reducer');
+ }
+ }
+};
diff --git a/src/features/Conversation/store/slices/data/selectors.ts b/src/features/Conversation/store/slices/data/selectors.ts
new file mode 100644
index 00000000000..aecee864e93
--- /dev/null
+++ b/src/features/Conversation/store/slices/data/selectors.ts
@@ -0,0 +1,121 @@
+import type { AssistantContentBlock, UIChatMessage } from '@lobechat/types';
+
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+
+import type { State } from '../../initialState';
+
+const displayMessages = (s: State) => s.displayMessages;
+const displayMessageIds = (s: State) => s.displayMessages.map((m) => m.id);
+const dbMessages = (s: State) => s.dbMessages;
+const messagesInit = (s: State) => s.messagesInit;
+const skipFetch = (s: State) => s.skipFetch;
+
+const getDisplayMessageById = (id: string) => (s: State) =>
+ s.displayMessages.find((m) => m.id === id);
+const getDbMessageById = (id: string) => (s: State) => s.dbMessages.find((m) => m.id === id);
+const getDbMessageByToolCallId = (id: string) => (s: State) =>
+ s.dbMessages.find((m) => m.tool_call_id === id);
+
+/**
+ * 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: State) => {
+ const message = getDisplayMessageById(id)(s);
+ return findLastMessageIdRecursive(message);
+};
+
+/**
+ * Gets the latest message block from a group message that doesn't contain tools
+ * Returns undefined if the last block contains tools or if message is not a group message
+ */
+const getGroupLatestMessageWithoutTools = (id: string) => (s: State) => {
+ const message = s.displayMessages.find((m) => m.id === id);
+
+ if (
+ !message ||
+ message.role !== 'assistantGroup' ||
+ !message.children ||
+ message.children.length === 0
+ )
+ return;
+
+ // Get the last child
+ const lastChild = message.children.at(-1);
+
+ if (!lastChild) return;
+
+ // Return the last child only if it doesn't have tools
+ if (!lastChild.tools || lastChild.tools.length === 0) {
+ if (!lastChild.content) return;
+
+ return lastChild;
+ }
+
+ return;
+};
+
+// ===== Topic-related selectors (bridged from ChatStore) =====
+
+/**
+ * Get the topic summary for current conversation
+ * This is a bridge selector that reads from global ChatStore
+ */
+const currentTopicSummary = () => {
+ const chatState = useChatStore.getState();
+ return topicSelectors.currentActiveTopicSummary(chatState);
+};
+
+export const dataSelectors = {
+ currentTopicSummary,
+ dbMessages,
+ displayMessageIds,
+ displayMessages,
+ findLastMessageId,
+ getDbMessageById,
+ getDbMessageByToolCallId,
+ getDisplayMessageById,
+ getGroupLatestMessageWithoutTools,
+ messagesInit,
+ skipFetch,
+};
diff --git a/src/features/Conversation/store/slices/generation/action.test.ts b/src/features/Conversation/store/slices/generation/action.test.ts
new file mode 100644
index 00000000000..8963a73a119
--- /dev/null
+++ b/src/features/Conversation/store/slices/generation/action.test.ts
@@ -0,0 +1,552 @@
+import { act } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation/types';
+
+import type { ConversationContext, ConversationHooks } from '../../../types';
+import { createStore } from '../../index';
+
+// Mock useChatStore
+const mockCancelOperations = vi.fn();
+const mockCancelOperation = vi.fn();
+const mockRegenerateUserMessage = vi.fn();
+const mockRegenerateAssistantMessage = vi.fn();
+const mockContinueGenerationMessage = vi.fn();
+const mockDeleteMessage = vi.fn();
+const mockSwitchMessageBranch = vi.fn();
+const mockStartOperation = vi.fn(() => ({ operationId: 'test-op-id' }));
+const mockCompleteOperation = vi.fn();
+const mockFailOperation = vi.fn();
+const mockInternalExecAgentRuntime = vi.fn();
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: {
+ getState: vi.fn(() => ({
+ messagesMap: {
+ 'session-1-': [
+ { id: 'msg-1', role: 'user', content: 'Hello' },
+ { id: 'msg-2', role: 'assistant', content: 'Hi there', parentId: 'msg-1' },
+ ],
+ },
+ operations: {},
+ messageLoadingIds: [],
+ cancelOperations: mockCancelOperations,
+ cancelOperation: mockCancelOperation,
+ regenerateUserMessage: mockRegenerateUserMessage,
+ regenerateAssistantMessage: mockRegenerateAssistantMessage,
+ continueGenerationMessage: mockContinueGenerationMessage,
+ deleteMessage: mockDeleteMessage,
+ switchMessageBranch: mockSwitchMessageBranch,
+ startOperation: mockStartOperation,
+ completeOperation: mockCompleteOperation,
+ failOperation: mockFailOperation,
+ internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ })),
+ setState: vi.fn(),
+ },
+}));
+
+describe('Generation Actions', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ vi.clearAllTimers();
+ });
+
+ describe('stopGenerating', () => {
+ it('should cancel all running execAgentRuntime operations', () => {
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: 'topic-1',
+ threadId: null,
+ };
+
+ const store = createStore({ context });
+
+ act(() => {
+ store.getState().stopGenerating();
+ });
+
+ expect(mockCancelOperations).toHaveBeenCalledWith(
+ {
+ type: AI_RUNTIME_OPERATION_TYPES,
+ status: 'running',
+ agentId: 'session-1',
+ topicId: 'topic-1',
+ },
+ expect.any(String),
+ );
+ });
+
+ it('should call onGenerationStop hook', () => {
+ const onGenerationStop = vi.fn();
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+ const hooks: ConversationHooks = { onGenerationStop };
+
+ const store = createStore({ context, hooks });
+
+ act(() => {
+ store.getState().stopGenerating();
+ });
+
+ expect(onGenerationStop).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('cancelOperation', () => {
+ it('should cancel specific operation via ChatStore', () => {
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+
+ const store = createStore({ context });
+
+ act(() => {
+ store.getState().cancelOperation('op-1', 'User cancelled');
+ });
+
+ expect(mockCancelOperation).toHaveBeenCalledWith('op-1', 'User cancelled');
+ });
+
+ it('should call onOperationCancelled hook', () => {
+ const onOperationCancelled = vi.fn();
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+ const hooks: ConversationHooks = { onOperationCancelled };
+
+ const store = createStore({ context, hooks });
+
+ act(() => {
+ store.getState().cancelOperation('op-1');
+ });
+
+ expect(onOperationCancelled).toHaveBeenCalledWith('op-1');
+ });
+ });
+
+ describe('clearOperations', () => {
+ it('should be a no-op since operations are managed by ChatStore', () => {
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+
+ const store = createStore({ context });
+
+ // clearOperations should be callable without error
+ act(() => {
+ store.getState().clearOperations();
+ });
+
+ // No assertions needed - it's a no-op
+ });
+ });
+
+ describe('continueGeneration', () => {
+ it('should continue generation from message with context including groupId', async () => {
+ // Reset mock to ensure all required functions are available
+ vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({
+ messagesMap: {},
+ operations: {},
+ startOperation: mockStartOperation,
+ completeOperation: mockCompleteOperation,
+ failOperation: mockFailOperation,
+ internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ } as any);
+
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: 'topic-1',
+ threadId: null,
+ groupId: 'group-1',
+ };
+
+ const store = createStore({ context });
+
+ // Set displayMessages after store creation
+ act(() => {
+ store.setState({
+ displayMessages: [{ id: 'msg-1', role: 'assistant', content: 'Hello' }],
+ } as any);
+ });
+
+ await act(async () => {
+ await store.getState().continueGeneration('msg-1');
+ });
+
+ // Should create operation with context including groupId
+ expect(mockStartOperation).toHaveBeenCalledWith({
+ context: { ...context, messageId: 'msg-1' },
+ type: 'continue',
+ });
+
+ // Should call internal_execAgentRuntime with context including groupId
+ expect(mockInternalExecAgentRuntime).toHaveBeenCalledWith(
+ expect.objectContaining({
+ context,
+ parentMessageId: 'msg-1',
+ parentMessageType: 'assistant',
+ parentOperationId: 'test-op-id',
+ }),
+ );
+ });
+
+ it('should call onBeforeContinue hook and respect false return', async () => {
+ // Reset mock to ensure all required functions are available
+ vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({
+ messagesMap: {},
+ operations: {},
+ startOperation: mockStartOperation,
+ completeOperation: mockCompleteOperation,
+ failOperation: mockFailOperation,
+ internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ } as any);
+
+ const onBeforeContinue = vi.fn().mockResolvedValue(false);
+
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+ const hooks: ConversationHooks = { onBeforeContinue };
+
+ const store = createStore({ context, hooks });
+
+ // Set displayMessages after store creation
+ act(() => {
+ store.setState({
+ displayMessages: [{ id: 'msg-1', role: 'assistant', content: 'Hello' }],
+ } as any);
+ });
+
+ await act(async () => {
+ await store.getState().continueGeneration('msg-1');
+ });
+
+ expect(onBeforeContinue).toHaveBeenCalledWith('msg-1');
+ // Should not call internal_execAgentRuntime if hook returns false
+ expect(mockInternalExecAgentRuntime).not.toHaveBeenCalled();
+ });
+
+ it('should call onContinueComplete hook after continuation', async () => {
+ // Reset mock to ensure all required functions are available
+ vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({
+ messagesMap: {},
+ operations: {},
+ startOperation: mockStartOperation,
+ completeOperation: mockCompleteOperation,
+ failOperation: mockFailOperation,
+ internal_execAgentRuntime: mockInternalExecAgentRuntime.mockResolvedValue(undefined),
+ } as any);
+
+ const onContinueComplete = vi.fn();
+
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+ const hooks: ConversationHooks = { onContinueComplete };
+
+ const store = createStore({ context, hooks });
+
+ // Set displayMessages after store creation
+ act(() => {
+ store.setState({
+ displayMessages: [{ id: 'msg-1', role: 'assistant', content: 'Hello' }],
+ } as any);
+ });
+
+ await act(async () => {
+ await store.getState().continueGeneration('msg-1');
+ });
+
+ expect(onContinueComplete).toHaveBeenCalledWith('msg-1');
+ });
+
+ it('should not continue if message is not found', async () => {
+ // Reset mock to ensure all required functions are available
+ vi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({
+ messagesMap: {},
+ operations: {},
+ startOperation: mockStartOperation,
+ completeOperation: mockCompleteOperation,
+ failOperation: mockFailOperation,
+ internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ } as any);
+
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+
+ const store = createStore({ context });
+
+ // Set empty displayMessages
+ act(() => {
+ store.setState({
+ displayMessages: [],
+ } as any);
+ });
+
+ await act(async () => {
+ await store.getState().continueGeneration('msg-not-exist');
+ });
+
+ // Should not create operation if message not found
+ expect(mockStartOperation).not.toHaveBeenCalled();
+ expect(mockInternalExecAgentRuntime).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('delAndRegenerateMessage', () => {
+ it('should create operation with context and pass operationId to deleteMessage', async () => {
+ // Re-setup mock to ensure all required functions are available
+ const { useChatStore } = await import('@/store/chat');
+ vi.mocked(useChatStore.getState).mockReturnValue({
+ messagesMap: {},
+ operations: {},
+ messageLoadingIds: [],
+ cancelOperations: mockCancelOperations,
+ cancelOperation: mockCancelOperation,
+ deleteMessage: mockDeleteMessage,
+ switchMessageBranch: mockSwitchMessageBranch,
+ startOperation: mockStartOperation,
+ completeOperation: mockCompleteOperation,
+ failOperation: mockFailOperation,
+ internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ } as any);
+
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: 'topic-1',
+ threadId: null,
+ groupId: 'group-1',
+ };
+
+ const store = createStore({ context });
+
+ // Set displayMessages after store creation
+ act(() => {
+ store.setState({
+ displayMessages: [
+ { id: 'msg-1', role: 'user', content: 'Hello' },
+ { id: 'msg-2', role: 'assistant', content: 'Hi there', parentId: 'msg-1' },
+ ],
+ } as any);
+ });
+
+ await act(async () => {
+ await store.getState().delAndRegenerateMessage('msg-2');
+ });
+
+ // Should create operation with context
+ expect(mockStartOperation).toHaveBeenCalledWith({
+ context: { ...context, messageId: 'msg-2' },
+ type: 'regenerate',
+ });
+
+ // Should pass operationId to deleteMessage for correct context isolation
+ expect(mockDeleteMessage).toHaveBeenCalledWith('msg-2', { operationId: 'test-op-id' });
+
+ // Should complete operation
+ expect(mockCompleteOperation).toHaveBeenCalledWith('test-op-id');
+ });
+ });
+
+ describe('delAndResendThreadMessage', () => {
+ it('should create operation with context and pass operationId to deleteMessage', async () => {
+ // Re-setup mock to ensure startOperation is available
+ const { useChatStore } = await import('@/store/chat');
+ vi.mocked(useChatStore.getState).mockReturnValue({
+ messagesMap: {},
+ operations: {},
+ messageLoadingIds: [],
+ cancelOperations: mockCancelOperations,
+ cancelOperation: mockCancelOperation,
+ deleteMessage: mockDeleteMessage,
+ switchMessageBranch: mockSwitchMessageBranch,
+ startOperation: mockStartOperation,
+ completeOperation: mockCompleteOperation,
+ internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ } as any);
+
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: 'topic-1',
+ threadId: 'thread-1',
+ groupId: 'group-1',
+ };
+
+ const store = createStore({ context });
+
+ // Set displayMessages after store creation
+ act(() => {
+ store.setState({
+ displayMessages: [{ id: 'msg-1', role: 'user', content: 'Hello' }],
+ } as any);
+ });
+
+ await act(async () => {
+ await store.getState().delAndResendThreadMessage('msg-1');
+ });
+
+ // Should create operation with context including threadId
+ expect(mockStartOperation).toHaveBeenCalledWith({
+ context: { ...context, messageId: 'msg-1' },
+ type: 'regenerate',
+ });
+
+ // Should pass operationId to deleteMessage
+ expect(mockDeleteMessage).toHaveBeenCalledWith('msg-1', { operationId: 'test-op-id' });
+
+ // Should complete operation
+ expect(mockCompleteOperation).toHaveBeenCalledWith('test-op-id');
+ });
+ });
+
+ describe('regenerateUserMessage', () => {
+ it('should pass operationId to switchMessageBranch for correct context', async () => {
+ // Re-setup mock with all required properties
+ const { useChatStore } = await import('@/store/chat');
+ vi.mocked(useChatStore.getState).mockReturnValue({
+ messagesMap: {},
+ operations: {},
+ messageLoadingIds: [],
+ cancelOperations: mockCancelOperations,
+ cancelOperation: mockCancelOperation,
+ deleteMessage: mockDeleteMessage,
+ switchMessageBranch: mockSwitchMessageBranch,
+ startOperation: mockStartOperation,
+ completeOperation: mockCompleteOperation,
+ failOperation: mockFailOperation,
+ internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ } as any);
+
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: 'topic-1',
+ threadId: null,
+ groupId: 'group-1',
+ };
+
+ const store = createStore({ context });
+
+ // Set displayMessages after store creation
+ act(() => {
+ store.setState({
+ displayMessages: [{ id: 'msg-1', role: 'user', content: 'Hello', branch: { count: 2 } }],
+ } as any);
+ });
+
+ await act(async () => {
+ await store.getState().regenerateUserMessage('msg-1');
+ });
+
+ // Should create operation with context
+ expect(mockStartOperation).toHaveBeenCalledWith({
+ context: { ...context, messageId: 'msg-1' },
+ type: 'regenerate',
+ });
+
+ // Should pass operationId to switchMessageBranch
+ expect(mockSwitchMessageBranch).toHaveBeenCalledWith('msg-1', 2, {
+ operationId: 'test-op-id',
+ });
+ });
+
+ it('should pass context to internal_execAgentRuntime', async () => {
+ // Re-setup mock with all required properties
+ const { useChatStore } = await import('@/store/chat');
+ vi.mocked(useChatStore.getState).mockReturnValue({
+ messagesMap: {},
+ operations: {},
+ messageLoadingIds: [],
+ cancelOperations: mockCancelOperations,
+ cancelOperation: mockCancelOperation,
+ deleteMessage: mockDeleteMessage,
+ switchMessageBranch: mockSwitchMessageBranch,
+ startOperation: mockStartOperation,
+ completeOperation: mockCompleteOperation,
+ failOperation: mockFailOperation,
+ internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ } as any);
+
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: 'topic-1',
+ threadId: null,
+ groupId: 'group-1',
+ };
+
+ const store = createStore({ context });
+
+ // Set displayMessages after store creation
+ act(() => {
+ store.setState({
+ displayMessages: [{ id: 'msg-1', role: 'user', content: 'Hello' }],
+ } as any);
+ });
+
+ await act(async () => {
+ await store.getState().regenerateUserMessage('msg-1');
+ });
+
+ // Should pass full context to internal_execAgentRuntime
+ expect(mockInternalExecAgentRuntime).toHaveBeenCalledWith(
+ expect.objectContaining({
+ context,
+ parentMessageId: 'msg-1',
+ parentMessageType: 'user',
+ parentOperationId: 'test-op-id',
+ }),
+ );
+ });
+
+ it('should not regenerate if message is already loading', async () => {
+ // Mock messageLoadingIds to include the target message
+ const { useChatStore } = await import('@/store/chat');
+ vi.mocked(useChatStore.getState).mockReturnValue({
+ messagesMap: {},
+ messageLoadingIds: ['msg-1'],
+ startOperation: mockStartOperation,
+ } as any);
+
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+
+ const store = createStore({ context });
+
+ // Set displayMessages after store creation
+ act(() => {
+ store.setState({
+ displayMessages: [{ id: 'msg-1', role: 'user', content: 'Hello' }],
+ } as any);
+ });
+
+ await act(async () => {
+ await store.getState().regenerateUserMessage('msg-1');
+ });
+
+ // Should not create operation if already regenerating
+ expect(mockStartOperation).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.ts
new file mode 100644
index 00000000000..e6895b2cc64
--- /dev/null
+++ b/src/features/Conversation/store/slices/generation/action.ts
@@ -0,0 +1,345 @@
+import type { StateCreator } from 'zustand';
+
+import { MESSAGE_CANCEL_FLAT } from '@/const/index';
+import { useChatStore } from '@/store/chat';
+import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation/types';
+
+import type { Store as ConversationStore } from '../../action';
+
+/**
+ * Generation Actions
+ *
+ * Handles generation control (stop, cancel, regenerate, continue)
+ */
+export interface GenerationAction {
+ /**
+ * Cancel a specific operation
+ */
+ cancelOperation: (operationId: string, reason?: string) => void;
+
+ /**
+ * Clear all operations
+ */
+ clearOperations: () => void;
+
+ /**
+ * Clear TTS for a message
+ * @deprecated Temporary bridge to ChatStore
+ */
+ clearTTS: (messageId: string) => Promise<void>;
+
+ /**
+ * Clear translate for a message
+ * @deprecated Temporary bridge to ChatStore
+ */
+ clearTranslate: (messageId: string) => Promise<void>;
+
+ /**
+ * Continue generation from a message
+ */
+ continueGeneration: (messageId: string) => Promise<void>;
+
+ /**
+ * Continue generation from a specific block
+ */
+ continueGenerationMessage: (blockId: string, messageId: string) => Promise<void>;
+
+ /**
+ * Delete and regenerate a message
+ */
+ delAndRegenerateMessage: (messageId: string) => Promise<void>;
+
+ /**
+ * Delete and resend a thread message
+ */
+ delAndResendThreadMessage: (messageId: string) => Promise<void>;
+
+ /**
+ * Open thread creator
+ * @deprecated Temporary bridge to ChatStore
+ */
+ openThreadCreator: (messageId: string) => void;
+
+ /**
+ * Re-invoke a tool message
+ * @deprecated Temporary bridge to ChatStore
+ */
+ reInvokeToolMessage: (messageId: string) => Promise<void>;
+
+ /**
+ * Regenerate an assistant message
+ */
+ regenerateAssistantMessage: (messageId: string) => Promise<void>;
+
+ /**
+ * Regenerate a user message
+ */
+ regenerateUserMessage: (messageId: string) => Promise<void>;
+
+ /**
+ * Resend a thread message
+ */
+ resendThreadMessage: (messageId: string) => Promise<void>;
+
+ /**
+ * Stop current generation
+ */
+ stopGenerating: () => void;
+
+ /**
+ * Translate a message
+ * @deprecated Temporary bridge to ChatStore
+ */
+ translateMessage: (messageId: string, targetLang: string) => Promise<void>;
+
+ /**
+ * TTS a message
+ * @deprecated Temporary bridge to ChatStore
+ */
+ ttsMessage: (
+ messageId: string,
+ state?: { contentMd5?: string; file?: string; voice?: string },
+ ) => Promise<void>;
+}
+
+export const generationSlice: StateCreator<
+ ConversationStore,
+ [['zustand/devtools', never]],
+ [],
+ GenerationAction
+> = (set, get) => ({
+ cancelOperation: (operationId: string, reason?: string) => {
+ const state = get();
+ const { hooks } = state;
+
+ const chatStore = useChatStore.getState();
+ chatStore.cancelOperation(operationId, reason || 'User cancelled');
+
+ // ===== Hook: onOperationCancelled =====
+ if (hooks.onOperationCancelled) {
+ hooks.onOperationCancelled(operationId);
+ }
+ },
+
+ clearOperations: () => {
+ // Operations are now managed by ChatStore, nothing to clear locally
+ },
+
+ clearTTS: async (messageId: string) => {
+ const chatStore = useChatStore.getState();
+ await chatStore.clearTTS(messageId);
+ },
+
+ clearTranslate: async (messageId: string) => {
+ const chatStore = useChatStore.getState();
+ await chatStore.clearTranslate(messageId);
+ },
+
+ continueGeneration: async (messageId: string) => {
+ // Note: continueGenerationMessage takes (blockId, messageId)
+ // For now, we use messageId for both since we don't have block ID
+ // Hooks are handled in continueGenerationMessage
+ await get().continueGenerationMessage(messageId, messageId);
+ },
+
+ continueGenerationMessage: async (blockId: string, messageId: string) => {
+ const { context, displayMessages, hooks } = get();
+ const chatStore = useChatStore.getState();
+
+ // Find the message (blockId refers to the assistant message to continue from)
+ const message = displayMessages.find((m) => m.id === blockId);
+ if (!message) return;
+
+ // ===== Hook: onBeforeContinue =====
+ if (hooks.onBeforeContinue) {
+ const shouldProceed = await hooks.onBeforeContinue(messageId);
+ if (shouldProceed === false) return;
+ }
+
+ // Create continue operation with ConversationStore context (includes groupId)
+ const { operationId } = chatStore.startOperation({
+ context: { ...context, messageId },
+ type: 'continue',
+ });
+
+ try {
+ // Execute agent runtime with full context from ConversationStore
+ await chatStore.internal_execAgentRuntime({
+ context,
+ messages: displayMessages,
+ parentMessageId: blockId,
+ parentMessageType: message.role as 'assistant' | 'tool' | 'user',
+ parentOperationId: operationId,
+ });
+
+ chatStore.completeOperation(operationId);
+
+ // ===== Hook: onContinueComplete =====
+ if (hooks.onContinueComplete) {
+ hooks.onContinueComplete(messageId);
+ }
+ } catch (error) {
+ chatStore.failOperation(operationId, {
+ message: error instanceof Error ? error.message : String(error),
+ type: 'ContinueError',
+ });
+ throw error;
+ }
+ },
+
+ delAndRegenerateMessage: async (messageId: string) => {
+ const { context } = get();
+ const chatStore = useChatStore.getState();
+
+ // Create operation to track context (use 'regenerate' type since this is a regenerate action)
+ const { operationId } = chatStore.startOperation({
+ context: { ...context, messageId },
+ type: 'regenerate',
+ });
+
+ // Regenerate first, then delete
+ await get().regenerateAssistantMessage(messageId);
+ await chatStore.deleteMessage(messageId, { operationId });
+ chatStore.completeOperation(operationId);
+ },
+
+ delAndResendThreadMessage: async (messageId: string) => {
+ const { context } = get();
+ const chatStore = useChatStore.getState();
+
+ // Create operation to track context (use 'regenerate' type since resend is essentially regenerate)
+ const { operationId } = chatStore.startOperation({
+ context: { ...context, messageId },
+ type: 'regenerate',
+ });
+
+ // Resend then delete
+ await get().resendThreadMessage(messageId);
+ await chatStore.deleteMessage(messageId, { operationId });
+ chatStore.completeOperation(operationId);
+ },
+
+ openThreadCreator: (messageId: string) => {
+ const chatStore = useChatStore.getState();
+ chatStore.openThreadCreator(messageId);
+ },
+
+ reInvokeToolMessage: async (messageId: string) => {
+ const chatStore = useChatStore.getState();
+ await chatStore.reInvokeToolMessage(messageId);
+ },
+
+ regenerateAssistantMessage: async (messageId: string) => {
+ const { displayMessages } = get();
+
+ // Find the assistant message
+ const currentIndex = displayMessages.findIndex((c) => c.id === messageId);
+ const currentMessage = displayMessages[currentIndex];
+
+ if (!currentMessage) return;
+
+ // Find the parent user message
+ const userId = currentMessage.parentId;
+ if (!userId) return;
+
+ // Delegate to regenerateUserMessage with the parent user message
+ await get().regenerateUserMessage(userId);
+ },
+
+ regenerateUserMessage: async (messageId: string) => {
+ const { context, displayMessages, hooks } = get();
+ const chatStore = useChatStore.getState();
+
+ // Check if already regenerating
+ const isRegenerating = chatStore.messageLoadingIds.includes(messageId);
+ if (isRegenerating) return;
+
+ // Find the message in current conversation messages
+ const currentIndex = displayMessages.findIndex((c) => c.id === messageId);
+ const item = displayMessages[currentIndex];
+ if (!item) return;
+
+ // Get context messages up to and including the target message
+ const contextMessages = displayMessages.slice(0, currentIndex + 1);
+ if (contextMessages.length <= 0) return;
+
+ // ===== Hook: onBeforeRegenerate =====
+ if (hooks.onBeforeRegenerate) {
+ const shouldProceed = await hooks.onBeforeRegenerate(messageId);
+ if (shouldProceed === false) return;
+ }
+
+ // Create regenerate operation with context
+ const { operationId } = chatStore.startOperation({
+ context: { ...context, messageId },
+ type: 'regenerate',
+ });
+
+ try {
+ // Switch to a new branch (pass operationId for correct context in optimistic update)
+ await chatStore.switchMessageBranch(messageId, item.branch ? item.branch.count : 1, {
+ operationId,
+ });
+
+ // Execute agent runtime with full context from ConversationStore
+ await chatStore.internal_execAgentRuntime({
+ context,
+ messages: contextMessages,
+ parentMessageId: messageId,
+ parentMessageType: 'user',
+ parentOperationId: operationId,
+ });
+
+ chatStore.completeOperation(operationId);
+
+ // ===== Hook: onRegenerateComplete =====
+ if (hooks.onRegenerateComplete) {
+ hooks.onRegenerateComplete(messageId);
+ }
+ } catch (error) {
+ chatStore.failOperation(operationId, {
+ message: error instanceof Error ? error.message : String(error),
+ type: 'RegenerateError',
+ });
+ throw error;
+ }
+ },
+
+ resendThreadMessage: async (messageId: string) => {
+ // Resend is essentially regenerating the user message in thread context
+ await get().regenerateUserMessage(messageId);
+ },
+
+ stopGenerating: () => {
+ const state = get();
+ const { context, hooks } = state;
+ const { agentId, topicId } = context;
+
+ const chatStore = useChatStore.getState();
+
+ // Cancel all running AI runtime operations in this conversation context
+ // Includes both client-side (execAgentRuntime) and server-side (execServerAgentRuntime) operations
+ chatStore.cancelOperations(
+ { agentId, status: 'running', topicId, type: AI_RUNTIME_OPERATION_TYPES },
+ MESSAGE_CANCEL_FLAT,
+ );
+
+ // ===== Hook: onGenerationStop =====
+ if (hooks.onGenerationStop) {
+ hooks.onGenerationStop();
+ }
+ },
+
+ translateMessage: async (messageId: string, targetLang: string) => {
+ const chatStore = useChatStore.getState();
+ await chatStore.translateMessage(messageId, targetLang);
+ },
+
+ ttsMessage: async (
+ messageId: string,
+ state?: { contentMd5?: string; file?: string; voice?: string },
+ ) => {
+ const chatStore = useChatStore.getState();
+ await chatStore.ttsMessage(messageId, state);
+ },
+});
diff --git a/src/features/Conversation/store/slices/input/action.ts b/src/features/Conversation/store/slices/input/action.ts
new file mode 100644
index 00000000000..53c496c8008
--- /dev/null
+++ b/src/features/Conversation/store/slices/input/action.ts
@@ -0,0 +1,34 @@
+import type { StateCreator } from 'zustand';
+
+import type { State } from '../../initialState';
+
+export interface InputAction {
+ /**
+ * Cleanup input state
+ */
+ cleanupInput: () => void;
+
+ /**
+ * Set the editor instance
+ */
+ setEditor: (editor: any) => void;
+
+ /**
+ * Update the input message
+ */
+ updateInputMessage: (message: string) => void;
+}
+
+export const inputSlice: StateCreator<State & InputAction, [], [], InputAction> = (set) => ({
+ cleanupInput: () => {
+ set({ editor: null, inputMessage: '' });
+ },
+
+ setEditor: (editor) => {
+ set({ editor });
+ },
+
+ updateInputMessage: (message) => {
+ set({ inputMessage: message });
+ },
+});
diff --git a/src/features/Conversation/store/slices/input/initialState.ts b/src/features/Conversation/store/slices/input/initialState.ts
new file mode 100644
index 00000000000..19061361e73
--- /dev/null
+++ b/src/features/Conversation/store/slices/input/initialState.ts
@@ -0,0 +1,16 @@
+export interface InputState {
+ /**
+ * Editor instance (for ChatInput)
+ */
+ editor: any | null;
+
+ /**
+ * Current input message text
+ */
+ inputMessage: string;
+}
+
+export const inputInitialState: InputState = {
+ editor: null,
+ inputMessage: '',
+};
diff --git a/src/features/Conversation/store/slices/input/selectors.ts b/src/features/Conversation/store/slices/input/selectors.ts
new file mode 100644
index 00000000000..31c01e9a5ae
--- /dev/null
+++ b/src/features/Conversation/store/slices/input/selectors.ts
@@ -0,0 +1,11 @@
+import type { State } from '../../initialState';
+
+const editor = (s: State) => s.editor;
+const inputMessage = (s: State) => s.inputMessage;
+const hasInput = (s: State) => s.inputMessage.trim().length > 0;
+
+export const inputSelectors = {
+ editor,
+ hasInput,
+ inputMessage,
+};
diff --git a/src/features/Conversation/store/slices/message/action/crud.test.ts b/src/features/Conversation/store/slices/message/action/crud.test.ts
new file mode 100644
index 00000000000..ae82edd884d
--- /dev/null
+++ b/src/features/Conversation/store/slices/message/action/crud.test.ts
@@ -0,0 +1,920 @@
+import type { UIChatMessage } from '@lobechat/types';
+import { act } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import * as messageServiceModule from '@/services/message';
+
+import type { ConversationContext } from '../../../../types';
+import { createStore } from '../../../index';
+
+// Mock conversation-flow parse function (必须 mock,因为这是外部库)
+vi.mock('@lobechat/conversation-flow', () => ({
+ parse: (messages: UIChatMessage[]) => {
+ const messageMap: Record<string, UIChatMessage> = {};
+ for (const msg of messages) {
+ messageMap[msg.id] = msg;
+ }
+ const flatList = [...messages].sort((a, b) => a.createdAt - b.createdAt);
+ return { flatList, messageMap };
+ },
+}));
+
+// Create a test store
+const createTestStore = (context?: Partial<ConversationContext>) =>
+ createStore({
+ context: {
+ agentId: 'test-session',
+ topicId: null,
+ threadId: null,
+ ...context,
+ },
+ });
+
+describe('Message CRUD Actions', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ vi.clearAllTimers();
+ vi.restoreAllMocks();
+ });
+
+ describe('createMessage', () => {
+ it('should create a message with optimistic update', async () => {
+ const createMessageSpy = vi
+ .spyOn(messageServiceModule.messageService, 'createMessage')
+ .mockResolvedValue({
+ id: 'msg-1',
+ messages: [
+ {
+ id: 'msg-1',
+ content: 'Hello',
+ role: 'user',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ },
+ ],
+ });
+
+ const store = createTestStore();
+
+ let result: string | undefined;
+ await act(async () => {
+ result = await store.getState().createMessage({
+ content: 'Hello',
+ role: 'user',
+ sessionId: 'test-session',
+ });
+ });
+
+ expect(result).toBe('msg-1');
+ expect(createMessageSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: 'Hello',
+ role: 'user',
+ sessionId: 'test-session',
+ }),
+ );
+ });
+
+ it('should handle creation error', async () => {
+ vi.spyOn(messageServiceModule.messageService, 'createMessage').mockRejectedValue(
+ new Error('Creation failed'),
+ );
+
+ const store = createTestStore();
+
+ let result: string | undefined;
+ await act(async () => {
+ result = await store.getState().createMessage({
+ content: 'Hello',
+ role: 'user',
+ sessionId: 'test-session',
+ });
+ });
+
+ expect(result).toBeUndefined();
+ });
+ });
+
+ describe('createTempMessage', () => {
+ it('should create a temporary message for optimistic update', () => {
+ const store = createTestStore();
+
+ let tempId: string;
+ act(() => {
+ tempId = store.getState().createTempMessage({
+ content: 'Temp message',
+ role: 'user',
+ sessionId: 'test-session',
+ });
+ });
+
+ expect(tempId!).toMatch(/^tmp_/);
+
+ const state = store.getState();
+ expect(state.displayMessages.length).toBe(1);
+ expect(state.displayMessages[0].content).toBe('Temp message');
+ });
+ });
+
+ describe('deleteMessage', () => {
+ it('should delete a message', async () => {
+ // Use removeMessage for single message deletion
+ const removeMessageSpy = vi
+ .spyOn(messageServiceModule.messageService, 'removeMessage')
+ .mockResolvedValue({
+ success: true,
+ messages: [],
+ });
+
+ const store = createTestStore();
+
+ const testMessage = {
+ id: 'msg-1',
+ content: 'Hello',
+ role: 'user' as const,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ };
+
+ act(() => {
+ store.getState().replaceMessages([testMessage]);
+ });
+
+ expect(store.getState().displayMessages.length).toBe(1);
+ expect(store.getState().displayMessages[0].id).toBe('msg-1');
+
+ await store.getState().deleteMessage('msg-1');
+
+ expect(removeMessageSpy).toHaveBeenCalledWith('msg-1', {
+ agentId: 'test-session',
+ threadId: null,
+ topicId: null,
+ });
+ });
+
+ it('should delete assistantGroup with children and tool results', async () => {
+ const removeMessagesSpy = vi
+ .spyOn(messageServiceModule.messageService, 'removeMessages')
+ .mockResolvedValue({
+ success: true,
+ messages: [],
+ });
+
+ const store = createTestStore();
+
+ const groupMessage: UIChatMessage = {
+ id: 'group-1',
+ content: '',
+ role: 'assistantGroup',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ children: [
+ {
+ id: 'child-1',
+ content: 'Response',
+ tools: [
+ {
+ id: 'tool-1',
+ type: 'default',
+ identifier: 'test',
+ apiName: 'test',
+ arguments: '',
+ result: { id: 'tool-result-1', content: 'tool result content' },
+ },
+ ],
+ },
+ ],
+ };
+
+ act(() => {
+ store.getState().replaceMessages([groupMessage]);
+ });
+
+ await act(async () => {
+ await store.getState().deleteMessage('group-1');
+ });
+
+ expect(removeMessagesSpy).toHaveBeenCalledWith(
+ ['group-1', 'child-1', 'tool-result-1'],
+ expect.any(Object),
+ );
+ });
+
+ it('should use removeMessage for single id and removeMessages for multiple ids', async () => {
+ const removeMessageSpy = vi
+ .spyOn(messageServiceModule.messageService, 'removeMessage')
+ .mockResolvedValue({ success: true, messages: [] });
+ const removeMessagesSpy = vi
+ .spyOn(messageServiceModule.messageService, 'removeMessages')
+ .mockResolvedValue({ success: true, messages: [] });
+
+ const store = createTestStore();
+
+ // Test single message - should use removeMessage
+ const singleMessage = {
+ id: 'single-1',
+ content: 'Single',
+ role: 'user' as const,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ };
+
+ act(() => {
+ store.getState().replaceMessages([singleMessage]);
+ });
+
+ await store.getState().deleteMessage('single-1');
+
+ expect(removeMessageSpy).toHaveBeenCalledWith('single-1', expect.any(Object));
+ expect(removeMessagesSpy).not.toHaveBeenCalled();
+
+ // Reset spies
+ removeMessageSpy.mockClear();
+ removeMessagesSpy.mockClear();
+
+ // Test assistantGroup - should use removeMessages
+ const groupMessage: UIChatMessage = {
+ id: 'group-1',
+ content: '',
+ role: 'assistantGroup',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ children: [{ id: 'child-1', content: 'Response' }],
+ };
+
+ act(() => {
+ store.getState().replaceMessages([groupMessage]);
+ });
+
+ await store.getState().deleteMessage('group-1');
+
+ expect(removeMessagesSpy).toHaveBeenCalledWith(['group-1', 'child-1'], expect.any(Object));
+ expect(removeMessageSpy).not.toHaveBeenCalled();
+ });
+
+ it('should do nothing if message not found', async () => {
+ const removeMessagesSpy = vi.spyOn(messageServiceModule.messageService, 'removeMessages');
+
+ const store = createTestStore();
+
+ await act(async () => {
+ await store.getState().deleteMessage('nonexistent');
+ });
+
+ expect(removeMessagesSpy).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('deleteMessages', () => {
+ it('should delete multiple messages', async () => {
+ const removeMessagesSpy = vi
+ .spyOn(messageServiceModule.messageService, 'removeMessages')
+ .mockResolvedValue({
+ success: true,
+ messages: [],
+ });
+
+ const store = createTestStore();
+
+ act(() => {
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'msg-1',
+ value: { content: 'Hello', role: 'user', sessionId: 'test-session' },
+ });
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'msg-2',
+ value: { content: 'World', role: 'assistant', sessionId: 'test-session' },
+ });
+ });
+
+ expect(store.getState().displayMessages.length).toBe(2);
+
+ await act(async () => {
+ await store.getState().deleteMessages(['msg-1', 'msg-2']);
+ });
+
+ expect(removeMessagesSpy).toHaveBeenCalledWith(['msg-1', 'msg-2'], expect.any(Object));
+ });
+ });
+
+ describe('deleteToolMessage', () => {
+ it('should delete tool message and remove from parent', async () => {
+ const removeMessageSpy = vi
+ .spyOn(messageServiceModule.messageService, 'removeMessage')
+ .mockResolvedValue({
+ success: true,
+ messages: [],
+ });
+
+ const store = createTestStore();
+
+ act(() => {
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'assistant-1',
+ value: {
+ content: '',
+ role: 'assistant',
+ sessionId: 'test-session',
+ },
+ });
+ store.getState().internal_dispatchMessage({
+ type: 'addMessageTool',
+ id: 'assistant-1',
+ value: {
+ id: 'tool-call-1',
+ type: 'default',
+ identifier: 'test',
+ apiName: 'testFunc',
+ arguments: '{}',
+ },
+ });
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'tool-msg-1',
+ value: {
+ content: 'Tool result',
+ role: 'tool',
+ sessionId: 'test-session',
+ parentId: 'assistant-1',
+ tool_call_id: 'tool-call-1',
+ },
+ });
+ });
+
+ await act(async () => {
+ await store.getState().deleteToolMessage('tool-msg-1');
+ });
+
+ expect(removeMessageSpy).toHaveBeenCalledWith('tool-msg-1', expect.any(Object));
+ });
+ });
+
+ describe('clearMessages', () => {
+ it('should clear all messages in the conversation', async () => {
+ const removeMessagesByAssistantSpy = vi
+ .spyOn(messageServiceModule.messageService, 'removeMessagesByAssistant')
+ .mockResolvedValue({ rowsAffected: 1 } as any);
+
+ const store = createTestStore();
+
+ act(() => {
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'msg-1',
+ value: { content: 'Hello', role: 'user', sessionId: 'test-session' },
+ });
+ });
+
+ await act(async () => {
+ await store.getState().clearMessages();
+ });
+
+ expect(removeMessagesByAssistantSpy).toHaveBeenCalledWith('test-session', undefined);
+ expect(store.getState().displayMessages.length).toBe(0);
+ });
+ });
+
+ describe('updateMessageContent', () => {
+ it('should update message content', async () => {
+ const updateMessageSpy = vi
+ .spyOn(messageServiceModule.messageService, 'updateMessage')
+ .mockResolvedValue({
+ success: true,
+ messages: [
+ {
+ id: 'msg-1',
+ content: 'Updated content',
+ role: 'user',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ },
+ ],
+ });
+
+ const store = createTestStore();
+
+ act(() => {
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'msg-1',
+ value: { content: 'Hello', role: 'user', sessionId: 'test-session' },
+ });
+ });
+
+ await act(async () => {
+ await store.getState().updateMessageContent('msg-1', 'Updated content');
+ });
+
+ expect(updateMessageSpy).toHaveBeenCalledWith(
+ 'msg-1',
+ expect.objectContaining({ content: 'Updated content' }),
+ expect.any(Object),
+ );
+ });
+ });
+
+ describe('updateMessageMetadata', () => {
+ it('should update message metadata', async () => {
+ const updateMessageMetadataSpy = vi
+ .spyOn(messageServiceModule.messageService, 'updateMessageMetadata')
+ .mockResolvedValue({
+ success: true,
+ messages: [],
+ });
+
+ const store = createTestStore();
+
+ act(() => {
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'msg-1',
+ value: { content: 'Hello', role: 'user', sessionId: 'test-session' },
+ });
+ });
+
+ await act(async () => {
+ await store.getState().updateMessageMetadata('msg-1', { collapsed: true });
+ });
+
+ expect(updateMessageMetadataSpy).toHaveBeenCalledWith(
+ 'msg-1',
+ { collapsed: true },
+ expect.any(Object),
+ );
+ });
+ });
+
+ describe('toggleMessageCollapsed', () => {
+ it('should toggle message collapsed state', async () => {
+ const updateMessageMetadataSpy = vi
+ .spyOn(messageServiceModule.messageService, 'updateMessageMetadata')
+ .mockResolvedValue({
+ success: true,
+ messages: [],
+ });
+
+ const store = createTestStore();
+
+ act(() => {
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'msg-1',
+ value: { content: 'Hello', role: 'assistant', sessionId: 'test-session' },
+ });
+ });
+
+ await act(async () => {
+ await store.getState().toggleMessageCollapsed('msg-1', true);
+ });
+
+ expect(updateMessageMetadataSpy).toHaveBeenCalledWith(
+ 'msg-1',
+ { collapsed: true },
+ expect.any(Object),
+ );
+ });
+ });
+
+ describe('internal_toggleMessageLoading', () => {
+ it('should toggle message loading state', () => {
+ const store = createTestStore();
+
+ act(() => {
+ store.getState().internal_toggleMessageLoading(true, 'msg-1');
+ });
+
+ expect(store.getState().messageLoadingIds).toContain('msg-1');
+
+ act(() => {
+ store.getState().internal_toggleMessageLoading(false, 'msg-1');
+ });
+
+ expect(store.getState().messageLoadingIds).not.toContain('msg-1');
+ });
+ });
+
+ describe('copyMessage', () => {
+ it('should copy message content and call hook', async () => {
+ const onMessageCopied = vi.fn();
+
+ const store = createStore({
+ context: { agentId: 'test-session', topicId: null, threadId: null },
+ hooks: { onMessageCopied },
+ });
+
+ await act(async () => {
+ await store.getState().copyMessage('msg-1', 'Content to copy');
+ });
+
+ expect(onMessageCopied).toHaveBeenCalledWith('msg-1');
+ });
+ });
+
+ describe('modifyMessageContent', () => {
+ it('should modify message content and call hook', async () => {
+ vi.spyOn(messageServiceModule.messageService, 'updateMessage').mockResolvedValue({
+ success: true,
+ messages: [],
+ });
+
+ const onMessageModified = vi.fn();
+
+ const store = createStore({
+ context: { agentId: 'test-session', topicId: null, threadId: null },
+ hooks: { onMessageModified },
+ });
+
+ act(() => {
+ store.getState().replaceMessages([
+ {
+ id: 'msg-1',
+ content: 'Original',
+ role: 'user',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ meta: {},
+ },
+ ]);
+ });
+
+ await act(async () => {
+ await store.getState().modifyMessageContent('msg-1', 'Modified');
+ });
+
+ expect(onMessageModified).toHaveBeenCalledWith('msg-1', 'Modified', 'Original');
+ });
+ });
+
+ describe('addToolToMessage', () => {
+ it('should add tool to message', async () => {
+ const updateMessageSpy = vi
+ .spyOn(messageServiceModule.messageService, 'updateMessage')
+ .mockResolvedValue({
+ success: true,
+ messages: [],
+ });
+
+ const store = createTestStore();
+
+ act(() => {
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'msg-1',
+ value: { content: '', role: 'assistant', sessionId: 'test-session' },
+ });
+ });
+
+ const tool = {
+ id: 'tool-1',
+ type: 'default' as const,
+ identifier: 'test',
+ apiName: 'testFunc',
+ arguments: '{}',
+ };
+
+ await act(async () => {
+ await store.getState().addToolToMessage('msg-1', tool);
+ });
+
+ expect(updateMessageSpy).toHaveBeenCalledWith(
+ 'msg-1',
+ expect.objectContaining({ tools: [tool] }),
+ expect.any(Object),
+ );
+ });
+ });
+
+ describe('updatePluginArguments', () => {
+ it('should update plugin arguments using toolCallId', async () => {
+ const updateToolArgsSpy = vi
+ .spyOn(messageServiceModule.messageService, 'updateToolArguments')
+ .mockResolvedValue({ success: true, messages: [] } as any);
+ vi.spyOn(messageServiceModule.messageService, 'getMessages').mockResolvedValue([]);
+
+ const store = createTestStore();
+
+ // Create an assistant message with a tool, and a tool message
+ act(() => {
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'assistant-1',
+ value: { content: '', role: 'assistant', sessionId: 'test-session' },
+ });
+ store.getState().internal_dispatchMessage({
+ type: 'addMessageTool',
+ id: 'assistant-1',
+ value: {
+ id: 'tool-call-1',
+ type: 'default',
+ identifier: 'test',
+ apiName: 'testFunc',
+ arguments: '{"key": "old"}',
+ },
+ });
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'tool-msg-1',
+ value: {
+ content: '',
+ role: 'tool',
+ sessionId: 'test-session',
+ parentId: 'assistant-1',
+ tool_call_id: 'tool-call-1',
+ plugin: {
+ apiName: 'test',
+ arguments: '{"key": "old"}',
+ identifier: 'test-plugin',
+ type: 'default',
+ },
+ },
+ });
+ });
+
+ await act(async () => {
+ // Use toolCallId (tool-call-1) instead of message id
+ await store.getState().updatePluginArguments('tool-call-1', { key: 'new' }, true);
+ });
+
+ // Backend API now uses toolCallId directly
+ expect(updateToolArgsSpy).toHaveBeenCalledWith(
+ 'tool-call-1',
+ { key: 'new' },
+ expect.any(Object),
+ );
+ });
+
+ it('should update using toolCallId even when tool message not persisted (intervention pending)', async () => {
+ const updateToolArgsSpy = vi
+ .spyOn(messageServiceModule.messageService, 'updateToolArguments')
+ .mockResolvedValue({ success: true, messages: [] } as any);
+ vi.spyOn(messageServiceModule.messageService, 'getMessages').mockResolvedValue([]);
+
+ const store = createTestStore();
+
+ // Create an assistant message with a tool, but NO tool message (simulating intervention pending)
+ act(() => {
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'assistant-1',
+ value: { content: '', role: 'assistant', sessionId: 'test-session' },
+ });
+ store.getState().internal_dispatchMessage({
+ type: 'addMessageTool',
+ id: 'assistant-1',
+ value: {
+ id: 'tool-call-1',
+ type: 'default',
+ identifier: 'test',
+ apiName: 'testFunc',
+ arguments: '{"key": "old"}',
+ result_msg_id: 'tmp_123', // Temporary ID
+ },
+ });
+ });
+
+ await act(async () => {
+ await store.getState().updatePluginArguments('tool-call-1', { key: 'new' }, true);
+ });
+
+ // Backend API uses toolCallId and handles intervention pending internally
+ expect(updateToolArgsSpy).toHaveBeenCalledWith(
+ 'tool-call-1',
+ { key: 'new' },
+ expect.any(Object),
+ );
+ });
+
+ it('should register and remove pending promise during update', async () => {
+ let resolveUpdate: () => void;
+ const updatePromise = new Promise<void>((resolve) => {
+ resolveUpdate = resolve;
+ });
+
+ vi.spyOn(messageServiceModule.messageService, 'updateToolArguments').mockImplementation(
+ async () => {
+ await updatePromise;
+ return { success: true, messages: [] } as any;
+ },
+ );
+ vi.spyOn(messageServiceModule.messageService, 'getMessages').mockResolvedValue([]);
+
+ const store = createTestStore();
+
+ // Create assistant with tool and tool message
+ act(() => {
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'assistant-1',
+ value: { content: '', role: 'assistant', sessionId: 'test-session' },
+ });
+ store.getState().internal_dispatchMessage({
+ type: 'addMessageTool',
+ id: 'assistant-1',
+ value: {
+ id: 'tool-call-1',
+ type: 'default',
+ identifier: 'test',
+ apiName: 'testFunc',
+ arguments: '{"key": "old"}',
+ },
+ });
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'tool-msg-1',
+ value: {
+ content: '',
+ role: 'tool',
+ sessionId: 'test-session',
+ parentId: 'assistant-1',
+ tool_call_id: 'tool-call-1',
+ plugin: {
+ apiName: 'test',
+ arguments: '{"key": "old"}',
+ identifier: 'test-plugin',
+ type: 'default',
+ },
+ },
+ });
+ });
+
+ // Start update (don't await yet)
+ let updateFinished = false;
+ const updateAction = act(async () => {
+ await store.getState().updatePluginArguments('tool-call-1', { key: 'new' }, true);
+ updateFinished = true;
+ });
+
+ // Give time for the promise to be registered
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ // Verify pending promise is registered using toolCallId
+ expect(store.getState().pendingArgsUpdates.has('tool-call-1')).toBe(true);
+ expect(updateFinished).toBe(false);
+
+ // Resolve the update
+ resolveUpdate!();
+ await updateAction;
+
+ // Verify pending promise is removed after completion
+ expect(store.getState().pendingArgsUpdates.has('tool-call-1')).toBe(false);
+ expect(updateFinished).toBe(true);
+ });
+
+ it('should skip update if value is equal', async () => {
+ const updateToolArgsSpy = vi.spyOn(
+ messageServiceModule.messageService,
+ 'updateToolArguments',
+ );
+
+ const store = createTestStore();
+
+ act(() => {
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'assistant-1',
+ value: { content: '', role: 'assistant', sessionId: 'test-session' },
+ });
+ store.getState().internal_dispatchMessage({
+ type: 'addMessageTool',
+ id: 'assistant-1',
+ value: {
+ id: 'tool-call-1',
+ type: 'default',
+ identifier: 'test',
+ apiName: 'testFunc',
+ arguments: '{"key": "value"}',
+ },
+ });
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'tool-msg-1',
+ value: {
+ content: '',
+ role: 'tool',
+ sessionId: 'test-session',
+ parentId: 'assistant-1',
+ tool_call_id: 'tool-call-1',
+ plugin: {
+ apiName: 'test',
+ arguments: '{"key": "value"}',
+ identifier: 'test-plugin',
+ type: 'default',
+ },
+ },
+ });
+ });
+
+ await act(async () => {
+ // Update with same value using toolCallId
+ await store.getState().updatePluginArguments('tool-call-1', { key: 'value' }, true);
+ });
+
+ expect(updateToolArgsSpy).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('waitForPendingArgsUpdate', () => {
+ it('should wait for pending update to complete', async () => {
+ let resolveUpdate: () => void;
+ const updatePromise = new Promise<void>((resolve) => {
+ resolveUpdate = resolve;
+ });
+
+ vi.spyOn(messageServiceModule.messageService, 'updateToolArguments').mockImplementation(
+ async () => {
+ await updatePromise;
+ return { success: true, messages: [] } as any;
+ },
+ );
+ vi.spyOn(messageServiceModule.messageService, 'getMessages').mockResolvedValue([]);
+
+ const store = createTestStore();
+
+ act(() => {
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'assistant-1',
+ value: { content: '', role: 'assistant', sessionId: 'test-session' },
+ });
+ store.getState().internal_dispatchMessage({
+ type: 'addMessageTool',
+ id: 'assistant-1',
+ value: {
+ id: 'tool-call-1',
+ type: 'default',
+ identifier: 'test',
+ apiName: 'testFunc',
+ arguments: '{"key": "old"}',
+ },
+ });
+ store.getState().internal_dispatchMessage({
+ type: 'createMessage',
+ id: 'tool-msg-1',
+ value: {
+ content: '',
+ role: 'tool',
+ sessionId: 'test-session',
+ parentId: 'assistant-1',
+ tool_call_id: 'tool-call-1',
+ plugin: {
+ apiName: 'test',
+ arguments: '{"key": "old"}',
+ identifier: 'test-plugin',
+ type: 'default',
+ },
+ },
+ });
+ });
+
+ // Start update without awaiting (using toolCallId)
+ const updateAction = act(async () => {
+ await store.getState().updatePluginArguments('tool-call-1', { key: 'new' }, true);
+ });
+
+ // Give time for the promise to be registered
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ // Start waiting for pending update (using toolCallId)
+ let waitFinished = false;
+ const waitAction = act(async () => {
+ await store.getState().waitForPendingArgsUpdate('tool-call-1');
+ waitFinished = true;
+ });
+
+ // Give time for wait to start
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(waitFinished).toBe(false);
+
+ // Resolve the update
+ resolveUpdate!();
+ await updateAction;
+ await waitAction;
+
+ expect(waitFinished).toBe(true);
+ });
+
+ it('should resolve immediately if no pending update', async () => {
+ const store = createTestStore();
+
+ let waitFinished = false;
+ await act(async () => {
+ await store.getState().waitForPendingArgsUpdate('nonexistent-tool-call');
+ waitFinished = true;
+ });
+
+ expect(waitFinished).toBe(true);
+ });
+ });
+});
diff --git a/src/features/Conversation/store/slices/message/action/crud.ts b/src/features/Conversation/store/slices/message/action/crud.ts
new file mode 100644
index 00000000000..2808dc6ec5f
--- /dev/null
+++ b/src/features/Conversation/store/slices/message/action/crud.ts
@@ -0,0 +1,609 @@
+import {
+ ChatErrorType,
+ type ChatImageItem,
+ type ChatMessageError,
+ type ChatMessagePluginError,
+ type ChatToolPayload,
+ type ChatVideoItem,
+ type CreateMessageParams,
+ type GroundingSearch,
+ type MessageMetadata,
+ type MessagePluginItem,
+ type ModelReasoning,
+ type UpdateMessageRAGParams,
+} from '@lobechat/types';
+import { merge, nanoid, safeParseJSON } from '@lobechat/utils';
+import isEqual from 'fast-deep-equal';
+import type { StateCreator } from 'zustand';
+
+import { messageService } from '@/services/message';
+
+import type { Store as ConversationStore } from '../../../action';
+import { dataSelectors } from '../../data/selectors';
+
+/**
+ * Message CRUD Actions
+ *
+ * Handles all message create, read, update, delete operations
+ * with optimistic updates (update UI first, then persist to database)
+ */
+export interface MessageCRUDAction {
+ // ===== Update Tools ===== //
+ /**
+ * Add a tool to an assistant message
+ */
+ addToolToMessage: (messageId: string, tool: ChatToolPayload) => Promise<void>;
+
+ /**
+ * Clear all messages in the current conversation
+ */
+ clearMessages: () => Promise<void>;
+
+ // ===== Create ===== //
+ /**
+ * Create a message with optimistic update
+ * Returns the created message ID
+ */
+ createMessage: (params: CreateMessageParams) => Promise<string | undefined>;
+
+ /**
+ * Create a temporary message for optimistic update
+ * Used for immediate UI feedback before server response
+ */
+ createTempMessage: (
+ params: CreateMessageParams & {
+ imageList?: ChatImageItem[];
+ videoList?: ChatVideoItem[];
+ },
+ ) => string;
+
+ /**
+ * Delete an assistant message and its associated tool messages
+ */
+ deleteAssistantMessage: (id: string) => Promise<void>;
+
+ // ===== Delete ===== //
+ /**
+ * Delete a single message
+ */
+ deleteMessage: (id: string) => Promise<void>;
+
+ /**
+ * Delete multiple messages
+ */
+ deleteMessages: (ids: string[]) => Promise<void>;
+
+ /**
+ * Delete a tool message and remove the tool from its parent assistant message
+ */
+ deleteToolMessage: (id: string) => Promise<void>;
+
+ /**
+ * Remove a tool from an assistant message
+ */
+ removeToolFromMessage: (messageId: string, toolCallId: string) => Promise<void>;
+
+ // ===== Update Content ===== //
+ /**
+ * Update message content with optimistic update
+ */
+ updateMessageContent: (
+ id: string,
+ content: string,
+ extra?: {
+ imageList?: ChatImageItem[];
+ metadata?: MessageMetadata;
+ model?: string;
+ provider?: string;
+ reasoning?: ModelReasoning;
+ search?: GroundingSearch;
+ tools?: ChatToolPayload[];
+ },
+ ) => Promise<void>;
+
+ /**
+ * Update message error with optimistic update
+ */
+ updateMessageError: (id: string, error: ChatMessageError | null) => Promise<void>;
+
+ /**
+ * Update message metadata with optimistic update
+ */
+ updateMessageMetadata: (id: string, metadata: Partial<MessageMetadata>) => Promise<void>;
+
+ /**
+ * Update message plugin with optimistic update
+ */
+ updateMessagePlugin: (id: string, value: Partial<MessagePluginItem>) => Promise<void>;
+
+ /**
+ * Update message plugin error with optimistic update
+ */
+ updateMessagePluginError: (id: string, error: ChatMessagePluginError | null) => Promise<void>;
+
+ /**
+ * Update message RAG with optimistic update
+ */
+ updateMessageRAG: (id: string, data: UpdateMessageRAGParams) => Promise<void>;
+
+ /**
+ * Update a tool in an assistant message
+ */
+ updateMessageTool: (
+ messageId: string,
+ toolCallId: string,
+ value: Partial<ChatToolPayload>,
+ ) => Promise<void>;
+
+ /**
+ * Update plugin arguments with optimistic update
+ * Updates both the tool message plugin arguments and the parent assistant message tools
+ * @param toolCallId - The tool call ID (stable identifier from AI response)
+ * @param value - The new arguments value
+ * @param replace - If true, replace arguments entirely; if false, merge with existing
+ */
+ updatePluginArguments: <T = any>(
+ toolCallId: string,
+ value: T,
+ replace?: boolean,
+ ) => Promise<void>;
+
+ /**
+ * Wait for pending plugin arguments update to complete for a specific message
+ * Should be called before approve/reject to ensure all pending saves are complete
+ */
+ waitForPendingArgsUpdate: (messageId: string) => Promise<void>;
+}
+
+export const messageCRUDSlice: StateCreator<
+ ConversationStore,
+ [['zustand/devtools', never]],
+ [],
+ MessageCRUDAction
+> = (set, get) => ({
+ // ===== Update Tools ===== //
+ addToolToMessage: async (messageId, tool) => {
+ const { internal_dispatchMessage, replaceMessages, context } = get();
+
+ // Optimistic update
+ internal_dispatchMessage({
+ id: messageId,
+ type: 'addMessageTool',
+ value: tool,
+ });
+
+ // Persist to database
+ const result = await messageService.updateMessage(messageId, { tools: [tool] }, context);
+
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
+ },
+
+ clearMessages: async () => {
+ const { context, replaceMessages } = get();
+
+ // Clear from database
+ await messageService.removeMessagesByAssistant(context.agentId, context.topicId ?? undefined);
+
+ // Clear local state
+ replaceMessages([]);
+ },
+
+ // ===== Create ===== //
+ createMessage: async (params) => {
+ const { context, internal_dispatchMessage, replaceMessages, internal_toggleMessageLoading } =
+ get();
+
+ // Create temp message for optimistic update
+ const tempId = get().createTempMessage(params);
+ internal_toggleMessageLoading(true, tempId);
+
+ try {
+ const result = await messageService.createMessage({
+ ...params,
+ agentId: context.agentId,
+ topicId: context.topicId ?? undefined,
+ });
+
+ // Replace with server response
+ replaceMessages(result.messages);
+ internal_toggleMessageLoading(false, tempId);
+
+ return result.id;
+ } catch (e) {
+ internal_toggleMessageLoading(false, tempId);
+
+ // Update temp message with error
+ internal_dispatchMessage({
+ id: tempId,
+ type: 'updateMessage',
+ value: {
+ error: {
+ body: e,
+ message: (e as Error).message,
+ type: ChatErrorType.CreateMessageError,
+ },
+ },
+ });
+
+ return undefined;
+ }
+ },
+
+ createTempMessage: (params) => {
+ const { internal_dispatchMessage } = get();
+
+ const tempId = 'tmp_' + nanoid();
+ internal_dispatchMessage({
+ id: tempId,
+ type: 'createMessage',
+ value: params,
+ });
+
+ return tempId;
+ },
+
+ deleteAssistantMessage: async (id) => {
+ const message = dataSelectors.getDbMessageById(id)(get());
+ if (!message) return;
+
+ let ids = [message.id];
+
+ // If assistant message has tools, also delete tool messages
+ if (message.tools) {
+ const allMessages = get().dbMessages;
+ const toolMessageIds = message.tools.flatMap((tool) => {
+ const messages = allMessages.filter((m) => m.tool_call_id === tool.id);
+ return messages.map((m) => m.id);
+ });
+ ids = ids.concat(toolMessageIds);
+ }
+
+ await get().deleteMessages(ids);
+ },
+
+ // ===== Delete ===== //
+ deleteMessage: async (id) => {
+ const state = get();
+ const { internal_dispatchMessage, replaceMessages, context } = state;
+
+ const message = dataSelectors.getDisplayMessageById(id)(state);
+ if (!message) return;
+
+ let ids = [message.id];
+
+ // Handle assistantGroup messages: delete all child blocks and tool results
+ if (message.role === 'assistantGroup' && message.children) {
+ const childIds = message.children.map((child) => child.id);
+ ids = ids.concat(childIds);
+
+ // Collect all tool result IDs from children
+ const toolResultIds = message.children.flatMap((child) => {
+ if (!child.tools) return [];
+ return child.tools.filter((tool) => tool.result?.id).map((tool) => tool.result!.id);
+ });
+ ids = ids.concat(toolResultIds);
+ }
+
+ // Optimistic update
+ internal_dispatchMessage({ ids, type: 'deleteMessages' });
+
+ // Persist to database
+ // Use removeMessage for single message to properly handle parentId chain
+ // Use removeMessages for batch deletion (e.g., assistantGroup with children)
+ const result =
+ ids.length === 1
+ ? await messageService.removeMessage(ids[0], context)
+ : await messageService.removeMessages(ids, context);
+
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
+ },
+
+ deleteMessages: async (ids) => {
+ const { internal_dispatchMessage, replaceMessages, context } = get();
+
+ // Optimistic update
+ internal_dispatchMessage({ ids, type: 'deleteMessages' });
+
+ // Persist to database
+ const result = await messageService.removeMessages(ids, context);
+
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
+ },
+
+ deleteToolMessage: async (id) => {
+ const { internal_dispatchMessage, replaceMessages, context } = get();
+
+ const message = dataSelectors.getDbMessageById(id)(get());
+ if (!message || message.role !== 'tool') return;
+
+ // 1. Remove tool message
+ internal_dispatchMessage({ id, type: 'deleteMessage' });
+
+ // 2. Remove tool from parent assistant message
+ if (message.parentId && message.tool_call_id) {
+ internal_dispatchMessage({
+ id: message.parentId,
+ tool_call_id: message.tool_call_id,
+ type: 'deleteMessageTool',
+ });
+ }
+
+ // Persist to database
+ const result = await messageService.removeMessage(id, context);
+
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
+ },
+
+ removeToolFromMessage: async (messageId, toolCallId) => {
+ const { internal_dispatchMessage, replaceMessages, context } = get();
+
+ // Optimistic update
+ internal_dispatchMessage({
+ id: messageId,
+ tool_call_id: toolCallId,
+ type: 'deleteMessageTool',
+ });
+
+ // Get the updated tools for persistence
+ const message = dataSelectors.getDbMessageById(messageId)(get());
+ if (message) {
+ const result = await messageService.updateMessage(
+ messageId,
+ { tools: message.tools || [] },
+ context,
+ );
+
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
+ }
+ },
+
+ // ===== Update Content ===== //
+ updateMessageContent: async (id, content, extra) => {
+ const { internal_dispatchMessage, replaceMessages, context } = get();
+
+ // Optimistic update
+ if (extra?.tools) {
+ internal_dispatchMessage({
+ id,
+ type: 'updateMessage',
+ value: { tools: extra.tools },
+ });
+ } else {
+ internal_dispatchMessage({
+ id,
+ type: 'updateMessage',
+ value: { content },
+ });
+ }
+
+ // Persist to database
+ const result = await messageService.updateMessage(
+ id,
+ {
+ content,
+ imageList: extra?.imageList,
+ metadata: extra?.metadata,
+ model: extra?.model,
+ provider: extra?.provider,
+ reasoning: extra?.reasoning,
+ search: extra?.search,
+ tools: extra?.tools,
+ },
+ context,
+ );
+
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
+ },
+
+ updateMessageError: async (id, error) => {
+ const { internal_dispatchMessage, replaceMessages, context } = get();
+
+ // Optimistic update
+ internal_dispatchMessage({
+ id,
+ type: 'updateMessage',
+ value: { error },
+ });
+
+ // Persist to database
+ const result = await messageService.updateMessage(id, { error }, context);
+
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
+ },
+
+ updateMessageMetadata: async (id, metadata) => {
+ const { internal_dispatchMessage, replaceMessages, context } = get();
+
+ // Optimistic update
+ internal_dispatchMessage({ id, type: 'updateMessageMetadata', value: metadata });
+
+ // Persist to database
+ const result = await messageService.updateMessageMetadata(id, metadata, context);
+
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
+ },
+
+ updateMessagePlugin: async (id, value) => {
+ const { internal_dispatchMessage, replaceMessages, context } = get();
+
+ // Optimistic update
+ internal_dispatchMessage({
+ id,
+ type: 'updateMessagePlugin',
+ value,
+ });
+
+ // Persist to database
+ const result = await messageService.updateMessagePlugin(id, value, context);
+
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
+ },
+
+ updateMessagePluginError: async (id, error) => {
+ const { replaceMessages, context } = get();
+
+ // Persist to database (no optimistic update for plugin error)
+ const result = await messageService.updateMessagePluginError(id, error, context);
+
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
+ },
+
+ updateMessageRAG: async (id, data) => {
+ const { replaceMessages, context } = get();
+
+ // Persist to database
+ const result = await messageService.updateMessageRAG(id, data, context);
+
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
+ },
+
+ updateMessageTool: async (messageId, toolCallId, value) => {
+ const { internal_dispatchMessage, replaceMessages, context } = get();
+
+ // Optimistic update
+ internal_dispatchMessage({
+ id: messageId,
+ tool_call_id: toolCallId,
+ type: 'updateMessageTools',
+ value,
+ });
+
+ // Get the updated tools for persistence
+ const message = dataSelectors.getDbMessageById(messageId)(get());
+ if (message?.tools) {
+ const result = await messageService.updateMessage(
+ messageId,
+ { tools: message.tools },
+ context,
+ );
+
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
+ }
+ },
+
+ updatePluginArguments: async (toolCallId, value, replace = false) => {
+ const { internal_dispatchMessage, replaceMessages, context } = get();
+
+ // Find previous arguments from either tool message or parent's tools array
+ let prevArguments: string | undefined;
+ let toolMessageId: string | undefined;
+ let parentMessageId: string | undefined;
+
+ // First, try to find the tool message by toolCallId
+ const toolMessage = dataSelectors.getDbMessageByToolCallId(toolCallId)(get());
+ if (toolMessage) {
+ prevArguments = toolMessage.plugin?.arguments;
+ toolMessageId = toolMessage.id;
+ parentMessageId = toolMessage.parentId;
+ } else {
+ // Tool message not in dbMessages yet (intervention pending state)
+ // Find the tool from assistant message's tools array
+ const dbMessages = get().dbMessages;
+ for (const msg of dbMessages) {
+ if (msg.role === 'assistant' && msg.tools) {
+ const tool = msg.tools.find((t) => t.id === toolCallId);
+ if (tool) {
+ prevArguments = tool.arguments;
+ parentMessageId = msg.id;
+ toolMessageId = tool.result_msg_id; // May be tmp_xxx or undefined
+ break;
+ }
+ }
+ }
+ }
+
+ // If we can't find the tool anywhere, return early
+ if (prevArguments === undefined && !parentMessageId) {
+ console.warn('[updatePluginArguments] Cannot find tool with toolCallId:', toolCallId);
+ return;
+ }
+
+ const prevJson = safeParseJSON(prevArguments || '');
+ const nextValue = replace ? (value as any) : merge(prevJson || {}, value);
+ if (isEqual(prevJson, nextValue)) return;
+
+ const nextArgumentsStr = JSON.stringify(nextValue);
+
+ // Optimistic update - update tool message plugin (if it exists)
+ if (toolMessageId) {
+ internal_dispatchMessage({
+ id: toolMessageId,
+ type: 'updateMessagePlugin',
+ value: { arguments: nextArgumentsStr },
+ });
+ }
+
+ // Update parent assistant message tools
+ if (parentMessageId) {
+ internal_dispatchMessage({
+ id: parentMessageId,
+ tool_call_id: toolCallId,
+ type: 'updateMessageTools',
+ value: { arguments: nextArgumentsStr },
+ });
+ }
+
+ // Create the update promise - backend handles all cases using toolCallId
+ const updatePromise = (async () => {
+ const result = await messageService.updateToolArguments(toolCallId, nextValue, context);
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
+ })();
+
+ // Register the pending promise using toolCallId as key
+ set(
+ (state) => ({
+ pendingArgsUpdates: new Map(state.pendingArgsUpdates).set(toolCallId, updatePromise),
+ }),
+ false,
+ 'updatePluginArguments/pending',
+ );
+
+ try {
+ await updatePromise;
+ } finally {
+ // Remove the completed promise
+ set(
+ (state) => {
+ const newMap = new Map(state.pendingArgsUpdates);
+ newMap.delete(toolCallId);
+ return { pendingArgsUpdates: newMap };
+ },
+ false,
+ 'updatePluginArguments/complete',
+ );
+ }
+ },
+
+ waitForPendingArgsUpdate: async (messageId) => {
+ const pending = get().pendingArgsUpdates.get(messageId);
+ if (pending) {
+ await pending;
+ }
+ },
+});
diff --git a/src/features/Conversation/store/slices/message/action/index.ts b/src/features/Conversation/store/slices/message/action/index.ts
new file mode 100644
index 00000000000..b90405a4019
--- /dev/null
+++ b/src/features/Conversation/store/slices/message/action/index.ts
@@ -0,0 +1,117 @@
+import type { StateCreator } from 'zustand';
+
+import type { Store as ConversationStore } from '../../../action';
+import { type MessageCRUDAction, messageCRUDSlice } from './crud';
+import { sendMessage } from './sendMessage';
+import { type MessageStateAction, messageStateSlice } from './state';
+
+/**
+ * Message Actions
+ *
+ * Handles all message operations:
+ * - CRUD (create, read, update, delete)
+ * - State management (loading, collapsed, editing)
+ * - Sending messages
+ */
+export interface MessageAction extends MessageCRUDAction, MessageStateAction {
+ /**
+ * Add an AI message (convenience method)
+ */
+ addAIMessage: (content: string) => Promise<string | undefined>;
+
+ /**
+ * Add a user message (convenience method)
+ */
+ addUserMessage: (params: { fileList?: string[]; message: string }) => Promise<string | undefined>;
+
+ /**
+ * Send a message in this conversation (unified Main + Thread)
+ */
+ sendMessage: ReturnType<typeof sendMessage>;
+}
+
+export const messageSlice: StateCreator<
+ ConversationStore,
+ [['zustand/devtools', never]],
+ [],
+ MessageAction
+> = (set, get, ...rest) => ({
+ // Spread CRUD actions
+ ...messageCRUDSlice(set, get, ...rest),
+
+ // Spread state actions
+ ...messageStateSlice(set, get, ...rest),
+
+ // Convenience methods
+ addAIMessage: async (content: string) => {
+ const state = get();
+ const { context, hooks } = state;
+ const { agentId, topicId, threadId } = context;
+
+ // Get parent message ID
+ const displayMessages = state.displayMessages;
+ const parentId = displayMessages.length > 0 ? displayMessages.at(-1)?.id : undefined;
+
+ const id = await state.createMessage({
+ agentId: agentId,
+ content,
+ parentId,
+ role: 'assistant',
+ threadId: threadId ?? undefined,
+ topicId: topicId ?? undefined,
+ });
+
+ if (id) {
+ // ===== Hook: onMessageCreated =====
+ if (hooks.onMessageCreated) {
+ const message = state.displayMessages.find((m) => m.id === id);
+ if (message) {
+ hooks.onMessageCreated(message);
+ }
+ }
+
+ // Clear input after successful creation
+ set({ inputMessage: '' });
+ }
+
+ return id;
+ },
+
+ addUserMessage: async ({ message, fileList }) => {
+ const state = get();
+ const { context, hooks } = state;
+ const { agentId, topicId, threadId } = context;
+
+ // Get parent message ID
+ const displayMessages = state.displayMessages;
+ const parentId = displayMessages.length > 0 ? displayMessages.at(-1)?.id : undefined;
+
+ const id = await state.createMessage({
+ agentId,
+ content: message,
+ files: fileList,
+ parentId,
+ role: 'user',
+ threadId: threadId ?? undefined,
+ topicId: topicId ?? undefined,
+ });
+
+ if (id) {
+ // ===== Hook: onMessageCreated =====
+ if (hooks.onMessageCreated) {
+ const createdMessage = state.displayMessages.find((m) => m.id === id);
+ if (createdMessage) {
+ hooks.onMessageCreated(createdMessage);
+ }
+ }
+
+ // Clear input after successful creation
+ set({ inputMessage: '' });
+ }
+
+ return id;
+ },
+
+ // Send message
+ sendMessage: sendMessage(set, get),
+});
diff --git a/src/features/Conversation/store/slices/message/action/sendMessage.ts b/src/features/Conversation/store/slices/message/action/sendMessage.ts
new file mode 100644
index 00000000000..1e382252aac
--- /dev/null
+++ b/src/features/Conversation/store/slices/message/action/sendMessage.ts
@@ -0,0 +1,63 @@
+import type { SendMessageParams } from '@lobechat/types';
+
+import { useChatStore } from '@/store/chat';
+
+import type { Store as ConversationStore } from '../../../action';
+
+/**
+ * Send a message in this conversation
+ *
+ * This is a simplified wrapper that:
+ * 1. Calls lifecycle hooks
+ * 2. Forwards to ChatStore.sendMessage with context
+ * 3. Passes displayMessages to decouple from store selectors
+ *
+ * All actual message sending logic lives in ChatStore.
+ */
+export const sendMessage = (
+ set: (partial: Partial<ConversationStore>) => void,
+ get: () => ConversationStore,
+) => {
+ return async (params: SendMessageParams) => {
+ const state = get();
+ const { context, hooks, displayMessages } = state;
+
+ // ===== Hook: onBeforeSendMessage =====
+ if (hooks.onBeforeSendMessage) {
+ const result = await hooks.onBeforeSendMessage(params);
+ if (result === false) {
+ console.log('[ConversationStore] sendMessage blocked by onBeforeSendMessage hook');
+ return;
+ }
+ }
+
+ // Get global chat store
+ const chatStore = useChatStore.getState();
+
+ // Forward to ChatStore.sendMessage with context and messages
+ // Pass displayMessages to decouple sendMessage from store selectors
+ const result = await chatStore.sendMessage({
+ ...params,
+ context,
+ messages: params.messages ?? displayMessages,
+ });
+
+ // ===== Hook: onAfterMessageCreate =====
+ // Called after messages are created but before AI response is complete
+ if (result && hooks.onAfterMessageCreate) {
+ await hooks.onAfterMessageCreate({
+ assistantMessageId: result.assistantMessageId,
+ createdThreadId: result.createdThreadId,
+ userMessageId: result.userMessageId,
+ });
+ }
+
+ // ===== Hook: onAfterSendMessage =====
+ if (hooks.onAfterSendMessage) {
+ await hooks.onAfterSendMessage();
+ }
+
+ // Clear input message
+ set({ inputMessage: '' });
+ };
+};
diff --git a/src/features/Conversation/store/slices/message/action/state.ts b/src/features/Conversation/store/slices/message/action/state.ts
new file mode 100644
index 00000000000..2a4d8d70b2e
--- /dev/null
+++ b/src/features/Conversation/store/slices/message/action/state.ts
@@ -0,0 +1,111 @@
+import { copyToClipboard } from '@lobehub/ui';
+import { produce } from 'immer';
+import type { StateCreator } from 'zustand';
+
+import type { Store as ConversationStore } from '../../../action';
+import { dataSelectors } from '../../data/selectors';
+
+/**
+ * Message State Actions
+ *
+ * Handles message state operations like loading, collapsed, etc.
+ */
+export interface MessageStateAction {
+ /**
+ * Copy message content to clipboard
+ */
+ copyMessage: (id: string, content: string) => Promise<void>;
+
+ /**
+ * Toggle message loading state
+ */
+ internal_toggleMessageLoading: (loading: boolean, id: string) => void;
+
+ /**
+ * Modify message content (with optimistic update)
+ */
+ modifyMessageContent: (id: string, content: string) => Promise<void>;
+
+ /**
+ * Toggle tool inspect expanded state
+ */
+ toggleInspectExpanded: (id: string, expanded?: boolean) => Promise<void>;
+
+ /**
+ * Toggle message collapsed state
+ */
+ toggleMessageCollapsed: (id: string, collapsed?: boolean) => Promise<void>;
+}
+
+export const messageStateSlice: StateCreator<
+ ConversationStore,
+ [['zustand/devtools', never]],
+ [],
+ MessageStateAction
+> = (set, get) => ({
+ copyMessage: async (id, content) => {
+ const { hooks } = get();
+
+ await copyToClipboard(content);
+
+ // ===== Hook: onMessageCopied =====
+ if (hooks.onMessageCopied) {
+ hooks.onMessageCopied(id);
+ }
+ },
+
+ internal_toggleMessageLoading: (loading, id) => {
+ set(
+ (state) => ({
+ messageLoadingIds: produce(state.messageLoadingIds, (draft) => {
+ if (loading) {
+ if (!draft.includes(id)) draft.push(id);
+ } else {
+ const index = draft.indexOf(id);
+ if (index >= 0) draft.splice(index, 1);
+ }
+ }),
+ }),
+ false,
+ loading ? 'toggleMessageLoading/start' : 'toggleMessageLoading/end',
+ );
+ },
+
+ modifyMessageContent: async (id, content) => {
+ const { hooks } = get();
+
+ // Get original content for hook
+ const originalMessage = dataSelectors.getDisplayMessageById(id)(get());
+ const originalContent = originalMessage?.content;
+
+ // Update content
+ await get().updateMessageContent(id, content);
+
+ // ===== Hook: onMessageModified =====
+ if (hooks.onMessageModified) {
+ hooks.onMessageModified(id, content, originalContent);
+ }
+ },
+
+ toggleInspectExpanded: async (id, expanded) => {
+ const message = dataSelectors.getDbMessageById(id)(get());
+ if (!message) return;
+
+ // If expanded is not provided, toggle current state
+ const nextExpanded = expanded ?? !message.metadata?.inspectExpanded;
+
+ // Use optimistic update
+ await get().updateMessageMetadata(id, { inspectExpanded: nextExpanded });
+ },
+
+ toggleMessageCollapsed: async (id, collapsed) => {
+ const message = dataSelectors.getDisplayMessageById(id)(get());
+ if (!message) return;
+
+ // If collapsed is not provided, toggle current state
+ const nextCollapsed = collapsed ?? !message.metadata?.collapsed;
+
+ // Use optimistic update
+ await get().updateMessageMetadata(id, { collapsed: nextCollapsed });
+ },
+});
diff --git a/src/features/Conversation/store/slices/messageState/action.ts b/src/features/Conversation/store/slices/messageState/action.ts
new file mode 100644
index 00000000000..4744d78f9e7
--- /dev/null
+++ b/src/features/Conversation/store/slices/messageState/action.ts
@@ -0,0 +1,38 @@
+import { produce } from 'immer';
+import type { StateCreator } from 'zustand';
+
+import type { State } from '../../initialState';
+
+export interface MessageEditingAction {
+ /**
+ * Toggle message editing state
+ */
+ toggleMessageEditing: (id: string, editing: boolean) => void;
+}
+
+/**
+ * Helper function to toggle an item in a boolean list
+ */
+const toggleBooleanList = (ids: string[], id: string, value: boolean) => {
+ return produce(ids, (draft) => {
+ if (value) {
+ if (!draft.includes(id)) draft.push(id);
+ } else {
+ const index = draft.indexOf(id);
+ if (index >= 0) draft.splice(index, 1);
+ }
+ });
+};
+
+export const messageEditingSlice: StateCreator<State, [['zustand/devtools', never]], [], MessageEditingAction> = (
+ set,
+ get,
+) => ({
+ toggleMessageEditing: (id, editing) => {
+ set(
+ { messageEditingIds: toggleBooleanList(get().messageEditingIds, id, editing) },
+ false,
+ 'toggleMessageEditing',
+ );
+ },
+});
diff --git a/src/features/Conversation/store/slices/messageState/initialState.ts b/src/features/Conversation/store/slices/messageState/initialState.ts
new file mode 100644
index 00000000000..914eef7d70e
--- /dev/null
+++ b/src/features/Conversation/store/slices/messageState/initialState.ts
@@ -0,0 +1,26 @@
+/**
+ * Message UI state (editing, loading, etc.)
+ */
+export interface MessageStateState {
+ /**
+ * IDs of messages currently being edited
+ */
+ messageEditingIds: string[];
+
+ /**
+ * IDs of messages currently loading (creating, updating, etc.)
+ */
+ messageLoadingIds: string[];
+
+ /**
+ * Pending plugin arguments update promises by message ID
+ * Used to ensure approve/reject waits for pending saves to complete
+ */
+ pendingArgsUpdates: Map<string, Promise<void>>;
+}
+
+export const messageStateInitialState: MessageStateState = {
+ messageEditingIds: [],
+ messageLoadingIds: [],
+ pendingArgsUpdates: new Map(),
+};
diff --git a/src/features/Conversation/store/slices/messageState/selectors.ts b/src/features/Conversation/store/slices/messageState/selectors.ts
new file mode 100644
index 00000000000..ee9fe87c098
--- /dev/null
+++ b/src/features/Conversation/store/slices/messageState/selectors.ts
@@ -0,0 +1,157 @@
+import { useChatStore } from '@/store/chat';
+import { threadSelectors } from '@/store/chat/selectors';
+
+import type { State } from '../../initialState';
+import { dataSelectors } from '../data/selectors';
+
+/**
+ * Check if a message is currently collapsed (from message metadata)
+ */
+const isMessageCollapsed = (id: string) => (s: State) => {
+ const message = s.dbMessages.find((m) => m.id === id);
+ return message?.metadata?.collapsed ?? false;
+};
+
+/**
+ * Check if a message is currently being edited
+ */
+const isMessageEditing = (id: string) => (s: State) => s.messageEditingIds.includes(id);
+
+/**
+ * Check if a message is currently loading
+ */
+const isMessageLoading = (id: string) => (s: State) => s.messageLoadingIds.includes(id);
+
+/**
+ * Get all message IDs currently being edited
+ */
+const messageEditingIds = (s: State) => s.messageEditingIds;
+
+/**
+ * Get all message IDs currently loading
+ */
+const messageLoadingIds = (s: State) => s.messageLoadingIds;
+
+// ===== Operation-based selectors (read from external operationState) =====
+// Note: These selectors read from operationState which is passed externally from ChatStore.
+// This ensures proper React reactivity while keeping operations global.
+
+/**
+ * Check if AI is generating in the current conversation context
+ */
+const isAIGenerating = (s: State) => s.operationState.isAIGenerating;
+
+/**
+ * Get send message error for this context (if any)
+ */
+const sendMessageError = (s: State) => s.operationState.sendMessageError;
+
+/**
+ * Check if a message is being created (sendMessage or createAssistantMessage)
+ */
+const isMessageCreating = (id: string) => (s: State) =>
+ s.operationState.getMessageOperationState(id).isCreating;
+
+/**
+ * Check if a message is being generated (streaming response)
+ */
+const isMessageGenerating = (id: string) => (s: State) =>
+ s.operationState.getMessageOperationState(id).isGenerating;
+
+/**
+ * Check if a message is being regenerated
+ */
+const isMessageRegenerating = (id: string) => (s: State) =>
+ s.operationState.getMessageOperationState(id).isRegenerating;
+
+/**
+ * Check if a message is continuing generation
+ */
+const isMessageContinuing = (id: string) => (s: State) =>
+ s.operationState.getMessageOperationState(id).isContinuing;
+
+/**
+ * Check if a message is in reasoning state
+ */
+const isMessageInReasoning = (id: string) => (s: State) =>
+ s.operationState.getMessageOperationState(id).isInReasoning;
+
+/**
+ * Check if a message is processing (any operation)
+ */
+const isMessageProcessing = (id: string) => (s: State) =>
+ s.operationState.getMessageOperationState(id).isProcessing;
+
+// ===== Tool-related selectors (read from external operationState) =====
+
+/**
+ * Check if plugin API is currently invoking
+ */
+const isPluginApiInvoking = (id: string) => (s: State) =>
+ s.operationState.getToolOperationState(id, 0).isInvoking;
+
+/**
+ * Check if a tool call is currently streaming
+ */
+const isToolCallStreaming = (id: string, index: number) => (s: State) =>
+ s.operationState.getToolOperationState(id, index).isStreaming;
+
+/**
+ * Check if tool API name should be shining (streaming or invoking)
+ */
+const isToolApiNameShining =
+ (messageId: string, index: number, toolCallId: string) => (s: State) => {
+ const toolMessage = dataSelectors.getDbMessageByToolCallId(toolCallId)(s);
+ const toolMessageId = toolMessage?.id;
+ const toolState = s.operationState.getToolOperationState(messageId, index, toolCallId);
+ const isStreaming = toolState.isStreaming;
+ const isInvoking = !toolMessageId
+ ? true
+ : s.operationState.getToolOperationState(toolMessageId, 0).isInvoking;
+
+ return isStreaming || isInvoking;
+ };
+
+// ===== Thread-related selectors (still bridge from ChatStore) =====
+// Note: Thread state is global and not part of operation state.
+
+/**
+ * Check if a message has a thread by source message ID
+ * This is a bridge selector that reads from global ChatStore
+ */
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+const hasThreadBySourceMsgId = (id: string) => (_s: State) => {
+ const chatState = useChatStore.getState();
+ return threadSelectors.hasThreadBySourceMsgId(id)(chatState);
+};
+
+/**
+ * Check if we are in thread mode (has active thread ID)
+ * This is a bridge selector that reads from global ChatStore
+ */
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+const isThreadMode = (_s: State) => {
+ const chatState = useChatStore.getState();
+ return !!chatState.activeThreadId;
+};
+
+export const messageStateSelectors = {
+ hasThreadBySourceMsgId,
+ isAIGenerating,
+ isMessageCollapsed,
+ isMessageContinuing,
+ isMessageCreating,
+ isMessageEditing,
+ isMessageGenerating,
+ isMessageInReasoning,
+ isMessageLoading,
+ isMessageProcessing,
+ isMessageRegenerating,
+ isPluginApiInvoking,
+ isThreadMode,
+ isToolApiNameShining,
+ isToolCallStreaming,
+ messageEditingIds,
+ messageLoadingIds,
+ sendMessageError,
+};
diff --git a/src/features/Conversation/store/slices/tool/action.test.ts b/src/features/Conversation/store/slices/tool/action.test.ts
new file mode 100644
index 00000000000..0ab098c6c0d
--- /dev/null
+++ b/src/features/Conversation/store/slices/tool/action.test.ts
@@ -0,0 +1,405 @@
+import { act } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { ConversationContext, ConversationHooks } from '../../../types';
+import { createStore } from '../../index';
+
+// Mock dependencies
+const mockApproveToolCalling = vi.fn();
+const mockRejectAndContinueToolCalling = vi.fn();
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: {
+ getState: vi.fn(() => ({
+ messagesMap: {},
+ operations: {},
+ approveToolCalling: mockApproveToolCalling,
+ rejectAndContinueToolCalling: mockRejectAndContinueToolCalling,
+ cancelOperations: vi.fn(),
+ cancelOperation: vi.fn(),
+ deleteMessage: vi.fn(),
+ modifyMessageContent: vi.fn(),
+ copyMessage: vi.fn(),
+ toggleMessageEditing: vi.fn(),
+ regenerateUserMessage: vi.fn(),
+ regenerateAssistantMessage: vi.fn(),
+ continueGenerationMessage: vi.fn(),
+ optimisticCreateMessage: vi.fn(),
+ })),
+ setState: vi.fn(),
+ },
+}));
+
+vi.mock('@/store/chat/selectors', () => ({
+ displayMessageSelectors: {
+ lastDisplayMessageId: vi.fn(() => 'last-msg-id'),
+ getDisplayMessagesByKey: vi.fn(() => () => []),
+ findLastMessageId: vi.fn(() => () => 'parent-id'),
+ getDisplayMessageById: vi.fn(() => () => ({ content: 'original content' })),
+ },
+ dbMessageSelectors: {
+ dbUserFiles: vi.fn(() => []),
+ },
+}));
+
+vi.mock('@/services/message', () => ({
+ messageService: {
+ createMessage: vi.fn(),
+ getMessages: vi.fn().mockResolvedValue([]),
+ updateMessage: vi.fn().mockResolvedValue({ success: true, messages: [] }),
+ updateMessageMetadata: vi.fn().mockResolvedValue({ success: true, messages: [] }),
+ updateMessagePlugin: vi.fn().mockResolvedValue({ success: true, messages: [] }),
+ removeMessage: vi.fn().mockResolvedValue({ success: true, messages: [] }),
+ removeMessages: vi.fn().mockResolvedValue({ success: true, messages: [] }),
+ removeMessagesByAssistant: vi.fn(),
+ updateMessagePluginArguments: vi.fn(),
+ },
+}));
+
+describe('Tool Actions', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ vi.clearAllTimers();
+ });
+
+ describe('approveToolCall', () => {
+ it('should pass entire context object to ChatStore.approveToolCalling', async () => {
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+
+ const store = createStore({ context });
+
+ await act(async () => {
+ await store.getState().approveToolCall('tool-call-1', 'group-1');
+ });
+
+ // Verify context is passed as third argument
+ expect(mockApproveToolCalling).toHaveBeenCalledWith('tool-call-1', 'group-1', context);
+ });
+
+ it('should pass agent_builder scope context correctly', async () => {
+ const context: ConversationContext = {
+ agentId: 'builder-agent',
+ topicId: 'builder-topic',
+ threadId: 'builder-thread',
+ scope: 'agent_builder',
+ };
+
+ const store = createStore({ context });
+
+ await act(async () => {
+ await store.getState().approveToolCall('tool-call-1', 'group-1');
+ });
+
+ // Verify entire context object is passed (including scope)
+ expect(mockApproveToolCalling).toHaveBeenCalledWith('tool-call-1', 'group-1', context);
+ });
+
+ it('should call onToolApproved hook before approval', async () => {
+ const onToolApproved = vi.fn().mockResolvedValue(true);
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+ const hooks: ConversationHooks = { onToolApproved };
+
+ const store = createStore({ context, hooks });
+
+ await act(async () => {
+ await store.getState().approveToolCall('tool-call-1', 'group-1');
+ });
+
+ expect(onToolApproved).toHaveBeenCalledWith('tool-call-1');
+ expect(mockApproveToolCalling).toHaveBeenCalledWith('tool-call-1', 'group-1', context);
+ });
+
+ it('should respect onToolApproved hook returning false', async () => {
+ const onToolApproved = vi.fn().mockResolvedValue(false);
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+ const hooks: ConversationHooks = { onToolApproved };
+
+ const store = createStore({ context, hooks });
+
+ await act(async () => {
+ await store.getState().approveToolCall('tool-call-1', 'group-1');
+ });
+
+ expect(onToolApproved).toHaveBeenCalledWith('tool-call-1');
+ expect(mockApproveToolCalling).not.toHaveBeenCalled();
+ });
+
+ it('should call onToolCallComplete hook after approval', async () => {
+ const onToolCallComplete = vi.fn();
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+ const hooks: ConversationHooks = { onToolCallComplete };
+
+ const store = createStore({ context, hooks });
+
+ await act(async () => {
+ await store.getState().approveToolCall('tool-call-1', 'group-1');
+ });
+
+ expect(onToolCallComplete).toHaveBeenCalledWith('tool-call-1', undefined);
+ });
+ });
+
+ describe('rejectToolCall', () => {
+ it('should call onToolRejected hook before rejection', async () => {
+ const onToolRejected = vi.fn().mockResolvedValue(true);
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+ const hooks: ConversationHooks = { onToolRejected };
+
+ const store = createStore({ context, hooks });
+
+ await act(async () => {
+ await store.getState().rejectToolCall('tool-call-1', 'Reason');
+ });
+
+ expect(onToolRejected).toHaveBeenCalledWith('tool-call-1', 'Reason');
+ });
+
+ it('should respect onToolRejected hook returning false', async () => {
+ const onToolRejected = vi.fn().mockResolvedValue(false);
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+ const hooks: ConversationHooks = { onToolRejected };
+
+ const store = createStore({ context, hooks });
+
+ await act(async () => {
+ await store.getState().rejectToolCall('tool-call-1', 'Reason');
+ });
+
+ expect(onToolRejected).toHaveBeenCalledWith('tool-call-1', 'Reason');
+ // Should not proceed when hook returns false
+ });
+ });
+
+ describe('rejectAndContinueToolCall', () => {
+ it('should pass entire context object to ChatStore.rejectAndContinueToolCalling', async () => {
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+
+ const store = createStore({ context });
+
+ await act(async () => {
+ await store.getState().rejectAndContinueToolCall('tool-call-1', 'Reason');
+ });
+
+ // Verify context is passed as third argument
+ expect(mockRejectAndContinueToolCalling).toHaveBeenCalledWith(
+ 'tool-call-1',
+ 'Reason',
+ context,
+ );
+ });
+
+ it('should pass agent_builder scope context correctly', async () => {
+ const context: ConversationContext = {
+ agentId: 'builder-agent',
+ topicId: 'builder-topic',
+ threadId: 'builder-thread',
+ scope: 'agent_builder',
+ };
+
+ const store = createStore({ context });
+
+ await act(async () => {
+ await store.getState().rejectAndContinueToolCall('tool-call-1', 'User rejected');
+ });
+
+ // Verify entire context object is passed (including scope)
+ expect(mockRejectAndContinueToolCalling).toHaveBeenCalledWith(
+ 'tool-call-1',
+ 'User rejected',
+ context,
+ );
+ });
+
+ it('should pass context with undefined reason', async () => {
+ const context: ConversationContext = {
+ agentId: 'builder-agent',
+ topicId: null,
+ threadId: null,
+ };
+
+ const store = createStore({ context });
+
+ await act(async () => {
+ await store.getState().rejectAndContinueToolCall('tool-call-1');
+ });
+
+ // Verify context is passed even with undefined reason
+ expect(mockRejectAndContinueToolCalling).toHaveBeenCalledWith(
+ 'tool-call-1',
+ undefined,
+ context,
+ );
+ });
+ });
+
+ describe('waitForPendingArgsUpdate integration', () => {
+ it('approveToolCall should wait for pending args update before proceeding', async () => {
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+
+ const store = createStore({ context });
+
+ // Manually set a pending promise in the store
+ let resolvePending: () => void;
+ const pendingPromise = new Promise<void>((resolve) => {
+ resolvePending = resolve;
+ });
+
+ act(() => {
+ store.setState({
+ pendingArgsUpdates: new Map([['tool-call-1', pendingPromise]]),
+ });
+ });
+
+ // Start approve (should wait for pending promise)
+ let approveFinished = false;
+ const approveAction = act(async () => {
+ await store.getState().approveToolCall('tool-call-1', 'group-1');
+ approveFinished = true;
+ });
+
+ // Give time for approve to start waiting
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ // Approve should not have finished yet (waiting for pending promise)
+ expect(approveFinished).toBe(false);
+ expect(mockApproveToolCalling).not.toHaveBeenCalled();
+
+ // Resolve the pending promise
+ resolvePending!();
+ await approveAction;
+
+ // Now approve should have finished
+ expect(approveFinished).toBe(true);
+ expect(mockApproveToolCalling).toHaveBeenCalledWith('tool-call-1', 'group-1', context);
+ });
+
+ it('rejectToolCall should wait for pending args update before proceeding', async () => {
+ const onToolRejected = vi.fn().mockResolvedValue(true);
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+ const hooks: ConversationHooks = { onToolRejected };
+
+ const store = createStore({ context, hooks });
+
+ // Manually set a pending promise in the store
+ let resolvePending: () => void;
+ const pendingPromise = new Promise<void>((resolve) => {
+ resolvePending = resolve;
+ });
+
+ act(() => {
+ store.setState({
+ pendingArgsUpdates: new Map([['tool-call-1', pendingPromise]]),
+ });
+ });
+
+ // Start reject (should wait for pending promise)
+ let rejectFinished = false;
+ const rejectAction = act(async () => {
+ await store.getState().rejectToolCall('tool-call-1', 'Reason');
+ rejectFinished = true;
+ });
+
+ // Give time for reject to start waiting
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ // Reject should not have finished yet (waiting for pending promise)
+ expect(rejectFinished).toBe(false);
+ expect(onToolRejected).not.toHaveBeenCalled();
+
+ // Resolve the pending promise
+ resolvePending!();
+ await rejectAction;
+
+ // Now reject should have finished
+ expect(rejectFinished).toBe(true);
+ expect(onToolRejected).toHaveBeenCalledWith('tool-call-1', 'Reason');
+ });
+
+ it('rejectAndContinueToolCall should wait for pending args update before proceeding', async () => {
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+
+ const store = createStore({ context });
+
+ // Manually set a pending promise in the store
+ let resolvePending: () => void;
+ const pendingPromise = new Promise<void>((resolve) => {
+ resolvePending = resolve;
+ });
+
+ act(() => {
+ store.setState({
+ pendingArgsUpdates: new Map([['tool-call-1', pendingPromise]]),
+ });
+ });
+
+ // Start rejectAndContinue (should wait for pending promise)
+ let rejectFinished = false;
+ const rejectAction = act(async () => {
+ await store.getState().rejectAndContinueToolCall('tool-call-1', 'Reason');
+ rejectFinished = true;
+ });
+
+ // Give time for reject to start waiting
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ // RejectAndContinue should not have finished yet (waiting for pending promise)
+ expect(rejectFinished).toBe(false);
+ expect(mockRejectAndContinueToolCalling).not.toHaveBeenCalled();
+
+ // Resolve the pending promise
+ resolvePending!();
+ await rejectAction;
+
+ // Now rejectAndContinue should have finished
+ expect(rejectFinished).toBe(true);
+ expect(mockRejectAndContinueToolCalling).toHaveBeenCalledWith(
+ 'tool-call-1',
+ 'Reason',
+ context,
+ );
+ });
+ });
+});
diff --git a/src/features/Conversation/store/slices/tool/action.ts b/src/features/Conversation/store/slices/tool/action.ts
new file mode 100644
index 00000000000..839bc1128d9
--- /dev/null
+++ b/src/features/Conversation/store/slices/tool/action.ts
@@ -0,0 +1,104 @@
+import type { StateCreator } from 'zustand';
+
+import { useChatStore } from '@/store/chat';
+
+import type { Store as ConversationStore } from '../../action';
+import { dataSelectors } from '../data/selectors';
+
+/**
+ * Tool Interaction Actions
+ *
+ * Handles tool call approval and rejection
+ */
+export interface ToolAction {
+ /**
+ * Approve a tool call
+ */
+ approveToolCall: (toolMessageId: string, assistantGroupId: string) => Promise<void>;
+
+ /**
+ * Reject a tool call and continue the conversation
+ */
+ rejectAndContinueToolCall: (toolMessageId: string, reason?: string) => Promise<void>;
+
+ /**
+ * Reject a tool call
+ */
+ rejectToolCall: (toolMessageId: string, reason?: string) => Promise<void>;
+}
+
+export const toolSlice: StateCreator<
+ ConversationStore,
+ [['zustand/devtools', never]],
+ [],
+ ToolAction
+> = (set, get) => ({
+ approveToolCall: async (toolMessageId: string, assistantGroupId: string) => {
+ const state = get();
+ const { hooks, context, waitForPendingArgsUpdate } = state;
+
+ // Wait for any pending args update to complete before approval
+ await waitForPendingArgsUpdate(toolMessageId);
+
+ // ===== Hook: onToolApproved =====
+ if (hooks.onToolApproved) {
+ const shouldProceed = await hooks.onToolApproved(toolMessageId);
+ if (shouldProceed === false) return;
+ }
+
+ // Delegate to global ChatStore with context for correct conversation scope
+ const chatStore = useChatStore.getState();
+ await chatStore.approveToolCalling(toolMessageId, assistantGroupId, context);
+
+ // ===== Hook: onToolCallComplete =====
+ if (hooks.onToolCallComplete) {
+ hooks.onToolCallComplete(toolMessageId, undefined);
+ }
+ },
+
+ rejectAndContinueToolCall: async (toolMessageId: string, reason?: string) => {
+ const { context, waitForPendingArgsUpdate } = get();
+
+ // Wait for any pending args update to complete before rejection
+ await waitForPendingArgsUpdate(toolMessageId);
+
+ // First reject the tool call
+ await get().rejectToolCall(toolMessageId, reason);
+
+ // Then delegate to ChatStore to continue the conversation with context
+ const chatStore = useChatStore.getState();
+ await chatStore.rejectAndContinueToolCalling(toolMessageId, reason, context);
+ },
+
+ rejectToolCall: async (toolMessageId: string, reason?: string) => {
+ const state = get();
+ const { hooks, updateMessagePlugin, updateMessageContent, waitForPendingArgsUpdate } = state;
+
+ // Wait for any pending args update to complete before rejection
+ await waitForPendingArgsUpdate(toolMessageId);
+
+ // ===== Hook: onToolRejected =====
+ if (hooks.onToolRejected) {
+ const shouldProceed = await hooks.onToolRejected(toolMessageId, reason);
+ if (shouldProceed === false) return;
+ }
+
+ const toolMessage = dataSelectors.getDbMessageById(toolMessageId)(state);
+ if (!toolMessage) return;
+
+ // Update intervention status to rejected
+ await updateMessagePlugin(toolMessageId, {
+ intervention: {
+ rejectedReason: reason,
+ status: 'rejected',
+ },
+ });
+
+ // Update tool message content with rejection reason
+ const toolContent = !!reason
+ ? `User reject this tool calling with reason: ${reason}`
+ : 'User reject this tool calling without reason';
+
+ await updateMessageContent(toolMessageId, toolContent);
+ },
+});
diff --git a/src/features/Conversation/store/slices/virtuaList/action.ts b/src/features/Conversation/store/slices/virtuaList/action.ts
new file mode 100644
index 00000000000..12d12aad781
--- /dev/null
+++ b/src/features/Conversation/store/slices/virtuaList/action.ts
@@ -0,0 +1,122 @@
+import type { StateCreator } from 'zustand';
+
+import type { State } from '../../initialState';
+import type { VirtuaScrollMethods, VisibleItemMetrics } from './initialState';
+
+export interface VirtuaListAction {
+ /**
+ * Register VList scroll methods
+ */
+ registerVirtuaScrollMethods: (methods: VirtuaScrollMethods | null) => void;
+
+ /**
+ * Remove visible item and recalculate active index
+ */
+ removeVisibleItem: (index: number) => void;
+
+ /**
+ * Reset all visible items (on unmount)
+ */
+ resetVisibleItems: () => void;
+
+ /**
+ * Scroll to bottom of the list
+ */
+ scrollToBottom: (smooth?: boolean) => void;
+
+ /**
+ * Scroll to specific index
+ */
+ scrollToIndex: (
+ index: number,
+ options?: { align?: 'start' | 'center' | 'end'; smooth?: boolean },
+ ) => void;
+
+ /**
+ * Update scroll state (atBottom, isScrolling)
+ */
+ setScrollState: (state: { atBottom?: boolean; isScrolling?: boolean }) => void;
+
+ /**
+ * Upsert visible item metrics and recalculate active index
+ */
+ upsertVisibleItem: (index: number, metrics: VisibleItemMetrics) => void;
+}
+
+/**
+ * Recalculate active index based on visible items
+ */
+const calculateActiveIndex = (visibleItems: Map<number, VisibleItemMetrics>): number | null => {
+ if (visibleItems.size === 0) return null;
+
+ let candidate: number | null = null;
+ let minTop = Infinity;
+ let maxRatio = -Infinity;
+
+ visibleItems.forEach(({ top, ratio }, index) => {
+ const shouldUpdate =
+ top < minTop ||
+ (top === minTop &&
+ (ratio > maxRatio || (ratio === maxRatio && index < (candidate ?? Infinity))));
+
+ if (shouldUpdate) {
+ candidate = index;
+ minTop = top;
+ maxRatio = ratio;
+ }
+ });
+
+ return candidate;
+};
+
+export const virtuaListSlice: StateCreator<State & VirtuaListAction, [], [], VirtuaListAction> = (
+ set,
+ get,
+) => ({
+ registerVirtuaScrollMethods: (methods) => {
+ set({ virtuaScrollMethods: methods });
+ },
+
+ removeVisibleItem: (index) => {
+ const { visibleItems } = get();
+ if (!visibleItems.has(index)) return;
+
+ const newVisibleItems = new Map(visibleItems);
+ newVisibleItems.delete(index);
+
+ const activeIndex = calculateActiveIndex(newVisibleItems);
+ set({ activeIndex, visibleItems: newVisibleItems });
+ },
+
+ resetVisibleItems: () => {
+ set({ activeIndex: null, visibleItems: new Map() });
+ },
+
+ scrollToBottom: (smooth = true) => {
+ const { displayMessages, virtuaScrollMethods } = get();
+ if (displayMessages.length === 0) return;
+
+ virtuaScrollMethods?.scrollToIndex(displayMessages.length - 1, {
+ align: 'end',
+ smooth,
+ });
+ },
+
+ scrollToIndex: (index, options) => {
+ const { virtuaScrollMethods } = get();
+ virtuaScrollMethods?.scrollToIndex(index, options);
+ },
+
+ setScrollState: (state) => {
+ set(state);
+ },
+
+ upsertVisibleItem: (index, metrics) => {
+ const { visibleItems } = get();
+ const newVisibleItems = new Map(visibleItems);
+ newVisibleItems.set(index, metrics);
+
+ const activeIndex = calculateActiveIndex(newVisibleItems);
+ set({ activeIndex, visibleItems: newVisibleItems });
+ },
+});
diff --git a/src/features/Conversation/store/slices/virtuaList/initialState.ts b/src/features/Conversation/store/slices/virtuaList/initialState.ts
new file mode 100644
index 00000000000..f0214b4b992
--- /dev/null
+++ b/src/features/Conversation/store/slices/virtuaList/initialState.ts
@@ -0,0 +1,56 @@
+/**
+ * Scroll methods exposed by VList, stored as callable functions
+ */
+export interface VirtuaScrollMethods {
+ getScrollOffset: () => number;
+ getScrollSize: () => number;
+ getViewportSize: () => number;
+ scrollToIndex: (
+ index: number,
+ options?: { align?: 'start' | 'center' | 'end'; smooth?: boolean },
+ ) => void;
+}
+
+/**
+ * Visible item metrics for active index calculation
+ */
+export interface VisibleItemMetrics {
+ bottom: number;
+ ratio: number;
+ top: number;
+}
+
+export interface VirtuaListState {
+ /**
+ * Currently active (most visible) message index
+ */
+ activeIndex: number | null;
+
+ /**
+ * Whether the list is at the bottom
+ */
+ atBottom: boolean;
+
+ /**
+ * Whether the list is currently scrolling
+ */
+ isScrolling: boolean;
+
+ /**
+ * Scroll methods from VList instance
+ */
+ virtuaScrollMethods: VirtuaScrollMethods | null;
+
+ /**
+ * Visible items metrics map (index -> metrics)
+ */
+ visibleItems: Map<number, VisibleItemMetrics>;
+}
+
+export const virtuaListInitialState: VirtuaListState = {
+ activeIndex: null,
+ atBottom: true,
+ isScrolling: false,
+ virtuaScrollMethods: null,
+ visibleItems: new Map(),
+};
diff --git a/src/features/Conversation/store/slices/virtuaList/selectors.ts b/src/features/Conversation/store/slices/virtuaList/selectors.ts
new file mode 100644
index 00000000000..89b5ac1cd93
--- /dev/null
+++ b/src/features/Conversation/store/slices/virtuaList/selectors.ts
@@ -0,0 +1,15 @@
+import type { State } from '../../initialState';
+
+const atBottom = (s: State) => s.atBottom;
+const isScrolling = (s: State) => s.isScrolling;
+const activeIndex = (s: State) => s.activeIndex;
+const visibleItems = (s: State) => s.visibleItems;
+const virtuaScrollMethods = (s: State) => s.virtuaScrollMethods;
+
+export const virtuaListSelectors = {
+ activeIndex,
+ atBottom,
+ isScrolling,
+ virtuaScrollMethods,
+ visibleItems,
+};
diff --git a/src/features/Conversation/types/context.ts b/src/features/Conversation/types/context.ts
new file mode 100644
index 00000000000..825bf353479
--- /dev/null
+++ b/src/features/Conversation/types/context.ts
@@ -0,0 +1,42 @@
+import { ConversationContext as BaseConversationContext } from '@lobechat/types';
+
+/**
+ * Extended Conversation Context
+ *
+ * Extends the base ConversationContext with optional metadata.
+ * Used to locate messages in the session → topic → thread hierarchy.
+ *
+ * Design Principles:
+ * - ❌ No `mode` field (avoid hardcoded types)
+ * - ✅ Only data coordinates (sessionId/topicId/threadId)
+ * - ✅ Scenario is naturally determined by coordinate combination
+ */
+export interface ConversationContext extends BaseConversationContext {
+ /**
+ * Metadata (optional, for extension)
+ *
+ * Can be used to store additional context-specific data:
+ * - knowledgeBaseId: For knowledge base chat
+ * - agentId: For agent preview chat
+ * - preview: Boolean flag for preview mode
+ * - etc.
+ */
+ metadata?: Record<string, any>;
+}
+
+/**
+ * Helper type: Extract metadata type for better type safety
+ */
+export type ConversationMetadata<T = Record<string, any>> = T;
+
+/**
+ * Common metadata types
+ */
+export interface KnowledgeBaseMetadata {
+ knowledgeBaseId: string;
+}
+
+export interface AgentPreviewMetadata {
+ agentId: string;
+ preview: true;
+}
diff --git a/src/features/Conversation/types/hooks.ts b/src/features/Conversation/types/hooks.ts
new file mode 100644
index 00000000000..aac89a485e8
--- /dev/null
+++ b/src/features/Conversation/types/hooks.ts
@@ -0,0 +1,276 @@
+import type {
+ ChatToolPayload,
+ MessageToolCall,
+ SendMessageParams,
+ UIChatMessage,
+} from '@lobechat/types';
+
+/**
+ * Conversation Lifecycle Hooks
+ *
+ * Allows external injection of custom behavior at various points
+ * in the conversation lifecycle.
+ *
+ * All hooks are optional and can be used to:
+ * - Validate or modify behavior before actions
+ * - React to state changes
+ * - Add analytics/logging
+ * - Implement custom approval flows
+ */
+/* eslint-disable typescript-sort-keys/interface */
+export interface ConversationHooks {
+ // ========================================
+ // Message Lifecycle Hooks
+ // ========================================
+
+ /**
+ * Called before sending a message
+ *
+ * @param params - The message parameters
+ * @returns false to prevent sending, true/void to continue
+ *
+ * @example
+ * ```ts
+ * onBeforeSendMessage: async (params) => {
+ * // Check for Chinese text with Gemini model
+ * if (await checkGeminiChineseWarning(params.message)) {
+ * return false; // Block sending
+ * }
+ * }
+ * ```
+ */
+ onBeforeSendMessage?: (params: SendMessageParams) => Promise<boolean | void>;
+
+ /**
+ * Called after a message is successfully sent
+ *
+ * @example
+ * ```ts
+ * onAfterSendMessage: async () => {
+ * analytics.track('message_sent');
+ * }
+ * ```
+ */
+ onAfterSendMessage?: () => Promise<void>;
+
+ /**
+ * Called when a message is created (user or assistant)
+ *
+ * @param message - The created message
+ */
+ onMessageCreated?: (message: UIChatMessage) => void;
+
+ /**
+ * Called when a message error occurs
+ *
+ * @param error - The error that occurred
+ * @param messageId - The message ID (if available)
+ */
+ onMessageError?: (error: Error, messageId?: string) => void;
+
+ /**
+ * Called when a message is deleted
+ *
+ * @param messageId - The deleted message ID
+ */
+ onMessageDeleted?: (messageId: string) => void;
+
+ /**
+ * Called when a message is modified
+ *
+ * @param messageId - The modified message ID
+ * @param newContent - The new content
+ * @param originalContent - The original content
+ */
+ onMessageModified?: (messageId: string, newContent: string, originalContent?: string) => void;
+
+ /**
+ * Called when a message is copied
+ *
+ * @param messageId - The copied message ID
+ */
+ onMessageCopied?: (messageId: string) => void;
+
+ // ========================================
+ // Generation State Change Hooks
+ // ========================================
+
+ /**
+ * Called when AI generation starts
+ *
+ * @param operationId - The operation ID for this generation
+ */
+ onGenerationStart?: (operationId: string) => void;
+
+ /**
+ * Called when AI generation completes successfully
+ *
+ * @param operationId - The operation ID for this generation
+ */
+ onGenerationComplete?: (operationId: string) => void;
+
+ /**
+ * Called when AI generation is cancelled
+ *
+ * @param operationId - The operation ID for this generation
+ */
+ onGenerationCancelled?: (operationId: string) => void;
+
+ /**
+ * Called when generation is stopped by user
+ */
+ onGenerationStop?: () => void;
+
+ /**
+ * Called when an operation is cancelled
+ *
+ * @param operationId - The cancelled operation ID
+ */
+ onOperationCancelled?: (operationId: string) => void;
+
+ /**
+ * Called before regenerating a message
+ *
+ * @param messageId - The message to regenerate
+ * @returns false to prevent regeneration, true/void to continue
+ */
+ onBeforeRegenerate?: (messageId: string) => Promise<boolean | void>;
+
+ /**
+ * Called after regeneration completes
+ *
+ * @param messageId - The regenerated message ID
+ */
+ onRegenerateComplete?: (messageId: string) => void;
+
+ /**
+ * Called before continuing generation
+ *
+ * @param messageId - The message to continue from
+ * @returns false to prevent continuation, true/void to continue
+ */
+ onBeforeContinue?: (messageId: string) => Promise<boolean | void>;
+
+ /**
+ * Called after continue generation completes
+ *
+ * @param messageId - The message ID
+ */
+ onContinueComplete?: (messageId: string) => void;
+
+ // ========================================
+ // Tool Interaction Hooks
+ // ========================================
+
+ /**
+ * Called when a tool call starts
+ *
+ * @param toolCallId - The tool call ID
+ */
+ onToolCallStart?: (toolCallId: string) => void;
+
+ /**
+ * Called when a tool call completes
+ *
+ * @param toolCallId - The tool call ID
+ * @param result - The tool call result
+ */
+ onToolCallComplete?: (toolCallId: string, result: any) => void;
+
+ /**
+ * Called when a tool call encounters an error
+ *
+ * @param toolCallId - The tool call ID
+ * @param error - The error that occurred
+ */
+ onToolCallError?: (toolCallId: string, error: Error) => void;
+
+ /**
+ * Called when a tool requires user approval
+ *
+ * @param toolCall - The tool call requiring approval
+ * @returns true to approve, false to reject
+ *
+ * @example
+ * ```ts
+ * onToolApprovalRequired: async (toolCall) => {
+ * return await showCustomApprovalDialog(toolCall);
+ * }
+ * ```
+ */
+ onToolApprovalRequired?: (toolCall: MessageToolCall | ChatToolPayload) => Promise<boolean>;
+
+ /**
+ * Called when a tool is approved
+ *
+ * @param toolCallId - The approved tool call ID
+ * @returns false to prevent approval, true/void to continue
+ */
+ onToolApproved?: (toolCallId: string) => Promise<boolean | void>;
+
+ /**
+ * Called when a tool is rejected
+ *
+ * @param toolCallId - The rejected tool call ID
+ * @param reason - The rejection reason
+ * @returns false to prevent rejection, true/void to continue
+ */
+ onToolRejected?: (toolCallId: string, reason?: string) => Promise<boolean | void>;
+
+ // ========================================
+ // Topic/Thread Change Hooks
+ // ========================================
+
+ /**
+ * Called when a new topic is created
+ *
+ * @param topicId - The created topic ID
+ */
+ onTopicCreated?: (topicId: string) => void;
+
+ /**
+ * Called when a new thread is created
+ *
+ * @param threadId - The created thread ID
+ */
+ onThreadCreated?: (threadId: string) => void;
+
+ /**
+ * Called after user and assistant messages are created in sendMessage.
+ * This hook allows for custom post-message-creation behavior like:
+ * - Refreshing thread lists
+ * - Summarizing thread/topic titles
+ * - Updating portal state
+ *
+ * @param params - Information about the created messages
+ *
+ * @example
+ * ```ts
+ * onAfterMessageCreate: async ({ createdThreadId, assistantMessageId }) => {
+ * if (createdThreadId) {
+ * // Refresh thread list for new thread
+ * await chatStore.refreshThreads();
+ * // Open thread in portal
+ * chatStore.openThreadInPortal(createdThreadId, sourceMessageId);
+ * }
+ * }
+ * ```
+ */
+ onAfterMessageCreate?: (params: {
+ /** The created assistant message ID */
+ assistantMessageId: string;
+ /** The created thread ID (if a new thread was created) */
+ createdThreadId?: string;
+ /** The created user message ID */
+ userMessageId: string;
+ }) => Promise<void>;
+
+ // ========================================
+ // Custom Extension
+ // ========================================
+
+ /**
+ * Allow custom hooks to be added dynamically
+ */
+ [key: string]: ((...args: any[]) => any) | undefined;
+}
diff --git a/src/features/Conversation/types/index.ts b/src/features/Conversation/types/index.ts
new file mode 100644
index 00000000000..9ef4e5316ac
--- /dev/null
+++ b/src/features/Conversation/types/index.ts
@@ -0,0 +1,4 @@
+export * from './context';
+export * from './hooks';
+export * from './operation';
+export * from './ui';
diff --git a/src/features/Conversation/types/operation.ts b/src/features/Conversation/types/operation.ts
new file mode 100644
index 00000000000..f591dca6d53
--- /dev/null
+++ b/src/features/Conversation/types/operation.ts
@@ -0,0 +1,124 @@
+/**
+ * Message Operation State
+ *
+ * Represents the current operation state for a specific message.
+ * These states indicate what actions are currently being performed on the message.
+ */
+export interface MessageOperationState {
+ /**
+ * Message is continuing generation
+ */
+ isContinuing: boolean;
+
+ /**
+ * Message is being created (sendMessage or createAssistantMessage)
+ */
+ isCreating: boolean;
+
+ /**
+ * Message is being generated (streaming response)
+ */
+ isGenerating: boolean;
+
+ /**
+ * Message is in reasoning/thinking state
+ */
+ isInReasoning: boolean;
+
+ /**
+ * Message has any operation in progress
+ */
+ isProcessing: boolean;
+
+ /**
+ * Message is being regenerated
+ */
+ isRegenerating: boolean;
+}
+
+/**
+ * Tool Operation State
+ *
+ * Represents the current operation state for a specific tool call.
+ */
+export interface ToolOperationState {
+ /**
+ * Tool API is currently being invoked
+ */
+ isInvoking: boolean;
+
+ /**
+ * Tool call is currently streaming
+ */
+ isStreaming: boolean;
+}
+
+/**
+ * Operation State
+ *
+ * External operation state passed into ConversationProvider.
+ * This state is managed by the global ChatStore and passed down for reactivity.
+ *
+ * Design Principles:
+ * - Operations are managed globally (supports multiple agents/topics running in parallel)
+ * - ConversationStore only reads this state, never modifies it
+ * - State is passed externally to ensure proper React reactivity
+ */
+export interface OperationState {
+ /**
+ * Get the operation state for a specific message
+ */
+ getMessageOperationState: (messageId: string) => MessageOperationState;
+
+ /**
+ * Get the operation state for a specific tool call
+ * @param messageId - The message ID containing the tool call
+ * @param index - The index of the tool call within the message
+ * @param toolCallId - The tool call ID (optional, for looking up tool message)
+ */
+ getToolOperationState: (
+ messageId: string,
+ index: number,
+ toolCallId?: string,
+ ) => ToolOperationState;
+
+ /**
+ * Check if AI is currently generating in this conversation context
+ */
+ isAIGenerating: boolean;
+
+ /**
+ * Send message error for this context (if any)
+ */
+ sendMessageError?: string;
+}
+
+/**
+ * Default empty message operation state
+ */
+export const DEFAULT_MESSAGE_OPERATION_STATE: MessageOperationState = {
+ isContinuing: false,
+ isCreating: false,
+ isGenerating: false,
+ isInReasoning: false,
+ isProcessing: false,
+ isRegenerating: false,
+};
+
+/**
+ * Default empty tool operation state
+ */
+export const DEFAULT_TOOL_OPERATION_STATE: ToolOperationState = {
+ isInvoking: false,
+ isStreaming: false,
+};
+
+/**
+ * Default empty operation state
+ */
+export const DEFAULT_OPERATION_STATE: OperationState = {
+ getMessageOperationState: () => DEFAULT_MESSAGE_OPERATION_STATE,
+ getToolOperationState: () => DEFAULT_TOOL_OPERATION_STATE,
+ isAIGenerating: false,
+ sendMessageError: undefined,
+};
diff --git a/src/features/Conversation/types/ui.ts b/src/features/Conversation/types/ui.ts
new file mode 100644
index 00000000000..b8b227c98c4
--- /dev/null
+++ b/src/features/Conversation/types/ui.ts
@@ -0,0 +1,92 @@
+import { LLMRoleType, UIChatMessage } from '@lobechat/types';
+import { ActionIconGroupItemType } from '@lobehub/ui';
+import { type ChatItemProps } from '@lobehub/ui/chat';
+import { FC, ReactNode } from 'react';
+
+export type RenderRole = LLMRoleType | 'default' | 'history' | string;
+export type RenderMessage = FC<UIChatMessage & { editableContent: ReactNode }>;
+export type RenderBelowMessage = FC<UIChatMessage>;
+export type RenderMessageExtra = FC<UIChatMessage>;
+export type MarkdownCustomRender = (props: {
+ dom: ReactNode;
+ id: string;
+ text: string;
+}) => ReactNode;
+
+export type RenderItem = FC<{ key: string } & UIChatMessage & ListItemProps>;
+
+/**
+ * Action item with click handler
+ */
+export interface MessageActionItem extends ActionIconGroupItemType {
+ children?: Array<{ handleClick?: () => void; key: string; label: string }>;
+ handleClick?: () => void | Promise<void>;
+}
+
+/**
+ * Action item or divider
+ */
+export type MessageActionItemOrDivider = MessageActionItem | { type: 'divider' };
+
+/**
+ * Factory function type for creating message-specific actions
+ * Receives message id and returns an action item or null
+ */
+export type MessageActionFactory = (id: string) => MessageActionItem | null;
+
+/**
+ * Action configuration for a specific message type
+ */
+export interface MessageActionsConfig {
+ /**
+ * Actions to display in the action bar (always visible)
+ */
+ bar?: MessageActionItemOrDivider[];
+ /**
+ * Extra actions to add to the bar, created per-message using factory functions.
+ * These are appended after the default/configured bar actions.
+ */
+ extraBarActions?: MessageActionFactory[];
+ /**
+ * Extra actions to add to the menu, created per-message using factory functions.
+ * These are appended after the default/configured menu actions.
+ */
+ extraMenuActions?: MessageActionFactory[];
+ /**
+ * Actions to display in the dropdown menu
+ */
+ menu?: MessageActionItemOrDivider[];
+}
+
+/**
+ * Actions bar configuration by message type
+ */
+export interface ActionsBarConfig {
+ /**
+ * Actions configuration for assistant messages
+ */
+ assistant?: MessageActionsConfig;
+ /**
+ * Actions configuration for assistant group messages
+ * If not provided, falls back to `assistant` config
+ */
+ assistantGroup?: MessageActionsConfig;
+ /**
+ * Actions configuration for user messages
+ */
+ user?: MessageActionsConfig;
+}
+
+export interface ListItemProps {
+ groupNav?: ChatItemProps['avatarAddon'];
+
+ renderItems?: {
+ [role: RenderRole]: RenderItem;
+ };
+
+ /**
+ * @description 是否显示聊天项的名称
+ * @default false
+ */
+ showTitle?: boolean;
+}
diff --git a/src/features/ChatList/utils/markdown.test.ts b/src/features/Conversation/utils/markdown.test.ts
similarity index 100%
rename from src/features/ChatList/utils/markdown.test.ts
rename to src/features/Conversation/utils/markdown.test.ts
diff --git a/src/features/ChatList/utils/markdown.ts b/src/features/Conversation/utils/markdown.ts
similarity index 100%
rename from src/features/ChatList/utils/markdown.ts
rename to src/features/Conversation/utils/markdown.ts
diff --git a/src/server/routers/lambda/__tests__/agent.test.ts b/src/server/routers/lambda/__tests__/agent.test.ts
index fbc7726ec12..1566706ad84 100644
--- a/src/server/routers/lambda/__tests__/agent.test.ts
+++ b/src/server/routers/lambda/__tests__/agent.test.ts
@@ -61,6 +61,7 @@ describe('agentRouter', () => {
getAgentAssignedKnowledge: vi.fn(),
toggleFile: vi.fn(),
toggleKnowledgeBase: vi.fn(),
+ update: vi.fn(),
};
vi.mocked(AgentModel).mockImplementation(() => agentModelMock);
@@ -303,4 +304,30 @@ describe('agentRouter', () => {
);
});
});
+
+ describe('updateAgentPinned', () => {
+ it('should pin an agent', async () => {
+ const mockInput = {
+ id: 'agent1',
+ pinned: true,
+ };
+
+ const caller = agentRouter.createCaller(mockCtx);
+ await caller.updateAgentPinned(mockInput);
+
+ expect(agentModelMock.update).toHaveBeenCalledWith(mockInput.id, { pinned: true });
+ });
+
+ it('should unpin an agent', async () => {
+ const mockInput = {
+ id: 'agent1',
+ pinned: false,
+ };
+
+ const caller = agentRouter.createCaller(mockCtx);
+ await caller.updateAgentPinned(mockInput);
+
+ expect(agentModelMock.update).toHaveBeenCalledWith(mockInput.id, { pinned: false });
+ });
+ });
});
diff --git a/src/server/routers/lambda/__tests__/agentGroup.test.ts b/src/server/routers/lambda/__tests__/agentGroup.test.ts
new file mode 100644
index 00000000000..7bd93f8418b
--- /dev/null
+++ b/src/server/routers/lambda/__tests__/agentGroup.test.ts
@@ -0,0 +1,416 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { DEFAULT_CHAT_GROUP_CHAT_CONFIG } from '@/const/settings';
+import * as AgentModelModule from '@/database/models/agent';
+import * as ChatGroupModelModule from '@/database/models/chatGroup';
+import * as AgentGroupRepoModule from '@/database/repositories/agentGroup';
+
+import { agentGroupRouter } from '../agentGroup';
+
+describe('agentGroupRouter', () => {
+ const userId = 'testUserId';
+ let mockCtx: any;
+ let agentModelMock: any;
+ let chatGroupModelMock: any;
+ let agentGroupRepoMock: any;
+
+ beforeEach(() => {
+ vi.restoreAllMocks();
+
+ agentModelMock = {
+ batchCreate: vi.fn(),
+ };
+
+ chatGroupModelMock = {
+ addAgentsToGroup: vi.fn(),
+ create: vi.fn(),
+ createWithAgents: vi.fn(),
+ delete: vi.fn(),
+ findById: vi.fn(),
+ getGroupAgents: vi.fn(),
+ queryWithMemberDetails: vi.fn(),
+ removeAgentFromGroup: vi.fn(),
+ update: vi.fn(),
+ updateAgentInGroup: vi.fn(),
+ };
+
+ agentGroupRepoMock = {
+ createGroupWithSupervisor: vi.fn(),
+ findByIdWithAgents: vi.fn(),
+ removeAgentsFromGroup: vi.fn(),
+ };
+
+ // Use vi.spyOn to mock the class constructors to return our mock instances
+ vi.spyOn(AgentModelModule, 'AgentModel').mockImplementation(() => agentModelMock as any);
+ vi.spyOn(ChatGroupModelModule, 'ChatGroupModel').mockImplementation(
+ () => chatGroupModelMock as any,
+ );
+ vi.spyOn(AgentGroupRepoModule, 'AgentGroupRepository').mockImplementation(
+ () => agentGroupRepoMock as any,
+ );
+
+ mockCtx = {
+ serverDB: {},
+ userId,
+ };
+ });
+
+ describe('createGroup', () => {
+ it('should create a group with normalized config', async () => {
+ const mockInput = {
+ title: 'Test Group',
+ description: 'Test Description',
+ config: {
+ enableSupervisor: true,
+ },
+ };
+
+ const mockCreatedGroup = {
+ id: 'group-1',
+ title: 'Test Group',
+ description: 'Test Description',
+ config: { ...DEFAULT_CHAT_GROUP_CHAT_CONFIG, enableSupervisor: true },
+ };
+
+ agentGroupRepoMock.createGroupWithSupervisor.mockResolvedValue({
+ group: mockCreatedGroup,
+ supervisorAgentId: 'supervisor-1',
+ });
+
+ const caller = agentGroupRouter.createCaller(mockCtx);
+ const result = await caller.createGroup(mockInput);
+
+ expect(agentGroupRepoMock.createGroupWithSupervisor).toHaveBeenCalledWith({
+ ...mockInput,
+ config: { ...DEFAULT_CHAT_GROUP_CHAT_CONFIG, enableSupervisor: true },
+ });
+ expect(result).toEqual({ group: mockCreatedGroup, supervisorAgentId: 'supervisor-1' });
+ });
+
+ it('should create a group without config', async () => {
+ const mockInput = {
+ title: 'Test Group',
+ };
+
+ const mockCreatedGroup = {
+ id: 'group-1',
+ title: 'Test Group',
+ };
+
+ agentGroupRepoMock.createGroupWithSupervisor.mockResolvedValue({
+ group: mockCreatedGroup,
+ supervisorAgentId: 'supervisor-1',
+ });
+
+ const caller = agentGroupRouter.createCaller(mockCtx);
+ const result = await caller.createGroup(mockInput);
+
+ expect(agentGroupRepoMock.createGroupWithSupervisor).toHaveBeenCalledWith({
+ ...mockInput,
+ config: undefined,
+ });
+ expect(result).toEqual({ group: mockCreatedGroup, supervisorAgentId: 'supervisor-1' });
+ });
+ });
+
+ describe('createGroupWithMembers', () => {
+ it('should create a group with virtual member agents', async () => {
+ const mockInput = {
+ groupConfig: {
+ title: 'Team Group',
+ config: { enableSupervisor: true },
+ },
+ members: [
+ { title: 'Agent 1', systemRole: 'Helper' },
+ { title: 'Agent 2', systemRole: 'Assistant' },
+ ],
+ };
+
+ const mockCreatedAgents = [{ id: 'agent-1' }, { id: 'agent-2' }];
+ const mockCreatedGroup = { id: 'group-1', title: 'Team Group' };
+
+ agentModelMock.batchCreate.mockResolvedValue(mockCreatedAgents);
+ agentGroupRepoMock.createGroupWithSupervisor.mockResolvedValue({
+ group: mockCreatedGroup,
+ supervisorAgentId: 'supervisor-1',
+ });
+
+ const caller = agentGroupRouter.createCaller(mockCtx);
+ const result = await caller.createGroupWithMembers(mockInput);
+
+ expect(agentModelMock.batchCreate).toHaveBeenCalledWith([
+ { title: 'Agent 1', systemRole: 'Helper', virtual: true },
+ { title: 'Agent 2', systemRole: 'Assistant', virtual: true },
+ ]);
+ expect(agentGroupRepoMock.createGroupWithSupervisor).toHaveBeenCalledWith(
+ {
+ title: 'Team Group',
+ config: { ...DEFAULT_CHAT_GROUP_CHAT_CONFIG, enableSupervisor: true },
+ },
+ ['agent-1', 'agent-2'],
+ );
+ expect(result).toEqual({
+ agentIds: ['agent-1', 'agent-2'],
+ groupId: 'group-1',
+ supervisorAgentId: 'supervisor-1',
+ });
+ });
+ });
+
+ describe('deleteGroup', () => {
+ it('should delete a group by id', async () => {
+ chatGroupModelMock.delete.mockResolvedValue({ id: 'group-1' });
+
+ const caller = agentGroupRouter.createCaller(mockCtx);
+ await caller.deleteGroup({ id: 'group-1' });
+
+ expect(chatGroupModelMock.delete).toHaveBeenCalledWith('group-1');
+ });
+ });
+
+ describe('getGroup', () => {
+ it('should get a group by id', async () => {
+ const mockGroup = {
+ id: 'group-1',
+ title: 'Test Group',
+ config: DEFAULT_CHAT_GROUP_CHAT_CONFIG,
+ };
+
+ chatGroupModelMock.findById.mockResolvedValue(mockGroup);
+
+ const caller = agentGroupRouter.createCaller(mockCtx);
+ const result = await caller.getGroup({ id: 'group-1' });
+
+ expect(chatGroupModelMock.findById).toHaveBeenCalledWith('group-1');
+ expect(result).toEqual(mockGroup);
+ });
+
+ it('should return undefined if group not found', async () => {
+ chatGroupModelMock.findById.mockResolvedValue(undefined);
+
+ const caller = agentGroupRouter.createCaller(mockCtx);
+ const result = await caller.getGroup({ id: 'non-existent' });
+
+ expect(result).toBeUndefined();
+ });
+ });
+
+ describe('getGroupDetail', () => {
+ it('should get group detail with agents', async () => {
+ const mockGroupDetail = {
+ id: 'group-1',
+ title: 'Test Group',
+ config: DEFAULT_CHAT_GROUP_CHAT_CONFIG,
+ agents: [
+ { id: 'agent-1', title: 'Agent 1' },
+ { id: 'agent-2', title: 'Agent 2' },
+ ],
+ };
+
+ agentGroupRepoMock.findByIdWithAgents.mockResolvedValue(mockGroupDetail);
+
+ const caller = agentGroupRouter.createCaller(mockCtx);
+ const result = await caller.getGroupDetail({ id: 'group-1' });
+
+ expect(agentGroupRepoMock.findByIdWithAgents).toHaveBeenCalledWith('group-1');
+ expect(result).toEqual(mockGroupDetail);
+ });
+
+ it('should return null if group not found', async () => {
+ agentGroupRepoMock.findByIdWithAgents.mockResolvedValue(null);
+
+ const caller = agentGroupRouter.createCaller(mockCtx);
+ const result = await caller.getGroupDetail({ id: 'non-existent' });
+
+ expect(result).toBeNull();
+ });
+ });
+
+ describe('getGroupAgents', () => {
+ it('should get agents of a group', async () => {
+ const mockAgents = [
+ { agentId: 'agent-1', chatGroupId: 'group-1', order: 0 },
+ { agentId: 'agent-2', chatGroupId: 'group-1', order: 1 },
+ ];
+
+ chatGroupModelMock.getGroupAgents.mockResolvedValue(mockAgents);
+
+ const caller = agentGroupRouter.createCaller(mockCtx);
+ const result = await caller.getGroupAgents({ groupId: 'group-1' });
+
+ expect(chatGroupModelMock.getGroupAgents).toHaveBeenCalledWith('group-1');
+ expect(result).toEqual(mockAgents);
+ });
+ });
+
+ describe('getGroups', () => {
+ it('should get all groups with member details', async () => {
+ const mockGroups = [
+ { id: 'group-1', title: 'Group 1' },
+ { id: 'group-2', title: 'Group 2' },
+ ];
+
+ chatGroupModelMock.queryWithMemberDetails.mockResolvedValue(mockGroups);
+
+ const caller = agentGroupRouter.createCaller(mockCtx);
+ const result = await caller.getGroups();
+
+ expect(chatGroupModelMock.queryWithMemberDetails).toHaveBeenCalled();
+ expect(result).toEqual(mockGroups);
+ });
+ });
+
+ describe('addAgentsToGroup', () => {
+ it('should add agents to a group', async () => {
+ const mockInput = {
+ groupId: 'group-1',
+ agentIds: ['agent-1', 'agent-2'],
+ };
+
+ const mockResult = [
+ { agentId: 'agent-1', chatGroupId: 'group-1' },
+ { agentId: 'agent-2', chatGroupId: 'group-1' },
+ ];
+
+ chatGroupModelMock.addAgentsToGroup.mockResolvedValue(mockResult);
+
+ const caller = agentGroupRouter.createCaller(mockCtx);
+ const result = await caller.addAgentsToGroup(mockInput);
+
+ expect(chatGroupModelMock.addAgentsToGroup).toHaveBeenCalledWith('group-1', [
+ 'agent-1',
+ 'agent-2',
+ ]);
+ expect(result).toEqual(mockResult);
+ });
+ });
+
+ describe('removeAgentsFromGroup', () => {
+ it('should remove agents from a group', async () => {
+ const mockInput = {
+ groupId: 'group-1',
+ agentIds: ['agent-1', 'agent-2'],
+ };
+
+ const mockResult = {
+ deletedVirtualAgentIds: [],
+ removedFromGroup: 2,
+ };
+
+ agentGroupRepoMock.removeAgentsFromGroup.mockResolvedValue(mockResult);
+
+ const caller = agentGroupRouter.createCaller(mockCtx);
+ const result = await caller.removeAgentsFromGroup(mockInput);
+
+ expect(agentGroupRepoMock.removeAgentsFromGroup).toHaveBeenCalledWith(
+ 'group-1',
+ ['agent-1', 'agent-2'],
+ undefined,
+ );
+ expect(result).toEqual(mockResult);
+ });
+ });
+
+ describe('updateAgentInGroup', () => {
+ it('should update agent in a group', async () => {
+ const mockInput = {
+ groupId: 'group-1',
+ agentId: 'agent-1',
+ updates: { order: 2, role: 'leader' },
+ };
+
+ const mockResult = {
+ agentId: 'agent-1',
+ chatGroupId: 'group-1',
+ order: 2,
+ role: 'leader',
+ };
+
+ chatGroupModelMock.updateAgentInGroup.mockResolvedValue(mockResult);
+
+ const caller = agentGroupRouter.createCaller(mockCtx);
+ const result = await caller.updateAgentInGroup(mockInput);
+
+ expect(chatGroupModelMock.updateAgentInGroup).toHaveBeenCalledWith('group-1', 'agent-1', {
+ order: 2,
+ role: 'leader',
+ });
+ expect(result).toEqual(mockResult);
+ });
+
+ it('should update agent with enabled flag', async () => {
+ const mockInput = {
+ groupId: 'group-1',
+ agentId: 'agent-1',
+ updates: { enabled: false },
+ };
+
+ chatGroupModelMock.updateAgentInGroup.mockResolvedValue({});
+
+ const caller = agentGroupRouter.createCaller(mockCtx);
+ await caller.updateAgentInGroup(mockInput);
+
+ expect(chatGroupModelMock.updateAgentInGroup).toHaveBeenCalledWith('group-1', 'agent-1', {
+ enabled: false,
+ });
+ });
+ });
+
+ describe('updateGroup', () => {
+ it('should update a group with normalized config', async () => {
+ const mockInput = {
+ id: 'group-1',
+ value: {
+ title: 'Updated Title',
+ config: { enableSupervisor: false },
+ },
+ };
+
+ const mockUpdatedGroup = {
+ id: 'group-1',
+ title: 'Updated Title',
+ config: { ...DEFAULT_CHAT_GROUP_CHAT_CONFIG, enableSupervisor: false },
+ };
+
+ chatGroupModelMock.update.mockResolvedValue(mockUpdatedGroup);
+
+ const caller = agentGroupRouter.createCaller(mockCtx);
+ const result = await caller.updateGroup(mockInput);
+
+ expect(chatGroupModelMock.update).toHaveBeenCalledWith('group-1', {
+ title: 'Updated Title',
+ config: { ...DEFAULT_CHAT_GROUP_CHAT_CONFIG, enableSupervisor: false },
+ });
+ expect(result).toEqual(mockUpdatedGroup);
+ });
+
+ it('should update a group without config changes', async () => {
+ const mockInput = {
+ id: 'group-1',
+ value: {
+ title: 'New Title',
+ description: 'New Description',
+ },
+ };
+
+ const mockUpdatedGroup = {
+ id: 'group-1',
+ title: 'New Title',
+ description: 'New Description',
+ };
+
+ chatGroupModelMock.update.mockResolvedValue(mockUpdatedGroup);
+
+ const caller = agentGroupRouter.createCaller(mockCtx);
+ const result = await caller.updateGroup(mockInput);
+
+ expect(chatGroupModelMock.update).toHaveBeenCalledWith('group-1', {
+ title: 'New Title',
+ description: 'New Description',
+ config: undefined,
+ });
+ expect(result).toEqual(mockUpdatedGroup);
+ });
+ });
+});
diff --git a/src/server/routers/lambda/__tests__/aiAgent.execGroupSubAgentTask.test.ts b/src/server/routers/lambda/__tests__/aiAgent.execGroupSubAgentTask.test.ts
new file mode 100644
index 00000000000..4e09be88ed9
--- /dev/null
+++ b/src/server/routers/lambda/__tests__/aiAgent.execGroupSubAgentTask.test.ts
@@ -0,0 +1,291 @@
+// @vitest-environment node
+import { LobeChatDatabase } from '@lobechat/database';
+import { agents, chatGroups, sessions, topics } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { TRPCError } from '@trpc/server';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { aiAgentRouter } from '../aiAgent';
+import { cleanupTestUser, createTestUser } from './integration/setup';
+
+// Mock getServerDB to return our test database instance
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => testDB),
+}));
+
+// Mock AiAgentService
+const mockExecGroupSubAgentTask = vi.fn();
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn().mockImplementation(() => ({
+ execGroupSubAgentTask: mockExecGroupSubAgentTask,
+ })),
+}));
+
+// Mock AgentRuntimeService
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(() => ({})),
+}));
+
+// Mock AiChatService
+vi.mock('@/server/services/aiChat', () => ({
+ AiChatService: vi.fn().mockImplementation(() => ({})),
+}));
+
+describe('aiAgentRouter.execGroupSubAgentTask', () => {
+ let serverDB: LobeChatDatabase;
+ let userId: string;
+ let testAgentId: string;
+ let testGroupId: string;
+ let testTopicId: string;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+
+ // Create test agent
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({
+ userId,
+ title: 'Test SubAgent',
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant.',
+ })
+ .returning();
+ testAgentId = agent.id;
+
+ // Create test session
+ const [session] = await serverDB.insert(sessions).values({ userId, type: 'group' }).returning();
+
+ // Create test group
+ const [group] = await serverDB
+ .insert(chatGroups)
+ .values({
+ userId,
+ title: 'Test Group',
+ })
+ .returning();
+ testGroupId = group.id;
+
+ // Create test topic
+ const [topic] = await serverDB
+ .insert(topics)
+ .values({
+ userId,
+ title: 'Test Topic',
+ agentId: testAgentId,
+ sessionId: session.id,
+ groupId: testGroupId,
+ })
+ .returning();
+ testTopicId = topic.id;
+
+ // Reset mock
+ mockExecGroupSubAgentTask.mockReset();
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ vi.clearAllMocks();
+ });
+
+ const createTestContext = () => ({
+ userId,
+ jwtPayload: { userId },
+ });
+
+ describe('successful execution', () => {
+ it('should call service method with correct parameters', async () => {
+ mockExecGroupSubAgentTask.mockResolvedValue({
+ assistantMessageId: 'assistant-msg-1',
+ operationId: 'op-123',
+ success: true,
+ threadId: 'thread-123',
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await caller.execGroupSubAgentTask({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ instruction: 'Test instruction',
+ parentMessageId: 'parent-msg-1',
+ topicId: testTopicId,
+ });
+
+ expect(mockExecGroupSubAgentTask).toHaveBeenCalledWith({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ instruction: 'Test instruction',
+ parentMessageId: 'parent-msg-1',
+ timeout: undefined,
+ topicId: testTopicId,
+ });
+ });
+
+ it('should return result from service', async () => {
+ mockExecGroupSubAgentTask.mockResolvedValue({
+ assistantMessageId: 'assistant-msg-1',
+ operationId: 'op-123',
+ success: true,
+ threadId: 'thread-123',
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.execGroupSubAgentTask({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ instruction: 'Test instruction',
+ parentMessageId: 'parent-msg-1',
+ topicId: testTopicId,
+ });
+
+ expect(result).toEqual({
+ assistantMessageId: 'assistant-msg-1',
+ operationId: 'op-123',
+ success: true,
+ threadId: 'thread-123',
+ });
+ });
+
+ it('should pass timeout parameter when provided', async () => {
+ mockExecGroupSubAgentTask.mockResolvedValue({
+ assistantMessageId: 'assistant-msg-1',
+ operationId: 'op-123',
+ success: true,
+ threadId: 'thread-123',
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await caller.execGroupSubAgentTask({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ instruction: 'Test instruction',
+ parentMessageId: 'parent-msg-1',
+ timeout: 60000,
+ topicId: testTopicId,
+ });
+
+ expect(mockExecGroupSubAgentTask).toHaveBeenCalledWith(
+ expect.objectContaining({
+ timeout: 60000,
+ }),
+ );
+ });
+ });
+
+ describe('input validation', () => {
+ it('should reject when agentId is missing', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await expect(
+ caller.execGroupSubAgentTask({
+ agentId: undefined,
+ groupId: testGroupId,
+ instruction: 'Test instruction',
+ parentMessageId: 'parent-msg-1',
+ topicId: testTopicId,
+ } as any),
+ ).rejects.toThrow();
+ });
+
+ it('should reject when groupId is missing', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await expect(
+ caller.execGroupSubAgentTask({
+ agentId: testAgentId,
+ groupId: undefined,
+ instruction: 'Test instruction',
+ parentMessageId: 'parent-msg-1',
+ topicId: testTopicId,
+ } as any),
+ ).rejects.toThrow();
+ });
+
+ it('should reject when instruction is missing', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await expect(
+ caller.execGroupSubAgentTask({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ instruction: undefined,
+ parentMessageId: 'parent-msg-1',
+ topicId: testTopicId,
+ } as any),
+ ).rejects.toThrow();
+ });
+
+ it('should reject when topicId is missing', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await expect(
+ caller.execGroupSubAgentTask({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ instruction: 'Test instruction',
+ parentMessageId: 'parent-msg-1',
+ topicId: undefined,
+ } as any),
+ ).rejects.toThrow();
+ });
+
+ it('should reject when parentMessageId is missing', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await expect(
+ caller.execGroupSubAgentTask({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ instruction: 'Test instruction',
+ parentMessageId: undefined,
+ topicId: testTopicId,
+ } as any),
+ ).rejects.toThrow();
+ });
+ });
+
+ describe('error handling', () => {
+ it('should re-throw TRPCError from service', async () => {
+ const trpcError = new TRPCError({
+ code: 'NOT_FOUND',
+ message: 'Agent not found',
+ });
+ mockExecGroupSubAgentTask.mockRejectedValue(trpcError);
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await expect(
+ caller.execGroupSubAgentTask({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ instruction: 'Test instruction',
+ parentMessageId: 'parent-msg-1',
+ topicId: testTopicId,
+ }),
+ ).rejects.toThrow('Agent not found');
+ });
+
+ it('should wrap non-TRPCError as INTERNAL_SERVER_ERROR', async () => {
+ mockExecGroupSubAgentTask.mockRejectedValue(new Error('Database connection failed'));
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await expect(
+ caller.execGroupSubAgentTask({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ instruction: 'Test instruction',
+ parentMessageId: 'parent-msg-1',
+ topicId: testTopicId,
+ }),
+ ).rejects.toThrow('Failed to execute sub-agent task: Database connection failed');
+ });
+ });
+});
diff --git a/src/server/routers/lambda/__tests__/aiAgent.getTaskStatus.test.ts b/src/server/routers/lambda/__tests__/aiAgent.getTaskStatus.test.ts
new file mode 100644
index 00000000000..2aebdd73a72
--- /dev/null
+++ b/src/server/routers/lambda/__tests__/aiAgent.getTaskStatus.test.ts
@@ -0,0 +1,710 @@
+// @vitest-environment node
+import { LobeChatDatabase } from '@lobechat/database';
+import {
+ agents,
+ chatGroups,
+ messages,
+ sessions,
+ threads,
+ topics,
+} from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { ThreadStatus, ThreadType } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { aiAgentRouter } from '../aiAgent';
+import { cleanupTestUser, createTestUser } from './integration/setup';
+
+// Mock getServerDB to return our test database instance
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => testDB),
+}));
+
+// Mock AgentRuntimeService
+const mockGetOperationStatus = vi.fn();
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(() => ({
+ getOperationStatus: mockGetOperationStatus,
+ })),
+}));
+
+// Mock AiAgentService
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn().mockImplementation(() => ({})),
+}));
+
+// Mock AiChatService
+vi.mock('@/server/services/aiChat', () => ({
+ AiChatService: vi.fn().mockImplementation(() => ({})),
+}));
+
+describe('aiAgentRouter.getGroupSubAgentTaskStatus', () => {
+ let serverDB: LobeChatDatabase;
+ let userId: string;
+ let testAgentId: string;
+ let testGroupId: string;
+ let testTopicId: string;
+ let testThreadId: string;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+
+ // Create test agent
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({
+ userId,
+ title: 'Test SubAgent',
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant.',
+ })
+ .returning();
+ testAgentId = agent.id;
+
+ // Create test session
+ const [session] = await serverDB.insert(sessions).values({ userId, type: 'group' }).returning();
+
+ // Create test group
+ const [group] = await serverDB
+ .insert(chatGroups)
+ .values({
+ userId,
+ title: 'Test Group',
+ })
+ .returning();
+ testGroupId = group.id;
+
+ // Create test topic
+ const [topic] = await serverDB
+ .insert(topics)
+ .values({
+ userId,
+ title: 'Test Topic',
+ agentId: testAgentId,
+ sessionId: session.id,
+ groupId: testGroupId,
+ })
+ .returning();
+ testTopicId = topic.id;
+
+ // Create test thread
+ const [thread] = (await serverDB
+ .insert(threads)
+ .values({
+ userId,
+ agentId: testAgentId,
+ topicId: testTopicId,
+ groupId: testGroupId,
+ sourceMessageId: 'source-msg-1',
+ type: ThreadType.Isolation,
+ status: ThreadStatus.Processing,
+ metadata: { operationId: 'op-test-123' },
+ })
+ .returning()) as any[];
+ testThreadId = thread.id;
+
+ // Reset mock
+ mockGetOperationStatus.mockReset();
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ vi.clearAllMocks();
+ });
+
+ const createTestContext = () => ({
+ userId,
+ jwtPayload: { userId },
+ });
+
+ describe('query by threadId', () => {
+ it('should return task status from Thread table', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.getGroupSubAgentTaskStatus({
+ threadId: testThreadId,
+ });
+
+ expect(result.status).toBe('processing');
+ expect(result.taskDetail).toBeDefined();
+ expect(result.taskDetail?.threadId).toBe(testThreadId);
+ expect(result.taskDetail?.status).toBe(ThreadStatus.Processing);
+ });
+
+ it('should throw NOT_FOUND when thread does not exist', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await expect(
+ caller.getGroupSubAgentTaskStatus({
+ threadId: 'non-existent-thread-id',
+ }),
+ ).rejects.toThrow('Thread not found');
+ });
+
+ it('should return completed status from Thread', async () => {
+ // Update thread to completed status
+ await serverDB
+ .update(threads)
+ .set({
+ status: ThreadStatus.Completed,
+ metadata: {
+ operationId: 'op-test-123',
+ completedAt: '2024-01-01T00:00:00Z',
+ duration: 5000,
+ totalTokens: 1000,
+ totalToolCalls: 3,
+ },
+ })
+ .where(eq(threads.id, testThreadId));
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.getGroupSubAgentTaskStatus({
+ threadId: testThreadId,
+ });
+
+ expect(result.status).toBe('completed');
+ expect(result.completedAt).toBe('2024-01-01T00:00:00Z');
+ expect(result.taskDetail?.duration).toBe(5000);
+ expect(result.taskDetail?.totalTokens).toBe(1000);
+ expect(result.taskDetail?.totalToolCalls).toBe(3);
+ });
+ });
+
+ describe('status mapping from ThreadStatus', () => {
+ it.each([
+ [ThreadStatus.Active, 'processing'],
+ [ThreadStatus.Processing, 'processing'],
+ [ThreadStatus.Pending, 'processing'],
+ [ThreadStatus.InReview, 'processing'],
+ [ThreadStatus.Todo, 'processing'],
+ [ThreadStatus.Completed, 'completed'],
+ [ThreadStatus.Failed, 'failed'],
+ [ThreadStatus.Cancel, 'cancel'],
+ ])(
+ 'should map ThreadStatus.%s to task status "%s"',
+ async (threadStatus, expectedTaskStatus) => {
+ // Update thread status
+ await serverDB
+ .update(threads)
+ .set({ status: threadStatus })
+ .where(eq(threads.id, testThreadId));
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.getGroupSubAgentTaskStatus({
+ threadId: testThreadId,
+ });
+
+ expect(result.status).toBe(expectedTaskStatus);
+ },
+ );
+ });
+
+ describe('real-time status from Redis', () => {
+ it('should supplement with Redis status when available for processing tasks', async () => {
+ mockGetOperationStatus.mockResolvedValue({
+ currentState: {
+ status: 'running',
+ stepCount: 3,
+ cost: { total: 0.05 },
+ usage: { total_tokens: 1000 },
+ },
+ isCompleted: false,
+ hasError: false,
+ metadata: {},
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.getGroupSubAgentTaskStatus({
+ threadId: testThreadId,
+ });
+
+ expect(result.status).toBe('processing');
+ expect(result.stepCount).toBe(3);
+ expect(result.cost).toEqual({ total: 0.05 });
+ expect(mockGetOperationStatus).toHaveBeenCalledWith({
+ operationId: 'op-test-123',
+ });
+ });
+
+ it('should extract totalToolCalls from usage.tools.totalCalls', async () => {
+ mockGetOperationStatus.mockResolvedValue({
+ currentState: {
+ status: 'running',
+ stepCount: 2,
+ cost: { total: 0.006678 },
+ usage: {
+ llm: {
+ tokens: { total: 8358 },
+ },
+ tools: {
+ totalCalls: 5,
+ byTool: [
+ { name: 'lobe-web-browsing/search', calls: 3 },
+ { name: 'lobe-web-browsing/fetch', calls: 2 },
+ ],
+ },
+ },
+ },
+ stats: { totalMessages: 4 },
+ isCompleted: false,
+ hasError: false,
+ metadata: {},
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.getGroupSubAgentTaskStatus({
+ threadId: testThreadId,
+ });
+
+ expect(result.taskDetail?.totalToolCalls).toBe(5);
+ expect(result.taskDetail?.totalTokens).toBe(8358);
+ });
+
+ it('should fallback to Thread data when Redis returns null (operation expired)', async () => {
+ // getOperationStatus now returns null when operation not found (instead of throwing)
+ mockGetOperationStatus.mockResolvedValue(null);
+
+ // Update thread with metadata
+ await serverDB
+ .update(threads)
+ .set({
+ metadata: {
+ operationId: 'op-test-123',
+ totalTokens: 500,
+ totalCost: 0.02,
+ },
+ })
+ .where(eq(threads.id, testThreadId));
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.getGroupSubAgentTaskStatus({
+ threadId: testThreadId,
+ });
+
+ expect(result.status).toBe('processing');
+ expect(result.usage).toEqual({ total_tokens: 500 });
+ expect(result.cost).toEqual({ total: 0.02 });
+ });
+
+ it('should not query Redis for completed tasks', async () => {
+ // Update thread to completed status
+ await serverDB
+ .update(threads)
+ .set({
+ status: ThreadStatus.Completed,
+ metadata: { operationId: 'op-test-123' },
+ })
+ .where(eq(threads.id, testThreadId));
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await caller.getGroupSubAgentTaskStatus({
+ threadId: testThreadId,
+ });
+
+ // Should not call Redis for completed tasks
+ expect(mockGetOperationStatus).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('error handling', () => {
+ it('should include error message from Thread metadata', async () => {
+ await serverDB
+ .update(threads)
+ .set({
+ status: ThreadStatus.Failed,
+ metadata: {
+ operationId: 'op-test-123',
+ error: 'Tool execution failed',
+ },
+ })
+ .where(eq(threads.id, testThreadId));
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.getGroupSubAgentTaskStatus({
+ threadId: testThreadId,
+ });
+
+ expect(result.status).toBe('failed');
+ expect(result.error).toBe('Tool execution failed');
+ expect(result.taskDetail?.error).toBe('Tool execution failed');
+ });
+ });
+
+ describe('taskDetail', () => {
+ it('should include complete taskDetail in response', async () => {
+ const startedAt = '2024-01-01T10:00:00.000Z';
+ const completedAt = '2024-01-01T10:05:00.000Z';
+
+ await serverDB
+ .update(threads)
+ .set({
+ title: 'Research Task',
+ status: ThreadStatus.Completed,
+ metadata: {
+ operationId: 'op-test-123',
+ startedAt,
+ completedAt,
+ duration: 300000,
+ totalTokens: 5000,
+ totalToolCalls: 10,
+ totalMessages: 20,
+ totalCost: 0.15,
+ },
+ })
+ .where(eq(threads.id, testThreadId));
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.getGroupSubAgentTaskStatus({
+ threadId: testThreadId,
+ });
+
+ expect(result.taskDetail).toEqual({
+ threadId: testThreadId,
+ title: 'Research Task',
+ status: ThreadStatus.Completed,
+ startedAt,
+ completedAt,
+ duration: 300000,
+ totalTokens: 5000,
+ totalToolCalls: 10,
+ totalMessages: 20,
+ totalCost: 0.15,
+ error: undefined,
+ });
+ });
+ });
+
+ describe('input validation', () => {
+ it('should require threadId', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await expect(caller.getGroupSubAgentTaskStatus({} as any)).rejects.toThrow();
+ });
+ });
+
+ describe('result content', () => {
+ it('should return result content from last assistant message when task is completed', async () => {
+ // Create assistant messages in the thread with different timestamps
+ const now = new Date();
+ await serverDB.insert(messages).values([
+ {
+ userId,
+ role: 'user',
+ content: 'User question',
+ agentId: testAgentId,
+ topicId: testTopicId,
+ threadId: testThreadId,
+ createdAt: new Date(now.getTime() - 2000),
+ },
+ {
+ userId,
+ role: 'assistant',
+ content: 'First assistant response',
+ agentId: testAgentId,
+ topicId: testTopicId,
+ threadId: testThreadId,
+ createdAt: new Date(now.getTime() - 1000),
+ },
+ {
+ userId,
+ role: 'assistant',
+ content: 'This is the final result of the task execution.',
+ agentId: testAgentId,
+ topicId: testTopicId,
+ threadId: testThreadId,
+ createdAt: now,
+ },
+ ]);
+
+ // Update thread to completed status
+ await serverDB
+ .update(threads)
+ .set({
+ status: ThreadStatus.Completed,
+ metadata: {
+ operationId: 'op-test-123',
+ completedAt: '2024-01-01T00:00:00Z',
+ },
+ })
+ .where(eq(threads.id, testThreadId));
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.getGroupSubAgentTaskStatus({
+ threadId: testThreadId,
+ });
+
+ expect(result.status).toBe('completed');
+ expect(result.result).toBe('This is the final result of the task execution.');
+ });
+
+ it('should return result content from last assistant message when task is failed', async () => {
+ // Create assistant message in the thread
+ await serverDB.insert(messages).values({
+ userId,
+ role: 'assistant',
+ content: 'Partial result before failure.',
+ agentId: testAgentId,
+ topicId: testTopicId,
+ threadId: testThreadId,
+ });
+
+ // Update thread to failed status
+ await serverDB
+ .update(threads)
+ .set({
+ status: ThreadStatus.Failed,
+ metadata: {
+ operationId: 'op-test-123',
+ error: 'Task failed due to timeout',
+ },
+ })
+ .where(eq(threads.id, testThreadId));
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.getGroupSubAgentTaskStatus({
+ threadId: testThreadId,
+ });
+
+ expect(result.status).toBe('failed');
+ expect(result.result).toBe('Partial result before failure.');
+ expect(result.error).toBe('Task failed due to timeout');
+ });
+
+ it('should not return result content when task is still processing', async () => {
+ // Create assistant message in the thread
+ await serverDB.insert(messages).values({
+ userId,
+ role: 'assistant',
+ content: 'Some content',
+ agentId: testAgentId,
+ topicId: testTopicId,
+ threadId: testThreadId,
+ });
+
+ // Thread is in processing status (default from beforeEach)
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.getGroupSubAgentTaskStatus({
+ threadId: testThreadId,
+ });
+
+ expect(result.status).toBe('processing');
+ expect(result.result).toBeUndefined();
+ });
+
+ it('should return undefined result when no assistant messages in thread', async () => {
+ // Update thread to completed status without any messages
+ await serverDB
+ .update(threads)
+ .set({
+ status: ThreadStatus.Completed,
+ metadata: {
+ operationId: 'op-test-123',
+ completedAt: '2024-01-01T00:00:00Z',
+ },
+ })
+ .where(eq(threads.id, testThreadId));
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.getGroupSubAgentTaskStatus({
+ threadId: testThreadId,
+ });
+
+ expect(result.status).toBe('completed');
+ expect(result.result).toBeUndefined();
+ });
+ });
+
+ describe('currentActivity', () => {
+ it('should return tool_calling activity when last assistant message has tools', async () => {
+ // Create assistant message with tools
+ await serverDB.insert(messages).values({
+ userId,
+ role: 'assistant',
+ content: '',
+ agentId: testAgentId,
+ topicId: testTopicId,
+ threadId: testThreadId,
+ tools: [
+ { identifier: 'lobe-web-browsing', apiName: 'search', arguments: '{"query":"test"}' },
+ ],
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.getGroupSubAgentTaskStatus({
+ threadId: testThreadId,
+ });
+
+ expect(result.status).toBe('processing');
+ expect(result.currentActivity).toEqual({
+ type: 'tool_calling',
+ identifier: 'lobe-web-browsing',
+ apiName: 'search',
+ });
+ });
+
+ it('should return tool_result activity when last message is tool role', async () => {
+ // First create the assistant message, then create tool message
+ const now = new Date();
+ await serverDB.insert(messages).values([
+ {
+ userId,
+ role: 'assistant',
+ content: '',
+ agentId: testAgentId,
+ topicId: testTopicId,
+ threadId: testThreadId,
+ tools: [{ identifier: 'lobe-web-browsing', apiName: 'search' }],
+ createdAt: new Date(now.getTime() - 1000),
+ },
+ {
+ userId,
+ role: 'tool',
+ content: 'Search results: found 10 items matching your query...',
+ agentId: testAgentId,
+ topicId: testTopicId,
+ threadId: testThreadId,
+ createdAt: now,
+ },
+ ]);
+
+ // Update the tool message with plugin info
+ const toolMessages = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.threadId, testThreadId));
+ const toolMsg = toolMessages.find((m) => m.role === 'tool');
+
+ if (toolMsg) {
+ const { messagePlugins } = await import('@lobechat/database/schemas');
+ await serverDB.insert(messagePlugins).values({
+ id: toolMsg.id,
+ userId,
+ identifier: 'lobe-web-browsing',
+ apiName: 'search',
+ type: 'default',
+ });
+ }
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.getGroupSubAgentTaskStatus({
+ threadId: testThreadId,
+ });
+
+ expect(result.status).toBe('processing');
+ expect(result.currentActivity?.type).toBe('tool_result');
+ expect(result.currentActivity?.identifier).toBe('lobe-web-browsing');
+ expect(result.currentActivity?.apiName).toBe('search');
+ expect(result.currentActivity?.contentPreview).toBe(
+ 'Search results: found 10 items matching your query...',
+ );
+ });
+
+ it('should return generating activity when last assistant message has no tools', async () => {
+ // Create assistant message without tools
+ await serverDB.insert(messages).values({
+ userId,
+ role: 'assistant',
+ content: 'I am generating a response based on the information...',
+ agentId: testAgentId,
+ topicId: testTopicId,
+ threadId: testThreadId,
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.getGroupSubAgentTaskStatus({
+ threadId: testThreadId,
+ });
+
+ expect(result.status).toBe('processing');
+ expect(result.currentActivity).toEqual({
+ type: 'generating',
+ contentPreview: 'I am generating a response based on the information...',
+ });
+ });
+
+ it('should truncate contentPreview to 100 characters', async () => {
+ const longContent = 'A'.repeat(200);
+
+ await serverDB.insert(messages).values({
+ userId,
+ role: 'assistant',
+ content: longContent,
+ agentId: testAgentId,
+ topicId: testTopicId,
+ threadId: testThreadId,
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.getGroupSubAgentTaskStatus({
+ threadId: testThreadId,
+ });
+
+ expect(result.currentActivity?.contentPreview).toBe('A'.repeat(100));
+ });
+
+ it('should not return currentActivity when task is completed', async () => {
+ // Create messages in thread
+ await serverDB.insert(messages).values({
+ userId,
+ role: 'assistant',
+ content: 'Final result',
+ agentId: testAgentId,
+ topicId: testTopicId,
+ threadId: testThreadId,
+ });
+
+ // Update thread to completed status
+ await serverDB
+ .update(threads)
+ .set({
+ status: ThreadStatus.Completed,
+ metadata: {
+ operationId: 'op-test-123',
+ completedAt: '2024-01-01T00:00:00Z',
+ },
+ })
+ .where(eq(threads.id, testThreadId));
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.getGroupSubAgentTaskStatus({
+ threadId: testThreadId,
+ });
+
+ expect(result.status).toBe('completed');
+ expect(result.currentActivity).toBeUndefined();
+ });
+
+ it('should not return currentActivity when no messages in thread', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.getGroupSubAgentTaskStatus({
+ threadId: testThreadId,
+ });
+
+ expect(result.status).toBe('processing');
+ expect(result.currentActivity).toBeUndefined();
+ });
+ });
+});
diff --git a/src/server/routers/lambda/__tests__/aiAgent.interruptTask.test.ts b/src/server/routers/lambda/__tests__/aiAgent.interruptTask.test.ts
new file mode 100644
index 00000000000..8dd9c7440c5
--- /dev/null
+++ b/src/server/routers/lambda/__tests__/aiAgent.interruptTask.test.ts
@@ -0,0 +1,297 @@
+// @vitest-environment node
+import { LobeChatDatabase } from '@lobechat/database';
+import { agents, chatGroups, sessions, threads, topics } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { ThreadStatus, ThreadType } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { aiAgentRouter } from '../aiAgent';
+import { cleanupTestUser, createTestUser } from './integration/setup';
+
+// Mock getServerDB to return our test database instance
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => testDB),
+}));
+
+// Mock AgentRuntimeService - interruptOperation method doesn't exist yet
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(() => ({
+ // No interruptOperation method - tests the graceful fallback
+ })),
+}));
+
+// Mock AiAgentService
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn().mockImplementation(() => ({})),
+}));
+
+// Mock AiChatService
+vi.mock('@/server/services/aiChat', () => ({
+ AiChatService: vi.fn().mockImplementation(() => ({})),
+}));
+
+describe('aiAgentRouter.interruptTask', () => {
+ let serverDB: LobeChatDatabase;
+ let userId: string;
+ let testAgentId: string;
+ let testGroupId: string;
+ let testTopicId: string;
+ let testThreadId: string;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+
+ // Create test agent
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({
+ userId,
+ title: 'Test SubAgent',
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant.',
+ })
+ .returning();
+ testAgentId = agent.id;
+
+ // Create test session
+ const [session] = await serverDB.insert(sessions).values({ userId, type: 'group' }).returning();
+
+ // Create test group
+ const [group] = await serverDB
+ .insert(chatGroups)
+ .values({
+ userId,
+ title: 'Test Group',
+ })
+ .returning();
+ testGroupId = group.id;
+
+ // Create test topic
+ const [topic] = await serverDB
+ .insert(topics)
+ .values({
+ userId,
+ title: 'Test Topic',
+ agentId: testAgentId,
+ sessionId: session.id,
+ groupId: testGroupId,
+ })
+ .returning();
+ testTopicId = topic.id;
+
+ // Create test thread with operationId in metadata
+ const [thread] = (await serverDB
+ .insert(threads)
+ .values({
+ userId,
+ agentId: testAgentId,
+ topicId: testTopicId,
+ groupId: testGroupId,
+ sourceMessageId: 'source-msg-1',
+ type: ThreadType.Isolation,
+ status: ThreadStatus.Processing,
+ metadata: { operationId: 'op-interrupt-test' },
+ })
+ .returning()) as any[];
+ testThreadId = thread.id;
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ vi.clearAllMocks();
+ });
+
+ const createTestContext = () => ({
+ userId,
+ jwtPayload: { userId },
+ });
+
+ describe('interrupt by threadId', () => {
+ it('should interrupt task and update thread status to cancel', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.interruptTask({
+ threadId: testThreadId,
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.threadId).toBe(testThreadId);
+ expect(result.operationId).toBe('op-interrupt-test');
+
+ // Verify thread status was updated
+ const [updatedThread] = await serverDB
+ .select()
+ .from(threads)
+ .where(eq(threads.id, testThreadId));
+
+ expect(updatedThread.status).toBe(ThreadStatus.Cancel);
+ expect(updatedThread.metadata?.completedAt).toBeDefined();
+ });
+
+ it('should throw NOT_FOUND when thread does not exist', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await expect(
+ caller.interruptTask({
+ threadId: 'non-existent-thread-id',
+ }),
+ ).rejects.toThrow('Thread not found');
+ });
+
+ it('should work even when thread has no operationId (only updates thread status)', async () => {
+ // Create a thread without operationId
+ const [threadWithoutOp] = (await serverDB
+ .insert(threads)
+ .values({
+ userId,
+ agentId: testAgentId,
+ topicId: testTopicId,
+ groupId: testGroupId,
+ sourceMessageId: 'source-msg-2',
+ type: ThreadType.Isolation,
+ status: ThreadStatus.Processing,
+ metadata: {},
+ })
+ .returning()) as any[];
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ // Should throw BAD_REQUEST because no operationId found
+ await expect(
+ caller.interruptTask({
+ threadId: threadWithoutOp.id,
+ }),
+ ).rejects.toThrow('Operation ID not found');
+ });
+ });
+
+ describe('interrupt by operationId', () => {
+ it('should interrupt task by operationId directly', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.interruptTask({
+ operationId: 'op-direct-interrupt',
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.operationId).toBe('op-direct-interrupt');
+ // threadId should be undefined when only operationId is provided
+ expect(result.threadId).toBeUndefined();
+ });
+
+ it('should use both threadId and operationId when both provided', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.interruptTask({
+ threadId: testThreadId,
+ operationId: 'op-override',
+ });
+
+ // operationId should take precedence
+ expect(result.operationId).toBe('op-override');
+ expect(result.threadId).toBe(testThreadId);
+
+ // Thread should still be updated
+ const [updatedThread] = await serverDB
+ .select()
+ .from(threads)
+ .where(eq(threads.id, testThreadId));
+
+ expect(updatedThread.status).toBe(ThreadStatus.Cancel);
+ });
+ });
+
+ describe('graceful handling without interruptOperation method', () => {
+ it('should succeed even when interruptOperation method is not available', async () => {
+ // The mock doesn't have interruptOperation method
+ // This tests the graceful fallback in the implementation
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.interruptTask({
+ threadId: testThreadId,
+ });
+
+ // Should still succeed and update thread status
+ expect(result.success).toBe(true);
+
+ const [updatedThread] = await serverDB
+ .select()
+ .from(threads)
+ .where(eq(threads.id, testThreadId));
+
+ expect(updatedThread.status).toBe(ThreadStatus.Cancel);
+ });
+ });
+
+ describe('thread status preservation', () => {
+ it('should preserve existing thread metadata when updating status', async () => {
+ // Update thread to have some existing metadata
+ await serverDB
+ .update(threads)
+ .set({
+ metadata: {
+ operationId: 'op-interrupt-test',
+ startedAt: '2024-01-01T00:00:00Z',
+ customField: 'preserved',
+ },
+ })
+ .where(eq(threads.id, testThreadId));
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await caller.interruptTask({
+ threadId: testThreadId,
+ });
+
+ const [updatedThread] = await serverDB
+ .select()
+ .from(threads)
+ .where(eq(threads.id, testThreadId));
+
+ // Existing metadata should be preserved
+ expect(updatedThread.metadata?.operationId).toBe('op-interrupt-test');
+ expect(updatedThread.metadata?.startedAt).toBe('2024-01-01T00:00:00Z');
+ expect(updatedThread.metadata?.customField).toBe('preserved');
+ // New metadata should be added
+ expect(updatedThread.metadata?.completedAt).toBeDefined();
+ });
+ });
+
+ describe('input validation', () => {
+ it('should require at least one of threadId or operationId', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await expect(caller.interruptTask({} as any)).rejects.toThrow();
+ });
+ });
+
+ describe('already cancelled thread', () => {
+ it('should handle re-interrupting an already cancelled thread', async () => {
+ // Update thread to cancelled status
+ await serverDB
+ .update(threads)
+ .set({
+ status: ThreadStatus.Cancel,
+ metadata: {
+ operationId: 'op-interrupt-test',
+ completedAt: '2024-01-01T00:00:00Z',
+ },
+ })
+ .where(eq(threads.id, testThreadId));
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ // Should still succeed (idempotent operation)
+ const result = await caller.interruptTask({
+ threadId: testThreadId,
+ });
+
+ expect(result.success).toBe(true);
+ });
+ });
+});
diff --git a/src/server/routers/lambda/__tests__/aiAgent.test.ts b/src/server/routers/lambda/__tests__/aiAgent.test.ts
new file mode 100644
index 00000000000..7cd6cdf31eb
--- /dev/null
+++ b/src/server/routers/lambda/__tests__/aiAgent.test.ts
@@ -0,0 +1,290 @@
+// @vitest-environment node
+import { LobeChatDatabase } from '@lobechat/database';
+import { agents, agentsToSessions, sessions, topics } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { aiAgentRouter } from '../aiAgent';
+import { cleanupTestUser, createTestUser } from './integration/setup';
+
+// Mock getServerDB to return our test database instance
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => testDB),
+}));
+
+// Mock AgentRuntimeService since we only want to test the router's business logic
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(() => ({
+ createOperation: vi.fn().mockResolvedValue({
+ success: true,
+ operationId: 'mock-operation-id',
+ autoStarted: true,
+ messageId: 'mock-message-id',
+ }),
+ })),
+}));
+
+// Mock serverMessagesEngine
+vi.mock('@/server/modules/Mecha', () => ({
+ createServerAgentToolsEngine: vi.fn(() => ({
+ generateToolsDetailed: vi.fn(() => ({ tools: [] })),
+ getEnabledPluginManifests: vi.fn(() => new Map()),
+ })),
+ serverMessagesEngine: vi.fn().mockResolvedValue([
+ { role: 'system', content: 'You are a helpful assistant.' },
+ { role: 'user', content: 'Hello' },
+ ]),
+}));
+
+// Mock AiChatService to avoid S3 dependency
+vi.mock('@/server/services/aiChat', () => ({
+ AiChatService: vi.fn().mockImplementation(() => ({
+ getMessagesAndTopics: vi.fn().mockResolvedValue({ messages: [], topics: [] }),
+ })),
+}));
+
+// Mock model-bank with dynamic import to preserve other exports
+vi.mock('model-bank', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('model-bank')>();
+ return {
+ ...actual,
+ LOBE_DEFAULT_MODEL_LIST: [
+ {
+ id: 'gpt-4o-mini',
+ providerId: 'openai',
+ abilities: { functionCall: true, vision: true, video: false },
+ },
+ ],
+ };
+});
+
+/**
+ * AI Agent Router 集成测试
+ *
+ * 测试目标:
+ * 1. 验证 execAgent 的业务逻辑
+ * 2. 确保 topic 创建逻辑正确
+ * 3. 验证与数据库的交互
+ */
+describe('AI Agent Router Integration Tests', () => {
+ let serverDB: LobeChatDatabase;
+ let userId: string;
+ let testAgentId: string;
+ let testSessionId: string;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+
+ // 创建测试 agent
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({
+ userId,
+ title: 'Test Agent',
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant.',
+ })
+ .returning();
+ testAgentId = agent.id;
+
+ // 创建测试 session
+ const [session] = await serverDB.insert(sessions).values({ userId, type: 'agent' }).returning();
+ testSessionId = session.id;
+
+ // 创建 agent 到 session 的映射关系
+ await serverDB.insert(agentsToSessions).values({
+ agentId: testAgentId,
+ sessionId: testSessionId,
+ userId,
+ });
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ vi.clearAllMocks();
+ });
+
+ const createTestContext = () => ({
+ userId,
+ jwtPayload: { userId },
+ });
+
+ describe('execAgent', () => {
+ it('should create a new topic when topicId is not provided', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.execAgent({
+ agentId: testAgentId,
+ prompt: 'Hello, how are you?',
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.operationId).toBeDefined();
+
+ // Verify a topic was created
+ const createdTopics = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.agentId, testAgentId));
+
+ expect(createdTopics).toHaveLength(1);
+ expect(createdTopics[0].title).toBe('Hello, how are you?');
+ });
+
+ it('should truncate long prompt for topic title', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+ const longPrompt =
+ 'This is a very long prompt that exceeds fifty characters and should be truncated';
+
+ await caller.execAgent({
+ agentId: testAgentId,
+ prompt: longPrompt,
+ });
+
+ const createdTopics = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.agentId, testAgentId));
+
+ expect(createdTopics).toHaveLength(1);
+ // Title should be first 50 characters + '...'
+ expect(createdTopics[0].title).toBe(longPrompt.slice(0, 50) + '...');
+ expect(createdTopics[0].title!.length).toBeLessThanOrEqual(53); // 50 + '...'
+ });
+
+ it('should reuse existing topic when topicId is provided', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ // Create an existing topic
+ const [existingTopic] = await serverDB
+ .insert(topics)
+ .values({
+ title: 'Existing Topic',
+ agentId: testAgentId,
+ sessionId: testSessionId,
+ userId,
+ })
+ .returning();
+
+ const result = await caller.execAgent({
+ agentId: testAgentId,
+ prompt: 'Follow up question',
+ appContext: {
+ topicId: existingTopic.id,
+ },
+ });
+
+ expect(result.success).toBe(true);
+
+ // Verify no new topic was created
+ const allTopics = await serverDB.select().from(topics).where(eq(topics.agentId, testAgentId));
+
+ expect(allTopics).toHaveLength(1);
+ expect(allTopics[0].id).toBe(existingTopic.id);
+ });
+
+ it('should throw error when agent does not exist', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ // When agent doesn't exist, getAgentConfigById returns null,
+ // which triggers NOT_FOUND error before topic creation
+ await expect(
+ caller.execAgent({
+ agentId: 'non-existent-agent-id',
+ prompt: 'Hello',
+ }),
+ ).rejects.toThrow();
+ });
+
+ it('should pass correct parameters to createOperation', async () => {
+ const { AgentRuntimeService } = await import('@/server/services/agentRuntime');
+ const mockCreateOperation = vi.fn().mockResolvedValue({
+ success: true,
+ operationId: 'test-op-id',
+ autoStarted: true,
+ messageId: 'test-msg-id',
+ });
+
+ vi.mocked(AgentRuntimeService).mockImplementation(
+ () =>
+ ({
+ createOperation: mockCreateOperation,
+ }) as any,
+ );
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await caller.execAgent({
+ agentId: testAgentId,
+ prompt: 'Test prompt',
+ autoStart: false,
+ });
+
+ expect(mockCreateOperation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentConfig: expect.objectContaining({
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ }),
+ appContext: expect.objectContaining({
+ agentId: testAgentId,
+ }),
+ autoStart: false,
+ modelRuntimeConfig: { model: 'gpt-4o-mini', provider: 'openai' },
+ userId,
+ }),
+ );
+ });
+
+ it('should handle autoStart=true by default', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.execAgent({
+ agentId: testAgentId,
+ prompt: 'Hello',
+ });
+
+ expect(result.autoStarted).toBe(true);
+ });
+
+ it('should include threadId in appContext when provided', async () => {
+ const { AgentRuntimeService } = await import('@/server/services/agentRuntime');
+ const mockCreateOperation = vi.fn().mockResolvedValue({
+ success: true,
+ operationId: 'test-op-id',
+ autoStarted: true,
+ messageId: 'test-msg-id',
+ });
+
+ vi.mocked(AgentRuntimeService).mockImplementation(
+ () =>
+ ({
+ createOperation: mockCreateOperation,
+ }) as any,
+ );
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await caller.execAgent({
+ agentId: testAgentId,
+ prompt: 'Test prompt',
+ appContext: {
+ threadId: 'test-thread-id',
+ },
+ });
+
+ expect(mockCreateOperation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ appContext: expect.objectContaining({
+ threadId: 'test-thread-id',
+ }),
+ }),
+ );
+ });
+ });
+});
diff --git a/src/server/routers/lambda/__tests__/aiChat.test.ts b/src/server/routers/lambda/__tests__/aiChat.test.ts
index c3ebb4104e1..b120ed99936 100644
--- a/src/server/routers/lambda/__tests__/aiChat.test.ts
+++ b/src/server/routers/lambda/__tests__/aiChat.test.ts
@@ -1,13 +1,18 @@
// @vitest-environment node
+import { ThreadType } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';
+import { AgentModel } from '@/database/models/agent';
import { MessageModel } from '@/database/models/message';
+import { ThreadModel } from '@/database/models/thread';
import { TopicModel } from '@/database/models/topic';
import { AiChatService } from '@/server/services/aiChat';
import { aiChatRouter } from '../aiChat';
+vi.mock('@/database/models/agent');
vi.mock('@/database/models/message');
+vi.mock('@/database/models/thread');
vi.mock('@/database/models/topic');
vi.mock('@/server/services/aiChat');
vi.mock('@/server/services/file', () => ({
@@ -29,9 +34,10 @@ describe('aiChatRouter', () => {
.fn()
.mockResolvedValueOnce({ id: 'm-user' })
.mockResolvedValueOnce({ id: 'm-assistant' });
- const mockGet = vi
- .fn()
- .mockResolvedValue({ messages: [{ id: 'm-user' }, { id: 'm-assistant' }], topics: [{}] });
+ const mockGet = vi.fn().mockResolvedValue({
+ messages: [{ id: 'm-user' }, { id: 'm-assistant' }],
+ topics: { items: [{}], total: 1 },
+ });
vi.mocked(TopicModel).mockImplementation(() => ({ create: mockCreateTopic }) as any);
vi.mocked(MessageModel).mockImplementation(() => ({ create: mockCreateMessage }) as any);
@@ -54,13 +60,16 @@ describe('aiChatRouter', () => {
title: 'T',
});
- expect(mockCreateMessage).toHaveBeenNthCalledWith(1, {
- content: 'hi',
- files: ['f1'],
- role: 'user',
- sessionId: 's1',
- topicId: 't1',
- });
+ expect(mockCreateMessage).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ content: 'hi',
+ files: ['f1'],
+ role: 'user',
+ sessionId: 's1',
+ topicId: 't1',
+ }),
+ );
expect(mockCreateMessage).toHaveBeenNthCalledWith(
2,
@@ -74,13 +83,16 @@ describe('aiChatRouter', () => {
}),
);
- expect(mockGet).toHaveBeenCalledWith({ includeTopic: true, sessionId: 's1', topicId: 't1' });
+ expect(mockGet).toHaveBeenCalledWith(
+ expect.objectContaining({ includeTopic: true, sessionId: 's1', topicId: 't1' }),
+ );
expect(res.assistantMessageId).toBe('m-assistant');
expect(res.userMessageId).toBe('m-user');
expect(res.isCreateNewTopic).toBe(true);
expect(res.topicId).toBe('t1');
expect(res.messages?.length).toBe(2);
- expect(res.topics?.length).toBe(1);
+ expect(res.topics?.items.length).toBe(1);
+ expect(res.topics?.total).toBe(1);
});
it('should reuse existing topic when topicId provided', async () => {
@@ -103,11 +115,13 @@ describe('aiChatRouter', () => {
} as any);
expect(mockCreateMessage).toHaveBeenCalled();
- expect(mockGet).toHaveBeenCalledWith({
- includeTopic: false,
- sessionId: 's1',
- topicId: 't-exist',
- });
+ expect(mockGet).toHaveBeenCalledWith(
+ expect.objectContaining({
+ includeTopic: false,
+ sessionId: 's1',
+ topicId: 't-exist',
+ }),
+ );
expect(res.isCreateNewTopic).toBe(false);
expect(res.topicId).toBe('t-exist');
});
@@ -132,24 +146,546 @@ describe('aiChatRouter', () => {
topicId: 't1',
} as any);
- expect(mockCreateMessage).toHaveBeenNthCalledWith(1, {
- content: 'hi',
- role: 'user',
+ expect(mockCreateMessage).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ content: 'hi',
+ role: 'user',
+ sessionId: 's1',
+ threadId: 'thread-123',
+ topicId: 't1',
+ }),
+ );
+
+ expect(mockCreateMessage).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ parentId: 'm-user',
+ role: 'assistant',
+ sessionId: 's1',
+ threadId: 'thread-123',
+ topicId: 't1',
+ }),
+ );
+ });
+
+ it('should create thread and use its id for messages when newThread is provided', async () => {
+ const mockCreateThread = vi.fn().mockResolvedValue({ id: 'thread-new' });
+ const mockCreateMessage = vi
+ .fn()
+ .mockResolvedValueOnce({ id: 'm-user' })
+ .mockResolvedValueOnce({ id: 'm-assistant' });
+ const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: undefined });
+
+ vi.mocked(ThreadModel).mockImplementation(() => ({ create: mockCreateThread }) as any);
+ vi.mocked(MessageModel).mockImplementation(() => ({ create: mockCreateMessage }) as any);
+ vi.mocked(AiChatService).mockImplementation(() => ({ getMessagesAndTopics: mockGet }) as any);
+
+ const caller = aiChatRouter.createCaller(mockCtx as any);
+
+ const res = await caller.sendMessageInServer({
+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
+ newThread: {
+ sourceMessageId: 'source-msg-123',
+ title: 'Thread Title',
+ type: ThreadType.Standalone,
+ },
+ newUserMessage: { content: 'hi' },
sessionId: 's1',
- threadId: 'thread-123',
topicId: 't1',
+ } as any);
+
+ // Verify thread was created with correct params
+ expect(mockCreateThread).toHaveBeenCalledWith({
+ parentThreadId: undefined,
+ sourceMessageId: 'source-msg-123',
+ title: 'Thread Title',
+ topicId: 't1',
+ type: ThreadType.Standalone,
});
+ // Verify messages use the newly created threadId
+ expect(mockCreateMessage).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ content: 'hi',
+ role: 'user',
+ sessionId: 's1',
+ threadId: 'thread-new',
+ topicId: 't1',
+ }),
+ );
+
expect(mockCreateMessage).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
parentId: 'm-user',
role: 'assistant',
sessionId: 's1',
- threadId: 'thread-123',
+ threadId: 'thread-new',
topicId: 't1',
}),
);
+
+ // Verify response includes createdThreadId
+ expect(res.createdThreadId).toBe('thread-new');
+ });
+
+ it('should create both topic and thread in same request', async () => {
+ const mockCreateTopic = vi.fn().mockResolvedValue({ id: 't-new' });
+ const mockCreateThread = vi.fn().mockResolvedValue({ id: 'thread-new' });
+ const mockCreateMessage = vi
+ .fn()
+ .mockResolvedValueOnce({ id: 'm-user' })
+ .mockResolvedValueOnce({ id: 'm-assistant' });
+ const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: [{ id: 't-new' }] });
+
+ vi.mocked(TopicModel).mockImplementation(() => ({ create: mockCreateTopic }) as any);
+ vi.mocked(ThreadModel).mockImplementation(() => ({ create: mockCreateThread }) as any);
+ vi.mocked(MessageModel).mockImplementation(() => ({ create: mockCreateMessage }) as any);
+ vi.mocked(AiChatService).mockImplementation(() => ({ getMessagesAndTopics: mockGet }) as any);
+
+ const caller = aiChatRouter.createCaller(mockCtx as any);
+
+ const res = await caller.sendMessageInServer({
+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
+ newThread: {
+ sourceMessageId: 'source-msg-123',
+ type: ThreadType.Continuation,
+ },
+ newTopic: { title: 'New Topic' },
+ newUserMessage: { content: 'hi' },
+ sessionId: 's1',
+ } as any);
+
+ // Topic created first
+ expect(mockCreateTopic).toHaveBeenCalledWith({
+ messages: undefined,
+ sessionId: 's1',
+ title: 'New Topic',
+ });
+
+ // Thread created with newly created topicId
+ expect(mockCreateThread).toHaveBeenCalledWith({
+ parentThreadId: undefined,
+ sourceMessageId: 'source-msg-123',
+ title: undefined,
+ topicId: 't-new',
+ type: ThreadType.Continuation,
+ });
+
+ // Messages use both new topicId and threadId
+ expect(mockCreateMessage).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ content: 'hi',
+ role: 'user',
+ sessionId: 's1',
+ threadId: 'thread-new',
+ topicId: 't-new',
+ }),
+ );
+
+ expect(res.isCreateNewTopic).toBe(true);
+ expect(res.topicId).toBe('t-new');
+ expect(res.createdThreadId).toBe('thread-new');
+ });
+
+ it('should not set createdThreadId when newThread is not provided', async () => {
+ const mockCreateMessage = vi
+ .fn()
+ .mockResolvedValueOnce({ id: 'm-user' })
+ .mockResolvedValueOnce({ id: 'm-assistant' });
+ const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: undefined });
+
+ vi.mocked(MessageModel).mockImplementation(() => ({ create: mockCreateMessage }) as any);
+ vi.mocked(AiChatService).mockImplementation(() => ({ getMessagesAndTopics: mockGet }) as any);
+
+ const caller = aiChatRouter.createCaller(mockCtx as any);
+
+ const res = await caller.sendMessageInServer({
+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
+ newUserMessage: { content: 'hi' },
+ sessionId: 's1',
+ topicId: 't1',
+ } as any);
+
+ expect(res.createdThreadId).toBeUndefined();
+ });
+
+ describe('groupId support', () => {
+ it('should pass groupId to topic creation when both newTopic and groupId exist', async () => {
+ const mockCreateTopic = vi.fn().mockResolvedValue({ id: 't1' });
+ const mockCreateMessage = vi
+ .fn()
+ .mockResolvedValueOnce({ id: 'm-user' })
+ .mockResolvedValueOnce({ id: 'm-assistant' });
+ const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: [{}] });
+
+ vi.mocked(TopicModel).mockImplementation(() => ({ create: mockCreateTopic }) as any);
+ vi.mocked(MessageModel).mockImplementation(() => ({ create: mockCreateMessage }) as any);
+ vi.mocked(AiChatService).mockImplementation(() => ({ getMessagesAndTopics: mockGet }) as any);
+
+ const caller = aiChatRouter.createCaller(mockCtx as any);
+
+ await caller.sendMessageInServer({
+ groupId: 'group-123',
+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
+ newTopic: { title: 'New Topic' },
+ newUserMessage: { content: 'hi' },
+ sessionId: 's1',
+ } as any);
+
+ // Verify groupId is passed to topic creation
+ expect(mockCreateTopic).toHaveBeenCalledWith(
+ expect.objectContaining({
+ groupId: 'group-123',
+ sessionId: 's1',
+ title: 'New Topic',
+ }),
+ );
+ });
+
+ it('should set groupId to null when newTopic exists but groupId is not provided', async () => {
+ const mockCreateTopic = vi.fn().mockResolvedValue({ id: 't1' });
+ const mockCreateMessage = vi
+ .fn()
+ .mockResolvedValueOnce({ id: 'm-user' })
+ .mockResolvedValueOnce({ id: 'm-assistant' });
+ const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: [{}] });
+
+ vi.mocked(TopicModel).mockImplementation(() => ({ create: mockCreateTopic }) as any);
+ vi.mocked(MessageModel).mockImplementation(() => ({ create: mockCreateMessage }) as any);
+ vi.mocked(AiChatService).mockImplementation(() => ({ getMessagesAndTopics: mockGet }) as any);
+
+ const caller = aiChatRouter.createCaller(mockCtx as any);
+
+ await caller.sendMessageInServer({
+ // no groupId provided
+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
+ newTopic: { title: 'New Topic' },
+ newUserMessage: { content: 'hi' },
+ sessionId: 's1',
+ } as any);
+
+ // Verify groupId is undefined (which will be treated as null in the database)
+ expect(mockCreateTopic).toHaveBeenCalledWith(
+ expect.objectContaining({
+ groupId: undefined,
+ sessionId: 's1',
+ title: 'New Topic',
+ }),
+ );
+ });
+
+ it('should pass groupId to both user and assistant message creation', async () => {
+ const mockCreateMessage = vi
+ .fn()
+ .mockResolvedValueOnce({ id: 'm-user' })
+ .mockResolvedValueOnce({ id: 'm-assistant' });
+ const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: undefined });
+
+ vi.mocked(MessageModel).mockImplementation(() => ({ create: mockCreateMessage }) as any);
+ vi.mocked(AiChatService).mockImplementation(() => ({ getMessagesAndTopics: mockGet }) as any);
+
+ const caller = aiChatRouter.createCaller(mockCtx as any);
+
+ await caller.sendMessageInServer({
+ agentId: 'supervisor-agent',
+ groupId: 'group-123',
+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
+ newUserMessage: { content: 'Analyze weather data' },
+ sessionId: 's1',
+ topicId: 't1',
+ } as any);
+
+ // Verify groupId is passed to user message
+ expect(mockCreateMessage).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ agentId: 'supervisor-agent',
+ content: 'Analyze weather data',
+ groupId: 'group-123',
+ role: 'user',
+ sessionId: 's1',
+ topicId: 't1',
+ }),
+ );
+
+ // Verify groupId is passed to assistant message
+ expect(mockCreateMessage).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ agentId: 'supervisor-agent',
+ groupId: 'group-123',
+ parentId: 'm-user',
+ role: 'assistant',
+ sessionId: 's1',
+ topicId: 't1',
+ }),
+ );
+ });
+
+ it('should pass groupId to getMessagesAndTopics for querying', async () => {
+ const mockCreateMessage = vi
+ .fn()
+ .mockResolvedValueOnce({ id: 'm-user' })
+ .mockResolvedValueOnce({ id: 'm-assistant' });
+ const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: undefined });
+
+ vi.mocked(MessageModel).mockImplementation(() => ({ create: mockCreateMessage }) as any);
+ vi.mocked(AiChatService).mockImplementation(() => ({ getMessagesAndTopics: mockGet }) as any);
+
+ const caller = aiChatRouter.createCaller(mockCtx as any);
+
+ await caller.sendMessageInServer({
+ agentId: 'supervisor-agent',
+ groupId: 'group-123',
+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
+ newUserMessage: { content: 'hi' },
+ sessionId: 's1',
+ topicId: 't1',
+ } as any);
+
+ // Verify groupId is passed to getMessagesAndTopics
+ expect(mockGet).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'supervisor-agent',
+ groupId: 'group-123',
+ sessionId: 's1',
+ topicId: 't1',
+ }),
+ );
+ });
+
+ it('should not set groupId when not provided (normal single-agent chat)', async () => {
+ const mockCreateMessage = vi
+ .fn()
+ .mockResolvedValueOnce({ id: 'm-user' })
+ .mockResolvedValueOnce({ id: 'm-assistant' });
+ const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: undefined });
+
+ vi.mocked(MessageModel).mockImplementation(() => ({ create: mockCreateMessage }) as any);
+ vi.mocked(AiChatService).mockImplementation(() => ({ getMessagesAndTopics: mockGet }) as any);
+
+ const caller = aiChatRouter.createCaller(mockCtx as any);
+
+ await caller.sendMessageInServer({
+ agentId: 'agent-1',
+ // no groupId - normal single-agent chat
+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
+ newUserMessage: { content: 'hi' },
+ sessionId: 's1',
+ topicId: 't1',
+ } as any);
+
+ // Verify groupId is undefined in user message
+ expect(mockCreateMessage).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ agentId: 'agent-1',
+ groupId: undefined,
+ role: 'user',
+ }),
+ );
+
+ // Verify groupId is undefined in assistant message
+ expect(mockCreateMessage).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ agentId: 'agent-1',
+ groupId: undefined,
+ role: 'assistant',
+ }),
+ );
+
+ // Verify groupId is undefined in getMessagesAndTopics
+ expect(mockGet).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ groupId: undefined,
+ }),
+ );
+ });
+ });
+
+ describe('agentId support', () => {
+ it('should pass agentId to messages when provided', async () => {
+ const mockCreateMessage = vi
+ .fn()
+ .mockResolvedValueOnce({ id: 'm-user' })
+ .mockResolvedValueOnce({ id: 'm-assistant' });
+ const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: undefined });
+
+ vi.mocked(MessageModel).mockImplementation(() => ({ create: mockCreateMessage }) as any);
+ vi.mocked(AiChatService).mockImplementation(() => ({ getMessagesAndTopics: mockGet }) as any);
+
+ const caller = aiChatRouter.createCaller(mockCtx as any);
+
+ await caller.sendMessageInServer({
+ agentId: 'agent-1',
+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
+ newUserMessage: { content: 'hi' },
+ sessionId: 's1',
+ topicId: 't1',
+ } as any);
+
+ // Verify agentId is passed to user message
+ expect(mockCreateMessage).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ agentId: 'agent-1',
+ content: 'hi',
+ role: 'user',
+ sessionId: 's1',
+ topicId: 't1',
+ }),
+ );
+
+ // Verify agentId is passed to assistant message
+ expect(mockCreateMessage).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ agentId: 'agent-1',
+ role: 'assistant',
+ sessionId: 's1',
+ topicId: 't1',
+ }),
+ );
+
+ // Verify agentId is passed to getMessagesAndTopics
+ expect(mockGet).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ sessionId: 's1',
+ topicId: 't1',
+ }),
+ );
+ });
+
+ it('should pass agentId to topic creation when provided', async () => {
+ const mockCreateTopic = vi.fn().mockResolvedValue({ id: 't1' });
+ const mockCreateMessage = vi
+ .fn()
+ .mockResolvedValueOnce({ id: 'm-user' })
+ .mockResolvedValueOnce({ id: 'm-assistant' });
+ const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: [{}] });
+ const mockTouchUpdatedAt = vi.fn().mockResolvedValue(undefined);
+
+ vi.mocked(TopicModel).mockImplementation(() => ({ create: mockCreateTopic }) as any);
+ vi.mocked(MessageModel).mockImplementation(() => ({ create: mockCreateMessage }) as any);
+ vi.mocked(AiChatService).mockImplementation(() => ({ getMessagesAndTopics: mockGet }) as any);
+ vi.mocked(AgentModel).mockImplementation(
+ () => ({ touchUpdatedAt: mockTouchUpdatedAt }) as any,
+ );
+
+ const caller = aiChatRouter.createCaller(mockCtx as any);
+
+ await caller.sendMessageInServer({
+ agentId: 'agent-1',
+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
+ newTopic: { title: 'New Topic' },
+ newUserMessage: { content: 'hi' },
+ sessionId: 's1',
+ } as any);
+
+ // Verify agentId is passed to topic creation
+ expect(mockCreateTopic).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ sessionId: 's1',
+ title: 'New Topic',
+ }),
+ );
+ });
+
+ it('should touch agent updatedAt when creating new topic with agentId', async () => {
+ const mockCreateTopic = vi.fn().mockResolvedValue({ id: 't1' });
+ const mockCreateMessage = vi
+ .fn()
+ .mockResolvedValueOnce({ id: 'm-user' })
+ .mockResolvedValueOnce({ id: 'm-assistant' });
+ const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: [{}] });
+ const mockTouchUpdatedAt = vi.fn().mockResolvedValue(undefined);
+
+ vi.mocked(TopicModel).mockImplementation(() => ({ create: mockCreateTopic }) as any);
+ vi.mocked(MessageModel).mockImplementation(() => ({ create: mockCreateMessage }) as any);
+ vi.mocked(AiChatService).mockImplementation(() => ({ getMessagesAndTopics: mockGet }) as any);
+ vi.mocked(AgentModel).mockImplementation(
+ () => ({ touchUpdatedAt: mockTouchUpdatedAt }) as any,
+ );
+
+ const caller = aiChatRouter.createCaller(mockCtx as any);
+
+ await caller.sendMessageInServer({
+ agentId: 'agent-1',
+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
+ newTopic: { title: 'New Topic' },
+ newUserMessage: { content: 'hi' },
+ sessionId: 's1',
+ } as any);
+
+ // Verify touchUpdatedAt was called with the agentId
+ expect(mockTouchUpdatedAt).toHaveBeenCalledWith('agent-1');
+ });
+
+ it('should not touch agent updatedAt when creating topic without agentId', async () => {
+ const mockCreateTopic = vi.fn().mockResolvedValue({ id: 't1' });
+ const mockCreateMessage = vi
+ .fn()
+ .mockResolvedValueOnce({ id: 'm-user' })
+ .mockResolvedValueOnce({ id: 'm-assistant' });
+ const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: [{}] });
+ const mockTouchUpdatedAt = vi.fn().mockResolvedValue(undefined);
+
+ vi.mocked(TopicModel).mockImplementation(() => ({ create: mockCreateTopic }) as any);
+ vi.mocked(MessageModel).mockImplementation(() => ({ create: mockCreateMessage }) as any);
+ vi.mocked(AiChatService).mockImplementation(() => ({ getMessagesAndTopics: mockGet }) as any);
+ vi.mocked(AgentModel).mockImplementation(
+ () => ({ touchUpdatedAt: mockTouchUpdatedAt }) as any,
+ );
+
+ const caller = aiChatRouter.createCaller(mockCtx as any);
+
+ await caller.sendMessageInServer({
+ // no agentId provided
+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
+ newTopic: { title: 'New Topic' },
+ newUserMessage: { content: 'hi' },
+ sessionId: 's1',
+ } as any);
+
+ // Verify touchUpdatedAt was NOT called
+ expect(mockTouchUpdatedAt).not.toHaveBeenCalled();
+ });
+
+ it('should not touch agent updatedAt when using existing topic', async () => {
+ const mockCreateMessage = vi
+ .fn()
+ .mockResolvedValueOnce({ id: 'm-user' })
+ .mockResolvedValueOnce({ id: 'm-assistant' });
+ const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: undefined });
+ const mockTouchUpdatedAt = vi.fn().mockResolvedValue(undefined);
+
+ vi.mocked(MessageModel).mockImplementation(() => ({ create: mockCreateMessage }) as any);
+ vi.mocked(AiChatService).mockImplementation(() => ({ getMessagesAndTopics: mockGet }) as any);
+ vi.mocked(AgentModel).mockImplementation(
+ () => ({ touchUpdatedAt: mockTouchUpdatedAt }) as any,
+ );
+
+ const caller = aiChatRouter.createCaller(mockCtx as any);
+
+ await caller.sendMessageInServer({
+ agentId: 'agent-1',
+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
+ newUserMessage: { content: 'hi' },
+ sessionId: 's1',
+ topicId: 't-exist', // existing topic, no newTopic
+ } as any);
+
+ // Verify touchUpdatedAt was NOT called since no new topic was created
+ expect(mockTouchUpdatedAt).not.toHaveBeenCalled();
+ });
});
describe('outputJSON', () => {
diff --git a/src/server/routers/lambda/__tests__/file.test.ts b/src/server/routers/lambda/__tests__/file.test.ts
index 6de93a83a3d..267308c454e 100644
--- a/src/server/routers/lambda/__tests__/file.test.ts
+++ b/src/server/routers/lambda/__tests__/file.test.ts
@@ -224,8 +224,9 @@ describe('fileRouter', () => {
const result = await caller.getKnowledgeItems({});
- expect(result).toHaveLength(2);
- expect(result[0]).toMatchObject({
+ expect(result.items).toHaveLength(2);
+ expect(result.hasMore).toBe(false);
+ expect(result.items[0]).toMatchObject({
chunkCount: 10,
chunkingStatus: AsyncTaskStatus.Success,
embeddingStatus: AsyncTaskStatus.Success,
@@ -234,7 +235,7 @@ describe('fileRouter', () => {
sourceType: 'file',
url: 'https://example.com/test-url',
});
- expect(result[1]).toMatchObject({
+ expect(result.items[1]).toMatchObject({
chunkCount: null,
chunkingError: null,
chunkingStatus: null,
diff --git a/src/server/routers/lambda/__tests__/integration/aiAgent.task.integration.test.ts b/src/server/routers/lambda/__tests__/integration/aiAgent.task.integration.test.ts
new file mode 100644
index 00000000000..5a6040c2a08
--- /dev/null
+++ b/src/server/routers/lambda/__tests__/integration/aiAgent.task.integration.test.ts
@@ -0,0 +1,737 @@
+// @vitest-environment node
+import { LobeChatDatabase } from '@lobechat/database';
+import { agents, chatGroups, sessions, threads, topics } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { ThreadStatus, ThreadType } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { aiAgentRouter } from '../../aiAgent';
+import { cleanupTestUser, createTestUser } from './setup';
+
+// Mock getServerDB to return our test database instance
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => testDB),
+}));
+
+// Mock AiAgentService - controls task execution behavior
+const mockExecGroupSubAgentTask = vi.fn();
+const mockInterruptTask = vi.fn();
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn().mockImplementation(() => ({
+ execGroupSubAgentTask: mockExecGroupSubAgentTask,
+ interruptTask: mockInterruptTask,
+ })),
+}));
+
+// Mock AgentRuntimeService - controls operation status
+const mockGetOperationStatus = vi.fn();
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(() => ({
+ getOperationStatus: mockGetOperationStatus,
+ })),
+}));
+
+// Mock AiChatService
+vi.mock('@/server/services/aiChat', () => ({
+ AiChatService: vi.fn().mockImplementation(() => ({})),
+}));
+
+describe('Agent Task Integration', () => {
+ let serverDB: LobeChatDatabase;
+ let userId: string;
+ let testAgentId: string;
+ let testAgent2Id: string;
+ let testGroupId: string;
+ let testTopicId: string;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+
+ // Create test agents
+ const [agent1] = await serverDB
+ .insert(agents)
+ .values({
+ userId,
+ title: 'Test SubAgent 1',
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant.',
+ })
+ .returning();
+ testAgentId = agent1.id;
+
+ const [agent2] = await serverDB
+ .insert(agents)
+ .values({
+ userId,
+ title: 'Test SubAgent 2',
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ systemRole: 'You are another helpful assistant.',
+ })
+ .returning();
+ testAgent2Id = agent2.id;
+
+ // Create test session
+ const [session] = await serverDB.insert(sessions).values({ userId, type: 'group' }).returning();
+
+ // Create test group
+ const [group] = await serverDB
+ .insert(chatGroups)
+ .values({
+ userId,
+ title: 'Test Group',
+ })
+ .returning();
+ testGroupId = group.id;
+
+ // Create test topic
+ const [topic] = await serverDB
+ .insert(topics)
+ .values({
+ userId,
+ title: 'Test Topic',
+ agentId: testAgentId,
+ sessionId: session.id,
+ groupId: testGroupId,
+ })
+ .returning();
+ testTopicId = topic.id;
+
+ // Reset mocks
+ mockExecGroupSubAgentTask.mockReset();
+ mockGetOperationStatus.mockReset();
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ vi.clearAllMocks();
+ });
+
+ const createTestContext = () => ({
+ userId,
+ jwtPayload: { userId },
+ });
+
+ describe('complete task execution lifecycle', () => {
+ it('should complete full task execution lifecycle', async () => {
+ const threadId = 'thread-lifecycle-test';
+ const operationId = 'op-lifecycle-test';
+
+ // Setup: Create thread in DB to simulate service behavior
+ await serverDB.insert(threads).values({
+ id: threadId,
+ userId,
+ agentId: testAgentId,
+ topicId: testTopicId,
+ groupId: testGroupId,
+ sourceMessageId: 'parent-msg-1',
+ type: ThreadType.Isolation,
+ status: ThreadStatus.Processing,
+ metadata: { operationId },
+ });
+
+ // 1. Mock service to return success
+ mockExecGroupSubAgentTask.mockResolvedValue({
+ assistantMessageId: 'assistant-msg-1',
+ operationId,
+ success: true,
+ threadId,
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ // Create task
+ const createResult = await caller.execGroupSubAgentTask({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ instruction: 'Test instruction',
+ parentMessageId: 'parent-msg-1',
+ topicId: testTopicId,
+ });
+
+ expect(createResult.success).toBe(true);
+ expect(createResult.threadId).toBe(threadId);
+ expect(createResult.operationId).toBe(operationId);
+
+ // 2. Query status (processing)
+ mockGetOperationStatus.mockResolvedValue({
+ currentState: {
+ status: 'running',
+ stepCount: 2,
+ },
+ isCompleted: false,
+ hasError: false,
+ metadata: {},
+ });
+
+ const processingStatus = await caller.getGroupSubAgentTaskStatus({
+ threadId,
+ });
+
+ expect(processingStatus.status).toBe('processing');
+ expect(processingStatus.stepCount).toBe(2);
+
+ // 3. Simulate task completion by updating Thread status
+ // Note: Status now comes from Thread table, Redis only supplements real-time info
+ await serverDB
+ .update(threads)
+ .set({
+ status: ThreadStatus.Completed,
+ metadata: {
+ operationId,
+ completedAt: '2024-01-01T12:00:00Z',
+ totalCost: 0.05,
+ totalTokens: 1500,
+ },
+ })
+ .where(eq(threads.id, threadId));
+
+ // Mock realtime status from Redis (optional, used for stepCount)
+ mockGetOperationStatus.mockResolvedValue({
+ currentState: {
+ status: 'done',
+ stepCount: 5,
+ cost: { total: 0.05 },
+ usage: { total_tokens: 1500 },
+ },
+ isCompleted: true,
+ hasError: false,
+ metadata: { lastActiveAt: '2024-01-01T12:00:00Z' },
+ });
+
+ const completedStatus = await caller.getGroupSubAgentTaskStatus({
+ threadId,
+ });
+
+ expect(completedStatus.status).toBe('completed');
+ expect(completedStatus.completedAt).toBe('2024-01-01T12:00:00Z');
+
+ // Verify taskDetail contains thread info
+ expect(completedStatus.taskDetail).toBeDefined();
+ expect(completedStatus.taskDetail?.threadId).toBe(threadId);
+ expect(completedStatus.taskDetail?.status).toBe(ThreadStatus.Completed);
+ expect(completedStatus.taskDetail?.totalCost).toBe(0.05);
+ expect(completedStatus.taskDetail?.totalTokens).toBe(1500);
+
+ // 4. Verify Thread status in DB
+ const [thread] = await serverDB.select().from(threads).where(eq(threads.id, threadId));
+
+ expect(thread.status).toBe(ThreadStatus.Completed);
+ expect(thread.metadata?.completedAt).toBeDefined();
+ });
+ });
+
+ describe('task interrupt flow', () => {
+ it('should interrupt running task', async () => {
+ const threadId = 'thread-interrupt-test';
+ const operationId = 'op-interrupt-test';
+
+ // Setup: Create thread in DB
+ await serverDB.insert(threads).values({
+ id: threadId,
+ userId,
+ agentId: testAgentId,
+ topicId: testTopicId,
+ groupId: testGroupId,
+ sourceMessageId: 'parent-msg-2',
+ type: ThreadType.Isolation,
+ status: ThreadStatus.Processing,
+ metadata: { operationId },
+ });
+
+ // 1. Create task
+ mockExecGroupSubAgentTask.mockResolvedValue({
+ assistantMessageId: 'assistant-msg-2',
+ operationId,
+ success: true,
+ threadId,
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const createResult = await caller.execGroupSubAgentTask({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ instruction: 'Long running task',
+ parentMessageId: 'parent-msg-2',
+ topicId: testTopicId,
+ });
+
+ expect(createResult.success).toBe(true);
+
+ // 2. Mock interruptTask and call it
+ mockInterruptTask.mockResolvedValue({
+ success: true,
+ threadId,
+ });
+
+ const interruptResult = await caller.interruptTask({
+ threadId,
+ });
+
+ expect(interruptResult.success).toBe(true);
+ expect(interruptResult.threadId).toBe(threadId);
+
+ // 3. Update thread status to Cancel (since status comes from Thread table now)
+ await serverDB
+ .update(threads)
+ .set({ status: ThreadStatus.Cancel })
+ .where(eq(threads.id, threadId));
+
+ const statusResult = await caller.getGroupSubAgentTaskStatus({
+ threadId,
+ });
+
+ expect(statusResult.status).toBe('cancel');
+
+ // 4. Verify Thread status
+ const [thread] = await serverDB.select().from(threads).where(eq(threads.id, threadId));
+
+ expect(thread.status).toBe(ThreadStatus.Cancel);
+ });
+ });
+
+ describe('task failure handling', () => {
+ it('should handle task failure during creation', async () => {
+ const threadId = 'thread-fail-test';
+ const operationId = 'op-fail-test';
+
+ // Setup: Create thread in DB with failed status
+ await serverDB.insert(threads).values({
+ id: threadId,
+ userId,
+ agentId: testAgentId,
+ topicId: testTopicId,
+ groupId: testGroupId,
+ sourceMessageId: 'parent-msg-3',
+ type: ThreadType.Isolation,
+ status: ThreadStatus.Failed,
+ metadata: { operationId, error: 'Agent execution failed' },
+ });
+
+ // Mock service to return failure
+ mockExecGroupSubAgentTask.mockResolvedValue({
+ assistantMessageId: 'assistant-msg-3',
+ error: 'Agent execution failed',
+ operationId,
+ success: false,
+ threadId,
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const createResult = await caller.execGroupSubAgentTask({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ instruction: 'Failing task',
+ parentMessageId: 'parent-msg-3',
+ topicId: testTopicId,
+ });
+
+ expect(createResult.success).toBe(false);
+ expect(createResult.error).toBe('Agent execution failed');
+ expect(createResult.threadId).toBe(threadId);
+
+ // Verify Thread status
+ const [thread] = await serverDB.select().from(threads).where(eq(threads.id, threadId));
+
+ expect(thread.status).toBe(ThreadStatus.Failed);
+ expect(thread.metadata?.error).toBe('Agent execution failed');
+ });
+
+ it('should handle task failure during execution', async () => {
+ const threadId = 'thread-exec-fail-test';
+ const operationId = 'op-exec-fail-test';
+
+ // Setup: Create thread in DB with Failed status and error in metadata
+ // Note: Status now comes from Thread table, Redis only supplements real-time info
+ await serverDB.insert(threads).values({
+ id: threadId,
+ userId,
+ agentId: testAgentId,
+ topicId: testTopicId,
+ groupId: testGroupId,
+ sourceMessageId: 'parent-msg-4',
+ type: ThreadType.Isolation,
+ status: ThreadStatus.Failed,
+ metadata: { operationId, error: 'Tool execution timeout' },
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const statusResult = await caller.getGroupSubAgentTaskStatus({
+ threadId,
+ });
+
+ expect(statusResult.status).toBe('failed');
+ expect(statusResult.error).toBe('Tool execution timeout');
+
+ // Verify taskDetail contains thread info
+ expect(statusResult.taskDetail).toBeDefined();
+ expect(statusResult.taskDetail?.threadId).toBe(threadId);
+ expect(statusResult.taskDetail?.status).toBe(ThreadStatus.Failed);
+ });
+ });
+
+ describe('concurrent task execution', () => {
+ it('should handle concurrent task execution', async () => {
+ const threadId1 = 'thread-concurrent-1';
+ const threadId2 = 'thread-concurrent-2';
+ const operationId1 = 'op-concurrent-1';
+ const operationId2 = 'op-concurrent-2';
+
+ // Setup: Create threads in DB
+ await serverDB.insert(threads).values([
+ {
+ id: threadId1,
+ userId,
+ agentId: testAgentId,
+ topicId: testTopicId,
+ groupId: testGroupId,
+ sourceMessageId: 'parent-msg-5',
+ type: ThreadType.Isolation,
+ status: ThreadStatus.Processing,
+ metadata: { operationId: operationId1 },
+ },
+ {
+ id: threadId2,
+ userId,
+ agentId: testAgent2Id,
+ topicId: testTopicId,
+ groupId: testGroupId,
+ sourceMessageId: 'parent-msg-5',
+ type: ThreadType.Isolation,
+ status: ThreadStatus.Processing,
+ metadata: { operationId: operationId2 },
+ },
+ ]);
+
+ // Mock service to return different results for each call
+ let callCount = 0;
+ mockExecGroupSubAgentTask.mockImplementation(() => {
+ callCount++;
+ if (callCount === 1) {
+ return Promise.resolve({
+ assistantMessageId: 'assistant-msg-5',
+ operationId: operationId1,
+ success: true,
+ threadId: threadId1,
+ });
+ }
+ return Promise.resolve({
+ assistantMessageId: 'assistant-msg-6',
+ operationId: operationId2,
+ success: true,
+ threadId: threadId2,
+ });
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ // Execute tasks concurrently
+ const [task1, task2] = await Promise.all([
+ caller.execGroupSubAgentTask({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ instruction: 'Task 1',
+ parentMessageId: 'parent-msg-5',
+ topicId: testTopicId,
+ }),
+ caller.execGroupSubAgentTask({
+ agentId: testAgent2Id,
+ groupId: testGroupId,
+ instruction: 'Task 2',
+ parentMessageId: 'parent-msg-5',
+ topicId: testTopicId,
+ }),
+ ]);
+
+ // Verify both tasks created successfully
+ expect(task1.success).toBe(true);
+ expect(task2.success).toBe(true);
+ expect(task1.threadId).not.toBe(task2.threadId);
+ expect(task1.operationId).not.toBe(task2.operationId);
+
+ // Verify threads exist in DB
+ const threadsInDB = await serverDB
+ .select()
+ .from(threads)
+ .where(eq(threads.topicId, testTopicId));
+
+ expect(threadsInDB.length).toBe(2);
+ });
+ });
+
+ describe('query task by threadId', () => {
+ it('should query task status by threadId', async () => {
+ const threadId = 'thread-query-test';
+ const operationId = 'op-query-test';
+
+ // Setup: Create thread in DB
+ await serverDB.insert(threads).values({
+ id: threadId,
+ userId,
+ agentId: testAgentId,
+ topicId: testTopicId,
+ groupId: testGroupId,
+ sourceMessageId: 'parent-msg-6',
+ type: ThreadType.Isolation,
+ status: ThreadStatus.Processing,
+ metadata: { operationId },
+ });
+
+ mockGetOperationStatus.mockResolvedValue({
+ currentState: {
+ status: 'running',
+ stepCount: 2,
+ },
+ isCompleted: false,
+ hasError: false,
+ metadata: {},
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ // Query by threadId
+ const status = await caller.getGroupSubAgentTaskStatus({
+ threadId,
+ });
+
+ expect(status.status).toBe('processing');
+ expect(status.stepCount).toBe(2);
+ });
+ });
+
+ describe('step lifecycle callbacks - thread metadata updates', () => {
+ it('should have complete metadata after task completion', async () => {
+ const threadId = 'thread-metadata-test';
+ const operationId = 'op-metadata-test';
+ const startedAt = '2024-01-01T10:00:00.000Z';
+ const completedAt = '2024-01-01T10:05:00.000Z';
+
+ // Setup: Create thread with complete metadata (simulating what callbacks would set)
+ await serverDB.insert(threads).values({
+ id: threadId,
+ userId,
+ agentId: testAgentId,
+ topicId: testTopicId,
+ groupId: testGroupId,
+ sourceMessageId: 'parent-msg-metadata',
+ type: ThreadType.Isolation,
+ status: ThreadStatus.Completed,
+ metadata: {
+ completedAt,
+ duration: 300000, // 5 minutes
+ operationId,
+ startedAt,
+ totalCost: 0.0123,
+ totalMessages: 5,
+ totalTokens: 2500,
+ totalToolCalls: 3,
+ },
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ // Query task status
+ const status = await caller.getGroupSubAgentTaskStatus({ threadId });
+
+ // Verify all metadata fields are accessible
+ expect(status.status).toBe('completed');
+ expect(status.completedAt).toBe(completedAt);
+
+ // Verify taskDetail contains all callback-populated metadata
+ expect(status.taskDetail).toBeDefined();
+ expect(status.taskDetail?.threadId).toBe(threadId);
+ expect(status.taskDetail?.status).toBe(ThreadStatus.Completed);
+ expect(status.taskDetail?.startedAt).toBe(startedAt);
+ expect(status.taskDetail?.completedAt).toBe(completedAt);
+ expect(status.taskDetail?.duration).toBe(300000);
+ expect(status.taskDetail?.totalCost).toBe(0.0123);
+ expect(status.taskDetail?.totalMessages).toBe(5);
+ expect(status.taskDetail?.totalTokens).toBe(2500);
+ expect(status.taskDetail?.totalToolCalls).toBe(3);
+ });
+
+ it('should have partial metadata during task processing', async () => {
+ const threadId = 'thread-processing-metadata';
+ const operationId = 'op-processing-metadata';
+ const startedAt = new Date().toISOString();
+
+ // Setup: Create thread with partial metadata (during processing, onAfterStep updates)
+ await serverDB.insert(threads).values({
+ id: threadId,
+ userId,
+ agentId: testAgentId,
+ topicId: testTopicId,
+ groupId: testGroupId,
+ sourceMessageId: 'parent-msg-processing',
+ type: ThreadType.Isolation,
+ status: ThreadStatus.Processing,
+ metadata: {
+ operationId,
+ startedAt,
+ totalMessages: 3,
+ totalTokens: 1200,
+ totalToolCalls: 1,
+ },
+ });
+
+ // Mock realtime status from operation
+ mockGetOperationStatus.mockResolvedValue({
+ currentState: {
+ status: 'running',
+ stepCount: 3,
+ },
+ isCompleted: false,
+ hasError: false,
+ metadata: {},
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const status = await caller.getGroupSubAgentTaskStatus({ threadId });
+
+ // Should be processing with partial metadata
+ expect(status.status).toBe('processing');
+ expect(status.taskDetail?.startedAt).toBe(startedAt);
+ expect(status.taskDetail?.totalMessages).toBe(3);
+ expect(status.taskDetail?.totalTokens).toBe(1200);
+ expect(status.taskDetail?.totalToolCalls).toBe(1);
+ // completedAt and duration should not be set yet
+ expect(status.taskDetail?.completedAt).toBeUndefined();
+ expect(status.taskDetail?.duration).toBeUndefined();
+ });
+
+ it('should have error info in metadata when task fails', async () => {
+ const threadId = 'thread-error-metadata';
+ const operationId = 'op-error-metadata';
+ const startedAt = '2024-01-01T10:00:00.000Z';
+ const completedAt = '2024-01-01T10:01:30.000Z';
+ const errorMessage = 'Tool execution failed: API rate limit exceeded';
+
+ // Setup: Create thread with error metadata (simulating onComplete with error)
+ await serverDB.insert(threads).values({
+ id: threadId,
+ userId,
+ agentId: testAgentId,
+ topicId: testTopicId,
+ groupId: testGroupId,
+ sourceMessageId: 'parent-msg-error',
+ type: ThreadType.Isolation,
+ status: ThreadStatus.Failed,
+ metadata: {
+ completedAt,
+ duration: 90000, // 1.5 minutes
+ error: errorMessage,
+ operationId,
+ startedAt,
+ totalCost: 0.005,
+ totalMessages: 2,
+ totalTokens: 800,
+ totalToolCalls: 1,
+ },
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const status = await caller.getGroupSubAgentTaskStatus({ threadId });
+
+ // Should be failed with error in metadata
+ expect(status.status).toBe('failed');
+ expect(status.error).toBe(errorMessage);
+ expect(status.taskDetail?.error).toBe(errorMessage);
+ expect(status.taskDetail?.duration).toBe(90000);
+ expect(status.taskDetail?.totalToolCalls).toBe(1);
+ });
+
+ it('should have correct status when task is interrupted', async () => {
+ const threadId = 'thread-interrupted-metadata';
+ const operationId = 'op-interrupted-metadata';
+ const startedAt = '2024-01-01T10:00:00.000Z';
+ const completedAt = '2024-01-01T10:02:00.000Z';
+
+ // Setup: Create thread with interrupted status (simulating onComplete with 'interrupted' reason)
+ await serverDB.insert(threads).values({
+ id: threadId,
+ userId,
+ agentId: testAgentId,
+ topicId: testTopicId,
+ groupId: testGroupId,
+ sourceMessageId: 'parent-msg-interrupted',
+ type: ThreadType.Isolation,
+ status: ThreadStatus.Cancel,
+ metadata: {
+ completedAt,
+ duration: 120000, // 2 minutes
+ operationId,
+ startedAt,
+ totalCost: 0.008,
+ totalMessages: 3,
+ totalTokens: 1000,
+ totalToolCalls: 2,
+ },
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const status = await caller.getGroupSubAgentTaskStatus({ threadId });
+
+ expect(status.status).toBe('cancel');
+ expect(status.taskDetail?.status).toBe(ThreadStatus.Cancel);
+ expect(status.taskDetail?.completedAt).toBe(completedAt);
+ expect(status.taskDetail?.duration).toBe(120000);
+ });
+
+ it('should have correct status when waiting for human intervention', async () => {
+ const threadId = 'thread-inreview-metadata';
+ const operationId = 'op-inreview-metadata';
+ const startedAt = '2024-01-01T10:00:00.000Z';
+
+ // Setup: Create thread with InReview status (simulating onComplete with 'waiting_for_human' reason)
+ await serverDB.insert(threads).values({
+ id: threadId,
+ userId,
+ agentId: testAgentId,
+ topicId: testTopicId,
+ groupId: testGroupId,
+ sourceMessageId: 'parent-msg-inreview',
+ type: ThreadType.Isolation,
+ status: ThreadStatus.InReview,
+ metadata: {
+ operationId,
+ startedAt,
+ totalMessages: 4,
+ totalTokens: 1500,
+ totalToolCalls: 2,
+ },
+ });
+
+ // Mock realtime status showing waiting for human
+ mockGetOperationStatus.mockResolvedValue({
+ currentState: {
+ status: 'waiting_for_human',
+ stepCount: 4,
+ pendingToolsCalling: [{ name: 'dangerous_tool' }],
+ },
+ isCompleted: false,
+ hasError: false,
+ needsHumanInput: true,
+ metadata: {},
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const status = await caller.getGroupSubAgentTaskStatus({ threadId });
+
+ // Status should reflect InReview from Thread table
+ expect(status.taskDetail?.status).toBe(ThreadStatus.InReview);
+ expect(status.taskDetail?.totalToolCalls).toBe(2);
+ });
+ });
+});
diff --git a/src/server/routers/lambda/__tests__/integration/aiAgent/execAgent.integration.test.ts b/src/server/routers/lambda/__tests__/integration/aiAgent/execAgent.integration.test.ts
new file mode 100644
index 00000000000..4d179d2d7dd
--- /dev/null
+++ b/src/server/routers/lambda/__tests__/integration/aiAgent/execAgent.integration.test.ts
@@ -0,0 +1,683 @@
+// @vitest-environment node
+/**
+ * Integration tests for execAgent router
+ *
+ * Note: AgentStateManager and StreamEventManager will automatically use
+ * InMemory implementations when Redis is not available (test environment).
+ */
+import { LobeChatDatabase } from '@lobechat/database';
+import { agents, messages, topics } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { and, eq } from 'drizzle-orm';
+import OpenAI from 'openai';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { inMemoryAgentStateManager } from '@/server/modules/AgentRuntime/InMemoryAgentStateManager';
+import { inMemoryStreamEventManager } from '@/server/modules/AgentRuntime/InMemoryStreamEventManager';
+import { ToolExecutionService } from '@/server/services/toolExecution';
+
+import { aiAgentRouter } from '../../../aiAgent';
+import { cleanupTestUser, createTestUser } from '../setup';
+import {
+ createMockResponsesAPIStream,
+ createMockResponsesStream,
+ waitForOperationComplete,
+} from './helpers';
+
+// Set fake API key for testing to bypass OpenAI SDK validation
+process.env.OPENAI_API_KEY = 'sk-test-fake-api-key-for-testing';
+
+// Mock getServerDB to return our test database instance
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => testDB),
+}));
+
+// Mock FileService to avoid S3 environment variable requirements
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(() => ({
+ getFullFileUrl: vi.fn().mockImplementation((path: string) => (path ? `/files${path}` : null)),
+ })),
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+let mockResponsesCreate: any;
+
+let serverDB: LobeChatDatabase;
+let userId: string;
+let testAgentId: string;
+
+const createTestContext = () => ({
+ jwtPayload: { userId },
+ userId,
+});
+
+beforeEach(async () => {
+ // Setup test database
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+
+ // Create test agent with gpt-5-pro (uses Responses API)
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({
+ model: 'gpt-5-pro',
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant.',
+ title: 'Test Assistant',
+ userId,
+ })
+ .returning();
+ testAgentId = agent.id;
+
+ // Setup spyOn for OpenAI Responses API prototype
+ mockResponsesCreate = vi.spyOn(OpenAI.Responses.prototype, 'create');
+});
+
+afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ vi.clearAllMocks();
+ vi.restoreAllMocks();
+
+ // Clear singleton instances for next test
+ inMemoryAgentStateManager.clear();
+ inMemoryStreamEventManager.clear();
+});
+
+describe('execAgent', () => {
+ describe('Basic execAgent Flow', () => {
+ it('should create operation successfully with prompt', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+ const prompt = "What's the weather of Hangzhou?";
+
+ const result = await caller.execAgent({ agentId: testAgentId, prompt });
+
+ expect(result.success).toBe(true);
+ expect(result.operationId).toBeDefined();
+ expect(result.operationId).toMatch(/^op_\d+_agt_.+_tpc_.+_\w+$/);
+
+ // Verify topic was created
+ const createdTopics = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.agentId, testAgentId));
+ expect(createdTopics).toHaveLength(1);
+ expect(createdTopics[0].title).toBe(prompt);
+
+ // Verify user message and assistant message placeholder were created
+ const createdMessages = await serverDB
+ .select()
+ .from(messages)
+ .where(and(eq(messages.agentId, testAgentId), eq(messages.topicId, createdTopics[0].id)));
+
+ expect(createdMessages).toHaveLength(2);
+
+ const userMessage = createdMessages.find((m) => m.role === 'user');
+ expect(userMessage).toBeDefined();
+ expect(userMessage?.content).toBe(prompt);
+
+ const assistantMessage = createdMessages.find((m) => m.role === 'assistant');
+ expect(assistantMessage).toBeDefined();
+ expect(assistantMessage?.parentId).toBe(userMessage?.id);
+ });
+
+ it('should create a new topic when topicId is not provided', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.execAgent({
+ agentId: testAgentId,
+ prompt: 'Hello, how are you?',
+ });
+
+ expect(result.success).toBe(true);
+
+ const createdTopics = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.agentId, testAgentId));
+
+ expect(createdTopics).toHaveLength(1);
+ expect(createdTopics[0].title).toBe('Hello, how are you?');
+ });
+
+ it('should truncate long prompt for topic title', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+ const longPrompt =
+ 'This is a very long prompt that exceeds fifty characters and should be truncated for the topic title';
+
+ await caller.execAgent({
+ agentId: testAgentId,
+ prompt: longPrompt,
+ });
+
+ const createdTopics = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.agentId, testAgentId));
+
+ expect(createdTopics).toHaveLength(1);
+ expect(createdTopics[0].title).toBe(longPrompt.slice(0, 50) + '...');
+ });
+
+ it('should reuse existing topic when topicId is provided', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const [existingTopic] = await serverDB
+ .insert(topics)
+ .values({ agentId: testAgentId, title: 'Existing Topic', userId })
+ .returning();
+
+ const result = await caller.execAgent({
+ agentId: testAgentId,
+ appContext: { topicId: existingTopic.id },
+ prompt: 'Follow up question',
+ });
+
+ expect(result.success).toBe(true);
+
+ const allTopics = await serverDB.select().from(topics).where(eq(topics.agentId, testAgentId));
+ expect(allTopics).toHaveLength(1);
+ expect(allTopics[0].id).toBe(existingTopic.id);
+ });
+ });
+
+ describe('Error Handling', () => {
+ it('should throw error when agent does not exist', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await expect(
+ caller.execAgent({
+ agentId: 'non-existent-agent-id',
+ prompt: 'Hello',
+ }),
+ ).rejects.toThrow();
+ });
+ });
+
+ describe('autoStart behavior', () => {
+ it('should have autoStarted=true by default', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.execAgent({
+ agentId: testAgentId,
+ prompt: 'Hello',
+ });
+
+ expect(result.autoStarted).toBe(true);
+ });
+
+ it('should respect autoStart=false', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.execAgent({
+ agentId: testAgentId,
+ autoStart: false,
+ prompt: 'Hello',
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.autoStarted).toBe(false);
+ });
+ });
+
+ describe('appContext handling', () => {
+ it('should include threadId in operation when provided', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.execAgent({
+ agentId: testAgentId,
+ appContext: {
+ threadId: 'test-thread-id',
+ },
+ prompt: 'Test prompt',
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.operationId).toBeDefined();
+ });
+ });
+
+ describe('Full LLM Execution with Local Async Mode', () => {
+ it('should execute LLM call using state.modelRuntimeConfig fallback', async () => {
+ const responseContent = 'The weather in Hangzhou is sunny today.';
+ mockResponsesCreate.mockResolvedValue(createMockResponsesAPIStream(responseContent) as any);
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ // Use autoStart: true (default) to trigger local async execution
+ const createResult = await caller.execAgent({
+ agentId: testAgentId,
+ prompt: 'What is the weather in Hangzhou?',
+ });
+
+ expect(createResult.success).toBe(true);
+ expect(createResult.operationId).toBeDefined();
+ expect(createResult.autoStarted).toBe(true);
+
+ // Wait for async execution to complete
+ const finalState = await waitForOperationComplete(
+ inMemoryAgentStateManager,
+ createResult.operationId,
+ );
+
+ expect(finalState.status).toBe('done');
+ expect(mockResponsesCreate).toHaveBeenCalled();
+
+ const callArgs = mockResponsesCreate.mock.calls[0][0] as { model: string };
+ expect(callArgs.model).toBe('gpt-5-pro');
+ });
+
+ it('should save assistant response content to database after execution', async () => {
+ const responseContent = 'I am doing great, thank you for asking!';
+ mockResponsesCreate.mockResolvedValue(createMockResponsesAPIStream(responseContent) as any);
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const createResult = await caller.execAgent({
+ agentId: testAgentId,
+ prompt: 'How are you?',
+ });
+
+ // Wait for async execution to complete
+ const finalState = await waitForOperationComplete(
+ inMemoryAgentStateManager,
+ createResult.operationId,
+ );
+
+ expect(finalState.status).toBe('done');
+
+ const assistantMessage = finalState.messages.find(
+ (m: { role: string }) => m.role === 'assistant',
+ );
+ expect(assistantMessage).toBeDefined();
+ expect(assistantMessage.content).toBe(responseContent);
+
+ const allMessages = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.agentId, testAgentId));
+
+ const dbAssistantMessageWithContent = allMessages.find((m) => m.role === 'assistant');
+ expect(dbAssistantMessageWithContent).toBeDefined();
+ expect(dbAssistantMessageWithContent?.content).toBe(responseContent);
+ });
+
+ it('should verify OpenAI responses.create was called with correct model', async () => {
+ const responseContent = 'Test response for model verification';
+ mockResponsesCreate.mockResolvedValue(createMockResponsesAPIStream(responseContent) as any);
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const createResult = await caller.execAgent({
+ agentId: testAgentId,
+ prompt: 'Test model verification',
+ });
+
+ // Wait for async execution to complete
+ const finalState = await waitForOperationComplete(
+ inMemoryAgentStateManager,
+ createResult.operationId,
+ );
+ expect(finalState.status).toBe('done');
+
+ expect(mockResponsesCreate).toHaveBeenCalled();
+ const callArgs = mockResponsesCreate.mock.calls[0][0] as {
+ input: unknown[];
+ model: string;
+ };
+ expect(callArgs.model).toBe('gpt-5-pro');
+ expect(callArgs.input).toBeDefined();
+ expect(Array.isArray(callArgs.input)).toBe(true);
+ });
+
+ it('should set correct parentId on assistant message (user message -> assistant message)', async () => {
+ const responseContent = 'Response for parentId verification';
+ mockResponsesCreate.mockResolvedValue(createMockResponsesAPIStream(responseContent) as any);
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const createResult = await caller.execAgent({
+ agentId: testAgentId,
+ prompt: 'Test parentId chain',
+ });
+
+ // Wait for async execution to complete
+ const finalState = await waitForOperationComplete(
+ inMemoryAgentStateManager,
+ createResult.operationId,
+ );
+ expect(finalState.status).toBe('done');
+
+ const allMessages = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.agentId, testAgentId));
+
+ const userMessage = allMessages.find((m) => m.role === 'user');
+ const assistantMessage = allMessages.find((m) => m.role === 'assistant');
+
+ expect(userMessage).toBeDefined();
+ expect(assistantMessage).toBeDefined();
+ expect(assistantMessage?.parentId).toBe(userMessage?.id);
+ });
+ });
+
+ describe('Tool Calling Flow with lobe-web-browsing', () => {
+ let testAgentWithToolsId: string;
+
+ const createMockResponsesAPIStreamWithTools = () => {
+ const responseId = `resp_${Date.now()}`;
+ const msgItemId = `msg_${Date.now()}`;
+ const toolCallId = `call_${Date.now()}`;
+
+ const chunks = [
+ {
+ type: 'response.created',
+ response: {
+ id: responseId,
+ object: 'response',
+ created_at: Math.floor(Date.now() / 1000),
+ status: 'in_progress',
+ model: 'gpt-5-pro',
+ output: [],
+ },
+ },
+ {
+ type: 'response.output_item.added',
+ output_index: 0,
+ item: {
+ id: msgItemId,
+ type: 'message',
+ status: 'in_progress',
+ content: [],
+ role: 'assistant',
+ },
+ },
+ {
+ type: 'response.output_text.delta',
+ item_id: msgItemId,
+ output_index: 0,
+ content_index: 0,
+ delta: '让我搜索一下杭州的天气信息。',
+ },
+ {
+ type: 'response.output_item.added',
+ output_index: 1,
+ item: {
+ type: 'function_call',
+ call_id: toolCallId,
+ name: 'lobe-web-browsing____search____builtin',
+ arguments: JSON.stringify({ query: '杭州天气' }),
+ },
+ },
+ {
+ type: 'response.completed',
+ response: {
+ id: responseId,
+ object: 'response',
+ created_at: Math.floor(Date.now() / 1000),
+ status: 'completed',
+ model: 'gpt-5-pro',
+ output: [
+ {
+ id: msgItemId,
+ type: 'message',
+ status: 'completed',
+ content: [{ type: 'output_text', text: '让我搜索一下杭州的天气信息。' }],
+ role: 'assistant',
+ },
+ {
+ type: 'function_call',
+ call_id: toolCallId,
+ name: 'lobe-web-browsing____search____builtin',
+ arguments: JSON.stringify({ query: '杭州天气' }),
+ },
+ ],
+ usage: {
+ input_tokens: 50,
+ output_tokens: 30,
+ total_tokens: 80,
+ },
+ },
+ },
+ ];
+
+ return createMockResponsesStream(chunks);
+ };
+
+ const createMockFinalResponseStream = () => {
+ const responseId = `resp_final_${Date.now()}`;
+ const msgItemId = `msg_final_${Date.now()}`;
+ const finalContent = '根据搜索结果,杭州今天天气晴朗,气温约15-22°C,适合外出活动。';
+
+ const chunks = [
+ {
+ type: 'response.created',
+ response: {
+ id: responseId,
+ object: 'response',
+ created_at: Math.floor(Date.now() / 1000),
+ status: 'in_progress',
+ model: 'gpt-5-pro',
+ output: [],
+ },
+ },
+ {
+ type: 'response.output_item.added',
+ output_index: 0,
+ item: {
+ id: msgItemId,
+ type: 'message',
+ status: 'in_progress',
+ content: [],
+ role: 'assistant',
+ },
+ },
+ {
+ type: 'response.output_text.delta',
+ item_id: msgItemId,
+ output_index: 0,
+ content_index: 0,
+ delta: finalContent,
+ },
+ {
+ type: 'response.output_item.done',
+ output_index: 0,
+ item: {
+ id: msgItemId,
+ type: 'message',
+ status: 'completed',
+ content: [{ type: 'output_text', text: finalContent }],
+ role: 'assistant',
+ },
+ },
+ {
+ type: 'response.completed',
+ response: {
+ id: responseId,
+ object: 'response',
+ created_at: Math.floor(Date.now() / 1000),
+ status: 'completed',
+ model: 'gpt-5-pro',
+ output: [
+ {
+ id: msgItemId,
+ type: 'message',
+ status: 'completed',
+ content: [{ type: 'output_text', text: finalContent }],
+ role: 'assistant',
+ },
+ ],
+ usage: {
+ input_tokens: 100,
+ output_tokens: 50,
+ total_tokens: 150,
+ },
+ },
+ },
+ ];
+
+ return createMockResponsesStream(chunks);
+ };
+
+ beforeEach(async () => {
+ const [agentWithTools] = await serverDB
+ .insert(agents)
+ .values({
+ chatConfig: { autoCreateTopicThreshold: 2, searchMode: 'auto' },
+ model: 'gpt-5-pro',
+ plugins: [],
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant that can search the web.',
+ title: 'Test Assistant with Web Browsing',
+ userId,
+ })
+ .returning();
+ testAgentWithToolsId = agentWithTools.id;
+ });
+
+ it('should execute tool call flow: LLM -> search tool -> LLM -> finish', async () => {
+ let callCount = 0;
+ mockResponsesCreate.mockImplementation(() => {
+ callCount++;
+ if (callCount === 1) {
+ return Promise.resolve(createMockResponsesAPIStreamWithTools() as any);
+ }
+ return Promise.resolve(createMockFinalResponseStream() as any);
+ });
+
+ const mockExecuteTool = vi.spyOn(ToolExecutionService.prototype, 'executeTool');
+ mockExecuteTool.mockResolvedValue({
+ content: JSON.stringify({
+ results: [
+ {
+ title: '杭州天气预报',
+ snippet: '杭州今天天气晴,气温15-22°C',
+ url: 'https://weather.com/hangzhou',
+ },
+ ],
+ }),
+ error: null,
+ executionTime: 500,
+ state: {},
+ success: true,
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const createResult = await caller.execAgent({
+ agentId: testAgentWithToolsId,
+ prompt: '杭州天气如何',
+ });
+
+ expect(createResult.success).toBe(true);
+ expect(createResult.operationId).toBeDefined();
+
+ // Wait for async execution to complete
+ const finalState = await waitForOperationComplete(
+ inMemoryAgentStateManager,
+ createResult.operationId,
+ );
+
+ expect(finalState.status).toBe('done');
+
+ expect(mockResponsesCreate).toHaveBeenCalled();
+ const firstCallArgs = mockResponsesCreate.mock.calls[0][0] as {
+ tools: Array<{ function?: { name: string }; name?: string }>;
+ };
+ expect(firstCallArgs.tools).toBeDefined();
+ expect(firstCallArgs.tools.length).toBeGreaterThan(0);
+
+ const toolNames = firstCallArgs.tools.map((t) => t.name || t.function?.name);
+ const hasWebBrowsingTools = toolNames.some((name) => name?.includes('lobe-web-browsing'));
+ expect(hasWebBrowsingTools).toBe(true);
+
+ const allMessages = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.agentId, testAgentWithToolsId));
+
+ expect(allMessages.length).toEqual(4);
+
+ const userMessage = allMessages.find((m) => m.role === 'user');
+ expect(userMessage).toBeDefined();
+ expect(userMessage?.content).toBe('杭州天气如何');
+
+ const assistantMessages = allMessages.filter((m) => m.role === 'assistant');
+ expect(assistantMessages.length).toBe(2);
+
+ const toolMessage = allMessages.find((m) => m.role === 'tool');
+ expect(toolMessage).toBeDefined();
+
+ expect(mockExecuteTool).toHaveBeenCalled();
+ const toolCallArgs = mockExecuteTool.mock.calls[0][0];
+ expect(toolCallArgs.identifier).toBe('lobe-web-browsing');
+ expect(toolCallArgs.apiName).toBe('search');
+
+ mockExecuteTool.mockRestore();
+ });
+
+ it('should create correct parentId chain: user -> assistant1 -> tool -> assistant2', async () => {
+ let callCount = 0;
+ mockResponsesCreate.mockImplementation(() => {
+ callCount++;
+ if (callCount === 1) {
+ return Promise.resolve(createMockResponsesAPIStreamWithTools() as any);
+ }
+ return Promise.resolve(createMockFinalResponseStream() as any);
+ });
+
+ const mockExecuteTool = vi.spyOn(ToolExecutionService.prototype, 'executeTool');
+ mockExecuteTool.mockResolvedValue({
+ content: 'Search results for Hangzhou weather',
+ error: null,
+ executionTime: 100,
+ state: {},
+ success: true,
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const createResult = await caller.execAgent({
+ agentId: testAgentWithToolsId,
+ prompt: '杭州天气如何',
+ });
+
+ // Wait for async execution to complete
+ const finalState = await waitForOperationComplete(
+ inMemoryAgentStateManager,
+ createResult.operationId,
+ );
+
+ expect(finalState.status).toBe('done');
+
+ const allMessages = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.agentId, testAgentWithToolsId));
+
+ expect(allMessages.length).toBe(4);
+
+ const userMessage = allMessages.find((m) => m.role === 'user');
+ expect(userMessage).toBeDefined();
+ expect(userMessage?.parentId).toBeNull();
+
+ const firstAssistant = allMessages.find(
+ (m) => m.role === 'assistant' && m.parentId === userMessage?.id,
+ );
+ expect(firstAssistant).toBeDefined();
+
+ const toolMessage = allMessages.find((m) => m.role === 'tool');
+ expect(toolMessage).toBeDefined();
+ expect(toolMessage?.parentId).toBe(firstAssistant?.id);
+
+ const secondAssistant = allMessages.find(
+ (m) => m.role === 'assistant' && m.parentId === toolMessage?.id,
+ );
+ expect(secondAssistant).toBeDefined();
+
+ mockExecuteTool.mockRestore();
+ });
+ });
+});
diff --git a/src/server/routers/lambda/__tests__/integration/aiAgent/execAgents.integration.test.ts b/src/server/routers/lambda/__tests__/integration/aiAgent/execAgents.integration.test.ts
new file mode 100644
index 00000000000..b65b7c5c8e9
--- /dev/null
+++ b/src/server/routers/lambda/__tests__/integration/aiAgent/execAgents.integration.test.ts
@@ -0,0 +1,226 @@
+// @vitest-environment node
+/**
+ * Integration tests for execAgents (batch execution) router
+ *
+ * Note: AgentStateManager and StreamEventManager will automatically use
+ * InMemory implementations when Redis is not available (test environment).
+ */
+import { LobeChatDatabase } from '@lobechat/database';
+import { agents, topics } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import OpenAI from 'openai';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { inMemoryAgentStateManager } from '@/server/modules/AgentRuntime/InMemoryAgentStateManager';
+import { inMemoryStreamEventManager } from '@/server/modules/AgentRuntime/InMemoryStreamEventManager';
+
+import { aiAgentRouter } from '../../../aiAgent';
+import { cleanupTestUser, createTestUser } from '../setup';
+import { createMockResponsesAPIStream } from './helpers';
+
+// Set fake API key for testing to bypass OpenAI SDK validation
+process.env.OPENAI_API_KEY = 'sk-test-fake-api-key-for-testing';
+
+// Mock getServerDB to return our test database instance
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => testDB),
+}));
+
+// Mock FileService to avoid S3 environment variable requirements
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(() => ({
+ getFullFileUrl: vi.fn().mockImplementation((path: string) => (path ? `/files${path}` : null)),
+ })),
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+let mockResponsesCreate: any;
+
+let serverDB: LobeChatDatabase;
+let userId: string;
+let testAgentId: string;
+let testAgent2Id: string;
+
+const createTestContext = () => ({
+ jwtPayload: { userId },
+ userId,
+});
+
+beforeEach(async () => {
+ // Setup test database
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+
+ // Create test agent with gpt-5-pro (uses Responses API)
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({
+ model: 'gpt-5-pro',
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant.',
+ title: 'Test Assistant',
+ userId,
+ })
+ .returning();
+ testAgentId = agent.id;
+
+ // Create a second test agent for batch testing
+ const [agent2] = await serverDB
+ .insert(agents)
+ .values({
+ model: 'gpt-5-pro',
+ provider: 'openai',
+ systemRole: 'You are a helpful coding assistant.',
+ title: 'Test Assistant 2',
+ userId,
+ })
+ .returning();
+ testAgent2Id = agent2.id;
+
+ // Setup spyOn for OpenAI Responses API prototype
+ mockResponsesCreate = vi.spyOn(OpenAI.Responses.prototype, 'create');
+});
+
+afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ vi.clearAllMocks();
+ vi.restoreAllMocks();
+
+ // Clear singleton instances for next test
+ inMemoryAgentStateManager.clear();
+ inMemoryStreamEventManager.clear();
+});
+
+describe('Batch Execution (execAgents)', () => {
+ it('should execute multiple agents in parallel', async () => {
+ const responseContent = 'Hello from batch execution!';
+ mockResponsesCreate.mockResolvedValue(createMockResponsesAPIStream(responseContent) as any);
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.execAgents({
+ parallel: true,
+ tasks: [
+ { agentId: testAgentId, autoStart: false, prompt: 'Task 1: Hello' },
+ { agentId: testAgent2Id, autoStart: false, prompt: 'Task 2: World' },
+ ],
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.results).toHaveLength(2);
+ expect(result.summary).toEqual({
+ failed: 0,
+ succeeded: 2,
+ total: 2,
+ });
+
+ expect(result.results[0]).toMatchObject({
+ success: true,
+ taskIndex: 0,
+ operationId: expect.stringMatching(/^op_\d+_agt_.+_tpc_.+_\w+$/),
+ });
+ expect(result.results[1]).toMatchObject({
+ success: true,
+ taskIndex: 1,
+ operationId: expect.stringMatching(/^op_\d+_agt_.+_tpc_.+_\w+$/),
+ });
+
+ expect(result.results[0].operationId).not.toBe(result.results[1].operationId);
+ });
+
+ it('should execute multiple agents sequentially when parallel=false', async () => {
+ const responseContent = 'Sequential execution response';
+ mockResponsesCreate.mockResolvedValue(createMockResponsesAPIStream(responseContent) as any);
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.execAgents({
+ parallel: false,
+ tasks: [
+ { agentId: testAgentId, autoStart: false, prompt: 'Sequential Task 1' },
+ { agentId: testAgent2Id, autoStart: false, prompt: 'Sequential Task 2' },
+ ],
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.results).toHaveLength(2);
+ expect(result.summary.succeeded).toBe(2);
+ });
+
+ it('should handle partial failures gracefully', async () => {
+ mockResponsesCreate.mockResolvedValue(createMockResponsesAPIStream('Success response') as any);
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.execAgents({
+ tasks: [
+ { agentId: testAgentId, autoStart: false, prompt: 'Valid task' },
+ { agentId: 'non-existent-agent', autoStart: false, prompt: 'Invalid task' },
+ { agentId: testAgent2Id, autoStart: false, prompt: 'Another valid task' },
+ ],
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.results).toHaveLength(3);
+
+ expect(result.results[0].success).toBe(true);
+ expect(result.results[0].taskIndex).toBe(0);
+
+ expect(result.results[1].success).toBe(false);
+ expect(result.results[1].taskIndex).toBe(1);
+ expect(result.results[1].error).toBeDefined();
+
+ expect(result.results[2].success).toBe(true);
+ expect(result.results[2].taskIndex).toBe(2);
+
+ expect(result.summary).toEqual({
+ failed: 1,
+ succeeded: 2,
+ total: 3,
+ });
+ });
+
+ it('should create separate topics for each task', async () => {
+ mockResponsesCreate.mockResolvedValue(
+ createMockResponsesAPIStream('Response for separate topics') as any,
+ );
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await caller.execAgents({
+ tasks: [
+ { agentId: testAgentId, autoStart: false, prompt: 'Topic 1 prompt' },
+ { agentId: testAgentId, autoStart: false, prompt: 'Topic 2 prompt' },
+ ],
+ });
+
+ const createdTopics = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.agentId, testAgentId));
+
+ expect(createdTopics).toHaveLength(2);
+ expect(createdTopics.map((t) => t.title).sort()).toEqual(['Topic 1 prompt', 'Topic 2 prompt']);
+ });
+
+ it('should support autoStart for batch tasks', async () => {
+ mockResponsesCreate.mockResolvedValue(createMockResponsesAPIStream('Auto start test') as any);
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.execAgents({
+ tasks: [
+ { agentId: testAgentId, autoStart: true, prompt: 'Auto start task 1' },
+ { agentId: testAgent2Id, autoStart: false, prompt: 'Manual start task 2' },
+ ],
+ });
+
+ expect(result.success).toBe(true);
+
+ expect(result.results[0].autoStarted).toBe(true);
+ expect(result.results[1].autoStarted).toBe(false);
+ });
+});
diff --git a/src/server/routers/lambda/__tests__/integration/aiAgent/execGroupAgent.integration.test.ts b/src/server/routers/lambda/__tests__/integration/aiAgent/execGroupAgent.integration.test.ts
new file mode 100644
index 00000000000..407305461e3
--- /dev/null
+++ b/src/server/routers/lambda/__tests__/integration/aiAgent/execGroupAgent.integration.test.ts
@@ -0,0 +1,460 @@
+// @vitest-environment node
+/**
+ * Integration tests for execGroupAgent router
+ * Tests Group Agent (Supervisor) execution with groupId support
+ *
+ * Note: AgentStateManager and StreamEventManager will automatically use
+ * InMemory implementations when Redis is not available (test environment).
+ */
+import { LobeChatDatabase } from '@lobechat/database';
+import { agents, chatGroups, messages, topics } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { and, eq } from 'drizzle-orm';
+import OpenAI from 'openai';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { inMemoryAgentStateManager } from '@/server/modules/AgentRuntime/InMemoryAgentStateManager';
+import { inMemoryStreamEventManager } from '@/server/modules/AgentRuntime/InMemoryStreamEventManager';
+
+import { aiAgentRouter } from '../../../aiAgent';
+import { cleanupTestUser, createTestUser } from '../setup';
+import { createMockResponsesAPIStream } from './helpers';
+
+// Set fake API key for testing to bypass OpenAI SDK validation
+process.env.OPENAI_API_KEY = 'sk-test-fake-api-key-for-testing';
+
+// Local testDB variable for mock closure
+let testDB: LobeChatDatabase;
+
+// Setup mocks at module level (vi.mock is hoisted)
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => testDB),
+}));
+
+// Mock FileService to avoid S3 environment variable requirements
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(() => ({
+ getFullFileUrl: vi.fn().mockImplementation((path: string) => (path ? `/files${path}` : null)),
+ })),
+}));
+
+let serverDB: LobeChatDatabase;
+let userId: string;
+let testAgentId: string;
+let testGroupId: string;
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+let mockResponsesCreate: any;
+
+const createTestCallerContext = (uid: string) => ({
+ jwtPayload: { userId: uid },
+ userId: uid,
+});
+
+beforeEach(async () => {
+ // Setup test database
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+
+ // Create test agent
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({
+ model: 'gpt-5-pro',
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant.',
+ title: 'Test Assistant',
+ userId,
+ })
+ .returning();
+ testAgentId = agent.id;
+
+ // Create a test chat group
+ const [group] = await serverDB
+ .insert(chatGroups)
+ .values({
+ title: 'Test Chat Group',
+ userId,
+ })
+ .returning();
+ testGroupId = group.id;
+
+ // Setup spyOn for OpenAI Responses API prototype
+ mockResponsesCreate = vi.spyOn(OpenAI.Responses.prototype, 'create');
+});
+
+afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ vi.clearAllMocks();
+ vi.restoreAllMocks();
+
+ // Clear singleton instances for next test
+ inMemoryAgentStateManager.clear();
+ inMemoryStreamEventManager.clear();
+});
+
+describe('execGroupAgent', () => {
+ describe('Topic Creation with groupId', () => {
+ it('should create a new topic with groupId when topicId is not provided', async () => {
+ mockResponsesCreate.mockResolvedValue(
+ createMockResponsesAPIStream('Hello from group agent!') as any,
+ );
+
+ const caller = aiAgentRouter.createCaller(createTestCallerContext(userId));
+
+ const result = await caller.execGroupAgent({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ message: 'Hello, group!',
+ });
+
+ expect(result.operationId).toBeDefined();
+ expect(result.topicId).toBeDefined();
+ expect(result.isCreateNewTopic).toBe(true);
+
+ // Verify topic was created with correct groupId
+ const createdTopics = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.id, result.topicId));
+
+ expect(createdTopics).toHaveLength(1);
+ expect(createdTopics[0].groupId).toBe(testGroupId);
+ expect(createdTopics[0].agentId).toBe(testAgentId);
+ expect(createdTopics[0].title).toBe('Hello, group!');
+ });
+
+ it('should truncate long message for topic title', async () => {
+ mockResponsesCreate.mockResolvedValue(createMockResponsesAPIStream('Response') as any);
+
+ const caller = aiAgentRouter.createCaller(createTestCallerContext(userId));
+ const longMessage =
+ 'This is a very long message that exceeds fifty characters and should be truncated for the topic title';
+
+ const result = await caller.execGroupAgent({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ message: longMessage,
+ });
+
+ expect(result.isCreateNewTopic).toBe(true);
+
+ const createdTopics = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.id, result.topicId));
+
+ expect(createdTopics[0].title).toBe(longMessage.slice(0, 50) + '...');
+ expect(createdTopics[0].groupId).toBe(testGroupId);
+ });
+
+ it('should reuse existing topic when topicId is provided', async () => {
+ mockResponsesCreate.mockResolvedValue(
+ createMockResponsesAPIStream('Follow up response') as any,
+ );
+
+ // Create an existing topic with groupId
+ const [existingTopic] = await serverDB
+ .insert(topics)
+ .values({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ title: 'Existing Group Topic',
+ userId,
+ })
+ .returning();
+
+ const caller = aiAgentRouter.createCaller(createTestCallerContext(userId));
+
+ const result = await caller.execGroupAgent({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ message: 'Follow up message',
+ topicId: existingTopic.id,
+ });
+
+ expect(result.topicId).toBe(existingTopic.id);
+ expect(result.isCreateNewTopic).toBe(false);
+
+ // Verify no new topic was created
+ const allTopics = await serverDB.select().from(topics).where(eq(topics.groupId, testGroupId));
+
+ expect(allTopics).toHaveLength(1);
+ expect(allTopics[0].id).toBe(existingTopic.id);
+ });
+
+ it('should create topic with custom title when newTopic is provided', async () => {
+ mockResponsesCreate.mockResolvedValue(
+ createMockResponsesAPIStream('Response with custom topic') as any,
+ );
+
+ const caller = aiAgentRouter.createCaller(createTestCallerContext(userId));
+
+ const result = await caller.execGroupAgent({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ message: 'Some message content',
+ newTopic: {
+ title: 'Custom Topic Title',
+ },
+ });
+
+ expect(result.isCreateNewTopic).toBe(true);
+
+ const createdTopics = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.id, result.topicId));
+
+ expect(createdTopics[0].title).toBe('Custom Topic Title');
+ expect(createdTopics[0].groupId).toBe(testGroupId);
+ });
+ });
+
+ describe('Message Creation', () => {
+ it('should create user message in the topic', async () => {
+ mockResponsesCreate.mockResolvedValue(createMockResponsesAPIStream('Agent response') as any);
+
+ const caller = aiAgentRouter.createCaller(createTestCallerContext(userId));
+
+ const result = await caller.execGroupAgent({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ message: 'User message in group',
+ });
+
+ // Verify user message was created
+ const createdMessages = await serverDB
+ .select()
+ .from(messages)
+ .where(and(eq(messages.topicId, result.topicId), eq(messages.role, 'user')));
+
+ expect(createdMessages).toHaveLength(1);
+ expect(createdMessages[0].content).toBe('User message in group');
+ expect(createdMessages[0].agentId).toBe(testAgentId);
+ });
+ });
+
+ describe('Response Data', () => {
+ it('should return messages and topics in response', async () => {
+ mockResponsesCreate.mockResolvedValue(
+ createMockResponsesAPIStream('Response with data') as any,
+ );
+
+ const caller = aiAgentRouter.createCaller(createTestCallerContext(userId));
+
+ const result = await caller.execGroupAgent({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ message: 'Test message',
+ });
+
+ // Verify response contains messages
+ expect(result.messages).toBeDefined();
+ expect(Array.isArray(result.messages)).toBe(true);
+
+ // Verify isCreateNewTopic flag
+ expect(result.isCreateNewTopic).toBe(true);
+
+ // Verify response contains topics when new topic is created
+ // topics is returned from topicModel.query() when includeTopic is true
+ expect(result.topics).toBeDefined();
+ });
+
+ it('should not return topics when using existing topic', async () => {
+ mockResponsesCreate.mockResolvedValue(createMockResponsesAPIStream('Response') as any);
+
+ // Create an existing topic
+ const [existingTopic] = await serverDB
+ .insert(topics)
+ .values({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ title: 'Existing Topic',
+ userId,
+ })
+ .returning();
+
+ const caller = aiAgentRouter.createCaller(createTestCallerContext(userId));
+
+ const result = await caller.execGroupAgent({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ message: 'Follow up',
+ topicId: existingTopic.id,
+ });
+
+ expect(result.isCreateNewTopic).toBe(false);
+ // Topics should be undefined or empty when not creating new topic
+ expect(result.topics).toBeUndefined();
+ });
+ });
+
+ describe('Error Handling', () => {
+ it('should throw error when agent does not exist', async () => {
+ const caller = aiAgentRouter.createCaller(createTestCallerContext(userId));
+
+ await expect(
+ caller.execGroupAgent({
+ agentId: 'non-existent-agent-id',
+ groupId: testGroupId,
+ message: 'Hello',
+ }),
+ ).rejects.toThrow();
+ });
+ });
+
+ describe('Stream Events', () => {
+ // TODO: LOBE-1748 - Fix missing agent_runtime_end event
+ // This test documents the current bug where agent_runtime_end is not sent
+ // When fixed, remove .todo and the test should pass
+ it.todo('should emit agent_runtime_end event when agent completes', async () => {
+ mockResponsesCreate.mockResolvedValue(
+ createMockResponsesAPIStream('Completed response') as any,
+ );
+
+ const caller = aiAgentRouter.createCaller(createTestCallerContext(userId));
+
+ const result = await caller.execGroupAgent({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ message: 'Test message for stream events',
+ });
+
+ expect(result.operationId).toBeDefined();
+
+ // Wait a bit for all events to be processed
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+
+ // Check all events that were emitted
+ const allEvents = inMemoryStreamEventManager.getAllEvents(result.operationId);
+ const eventTypes = allEvents.map((e) => e.type);
+
+ console.log('All emitted event types:', eventTypes);
+
+ // IMPORTANT: This test verifies that agent_runtime_end event is sent
+ // If this test fails, it means the SSE stream won't close properly
+ // See LOBE-1748 for details
+ expect(eventTypes).toContain('agent_runtime_end');
+
+ // Also verify the event has correct data structure
+ const endEvent = allEvents.find((e) => e.type === 'agent_runtime_end');
+ if (endEvent) {
+ expect(endEvent.data).toBeDefined();
+ expect(endEvent.data.phase).toBe('execution_complete');
+ }
+ });
+
+ it('should emit events in correct order: init -> chunks -> end', async () => {
+ mockResponsesCreate.mockResolvedValue(
+ createMockResponsesAPIStream('Response content') as any,
+ );
+
+ const caller = aiAgentRouter.createCaller(createTestCallerContext(userId));
+
+ const result = await caller.execGroupAgent({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ message: 'Test event order',
+ });
+
+ // Wait a bit for all events to be processed
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+
+ const allEvents = inMemoryStreamEventManager.getAllEvents(result.operationId);
+ const eventTypes = allEvents.map((e) => e.type);
+
+ // Log event types for debugging
+ console.log('Emitted event types:', eventTypes);
+
+ // Verify agent_runtime_init is emitted (should be first or near first)
+ const initIndex = eventTypes.indexOf('agent_runtime_init');
+
+ // Verify agent_runtime_end is emitted (should be last)
+ const endIndex = eventTypes.indexOf('agent_runtime_end');
+
+ // If both events exist, verify order
+ if (initIndex !== -1 && endIndex !== -1) {
+ expect(initIndex).toBeLessThan(endIndex);
+ }
+
+ // At minimum, we should have some events
+ expect(allEvents.length).toBeGreaterThan(0);
+ });
+ });
+
+ describe('Multiple Group Sessions', () => {
+ it('should create separate topics for different groups', async () => {
+ mockResponsesCreate.mockResolvedValue(createMockResponsesAPIStream('Response') as any);
+
+ // Create another group
+ const [group2] = await serverDB
+ .insert(chatGroups)
+ .values({
+ title: 'Test Chat Group 2',
+ userId,
+ })
+ .returning();
+
+ const caller = aiAgentRouter.createCaller(createTestCallerContext(userId));
+
+ // Send message to first group
+ const result1 = await caller.execGroupAgent({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ message: 'Message to group 1',
+ });
+
+ // Send message to second group
+ const result2 = await caller.execGroupAgent({
+ agentId: testAgentId,
+ groupId: group2.id,
+ message: 'Message to group 2',
+ });
+
+ // Verify different topics were created
+ expect(result1.topicId).not.toBe(result2.topicId);
+
+ // Verify topics have correct groupIds
+ const topic1 = await serverDB.select().from(topics).where(eq(topics.id, result1.topicId));
+ const topic2 = await serverDB.select().from(topics).where(eq(topics.id, result2.topicId));
+
+ expect(topic1[0].groupId).toBe(testGroupId);
+ expect(topic2[0].groupId).toBe(group2.id);
+ });
+
+ it('should allow multiple topics within same group', async () => {
+ mockResponsesCreate.mockResolvedValue(createMockResponsesAPIStream('Response') as any);
+
+ const caller = aiAgentRouter.createCaller(createTestCallerContext(userId));
+
+ // Create first topic in group
+ const result1 = await caller.execGroupAgent({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ message: 'First conversation',
+ });
+
+ // Create second topic in same group (without topicId, should create new)
+ const result2 = await caller.execGroupAgent({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ message: 'Second conversation',
+ });
+
+ // Verify different topics were created
+ expect(result1.topicId).not.toBe(result2.topicId);
+ expect(result1.isCreateNewTopic).toBe(true);
+ expect(result2.isCreateNewTopic).toBe(true);
+
+ // Verify both topics belong to same group
+ const groupTopics = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.groupId, testGroupId));
+
+ expect(groupTopics).toHaveLength(2);
+ expect(groupTopics.every((t) => t.groupId === testGroupId)).toBe(true);
+ });
+ });
+});
diff --git a/src/server/routers/lambda/__tests__/integration/aiAgent/helpers.ts b/src/server/routers/lambda/__tests__/integration/aiAgent/helpers.ts
new file mode 100644
index 00000000000..466c789cac1
--- /dev/null
+++ b/src/server/routers/lambda/__tests__/integration/aiAgent/helpers.ts
@@ -0,0 +1,147 @@
+/**
+ * Shared helpers for aiAgent integration tests
+ */
+import { AgentState } from '@lobechat/agent-runtime';
+import { vi } from 'vitest';
+
+import { IAgentStateManager } from '@/server/modules/AgentRuntime/types';
+
+/**
+ * Wait for an operation to complete (or reach terminal state)
+ *
+ * @param stateManager - The agent state manager to check state
+ * @param operationId - The operation ID to wait for
+ * @param options - Configuration options
+ * @returns The final state when complete
+ */
+export const waitForOperationComplete = async (
+ stateManager: IAgentStateManager,
+ operationId: string,
+ options?: {
+ /** Maximum time to wait in ms (default: 30000) */
+ maxWaitTime?: number;
+ /** Polling interval in ms (default: 100) */
+ pollInterval?: number;
+ },
+): Promise<AgentState> => {
+ const { maxWaitTime = 30_000, pollInterval = 100 } = options ?? {};
+ const startTime = Date.now();
+
+ while (Date.now() - startTime < maxWaitTime) {
+ const state = await stateManager.loadAgentState(operationId);
+ if (!state) {
+ throw new Error(`Operation ${operationId} not found`);
+ }
+
+ // Check for terminal states
+ if (['done', 'error', 'interrupted', 'waiting_for_human'].includes(state.status)) {
+ return state;
+ }
+
+ // Wait before next poll
+ await new Promise((resolve) => {
+ setTimeout(resolve, pollInterval);
+ });
+ }
+
+ throw new Error(`Operation ${operationId} did not complete within ${maxWaitTime}ms`);
+};
+
+// Mock FileService to avoid S3 environment variable requirements
+// This mock needs to be in a shared place but vitest hoists vi.mock
+// So each test file should import and use this constant
+export const FILE_SERVICE_MOCK = {
+ FileService: vi.fn().mockImplementation(() => ({
+ getFullFileUrl: vi.fn().mockImplementation((path: string) => (path ? `/files${path}` : null)),
+ })),
+};
+
+/**
+ * Helper to create a mock OpenAI Responses API stream from an array of chunks.
+ * This creates an async iterable with tee() method that matches the OpenAI SDK response format.
+ */
+export const createMockResponsesStream = <T>(chunks: T[]) => {
+ const createAsyncIterator = () => ({
+ [Symbol.asyncIterator]: async function* () {
+ for (const chunk of chunks) {
+ yield chunk;
+ }
+ },
+ toReadableStream: () =>
+ new ReadableStream({
+ start(controller) {
+ for (const chunk of chunks) {
+ controller.enqueue(chunk);
+ }
+ controller.close();
+ },
+ }),
+ });
+
+ const mainIterator = createAsyncIterator();
+ return Object.assign(mainIterator, {
+ tee: () => [createAsyncIterator(), createAsyncIterator()],
+ });
+};
+
+/**
+ * Helper to create mock streaming response for OpenAI Responses API
+ */
+export const createMockResponsesAPIStream = (
+ content: string = 'Hello! How can I help you today?',
+) => {
+ const responseId = `resp_${Date.now()}`;
+ const itemId = `msg_${Date.now()}`;
+
+ const chunks = [
+ {
+ response: {
+ created_at: Math.floor(Date.now() / 1000),
+ id: responseId,
+ model: 'gpt-5-pro',
+ object: 'response',
+ output: [],
+ status: 'in_progress',
+ },
+ type: 'response.created',
+ },
+ {
+ content_index: 0,
+ delta: content,
+ item_id: itemId,
+ output_index: 0,
+ type: 'response.output_text.delta',
+ },
+ {
+ content_index: 0,
+ item_id: itemId,
+ output_index: 0,
+ text: content,
+ type: 'response.output_text.done',
+ },
+ {
+ response: {
+ created_at: Math.floor(Date.now() / 1000),
+ id: responseId,
+ model: 'gpt-5-pro',
+ object: 'response',
+ output: [
+ {
+ content: [{ text: content, type: 'output_text' }],
+ role: 'assistant',
+ type: 'message',
+ },
+ ],
+ status: 'completed',
+ usage: {
+ input_tokens: 20,
+ output_tokens: 10,
+ total_tokens: 30,
+ },
+ },
+ type: 'response.completed',
+ },
+ ];
+
+ return createMockResponsesStream(chunks);
+};
diff --git a/src/server/routers/lambda/__tests__/integration/aiAgent/multiRoundTools.integration.test.ts b/src/server/routers/lambda/__tests__/integration/aiAgent/multiRoundTools.integration.test.ts
new file mode 100644
index 00000000000..946e23fc864
--- /dev/null
+++ b/src/server/routers/lambda/__tests__/integration/aiAgent/multiRoundTools.integration.test.ts
@@ -0,0 +1,386 @@
+// @vitest-environment node
+/**
+ * Integration tests for multi-round tool execution
+ * Tests for LOBE-1657 fix: tool messages should not be duplicated across rounds
+ *
+ * Note: AgentStateManager and StreamEventManager will automatically use
+ * InMemory implementations when Redis is not available (test environment).
+ */
+import { LobeChatDatabase } from '@lobechat/database';
+import { agents, messages } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import OpenAI from 'openai';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { inMemoryAgentStateManager } from '@/server/modules/AgentRuntime/InMemoryAgentStateManager';
+import { inMemoryStreamEventManager } from '@/server/modules/AgentRuntime/InMemoryStreamEventManager';
+import { ToolExecutionService } from '@/server/services/toolExecution';
+
+import { aiAgentRouter } from '../../../aiAgent';
+import { cleanupTestUser, createTestUser } from '../setup';
+import { createMockResponsesStream, waitForOperationComplete } from './helpers';
+
+// Set fake API key for testing to bypass OpenAI SDK validation
+process.env.OPENAI_API_KEY = 'sk-test-fake-api-key-for-testing';
+
+// Mock getServerDB to return our test database instance
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => testDB),
+}));
+
+// Mock FileService to avoid S3 environment variable requirements
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(() => ({
+ getFullFileUrl: vi.fn().mockImplementation((path: string) => (path ? `/files${path}` : null)),
+ })),
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+let mockResponsesCreate: any;
+
+let serverDB: LobeChatDatabase;
+let userId: string;
+let testAgentWithToolsId: string;
+
+const createTestContext = () => ({
+ jwtPayload: { userId },
+ userId,
+});
+
+// Helper to create mock streaming response with multiple tool calls
+const createMockResponseWithMultipleTools = (roundNum: number) => {
+ const responseId = `resp_round${roundNum}_${Date.now()}`;
+ const msgItemId = `msg_round${roundNum}_${Date.now()}`;
+ const toolCallId1 = `call_search_round${roundNum}`;
+ const toolCallId2 = `call_crawl_round${roundNum}`;
+
+ const chunks = [
+ {
+ type: 'response.created',
+ response: {
+ id: responseId,
+ object: 'response',
+ created_at: Math.floor(Date.now() / 1000),
+ status: 'in_progress',
+ model: 'gpt-5-pro',
+ output: [],
+ },
+ },
+ {
+ type: 'response.output_item.added',
+ output_index: 0,
+ item: {
+ id: msgItemId,
+ type: 'message',
+ status: 'in_progress',
+ content: [],
+ role: 'assistant',
+ },
+ },
+ {
+ type: 'response.output_text.delta',
+ item_id: msgItemId,
+ output_index: 0,
+ content_index: 0,
+ delta: `Round ${roundNum}: Let me search and crawl for you.`,
+ },
+ {
+ type: 'response.output_item.added',
+ output_index: 1,
+ item: {
+ type: 'function_call',
+ call_id: toolCallId1,
+ name: 'lobe-web-browsing____search____builtin',
+ arguments: JSON.stringify({ query: `query_round${roundNum}` }),
+ },
+ },
+ {
+ type: 'response.output_item.added',
+ output_index: 2,
+ item: {
+ type: 'function_call',
+ call_id: toolCallId2,
+ name: 'lobe-web-browsing____crawl____builtin',
+ arguments: JSON.stringify({ url: `https://example.com/page${roundNum}` }),
+ },
+ },
+ {
+ type: 'response.completed',
+ response: {
+ id: responseId,
+ object: 'response',
+ created_at: Math.floor(Date.now() / 1000),
+ status: 'completed',
+ model: 'gpt-5-pro',
+ output: [
+ {
+ id: msgItemId,
+ type: 'message',
+ status: 'completed',
+ content: [
+ {
+ type: 'output_text',
+ text: `Round ${roundNum}: Let me search and crawl for you.`,
+ },
+ ],
+ role: 'assistant',
+ },
+ {
+ type: 'function_call',
+ call_id: toolCallId1,
+ name: 'lobe-web-browsing____search____builtin',
+ arguments: JSON.stringify({ query: `query_round${roundNum}` }),
+ },
+ {
+ type: 'function_call',
+ call_id: toolCallId2,
+ name: 'lobe-web-browsing____crawl____builtin',
+ arguments: JSON.stringify({ url: `https://example.com/page${roundNum}` }),
+ },
+ ],
+ usage: {
+ input_tokens: 50 * roundNum,
+ output_tokens: 30,
+ total_tokens: 50 * roundNum + 30,
+ },
+ },
+ },
+ ];
+
+ return createMockResponsesStream(chunks);
+};
+
+// Helper to create final response (no tools)
+const createMockFinalResponse = () => {
+ const responseId = `resp_final_${Date.now()}`;
+ const msgItemId = `msg_final_${Date.now()}`;
+ const finalContent = 'Based on my research across multiple rounds, here is the final answer.';
+
+ const chunks = [
+ {
+ type: 'response.created',
+ response: {
+ id: responseId,
+ object: 'response',
+ created_at: Math.floor(Date.now() / 1000),
+ status: 'in_progress',
+ model: 'gpt-5-pro',
+ output: [],
+ },
+ },
+ {
+ type: 'response.output_text.delta',
+ item_id: msgItemId,
+ output_index: 0,
+ content_index: 0,
+ delta: finalContent,
+ },
+ {
+ type: 'response.completed',
+ response: {
+ id: responseId,
+ object: 'response',
+ created_at: Math.floor(Date.now() / 1000),
+ status: 'completed',
+ model: 'gpt-5-pro',
+ output: [
+ {
+ id: msgItemId,
+ type: 'message',
+ status: 'completed',
+ content: [{ type: 'output_text', text: finalContent }],
+ role: 'assistant',
+ },
+ ],
+ usage: {
+ input_tokens: 200,
+ output_tokens: 50,
+ total_tokens: 250,
+ },
+ },
+ },
+ ];
+
+ return createMockResponsesStream(chunks);
+};
+
+beforeEach(async () => {
+ // Setup test database
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+
+ // Create test agent with search enabled via chatConfig.searchMode
+ const [agentWithTools] = await serverDB
+ .insert(agents)
+ .values({
+ chatConfig: { autoCreateTopicThreshold: 2, searchMode: 'auto' },
+ model: 'gpt-5-pro',
+ plugins: [],
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant that can search and crawl the web.',
+ title: 'Test Assistant for Multi-Round Tools',
+ userId,
+ })
+ .returning();
+ testAgentWithToolsId = agentWithTools.id;
+
+ // Setup spyOn for OpenAI Responses API prototype
+ mockResponsesCreate = vi.spyOn(OpenAI.Responses.prototype, 'create');
+});
+
+afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ vi.clearAllMocks();
+ vi.restoreAllMocks();
+
+ // Clear singleton instances for next test
+ inMemoryAgentStateManager.clear();
+ inMemoryStreamEventManager.clear();
+});
+
+describe('Multi-Round Tool Execution', () => {
+ /**
+ * This test verifies the fix for LOBE-1657:
+ * When executing multiple rounds of batch tool calls, tool messages should not be duplicated.
+ *
+ * Scenario: LLM returns multiple tool calls in each round
+ * - Round 1: LLM -> 2 tools (search + crawl) -> tool results
+ * - Round 2: LLM -> 2 tools (search + crawl) -> tool results
+ * - Round 3: LLM -> final response
+ *
+ * Expected: 4 tool messages total (2 from round 1 + 2 from round 2), no duplicates
+ */
+ it('should not duplicate tool messages across multiple LLM rounds with batch tool execution', async () => {
+ let callCount = 0;
+ mockResponsesCreate.mockImplementation(() => {
+ callCount++;
+ if (callCount === 1) {
+ return Promise.resolve(createMockResponseWithMultipleTools(1) as any);
+ } else if (callCount === 2) {
+ return Promise.resolve(createMockResponseWithMultipleTools(2) as any);
+ }
+ return Promise.resolve(createMockFinalResponse() as any);
+ });
+
+ const mockExecuteTool = vi.spyOn(ToolExecutionService.prototype, 'executeTool');
+ mockExecuteTool.mockImplementation(async (toolCall) => {
+ const isSearch = toolCall.apiName === 'search';
+ return {
+ content: JSON.stringify({
+ result: isSearch ? 'Search results' : 'Crawled content',
+ tool: toolCall.apiName,
+ id: toolCall.id,
+ }),
+ error: null,
+ executionTime: 100,
+ state: {},
+ success: true,
+ };
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const createResult = await caller.execAgent({
+ agentId: testAgentWithToolsId,
+ prompt: 'Please search and crawl multiple pages for comprehensive research',
+ });
+
+ expect(createResult.success).toBe(true);
+
+ // Wait for async execution to complete
+ const finalState = await waitForOperationComplete(
+ inMemoryAgentStateManager,
+ createResult.operationId,
+ );
+
+ expect(finalState.status).toBe('done');
+
+ const allMessages = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.agentId, testAgentWithToolsId));
+
+ const toolMessages = allMessages.filter((m) => m.role === 'tool');
+ expect(toolMessages).toHaveLength(4);
+
+ const toolCallIdsFromContent = toolMessages
+ .map((m) => {
+ try {
+ const parsed = JSON.parse(m.content || '{}');
+ return parsed.id;
+ } catch {
+ return null;
+ }
+ })
+ .filter(Boolean);
+
+ const uniqueToolCallIds = [...new Set(toolCallIdsFromContent)];
+ expect(toolCallIdsFromContent.length).toBe(uniqueToolCallIds.length);
+
+ expect(toolCallIdsFromContent.sort()).toEqual([
+ 'call_crawl_round1',
+ 'call_crawl_round2',
+ 'call_search_round1',
+ 'call_search_round2',
+ ]);
+
+ expect(allMessages).toHaveLength(8);
+
+ const assistantMessages = allMessages.filter((m) => m.role === 'assistant');
+ expect(assistantMessages).toHaveLength(3);
+
+ expect(mockResponsesCreate).toHaveBeenCalledTimes(3);
+
+ mockExecuteTool.mockRestore();
+ });
+
+ it('should maintain correct state.messages count in AgentState across tool rounds', async () => {
+ let callCount = 0;
+ mockResponsesCreate.mockImplementation(() => {
+ callCount++;
+ if (callCount === 1) {
+ return Promise.resolve(createMockResponseWithMultipleTools(1) as any);
+ } else if (callCount === 2) {
+ return Promise.resolve(createMockResponseWithMultipleTools(2) as any);
+ }
+ return Promise.resolve(createMockFinalResponse() as any);
+ });
+
+ const mockExecuteTool = vi.spyOn(ToolExecutionService.prototype, 'executeTool');
+ mockExecuteTool.mockResolvedValue({
+ content: JSON.stringify({ result: 'Tool executed' }),
+ error: null,
+ executionTime: 100,
+ state: {},
+ success: true,
+ });
+
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const createResult = await caller.execAgent({
+ agentId: testAgentWithToolsId,
+ prompt: 'Multi-round tool test',
+ });
+
+ // Wait for async execution to complete
+ const finalState = await waitForOperationComplete(
+ inMemoryAgentStateManager,
+ createResult.operationId,
+ );
+
+ expect(finalState.status).toBe('done');
+
+ const stateToolMessages = finalState.messages.filter(
+ (m: { role: string }) => m.role === 'tool',
+ );
+ expect(stateToolMessages).toHaveLength(4);
+
+ const stateToolCallIds = stateToolMessages.map((m: { tool_call_id: string }) => m.tool_call_id);
+ expect(new Set(stateToolCallIds).size).toBe(4);
+
+ mockExecuteTool.mockRestore();
+ });
+});
diff --git a/src/server/routers/lambda/__tests__/integration/helpers/openaiMock.ts b/src/server/routers/lambda/__tests__/integration/helpers/openaiMock.ts
new file mode 100644
index 00000000000..f48b40d5a00
--- /dev/null
+++ b/src/server/routers/lambda/__tests__/integration/helpers/openaiMock.ts
@@ -0,0 +1,86 @@
+/**
+ * OpenAI API Mock Helper
+ *
+ * Provides utilities to create mock OpenAI streaming responses
+ * for E2E testing without hitting the real API.
+ */
+
+export const createMockOpenAIResponsesAPIStream = (
+ content: string = 'Hello! How can I help you today?',
+) => {
+ const responseId = `resp_${Date.now()}`;
+ const itemId = `msg_${Date.now()}`;
+
+ // Create Responses API event chunks
+ const createChunks = () => [
+ {
+ response: {
+ created_at: Math.floor(Date.now() / 1000),
+ id: responseId,
+ model: 'gpt-5-pro',
+ object: 'response',
+ output: [],
+ status: 'in_progress',
+ },
+ type: 'response.created',
+ },
+ {
+ content_index: 0,
+ delta: content,
+ item_id: itemId,
+ output_index: 0,
+ type: 'response.output_text.delta',
+ },
+ {
+ content_index: 0,
+ item_id: itemId,
+ output_index: 0,
+ text: content,
+ type: 'response.output_text.done',
+ },
+ {
+ response: {
+ created_at: Math.floor(Date.now() / 1000),
+ id: responseId,
+ model: 'gpt-5-pro',
+ object: 'response',
+ output: [
+ { content: [{ text: content, type: 'output_text' }], role: 'assistant', type: 'message' },
+ ],
+ status: 'completed',
+ usage: {
+ input_tokens: 20,
+ output_tokens: 10,
+ total_tokens: 30,
+ },
+ },
+ type: 'response.completed',
+ },
+ ];
+
+ // Factory to create fresh async iterator (since each iterator can only be consumed once)
+ const createAsyncIterator = () => ({
+ [Symbol.asyncIterator]: async function* () {
+ for (const chunk of createChunks()) {
+ yield chunk;
+ }
+ },
+ toReadableStream: () =>
+ new ReadableStream({
+ start(controller) {
+ for (const chunk of createChunks()) {
+ controller.enqueue(chunk);
+ }
+ controller.close();
+ },
+ }),
+ });
+
+ // Main iterator with tee method
+ const mainIterator = createAsyncIterator();
+
+ // Add tee method that returns two independent iterators
+ return Object.assign(mainIterator, {
+ tee: () => [createAsyncIterator(), createAsyncIterator()],
+ });
+};
diff --git a/src/server/routers/lambda/__tests__/integration/message.integration.test.ts b/src/server/routers/lambda/__tests__/integration/message.integration.test.ts
index 25b4ad4dd29..cd423ad7504 100644
--- a/src/server/routers/lambda/__tests__/integration/message.integration.test.ts
+++ b/src/server/routers/lambda/__tests__/integration/message.integration.test.ts
@@ -36,12 +36,24 @@ describe('Message Router Integration Tests', () => {
let userId: string;
let testSessionId: string;
let testTopicId: string;
+ let testAgentId: string;
beforeEach(async () => {
serverDB = await getTestDB();
testDB = serverDB; // Set the test DB for the mock
userId = await createTestUser(serverDB);
+ // 创建测试 agent
+ const { agents } = await import('@/database/schemas');
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({
+ userId,
+ title: 'Test Agent',
+ })
+ .returning();
+ testAgentId = agent.id;
+
// 创建测试 session
const [session] = await serverDB
.insert(sessions)
@@ -52,6 +64,14 @@ describe('Message Router Integration Tests', () => {
.returning();
testSessionId = session.id;
+ // 创建 agent 到 session 的映射关系
+ const { agentsToSessions } = await import('@/database/schemas');
+ await serverDB.insert(agentsToSessions).values({
+ agentId: testAgentId,
+ sessionId: testSessionId,
+ userId,
+ });
+
// 创建测试 topic
const [topic] = await serverDB
.insert(topics)
@@ -88,7 +108,7 @@ describe('Message Router Integration Tests', () => {
expect(createdMessage).toBeDefined();
expect(createdMessage).toMatchObject({
id: result.id,
- sessionId: testSessionId,
+ agentId: testAgentId, // sessionId 会解析为 agentId 存储
topicId: testTopicId,
userId: userId,
content: 'Test message',
@@ -129,7 +149,7 @@ describe('Message Router Integration Tests', () => {
expect(createdMessage.threadId).toBe(thread.id);
expect(createdMessage).toMatchObject({
id: result.id,
- sessionId: testSessionId,
+ agentId: testAgentId,
topicId: testTopicId,
threadId: thread.id,
content: 'Test message in thread',
@@ -153,7 +173,7 @@ describe('Message Router Integration Tests', () => {
.where(eq(messages.id, result.id));
expect(createdMessage.topicId).toBeNull();
- expect(createdMessage.sessionId).toBe(testSessionId);
+ expect(createdMessage.agentId).toBe(testAgentId);
});
it('should fail when sessionId does not exist', async () => {
@@ -202,6 +222,298 @@ describe('Message Router Integration Tests', () => {
});
});
+ /**
+ * agentId 兼容性测试
+ *
+ * 测试 agentId → sessionId 解析功能
+ * 确保可以使用 agentId 替代 sessionId 进行操作
+ */
+ describe('agentId compatibility', () => {
+ describe('createMessage with agentId', () => {
+ it('should create message using agentId instead of sessionId', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const result = await caller.createMessage({
+ content: 'Message created with agentId',
+ role: 'user',
+ agentId: testAgentId,
+ // 不提供 sessionId,只使用 agentId
+ });
+
+ // 验证消息创建成功,且关联到正确的 sessionId
+ const [createdMessage] = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.id, result.id));
+
+ expect(createdMessage).toBeDefined();
+ expect(createdMessage.agentId).toBe(testAgentId);
+ expect(createdMessage.content).toBe('Message created with agentId');
+ });
+
+ it('should create message with agentId and topicId', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const result = await caller.createMessage({
+ content: 'Message with agentId and topicId',
+ role: 'user',
+ agentId: testAgentId,
+ topicId: testTopicId,
+ });
+
+ const [createdMessage] = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.id, result.id));
+
+ expect(createdMessage.agentId).toBe(testAgentId);
+ expect(createdMessage.topicId).toBe(testTopicId);
+ });
+
+ it('should prefer agentId over sessionId when both provided', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ // 创建另一个 session(不关联到 agent)
+ const [anotherSession] = await serverDB
+ .insert(sessions)
+ .values({
+ userId,
+ type: 'agent',
+ })
+ .returning();
+
+ const result = await caller.createMessage({
+ content: 'Message with both agentId and sessionId',
+ role: 'user',
+ agentId: testAgentId,
+ sessionId: anotherSession.id, // 这个会被 agentId 覆盖
+ });
+
+ const [createdMessage] = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.id, result.id));
+
+ // 应该使用提供的 agentId
+ expect(createdMessage.agentId).toBe(testAgentId);
+ });
+
+ it('should fail when agentId does not exist due to FK constraint', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ // 当 agentId 不存在时,应该因为外键约束而失败
+ await expect(
+ caller.createMessage({
+ content: 'Message with non-existent agentId',
+ role: 'user',
+ agentId: 'non-existent-agent-id',
+ }),
+ ).rejects.toThrow();
+ });
+ });
+
+ describe('removeMessage with agentId', () => {
+ it('should remove message using agentId and return updated list', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ // 创建两条消息
+ const msg1 = await caller.createMessage({
+ content: 'Message 1',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ const msg2 = await caller.createMessage({
+ content: 'Message 2',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ // 使用 agentId 删除消息
+ const result = await caller.removeMessage({
+ id: msg1.id,
+ agentId: testAgentId,
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages?.[0].id).toBe(msg2.id);
+ });
+ });
+
+ describe('removeMessages with agentId', () => {
+ it('should remove multiple messages using agentId', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const msg1 = await caller.createMessage({
+ content: 'Message 1',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ const msg2 = await caller.createMessage({
+ content: 'Message 2',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ const msg3 = await caller.createMessage({
+ content: 'Message 3',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ const result = await caller.removeMessages({
+ ids: [msg1.id, msg2.id],
+ agentId: testAgentId,
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages?.[0].id).toBe(msg3.id);
+ });
+ });
+
+ describe('update with agentId', () => {
+ it('should update message using agentId', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const msg = await caller.createMessage({
+ content: 'Original content',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ const result = await caller.update({
+ id: msg.id,
+ agentId: testAgentId,
+ value: { content: 'Updated via agentId' },
+ });
+
+ expect(result.success).toBe(true);
+
+ const [updatedMessage] = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.id, msg.id));
+
+ expect(updatedMessage.content).toBe('Updated via agentId');
+ });
+ });
+
+ describe('removeMessagesByAssistant with agentId', () => {
+ it('should remove messages by assistant using agentId', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ await caller.createMessage({
+ content: 'Message 1',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ await caller.createMessage({
+ content: 'Message 2',
+ role: 'assistant',
+ sessionId: testSessionId,
+ });
+
+ // 使用 agentId 删除 session 中的所有消息
+ await caller.removeMessagesByAssistant({
+ agentId: testAgentId,
+ });
+
+ const remainingMessages = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.agentId, testAgentId));
+
+ expect(remainingMessages).toHaveLength(0);
+ });
+
+ it('should remove messages in specific topic using agentId', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ // 在 topic 中创建消息
+ await caller.createMessage({
+ content: 'Message in topic',
+ role: 'user',
+ sessionId: testSessionId,
+ topicId: testTopicId,
+ });
+
+ // 在 session 中创建消息(不在 topic 中)
+ const msgOutside = await caller.createMessage({
+ content: 'Message outside topic',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ // 使用 agentId 和 topicId 删除
+ await caller.removeMessagesByAssistant({
+ agentId: testAgentId,
+ topicId: testTopicId,
+ });
+
+ const remainingMessages = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.agentId, testAgentId));
+
+ expect(remainingMessages).toHaveLength(1);
+ expect(remainingMessages[0].id).toBe(msgOutside.id);
+ });
+ });
+
+ describe('updatePluginState with agentId', () => {
+ it('should update plugin state using agentId', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const msg = await caller.createMessage({
+ content: 'Message with plugin',
+ role: 'assistant',
+ sessionId: testSessionId,
+ });
+
+ // 创建 plugin 记录
+ const { messagePlugins } = await import('@/database/schemas');
+ await serverDB.insert(messagePlugins).values({
+ id: msg.id,
+ userId,
+ toolCallId: 'test-tool-call-agentid',
+ type: 'default',
+ });
+
+ const result = await caller.updatePluginState({
+ id: msg.id,
+ agentId: testAgentId,
+ value: { testKey: 'testValue' },
+ });
+
+ expect(result.success).toBe(true);
+ });
+ });
+
+ describe('updateMetadata with agentId', () => {
+ it('should update metadata using agentId', async () => {
+ const caller = messageRouter.createCaller(createTestContext(userId));
+
+ const msg = await caller.createMessage({
+ content: 'Message with metadata',
+ role: 'user',
+ sessionId: testSessionId,
+ });
+
+ const result = await caller.updateMetadata({
+ id: msg.id,
+ agentId: testAgentId,
+ value: { customField: 'customValue' },
+ });
+
+ expect(result.success).toBe(true);
+ });
+ });
+ });
+
describe('getMessages', () => {
it('should return messages filtered by sessionId', async () => {
const caller = messageRouter.createCaller(createTestContext(userId));
@@ -384,7 +696,7 @@ describe('Message Router Integration Tests', () => {
const remainingMessages = await serverDB
.select()
.from(messages)
- .where(eq(messages.sessionId, testSessionId));
+ .where(eq(messages.agentId, testAgentId));
expect(remainingMessages).toHaveLength(0);
});
@@ -570,7 +882,7 @@ describe('Message Router Integration Tests', () => {
const remainingMessages = await serverDB
.select()
.from(messages)
- .where(eq(messages.sessionId, testSessionId));
+ .where(eq(messages.agentId, testAgentId));
expect(remainingMessages).toHaveLength(0);
});
@@ -599,11 +911,11 @@ describe('Message Router Integration Tests', () => {
topicId: testTopicId,
});
- // 验证 topic 中的消息已删除,但 session 中的其他消息仍存在
+ // 验证 topic 中的消息已删除,但其他消息仍存在
const remainingMessages = await serverDB
.select()
.from(messages)
- .where(eq(messages.sessionId, testSessionId));
+ .where(eq(messages.agentId, testAgentId));
expect(remainingMessages).toHaveLength(1);
expect(remainingMessages[0].id).toBe(msgOutsideTopicResult.id);
diff --git a/src/server/routers/lambda/__tests__/integration/topic.integration.test.ts b/src/server/routers/lambda/__tests__/integration/topic.integration.test.ts
new file mode 100644
index 00000000000..7cd8dce7048
--- /dev/null
+++ b/src/server/routers/lambda/__tests__/integration/topic.integration.test.ts
@@ -0,0 +1,777 @@
+// @vitest-environment node
+import { LobeChatDatabase } from '@lobechat/database';
+import { sessions, topics } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { topicRouter } from '../../topic';
+import { cleanupTestUser, createTestContext, createTestUser } from './setup';
+
+// We need to mock getServerDB to return our test database instance
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => testDB),
+}));
+
+// Mock next/server's after() to execute callback immediately in tests
+vi.mock('next/server', () => ({
+ after: vi.fn((callback: () => void) => callback()),
+}));
+
+/**
+ * Topic Router 集成测试
+ *
+ * 测试目标:
+ * 1. 验证完整的 tRPC 调用链路(Router → Model → Database)
+ * 2. 确保 agentId → sessionId 解析正常工作
+ * 3. 验证数据库约束和关联关系
+ */
+describe('Topic Router Integration Tests', () => {
+ let serverDB: LobeChatDatabase;
+ let userId: string;
+ let testSessionId: string;
+ let testAgentId: string;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+
+ // 创建测试 agent
+ const { agents } = await import('@/database/schemas');
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'Test Agent' })
+ .returning();
+ testAgentId = agent.id;
+
+ // 创建测试 session
+ const [session] = await serverDB.insert(sessions).values({ userId, type: 'agent' }).returning();
+ testSessionId = session.id;
+
+ // 创建 agent 到 session 的映射关系
+ const { agentsToSessions } = await import('@/database/schemas');
+ await serverDB.insert(agentsToSessions).values({
+ agentId: testAgentId,
+ sessionId: testSessionId,
+ userId,
+ });
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ });
+
+ describe('createTopic', () => {
+ it('should create topic with sessionId', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ const topicId = await caller.createTopic({
+ title: 'Test Topic',
+ sessionId: testSessionId,
+ });
+
+ const [createdTopic] = await serverDB.select().from(topics).where(eq(topics.id, topicId));
+
+ expect(createdTopic).toBeDefined();
+ expect(createdTopic.title).toBe('Test Topic');
+ expect(createdTopic.sessionId).toBe(testSessionId);
+ });
+
+ it('should create topic using agentId instead of sessionId', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ const topicId = await caller.createTopic({
+ title: 'Topic with agentId',
+ agentId: testAgentId,
+ });
+
+ const [createdTopic] = await serverDB.select().from(topics).where(eq(topics.id, topicId));
+
+ expect(createdTopic).toBeDefined();
+ expect(createdTopic.title).toBe('Topic with agentId');
+ // 验证 agentId 被正确解析为 sessionId
+ expect(createdTopic.sessionId).toBe(testSessionId);
+ });
+
+ it('should prefer agentId over sessionId when both provided', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ // 创建另一个 session
+ const [anotherSession] = await serverDB
+ .insert(sessions)
+ .values({
+ userId,
+ type: 'agent',
+ })
+ .returning();
+
+ const topicId = await caller.createTopic({
+ title: 'Topic with both ids',
+ agentId: testAgentId,
+ sessionId: anotherSession.id, // 这个会被 agentId 覆盖
+ });
+
+ const [createdTopic] = await serverDB.select().from(topics).where(eq(topics.id, topicId));
+
+ // 应该使用 agentId 解析出的 sessionId
+ expect(createdTopic.sessionId).toBe(testSessionId);
+ });
+
+ it('should fall back to sessionId when agentId not found', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ const topicId = await caller.createTopic({
+ title: 'Topic with non-existent agentId',
+ agentId: 'non-existent-agent',
+ sessionId: testSessionId,
+ });
+
+ const [createdTopic] = await serverDB.select().from(topics).where(eq(topics.id, topicId));
+
+ expect(createdTopic.sessionId).toBe(testSessionId);
+ });
+ });
+
+ describe('batchCreateTopics', () => {
+ it('should batch create topics with agentId', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ const result = await caller.batchCreateTopics([
+ { title: 'Batch Topic 1', agentId: testAgentId },
+ { title: 'Batch Topic 2', agentId: testAgentId },
+ ]);
+
+ expect(result.success).toBe(true);
+ expect(result.added).toBe(2);
+
+ const createdTopics = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.sessionId, testSessionId));
+
+ expect(createdTopics).toHaveLength(2);
+ expect(createdTopics.map((t) => t.title)).toContain('Batch Topic 1');
+ expect(createdTopics.map((t) => t.title)).toContain('Batch Topic 2');
+ });
+
+ it('should batch create topics with mixed agentId and sessionId', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ // 创建另一个 session
+ const [anotherSession] = await serverDB
+ .insert(sessions)
+ .values({
+ userId,
+ type: 'agent',
+ })
+ .returning();
+
+ const result = await caller.batchCreateTopics([
+ { title: 'Topic with agentId', agentId: testAgentId },
+ { title: 'Topic with sessionId', sessionId: anotherSession.id },
+ ]);
+
+ expect(result.success).toBe(true);
+ expect(result.added).toBe(2);
+
+ // 验证每个 topic 关联到正确的 session
+ const allTopics = await serverDB.select().from(topics).where(eq(topics.userId, userId));
+
+ const topicWithAgent = allTopics.find((t) => t.title === 'Topic with agentId');
+ const topicWithSession = allTopics.find((t) => t.title === 'Topic with sessionId');
+
+ expect(topicWithAgent?.sessionId).toBe(testSessionId);
+ expect(topicWithSession?.sessionId).toBe(anotherSession.id);
+ });
+ });
+
+ describe('getTopics', () => {
+ it('should get topics by agentId', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ // 创建测试 topic
+ await caller.createTopic({
+ title: 'Topic 1',
+ sessionId: testSessionId,
+ });
+
+ await caller.createTopic({
+ title: 'Topic 2',
+ sessionId: testSessionId,
+ });
+
+ // 使用 agentId 查询
+ const result = await caller.getTopics({
+ agentId: testAgentId,
+ });
+
+ // result 包含 items 和 total
+ expect(result.items).toHaveLength(2);
+ expect(result.items.map((t) => t.title)).toContain('Topic 1');
+ expect(result.items.map((t) => t.title)).toContain('Topic 2');
+ expect(result.total).toBe(2);
+ });
+
+ it('should resolve sessionId to agentId when only sessionId provided', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ // 创建测试 topic
+ await caller.createTopic({
+ title: 'Topic for reverse lookup',
+ sessionId: testSessionId,
+ });
+
+ // 使用 sessionId 查询(需要反向查找 agentId)
+ const result = await caller.getTopics({
+ sessionId: testSessionId,
+ });
+
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0].title).toBe('Topic for reverse lookup');
+ expect(result.total).toBe(1);
+ });
+ });
+
+ describe('batchDeleteBySessionId', () => {
+ it('should batch delete topics using agentId', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ // 创建测试 topics
+ await caller.createTopic({
+ title: 'Topic to delete 1',
+ sessionId: testSessionId,
+ });
+
+ await caller.createTopic({
+ title: 'Topic to delete 2',
+ sessionId: testSessionId,
+ });
+
+ // 使用 agentId 批量删除
+ await caller.batchDeleteBySessionId({
+ agentId: testAgentId,
+ });
+
+ const remainingTopics = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.sessionId, testSessionId));
+
+ expect(remainingTopics).toHaveLength(0);
+ });
+
+ it('should batch delete topics using sessionId', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ // 创建测试 topics
+ await caller.createTopic({
+ title: 'Topic to delete',
+ sessionId: testSessionId,
+ });
+
+ // 使用 sessionId 批量删除
+ await caller.batchDeleteBySessionId({
+ id: testSessionId,
+ });
+
+ const remainingTopics = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.sessionId, testSessionId));
+
+ expect(remainingTopics).toHaveLength(0);
+ });
+ });
+
+ describe('searchTopics', () => {
+ it('should search topics using agentId', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ // 创建测试 topics
+ await caller.createTopic({
+ title: 'TypeScript Discussion',
+ sessionId: testSessionId,
+ });
+
+ await caller.createTopic({
+ title: 'JavaScript Basics',
+ sessionId: testSessionId,
+ });
+
+ // 使用 agentId 搜索
+ const result = await caller.searchTopics({
+ keywords: 'TypeScript',
+ agentId: testAgentId,
+ });
+
+ expect(result.length).toBeGreaterThan(0);
+ expect(result[0].title).toContain('TypeScript');
+ });
+ });
+
+ describe('updateTopic', () => {
+ it('should update topic with agentId in value', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ // 创建测试 topic
+ const topicId = await caller.createTopic({
+ title: 'Original Title',
+ sessionId: testSessionId,
+ });
+
+ // 创建另一个 agent 和 session
+ const { agents, agentsToSessions } = await import('@/database/schemas');
+ const [newAgent] = await serverDB
+ .insert(agents)
+ .values({
+ userId,
+ title: 'New Agent',
+ })
+ .returning();
+
+ const [newSession] = await serverDB
+ .insert(sessions)
+ .values({
+ userId,
+ type: 'agent',
+ })
+ .returning();
+
+ await serverDB.insert(agentsToSessions).values({
+ agentId: newAgent.id,
+ sessionId: newSession.id,
+ userId,
+ });
+
+ // 更新 topic,使用 agentId 指定新的关联
+ await caller.updateTopic({
+ id: topicId,
+ value: {
+ title: 'Updated Title',
+ agentId: newAgent.id,
+ },
+ });
+
+ const [updatedTopic] = await serverDB.select().from(topics).where(eq(topics.id, topicId));
+
+ expect(updatedTopic.title).toBe('Updated Title');
+ expect(updatedTopic.sessionId).toBe(newSession.id);
+ });
+ });
+
+ describe('runtime migration - agentId backfill', () => {
+ it('should trigger migration for legacy topics (with sessionId but no agentId)', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ // Directly insert legacy topic with sessionId but no agentId (simulating old data)
+ const [legacyTopic] = await serverDB
+ .insert(topics)
+ .values({
+ title: 'Legacy Topic',
+ sessionId: testSessionId,
+ agentId: null, // Legacy data has no agentId
+ userId,
+ })
+ .returning();
+
+ // Verify the topic has no agentId initially
+ const [beforeMigration] = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.id, legacyTopic.id));
+ expect(beforeMigration.agentId).toBeNull();
+
+ // Query topics using agentId - this should trigger migration
+ const result = await caller.getTopics({
+ agentId: testAgentId,
+ });
+
+ // Should return the legacy topic
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0].id).toBe(legacyTopic.id);
+
+ // Wait a bit for the after() callback to execute
+ await new Promise((resolve) => setTimeout(resolve, 100));
+
+ // Verify the agentId was backfilled
+ const [afterMigration] = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.id, legacyTopic.id));
+ expect(afterMigration.agentId).toBe(testAgentId);
+ });
+
+ it('should not migrate topics that already have agentId', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ // Create topic with agentId already set
+ const [topicWithAgentId] = await serverDB
+ .insert(topics)
+ .values({
+ title: 'New Topic',
+ sessionId: testSessionId,
+ agentId: testAgentId, // Already has agentId
+ userId,
+ })
+ .returning();
+
+ // Query topics using agentId
+ await caller.getTopics({
+ agentId: testAgentId,
+ });
+
+ // Wait for potential migration
+ await new Promise((resolve) => setTimeout(resolve, 100));
+
+ // Verify the agentId is unchanged
+ const [afterQuery] = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.id, topicWithAgentId.id));
+ expect(afterQuery.agentId).toBe(testAgentId);
+ });
+
+ it('should migrate multiple legacy topics in batch', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ // Insert multiple legacy topics
+ const legacyTopics = await serverDB
+ .insert(topics)
+ .values([
+ { title: 'Legacy 1', sessionId: testSessionId, agentId: null, userId },
+ { title: 'Legacy 2', sessionId: testSessionId, agentId: null, userId },
+ { title: 'Legacy 3', sessionId: testSessionId, agentId: null, userId },
+ ])
+ .returning();
+
+ // Query topics using agentId
+ const result = await caller.getTopics({
+ agentId: testAgentId,
+ });
+
+ expect(result.items).toHaveLength(3);
+
+ // Wait for migration
+ await new Promise((resolve) => setTimeout(resolve, 100));
+
+ // Verify all topics were migrated
+ for (const topic of legacyTopics) {
+ const [migrated] = await serverDB.select().from(topics).where(eq(topics.id, topic.id));
+ expect(migrated.agentId).toBe(testAgentId);
+ }
+ });
+
+ it('should only migrate topics that match the query', async () => {
+ // Create another agent and session
+ const { agents, agentsToSessions } = await import('@/database/schemas');
+ const [otherAgent] = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'Other Agent' })
+ .returning();
+
+ const [otherSession] = await serverDB
+ .insert(sessions)
+ .values({ userId, type: 'agent' })
+ .returning();
+
+ await serverDB.insert(agentsToSessions).values({
+ agentId: otherAgent.id,
+ sessionId: otherSession.id,
+ userId,
+ });
+
+ // Insert legacy topics for different sessions
+ const [topic1] = await serverDB
+ .insert(topics)
+ .values({ title: 'Topic 1', sessionId: testSessionId, agentId: null, userId })
+ .returning();
+
+ const [topic2] = await serverDB
+ .insert(topics)
+ .values({ title: 'Topic 2', sessionId: otherSession.id, agentId: null, userId })
+ .returning();
+
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ // Query only for testAgentId
+ await caller.getTopics({ agentId: testAgentId });
+
+ // Wait for migration
+ await new Promise((resolve) => setTimeout(resolve, 100));
+
+ // Only topic1 should be migrated
+ const [migrated1] = await serverDB.select().from(topics).where(eq(topics.id, topic1.id));
+ const [migrated2] = await serverDB.select().from(topics).where(eq(topics.id, topic2.id));
+
+ expect(migrated1.agentId).toBe(testAgentId);
+ expect(migrated2.agentId).toBeNull(); // Should not be migrated
+ });
+ });
+
+ describe('inbox agent queries', () => {
+ let inboxAgentId: string;
+
+ beforeEach(async () => {
+ // Create an inbox agent (virtual agent with slug='inbox')
+ const { agents } = await import('@/database/schemas');
+ const [inboxAgent] = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'Inbox Agent', slug: 'inbox', virtual: true })
+ .returning();
+ inboxAgentId = inboxAgent.id;
+ });
+
+ it('should query legacy inbox topics with isInbox=true', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ // Insert legacy inbox topic (sessionId IS NULL, groupId IS NULL, agentId IS NULL)
+ await serverDB.insert(topics).values({
+ title: 'Legacy Inbox Topic',
+ sessionId: null,
+ groupId: null,
+ agentId: null,
+ userId,
+ });
+
+ // Query with isInbox=true
+ const result = await caller.getTopics({
+ agentId: inboxAgentId,
+ isInbox: true,
+ });
+
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0].title).toBe('Legacy Inbox Topic');
+ });
+
+ it('should query both legacy inbox topics and new inbox topics', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ // Insert legacy inbox topic
+ await serverDB.insert(topics).values({
+ title: 'Legacy Inbox Topic',
+ sessionId: null,
+ groupId: null,
+ agentId: null,
+ userId,
+ });
+
+ // Insert new inbox topic with agentId
+ await serverDB.insert(topics).values({
+ title: 'New Inbox Topic',
+ sessionId: null,
+ groupId: null,
+ agentId: inboxAgentId,
+ userId,
+ });
+
+ // Query with isInbox=true
+ const result = await caller.getTopics({
+ agentId: inboxAgentId,
+ isInbox: true,
+ });
+
+ expect(result.items).toHaveLength(2);
+ expect(result.items.map((t) => t.title)).toContain('Legacy Inbox Topic');
+ expect(result.items.map((t) => t.title)).toContain('New Inbox Topic');
+ });
+
+ it('should migrate legacy inbox topics when queried', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ // Insert legacy inbox topic
+ const [legacyTopic] = await serverDB
+ .insert(topics)
+ .values({
+ title: 'Legacy Inbox to Migrate',
+ sessionId: null,
+ groupId: null,
+ agentId: null,
+ userId,
+ })
+ .returning();
+
+ // Query with isInbox=true
+ await caller.getTopics({
+ agentId: inboxAgentId,
+ isInbox: true,
+ });
+
+ // Wait for migration
+ await new Promise((resolve) => setTimeout(resolve, 100));
+
+ // Verify agentId was backfilled
+ const [migrated] = await serverDB.select().from(topics).where(eq(topics.id, legacyTopic.id));
+ expect(migrated.agentId).toBe(inboxAgentId);
+ });
+
+ it('should not include legacy inbox topics when isInbox=false', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ // Insert legacy inbox topic
+ await serverDB.insert(topics).values({
+ title: 'Legacy Inbox Topic',
+ sessionId: null,
+ groupId: null,
+ agentId: null,
+ userId,
+ });
+
+ // Query without isInbox (default is false/undefined)
+ // Using testAgentId instead since it has a proper session mapping
+ const result = await caller.getTopics({
+ agentId: testAgentId,
+ });
+
+ // Legacy inbox topic should NOT be included
+ expect(result.items.some((t) => t.title === 'Legacy Inbox Topic')).toBe(false);
+ });
+
+ it('should not return sessionId/agentId in items for inbox queries', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ // Insert inbox topic with agentId
+ await serverDB.insert(topics).values({
+ title: 'Inbox Topic',
+ sessionId: null,
+ groupId: null,
+ agentId: inboxAgentId,
+ userId,
+ });
+
+ // Query with isInbox=true
+ const result = await caller.getTopics({
+ agentId: inboxAgentId,
+ isInbox: true,
+ });
+
+ expect(result.items).toHaveLength(1);
+ // Verify internal fields are not exposed
+ expect('sessionId' in result.items[0]).toBe(false);
+ expect('agentId' in result.items[0]).toBe(false);
+ });
+ });
+
+ describe('other topic operations', () => {
+ it('should clone topic', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ // 创建原始 topic
+ const originalId = await caller.createTopic({
+ title: 'Original Topic',
+ sessionId: testSessionId,
+ });
+
+ // 克隆 topic
+ const clonedId = await caller.cloneTopic({
+ id: originalId,
+ newTitle: 'Cloned Topic',
+ });
+
+ const [clonedTopic] = await serverDB.select().from(topics).where(eq(topics.id, clonedId));
+
+ expect(clonedTopic).toBeDefined();
+ expect(clonedTopic.title).toBe('Cloned Topic');
+ expect(clonedTopic.sessionId).toBe(testSessionId);
+ });
+
+ it('should batch delete topics by ids', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ const id1 = await caller.createTopic({
+ title: 'Topic 1',
+ sessionId: testSessionId,
+ });
+
+ const id2 = await caller.createTopic({
+ title: 'Topic 2',
+ sessionId: testSessionId,
+ });
+
+ await caller.createTopic({
+ title: 'Topic 3',
+ sessionId: testSessionId,
+ });
+
+ // 删除前两个
+ await caller.batchDelete({ ids: [id1, id2] });
+
+ const remainingTopics = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.sessionId, testSessionId));
+
+ expect(remainingTopics).toHaveLength(1);
+ expect(remainingTopics[0].title).toBe('Topic 3');
+ });
+
+ it('should remove single topic', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ const topicId = await caller.createTopic({
+ title: 'Topic to remove',
+ sessionId: testSessionId,
+ });
+
+ await caller.removeTopic({ id: topicId });
+
+ const deletedTopic = await serverDB.select().from(topics).where(eq(topics.id, topicId));
+
+ expect(deletedTopic).toHaveLength(0);
+ });
+
+ it('should count topics', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ await caller.createTopic({
+ title: 'Topic 1',
+ sessionId: testSessionId,
+ });
+
+ await caller.createTopic({
+ title: 'Topic 2',
+ sessionId: testSessionId,
+ });
+
+ const count = await caller.countTopics();
+
+ expect(count).toBe(2);
+ });
+
+ it('should get all topics', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ await caller.createTopic({
+ title: 'Topic 1',
+ sessionId: testSessionId,
+ });
+
+ await caller.createTopic({
+ title: 'Topic 2',
+ sessionId: testSessionId,
+ });
+
+ const allTopics = await caller.getAllTopics();
+
+ expect(allTopics).toHaveLength(2);
+ });
+
+ it('should check if user has topics', async () => {
+ const caller = topicRouter.createCaller(createTestContext(userId));
+
+ // 初始应该没有 topics
+ const hasNoTopics = await caller.hasTopics();
+ expect(hasNoTopics).toBe(true); // 注意:hasTopics 返回 count === 0
+
+ // 创建 topic 后
+ await caller.createTopic({
+ title: 'First Topic',
+ sessionId: testSessionId,
+ });
+
+ const hasTopicsAfter = await caller.hasTopics();
+ expect(hasTopicsAfter).toBe(false); // count !== 0
+ });
+ });
+});
diff --git a/src/server/routers/lambda/__tests__/message.test.ts b/src/server/routers/lambda/__tests__/message.test.ts
index 97270c06ef2..8e6caa73bfa 100644
--- a/src/server/routers/lambda/__tests__/message.test.ts
+++ b/src/server/routers/lambda/__tests__/message.test.ts
@@ -239,4 +239,111 @@ describe('messageRouter', () => {
fileChunks: [{ id: 'c1', similarity: 0.9 }],
});
});
+
+ describe('agentId support', () => {
+ it('should handle createMessage with agentId', async () => {
+ const mockCreate = vi.fn().mockResolvedValue({ id: 'msg1' });
+ vi.mocked(MessageModel).mockImplementation(
+ () =>
+ ({
+ create: mockCreate,
+ }) as any,
+ );
+
+ const input: CreateMessageParams = {
+ agentId: 'agent1',
+ content: 'test',
+ role: 'user',
+ sessionId: 'session1',
+ };
+
+ const ctx = {
+ messageModel: new MessageModel({} as any, 'user1'),
+ };
+
+ const result = await ctx.messageModel.create(input);
+
+ expect(mockCreate).toHaveBeenCalledWith(input);
+ expect(result.id).toBe('msg1');
+ });
+
+ it('should handle getMessages with agentId', async () => {
+ const mockQuery = vi.fn().mockResolvedValue([{ id: 'msg1' }]);
+ const mockGetFullFileUrl = vi
+ .fn()
+ .mockImplementation((path: string | null) => Promise.resolve('url'));
+
+ vi.mocked(MessageModel).mockImplementation(
+ () =>
+ ({
+ query: mockQuery,
+ }) as any,
+ );
+
+ vi.mocked(FileService).mockImplementation(
+ () =>
+ ({
+ getFullFileUrl: mockGetFullFileUrl,
+ }) as any,
+ );
+
+ const input = { agentId: 'agent1', sessionId: 'session1' };
+ const ctx = {
+ messageModel: new MessageModel({} as any, 'user1'),
+ fileService: new FileService({} as any, 'user1'),
+ };
+
+ const result = await ctx.messageModel.query(input, {
+ postProcessUrl: mockGetFullFileUrl,
+ });
+
+ expect(mockQuery).toHaveBeenCalledWith(input, expect.any(Object));
+ expect(result).toEqual([{ id: 'msg1' }]);
+ });
+
+ it('should handle getMessages with agentId only (no sessionId)', async () => {
+ const mockQuery = vi.fn().mockResolvedValue([{ id: 'msg1' }]);
+ const mockGetFullFileUrl = vi
+ .fn()
+ .mockImplementation((path: string | null) => Promise.resolve('url'));
+
+ vi.mocked(MessageModel).mockImplementation(
+ () =>
+ ({
+ query: mockQuery,
+ }) as any,
+ );
+
+ const input = { agentId: 'agent1' };
+ const ctx = {
+ messageModel: new MessageModel({} as any, 'user1'),
+ };
+
+ const result = await ctx.messageModel.query(input, {
+ postProcessUrl: mockGetFullFileUrl,
+ });
+
+ expect(mockQuery).toHaveBeenCalledWith(input, expect.any(Object));
+ expect(result).toEqual([{ id: 'msg1' }]);
+ });
+
+ it('should handle batchDeleteByAgentId', async () => {
+ const mockBatchDeleteByAgentId = vi.fn().mockResolvedValue({ rowCount: 5 });
+ vi.mocked(MessageModel).mockImplementation(
+ () =>
+ ({
+ batchDeleteByAgentId: mockBatchDeleteByAgentId,
+ }) as any,
+ );
+
+ const ctx = {
+ messageModel: new MessageModel({} as any, 'user1'),
+ };
+
+ const result = await ctx.messageModel.batchDeleteByAgentId('agent1');
+
+ expect(mockBatchDeleteByAgentId).toHaveBeenCalledWith('agent1');
+ expect(result.rowCount).toBe(5);
+ });
+ });
});
diff --git a/src/server/routers/lambda/__tests__/topic.test.ts b/src/server/routers/lambda/__tests__/topic.test.ts
new file mode 100644
index 00000000000..14f333e608e
--- /dev/null
+++ b/src/server/routers/lambda/__tests__/topic.test.ts
@@ -0,0 +1,263 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { TopicModel } from '@/database/models/topic';
+
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn(),
+}));
+
+vi.mock('@/database/server', () => ({
+ getServerDB: vi.fn(),
+}));
+
+describe('topicRouter', () => {
+ it('should handle createTopic with sessionId', async () => {
+ const mockCreate = vi.fn().mockResolvedValue({ id: 'topic1' });
+ vi.mocked(TopicModel).mockImplementation(
+ () =>
+ ({
+ create: mockCreate,
+ }) as any,
+ );
+
+ const input = {
+ sessionId: 'session1',
+ title: 'Test Topic',
+ };
+
+ const ctx = {
+ topicModel: new TopicModel({} as any, 'user1'),
+ };
+
+ const result = await ctx.topicModel.create(input);
+
+ expect(mockCreate).toHaveBeenCalledWith(input);
+ expect(result.id).toBe('topic1');
+ });
+
+ it('should handle getTopics with groupId', async () => {
+ const mockQuery = vi
+ .fn()
+ .mockResolvedValue({ items: [{ id: 'topic1', title: 'Test' }], total: 1 });
+ vi.mocked(TopicModel).mockImplementation(
+ () =>
+ ({
+ query: mockQuery,
+ }) as any,
+ );
+
+ const input = { groupId: 'group1' };
+ const ctx = {
+ topicModel: new TopicModel({} as any, 'user1'),
+ };
+
+ const result = await ctx.topicModel.query(input);
+
+ expect(mockQuery).toHaveBeenCalledWith(input);
+ expect(result).toEqual({ items: [{ id: 'topic1', title: 'Test' }], total: 1 });
+ });
+
+ it('should handle deleteTopic', async () => {
+ const mockDelete = vi.fn().mockResolvedValue(undefined);
+ vi.mocked(TopicModel).mockImplementation(
+ () =>
+ ({
+ delete: mockDelete,
+ }) as any,
+ );
+
+ const ctx = {
+ topicModel: new TopicModel({} as any, 'user1'),
+ };
+
+ await ctx.topicModel.delete('topic1');
+
+ expect(mockDelete).toHaveBeenCalledWith('topic1');
+ });
+
+ it('should handle updateTopic', async () => {
+ const mockUpdate = vi.fn().mockResolvedValue({ success: true });
+ vi.mocked(TopicModel).mockImplementation(
+ () =>
+ ({
+ update: mockUpdate,
+ }) as any,
+ );
+
+ const ctx = {
+ topicModel: new TopicModel({} as any, 'user1'),
+ };
+
+ const result = await ctx.topicModel.update('topic1', { title: 'Updated Title' });
+
+ expect(mockUpdate).toHaveBeenCalledWith('topic1', { title: 'Updated Title' });
+ expect(result).toEqual({ success: true });
+ });
+
+ it('should handle batchDelete', async () => {
+ const mockBatchDelete = vi.fn().mockResolvedValue({ rowCount: 3 });
+ vi.mocked(TopicModel).mockImplementation(
+ () =>
+ ({
+ batchDelete: mockBatchDelete,
+ }) as any,
+ );
+
+ const ctx = {
+ topicModel: new TopicModel({} as any, 'user1'),
+ };
+
+ const result = await ctx.topicModel.batchDelete(['topic1', 'topic2', 'topic3']);
+
+ expect(mockBatchDelete).toHaveBeenCalledWith(['topic1', 'topic2', 'topic3']);
+ expect(result.rowCount).toBe(3);
+ });
+
+ it('should handle countTopics', async () => {
+ const mockCount = vi.fn().mockResolvedValue(10);
+ vi.mocked(TopicModel).mockImplementation(
+ () =>
+ ({
+ count: mockCount,
+ }) as any,
+ );
+
+ const ctx = {
+ topicModel: new TopicModel({} as any, 'user1'),
+ };
+
+ const result = await ctx.topicModel.count();
+
+ expect(mockCount).toHaveBeenCalled();
+ expect(result).toBe(10);
+ });
+
+ describe('agentId support', () => {
+ it('should handle createTopic with agentId', async () => {
+ const mockCreate = vi.fn().mockResolvedValue({ id: 'topic1' });
+ vi.mocked(TopicModel).mockImplementation(
+ () =>
+ ({
+ create: mockCreate,
+ }) as any,
+ );
+
+ const input = {
+ agentId: 'agent1',
+ sessionId: 'session1',
+ title: 'Test Topic',
+ };
+
+ const ctx = {
+ topicModel: new TopicModel({} as any, 'user1'),
+ };
+
+ const result = await ctx.topicModel.create(input);
+
+ expect(mockCreate).toHaveBeenCalledWith(input);
+ expect(result.id).toBe('topic1');
+ });
+
+ it('should handle getTopics with agentId', async () => {
+ const mockQuery = vi.fn().mockResolvedValue([{ id: 'topic1', title: 'Test' }]);
+ vi.mocked(TopicModel).mockImplementation(
+ () =>
+ ({
+ query: mockQuery,
+ }) as any,
+ );
+
+ const input = { agentId: 'agent1' };
+ const ctx = {
+ topicModel: new TopicModel({} as any, 'user1'),
+ };
+
+ const result = await ctx.topicModel.query(input);
+
+ expect(mockQuery).toHaveBeenCalledWith(input);
+ expect(result).toEqual([{ id: 'topic1', title: 'Test' }]);
+ });
+
+ it('should handle getTopics with both agentId and sessionId', async () => {
+ const mockQuery = vi.fn().mockResolvedValue([{ id: 'topic1', title: 'Test' }]);
+ vi.mocked(TopicModel).mockImplementation(
+ () =>
+ ({
+ query: mockQuery,
+ }) as any,
+ );
+
+ const input = { agentId: 'agent1', sessionId: 'session1' };
+ const ctx = {
+ topicModel: new TopicModel({} as any, 'user1'),
+ };
+
+ const result = await ctx.topicModel.query(input);
+
+ expect(mockQuery).toHaveBeenCalledWith(input);
+ expect(result).toEqual([{ id: 'topic1', title: 'Test' }]);
+ });
+
+ it('should handle batchDeleteByAgentId', async () => {
+ const mockBatchDeleteByAgentId = vi.fn().mockResolvedValue({ rowCount: 5 });
+ vi.mocked(TopicModel).mockImplementation(
+ () =>
+ ({
+ batchDeleteByAgentId: mockBatchDeleteByAgentId,
+ }) as any,
+ );
+
+ const ctx = {
+ topicModel: new TopicModel({} as any, 'user1'),
+ };
+
+ const result = await ctx.topicModel.batchDeleteByAgentId('agent1');
+
+ expect(mockBatchDeleteByAgentId).toHaveBeenCalledWith('agent1');
+ expect(result.rowCount).toBe(5);
+ });
+
+ it('should handle batchCreateTopics with agentId', async () => {
+ const mockBatchCreate = vi.fn().mockResolvedValue([{ id: 'topic1' }, { id: 'topic2' }]);
+ vi.mocked(TopicModel).mockImplementation(
+ () =>
+ ({
+ batchCreate: mockBatchCreate,
+ }) as any,
+ );
+
+ const input = [
+ { agentId: 'agent1', sessionId: 'session1', title: 'Topic 1' },
+ { agentId: 'agent1', sessionId: 'session1', title: 'Topic 2' },
+ ];
+
+ const ctx = {
+ topicModel: new TopicModel({} as any, 'user1'),
+ };
+
+ const result = await ctx.topicModel.batchCreate(input as any);
+
+ expect(mockBatchCreate).toHaveBeenCalledWith(input);
+ expect(result).toHaveLength(2);
+ });
+
+ it('should handle searchTopics with agentId', async () => {
+ const mockQueryByKeyword = vi.fn().mockResolvedValue([{ id: 'topic1', title: 'Test' }]);
+ vi.mocked(TopicModel).mockImplementation(
+ () =>
+ ({
+ queryByKeyword: mockQueryByKeyword,
+ }) as any,
+ );
+
+ const ctx = {
+ topicModel: new TopicModel({} as any, 'user1'),
+ };
+
+ const result = await ctx.topicModel.queryByKeyword('test', 'session1');
+
+ expect(mockQueryByKeyword).toHaveBeenCalledWith('test', 'session1');
+ expect(result).toEqual([{ id: 'topic1', title: 'Test' }]);
+ });
+ });
+});
diff --git a/src/server/routers/lambda/_helpers/resolveContext.test.ts b/src/server/routers/lambda/_helpers/resolveContext.test.ts
new file mode 100644
index 00000000000..3d9211668c2
--- /dev/null
+++ b/src/server/routers/lambda/_helpers/resolveContext.test.ts
@@ -0,0 +1,251 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ batchResolveAgentIdFromSessions,
+ resolveAgentIdFromSession,
+ resolveContext,
+} from './resolveContext';
+
+// Mock the database module
+vi.mock('@/database/schemas', () => ({
+ agentsToSessions: {
+ agentId: 'agent_id',
+ sessionId: 'session_id',
+ userId: 'user_id',
+ },
+}));
+
+describe('resolveContext', () => {
+ const mockUserId = 'user-1';
+
+ // Helper to create a mock database
+ const createMockDb = (queryResult: any[] = []) => {
+ const mockLimit = vi.fn().mockResolvedValue(queryResult);
+ const mockWhere = vi.fn().mockReturnValue({ limit: mockLimit });
+ const mockFrom = vi.fn().mockReturnValue({ where: mockWhere });
+ const mockSelect = vi.fn().mockReturnValue({ from: mockFrom });
+
+ return {
+ select: mockSelect,
+ _mocks: { mockSelect, mockFrom, mockWhere, mockLimit },
+ } as any;
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('resolveContext', () => {
+ it('should return sessionId when only sessionId is provided', async () => {
+ const mockDb = createMockDb([]);
+
+ const result = await resolveContext(
+ { sessionId: 'session-1', topicId: 'topic-1' },
+ mockDb,
+ mockUserId,
+ );
+
+ expect(result).toEqual({
+ agentId: null,
+ groupId: null,
+ sessionId: 'session-1',
+ threadId: null,
+ topicId: 'topic-1',
+ });
+ // Should not query database when no agentId
+ expect(mockDb.select).not.toHaveBeenCalled();
+ });
+
+ it('should resolve agentId to sessionId when agentId is provided', async () => {
+ const mockDb = createMockDb([{ sessionId: 'resolved-session-1' }]);
+
+ const result = await resolveContext({ agentId: 'agent-1' }, mockDb, mockUserId);
+
+ expect(result.sessionId).toBe('resolved-session-1');
+ expect(mockDb.select).toHaveBeenCalled();
+ });
+
+ it('should prefer agentId over sessionId when both are provided', async () => {
+ const mockDb = createMockDb([{ sessionId: 'resolved-from-agent' }]);
+
+ const result = await resolveContext(
+ { agentId: 'agent-1', sessionId: 'original-session' },
+ mockDb,
+ mockUserId,
+ );
+
+ // Should use the sessionId resolved from agentId, not the provided sessionId
+ expect(result.sessionId).toBe('resolved-from-agent');
+ });
+
+ it('should return null sessionId when agentId is not found in database', async () => {
+ const mockDb = createMockDb([]); // Empty result
+
+ const result = await resolveContext({ agentId: 'non-existent-agent' }, mockDb, mockUserId);
+
+ // When agentId doesn't exist and no sessionId provided, should return null
+ expect(result.sessionId).toBeNull();
+ });
+
+ it('should fall back to provided sessionId when agentId is not found', async () => {
+ const mockDb = createMockDb([]); // Empty result - agentId not found
+
+ const result = await resolveContext(
+ { agentId: 'non-existent-agent', sessionId: 'fallback-session' },
+ mockDb,
+ mockUserId,
+ );
+
+ // When agentId doesn't resolve, keep the original sessionId
+ expect(result.sessionId).toBe('fallback-session');
+ });
+
+ it('should pass through all context fields correctly', async () => {
+ const mockDb = createMockDb([]);
+
+ const result = await resolveContext(
+ {
+ sessionId: 'session-1',
+ topicId: 'topic-1',
+ threadId: 'thread-1',
+ groupId: 'group-1',
+ },
+ mockDb,
+ mockUserId,
+ );
+
+ expect(result).toEqual({
+ agentId: null,
+ sessionId: 'session-1',
+ topicId: 'topic-1',
+ threadId: 'thread-1',
+ groupId: 'group-1',
+ });
+ });
+
+ it('should handle null values in input', async () => {
+ const mockDb = createMockDb([]);
+
+ const result = await resolveContext(
+ {
+ sessionId: null,
+ topicId: null,
+ threadId: null,
+ groupId: null,
+ },
+ mockDb,
+ mockUserId,
+ );
+
+ expect(result).toEqual({
+ agentId: null,
+ sessionId: null,
+ topicId: null,
+ threadId: null,
+ groupId: null,
+ });
+ });
+
+ it('should handle undefined values in input', async () => {
+ const mockDb = createMockDb([]);
+
+ const result = await resolveContext({}, mockDb, mockUserId);
+
+ expect(result).toEqual({
+ agentId: null,
+ sessionId: null,
+ topicId: null,
+ threadId: null,
+ groupId: null,
+ });
+ });
+ });
+
+ describe('resolveAgentIdFromSession', () => {
+ it('should resolve sessionId to agentId', async () => {
+ const mockDb = createMockDb([{ agentId: 'resolved-agent-1' }]);
+
+ const result = await resolveAgentIdFromSession('session-1', mockDb, mockUserId);
+
+ expect(result).toBe('resolved-agent-1');
+ expect(mockDb.select).toHaveBeenCalled();
+ });
+
+ it('should return undefined when sessionId is not found', async () => {
+ const mockDb = createMockDb([]); // Empty result
+
+ const result = await resolveAgentIdFromSession('non-existent-session', mockDb, mockUserId);
+
+ expect(result).toBeUndefined();
+ });
+
+ it('should query with correct userId filter', async () => {
+ const mockLimit = vi.fn().mockResolvedValue([{ agentId: 'agent-1' }]);
+ const mockWhere = vi.fn().mockReturnValue({ limit: mockLimit });
+ const mockFrom = vi.fn().mockReturnValue({ where: mockWhere });
+ const mockSelect = vi.fn().mockReturnValue({ from: mockFrom });
+ const mockDb = { select: mockSelect } as any;
+
+ await resolveAgentIdFromSession('session-1', mockDb, 'specific-user');
+
+ expect(mockWhere).toHaveBeenCalled();
+ // The where clause should be called with userId filter
+ });
+ });
+
+ describe('batchResolveAgentIdFromSessions', () => {
+ // Helper to create a mock database for batch queries (no limit)
+ const createBatchMockDb = (queryResult: any[] = []) => {
+ const mockWhere = vi.fn().mockResolvedValue(queryResult);
+ const mockFrom = vi.fn().mockReturnValue({ where: mockWhere });
+ const mockSelect = vi.fn().mockReturnValue({ from: mockFrom });
+
+ return {
+ select: mockSelect,
+ _mocks: { mockSelect, mockFrom, mockWhere },
+ } as any;
+ };
+
+ it('should return empty map when sessionIds is empty', async () => {
+ const mockDb = createBatchMockDb([]);
+
+ const result = await batchResolveAgentIdFromSessions([], mockDb, 'user-1');
+
+ expect(result).toBeInstanceOf(Map);
+ expect(result.size).toBe(0);
+ expect(mockDb.select).not.toHaveBeenCalled();
+ });
+
+ it('should resolve multiple sessionIds to agentIds', async () => {
+ const mockDb = createBatchMockDb([
+ { sessionId: 'session-1', agentId: 'agent-1' },
+ { sessionId: 'session-2', agentId: 'agent-2' },
+ ]);
+
+ const result = await batchResolveAgentIdFromSessions(
+ ['session-1', 'session-2'],
+ mockDb,
+ 'user-1',
+ );
+
+ expect(result).toBeInstanceOf(Map);
+ expect(result.size).toBe(2);
+ expect(result.get('session-1')).toBe('agent-1');
+ expect(result.get('session-2')).toBe('agent-2');
+ });
+
+ it('should handle partial matches', async () => {
+ const mockDb = createBatchMockDb([{ sessionId: 'session-1', agentId: 'agent-1' }]);
+
+ const result = await batchResolveAgentIdFromSessions(
+ ['session-1', 'session-not-found'],
+ mockDb,
+ 'user-1',
+ );
+
+ expect(result.size).toBe(1);
+ expect(result.get('session-1')).toBe('agent-1');
+ expect(result.get('session-not-found')).toBeUndefined();
+ });
+ });
+});
diff --git a/src/server/routers/lambda/_helpers/resolveContext.ts b/src/server/routers/lambda/_helpers/resolveContext.ts
new file mode 100644
index 00000000000..466f41cf7a1
--- /dev/null
+++ b/src/server/routers/lambda/_helpers/resolveContext.ts
@@ -0,0 +1,103 @@
+import { and, eq, inArray } from 'drizzle-orm';
+
+import { agentsToSessions } from '@/database/schemas';
+import { LobeChatDatabase } from '@/database/type';
+
+import { ConversationContextInput } from '../_schema/context';
+
+export interface ResolvedContext {
+ agentId: string | null;
+ groupId: string | null;
+ sessionId: string | null;
+ threadId: string | null;
+ topicId: string | null;
+}
+
+/**
+ * 解析会话上下文
+ *
+ * 将 agentId 解析为 sessionId(如果提供了 agentId)
+ * 优先级:agentId > sessionId
+ *
+ * @param input - 输入的上下文参数
+ * @param db - 数据库实例
+ * @param userId - 用户 ID
+ * @returns 解析后的上下文,sessionId 已从 agentId 解析
+ */
+export const resolveContext = async (
+ input: ConversationContextInput,
+ db: LobeChatDatabase,
+ userId: string,
+): Promise<ResolvedContext> => {
+ let resolvedSessionId: string | null = input.sessionId ?? null;
+
+ // 如果提供了 agentId,优先从 agentsToSessions 表查找对应的 sessionId
+ if (input.agentId) {
+ const [relation] = await db
+ .select({ sessionId: agentsToSessions.sessionId })
+ .from(agentsToSessions)
+ .where(and(eq(agentsToSessions.agentId, input.agentId), eq(agentsToSessions.userId, userId)))
+ .limit(1);
+
+ if (relation) {
+ resolvedSessionId = relation.sessionId;
+ }
+ }
+
+ return {
+ agentId: input.agentId ?? null,
+ groupId: input.groupId ?? null,
+ sessionId: resolvedSessionId,
+ threadId: input.threadId ?? null,
+ topicId: input.topicId ?? null,
+ };
+};
+
+/**
+ * 反向解析:从 sessionId 获取 agentId
+ *
+ * 用于 Topic Router 等需要 agentId 进行查询的场景
+ *
+ * @param sessionId - session ID
+ * @param db - 数据库实例
+ * @param userId - 用户 ID
+ * @returns agentId 或 undefined
+ */
+export const resolveAgentIdFromSession = async (
+ sessionId: string,
+ db: LobeChatDatabase,
+ userId: string,
+): Promise<string | undefined> => {
+ const [relation] = await db
+ .select({ agentId: agentsToSessions.agentId })
+ .from(agentsToSessions)
+ .where(and(eq(agentsToSessions.sessionId, sessionId), eq(agentsToSessions.userId, userId)))
+ .limit(1);
+
+ return relation?.agentId;
+};
+
+/**
+ * 批量反向解析:从多个 sessionId 获取 agentId 映射
+ *
+ * 用于需要批量解析 sessionId -> agentId 的场景(如 recentTopics)
+ *
+ * @param sessionIds - session ID 数组
+ * @param db - 数据库实例
+ * @param userId - 用户 ID
+ * @returns sessionId -> agentId 的映射 Map
+ */
+export const batchResolveAgentIdFromSessions = async (
+ sessionIds: string[],
+ db: LobeChatDatabase,
+ userId: string,
+): Promise<Map<string, string>> => {
+ if (sessionIds.length === 0) return new Map();
+
+ const relations = await db
+ .select({ agentId: agentsToSessions.agentId, sessionId: agentsToSessions.sessionId })
+ .from(agentsToSessions)
+ .where(and(eq(agentsToSessions.userId, userId), inArray(agentsToSessions.sessionId, sessionIds)));
+
+ return new Map(relations.map((r) => [r.sessionId, r.agentId]));
+};
diff --git a/src/server/routers/lambda/_schema/context.ts b/src/server/routers/lambda/_schema/context.ts
new file mode 100644
index 00000000000..95011e0b4b6
--- /dev/null
+++ b/src/server/routers/lambda/_schema/context.ts
@@ -0,0 +1,31 @@
+import { z } from 'zod';
+
+/**
+ * 会话上下文 Schema
+ * 同时支持 agentId 和 sessionId,用于向后兼容
+ *
+ * 优先级:agentId > sessionId
+ * 当同时提供时,agentId 会被用于解析对应的 sessionId
+ */
+export const conversationContextSchema = z.object({
+ agentId: z.string().optional(),
+ groupId: z.string().nullable().optional(),
+ sessionId: z.string().nullable().optional(),
+ threadId: z.string().nullable().optional(),
+ topicId: z.string().nullable().optional(),
+});
+
+/**
+ * 简化版上下文
+ * 用于 message 和 topic 的 CRUD 操作
+ */
+export const basicContextSchema = z.object({
+ agentId: z.string().optional(),
+ groupId: z.string().nullable().optional(),
+ sessionId: z.string().nullable().optional(),
+ threadId: z.string().nullable().optional(),
+ topicId: z.string().nullable().optional(),
+});
+
+export type ConversationContextInput = z.infer<typeof conversationContextSchema>;
+export type BasicContextInput = z.infer<typeof basicContextSchema>;
diff --git a/src/server/routers/lambda/agent.ts b/src/server/routers/lambda/agent.ts
index 092a42564c1..4e2bea8360a 100644
--- a/src/server/routers/lambda/agent.ts
+++ b/src/server/routers/lambda/agent.ts
@@ -7,6 +7,7 @@ import { FileModel } from '@/database/models/file';
import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
import { SessionModel } from '@/database/models/session';
import { UserModel } from '@/database/models/user';
+import { insertAgentSchema } from '@/database/schemas';
import { pino } from '@/libs/logger';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
@@ -27,6 +28,58 @@ const agentProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
});
export const agentRouter = router({
+ /**
+ * Check if an agent with the given marketIdentifier already exists
+ */
+ checkByMarketIdentifier: agentProcedure
+ .input(
+ z.object({
+ marketIdentifier: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ return ctx.agentModel.checkByMarketIdentifier(input.marketIdentifier);
+ }),
+
+ /**
+ * Create a new agent with session
+ * Returns the created agent ID and session ID
+ */
+ createAgent: agentProcedure
+ .input(
+ z.object({
+ config: insertAgentSchema
+ .omit({
+ chatConfig: true,
+ openingMessage: true,
+ openingQuestions: true,
+ plugins: true,
+ tags: true,
+ tts: true,
+ })
+ .passthrough()
+ .partial()
+ .optional(),
+ groupId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const session = await ctx.sessionModel.create({
+ config: input.config,
+ session: { groupId: input.groupId },
+ type: 'agent',
+ });
+
+ // Get the agent ID from the created session
+ const sessionWithAgent = await ctx.sessionModel.findByIdOrSlug(session.id);
+ const agentId = sessionWithAgent?.agent?.id;
+
+ return {
+ agentId,
+ sessionId: session.id,
+ };
+ }),
+
createAgentFiles: agentProcedure
.input(
z.object({
@@ -77,6 +130,20 @@ export const agentRouter = router({
return ctx.agentModel.deleteAgentKnowledgeBase(input.agentId, input.knowledgeBaseId);
}),
+ /**
+ * Get an agent by marketIdentifier
+ * @returns agent id if exists, null otherwise
+ */
+ getAgentByMarketIdentifier: agentProcedure
+ .input(
+ z.object({
+ marketIdentifier: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ return ctx.agentModel.getAgentByMarketIdentifier(input.marketIdentifier);
+ }),
+
getAgentConfig: agentProcedure
.input(
z.object({
@@ -99,12 +166,36 @@ export const agentRouter = router({
const session = await ctx.sessionModel.findByIdOrSlug(input.sessionId);
- if (!session) throw new Error('Session not found');
+ if (!session) throw new Error(`Session [${input.sessionId}] not found`);
const sessionId = session.id;
return ctx.agentModel.findBySessionId(sessionId);
}),
+ getAgentConfigById: agentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ return ctx.agentService.getAgentConfigById(input.agentId);
+ }),
+
+ /**
+ * Get a builtin agent by slug, creating it if it doesn't exist.
+ * This is a generic interface for all builtin agents (page-copilot, inbox, etc.)
+ */
+ getBuiltinAgent: agentProcedure
+ .input(
+ z.object({
+ slug: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ return ctx.agentService.getBuiltinAgent(input.slug);
+ }),
+
getKnowledgeBasesAndFiles: agentProcedure
.input(
z.object({
@@ -142,6 +233,34 @@ export const agentRouter = router({
];
}),
+ /**
+ * Query non-virtual agents with optional keyword filter.
+ * Returns agents with minimal info (id, title, description, avatar, backgroundColor).
+ * Used by AddGroupMemberModal and group-management tool to search/select agents.
+ */
+ queryAgents: agentProcedure
+ .input(
+ z
+ .object({
+ keyword: z.string().optional(),
+ limit: z.number().optional(),
+ offset: z.number().optional(),
+ })
+ .optional(),
+ )
+ .query(async ({ input, ctx }) => {
+ return ctx.agentModel.queryAgents(input);
+ }),
+
+ /**
+ * Remove an agent and its associated session
+ */
+ removeAgent: agentProcedure
+ .input(z.object({ agentId: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ return ctx.agentModel.delete(input.agentId);
+ }),
+
toggleFile: agentProcedure
.input(
z.object({
@@ -169,4 +288,30 @@ export const agentRouter = router({
input.enabled,
);
}),
+
+ updateAgentConfig: agentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ value: z.object({}).passthrough().partial(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ // Use AgentService to update and return the updated agent data
+ return ctx.agentService.updateAgentConfig(input.agentId, input.value);
+ }),
+
+ /**
+ * Pin or unpin an agent
+ */
+ updateAgentPinned: agentProcedure
+ .input(
+ z.object({
+ id: z.string(),
+ pinned: z.boolean(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ return ctx.agentModel.update(input.id, { pinned: input.pinned });
+ }),
});
diff --git a/src/server/routers/lambda/agentGroup.ts b/src/server/routers/lambda/agentGroup.ts
new file mode 100644
index 00000000000..4e9334a31fb
--- /dev/null
+++ b/src/server/routers/lambda/agentGroup.ts
@@ -0,0 +1,227 @@
+import { z } from 'zod';
+
+import { AgentModel } from '@/database/models/agent';
+import { ChatGroupModel } from '@/database/models/chatGroup';
+import { UserModel } from '@/database/models/user';
+import { AgentGroupRepository } from '@/database/repositories/agentGroup';
+import { insertAgentSchema } from '@/database/schemas';
+import { insertChatGroupSchema } from '@/database/schemas/chatGroup';
+import { ChatGroupConfig } from '@/database/types/chatGroup';
+import { authedProcedure, router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { ChatGroupService } from '@/server/services/chatGroup';
+
+const agentGroupProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+
+ return opts.next({
+ ctx: {
+ agentGroupRepo: new AgentGroupRepository(ctx.serverDB, ctx.userId),
+ agentModel: new AgentModel(ctx.serverDB, ctx.userId),
+ chatGroupModel: new ChatGroupModel(ctx.serverDB, ctx.userId),
+ chatGroupService: new ChatGroupService(ctx.serverDB, ctx.userId),
+ userModel: new UserModel(ctx.serverDB, ctx.userId),
+ },
+ });
+});
+
+export const agentGroupRouter = router({
+ addAgentsToGroup: agentGroupProcedure
+ .input(
+ z.object({
+ agentIds: z.array(z.string()),
+ groupId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ return ctx.chatGroupModel.addAgentsToGroup(input.groupId, input.agentIds);
+ }),
+
+ /**
+ * Check agents before removal to identify virtual agents that will be permanently deleted.
+ * This allows the frontend to show a confirmation dialog.
+ */
+ checkAgentsBeforeRemoval: agentGroupProcedure
+ .input(
+ z.object({
+ agentIds: z.array(z.string()),
+ groupId: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ return ctx.agentGroupRepo.checkAgentsBeforeRemoval(input.groupId, input.agentIds);
+ }),
+
+ /**
+ * Create a group with a supervisor agent.
+ * The supervisor agent is automatically created as a virtual agent.
+ * Returns the groupId and supervisorAgentId.
+ */
+ createGroup: agentGroupProcedure
+ .input(insertChatGroupSchema.omit({ userId: true }))
+ .mutation(async ({ input, ctx }) => {
+ const { group, supervisorAgentId } = await ctx.agentGroupRepo.createGroupWithSupervisor({
+ ...input,
+ config: ctx.chatGroupService.normalizeGroupConfig(input.config as ChatGroupConfig | null),
+ });
+
+ return { group, supervisorAgentId };
+ }),
+
+ /**
+ * Create a group with virtual member agents in one request.
+ * This is the recommended way to create a group from a template.
+ * The backend will:
+ * 1. Create a supervisor agent (virtual)
+ * 2. Batch create virtual agents from member configs
+ * 3. Create the group with supervisor and member agents
+ * Returns the groupId, supervisorAgentId, and created member agentIds.
+ */
+ createGroupWithMembers: agentGroupProcedure
+ .input(
+ z.object({
+ groupConfig: insertChatGroupSchema.omit({ userId: true }),
+ members: z.array(
+ insertAgentSchema
+ .omit({
+ chatConfig: true,
+ openingMessage: true,
+ openingQuestions: true,
+ tts: true,
+ userId: true,
+ })
+ .partial(),
+ ),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ // 1. Batch create virtual member agents
+ const memberConfigs = input.members.map((member) => ({
+ ...member,
+ plugins: member.plugins as string[] | undefined,
+ tags: member.tags as string[] | undefined,
+ virtual: true,
+ }));
+
+ const createdAgents = await ctx.agentModel.batchCreate(memberConfigs);
+ const memberAgentIds = createdAgents.map((agent) => agent.id);
+
+ // 2. Create group with supervisor and member agents
+ const { group, supervisorAgentId } = await ctx.agentGroupRepo.createGroupWithSupervisor(
+ {
+ ...input.groupConfig,
+ config: ctx.chatGroupService.normalizeGroupConfig(
+ input.groupConfig.config as ChatGroupConfig | null,
+ ),
+ },
+ memberAgentIds,
+ );
+
+ return { agentIds: memberAgentIds, groupId: group.id, supervisorAgentId };
+ }),
+
+ deleteGroup: agentGroupProcedure
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ return ctx.chatGroupModel.delete(input.id);
+ }),
+
+ getGroup: agentGroupProcedure
+ .input(z.object({ id: z.string() }))
+ .query(async ({ input, ctx }) => {
+ return ctx.chatGroupModel.findById(input.id);
+ }),
+
+ getGroupAgents: agentGroupProcedure
+ .input(z.object({ groupId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ return ctx.chatGroupModel.getGroupAgents(input.groupId);
+ }),
+
+ getGroupDetail: agentGroupProcedure
+ .input(z.object({ id: z.string() }))
+ .query(async ({ input, ctx }) => {
+ const [defaultAgentConfig, detail] = await Promise.all([
+ ctx.userModel.getUserSettingsDefaultAgentConfig(),
+ ctx.chatGroupService.getGroupDetail(input.id),
+ ]);
+
+ if (!detail) return null;
+
+ return {
+ ...detail,
+ agents: ctx.chatGroupService.mergeAgentsDefaultConfig(defaultAgentConfig, detail.agents),
+ };
+ }),
+
+ getGroups: agentGroupProcedure.query(async ({ ctx }) => {
+ const [defaultAgentConfig, groups] = await Promise.all([
+ ctx.userModel.getUserSettingsDefaultAgentConfig(),
+ ctx.chatGroupService.getGroups(),
+ ]);
+
+ return groups.map((group) => ({
+ ...group,
+ agents: ctx.chatGroupService.mergeAgentsDefaultConfig(defaultAgentConfig, group.agents),
+ }));
+ }),
+
+ /**
+ * Remove agents from a group.
+ * - Non-virtual agents are simply removed from the group (agent still exists)
+ * - Virtual agents are permanently deleted along with removal from group
+ *
+ * @param groupId - The group to remove agents from
+ * @param agentIds - Array of agent IDs to remove
+ * @param deleteVirtualAgents - Whether to delete virtual agents (default: true)
+ */
+ removeAgentsFromGroup: agentGroupProcedure
+ .input(
+ z.object({
+ agentIds: z.array(z.string()),
+ deleteVirtualAgents: z.boolean().optional(),
+ groupId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ return ctx.agentGroupRepo.removeAgentsFromGroup(
+ input.groupId,
+ input.agentIds,
+ input.deleteVirtualAgents,
+ );
+ }),
+
+ updateAgentInGroup: agentGroupProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ groupId: z.string(),
+ updates: z.object({
+ enabled: z.boolean().optional(),
+ order: z.number().optional(),
+ role: z.string().optional(),
+ }),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ return ctx.chatGroupModel.updateAgentInGroup(input.groupId, input.agentId, input.updates);
+ }),
+
+ updateGroup: agentGroupProcedure
+ .input(
+ z.object({
+ id: z.string(),
+ value: insertChatGroupSchema.partial(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ return ctx.chatGroupModel.update(input.id, {
+ ...input.value,
+ config: ctx.chatGroupService.normalizeGroupConfig(
+ input.value.config as ChatGroupConfig | null,
+ ),
+ });
+ }),
+});
+
+export type AgentGroupRouter = typeof agentGroupRouter;
diff --git a/src/server/routers/lambda/aiAgent.ts b/src/server/routers/lambda/aiAgent.ts
new file mode 100644
index 00000000000..cdf5a82191a
--- /dev/null
+++ b/src/server/routers/lambda/aiAgent.ts
@@ -0,0 +1,829 @@
+import { AgentRuntimeContext } from '@lobechat/agent-runtime';
+import { TaskCurrentActivity, TaskStatusResult, ThreadStatus } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import debug from 'debug';
+import pMap from 'p-map';
+import { z } from 'zod';
+
+import { MessageModel } from '@/database/models/message';
+import { ThreadModel } from '@/database/models/thread';
+import { TopicModel } from '@/database/models/topic';
+import { authedProcedure, router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { AgentRuntimeService } from '@/server/services/agentRuntime';
+import { AiAgentService } from '@/server/services/aiAgent';
+import { AiChatService } from '@/server/services/aiChat';
+import { nanoid } from '@/utils/uuid';
+
+const log = debug('lobe-server:ai-agent-router');
+
+// Zod schemas for agent operation
+const CreateAgentOperationSchema = z.object({
+ agentConfig: z.record(z.any()).optional().default({}),
+ agentId: z.string().optional(),
+ autoStart: z.boolean().optional().default(true),
+ messages: z.array(z.any()).optional().default([]),
+ modelRuntimeConfig: z.object({
+ model: z.string(),
+ provider: z.string(),
+ }),
+ threadId: z.string().optional().nullable(),
+ toolManifestMap: z.record(z.string(), z.any()).default({}),
+ tools: z.array(z.any()).optional(),
+ topicId: z.string().optional().nullable(),
+ userId: z.string().optional(),
+});
+
+const GetOperationStatusSchema = z.object({
+ historyLimit: z.number().optional().default(10),
+ includeHistory: z.boolean().optional().default(false),
+ operationId: z.string(),
+});
+
+const ProcessHumanInterventionSchema = z.object({
+ action: z.enum(['approve', 'reject', 'input', 'select']),
+ data: z
+ .object({
+ approvedToolCall: z.any().optional(),
+ input: z.any().optional(),
+ selection: z.any().optional(),
+ })
+ .optional(),
+ operationId: z.string(),
+ reason: z.string().optional(),
+ stepIndex: z.number().optional().default(0),
+});
+
+const GetPendingInterventionsSchema = z
+ .object({
+ operationId: z.string().optional(),
+ userId: z.string().optional(),
+ })
+ .refine((data) => data.operationId || data.userId, {
+ message: 'Either operationId or userId must be provided',
+ });
+
+const StartExecutionSchema = z.object({
+ context: z.any().optional(),
+ delay: z.number().optional().default(1000),
+ operationId: z.string(),
+ priority: z.enum(['high', 'normal', 'low']).optional().default('normal'),
+});
+
+/**
+ * Schema for execAgent - execute a single Agent
+ */
+const ExecAgentSchema = z
+ .object({
+ /** The agent ID to run (either agentId or slug is required) */
+ agentId: z.string().optional(),
+ /** Application context for message storage */
+ appContext: z
+ .object({
+ groupId: z.string().optional().nullable(),
+ scope: z.string().optional().nullable(),
+ sessionId: z.string().optional(),
+ threadId: z.string().optional().nullable(),
+ topicId: z.string().optional().nullable(),
+ })
+ .optional(),
+ /** Whether to auto-start execution after creating operation */
+ autoStart: z.boolean().optional().default(true),
+ /** Optional existing message IDs to include in context */
+ existingMessageIds: z.array(z.string()).optional().default([]),
+ /** The user input/prompt */
+ prompt: z.string(),
+ /** The agent slug to run (either agentId or slug is required) */
+ slug: z.string().optional(),
+ })
+ .refine((data) => data.agentId || data.slug, {
+ message: 'Either agentId or slug must be provided',
+ });
+
+/**
+ * Schema for execGroupAgent - execute Supervisor Agent in Group chat
+ */
+const ExecGroupAgentSchema = z.object({
+ /** The Supervisor agent ID */
+ agentId: z.string(),
+ /** File IDs attached to the message */
+ files: z.array(z.string()).optional(),
+ /** The Group ID */
+ groupId: z.string(),
+ /** User message content */
+ message: z.string(),
+ /** Optional: Create a new topic */
+ newTopic: z
+ .object({
+ title: z.string().optional(),
+ topicMessageIds: z.array(z.string()).optional(),
+ })
+ .optional(),
+ /** Existing topic ID */
+ topicId: z.string().optional().nullable(),
+});
+
+/**
+ * Schema for execAgents - batch execution of multiple agents
+ */
+const ExecAgentsSchema = z.object({
+ /** Whether to execute tasks in parallel (default: true) */
+ parallel: z.boolean().optional().default(true),
+ /** Array of agent tasks to execute */
+ tasks: z.array(ExecAgentSchema).min(1),
+});
+
+/**
+ * Schema for execGroupSubAgentTask - execute SubAgent task in Group chat
+ */
+const ExecGroupSubAgentTaskSchema = z.object({
+ /** The SubAgent ID to execute the task */
+ agentId: z.string(),
+ /** The Group ID (required) */
+ groupId: z.string(),
+ /** Task instruction/prompt for the SubAgent */
+ instruction: z.string(),
+ /** The parent message ID (Supervisor's tool call message) */
+ parentMessageId: z.string(),
+ /** Timeout in milliseconds (optional) */
+ timeout: z.number().optional(),
+ /** The Topic ID */
+ topicId: z.string(),
+});
+
+/**
+ * Schema for interruptTask - interrupt a running task
+ */
+const InterruptTaskSchema = z
+ .object({
+ /** Operation ID */
+ operationId: z.string().optional(),
+ /** Thread ID */
+ threadId: z.string().optional(),
+ })
+ .refine((data) => data.threadId || data.operationId, {
+ message: 'Either threadId or operationId must be provided',
+ });
+
+const aiAgentProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+
+ return opts.next({
+ ctx: {
+ agentRuntimeService: new AgentRuntimeService(ctx.serverDB, ctx.userId),
+ aiAgentService: new AiAgentService(ctx.serverDB, ctx.userId),
+ aiChatService: new AiChatService(ctx.serverDB, ctx.userId),
+ messageModel: new MessageModel(ctx.serverDB, ctx.userId),
+ threadModel: new ThreadModel(ctx.serverDB, ctx.userId),
+ topicModel: new TopicModel(ctx.serverDB, ctx.userId),
+ },
+ });
+});
+
+export const aiAgentRouter = router({
+ createOperation: aiAgentProcedure
+ .input(CreateAgentOperationSchema)
+ .mutation(async ({ input, ctx }) => {
+ const {
+ agentConfig = {},
+ agentId,
+ autoStart = true,
+ messages = [],
+ modelRuntimeConfig,
+ threadId,
+ topicId,
+ tools,
+ toolManifestMap,
+ } = input;
+ log('input: %O', input);
+
+ // Validate required parameters
+ if (!modelRuntimeConfig.model || !modelRuntimeConfig.provider) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'modelRuntimeConfig.model and modelRuntimeConfig.provider are required',
+ });
+ }
+
+ // Generate runtime operation ID: agt_{timestamp}_{agentId}_{topicId}_{random}
+ const timestamp = Date.now();
+ const operationId = `agt_${timestamp}_${agentId || 'unknown'}_${topicId || 'none'}_${nanoid(8)}`;
+
+ log(`Creating operation ${operationId} for user ${ctx.userId}`);
+
+ // Create initial context
+ const initialContext: AgentRuntimeContext = {
+ payload: {},
+ phase: 'user_input' as const,
+ session: {
+ messageCount: messages.length,
+ sessionId: operationId,
+ status: 'idle' as const,
+ stepCount: 0,
+ },
+ };
+
+ // Create operation using AgentRuntimeService
+ const result = await ctx.agentRuntimeService.createOperation({
+ agentConfig,
+ appContext: {
+ agentId,
+ threadId,
+ topicId,
+ },
+ autoStart,
+ initialContext,
+ initialMessages: messages,
+ modelRuntimeConfig,
+ operationId,
+ toolManifestMap,
+ tools,
+ userId: ctx.userId,
+ });
+
+ let firstStepResult;
+ if (result.autoStarted) {
+ firstStepResult = {
+ context: initialContext,
+ messageId: result.messageId,
+ scheduled: true,
+ };
+
+ log(
+ `Operation ${operationId} created and first step scheduled (messageId: ${result.messageId})`,
+ );
+ } else {
+ log(`Operation ${operationId} created without auto-start`);
+ }
+
+ return {
+ autoStart,
+ createdAt: new Date().toISOString(),
+ firstStep: firstStepResult,
+ operationId,
+ status: 'created',
+ success: true,
+ };
+ }),
+
+ execAgent: aiAgentProcedure.input(ExecAgentSchema).mutation(async ({ input, ctx }) => {
+ const { agentId, slug, prompt, appContext, autoStart = true, existingMessageIds = [] } = input;
+
+ log('execAgent: identifier=%s, prompt=%s', agentId || slug, prompt.slice(0, 50));
+
+ try {
+ return await ctx.aiAgentService.execAgent({
+ agentId,
+ appContext,
+ autoStart,
+ existingMessageIds,
+ prompt,
+ slug,
+ });
+ } catch (error: any) {
+ console.error('execAgent failed: %O', error);
+
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+
+ throw new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: `Failed to execute agent: ${error.message}`,
+ });
+ }
+ }),
+
+ /**
+ * Batch execute multiple agents
+ * Supports parallel or sequential execution
+ */
+ execAgents: aiAgentProcedure.input(ExecAgentsSchema).mutation(async ({ input, ctx }) => {
+ const { tasks, parallel = true } = input;
+
+ log('execAgents: %d tasks, parallel=%s', tasks.length, parallel);
+
+ type TaskResult = {
+ autoStarted?: boolean;
+ error?: string;
+ operationId?: string;
+ success: boolean;
+ taskIndex: number;
+ };
+
+ const executeTask = async (
+ task: (typeof tasks)[number],
+ taskIndex: number,
+ ): Promise<TaskResult> => {
+ const { agentId, slug, prompt, appContext, autoStart = true, existingMessageIds = [] } = task;
+
+ try {
+ const result = await ctx.aiAgentService.execAgent({
+ agentId,
+ appContext,
+ autoStart,
+ existingMessageIds,
+ prompt,
+ slug,
+ });
+
+ return {
+ autoStarted: result.autoStarted,
+ operationId: result.operationId,
+ success: true,
+ taskIndex,
+ };
+ } catch (error: any) {
+ log('execAgents task %d failed: %O', taskIndex, error);
+
+ return {
+ error: error.message || 'Unknown error',
+ success: false,
+ taskIndex,
+ };
+ }
+ };
+
+ // Execute tasks with pMap for concurrency control
+ // parallel=true: concurrency of 5, parallel=false: sequential (concurrency of 1)
+ const concurrency = parallel ? 5 : 1;
+
+ const results = await pMap(tasks, (task, index) => executeTask(task, index), { concurrency });
+
+ // Calculate summary
+ const succeeded = results.filter((r) => r.success).length;
+ const failed = results.filter((r) => !r.success).length;
+
+ return {
+ results,
+ success: failed === 0,
+ summary: {
+ failed,
+ succeeded,
+ total: tasks.length,
+ },
+ };
+ }),
+
+ /**
+ * Execute Group Agent (Supervisor) in a single call
+ *
+ * This endpoint combines message creation and agent execution:
+ * 1. Create topic (if needed)
+ * 2. Create user message
+ * 3. Create assistant message placeholder
+ * 4. Trigger Supervisor Agent execution
+ * 5. Return operationId for SSE connection + messages for UI sync
+ */
+ execGroupAgent: aiAgentProcedure.input(ExecGroupAgentSchema).mutation(async ({ input, ctx }) => {
+ const { agentId, groupId, message, files, topicId, newTopic } = input;
+
+ log('execGroupAgent: agentId=%s, groupId=%s', agentId, groupId);
+
+ try {
+ // Execute group agent
+ const result = await ctx.aiAgentService.execGroupAgent({
+ agentId,
+ files,
+ groupId,
+ message,
+ newTopic,
+ topicId,
+ });
+
+ // Get messages and topics for UI sync
+ // Messages include the assistant message with error if operation failed to start
+ const { messages, topics } = await ctx.aiChatService.getMessagesAndTopics({
+ agentId,
+ groupId,
+ includeTopic: result.isCreateNewTopic,
+ topicId: result.topicId,
+ });
+
+ // Return result with messages/topics - includes error/success fields
+ // Frontend can check success to decide whether to connect to SSE stream
+ return { ...result, messages, topics };
+ } catch (error: any) {
+ log('execGroupAgent failed: %O', error);
+
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+
+ throw new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: `Failed to execute group agent: ${error.message}`,
+ });
+ }
+ }),
+
+ /**
+ * Execute SubAgent task in Group chat
+ *
+ * This endpoint is called by Supervisor to delegate tasks to SubAgents.
+ * Each task runs in an isolated Thread context.
+ */
+ execGroupSubAgentTask: aiAgentProcedure
+ .input(ExecGroupSubAgentTaskSchema)
+ .mutation(async ({ input, ctx }) => {
+ const { agentId, groupId, instruction, parentMessageId, topicId, timeout } = input;
+
+ log('execGroupSubAgentTask: agentId=%s, groupId=%s', agentId, groupId);
+
+ try {
+ return await ctx.aiAgentService.execGroupSubAgentTask({
+ agentId,
+ groupId,
+ instruction,
+ parentMessageId,
+ timeout,
+ topicId,
+ });
+ } catch (error: any) {
+ log('execGroupSubAgentTask failed: %O', error);
+
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+
+ throw new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: `Failed to execute sub-agent task: ${error.message}`,
+ });
+ }
+ }),
+
+ /**
+ * Get SubAgent task execution status
+ *
+ * This endpoint queries the status of a SubAgent task by threadId.
+ * It queries from Thread table (PostgreSQL) for persistence,
+ * and supplements with real-time status from Redis if available.
+ *
+ * IMPORTANT: In QStash queue mode, step lifecycle callbacks cannot fire
+ * because each HTTP request creates a new AgentRuntimeService instance.
+ * As a workaround, this endpoint also updates Thread metadata from Redis
+ * when real-time status is available.
+ */
+ getGroupSubAgentTaskStatus: aiAgentProcedure
+ .input(
+ z.object({
+ /** Thread ID */
+ threadId: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ const { threadId } = input;
+
+ log('getGroupSubAgentTaskStatus: threadId=%s', threadId);
+
+ // 1. Find thread by threadId
+ const thread = await ctx.threadModel.findById(threadId);
+
+ if (!thread) {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: 'Thread not found',
+ });
+ }
+
+ // 2. Map Thread status to task status
+ const threadStatusToTaskStatus: Record<string, TaskStatusResult['status']> = {
+ [ThreadStatus.Active]: 'processing',
+ [ThreadStatus.Cancel]: 'cancel',
+ [ThreadStatus.Completed]: 'completed',
+ [ThreadStatus.Failed]: 'failed',
+ [ThreadStatus.InReview]: 'processing',
+ [ThreadStatus.Pending]: 'processing',
+ [ThreadStatus.Processing]: 'processing',
+ [ThreadStatus.Todo]: 'processing',
+ };
+
+ const taskStatus = threadStatusToTaskStatus[thread.status] || 'processing';
+ const metadata = thread.metadata;
+
+ // 3. Try to get real-time status from Redis (for active tasks)
+ // Note: This is optional - Redis operation may be expired or unavailable.
+ // Thread table is the persistent source of truth.
+ let realtimeStatus: Awaited<ReturnType<typeof ctx.agentRuntimeService.getOperationStatus>> =
+ null;
+ const resolvedOperationId = metadata?.operationId;
+ if (resolvedOperationId && taskStatus === 'processing') {
+ realtimeStatus = await ctx.agentRuntimeService.getOperationStatus({
+ operationId: resolvedOperationId,
+ });
+
+ // 4. WORKAROUND for QStash mode: Update Thread metadata from Redis
+ // In QStash mode, step callbacks don't fire because each HTTP request
+ // creates a new AgentRuntimeService instance with empty callback map.
+ // So we update Thread metadata here when polling for status.
+ // Note: realtimeStatus may be null if operation expired from Redis
+ if (realtimeStatus) {
+ const redisState = realtimeStatus.currentState;
+ const updatedMetadata: Record<string, any> = {
+ ...metadata,
+ operationId: resolvedOperationId,
+ };
+
+ // Update metrics from Redis state using currentState and stats
+ if (redisState.usage) {
+ updatedMetadata.totalTokens = redisState.usage.llm?.tokens?.total;
+ updatedMetadata.totalToolCalls = redisState.usage.tools?.totalCalls;
+ }
+ if (redisState.cost?.total !== undefined) {
+ updatedMetadata.totalCost = redisState.cost.total;
+ }
+
+ // Use stats for totalMessages (currentState doesn't include messages array)
+ const { stats } = realtimeStatus;
+ if (stats?.totalMessages) {
+ updatedMetadata.totalMessages = stats.totalMessages;
+ }
+
+ // Store totalSteps from stepCount
+ if (redisState.stepCount) {
+ updatedMetadata.totalSteps = redisState.stepCount;
+ }
+
+ // Check if operation is completed
+ if (realtimeStatus.isCompleted || redisState.status === 'done') {
+ updatedMetadata.completedAt = new Date().toISOString();
+ if (metadata?.startedAt) {
+ updatedMetadata.duration = Date.now() - new Date(metadata.startedAt).getTime();
+ }
+
+ // Update thread status to completed
+ await ctx.threadModel.update(threadId, {
+ metadata: updatedMetadata,
+ status: ThreadStatus.Completed,
+ });
+
+ log('getGroupSubAgentTaskStatus: marked thread %s as completed', threadId);
+ } else if (realtimeStatus.hasError || redisState.status === 'error') {
+ updatedMetadata.error = redisState.error;
+ updatedMetadata.completedAt = new Date().toISOString();
+ if (metadata?.startedAt) {
+ updatedMetadata.duration = Date.now() - new Date(metadata.startedAt).getTime();
+ }
+
+ await ctx.threadModel.update(threadId, {
+ metadata: updatedMetadata,
+ status: ThreadStatus.Failed,
+ });
+ log('getGroupSubAgentTaskStatus: marked thread %s as failed', threadId);
+ } else {
+ // Still processing, just update metrics
+ await ctx.threadModel.update(threadId, {
+ metadata: updatedMetadata,
+ });
+ log('getGroupSubAgentTaskStatus: updated thread %s metadata', threadId);
+ }
+ } else {
+ // Redis status not available (expired), use Thread data only
+ log(
+ 'getGroupSubAgentTaskStatus: Redis operation %s expired, using Thread data only',
+ resolvedOperationId,
+ );
+ }
+ }
+
+ // 5. Re-fetch thread to get updated metadata
+ const updatedThread = await ctx.threadModel.findById(threadId);
+ const updatedMetadata = updatedThread?.metadata ?? metadata;
+ const updatedStatus = updatedThread?.status ?? thread.status;
+ const updatedTaskStatus = threadStatusToTaskStatus[updatedStatus] || 'processing';
+
+ // 6. Query thread messages for result content or current activity
+ const threadMessages = await ctx.messageModel.query({ threadId });
+ const sortedMessages = threadMessages.sort(
+ (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
+ );
+
+ // 7. Get result content when task is completed or failed
+ let resultContent: string | undefined;
+ if (updatedTaskStatus === 'completed' || updatedTaskStatus === 'failed') {
+ const lastAssistantMessage = sortedMessages.find((m) => m.role === 'assistant');
+ resultContent = lastAssistantMessage?.content;
+ }
+
+ // 8. Build currentActivity when task is processing
+ let currentActivity: TaskCurrentActivity | undefined;
+ if (updatedTaskStatus === 'processing' && sortedMessages.length > 0) {
+ const lastMessage = sortedMessages[0];
+
+ if (lastMessage.role === 'tool') {
+ // Tool message means tool has returned result
+ currentActivity = {
+ apiName: lastMessage.plugin?.apiName ?? undefined,
+ identifier: lastMessage.plugin?.identifier ?? undefined,
+ type: 'tool_result',
+ };
+ } else if (lastMessage.role === 'assistant') {
+ // Check if assistant is calling tools
+ const tools = lastMessage.tools as Array<{
+ apiName?: string;
+ identifier?: string;
+ }> | null;
+ if (tools && tools.length > 0) {
+ const lastTool = tools.at(-1);
+ currentActivity = {
+ apiName: lastTool?.apiName,
+ identifier: lastTool?.identifier,
+ type: 'tool_calling',
+ };
+ } else {
+ // Assistant is generating content
+ currentActivity = {
+ contentPreview: lastMessage.content?.slice(0, 100),
+ type: 'generating',
+ };
+ }
+ }
+ }
+
+ // 9. Build TaskDetail from Thread (uses ThreadStatus)
+ const taskDetail = {
+ completedAt: updatedMetadata?.completedAt,
+ duration: updatedMetadata?.duration,
+ error: updatedMetadata?.error,
+ startedAt: updatedMetadata?.startedAt,
+ status: updatedStatus,
+ threadId: thread.id,
+ title: thread.title,
+ totalCost: updatedMetadata?.totalCost,
+ totalMessages: updatedMetadata?.totalMessages,
+ totalSteps: updatedMetadata?.totalSteps,
+ totalTokens: updatedMetadata?.totalTokens,
+ totalToolCalls: updatedMetadata?.totalToolCalls,
+ };
+
+ // 10. Build result
+ const result: TaskStatusResult = {
+ completedAt: updatedMetadata?.completedAt,
+ cost:
+ realtimeStatus?.currentState?.cost ??
+ (updatedMetadata?.totalCost ? { total: updatedMetadata.totalCost } : undefined),
+ currentActivity,
+ error: updatedMetadata?.error ?? realtimeStatus?.currentState?.error,
+ result: resultContent,
+ status: updatedTaskStatus,
+ stepCount: realtimeStatus?.currentState?.stepCount,
+ taskDetail,
+ usage:
+ realtimeStatus?.currentState?.usage ??
+ (updatedMetadata?.totalTokens
+ ? { total_tokens: updatedMetadata.totalTokens }
+ : undefined),
+ };
+
+ return result;
+ }),
+
+ getOperationStatus: aiAgentProcedure
+ .input(GetOperationStatusSchema)
+ .query(async ({ input, ctx }) => {
+ const { historyLimit, includeHistory, operationId } = input;
+
+ if (!operationId) {
+ throw new Error('operationId parameter is required');
+ }
+
+ log('Getting operation status for %s', operationId);
+
+ // Get operation status using AgentRuntimeService
+ const operationStatus = await ctx.agentRuntimeService.getOperationStatus({
+ historyLimit,
+ includeHistory,
+ operationId,
+ });
+
+ return operationStatus;
+ }),
+
+ getPendingInterventions: aiAgentProcedure
+ .input(GetPendingInterventionsSchema)
+ .query(async ({ input, ctx }) => {
+ const { operationId, userId } = input;
+
+ log('Getting pending interventions for operationId: %s, userId: %s', operationId, userId);
+
+ // Get pending interventions using AgentRuntimeService
+ const result = await ctx.agentRuntimeService.getPendingInterventions({
+ operationId: operationId || undefined,
+ userId: userId || undefined,
+ });
+
+ return result;
+ }),
+
+ /**
+ * Interrupt a running task
+ *
+ * This endpoint interrupts a SubAgent task by threadId or operationId.
+ * It updates both operation status and Thread status to cancelled state.
+ */
+ interruptTask: aiAgentProcedure.input(InterruptTaskSchema).mutation(async ({ input, ctx }) => {
+ const { threadId, operationId } = input;
+
+ log('interruptTask: threadId=%s, operationId=%s', threadId, operationId);
+
+ try {
+ return await ctx.aiAgentService.interruptTask({ operationId, threadId });
+ } catch (error: any) {
+ if (error.message === 'Thread not found') {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Thread not found' });
+ }
+ if (error.message === 'Operation ID not found') {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Operation ID not found' });
+ }
+ throw error;
+ }
+ }),
+
+ processHumanIntervention: aiAgentProcedure
+ .input(ProcessHumanInterventionSchema)
+ .mutation(async ({ input, ctx }) => {
+ const { operationId, action, data, reason, stepIndex } = input;
+
+ log(`Processing ${action} for operation ${operationId}`);
+
+ // Build intervention parameters
+ let interventionParams: any = {
+ action,
+ operationId,
+ stepIndex,
+ };
+
+ switch (action) {
+ case 'approve': {
+ if (!data?.approvedToolCall) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'approvedToolCall is required for approve action',
+ });
+ }
+ interventionParams.approvedToolCall = data.approvedToolCall;
+ break;
+ }
+ case 'reject': {
+ interventionParams.rejectionReason = reason || 'Tool call rejected by user';
+ break;
+ }
+ case 'input': {
+ if (!data?.input) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'input is required for input action',
+ });
+ }
+ interventionParams.humanInput = { response: data.input };
+ break;
+ }
+ case 'select': {
+ if (!data?.selection) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'selection is required for select action',
+ });
+ }
+ interventionParams.humanInput = { selection: data.selection };
+ break;
+ }
+ }
+
+ // Process human intervention using AgentRuntimeService
+ const result = await ctx.agentRuntimeService.processHumanIntervention(interventionParams);
+
+ return {
+ action,
+ message: `Human intervention processed successfully. Execution resumed.`,
+ operationId,
+ scheduledMessageId: result.messageId,
+ success: true,
+ timestamp: new Date().toISOString(),
+ };
+ }),
+
+ startExecution: aiAgentProcedure.input(StartExecutionSchema).mutation(async ({ input, ctx }) => {
+ const { operationId, context, priority, delay } = input;
+
+ log('Starting execution for operation %s', operationId);
+
+ // Start execution using AgentRuntimeService
+ const result = await ctx.agentRuntimeService.startExecution({
+ context,
+ delay,
+ operationId,
+ priority,
+ });
+
+ return {
+ ...result,
+ message: 'Agent execution started successfully',
+ timestamp: new Date().toISOString(),
+ };
+ }),
+});
diff --git a/src/server/routers/lambda/aiChat.ts b/src/server/routers/lambda/aiChat.ts
index 226c4c71253..68bcf8045df 100644
--- a/src/server/routers/lambda/aiChat.ts
+++ b/src/server/routers/lambda/aiChat.ts
@@ -7,11 +7,14 @@ import { TRPCError } from '@trpc/server';
import debug from 'debug';
import { LOADING_FLAT } from '@/const/message';
+import { AgentModel } from '@/database/models/agent';
import { MessageModel } from '@/database/models/message';
+import { ThreadModel } from '@/database/models/thread';
import { TopicModel } from '@/database/models/topic';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { initModelRuntimeWithUserPayload } from '@/server/modules/ModelRuntime';
+import { resolveContext } from '@/server/routers/lambda/_helpers/resolveContext';
import { AiChatService } from '@/server/services/aiChat';
import { FileService } from '@/server/services/file';
import { getXorPayload } from '@/utils/server';
@@ -23,9 +26,11 @@ const aiChatProcedure = authedProcedure.use(serverDatabase).use(async (opts) =>
return opts.next({
ctx: {
+ agentModel: new AgentModel(ctx.serverDB, ctx.userId),
aiChatService: new AiChatService(ctx.serverDB, ctx.userId),
fileService: new FileService(ctx.serverDB, ctx.userId),
messageModel: new MessageModel(ctx.serverDB, ctx.userId),
+ threadModel: new ThreadModel(ctx.serverDB, ctx.userId),
topicModel: new TopicModel(ctx.serverDB, ctx.userId),
},
});
@@ -70,11 +75,23 @@ export const aiChatRouter = router({
sendMessageInServer: aiChatProcedure
.input(AiSendMessageServerSchema)
.mutation(async ({ input, ctx }) => {
- log('sendMessageInServer called for sessionId: %s', input.sessionId);
- log('topicId: %s, newTopic: %O', input.topicId, input.newTopic);
+ log('sendMessageInServer called for agentId: %s', input.agentId);
+ log(
+ 'topicId: %s, newTopic: %O, newThread: %O',
+ input.topicId,
+ input.newTopic,
+ input.newThread,
+ );
+ let sessionId = input.sessionId;
+ if (!sessionId) {
+ const context = await resolveContext(input, ctx.serverDB, ctx.userId);
+ if (!!context.sessionId) sessionId = context.sessionId;
+ }
let messageId: string;
let topicId = input.topicId!;
+ let threadId = input.threadId;
+ let createdThreadId: string | undefined;
let isCreateNewTopic = false;
@@ -82,24 +99,55 @@ export const aiChatRouter = router({
if (input.newTopic) {
log('creating new topic with title: %s', input.newTopic.title);
const topicItem = await ctx.topicModel.create({
+ agentId: input.agentId,
+ groupId: input.groupId,
messages: input.newTopic.topicMessageIds,
- sessionId: input.sessionId,
+ sessionId,
title: input.newTopic.title,
});
topicId = topicItem.id;
isCreateNewTopic = true;
log('new topic created with id: %s', topicId);
+
+ // update agent's updatedAt to reflect new activity
+ if (input.agentId) {
+ await ctx.agentModel.touchUpdatedAt(input.agentId);
+ log('agent updatedAt touched for agentId: %s', input.agentId);
+ }
+ }
+
+ // create thread if there should be a new thread
+ if (input.newThread) {
+ log(
+ 'creating new thread with sourceMessageId: %s, type: %s',
+ input.newThread.sourceMessageId,
+ input.newThread.type,
+ );
+ const threadItem = await ctx.threadModel.create({
+ parentThreadId: input.newThread.parentThreadId,
+ sourceMessageId: input.newThread.sourceMessageId,
+ title: input.newThread.title,
+ topicId,
+ type: input.newThread.type,
+ });
+ if (threadItem) {
+ threadId = threadItem.id;
+ createdThreadId = threadItem.id;
+ log('new thread created with id: %s', threadId);
+ }
}
// create user message
log('creating user message with content length: %d', input.newUserMessage.content.length);
const userMessageItem = await ctx.messageModel.create({
+ agentId: input.agentId,
content: input.newUserMessage.content,
files: input.newUserMessage.files,
+ groupId: input.groupId,
parentId: input.newUserMessage.parentId,
role: 'user',
- sessionId: input.sessionId!,
- threadId: input.threadId,
+ sessionId,
+ threadId,
topicId,
});
@@ -113,13 +161,15 @@ export const aiChatRouter = router({
input.newAssistantMessage.provider,
);
const assistantMessageItem = await ctx.messageModel.create({
+ agentId: input.agentId,
content: LOADING_FLAT,
+ groupId: input.groupId,
model: input.newAssistantMessage.model,
parentId: messageId,
provider: input.newAssistantMessage.provider,
role: 'assistant',
- sessionId: input.sessionId!,
- threadId: input.threadId,
+ sessionId,
+ threadId,
topicId,
});
log('assistant message created with id: %s', assistantMessageItem.id);
@@ -127,15 +177,18 @@ export const aiChatRouter = router({
// retrieve latest messages and topic with
log('retrieving messages and topics');
const { messages, topics } = await ctx.aiChatService.getMessagesAndTopics({
+ agentId: input.agentId,
+ groupId: input.groupId,
includeTopic: isCreateNewTopic,
- sessionId: input.sessionId,
+ sessionId,
topicId,
});
- log('retrieved %d messages, %d topics', messages.length, topics?.length ?? 0);
+ log('retrieved %d messages, %d topics', messages.length, topics?.items?.length ?? 0);
return {
assistantMessageId: assistantMessageItem.id,
+ createdThreadId,
isCreateNewTopic,
messages,
topicId,
diff --git a/src/server/routers/lambda/group.ts b/src/server/routers/lambda/group.ts
deleted file mode 100644
index aa34e212b3c..00000000000
--- a/src/server/routers/lambda/group.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import { z } from 'zod';
-
-import { DEFAULT_CHAT_GROUP_CHAT_CONFIG } from '@/const/settings';
-import { ChatGroupModel } from '@/database/models/chatGroup';
-import { insertChatGroupSchema } from '@/database/schemas/chatGroup';
-import { ChatGroupConfig } from '@/database/types/chatGroup';
-import { authedProcedure, router } from '@/libs/trpc/lambda';
-import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-
-const groupProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
- const { ctx } = opts;
-
- return opts.next({
- ctx: {
- chatGroupModel: new ChatGroupModel(ctx.serverDB, ctx.userId),
- },
- });
-});
-
-const normalizeGroupConfig = (config?: ChatGroupConfig | null): ChatGroupConfig | undefined =>
- config
- ? {
- ...DEFAULT_CHAT_GROUP_CHAT_CONFIG,
- ...config,
- }
- : undefined;
-
-export const groupRouter = router({
- addAgentsToGroup: groupProcedure
- .input(
- z.object({
- agentIds: z.array(z.string()),
- groupId: z.string(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- return ctx.chatGroupModel.addAgentsToGroup(input.groupId, input.agentIds);
- }),
-
- createGroup: groupProcedure
- .input(insertChatGroupSchema.omit({ userId: true }))
- .mutation(async ({ input, ctx }) => {
- return ctx.chatGroupModel.create({
- ...input,
- config: normalizeGroupConfig(input.config as ChatGroupConfig | null),
- });
- }),
-
- deleteGroup: groupProcedure
- .input(z.object({ id: z.string() }))
- .mutation(async ({ input, ctx }) => {
- return ctx.chatGroupModel.delete(input.id);
- }),
-
- getGroup: groupProcedure.input(z.object({ id: z.string() })).query(async ({ input, ctx }) => {
- return ctx.chatGroupModel.findById(input.id);
- }),
-
- getGroupAgents: groupProcedure
- .input(z.object({ groupId: z.string() }))
- .query(async ({ input, ctx }) => {
- return ctx.chatGroupModel.getGroupAgents(input.groupId);
- }),
-
- getGroups: groupProcedure.query(async ({ ctx }) => {
- return ctx.chatGroupModel.queryWithMemberDetails();
- }),
-
- removeAgentsFromGroup: groupProcedure
- .input(
- z.object({
- agentIds: z.array(z.string()),
- groupId: z.string(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- for (const agentId of input.agentIds) {
- await ctx.chatGroupModel.removeAgentFromGroup(input.groupId, agentId);
- }
- }),
-
- updateAgentInGroup: groupProcedure
- .input(
- z.object({
- agentId: z.string(),
- groupId: z.string(),
- updates: z.object({
- enabled: z.boolean().optional(),
- order: z.number().optional(),
- role: z.string().optional(),
- }),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- return ctx.chatGroupModel.updateAgentInGroup(input.groupId, input.agentId, input.updates);
- }),
-
- updateGroup: groupProcedure
- .input(
- z.object({
- id: z.string(),
- value: insertChatGroupSchema.partial(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- return ctx.chatGroupModel.update(input.id, {
- ...input.value,
- config: normalizeGroupConfig(input.value.config as ChatGroupConfig | null),
- });
- }),
-});
-
-export type GroupRouter = typeof groupRouter;
diff --git a/src/server/routers/lambda/home.ts b/src/server/routers/lambda/home.ts
new file mode 100644
index 00000000000..a9bd69cf723
--- /dev/null
+++ b/src/server/routers/lambda/home.ts
@@ -0,0 +1,29 @@
+import { z } from 'zod';
+
+import { HomeRepository } from '@/database/repositories/home';
+import { authedProcedure, router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+
+const homeProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+
+ return opts.next({
+ ctx: {
+ homeRepository: new HomeRepository(ctx.serverDB, ctx.userId),
+ },
+ });
+});
+
+export const homeRouter = router({
+ getSidebarAgentList: homeProcedure.query(async ({ ctx }) => {
+ return ctx.homeRepository.getSidebarAgentList();
+ }),
+
+ searchAgents: homeProcedure
+ .input(z.object({ keyword: z.string() }))
+ .query(async ({ input, ctx }) => {
+ return ctx.homeRepository.searchAgents(input.keyword);
+ }),
+});
+
+export type HomeRouter = typeof homeRouter;
diff --git a/src/server/routers/lambda/message.ts b/src/server/routers/lambda/message.ts
index b29448c1c9f..9b0b9270200 100644
--- a/src/server/routers/lambda/message.ts
+++ b/src/server/routers/lambda/message.ts
@@ -7,12 +7,14 @@ import {
import { z } from 'zod';
import { MessageModel } from '@/database/models/message';
-import { getServerDB } from '@/database/server';
-import { authedProcedure, publicProcedure, router } from '@/libs/trpc/lambda';
+import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { FileService } from '@/server/services/file';
import { MessageService } from '@/server/services/message';
+import { resolveAgentIdFromSession, resolveContext } from './_helpers/resolveContext';
+import { basicContextSchema } from './_schema/context';
+
const messageProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
@@ -26,6 +28,22 @@ const messageProcedure = authedProcedure.use(serverDatabase).use(async (opts) =>
});
export const messageRouter = router({
+ addFilesToMessage: messageProcedure
+ .input(
+ z
+ .object({
+ fileIds: z.array(z.string()),
+ id: z.string(),
+ })
+ .extend(basicContextSchema.shape),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const { id, fileIds, agentId, ...options } = input;
+ const resolved = await resolveContext({ agentId, ...options }, ctx.serverDB, ctx.userId);
+
+ return ctx.messageService.addFilesToMessage(id, fileIds, resolved);
+ }),
+
count: messageProcedure
.input(
z
@@ -57,34 +75,35 @@ export const messageRouter = router({
createMessage: messageProcedure
.input(CreateNewMessageParamsSchema)
.mutation(async ({ input, ctx }) => {
- return ctx.messageService.createMessage(input as any);
+ // 如果没有 agentId 但有 sessionId,从 sessionId 解析出 agentId
+ let agentId = input.agentId;
+ if (!agentId && input.sessionId) {
+ agentId = (await resolveAgentIdFromSession(input.sessionId, ctx.serverDB, ctx.userId))!;
+ }
+
+ // 使用解析后的 agentId 创建消息
+ return ctx.messageService.createMessage({ ...input, agentId } as any);
}),
getHeatmaps: messageProcedure.query(async ({ ctx }) => {
return ctx.messageModel.getHeatmaps();
}),
- // TODO: 未来这部分方法也需要使用 authedProcedure
- getMessages: publicProcedure
+ getMessages: messageProcedure
.input(
z.object({
+ agentId: z.string().nullable().optional(),
current: z.number().optional(),
groupId: z.string().nullable().optional(),
pageSize: z.number().optional(),
sessionId: z.string().nullable().optional(),
+ threadId: z.string().nullable().optional(),
topicId: z.string().nullable().optional(),
}),
)
.query(async ({ input, ctx }) => {
- if (!ctx.userId) return [];
- const serverDB = await getServerDB();
-
- const messageModel = new MessageModel(serverDB, ctx.userId);
- const fileService = new FileService(serverDB, ctx.userId);
-
- return messageModel.query(input, {
- groupAssistantMessages: false,
- postProcessUrl: (path) => fileService.getFullFileUrl(path),
+ return ctx.messageModel.query(input, {
+ postProcessUrl: (path) => ctx.fileService.getFullFileUrl(path),
});
}),
@@ -98,15 +117,17 @@ export const messageRouter = router({
removeMessage: messageProcedure
.input(
- z.object({
- id: z.string(),
- sessionId: z.string().nullable().optional(),
- topicId: z.string().nullable().optional(),
- }),
+ z
+ .object({
+ id: z.string(),
+ })
+ .extend(basicContextSchema.shape),
)
.mutation(async ({ input, ctx }) => {
- const { id, ...options } = input;
- return ctx.messageService.removeMessage(id, options);
+ const { id, agentId, ...options } = input;
+ const resolved = await resolveContext({ agentId, ...options }, ctx.serverDB, ctx.userId);
+
+ return ctx.messageService.removeMessage(id, resolved);
}),
removeMessageQuery: messageProcedure
@@ -117,29 +138,34 @@ export const messageRouter = router({
removeMessages: messageProcedure
.input(
- z.object({
- ids: z.array(z.string()),
- sessionId: z.string().nullable().optional(),
- topicId: z.string().nullable().optional(),
- }),
+ z
+ .object({
+ ids: z.array(z.string()),
+ })
+ .extend(basicContextSchema.shape),
)
.mutation(async ({ input, ctx }) => {
- const { ids, ...options } = input;
- return ctx.messageService.removeMessages(ids, options);
+ const { ids, agentId, ...options } = input;
+ const resolved = await resolveContext({ agentId, ...options }, ctx.serverDB, ctx.userId);
+
+ return ctx.messageService.removeMessages(ids, resolved);
}),
removeMessagesByAssistant: messageProcedure
.input(
- z.object({
- groupId: z.string().nullable().optional(),
- sessionId: z.string().nullable().optional(),
- topicId: z.string().nullable().optional(),
- }),
+ z
+ .object({
+ groupId: z.string().nullable().optional(),
+ })
+ .extend(basicContextSchema.shape),
)
.mutation(async ({ input, ctx }) => {
+ const { agentId, ...options } = input;
+ const resolved = await resolveContext({ agentId, ...options }, ctx.serverDB, ctx.userId);
+
return ctx.messageModel.deleteMessagesBySession(
- input.sessionId,
- input.topicId,
+ resolved.sessionId,
+ resolved.topicId,
input.groupId,
);
}),
@@ -163,84 +189,91 @@ export const messageRouter = router({
update: messageProcedure
.input(
- z.object({
- id: z.string(),
- sessionId: z.string().nullable().optional(),
- topicId: z.string().nullable().optional(),
- value: UpdateMessageParamsSchema,
- }),
+ z
+ .object({
+ id: z.string(),
+ value: UpdateMessageParamsSchema,
+ })
+ .extend(basicContextSchema.shape),
)
.mutation(async ({ input, ctx }) => {
- const { id, value, ...options } = input;
- return ctx.messageService.updateMessage(id, value as any, options);
+ const { id, value, agentId, ...options } = input;
+ const resolved = await resolveContext({ agentId, ...options }, ctx.serverDB, ctx.userId);
+
+ return ctx.messageService.updateMessage(id, value as any, resolved);
}),
updateMessagePlugin: messageProcedure
.input(
- z.object({
- id: z.string(),
- sessionId: z.string().nullable().optional(),
- topicId: z.string().nullable().optional(),
- value: UpdateMessagePluginSchema.partial(),
- }),
+ z
+ .object({
+ id: z.string(),
+ value: UpdateMessagePluginSchema.partial(),
+ })
+ .extend(basicContextSchema.shape),
)
.mutation(async ({ input, ctx }) => {
- const { id, value, ...options } = input;
- return ctx.messageService.updateMessagePlugin(id, value, options);
+ const { id, value, agentId, ...options } = input;
+ const resolved = await resolveContext({ agentId, ...options }, ctx.serverDB, ctx.userId);
+
+ return ctx.messageService.updateMessagePlugin(id, value, resolved);
}),
updateMessageRAG: messageProcedure
- .input(
- UpdateMessageRAGParamsSchema.extend({
- sessionId: z.string().nullable().optional(),
- topicId: z.string().nullable().optional(),
- }),
- )
+ .input(UpdateMessageRAGParamsSchema.extend(basicContextSchema.shape))
.mutation(async ({ input, ctx }) => {
- const { id, value, ...options } = input;
- return ctx.messageService.updateMessageRAG(id, value, options);
+ const { id, value, agentId, ...options } = input;
+ const resolved = await resolveContext({ agentId, ...options }, ctx.serverDB, ctx.userId);
+
+ return ctx.messageService.updateMessageRAG(id, value, resolved);
}),
updateMetadata: messageProcedure
.input(
- z.object({
- id: z.string(),
- sessionId: z.string().nullable().optional(),
- topicId: z.string().nullable().optional(),
- value: z.object({}).passthrough(),
- }),
+ z
+ .object({
+ id: z.string(),
+ value: z.object({}).passthrough(),
+ })
+ .extend(basicContextSchema.shape),
)
.mutation(async ({ input, ctx }) => {
- const { id, value, ...options } = input;
- return ctx.messageService.updateMetadata(id, value, options);
+ const { id, value, agentId, ...options } = input;
+ const resolved = await resolveContext({ agentId, ...options }, ctx.serverDB, ctx.userId);
+
+ return ctx.messageService.updateMetadata(id, value, resolved);
}),
updatePluginError: messageProcedure
.input(
- z.object({
- id: z.string(),
- sessionId: z.string().nullable().optional(),
- topicId: z.string().nullable().optional(),
- value: z.object({}).passthrough().nullable(),
- }),
+ z
+ .object({
+ id: z.string(),
+ value: z.object({}).passthrough().nullable(),
+ })
+ .extend(basicContextSchema.shape),
)
.mutation(async ({ input, ctx }) => {
- const { id, value, ...options } = input;
- return ctx.messageService.updatePluginError(id, value, options);
+ const { id, value, agentId, ...options } = input;
+ const resolved = await resolveContext({ agentId, ...options }, ctx.serverDB, ctx.userId);
+
+ return ctx.messageService.updatePluginError(id, value, resolved);
}),
updatePluginState: messageProcedure
.input(
- z.object({
- id: z.string(),
- sessionId: z.string().nullable().optional(),
- topicId: z.string().nullable().optional(),
- value: z.object({}).passthrough(),
- }),
+ z
+ .object({
+ id: z.string(),
+ value: z.object({}).passthrough(),
+ })
+ .extend(basicContextSchema.shape),
)
.mutation(async ({ input, ctx }) => {
- const { id, value, ...options } = input;
- return ctx.messageService.updatePluginState(id, value, options);
+ const { id, value, agentId, ...options } = input;
+ const resolved = await resolveContext({ agentId, ...options }, ctx.serverDB, ctx.userId);
+
+ return ctx.messageService.updatePluginState(id, value, resolved);
}),
updateTTS: messageProcedure
@@ -263,6 +296,47 @@ export const messageRouter = router({
return ctx.messageModel.updateTTS(input.id, input.value);
}),
+
+ updateToolArguments: messageProcedure
+ .input(
+ z
+ .object({
+ toolCallId: z.string(),
+ value: z.union([z.string(), z.record(z.unknown())]),
+ })
+ .extend(basicContextSchema.shape),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const { toolCallId, value, agentId, ...options } = input;
+ const resolved = await resolveContext({ agentId, ...options }, ctx.serverDB, ctx.userId);
+
+ return ctx.messageService.updateToolArguments(toolCallId, value, resolved);
+ }),
+
+ /**
+ * Update tool message with content, metadata, pluginState, and pluginError in a single transaction
+ * This prevents race conditions when updating multiple fields
+ */
+ updateToolMessage: messageProcedure
+ .input(
+ z
+ .object({
+ id: z.string(),
+ value: z.object({
+ content: z.string().optional(),
+ metadata: z.object({}).passthrough().optional(),
+ pluginError: z.any().optional(),
+ pluginState: z.object({}).passthrough().optional(),
+ }),
+ })
+ .extend(basicContextSchema.shape),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const { id, value, agentId, ...options } = input;
+ const resolved = await resolveContext({ agentId, ...options }, ctx.serverDB, ctx.userId);
+
+ return ctx.messageService.updateToolMessage(id, value, resolved);
+ }),
updateTranslate: messageProcedure
.input(
z.object({
diff --git a/src/server/routers/lambda/topic.ts b/src/server/routers/lambda/topic.ts
index 990de60d2a0..45693123e9b 100644
--- a/src/server/routers/lambda/topic.ts
+++ b/src/server/routers/lambda/topic.ts
@@ -1,16 +1,30 @@
+import { RecentTopic, RecentTopicGroup, RecentTopicGroupMember } from '@lobechat/types';
+import { eq, inArray } from 'drizzle-orm';
+import { after } from 'next/server';
import { z } from 'zod';
import { TopicModel } from '@/database/models/topic';
-import { getServerDB } from '@/database/server';
-import { authedProcedure, publicProcedure, router } from '@/libs/trpc/lambda';
+import { AgentMigrationRepo } from '@/database/repositories/agentMigration';
+import { agents, chatGroups, chatGroupsAgents } from '@/database/schemas';
+import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { BatchTaskResult } from '@/types/service';
+import {
+ batchResolveAgentIdFromSessions,
+ resolveAgentIdFromSession,
+ resolveContext,
+} from './_helpers/resolveContext';
+import { basicContextSchema } from './_schema/context';
+
const topicProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
return opts.next({
- ctx: { topicModel: new TopicModel(ctx.serverDB, ctx.userId) },
+ ctx: {
+ agentMigrationRepo: new AgentMigrationRepo(ctx.serverDB, ctx.userId),
+ topicModel: new TopicModel(ctx.serverDB, ctx.userId),
+ },
});
});
@@ -18,22 +32,32 @@ export const topicRouter = router({
batchCreateTopics: topicProcedure
.input(
z.array(
- z.object({
- favorite: z.boolean().optional(),
- id: z.string().optional(),
- messages: z.array(z.string()).optional(),
- sessionId: z.string().optional(),
- title: z.string(),
- }),
+ z
+ .object({
+ favorite: z.boolean().optional(),
+ id: z.string().optional(),
+ messages: z.array(z.string()).optional(),
+ title: z.string(),
+ })
+ .extend(basicContextSchema.shape),
),
)
.mutation(async ({ input, ctx }): Promise<BatchTaskResult> => {
- const data = await ctx.topicModel.batchCreate(
- input.map((item) => ({
- ...item,
- })) as any,
+ // 解析每个 topic 的 sessionId
+ const resolvedTopics = await Promise.all(
+ input.map(async (item) => {
+ const { agentId, ...rest } = item;
+ const resolved = await resolveContext(
+ { agentId, sessionId: rest.sessionId },
+ ctx.serverDB,
+ ctx.userId,
+ );
+ return { ...rest, sessionId: resolved.sessionId };
+ }),
);
+ const data = await ctx.topicModel.batchCreate(resolvedTopics as any);
+
return { added: data.length, ids: [], skips: [], success: true };
}),
@@ -44,9 +68,20 @@ export const topicRouter = router({
}),
batchDeleteBySessionId: topicProcedure
- .input(z.object({ id: z.string().nullable().optional() }))
+ .input(
+ z.object({
+ agentId: z.string().optional(),
+ id: z.string().nullable().optional(),
+ }),
+ )
.mutation(async ({ input, ctx }) => {
- return ctx.topicModel.batchDeleteBySessionId(input.id);
+ const resolved = await resolveContext(
+ { agentId: input.agentId, sessionId: input.id },
+ ctx.serverDB,
+ ctx.userId,
+ );
+
+ return ctx.topicModel.batchDeleteBySessionId(resolved.sessionId);
}),
cloneTopic: topicProcedure
@@ -61,6 +96,8 @@ export const topicRouter = router({
.input(
z
.object({
+ agentId: z.string().optional(),
+ containerId: z.string().nullable().optional(),
endDate: z.string().optional(),
range: z.tuple([z.string(), z.string()]).optional(),
startDate: z.string().optional(),
@@ -73,16 +110,24 @@ export const topicRouter = router({
createTopic: topicProcedure
.input(
- z.object({
- favorite: z.boolean().optional(),
- groupId: z.string().nullable().optional(),
- messages: z.array(z.string()).optional(),
- sessionId: z.string().nullable().optional(),
- title: z.string(),
- }),
+ z
+ .object({
+ favorite: z.boolean().optional(),
+ groupId: z.string().nullable().optional(),
+ messages: z.array(z.string()).optional(),
+ title: z.string(),
+ })
+ .extend(basicContextSchema.shape),
)
.mutation(async ({ input, ctx }) => {
- const data = await ctx.topicModel.create(input);
+ const { agentId, ...rest } = input;
+ const resolved = await resolveContext(
+ { agentId, sessionId: rest.sessionId },
+ ctx.serverDB,
+ ctx.userId,
+ );
+
+ const data = await ctx.topicModel.create({ ...rest, sessionId: resolved.sessionId });
return data.id;
}),
@@ -91,22 +136,64 @@ export const topicRouter = router({
return ctx.topicModel.queryAll();
}),
- // TODO: this procedure should be used with authedProcedure
- getTopics: publicProcedure
+ getTopics: topicProcedure
.input(
z.object({
- containerId: z.string().nullable().optional(),
+ agentId: z.string().nullable().optional(),
current: z.number().optional(),
+ groupId: z.string().nullable().optional(),
+ isInbox: z.boolean().optional(),
pageSize: z.number().optional(),
+ sessionId: z.string().nullable().optional(),
}),
)
.query(async ({ input, ctx }) => {
- if (!ctx.userId) return [];
+ const { sessionId, isInbox, groupId, ...rest } = input;
+
+ // If groupId is provided, query by groupId directly
+ if (groupId) {
+ const result = await ctx.topicModel.query({ groupId, ...rest });
+ return { items: result.items, total: result.total };
+ }
+
+ // 如果提供了 sessionId 但没有 agentId,需要反向查找 agentId
+ let effectiveAgentId = rest.agentId;
+ if (!effectiveAgentId && sessionId) {
+ effectiveAgentId = await resolveAgentIdFromSession(sessionId, ctx.serverDB, ctx.userId);
+ }
+
+ const result = await ctx.topicModel.query({ ...rest, agentId: effectiveAgentId, isInbox });
- const serverDB = await getServerDB();
- const topicModel = new TopicModel(serverDB, ctx.userId);
+ // Runtime migration: backfill agentId for ALL legacy topics and messages under this agent
+ const runMigration = async () => {
+ if (!effectiveAgentId) return;
- return topicModel.query(input);
+ // Get the associated sessionId for migration
+ const resolved = await resolveContext(
+ { agentId: effectiveAgentId },
+ ctx.serverDB,
+ ctx.userId,
+ );
+
+ const migrationParams = isInbox
+ ? { agentId: effectiveAgentId, isInbox: true as const, sessionId: resolved.sessionId }
+ : resolved.sessionId
+ ? { agentId: effectiveAgentId, sessionId: resolved.sessionId }
+ : null;
+
+ if (migrationParams) {
+ try {
+ await ctx.agentMigrationRepo.migrateAgentId(migrationParams);
+ } catch (error) {
+ console.error('[AgentMigration] Failed to migrate agentId:', error);
+ }
+ }
+ };
+
+ // Use Next.js after() for non-blocking execution
+ after(runMigration);
+
+ return { items: result.items, total: result.total };
}),
hasTopics: topicProcedure.query(async ({ ctx }) => {
@@ -117,6 +204,156 @@ export const topicRouter = router({
return ctx.topicModel.rank(input);
}),
+ recentTopics: topicProcedure
+ .input(z.object({ limit: z.number().optional() }).optional())
+ .query(async ({ ctx, input }): Promise<RecentTopic[]> => {
+ const recentTopics = await ctx.topicModel.queryRecent(input?.limit ?? 12);
+
+ // Separate agent topics and group topics
+ const agentTopics = recentTopics.filter((t) => t.type === 'agent');
+ const groupTopics = recentTopics.filter((t) => t.type === 'group');
+
+ // Find legacy topics: no agentId but has sessionId
+ const legacyTopics = agentTopics.filter(
+ (topic) => topic.agentId === null && topic.sessionId !== null,
+ );
+
+ // Batch resolve agentId for legacy topics
+ const sessionIds = [...new Set(legacyTopics.map((t) => t.sessionId!))];
+ const sessionAgentMap = await batchResolveAgentIdFromSessions(
+ sessionIds,
+ ctx.serverDB,
+ ctx.userId,
+ );
+
+ // Build agentId map: merge existing agentId with resolved ones
+ const topicAgentIdMap = new Map<string, string>();
+ for (const topic of agentTopics) {
+ if (topic.agentId) {
+ topicAgentIdMap.set(topic.id, topic.agentId);
+ } else if (topic.sessionId) {
+ const resolvedAgentId = sessionAgentMap.get(topic.sessionId);
+ if (resolvedAgentId) {
+ topicAgentIdMap.set(topic.id, resolvedAgentId);
+ }
+ }
+ }
+
+ // Collect all agentIds to fetch agent info
+ const allAgentIds = [...new Set(topicAgentIdMap.values())];
+
+ // Batch query agent info
+ const agentInfoMap = new Map<
+ string,
+ { avatar: string | null; backgroundColor: string | null; id: string; title: string | null }
+ >();
+
+ if (allAgentIds.length > 0) {
+ const agentInfos = await ctx.serverDB
+ .select({
+ avatar: agents.avatar,
+ backgroundColor: agents.backgroundColor,
+ id: agents.id,
+ title: agents.title,
+ })
+ .from(agents)
+ .where(inArray(agents.id, allAgentIds));
+
+ for (const agent of agentInfos) {
+ agentInfoMap.set(agent.id, agent);
+ }
+ }
+
+ // Batch query group info with member avatars
+ const groupInfoMap = new Map<string, RecentTopicGroup>();
+ const allGroupIds = [...new Set(groupTopics.map((t) => t.groupId!).filter(Boolean))];
+
+ if (allGroupIds.length > 0) {
+ // Query chat groups
+ const chatGroupInfos = await ctx.serverDB
+ .select({
+ id: chatGroups.id,
+ title: chatGroups.title,
+ })
+ .from(chatGroups)
+ .where(inArray(chatGroups.id, allGroupIds));
+
+ // Query group member agents (get avatar info)
+ const groupMembersRaw = await ctx.serverDB
+ .select({
+ agentAvatar: agents.avatar,
+ agentBackgroundColor: agents.backgroundColor,
+ chatGroupId: chatGroupsAgents.chatGroupId,
+ order: chatGroupsAgents.order,
+ })
+ .from(chatGroupsAgents)
+ .leftJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
+ .where(inArray(chatGroupsAgents.chatGroupId, allGroupIds));
+
+ // Group members by chatGroupId
+ const groupMembersMap = new Map<string, RecentTopicGroupMember[]>();
+ for (const member of groupMembersRaw) {
+ const members = groupMembersMap.get(member.chatGroupId) || [];
+ members.push({
+ avatar: member.agentAvatar,
+ backgroundColor: member.agentBackgroundColor,
+ });
+ groupMembersMap.set(member.chatGroupId, members);
+ }
+
+ // Build group info map
+ for (const group of chatGroupInfos) {
+ groupInfoMap.set(group.id, {
+ id: group.id,
+ members: groupMembersMap.get(group.id) || [],
+ title: group.title,
+ });
+ }
+ }
+
+ // Runtime migration: backfill agentId for legacy topics
+ const runMigration = async () => {
+ for (const [sessionId, agentId] of sessionAgentMap) {
+ try {
+ await ctx.agentMigrationRepo.migrateAgentId({ agentId, sessionId });
+ } catch (error) {
+ console.error('[AgentMigration] Failed to migrate agentId for recentTopics:', error);
+ }
+ }
+ };
+
+ // Use Next.js after() for non-blocking execution
+ after(runMigration);
+
+ // Assemble final result
+ return recentTopics.map((topic) => {
+ if (topic.type === 'group' && topic.groupId) {
+ const groupInfo = groupInfoMap.get(topic.groupId);
+ return {
+ agent: null,
+ group: groupInfo ?? null,
+ id: topic.id,
+ title: topic.title,
+ type: 'group' as const,
+ updatedAt: topic.updatedAt,
+ };
+ }
+
+ // Agent topic
+ const agentId = topicAgentIdMap.get(topic.id);
+ const agentInfo = agentId ? agentInfoMap.get(agentId) : null;
+
+ return {
+ agent: agentInfo ?? null,
+ group: null,
+ id: topic.id,
+ title: topic.title,
+ type: 'agent' as const,
+ updatedAt: topic.updatedAt,
+ };
+ });
+ }),
+
removeAllTopics: topicProcedure.mutation(async ({ ctx }) => {
return ctx.topicModel.deleteAll();
}),
@@ -130,13 +367,20 @@ export const topicRouter = router({
searchTopics: topicProcedure
.input(
z.object({
+ agentId: z.string().optional(),
groupId: z.string().nullable().optional(),
keywords: z.string(),
sessionId: z.string().nullable().optional(),
}),
)
.query(async ({ input, ctx }) => {
- return ctx.topicModel.queryByKeyword(input.keywords, input.sessionId);
+ const resolved = await resolveContext(
+ { agentId: input.agentId, sessionId: input.sessionId },
+ ctx.serverDB,
+ ctx.userId,
+ );
+
+ return ctx.topicModel.queryByKeyword(input.keywords, resolved.sessionId);
}),
updateTopic: topicProcedure
@@ -144,6 +388,7 @@ export const topicRouter = router({
z.object({
id: z.string(),
value: z.object({
+ agentId: z.string().optional(),
favorite: z.boolean().optional(),
historySummary: z.string().optional(),
messages: z.array(z.string()).optional(),
@@ -159,7 +404,16 @@ export const topicRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
- return ctx.topicModel.update(input.id, input.value);
+ const { agentId, ...restValue } = input.value;
+
+ // 如果提供了 agentId,解析为 sessionId
+ let resolvedSessionId = restValue.sessionId;
+ if (agentId && !resolvedSessionId) {
+ const resolved = await resolveContext({ agentId }, ctx.serverDB, ctx.userId);
+ resolvedSessionId = resolved.sessionId ?? undefined;
+ }
+
+ return ctx.topicModel.update(input.id, { ...restValue, sessionId: resolvedSessionId });
}),
});
diff --git a/src/server/services/agent/index.test.ts b/src/server/services/agent/index.test.ts
index 55380c602c0..6a8231dd0ed 100644
--- a/src/server/services/agent/index.test.ts
+++ b/src/server/services/agent/index.test.ts
@@ -1,7 +1,10 @@
// @vitest-environment node
+import { DEFAULT_AGENT_CONFIG } from '@lobechat/const';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { AgentModel } from '@/database/models/agent';
import { SessionModel } from '@/database/models/session';
+import { UserModel } from '@/database/models/user';
import { parseAgentConfig } from '@/server/globalConfig/parseDefaultAgent';
import { AgentService } from './index';
@@ -23,13 +26,28 @@ vi.mock('@/database/models/session', () => ({
SessionModel: vi.fn(),
}));
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn(),
+}));
+
+vi.mock('@/database/models/user', () => ({
+ UserModel: vi.fn(),
+}));
+
describe('AgentService', () => {
let service: AgentService;
const mockDb = {} as any;
const mockUserId = 'test-user-id';
+ // Default mock for UserModel that returns empty settings
+ const mockUserModel = {
+ getUserSettings: vi.fn().mockResolvedValue({}),
+ };
+
beforeEach(() => {
vi.clearAllMocks();
+ // Setup default UserModel mock
+ (UserModel as any).mockImplementation(() => mockUserModel);
service = new AgentService(mockDb, mockUserId);
});
@@ -65,4 +83,192 @@ describe('AgentService', () => {
expect(mockSessionModel.createInbox).toHaveBeenCalledWith({});
});
});
+
+ describe('getBuiltinAgent', () => {
+ it('should return null if agent does not exist', async () => {
+ const mockAgentModel = {
+ getBuiltinAgent: vi.fn().mockResolvedValue(null),
+ };
+
+ (AgentModel as any).mockImplementation(() => mockAgentModel);
+ (parseAgentConfig as any).mockReturnValue({});
+
+ // Need to recreate service to use the new mock
+ const newService = new AgentService(mockDb, mockUserId);
+ const result = await newService.getBuiltinAgent('non-existent');
+
+ expect(result).toBeNull();
+ });
+
+ it('should merge DEFAULT_AGENT_CONFIG and serverDefaultAgentConfig with agent config', async () => {
+ const mockAgent = {
+ id: 'agent-1',
+ slug: 'inbox',
+ systemRole: 'Custom system role',
+ };
+ const serverDefaultConfig = { model: 'gpt-4', params: { temperature: 0.7 } };
+
+ const mockAgentModel = {
+ getBuiltinAgent: vi.fn().mockResolvedValue(mockAgent),
+ };
+
+ (AgentModel as any).mockImplementation(() => mockAgentModel);
+ (parseAgentConfig as any).mockReturnValue(serverDefaultConfig);
+
+ const newService = new AgentService(mockDb, mockUserId);
+ const result = await newService.getBuiltinAgent('inbox');
+
+ // Should have DEFAULT_AGENT_CONFIG as base
+ expect(result).toMatchObject({
+ // From DEFAULT_AGENT_CONFIG
+ chatConfig: DEFAULT_AGENT_CONFIG.chatConfig,
+ plugins: DEFAULT_AGENT_CONFIG.plugins,
+ tts: DEFAULT_AGENT_CONFIG.tts,
+ // From serverDefaultConfig (overrides DEFAULT_AGENT_CONFIG)
+ model: 'gpt-4',
+ params: { temperature: 0.7 },
+ // From mockAgent (overrides all)
+ id: 'agent-1',
+ slug: 'inbox',
+ systemRole: 'Custom system role',
+ });
+ });
+
+ it('should prioritize agent config over server default config', async () => {
+ const mockAgent = {
+ id: 'agent-1',
+ slug: 'inbox',
+ model: 'claude-3',
+ provider: 'anthropic',
+ };
+ const serverDefaultConfig = { model: 'gpt-4', provider: 'openai' };
+
+ const mockAgentModel = {
+ getBuiltinAgent: vi.fn().mockResolvedValue(mockAgent),
+ };
+
+ (AgentModel as any).mockImplementation(() => mockAgentModel);
+ (parseAgentConfig as any).mockReturnValue(serverDefaultConfig);
+
+ const newService = new AgentService(mockDb, mockUserId);
+ const result = await newService.getBuiltinAgent('inbox');
+
+ // Agent config should override server default
+ expect(result?.model).toBe('claude-3');
+ expect(result?.provider).toBe('anthropic');
+ });
+
+ it('should merge avatar from builtin-agents package definition', async () => {
+ const mockAgent = {
+ id: 'agent-1',
+ slug: 'inbox',
+ model: 'gpt-4',
+ };
+
+ const mockAgentModel = {
+ getBuiltinAgent: vi.fn().mockResolvedValue(mockAgent),
+ };
+
+ (AgentModel as any).mockImplementation(() => mockAgentModel);
+ (parseAgentConfig as any).mockReturnValue({});
+
+ const newService = new AgentService(mockDb, mockUserId);
+ const result = await newService.getBuiltinAgent('inbox');
+
+ // Avatar should be merged from BUILTIN_AGENTS definition
+ expect((result as any)?.avatar).toBe('/icons/icon-lobe.png');
+ });
+
+ it('should not include avatar for non-builtin agents', async () => {
+ const mockAgent = {
+ id: 'agent-1',
+ slug: 'custom-agent',
+ model: 'gpt-4',
+ };
+
+ const mockAgentModel = {
+ getBuiltinAgent: vi.fn().mockResolvedValue(mockAgent),
+ };
+
+ (AgentModel as any).mockImplementation(() => mockAgentModel);
+ (parseAgentConfig as any).mockReturnValue({});
+
+ const newService = new AgentService(mockDb, mockUserId);
+ const result = await newService.getBuiltinAgent('custom-agent');
+
+ // Avatar should not be present for non-builtin agents
+ expect((result as any)?.avatar).toBeUndefined();
+ });
+ });
+
+ describe('getAgentConfigById', () => {
+ it('should return null if agent does not exist', async () => {
+ const mockAgentModel = {
+ getAgentConfigById: vi.fn().mockResolvedValue(null),
+ };
+
+ (AgentModel as any).mockImplementation(() => mockAgentModel);
+ (parseAgentConfig as any).mockReturnValue({});
+
+ const newService = new AgentService(mockDb, mockUserId);
+ const result = await newService.getAgentConfigById('non-existent');
+
+ expect(result).toBeNull();
+ });
+
+ it('should merge DEFAULT_AGENT_CONFIG and serverDefaultAgentConfig with agent config', async () => {
+ const mockAgent = {
+ id: 'agent-1',
+ systemRole: 'Custom system role',
+ };
+ const serverDefaultConfig = { model: 'gpt-4', params: { temperature: 0.7 } };
+
+ const mockAgentModel = {
+ getAgentConfigById: vi.fn().mockResolvedValue(mockAgent),
+ };
+
+ (AgentModel as any).mockImplementation(() => mockAgentModel);
+ (parseAgentConfig as any).mockReturnValue(serverDefaultConfig);
+
+ const newService = new AgentService(mockDb, mockUserId);
+ const result = await newService.getAgentConfigById('agent-1');
+
+ // Should have DEFAULT_AGENT_CONFIG as base
+ expect(result).toMatchObject({
+ // From DEFAULT_AGENT_CONFIG
+ chatConfig: DEFAULT_AGENT_CONFIG.chatConfig,
+ plugins: DEFAULT_AGENT_CONFIG.plugins,
+ tts: DEFAULT_AGENT_CONFIG.tts,
+ // From serverDefaultConfig (overrides DEFAULT_AGENT_CONFIG)
+ model: 'gpt-4',
+ params: { temperature: 0.7 },
+ // From mockAgent (overrides all)
+ id: 'agent-1',
+ systemRole: 'Custom system role',
+ });
+ });
+
+ it('should prioritize agent config over server default config', async () => {
+ const mockAgent = {
+ id: 'agent-1',
+ model: 'claude-3',
+ provider: 'anthropic',
+ };
+ const serverDefaultConfig = { model: 'gpt-4', provider: 'openai' };
+
+ const mockAgentModel = {
+ getAgentConfigById: vi.fn().mockResolvedValue(mockAgent),
+ };
+
+ (AgentModel as any).mockImplementation(() => mockAgentModel);
+ (parseAgentConfig as any).mockReturnValue(serverDefaultConfig);
+
+ const newService = new AgentService(mockDb, mockUserId);
+ const result = await newService.getAgentConfigById('agent-1');
+
+ // Agent config should override server default
+ expect(result?.model).toBe('claude-3');
+ expect(result?.provider).toBe('anthropic');
+ });
+ });
});
diff --git a/src/server/services/agent/index.ts b/src/server/services/agent/index.ts
index e2aa89658ff..a353af299d3 100644
--- a/src/server/services/agent/index.ts
+++ b/src/server/services/agent/index.ts
@@ -1,15 +1,34 @@
+import { BUILTIN_AGENTS, BuiltinAgentSlug } from '@lobechat/builtin-agents';
+import { DEFAULT_AGENT_CONFIG } from '@lobechat/const';
import { LobeChatDatabase } from '@lobechat/database';
+import { AgentItem, LobeAgentConfig } from '@lobechat/types';
+import { cleanObject, merge } from '@lobechat/utils';
+import type { PartialDeep } from 'type-fest';
+import { AgentModel } from '@/database/models/agent';
import { SessionModel } from '@/database/models/session';
+import { UserModel } from '@/database/models/user';
import { getServerDefaultAgentConfig } from '@/server/globalConfig';
+import { UpdateAgentResult } from './type';
+
+/**
+ * Agent Service
+ *
+ * Encapsulates "mutation + query" logic for agent operations.
+ * After performing update operations, returns the updated agent data.
+ */
export class AgentService {
private readonly userId: string;
private readonly db: LobeChatDatabase;
+ private readonly agentModel: AgentModel;
+ private readonly userModel: UserModel;
constructor(db: LobeChatDatabase, userId: string) {
this.userId = userId;
this.db = db;
+ this.agentModel = new AgentModel(db, userId);
+ this.userModel = new UserModel(db, userId);
}
async createInbox() {
@@ -17,4 +36,99 @@ export class AgentService {
const defaultAgentConfig = getServerDefaultAgentConfig();
await sessionModel.createInbox(defaultAgentConfig);
}
+
+ /**
+ * Get a builtin agent by slug, creating it if it doesn't exist.
+ * This is a generic interface for all builtin agents (page-copilot, inbox, etc.)
+ *
+ * The returned agent config is merged with:
+ * 1. DEFAULT_AGENT_CONFIG (hardcoded defaults)
+ * 2. Server's globalDefaultAgentConfig (from environment variable DEFAULT_AGENT_CONFIG)
+ * 3. The actual agent config from database
+ * 4. Avatar from builtin-agents package definition (if available)
+ *
+ * This ensures the frontend always receives a complete config with model/provider.
+ */
+ async getBuiltinAgent(slug: string) {
+ // Fetch agent and defaultAgentConfig in parallel
+ const [agent, defaultAgentConfig] = await Promise.all([
+ this.agentModel.getBuiltinAgent(slug),
+ this.userModel.getUserSettingsDefaultAgentConfig(),
+ ]);
+
+ const mergedConfig = this.mergeDefaultConfig(agent, defaultAgentConfig);
+ if (!mergedConfig) return null;
+
+ // Merge avatar from builtin-agents package definition
+ const builtinAgent = BUILTIN_AGENTS[slug as BuiltinAgentSlug];
+ if (builtinAgent?.avatar) {
+ return { ...mergedConfig, avatar: builtinAgent.avatar };
+ }
+
+ return mergedConfig;
+ }
+
+ /**
+ * Get agent config by ID with default config merged.
+ *
+ * The returned agent config is merged with:
+ * 1. DEFAULT_AGENT_CONFIG (hardcoded defaults)
+ * 2. Server's globalDefaultAgentConfig (from environment variable DEFAULT_AGENT_CONFIG)
+ * 3. User's defaultAgentConfig (from user settings)
+ * 4. The actual agent config from database
+ */
+ async getAgentConfigById(agentId: string) {
+ const [agent, defaultAgentConfig] = await Promise.all([
+ this.agentModel.getAgentConfigById(agentId),
+ this.userModel.getUserSettingsDefaultAgentConfig(),
+ ]);
+ return this.mergeDefaultConfig(agent, defaultAgentConfig);
+ }
+
+ /**
+ * Merge default config with agent config.
+ * Returns null if agent is null/undefined.
+ *
+ * Merge order (later values override earlier):
+ * 1. DEFAULT_AGENT_CONFIG - hardcoded defaults
+ * 2. serverDefaultAgentConfig - from environment variable
+ * 3. userDefaultAgentConfig - from user settings (defaultAgent.config)
+ * 4. agent - actual agent config from database
+ */
+ private mergeDefaultConfig(
+ agent: any,
+ defaultAgentConfig: Awaited<ReturnType<UserModel['getUserSettingsDefaultAgentConfig']>>,
+ ): LobeAgentConfig | null {
+ if (!agent) return null;
+
+ const userDefaultAgentConfig =
+ (defaultAgentConfig as { config?: PartialDeep<LobeAgentConfig> })?.config || {};
+
+ // Merge configs in order: DEFAULT -> server -> user -> agent
+ const serverDefaultAgentConfig = getServerDefaultAgentConfig();
+ const baseConfig = merge(DEFAULT_AGENT_CONFIG, serverDefaultAgentConfig);
+ const withUserConfig = merge(baseConfig, userDefaultAgentConfig);
+
+ return merge(withUserConfig, cleanObject(agent));
+ }
+
+ /**
+ * Update agent config and return the updated data
+ * Pattern: update + query
+ *
+ * This method combines config update and querying into a single operation,
+ * reducing the need for separate refresh calls and improving performance.
+ */
+ async updateAgentConfig(
+ agentId: string,
+ value: PartialDeep<AgentItem>,
+ ): Promise<UpdateAgentResult> {
+ // 1. Execute update
+ await this.agentModel.updateConfig(agentId, value);
+
+ // 2. Query and return updated data (with default config merged)
+ const agent = await this.getAgentConfigById(agentId);
+
+ return { agent: agent as any, success: true };
+ }
}
diff --git a/src/server/services/agent/type.ts b/src/server/services/agent/type.ts
new file mode 100644
index 00000000000..4e2b9ee2f7f
--- /dev/null
+++ b/src/server/services/agent/type.ts
@@ -0,0 +1,6 @@
+import { LobeAgentConfig } from '@/types/agent';
+
+export interface UpdateAgentResult {
+ agent?: LobeAgentConfig;
+ success: boolean;
+}