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: improve group profile builder (#11452)

Arvin Xu9012b4023027
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index e0ed99130fc..4d168f745a4 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -71,11 +71,18 @@
"group.desc": "Move a task forward with multiple Agents in one shared space.",
"group.memberTooltip": "There are {{count}} members in the group",
"group.orchestratorThinking": "Orchestrator is thinking...",
+ "group.profile.contentPlaceholder": "Set the group objectives/work modes here. This information will be shared with all group members.",
+ "group.profile.external": "External",
+ "group.profile.externalAgentWarning": "External agent - changes will sync globally",
+ "group.profile.groupSettings": "Group Settings",
+ "group.profile.supervisor": "Supervisor",
+ "group.profile.supervisorPlaceholder": "The supervisor coordinates different agents. Setting supervisor information here enables more precise workflow coordination.",
"group.removeMember": "Remove Member",
"group.title": "Group",
"groupDescription": "Group description",
"groupSidebar.agentProfile.chat": "Chat",
"groupSidebar.agentProfile.model": "Model",
+ "groupSidebar.agentProfile.settings": "Settings",
"groupSidebar.members.addMember": "Add Member",
"groupSidebar.members.enableOrchestrator": "Enable Orchestrator",
"groupSidebar.members.memberSettings": "Member Settings",
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index ca1ea0a7544..7d80feea464 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -5,6 +5,7 @@
"builtins.lobe-agent-builder.apiName.getConfig": "Get config",
"builtins.lobe-agent-builder.apiName.getMeta": "Get metadata",
"builtins.lobe-agent-builder.apiName.getPrompt": "Get system prompt",
+ "builtins.lobe-agent-builder.apiName.installPlugin": "Install Skill",
"builtins.lobe-agent-builder.apiName.searchMarketTools": "Search Skill market",
"builtins.lobe-agent-builder.apiName.searchOfficialTools": "Search official Skills",
"builtins.lobe-agent-builder.apiName.setModel": "Set model",
@@ -15,6 +16,12 @@
"builtins.lobe-agent-builder.apiName.updateConfig": "Update config",
"builtins.lobe-agent-builder.apiName.updateMeta": "Update metadata",
"builtins.lobe-agent-builder.apiName.updatePrompt": "Update system prompt",
+ "builtins.lobe-agent-builder.inspector.chars": " chars",
+ "builtins.lobe-agent-builder.inspector.disablePlugin": "Disable",
+ "builtins.lobe-agent-builder.inspector.enablePlugin": "Enable",
+ "builtins.lobe-agent-builder.inspector.modelsCount": " and {{count}} more",
+ "builtins.lobe-agent-builder.inspector.noResults": "No results",
+ "builtins.lobe-agent-builder.inspector.togglePlugin": "Toggle",
"builtins.lobe-agent-builder.title": "Agent Builder Expert",
"builtins.lobe-cloud-sandbox.apiName.editLocalFile": "Edit file",
"builtins.lobe-cloud-sandbox.apiName.executeCode": "Execute code",
@@ -31,13 +38,27 @@
"builtins.lobe-cloud-sandbox.apiName.searchLocalFiles": "Search files",
"builtins.lobe-cloud-sandbox.apiName.writeLocalFile": "Write file",
"builtins.lobe-cloud-sandbox.title": "Cloud Sandbox",
+ "builtins.lobe-group-agent-builder.apiName.createAgent": "Create Agent",
"builtins.lobe-group-agent-builder.apiName.getAvailableModels": "Get available models",
"builtins.lobe-group-agent-builder.apiName.installPlugin": "Install Skill",
"builtins.lobe-group-agent-builder.apiName.inviteAgent": "Invite member",
"builtins.lobe-group-agent-builder.apiName.removeAgent": "Remove member",
+ "builtins.lobe-group-agent-builder.apiName.searchAgent": "Search Agents",
"builtins.lobe-group-agent-builder.apiName.searchMarketTools": "Search Skill market",
+ "builtins.lobe-group-agent-builder.apiName.batchCreateAgents": "Batch create agents",
"builtins.lobe-group-agent-builder.apiName.updateAgentConfig": "Update agent config",
- "builtins.lobe-group-agent-builder.apiName.updatePrompt": "Update system prompt",
+ "builtins.lobe-group-agent-builder.apiName.updateAgentPrompt": "Update agent prompt",
+ "builtins.lobe-group-agent-builder.apiName.updateSupervisorPrompt": "Update supervisor prompt",
+ "builtins.lobe-group-agent-builder.apiName.updateGroup": "Update group",
+ "builtins.lobe-group-agent-builder.apiName.updateGroupPrompt": "Update group prompt",
+ "builtins.lobe-group-agent-builder.inspector.agents": "agents",
+ "builtins.lobe-group-agent-builder.inspector.avatar": "Avatar",
+ "builtins.lobe-group-agent-builder.inspector.backgroundColor": "Background color",
+ "builtins.lobe-group-agent-builder.inspector.description": "Description",
+ "builtins.lobe-group-agent-builder.inspector.noResults": "No results",
+ "builtins.lobe-group-agent-builder.inspector.openingMessage": "Opening message",
+ "builtins.lobe-group-agent-builder.inspector.openingQuestions": "Opening questions",
+ "builtins.lobe-group-agent-builder.inspector.title": "Title",
"builtins.lobe-group-agent-builder.title": "Group Builder Expert",
"builtins.lobe-group-management.apiName.broadcast": "All speak",
"builtins.lobe-group-management.apiName.createAgent": "Add group member",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 48d4d9e6784..c337d301b5b 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -71,11 +71,18 @@
"group.desc": "在同一对话空间,让多个助理一起推进任务",
"group.memberTooltip": "群组内有 {{count}} 名成员",
"group.orchestratorThinking": "主持人思考中…",
+ "group.profile.external": "外部",
+ "group.profile.contentPlaceholder": "在此设定群组的目标/工作模式等,这些信息将会共享给所有群组成员",
+ "group.profile.externalAgentWarning": "外部助理的配置修改将全局同步生效",
+ "group.profile.groupSettings": "群组设定",
+ "group.profile.supervisor": "群组主管",
+ "group.profile.supervisorPlaceholder": "群组主管负责协调不同 Agent,在此设定主管的信息可以使得协调工作流更加精准",
"group.removeMember": "移除成员",
"group.title": "群组",
"groupDescription": "群组描述",
"groupSidebar.agentProfile.chat": "对话",
"groupSidebar.agentProfile.model": "模型",
+ "groupSidebar.agentProfile.settings": "设置",
"groupSidebar.members.addMember": "添加成员",
"groupSidebar.members.enableOrchestrator": "启用主持人",
"groupSidebar.members.memberSettings": "成员设置",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index 4663dc28dbd..4ec1e352502 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -5,6 +5,7 @@
"builtins.lobe-agent-builder.apiName.getConfig": "获取配置",
"builtins.lobe-agent-builder.apiName.getMeta": "获取元数据",
"builtins.lobe-agent-builder.apiName.getPrompt": "获取系统提示词",
+ "builtins.lobe-agent-builder.apiName.installPlugin": "安装技能",
"builtins.lobe-agent-builder.apiName.searchMarketTools": "搜索技能市场",
"builtins.lobe-agent-builder.apiName.searchOfficialTools": "搜索官方技能",
"builtins.lobe-agent-builder.apiName.setModel": "设置模型",
@@ -15,6 +16,12 @@
"builtins.lobe-agent-builder.apiName.updateConfig": "更新配置",
"builtins.lobe-agent-builder.apiName.updateMeta": "更新元数据",
"builtins.lobe-agent-builder.apiName.updatePrompt": "更新系统提示词",
+ "builtins.lobe-agent-builder.inspector.chars": "字",
+ "builtins.lobe-agent-builder.inspector.disablePlugin": "关闭",
+ "builtins.lobe-agent-builder.inspector.enablePlugin": "开启",
+ "builtins.lobe-agent-builder.inspector.modelsCount": " 等 {{count}} 个模型",
+ "builtins.lobe-agent-builder.inspector.noResults": "无结果",
+ "builtins.lobe-agent-builder.inspector.togglePlugin": "切换",
"builtins.lobe-agent-builder.title": "助理构建专家",
"builtins.lobe-cloud-sandbox.apiName.editLocalFile": "编辑文件",
"builtins.lobe-cloud-sandbox.apiName.executeCode": "执行代码",
@@ -31,13 +38,27 @@
"builtins.lobe-cloud-sandbox.apiName.searchLocalFiles": "搜索文件",
"builtins.lobe-cloud-sandbox.apiName.writeLocalFile": "写入文件",
"builtins.lobe-cloud-sandbox.title": "云端沙盒",
+ "builtins.lobe-group-agent-builder.apiName.createAgent": "创建 Agent",
"builtins.lobe-group-agent-builder.apiName.getAvailableModels": "获取可用模型",
"builtins.lobe-group-agent-builder.apiName.installPlugin": "安装技能",
"builtins.lobe-group-agent-builder.apiName.inviteAgent": "邀请成员",
"builtins.lobe-group-agent-builder.apiName.removeAgent": "移除成员",
+ "builtins.lobe-group-agent-builder.apiName.searchAgent": "搜索 Agent",
"builtins.lobe-group-agent-builder.apiName.searchMarketTools": "搜索技能市场",
+ "builtins.lobe-group-agent-builder.apiName.batchCreateAgents": "批量创建 Agent",
"builtins.lobe-group-agent-builder.apiName.updateAgentConfig": "更新代理配置",
- "builtins.lobe-group-agent-builder.apiName.updatePrompt": "更新系统提示词",
+ "builtins.lobe-group-agent-builder.apiName.updateAgentPrompt": "更新助理提示词",
+ "builtins.lobe-group-agent-builder.apiName.updateSupervisorPrompt": "更新群组主管提示词",
+ "builtins.lobe-group-agent-builder.apiName.updateGroup": "更新群组",
+ "builtins.lobe-group-agent-builder.apiName.updateGroupPrompt": "更新群组提示词",
+ "builtins.lobe-group-agent-builder.inspector.agents": "个 Agent",
+ "builtins.lobe-group-agent-builder.inspector.avatar": "头像",
+ "builtins.lobe-group-agent-builder.inspector.backgroundColor": "背景色",
+ "builtins.lobe-group-agent-builder.inspector.description": "描述",
+ "builtins.lobe-group-agent-builder.inspector.noResults": "无结果",
+ "builtins.lobe-group-agent-builder.inspector.openingMessage": "开场白",
+ "builtins.lobe-group-agent-builder.inspector.openingQuestions": "开场问题",
+ "builtins.lobe-group-agent-builder.inspector.title": "标题",
"builtins.lobe-group-agent-builder.title": "群组构建专家",
"builtins.lobe-group-management.apiName.broadcast": "所有人发言",
"builtins.lobe-group-management.apiName.createAgent": "添加群组成员",
diff --git a/packages/builtin-tool-agent-builder/package.json b/packages/builtin-tool-agent-builder/package.json
index 8a8c5b4fc06..27e7bd9dd90 100644
--- a/packages/builtin-tool-agent-builder/package.json
+++ b/packages/builtin-tool-agent-builder/package.json
@@ -5,6 +5,7 @@
"exports": {
".": "./src/index.ts",
"./client": "./src/client/index.ts",
+ "./executor": "./src/executor.ts",
"./executionRuntime": "./src/ExecutionRuntime/index.ts"
},
"main": "./src/index.ts",
diff --git a/packages/builtin-tool-agent-builder/src/client/Inspector/GetAvailableModels/index.tsx b/packages/builtin-tool-agent-builder/src/client/Inspector/GetAvailableModels/index.tsx
new file mode 100644
index 00000000000..57abf95a013
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/client/Inspector/GetAvailableModels/index.tsx
@@ -0,0 +1,66 @@
+'use client';
+
+import type { BuiltinInspectorProps } from '@lobechat/types';
+import { cx } from 'antd-style';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import type { GetAvailableModelsParams, GetAvailableModelsState } from '../../../types';
+
+export const GetAvailableModelsInspector = memo<
+ BuiltinInspectorProps<GetAvailableModelsParams, GetAvailableModelsState>
+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
+ const { t } = useTranslation('plugin');
+
+ const providerId = args?.providerId || partialArgs?.providerId;
+
+ // Calculate total model count from providers
+ const modelInfo = useMemo(() => {
+ if (!pluginState?.providers) return null;
+
+ const allModels = pluginState.providers.flatMap((p) => p.models);
+ const totalCount = allModels.length;
+
+ if (totalCount === 0) return null;
+
+ // Get first 2 model names for display
+ const displayModels = allModels.slice(0, 2).map((m) => m.name || m.id);
+ return { displayModels, totalCount };
+ }, [pluginState?.providers]);
+
+ // Initial streaming state
+ if (isArgumentsStreaming || isLoading) {
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-agent-builder.apiName.getAvailableModels')}</span>
+ {providerId && (
+ <>
+ : <span className={highlightTextStyles.primary}>{providerId}</span>
+ </>
+ )}
+ </div>
+ );
+ }
+
+ // Loaded state with results
+ return (
+ <div className={inspectorTextStyles.root}>
+ <span>{t('builtins.lobe-agent-builder.apiName.getAvailableModels')}: </span>
+ {modelInfo && (
+ <span className={highlightTextStyles.primary}>
+ {modelInfo.displayModels.join(' / ')}
+ {modelInfo.totalCount > 2 &&
+ t('builtins.lobe-agent-builder.inspector.modelsCount', {
+ count: modelInfo.totalCount,
+ })}
+ </span>
+ )}
+ </div>
+ );
+});
+
+GetAvailableModelsInspector.displayName = 'GetAvailableModelsInspector';
+
+export default GetAvailableModelsInspector;
diff --git a/packages/builtin-tool-agent-builder/src/client/Inspector/InstallPlugin/index.tsx b/packages/builtin-tool-agent-builder/src/client/Inspector/InstallPlugin/index.tsx
new file mode 100644
index 00000000000..23a7092204d
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/client/Inspector/InstallPlugin/index.tsx
@@ -0,0 +1,63 @@
+'use client';
+
+import type { BuiltinInspectorProps } from '@lobechat/types';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { Check, X } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import type { InstallPluginParams, InstallPluginState } from '../../../types';
+
+const styles = createStaticStyles(({ css }) => ({
+ statusIcon: css`
+ margin-block-end: -2px;
+ margin-inline-start: 4px;
+ `,
+}));
+
+export const InstallPluginInspector = memo<
+ BuiltinInspectorProps<InstallPluginParams, InstallPluginState>
+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
+ const { t } = useTranslation('plugin');
+
+ const identifier = args?.identifier || partialArgs?.identifier;
+ const displayName = pluginState?.pluginName || identifier;
+
+ // Initial streaming state
+ if (isArgumentsStreaming && !identifier) {
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-agent-builder.apiName.installPlugin')}</span>
+ </div>
+ );
+ }
+
+ // Get installation result
+ const isSuccess = pluginState?.success && pluginState?.installed;
+ const hasResult = pluginState?.success !== undefined;
+
+ return (
+ <div
+ className={cx(
+ inspectorTextStyles.root,
+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,
+ )}
+ >
+ <span>{t('builtins.lobe-agent-builder.apiName.installPlugin')}: </span>
+ {displayName && <span className={highlightTextStyles.primary}>{displayName}</span>}
+ {!isLoading &&
+ hasResult &&
+ (isSuccess ? (
+ <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ ) : (
+ <X className={styles.statusIcon} color={cssVar.colorError} size={14} />
+ ))}
+ </div>
+ );
+});
+
+InstallPluginInspector.displayName = 'InstallPluginInspector';
+
+export default InstallPluginInspector;
diff --git a/packages/builtin-tool-agent-builder/src/client/Inspector/SearchMarketTools/index.tsx b/packages/builtin-tool-agent-builder/src/client/Inspector/SearchMarketTools/index.tsx
new file mode 100644
index 00000000000..7547e8e3163
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/client/Inspector/SearchMarketTools/index.tsx
@@ -0,0 +1,64 @@
+'use client';
+
+import type { BuiltinInspectorProps } from '@lobechat/types';
+import { Text } from '@lobehub/ui';
+import { cssVar, cx } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import type { SearchMarketToolsParams, SearchMarketToolsState } from '../../../types';
+
+export const SearchMarketToolsInspector = memo<
+ BuiltinInspectorProps<SearchMarketToolsParams, SearchMarketToolsState>
+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
+ const { t } = useTranslation('plugin');
+
+ const query = args?.query || partialArgs?.query;
+ const category = args?.category || partialArgs?.category;
+ const displayText = query || category;
+
+ // Initial streaming state
+ if (isArgumentsStreaming && !displayText) {
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-agent-builder.apiName.searchMarketTools')}</span>
+ </div>
+ );
+ }
+
+ const resultCount = pluginState?.tools?.length ?? 0;
+ const hasResults = resultCount > 0;
+
+ return (
+ <div
+ className={cx(
+ inspectorTextStyles.root,
+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,
+ )}
+ >
+ <span>{t('builtins.lobe-agent-builder.apiName.searchMarketTools')}: </span>
+ {displayText && <span className={highlightTextStyles.primary}>{displayText}</span>}
+ {!isLoading &&
+ !isArgumentsStreaming &&
+ pluginState?.tools &&
+ (hasResults ? (
+ <span style={{ marginInlineStart: 4 }}>({resultCount})</span>
+ ) : (
+ <Text
+ as={'span'}
+ color={cssVar.colorTextDescription}
+ fontSize={12}
+ style={{ marginInlineStart: 4 }}
+ >
+ ({t('builtins.lobe-agent-builder.inspector.noResults')})
+ </Text>
+ ))}
+ </div>
+ );
+});
+
+SearchMarketToolsInspector.displayName = 'SearchMarketToolsInspector';
+
+export default SearchMarketToolsInspector;
diff --git a/packages/builtin-tool-agent-builder/src/client/Inspector/UpdateConfig/index.tsx b/packages/builtin-tool-agent-builder/src/client/Inspector/UpdateConfig/index.tsx
new file mode 100644
index 00000000000..cc5252a4c2e
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/client/Inspector/UpdateConfig/index.tsx
@@ -0,0 +1,94 @@
+'use client';
+
+import type { BuiltinInspectorProps } from '@lobechat/types';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { Check } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import type { UpdateAgentConfigParams, UpdateConfigState } from '../../../types';
+
+const styles = createStaticStyles(({ css }) => ({
+ statusIcon: css`
+ margin-block-end: -2px;
+ margin-inline-start: 4px;
+ `,
+}));
+
+export const UpdateConfigInspector = memo<
+ BuiltinInspectorProps<UpdateAgentConfigParams, UpdateConfigState>
+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
+ const { t } = useTranslation('plugin');
+
+ const togglePlugin = args?.togglePlugin || partialArgs?.togglePlugin;
+ const config = args?.config || partialArgs?.config;
+ const meta = args?.meta || partialArgs?.meta;
+
+ // Build display text
+ const displayText = useMemo(() => {
+ // If toggling plugin, show that info
+ if (togglePlugin?.pluginId) {
+ const enabled = togglePlugin.enabled ?? pluginState?.togglePlugin?.enabled;
+ const action =
+ enabled === true
+ ? t('builtins.lobe-agent-builder.inspector.enablePlugin')
+ : enabled === false
+ ? t('builtins.lobe-agent-builder.inspector.disablePlugin')
+ : t('builtins.lobe-agent-builder.inspector.togglePlugin');
+ return `${action} ${togglePlugin.pluginId}`;
+ }
+
+ // Otherwise show updated fields
+ const fields: string[] = [];
+ if (config) {
+ if (config.model) fields.push('model');
+ if (config.provider) fields.push('provider');
+ if (config.plugins) fields.push('plugins');
+ if (config.params) fields.push('params');
+ if (config.chatConfig) fields.push('chatConfig');
+ }
+ if (meta) {
+ if (meta.title) fields.push('title');
+ if (meta.description) fields.push('description');
+ if (meta.avatar) fields.push('avatar');
+ }
+
+ return fields.length > 0 ? fields.join(', ') : '';
+ }, [togglePlugin, config, meta, pluginState, t]);
+
+ // Initial streaming state
+ if (isArgumentsStreaming && !displayText) {
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-agent-builder.apiName.updateConfig')}</span>
+ </div>
+ );
+ }
+
+ const isSuccess = pluginState?.success;
+
+ return (
+ <div
+ className={cx(
+ inspectorTextStyles.root,
+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,
+ )}
+ >
+ <span>{t('builtins.lobe-agent-builder.apiName.updateConfig')}</span>
+ {displayText && (
+ <>
+ : <span className={highlightTextStyles.primary}>{displayText}</span>
+ </>
+ )}
+ {!isLoading && isSuccess && (
+ <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ )}
+ </div>
+ );
+});
+
+UpdateConfigInspector.displayName = 'UpdateConfigInspector';
+
+export default UpdateConfigInspector;
diff --git a/packages/builtin-tool-agent-builder/src/client/Inspector/UpdatePrompt/index.tsx b/packages/builtin-tool-agent-builder/src/client/Inspector/UpdatePrompt/index.tsx
new file mode 100644
index 00000000000..aaa8e8f6dda
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/client/Inspector/UpdatePrompt/index.tsx
@@ -0,0 +1,96 @@
+'use client';
+
+import type { BuiltinInspectorProps } from '@lobechat/types';
+import { Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { Check } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import type { UpdatePromptParams, UpdatePromptState } from '../../../types';
+
+const styles = createStaticStyles(({ css }) => ({
+ statusIcon: css`
+ margin-block-end: -2px;
+ margin-inline-start: 4px;
+ `,
+}));
+
+export const UpdatePromptInspector = memo<
+ BuiltinInspectorProps<UpdatePromptParams, UpdatePromptState>
+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
+ const { t } = useTranslation('plugin');
+
+ const prompt = args?.prompt || partialArgs?.prompt;
+
+ // Calculate length difference
+ const lengthDiff = useMemo(() => {
+ if (!pluginState) return null;
+
+ const newLength = pluginState.newPrompt?.length ?? 0;
+ const prevLength = pluginState.previousPrompt?.length ?? 0;
+ const diff = newLength - prevLength;
+
+ return diff;
+ }, [pluginState]);
+
+ // Initial streaming state
+ if (isArgumentsStreaming && !prompt) {
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-agent-builder.apiName.updatePrompt')}</span>
+ </div>
+ );
+ }
+
+ // Calculate streaming length change
+ const streamingLength = prompt?.length ?? 0;
+ const isSuccess = pluginState?.success;
+
+ return (
+ <div
+ className={cx(
+ inspectorTextStyles.root,
+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,
+ )}
+ >
+ <span>{t('builtins.lobe-agent-builder.apiName.updatePrompt')}</span>
+ {/* Show length diff when completed */}
+ {!isLoading && !isArgumentsStreaming && lengthDiff !== null && (
+ <Text
+ as={'span'}
+ code
+ color={lengthDiff >= 0 ? cssVar.colorSuccess : cssVar.colorError}
+ fontSize={12}
+ style={{ marginInlineStart: 4 }}
+ >
+ ({lengthDiff >= 0 ? '+' : ''}
+ {lengthDiff}
+ {t('builtins.lobe-agent-builder.inspector.chars')})
+ </Text>
+ )}
+ {/* Show streaming length */}
+ {(isArgumentsStreaming || isLoading) && streamingLength > 0 && (
+ <Text
+ as={'span'}
+ code
+ color={cssVar.colorTextDescription}
+ fontSize={12}
+ style={{ marginInlineStart: 4 }}
+ >
+ ({streamingLength}
+ {t('builtins.lobe-agent-builder.inspector.chars')})
+ </Text>
+ )}
+ {!isLoading && !isArgumentsStreaming && isSuccess && (
+ <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ )}
+ </div>
+ );
+});
+
+UpdatePromptInspector.displayName = 'UpdatePromptInspector';
+
+export default UpdatePromptInspector;
diff --git a/packages/builtin-tool-agent-builder/src/client/Inspector/index.ts b/packages/builtin-tool-agent-builder/src/client/Inspector/index.ts
new file mode 100644
index 00000000000..5db04cf533a
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/client/Inspector/index.ts
@@ -0,0 +1,29 @@
+import { type BuiltinInspector } from '@lobechat/types';
+
+import { AgentBuilderApiName } from '../../types';
+import { GetAvailableModelsInspector } from './GetAvailableModels';
+import { InstallPluginInspector } from './InstallPlugin';
+import { SearchMarketToolsInspector } from './SearchMarketTools';
+import { UpdateConfigInspector } from './UpdateConfig';
+import { UpdatePromptInspector } from './UpdatePrompt';
+
+/**
+ * Agent Builder Inspector Components Registry
+ *
+ * Inspector components customize the title/header area
+ * of tool calls in the conversation UI.
+ */
+export const AgentBuilderInspectors: Record<string, BuiltinInspector> = {
+ [AgentBuilderApiName.getAvailableModels]: GetAvailableModelsInspector as BuiltinInspector,
+ [AgentBuilderApiName.installPlugin]: InstallPluginInspector as BuiltinInspector,
+ [AgentBuilderApiName.searchMarketTools]: SearchMarketToolsInspector as BuiltinInspector,
+ [AgentBuilderApiName.updateAgentConfig]: UpdateConfigInspector as BuiltinInspector,
+ [AgentBuilderApiName.updatePrompt]: UpdatePromptInspector as BuiltinInspector,
+};
+
+// Re-export individual inspectors for reuse in group-agent-builder
+export { GetAvailableModelsInspector } from './GetAvailableModels';
+export { InstallPluginInspector } from './InstallPlugin';
+export { SearchMarketToolsInspector } from './SearchMarketTools';
+export { UpdateConfigInspector } from './UpdateConfig';
+export { UpdatePromptInspector } from './UpdatePrompt';
diff --git a/packages/builtin-tool-agent-builder/src/client/index.ts b/packages/builtin-tool-agent-builder/src/client/index.ts
index d51263fa4c2..3eb7037d62a 100644
--- a/packages/builtin-tool-agent-builder/src/client/index.ts
+++ b/packages/builtin-tool-agent-builder/src/client/index.ts
@@ -1,4 +1,17 @@
+// Inspector components (customized tool call headers)
+export { AgentBuilderInspectors } from './Inspector';
+export {
+ GetAvailableModelsInspector,
+ InstallPluginInspector,
+ SearchMarketToolsInspector,
+ UpdateConfigInspector,
+ UpdatePromptInspector,
+} from './Inspector';
+
+// Intervention components (interactive editing)
export { AgentBuilderInterventions } from './Intervention';
+
+// Render components (read-only snapshots)
export { AgentBuilderRenders } from './Render';
// Re-export types and manifest for convenience
diff --git a/packages/builtin-tool-agent-builder/src/executor.ts b/packages/builtin-tool-agent-builder/src/executor.ts
new file mode 100644
index 00000000000..7616cacea93
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/executor.ts
@@ -0,0 +1,132 @@
+/**
+ * Agent Builder Executor
+ *
+ * Handles all agent builder tool calls for configuring and customizing agents.
+ */
+import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@lobechat/types';
+
+import { AgentBuilderExecutionRuntime } from './ExecutionRuntime';
+import {
+ AgentBuilderApiName,
+ AgentBuilderIdentifier,
+ type GetAvailableModelsParams,
+ type InstallPluginParams,
+ type SearchMarketToolsParams,
+ type UpdateAgentConfigParams,
+ type UpdatePromptParams,
+} from './types';
+
+const runtime = new AgentBuilderExecutionRuntime();
+
+class AgentBuilderExecutor extends BaseExecutor<typeof AgentBuilderApiName> {
+ readonly identifier = AgentBuilderIdentifier;
+ protected readonly apiEnum = AgentBuilderApiName;
+
+ // ==================== Read Operations ====================
+
+ getAvailableModels = async (params: GetAvailableModelsParams): Promise<BuiltinToolResult> => {
+ const result = await runtime.getAvailableModels(params);
+ return {
+ content: result.content,
+ error: result.error
+ ? { body: result.error, message: String(result.error), type: 'RuntimeError' }
+ : undefined,
+ state: result.state,
+ success: result.success,
+ };
+ };
+
+ searchMarketTools = async (params: SearchMarketToolsParams): Promise<BuiltinToolResult> => {
+ const result = await runtime.searchMarketTools(params);
+ return {
+ content: result.content,
+ error: result.error
+ ? { body: result.error, message: String(result.error), type: 'RuntimeError' }
+ : undefined,
+ state: result.state,
+ success: result.success,
+ };
+ };
+
+ // ==================== Write Operations ====================
+
+ updateConfig = async (
+ params: UpdateAgentConfigParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const agentId = ctx.agentId;
+
+ if (!agentId) {
+ return {
+ content: 'No active agent found',
+ error: { message: 'No active agent found', type: 'NoAgentContext' },
+ success: false,
+ };
+ }
+
+ const result = await runtime.updateAgentConfig(agentId, params);
+ return {
+ content: result.content,
+ error: result.error
+ ? { body: result.error, message: String(result.error), type: 'RuntimeError' }
+ : undefined,
+ state: result.state,
+ success: result.success,
+ };
+ };
+
+ updatePrompt = async (
+ params: UpdatePromptParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const agentId = ctx.agentId;
+
+ if (!agentId) {
+ return {
+ content: 'No active agent found',
+ error: { message: 'No active agent found', type: 'NoAgentContext' },
+ success: false,
+ };
+ }
+
+ const result = await runtime.updatePrompt(agentId, {
+ streaming: true,
+ ...params,
+ });
+ return {
+ content: result.content,
+ error: result.error
+ ? { body: result.error, message: String(result.error), type: 'RuntimeError' }
+ : undefined,
+ state: result.state,
+ success: result.success,
+ };
+ };
+
+ installPlugin = async (
+ params: InstallPluginParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const agentId = ctx.agentId;
+
+ if (!agentId) {
+ return {
+ content: 'No active agent found',
+ error: { message: 'No active agent found', type: 'NoAgentContext' },
+ success: false,
+ };
+ }
+
+ const result = await runtime.installPlugin(agentId, params);
+ return {
+ content: result.content,
+ error: result.error
+ ? { body: result.error, message: String(result.error), type: 'RuntimeError' }
+ : undefined,
+ state: result.state,
+ success: result.success,
+ };
+ };
+}
+
+export const agentBuilderExecutor = new AgentBuilderExecutor();
diff --git a/packages/builtin-tool-cloud-sandbox/src/client/Inspector/ExecuteCode/index.tsx b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/ExecuteCode/index.tsx
index 809875254b6..d23a7bcc034 100644
--- a/packages/builtin-tool-cloud-sandbox/src/client/Inspector/ExecuteCode/index.tsx
+++ b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/ExecuteCode/index.tsx
@@ -6,20 +6,11 @@ import { Check, X } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { highlightTextStyles, shinyTextStyles } from '@/styles';
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
import { type ExecuteCodeState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
-
+const styles = createStaticStyles(({ css }) => ({
statusIcon: css`
margin-block-end: -2px;
margin-inline-start: 4px;
@@ -42,13 +33,13 @@ export const ExecuteCodeInspector = memo<
if (isArgumentsStreaming) {
if (!description)
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-cloud-sandbox.apiName.executeCode')}</span>
</div>
);
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-cloud-sandbox.apiName.executeCode')}: </span>
<span className={highlightTextStyles.gold}>{description}</span>
</div>
@@ -56,7 +47,7 @@ export const ExecuteCodeInspector = memo<
}
return (
- <div className={cx(styles.root, isLoading && shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
<span style={{ marginInlineStart: 2 }}>
<span>{t('builtins.lobe-cloud-sandbox.apiName.executeCode')}: </span>
{description && <span className={highlightTextStyles.primary}>{description}</span>}
diff --git a/packages/builtin-tool-cloud-sandbox/src/client/Inspector/RunCommand/index.tsx b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/RunCommand/index.tsx
index 9ac3d93d2f4..365e8d8bc4e 100644
--- a/packages/builtin-tool-cloud-sandbox/src/client/Inspector/RunCommand/index.tsx
+++ b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/RunCommand/index.tsx
@@ -6,19 +6,11 @@ import { Check, X } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { highlightTextStyles, shinyTextStyles } from '@/styles';
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
import { type RunCommandState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
+const styles = createStaticStyles(({ css }) => ({
statusIcon: css`
margin-block-end: -2px;
margin-inline-start: 4px;
@@ -41,13 +33,13 @@ export const RunCommandInspector = memo<BuiltinInspectorProps<RunCommandParams,
if (isArgumentsStreaming) {
if (!description)
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-cloud-sandbox.apiName.runCommand')}</span>
</div>
);
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-cloud-sandbox.apiName.runCommand')}: </span>
<span className={highlightTextStyles.primary}>{description}</span>
</div>
@@ -55,7 +47,7 @@ export const RunCommandInspector = memo<BuiltinInspectorProps<RunCommandParams,
}
return (
- <div className={cx(styles.root, isLoading && shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
<span style={{ marginInlineStart: 2 }}>
<span>{t('builtins.lobe-cloud-sandbox.apiName.runCommand')}: </span>
{description && <span className={highlightTextStyles.primary}>{description}</span>}
diff --git a/packages/builtin-tool-group-agent-builder/package.json b/packages/builtin-tool-group-agent-builder/package.json
index 02013639aae..0ab737b4441 100644
--- a/packages/builtin-tool-group-agent-builder/package.json
+++ b/packages/builtin-tool-group-agent-builder/package.json
@@ -4,6 +4,8 @@
"private": true,
"exports": {
".": "./src/index.ts",
+ "./client": "./src/client/index.ts",
+ "./executor": "./src/executor.ts",
"./executionRuntime": "./src/ExecutionRuntime/index.ts"
},
"main": "./src/index.ts",
@@ -14,6 +16,10 @@
"@lobechat/types": "workspace:*"
},
"peerDependencies": {
- "react": "*"
+ "@lobehub/ui": "^4",
+ "antd": "^6",
+ "lucide-react": "*",
+ "react": "*",
+ "react-i18next": "*"
}
}
diff --git a/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts b/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts
index 7aeae1c347d..31f864dfa49 100644
--- a/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts
@@ -1,18 +1,27 @@
import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
-import { chatGroupService } from '@/services/chatGroup';
+import { agentService } from '@/services/agent';
+import { type GroupMemberConfig, chatGroupService } from '@/services/chatGroup';
+import { useAgentStore } from '@/store/agent';
import { getChatGroupStoreState } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
import type {
+ BatchCreateAgentsParams,
+ BatchCreateAgentsState,
+ CreateAgentParams,
+ CreateAgentState,
InviteAgentParams,
InviteAgentState,
RemoveAgentParams,
RemoveAgentState,
- UpdateGroupConfigParams,
- UpdateGroupConfigState,
+ SearchAgentParams,
+ SearchAgentState,
+ UpdateAgentPromptParams,
+ UpdateGroupParams,
UpdateGroupPromptParams,
UpdateGroupPromptState,
+ UpdateGroupState,
} from '../types';
/**
@@ -21,7 +30,184 @@ import type {
* Extends AgentBuilder functionality with group-specific operations
*/
export class GroupAgentBuilderExecutionRuntime {
- // ==================== Group-specific Operations ====================
+ // ==================== Group Member Management ====================
+
+ /**
+ * Search for agents that can be invited to the group
+ */
+ async searchAgent(args: SearchAgentParams): Promise<BuiltinServerRuntimeOutput> {
+ const { query, limit = 10 } = args;
+
+ try {
+ const results = await agentService.queryAgents({ keyword: query, limit });
+
+ const agents = results.map((agent) => ({
+ avatar: agent.avatar,
+ description: agent.description,
+ id: agent.id,
+ title: agent.title,
+ }));
+
+ const total = agents.length;
+
+ if (total === 0) {
+ return {
+ content: query
+ ? `No agents found matching "${query}".`
+ : 'No agents found. You can create a new agent or search with different keywords.',
+ state: { agents: [], query, total: 0 } as SearchAgentState,
+ success: true,
+ };
+ }
+
+ // Format agents list for LLM consumption
+ const agentList = agents
+ .map(
+ (a, i) =>
+ `${i + 1}. ${a.title || 'Untitled'} (ID: ${a.id})${a.description ? ` - ${a.description}` : ''}`,
+ )
+ .join('\n');
+
+ return {
+ content: query
+ ? `Found ${total} agent${total > 1 ? 's' : ''} matching "${query}":\n${agentList}`
+ : `Found ${total} agent${total > 1 ? 's' : ''}:\n${agentList}`,
+ state: { agents, query, total } as SearchAgentState,
+ success: true,
+ };
+ } catch (error) {
+ const err = error as Error;
+ return {
+ content: `Failed to search agents: ${err.message}`,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * Create a new agent and add it to the group
+ */
+ async createAgent(groupId: string, args: CreateAgentParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const state = getChatGroupStoreState();
+ const group = agentGroupSelectors.getGroupById(groupId)(state);
+
+ if (!group) {
+ return {
+ content: 'Group not found',
+ error: 'Group not found',
+ success: false,
+ };
+ }
+
+ // Create a virtual agent only (no session needed for group agents)
+ // Map 'tools' from LLM input to 'plugins' for internal API
+ const result = await agentService.createAgentOnly({
+ config: {
+ avatar: args.avatar,
+ description: args.description,
+ plugins: args.tools,
+ systemRole: args.systemRole,
+ title: args.title,
+ virtual: true,
+ },
+ groupId,
+ });
+
+ if (!result.agentId) {
+ return {
+ content: 'Failed to create agent: No agent ID returned',
+ success: false,
+ };
+ }
+
+ // Refresh the group detail in the store
+ await state.refreshGroupDetail(groupId);
+
+ return {
+ content: `Successfully created agent "${args.title}" and added it to the group.`,
+ state: {
+ agentId: result.agentId,
+ success: true,
+ title: args.title,
+ } as CreateAgentState,
+ success: true,
+ };
+ } catch (error) {
+ const err = error as Error;
+ return {
+ content: `Failed to create agent: ${err.message}`,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * Create multiple agents at once and add them to the group
+ * Uses batch API for efficiency (single request instead of N requests)
+ */
+ async batchCreateAgents(
+ groupId: string,
+ args: BatchCreateAgentsParams,
+ ): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const state = getChatGroupStoreState();
+ const group = agentGroupSelectors.getGroupById(groupId)(state);
+
+ if (!group) {
+ return {
+ content: 'Group not found',
+ error: 'Group not found',
+ success: false,
+ };
+ }
+
+ // Use batch API to create all agents in one request
+ // Map 'tools' from LLM input to 'plugins' for internal API
+ const agentConfigs: GroupMemberConfig[] = args.agents.map((agentDef) => ({
+ avatar: agentDef.avatar,
+ description: agentDef.description,
+ plugins: agentDef.tools,
+ systemRole: agentDef.systemRole,
+ title: agentDef.title,
+ }));
+
+ const { agents: createdAgents } = await chatGroupService.batchCreateAgentsInGroup(
+ groupId,
+ agentConfigs,
+ );
+
+ // Refresh the group detail in the store
+ await state.refreshGroupDetail(groupId);
+
+ const results = createdAgents.map((agent, index) => ({
+ agentId: agent.id,
+ success: true,
+ title: args.agents[index].title,
+ }));
+
+ const createdList = results.map((r) => `- ${r.title} (ID: ${r.agentId})`).join('\n');
+
+ return {
+ content: `Successfully created ${results.length} agent${results.length > 1 ? 's' : ''}:\n${createdList}`,
+ state: {
+ agents: results,
+ failedCount: 0,
+ successCount: results.length,
+ } as BatchCreateAgentsState,
+ success: true,
+ };
+ } catch (error) {
+ const err = error as Error;
+ return {
+ content: `Failed to create agents: ${err.message}`,
+ error,
+ success: false,
+ };
+ }
+ }
/**
* Invite an agent to the group
@@ -149,64 +335,58 @@ export class GroupAgentBuilderExecutionRuntime {
}
}
+ // ==================== Group Configuration ====================
+
/**
- * Update group system prompt
- * Unlike regular AgentBuilder, this updates the group's systemPrompt in groupConfig
+ * Update a specific agent's system prompt (systemRole)
*/
- async updatePrompt(args: UpdateGroupPromptParams): Promise<BuiltinServerRuntimeOutput> {
+ async updateAgentPrompt(
+ groupId: string,
+ args: UpdateAgentPromptParams,
+ ): Promise<BuiltinServerRuntimeOutput> {
try {
- const state = getChatGroupStoreState();
- const group = agentGroupSelectors.currentGroup(state);
+ const { agentId, prompt } = args;
- if (!group) {
- return {
- content: 'No active group found',
- error: 'No active group found',
- success: false,
- };
- }
+ // Get previous prompt for state
+ const state = getChatGroupStoreState();
+ const group = agentGroupSelectors.getGroupById(groupId)(state);
+ const agent = group?.agents?.find((a) => a.id === agentId);
+ const previousPrompt = agent?.systemRole ?? undefined;
- const previousPrompt = group.config?.systemPrompt;
+ // Update the agent's systemRole via agent store
+ await useAgentStore.getState().updateAgentConfigById(agentId, { systemRole: prompt });
- if (args.streaming) {
- // Use streaming mode for typewriter effect
- await this.streamUpdatePrompt(args.prompt);
- } else {
- // Update the system prompt directly
- await state.updateGroupConfig({ systemPrompt: args.prompt });
- }
+ // Refresh the group detail in the store to sync agent data
+ await state.refreshGroupDetail(groupId);
- const content = args.prompt
- ? `Successfully updated group system prompt (${args.prompt.length} characters)`
- : 'Successfully cleared group system prompt';
+ const content = prompt
+ ? `Successfully updated agent ${agentId} system prompt (${prompt.length} characters)`
+ : `Successfully cleared agent ${agentId} system prompt`;
return {
content,
state: {
- newPrompt: args.prompt,
+ agentId,
+ newPrompt: prompt,
previousPrompt,
success: true,
- } as UpdateGroupPromptState,
+ },
success: true,
};
} catch (error) {
const err = error as Error;
return {
- content: `Failed to update group prompt: ${err.message}`,
+ content: `Failed to update agent prompt: ${err.message}`,
error,
- state: {
- newPrompt: args.prompt,
- success: false,
- } as UpdateGroupPromptState,
success: false,
};
}
}
/**
- * Update group configuration (openingMessage, openingQuestions)
+ * Update group configuration and metadata (unified method)
*/
- async updateGroupConfig(args: UpdateGroupConfigParams): Promise<BuiltinServerRuntimeOutput> {
+ async updateGroup(args: UpdateGroupParams): Promise<BuiltinServerRuntimeOutput> {
try {
const state = getChatGroupStoreState();
const group = agentGroupSelectors.currentGroup(state);
@@ -219,91 +399,155 @@ export class GroupAgentBuilderExecutionRuntime {
};
}
- const { config } = args;
+ const { config, meta } = args;
- if (!config) {
+ if (!config && !meta) {
return {
- content: 'No configuration provided',
- error: 'No configuration provided',
+ content: 'No configuration or metadata provided',
+ error: 'No configuration or metadata provided',
success: false,
};
}
- // Build the config update object
- const configUpdate: { openingMessage?: string; openingQuestions?: string[] } = {};
-
- if (config.openingMessage !== undefined) {
- configUpdate.openingMessage = config.openingMessage;
+ const updatedFields: string[] = [];
+ const resultState: UpdateGroupState = { success: true };
+
+ // Update config if provided
+ if (config) {
+ const configUpdate: { openingMessage?: string; openingQuestions?: string[] } = {};
+
+ if (config.openingMessage !== undefined) {
+ configUpdate.openingMessage = config.openingMessage;
+ updatedFields.push(
+ config.openingMessage
+ ? `openingMessage (${config.openingMessage.length} chars)`
+ : 'openingMessage (cleared)',
+ );
+ }
+
+ if (config.openingQuestions !== undefined) {
+ configUpdate.openingQuestions = config.openingQuestions;
+ updatedFields.push(
+ config.openingQuestions.length > 0
+ ? `openingQuestions (${config.openingQuestions.length} questions)`
+ : 'openingQuestions (cleared)',
+ );
+ }
+
+ if (Object.keys(configUpdate).length > 0) {
+ await state.updateGroupConfig(configUpdate);
+ resultState.updatedConfig = configUpdate;
+ }
}
- if (config.openingQuestions !== undefined) {
- configUpdate.openingQuestions = config.openingQuestions;
+ // Update meta if provided
+ if (meta && Object.keys(meta).length > 0) {
+ await state.updateGroupMeta(meta);
+ resultState.updatedMeta = meta;
+
+ if (meta.avatar !== undefined) {
+ updatedFields.push(`avatar (${meta.avatar || 'cleared'})`);
+ }
+ if (meta.title !== undefined) {
+ updatedFields.push(`title (${meta.title || 'cleared'})`);
+ }
+ if (meta.description !== undefined) {
+ updatedFields.push(
+ meta.description
+ ? `description (${meta.description.length} chars)`
+ : 'description (cleared)',
+ );
+ }
+ if (meta.backgroundColor !== undefined) {
+ updatedFields.push(`backgroundColor (${meta.backgroundColor || 'cleared'})`);
+ }
}
- // Update the group config
- await state.updateGroupConfig(configUpdate);
+ // Refresh the group detail in the store to ensure data sync
+ await state.refreshGroupDetail(group.id);
- const updatedFields: string[] = [];
- if (config.openingMessage !== undefined) {
- updatedFields.push(
- config.openingMessage
- ? `openingMessage (${config.openingMessage.length} chars)`
- : 'openingMessage (cleared)',
- );
+ const content = `Successfully updated group: ${updatedFields.join(', ')}`;
+
+ return {
+ content,
+ state: resultState,
+ success: true,
+ };
+ } catch (error) {
+ const err = error as Error;
+ return {
+ content: `Failed to update group: ${err.message}`,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * Update group shared prompt/content
+ */
+ async updateGroupPrompt(args: UpdateGroupPromptParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const state = getChatGroupStoreState();
+ const group = agentGroupSelectors.currentGroup(state);
+
+ if (!group) {
+ return {
+ content: 'No active group found',
+ error: 'No active group found',
+ success: false,
+ };
}
- if (config.openingQuestions !== undefined) {
- updatedFields.push(
- config.openingQuestions.length > 0
- ? `openingQuestions (${config.openingQuestions.length} questions)`
- : 'openingQuestions (cleared)',
- );
+
+ const previousPrompt = group.content ?? undefined;
+
+ if (args.streaming) {
+ // Use streaming mode for typewriter effect
+ await this.streamUpdateGroupPrompt(args.prompt);
+ } else {
+ // Update the content directly
+ await state.updateGroup(group.id, { content: args.prompt });
}
- const content = `Successfully updated group configuration: ${updatedFields.join(', ')}`;
+ // Refresh the group detail in the store to ensure data sync
+ await state.refreshGroupDetail(group.id);
+
+ const content = args.prompt
+ ? `Successfully updated group shared prompt (${args.prompt.length} characters)`
+ : 'Successfully cleared group shared prompt';
return {
content,
state: {
+ newPrompt: args.prompt,
+ previousPrompt,
success: true,
- updatedConfig: configUpdate,
- } as UpdateGroupConfigState,
+ } as UpdateGroupPromptState,
success: true,
};
} catch (error) {
const err = error as Error;
return {
- content: `Failed to update group configuration: ${err.message}`,
+ content: `Failed to update group prompt: ${err.message}`,
error,
+ state: {
+ newPrompt: args.prompt,
+ success: false,
+ } as UpdateGroupPromptState,
success: false,
};
}
}
/**
- * Stream update prompt with typewriter effect for group
+ * Stream update group prompt with typewriter effect
*/
- private async streamUpdatePrompt(prompt: string): Promise<void> {
+ private async streamUpdateGroupPrompt(prompt: string): Promise<void> {
const state = getChatGroupStoreState();
+ const group = agentGroupSelectors.currentGroup(state);
- // Start streaming
- state.startStreamingSystemPrompt();
-
- // Simulate streaming by chunking the content
- const chunkSize = 5; // Characters per chunk
- const delay = 10; // Milliseconds between chunks
-
- for (let i = 0; i < prompt.length; i += chunkSize) {
- const chunk = prompt.slice(i, i + chunkSize);
- getChatGroupStoreState().appendStreamingSystemPrompt(chunk);
-
- // Small delay for typewriter effect
- if (i + chunkSize < prompt.length) {
- // eslint-disable-next-line no-promise-executor-return
- await new Promise((resolve) => setTimeout(resolve, delay));
- }
- }
+ if (!group) return;
- // Finish streaming - EditorCanvas will handle save when streaming ends
- await getChatGroupStoreState().finishStreamingSystemPrompt();
+ await state.updateGroup(group.id, { content: prompt });
}
}
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Inspector/BatchCreateAgents/index.tsx b/packages/builtin-tool-group-agent-builder/src/client/Inspector/BatchCreateAgents/index.tsx
new file mode 100644
index 00000000000..2985e04e223
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/client/Inspector/BatchCreateAgents/index.tsx
@@ -0,0 +1,110 @@
+'use client';
+
+import type { BuiltinInspectorProps } from '@lobechat/types';
+import { Avatar, Flexbox } from '@lobehub/ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { Check } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { shinyTextStyles } from '@/styles';
+
+import type { BatchCreateAgentsParams, BatchCreateAgentsState } from '../../../types';
+
+const styles = createStaticStyles(({ css, cssVar: cv }) => ({
+ avatarGroup: css`
+ display: flex;
+ gap: 2px;
+ align-items: center;
+ `,
+ count: css`
+ color: ${cv.colorTextSecondary};
+ font-size: 12px;
+ `,
+ root: css`
+ overflow: hidden;
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ `,
+ statusIcon: css`
+ flex-shrink: 0;
+ margin-block-end: -2px;
+ `,
+ title: css`
+ flex-shrink: 0;
+ color: ${cv.colorTextSecondary};
+ white-space: nowrap;
+ `,
+}));
+
+export const BatchCreateAgentsInspector = memo<
+ BuiltinInspectorProps<BatchCreateAgentsParams, BatchCreateAgentsState>
+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
+ const { t } = useTranslation('plugin');
+
+ const agents = args?.agents || partialArgs?.agents;
+
+ // Get display info from agents
+ const displayInfo = useMemo(() => {
+ if (!agents || agents.length === 0) return null;
+
+ const count = agents.length;
+ const displayAgents = agents.slice(0, 3); // Show up to 3 avatars
+
+ return { count, displayAgents };
+ }, [agents]);
+
+ // Initial streaming state
+ if (isArgumentsStreaming && !displayInfo) {
+ return (
+ <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-group-agent-builder.apiName.batchCreateAgents')}</span>
+ </div>
+ );
+ }
+
+ const isSuccess = pluginState?.successCount === pluginState?.agents?.length;
+ const successCount = pluginState?.successCount ?? 0;
+ const totalCount = displayInfo?.count ?? 0;
+
+ return (
+ <Flexbox
+ align={'center'}
+ className={cx(styles.root, (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText)}
+ gap={8}
+ horizontal
+ >
+ <span className={styles.title}>
+ {t('builtins.lobe-group-agent-builder.apiName.batchCreateAgents')}:
+ </span>
+ {displayInfo && (
+ <>
+ <div className={styles.avatarGroup}>
+ {displayInfo.displayAgents.map((agent, index) => (
+ <Avatar
+ key={index}
+ avatar={agent.avatar}
+ shape={'square'}
+ size={20}
+ title={agent.title}
+ />
+ ))}
+ </div>
+ <span className={styles.count}>
+ {pluginState
+ ? `${successCount}/${totalCount}`
+ : `${totalCount} ${t('builtins.lobe-group-agent-builder.inspector.agents')}`}
+ </span>
+ </>
+ )}
+ {!isLoading && isSuccess && (
+ <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ )}
+ </Flexbox>
+ );
+});
+
+BatchCreateAgentsInspector.displayName = 'BatchCreateAgentsInspector';
+
+export default BatchCreateAgentsInspector;
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Inspector/CreateAgent/index.tsx b/packages/builtin-tool-group-agent-builder/src/client/Inspector/CreateAgent/index.tsx
new file mode 100644
index 00000000000..0d7faf4b2cd
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/client/Inspector/CreateAgent/index.tsx
@@ -0,0 +1,72 @@
+'use client';
+
+import type { BuiltinInspectorProps } from '@lobechat/types';
+import { Avatar, Flexbox } from '@lobehub/ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { Check } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { shinyTextStyles } from '@/styles';
+
+import type { CreateAgentParams, CreateAgentState } from '../../../types';
+
+const styles = createStaticStyles(({ css, cssVar: cv }) => ({
+ root: css`
+ overflow: hidden;
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ `,
+ statusIcon: css`
+ flex-shrink: 0;
+ margin-block-end: -2px;
+ `,
+ title: css`
+ flex-shrink: 0;
+ color: ${cv.colorTextSecondary};
+ white-space: nowrap;
+ `,
+}));
+
+export const CreateAgentInspector = memo<
+ BuiltinInspectorProps<CreateAgentParams, CreateAgentState>
+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
+ const { t } = useTranslation('plugin');
+
+ const title = args?.title || partialArgs?.title;
+ const avatar = args?.avatar || partialArgs?.avatar;
+
+ // Initial streaming state
+ if (isArgumentsStreaming && !title) {
+ return (
+ <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-group-agent-builder.apiName.createAgent')}</span>
+ </div>
+ );
+ }
+
+ const isSuccess = pluginState?.success;
+
+ return (
+ <Flexbox
+ align={'center'}
+ className={cx(styles.root, (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText)}
+ gap={8}
+ horizontal
+ >
+ <span className={styles.title}>
+ {t('builtins.lobe-group-agent-builder.apiName.createAgent')}:
+ </span>
+ {avatar && <Avatar avatar={avatar} shape={'square'} size={20} title={title || undefined} />}
+ {title && <span>{title}</span>}
+ {!isLoading && isSuccess && (
+ <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ )}
+ </Flexbox>
+ );
+});
+
+CreateAgentInspector.displayName = 'CreateAgentInspector';
+
+export default CreateAgentInspector;
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Inspector/InviteAgent/index.tsx b/packages/builtin-tool-group-agent-builder/src/client/Inspector/InviteAgent/index.tsx
new file mode 100644
index 00000000000..a4db77708ee
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/client/Inspector/InviteAgent/index.tsx
@@ -0,0 +1,57 @@
+'use client';
+
+import type { BuiltinInspectorProps } from '@lobechat/types';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { Check } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import type { InviteAgentParams, InviteAgentState } from '../../../types';
+
+const styles = createStaticStyles(({ css }) => ({
+ statusIcon: css`
+ margin-block-end: -2px;
+ margin-inline-start: 4px;
+ `,
+}));
+
+export const InviteAgentInspector = memo<
+ BuiltinInspectorProps<InviteAgentParams, InviteAgentState>
+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
+ const { t } = useTranslation('plugin');
+
+ const agentId = args?.agentId || partialArgs?.agentId;
+ const displayName = pluginState?.agentName || agentId;
+
+ // Initial streaming state
+ if (isArgumentsStreaming && !agentId) {
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-group-agent-builder.apiName.inviteAgent')}</span>
+ </div>
+ );
+ }
+
+ const isSuccess = pluginState?.success;
+
+ return (
+ <div
+ className={cx(
+ inspectorTextStyles.root,
+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,
+ )}
+ >
+ <span>{t('builtins.lobe-group-agent-builder.apiName.inviteAgent')}: </span>
+ {displayName && <span className={highlightTextStyles.primary}>{displayName}</span>}
+ {!isLoading && isSuccess && (
+ <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ )}
+ </div>
+ );
+});
+
+InviteAgentInspector.displayName = 'InviteAgentInspector';
+
+export default InviteAgentInspector;
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Inspector/RemoveAgent/index.tsx b/packages/builtin-tool-group-agent-builder/src/client/Inspector/RemoveAgent/index.tsx
new file mode 100644
index 00000000000..bdfc6547dcb
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/client/Inspector/RemoveAgent/index.tsx
@@ -0,0 +1,57 @@
+'use client';
+
+import type { BuiltinInspectorProps } from '@lobechat/types';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { Check } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import type { RemoveAgentParams, RemoveAgentState } from '../../../types';
+
+const styles = createStaticStyles(({ css }) => ({
+ statusIcon: css`
+ margin-block-end: -2px;
+ margin-inline-start: 4px;
+ `,
+}));
+
+export const RemoveAgentInspector = memo<
+ BuiltinInspectorProps<RemoveAgentParams, RemoveAgentState>
+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
+ const { t } = useTranslation('plugin');
+
+ const agentId = args?.agentId || partialArgs?.agentId;
+ const displayName = pluginState?.agentName || agentId;
+
+ // Initial streaming state
+ if (isArgumentsStreaming && !agentId) {
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-group-agent-builder.apiName.removeAgent')}</span>
+ </div>
+ );
+ }
+
+ const isSuccess = pluginState?.success;
+
+ return (
+ <div
+ className={cx(
+ inspectorTextStyles.root,
+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,
+ )}
+ >
+ <span>{t('builtins.lobe-group-agent-builder.apiName.removeAgent')}: </span>
+ {displayName && <span className={highlightTextStyles.primary}>{displayName}</span>}
+ {!isLoading && isSuccess && (
+ <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ )}
+ </div>
+ );
+});
+
+RemoveAgentInspector.displayName = 'RemoveAgentInspector';
+
+export default RemoveAgentInspector;
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Inspector/SearchAgent/index.tsx b/packages/builtin-tool-group-agent-builder/src/client/Inspector/SearchAgent/index.tsx
new file mode 100644
index 00000000000..18b64552464
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/client/Inspector/SearchAgent/index.tsx
@@ -0,0 +1,66 @@
+'use client';
+
+import type { BuiltinInspectorProps } from '@lobechat/types';
+import { Text } from '@lobehub/ui';
+import { cssVar, cx } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import type { SearchAgentParams, SearchAgentState } from '../../../types';
+
+export const SearchAgentInspector = memo<
+ BuiltinInspectorProps<SearchAgentParams, SearchAgentState>
+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
+ const { t } = useTranslation('plugin');
+
+ const query = args?.query || partialArgs?.query;
+
+ // Initial streaming state
+ if (isArgumentsStreaming && !query) {
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-group-agent-builder.apiName.searchAgent')}</span>
+ </div>
+ );
+ }
+
+ const resultCount = pluginState?.total ?? pluginState?.agents?.length ?? 0;
+ const hasResults = resultCount > 0;
+
+ return (
+ <div
+ className={cx(
+ inspectorTextStyles.root,
+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,
+ )}
+ >
+ <span>{t('builtins.lobe-group-agent-builder.apiName.searchAgent')}</span>
+ {query && (
+ <>
+ : <span className={highlightTextStyles.primary}>{query}</span>
+ </>
+ )}
+ {!isLoading &&
+ !isArgumentsStreaming &&
+ pluginState?.agents &&
+ (hasResults ? (
+ <span style={{ marginInlineStart: 4 }}>({resultCount})</span>
+ ) : (
+ <Text
+ as={'span'}
+ color={cssVar.colorTextDescription}
+ fontSize={12}
+ style={{ marginInlineStart: 4 }}
+ >
+ ({t('builtins.lobe-group-agent-builder.inspector.noResults')})
+ </Text>
+ ))}
+ </div>
+ );
+});
+
+SearchAgentInspector.displayName = 'SearchAgentInspector';
+
+export default SearchAgentInspector;
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Inspector/UpdateAgentPrompt/index.tsx b/packages/builtin-tool-group-agent-builder/src/client/Inspector/UpdateAgentPrompt/index.tsx
new file mode 100644
index 00000000000..12e830201fb
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/client/Inspector/UpdateAgentPrompt/index.tsx
@@ -0,0 +1,120 @@
+'use client';
+
+import type { BuiltinInspectorProps } from '@lobechat/types';
+import { Avatar, Flexbox, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+import { inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import type { UpdateAgentPromptParams, UpdateAgentPromptState } from '../../../types';
+
+const styles = createStaticStyles(({ css, cssVar: cv }) => ({
+ agentName: css`
+ overflow: hidden;
+
+ max-width: 120px;
+
+ font-weight: 500;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ label: css`
+ flex-shrink: 0;
+ color: ${cv.colorTextSecondary};
+ white-space: nowrap;
+ `,
+ root: css`
+ overflow: hidden;
+ display: flex;
+ gap: 6px;
+ align-items: center;
+ `,
+}));
+
+export const UpdateAgentPromptInspector = memo<
+ BuiltinInspectorProps<UpdateAgentPromptParams, UpdateAgentPromptState>
+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
+ const { t } = useTranslation('plugin');
+
+ const agentId = args?.agentId || partialArgs?.agentId;
+ const prompt = args?.prompt || partialArgs?.prompt;
+
+ // Get agent info from the current group
+ const agent = useAgentGroupStore((s) => {
+ const agents = agentGroupSelectors.currentGroupAgents(s);
+ return agents.find((a) => a.id === agentId);
+ });
+
+ // Calculate length difference
+ const lengthDiff = useMemo(() => {
+ if (!pluginState) return null;
+
+ const newLength = pluginState.newPrompt?.length ?? 0;
+ const prevLength = pluginState.previousPrompt?.length ?? 0;
+ return newLength - prevLength;
+ }, [pluginState]);
+
+ // Initial streaming state
+ if (isArgumentsStreaming && !agentId) {
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-group-agent-builder.apiName.updateAgentPrompt')}</span>
+ </div>
+ );
+ }
+
+ const streamingLength = prompt?.length ?? 0;
+
+ const isSupervisor = agent?.isSupervisor ?? false;
+
+ // Use different i18n key for supervisor
+ const labelKey = isSupervisor
+ ? 'builtins.lobe-group-agent-builder.apiName.updateSupervisorPrompt'
+ : 'builtins.lobe-group-agent-builder.apiName.updateAgentPrompt';
+
+ return (
+ <Flexbox
+ align="center"
+ className={cx(styles.root, (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText)}
+ gap={6}
+ horizontal
+ >
+ <span className={styles.label}>{t(labelKey)}</span>
+ {/* Only show avatar and title for non-supervisor agents */}
+ {agent && !isSupervisor && (
+ <>
+ <Avatar avatar={agent.avatar ?? undefined} size={18} title={agent.title ?? undefined} />
+ <span className={styles.agentName}>{agent.title}</span>
+ </>
+ )}
+ {/* Show length diff when completed */}
+ {!isLoading && !isArgumentsStreaming && lengthDiff !== null && (
+ <Text
+ as="span"
+ code
+ color={lengthDiff >= 0 ? cssVar.colorSuccess : cssVar.colorError}
+ fontSize={12}
+ >
+ {lengthDiff >= 0 ? '+' : ''}
+ {lengthDiff}
+ {t('builtins.lobe-agent-builder.inspector.chars')}
+ </Text>
+ )}
+ {/* Show streaming length */}
+ {(isArgumentsStreaming || isLoading) && streamingLength > 0 && (
+ <Text as="span" code color={cssVar.colorTextDescription} fontSize={12}>
+ ({streamingLength}
+ {t('builtins.lobe-agent-builder.inspector.chars')})
+ </Text>
+ )}
+ </Flexbox>
+ );
+});
+
+UpdateAgentPromptInspector.displayName = 'UpdateAgentPromptInspector';
+
+export default UpdateAgentPromptInspector;
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Inspector/UpdateGroup/index.tsx b/packages/builtin-tool-group-agent-builder/src/client/Inspector/UpdateGroup/index.tsx
new file mode 100644
index 00000000000..e1baf8d91cf
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/client/Inspector/UpdateGroup/index.tsx
@@ -0,0 +1,87 @@
+'use client';
+
+import type { BuiltinInspectorProps } from '@lobechat/types';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { Check } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import type { UpdateGroupParams, UpdateGroupState } from '../../../types';
+
+const styles = createStaticStyles(({ css }) => ({
+ statusIcon: css`
+ margin-block-end: -2px;
+ margin-inline-start: 4px;
+ `,
+}));
+
+export const UpdateGroupInspector = memo<BuiltinInspectorProps<UpdateGroupParams, UpdateGroupState>>(
+ ({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
+ const { t } = useTranslation('plugin');
+
+ const config = args?.config || partialArgs?.config;
+ const meta = args?.meta || partialArgs?.meta;
+
+ // Build display text from updated fields
+ const displayText = useMemo(() => {
+ const fields: string[] = [];
+ // Config fields
+ if (config?.openingMessage !== undefined) {
+ fields.push(t('builtins.lobe-group-agent-builder.inspector.openingMessage'));
+ }
+ if (config?.openingQuestions !== undefined) {
+ fields.push(t('builtins.lobe-group-agent-builder.inspector.openingQuestions'));
+ }
+ // Meta fields
+ if (meta?.title !== undefined) {
+ fields.push(t('builtins.lobe-group-agent-builder.inspector.title'));
+ }
+ if (meta?.description !== undefined) {
+ fields.push(t('builtins.lobe-group-agent-builder.inspector.description'));
+ }
+ if (meta?.avatar !== undefined) {
+ fields.push(t('builtins.lobe-group-agent-builder.inspector.avatar'));
+ }
+ if (meta?.backgroundColor !== undefined) {
+ fields.push(t('builtins.lobe-group-agent-builder.inspector.backgroundColor'));
+ }
+ return fields.length > 0 ? fields.join(', ') : '';
+ }, [config, meta, t]);
+
+ // Initial streaming state
+ if (isArgumentsStreaming && !displayText) {
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-group-agent-builder.apiName.updateGroup')}</span>
+ </div>
+ );
+ }
+
+ const isSuccess = pluginState?.success;
+
+ return (
+ <div
+ className={cx(
+ inspectorTextStyles.root,
+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,
+ )}
+ >
+ <span>{t('builtins.lobe-group-agent-builder.apiName.updateGroup')}</span>
+ {displayText && (
+ <>
+ : <span className={highlightTextStyles.primary}>{displayText}</span>
+ </>
+ )}
+ {!isLoading && isSuccess && (
+ <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ )}
+ </div>
+ );
+ },
+);
+
+UpdateGroupInspector.displayName = 'UpdateGroupInspector';
+
+export default UpdateGroupInspector;
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Inspector/UpdateGroupPrompt/index.tsx b/packages/builtin-tool-group-agent-builder/src/client/Inspector/UpdateGroupPrompt/index.tsx
new file mode 100644
index 00000000000..460fb8a0ebf
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/client/Inspector/UpdateGroupPrompt/index.tsx
@@ -0,0 +1,99 @@
+'use client';
+
+import type { BuiltinInspectorProps } from '@lobechat/types';
+import { Flexbox, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import type { UpdateGroupPromptParams, UpdateGroupPromptState } from '../../../types';
+
+const styles = createStaticStyles(({ css, cssVar: cv }) => ({
+ groupName: css`
+ overflow: hidden;
+
+ max-width: 120px;
+
+ font-weight: 500;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ label: css`
+ flex-shrink: 0;
+ color: ${cv.colorTextSecondary};
+ white-space: nowrap;
+ `,
+ root: css`
+ overflow: hidden;
+ display: flex;
+ gap: 6px;
+ align-items: center;
+ `,
+}));
+
+export const UpdateGroupPromptInspector = memo<
+ BuiltinInspectorProps<UpdateGroupPromptParams, UpdateGroupPromptState>
+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
+ const { t } = useTranslation('plugin');
+
+ const prompt = args?.prompt || partialArgs?.prompt;
+
+ // Calculate length difference
+ const lengthDiff = useMemo(() => {
+ if (!pluginState) return null;
+
+ const newLength = pluginState.newPrompt?.length ?? 0;
+ const prevLength = pluginState.previousPrompt?.length ?? 0;
+ return newLength - prevLength;
+ }, [pluginState]);
+
+ // Initial streaming state
+ if (isArgumentsStreaming && !prompt) {
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-group-agent-builder.apiName.updateGroupPrompt')}</span>
+ </div>
+ );
+ }
+
+ const streamingLength = prompt?.length ?? 0;
+
+ return (
+ <Flexbox
+ align="center"
+ className={cx(styles.root, (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText)}
+ gap={6}
+ horizontal
+ >
+ <span className={styles.label}>
+ {t('builtins.lobe-group-agent-builder.apiName.updateGroupPrompt')}
+ </span>
+ {/* Show length diff when completed */}
+ {!isLoading && !isArgumentsStreaming && lengthDiff !== null && (
+ <Text
+ as="span"
+ code
+ color={lengthDiff >= 0 ? cssVar.colorSuccess : cssVar.colorError}
+ fontSize={12}
+ >
+ {lengthDiff >= 0 ? '+' : ''}
+ {lengthDiff}
+ {t('builtins.lobe-agent-builder.inspector.chars')}
+ </Text>
+ )}
+ {/* Show streaming length */}
+ {(isArgumentsStreaming || isLoading) && streamingLength > 0 && (
+ <Text as="span" code color={cssVar.colorTextDescription} fontSize={12}>
+ ({streamingLength}
+ {t('builtins.lobe-agent-builder.inspector.chars')})
+ </Text>
+ )}
+ </Flexbox>
+ );
+});
+
+UpdateGroupPromptInspector.displayName = 'UpdateGroupPromptInspector';
+
+export default UpdateGroupPromptInspector;
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Inspector/index.ts b/packages/builtin-tool-group-agent-builder/src/client/Inspector/index.ts
new file mode 100644
index 00000000000..c5488e74e54
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/client/Inspector/index.ts
@@ -0,0 +1,52 @@
+// Import shared inspectors from agent-builder
+import {
+ GetAvailableModelsInspector,
+ InstallPluginInspector,
+ SearchMarketToolsInspector,
+ UpdateConfigInspector,
+} from '@lobechat/builtin-tool-agent-builder/client';
+import { type BuiltinInspector } from '@lobechat/types';
+
+import { GroupAgentBuilderApiName } from '../../types';
+import { BatchCreateAgentsInspector } from './BatchCreateAgents';
+import { CreateAgentInspector } from './CreateAgent';
+import { InviteAgentInspector } from './InviteAgent';
+import { RemoveAgentInspector } from './RemoveAgent';
+import { SearchAgentInspector } from './SearchAgent';
+import { UpdateAgentPromptInspector } from './UpdateAgentPrompt';
+import { UpdateGroupInspector } from './UpdateGroup';
+import { UpdateGroupPromptInspector } from './UpdateGroupPrompt';
+
+/**
+ * Group Agent Builder Inspector Components Registry
+ *
+ * Inspector components customize the title/header area
+ * of tool calls in the conversation UI.
+ */
+export const GroupAgentBuilderInspectors: Record<string, BuiltinInspector> = {
+ // Group-specific inspectors
+ [GroupAgentBuilderApiName.batchCreateAgents]: BatchCreateAgentsInspector as BuiltinInspector,
+ [GroupAgentBuilderApiName.createAgent]: CreateAgentInspector as BuiltinInspector,
+ [GroupAgentBuilderApiName.inviteAgent]: InviteAgentInspector as BuiltinInspector,
+ [GroupAgentBuilderApiName.removeAgent]: RemoveAgentInspector as BuiltinInspector,
+ [GroupAgentBuilderApiName.searchAgent]: SearchAgentInspector as BuiltinInspector,
+ [GroupAgentBuilderApiName.updateAgentPrompt]: UpdateAgentPromptInspector as BuiltinInspector,
+ [GroupAgentBuilderApiName.updateGroup]: UpdateGroupInspector as BuiltinInspector,
+ [GroupAgentBuilderApiName.updateGroupPrompt]: UpdateGroupPromptInspector as BuiltinInspector,
+
+ // Shared inspectors from agent-builder (reused for group context)
+ [GroupAgentBuilderApiName.getAvailableModels]: GetAvailableModelsInspector as BuiltinInspector,
+ [GroupAgentBuilderApiName.installPlugin]: InstallPluginInspector as BuiltinInspector,
+ [GroupAgentBuilderApiName.searchMarketTools]: SearchMarketToolsInspector as BuiltinInspector,
+ [GroupAgentBuilderApiName.updateAgentConfig]: UpdateConfigInspector as BuiltinInspector,
+};
+
+// Re-export individual inspectors
+export { BatchCreateAgentsInspector } from './BatchCreateAgents';
+export { CreateAgentInspector } from './CreateAgent';
+export { InviteAgentInspector } from './InviteAgent';
+export { RemoveAgentInspector } from './RemoveAgent';
+export { SearchAgentInspector } from './SearchAgent';
+export { UpdateAgentPromptInspector } from './UpdateAgentPrompt';
+export { UpdateGroupInspector } from './UpdateGroup';
+export { UpdateGroupPromptInspector } from './UpdateGroupPrompt';
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Render/BatchCreateAgents.tsx b/packages/builtin-tool-group-agent-builder/src/client/Render/BatchCreateAgents.tsx
new file mode 100644
index 00000000000..28ce7b52cbb
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/client/Render/BatchCreateAgents.tsx
@@ -0,0 +1,103 @@
+'use client';
+
+import { BuiltinRenderProps } from '@lobechat/types';
+import { Avatar, Flexbox } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { Users } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { BatchCreateAgentsParams, BatchCreateAgentsState } from '../../types';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ container: css`
+ padding: 4px 16px;
+ background: ${cssVar.colorFillQuaternary};
+ border-radius: 8px;
+ `,
+ description: css`
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 1;
+
+ font-size: 12px;
+ line-height: 1.5;
+ color: ${cssVar.colorTextDescription};
+ text-overflow: ellipsis;
+ `,
+ empty: css`
+ padding: 16px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ item: css`
+ padding-block: 12px;
+
+ &:not(:last-child) {
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ }
+ `,
+ title: css`
+ overflow: hidden;
+
+ font-size: 13px;
+ font-weight: 500;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+}));
+
+interface AgentItemProps {
+ agent: {
+ agentId: string;
+ success: boolean;
+ title: string;
+ };
+ definition?: {
+ avatar?: string;
+ description?: string;
+ title: string;
+ };
+}
+
+const AgentItem = memo<AgentItemProps>(({ agent, definition }) => {
+ const avatar = definition?.avatar;
+ const description = definition?.description;
+
+ return (
+ <Flexbox align="center" className={styles.item} gap={12} horizontal>
+ <Avatar avatar={avatar} size={24} style={{ flexShrink: 0 }} title={agent.title} />
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0, overflow: 'hidden' }}>
+ <span className={styles.title}>{agent.title}</span>
+ {description && <span className={styles.description}>{description}</span>}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+const BatchCreateAgentsRender = memo<
+ BuiltinRenderProps<BatchCreateAgentsParams, BatchCreateAgentsState>
+>(({ args, pluginState }) => {
+ const { t } = useTranslation('plugin');
+ const { agents: resultAgents } = pluginState || {};
+ const definitions = args?.agents || [];
+
+ if (!resultAgents || resultAgents.length === 0) {
+ return (
+ <Flexbox align="center" className={styles.empty} gap={8}>
+ <Users size={24} />
+ <span>{t('builtins.lobe-group-agent-builder.inspector.noResults')}</span>
+ </Flexbox>
+ );
+ }
+
+ return (
+ <Flexbox className={styles.container}>
+ {resultAgents.map((agent, index) => (
+ <AgentItem agent={agent} definition={definitions[index]} key={agent.agentId || index} />
+ ))}
+ </Flexbox>
+ );
+});
+
+export default BatchCreateAgentsRender;
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Render/UpdateAgentPrompt/index.tsx b/packages/builtin-tool-group-agent-builder/src/client/Render/UpdateAgentPrompt/index.tsx
new file mode 100644
index 00000000000..e39e39651e0
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/client/Render/UpdateAgentPrompt/index.tsx
@@ -0,0 +1,36 @@
+'use client';
+
+import type { BuiltinRenderProps } from '@lobechat/types';
+import { Markdown } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { memo } from 'react';
+
+import type { UpdateAgentPromptParams, UpdateAgentPromptState } from '../../../types';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ container: css`
+ padding: 12px;
+ border-radius: 8px;
+ background: ${cssVar.colorFillQuaternary};
+ `,
+}));
+
+export const UpdateAgentPromptRender = memo<
+ BuiltinRenderProps<UpdateAgentPromptParams, UpdateAgentPromptState>
+>(({ pluginState }) => {
+ const prompt = pluginState?.newPrompt;
+
+ if (!prompt) return null;
+
+ return (
+ <div className={styles.container}>
+ <div>
+ <Markdown variant={'chat'}>{prompt}</Markdown>
+ </div>
+ </div>
+ );
+});
+
+UpdateAgentPromptRender.displayName = 'UpdateAgentPromptRender';
+
+export default UpdateAgentPromptRender;
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Render/UpdateGroupPrompt/index.tsx b/packages/builtin-tool-group-agent-builder/src/client/Render/UpdateGroupPrompt/index.tsx
new file mode 100644
index 00000000000..6006478495e
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/client/Render/UpdateGroupPrompt/index.tsx
@@ -0,0 +1,36 @@
+'use client';
+
+import type { BuiltinRenderProps } from '@lobechat/types';
+import { Markdown } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { memo } from 'react';
+
+import type { UpdateGroupPromptParams, UpdateGroupPromptState } from '../../../types';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ container: css`
+ padding: 12px;
+ border-radius: 8px;
+ background: ${cssVar.colorFillQuaternary};
+ `,
+}));
+
+export const UpdateGroupPromptRender = memo<
+ BuiltinRenderProps<UpdateGroupPromptParams, UpdateGroupPromptState>
+>(({ pluginState }) => {
+ const prompt = pluginState?.newPrompt;
+
+ if (!prompt) return null;
+
+ return (
+ <div className={styles.container}>
+ <div>
+ <Markdown variant={'chat'}>{prompt}</Markdown>
+ </div>
+ </div>
+ );
+});
+
+UpdateGroupPromptRender.displayName = 'UpdateGroupPromptRender';
+
+export default UpdateGroupPromptRender;
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Render/index.ts b/packages/builtin-tool-group-agent-builder/src/client/Render/index.ts
new file mode 100644
index 00000000000..3f8f7d00ab5
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/client/Render/index.ts
@@ -0,0 +1,16 @@
+import { GroupAgentBuilderApiName } from '../../types';
+import BatchCreateAgents from './BatchCreateAgents';
+import UpdateAgentPrompt from './UpdateAgentPrompt';
+import UpdateGroupPrompt from './UpdateGroupPrompt';
+
+/**
+ * Group Agent Builder Render Components Registry
+ *
+ * Render components display the results of tool calls
+ * in a user-friendly format.
+ */
+export const GroupAgentBuilderRenders = {
+ [GroupAgentBuilderApiName.batchCreateAgents]: BatchCreateAgents,
+ [GroupAgentBuilderApiName.updateAgentPrompt]: UpdateAgentPrompt,
+ [GroupAgentBuilderApiName.updateGroupPrompt]: UpdateGroupPrompt,
+};
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Streaming/BatchCreateAgents/index.tsx b/packages/builtin-tool-group-agent-builder/src/client/Streaming/BatchCreateAgents/index.tsx
new file mode 100644
index 00000000000..9dde1ed271e
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/client/Streaming/BatchCreateAgents/index.tsx
@@ -0,0 +1,88 @@
+'use client';
+
+import type { BuiltinStreamingProps } from '@lobechat/types';
+import { Avatar, Block, Flexbox, Markdown } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { memo } from 'react';
+
+import type { BatchCreateAgentsParams } from '../../../types';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ description: css`
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 2;
+
+ font-size: 12px;
+ line-height: 1.5;
+ color: ${cssVar.colorTextDescription};
+ text-overflow: ellipsis;
+ `,
+ index: css`
+ flex-shrink: 0;
+ font-size: 12px;
+ color: ${cssVar.colorTextQuaternary};
+ `,
+ item: css`
+ padding-block: 10px;
+ padding-inline: 12px;
+
+ &:not(:last-child) {
+ border-block-end: 1px dashed ${cssVar.colorBorderSecondary};
+ }
+ `,
+ systemRole: css`
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 3;
+
+ font-size: 12px;
+ line-height: 1.5;
+ color: ${cssVar.colorTextTertiary};
+ text-overflow: ellipsis;
+ `,
+ title: css`
+ overflow: hidden;
+
+ font-size: 13px;
+ font-weight: 500;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+}));
+
+export const BatchCreateAgentsStreaming = memo<BuiltinStreamingProps<BatchCreateAgentsParams>>(
+ ({ args }) => {
+ const { agents } = args || {};
+
+ if (!agents || agents.length === 0) return null;
+
+ return (
+ <Block variant={'outlined'} width="100%">
+ {agents.map((agent, index) => (
+ <Flexbox className={styles.item} gap={8} horizontal key={index}>
+ <div className={styles.index}>{index + 1}.</div>
+ <Avatar avatar={agent.avatar} size={24} style={{ flexShrink: 0 }} title={agent.title} />
+ <Flexbox flex={1} gap={4} style={{ minWidth: 0, overflow: 'hidden' }}>
+ <span className={styles.title}>{agent.title}</span>
+ {agent.description && <span className={styles.description}>{agent.description}</span>}
+ {agent.systemRole && (
+ <div className={styles.systemRole}>
+ <Markdown animated variant={'chat'}>
+ {agent.systemRole}
+ </Markdown>
+ </div>
+ )}
+ </Flexbox>
+ </Flexbox>
+ ))}
+ </Block>
+ );
+ },
+);
+
+BatchCreateAgentsStreaming.displayName = 'BatchCreateAgentsStreaming';
+
+export default BatchCreateAgentsStreaming;
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Streaming/UpdateAgentPrompt/index.tsx b/packages/builtin-tool-group-agent-builder/src/client/Streaming/UpdateAgentPrompt/index.tsx
new file mode 100644
index 00000000000..9de9c5b53cb
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/client/Streaming/UpdateAgentPrompt/index.tsx
@@ -0,0 +1,37 @@
+'use client';
+
+import type { BuiltinStreamingProps } from '@lobechat/types';
+import { Block, Markdown } from '@lobehub/ui';
+import { memo, useEffect } from 'react';
+
+import { useGroupProfileStore } from '@/store/groupProfile';
+
+import type { UpdateAgentPromptParams } from '../../../types';
+
+export const UpdateAgentPromptStreaming = memo<BuiltinStreamingProps<UpdateAgentPromptParams>>(
+ ({ args }) => {
+ const { agentId, prompt } = args || {};
+ const setActiveTabId = useGroupProfileStore((s) => s.setActiveTabId);
+
+ // Switch to agent tab when streaming agent prompt
+ useEffect(() => {
+ if (agentId) {
+ setActiveTabId(agentId);
+ }
+ }, [agentId, setActiveTabId]);
+
+ if (!prompt) return null;
+
+ return (
+ <Block padding={4} variant={'outlined'} width="100%">
+ <Markdown animated variant={'chat'}>
+ {prompt}
+ </Markdown>
+ </Block>
+ );
+ },
+);
+
+UpdateAgentPromptStreaming.displayName = 'UpdateAgentPromptStreaming';
+
+export default UpdateAgentPromptStreaming;
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Streaming/UpdateGroupPrompt/index.tsx b/packages/builtin-tool-group-agent-builder/src/client/Streaming/UpdateGroupPrompt/index.tsx
new file mode 100644
index 00000000000..e9a4a9b5161
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/client/Streaming/UpdateGroupPrompt/index.tsx
@@ -0,0 +1,35 @@
+'use client';
+
+import type { BuiltinStreamingProps } from '@lobechat/types';
+import { Block, Markdown } from '@lobehub/ui';
+import { memo, useEffect } from 'react';
+
+import { useGroupProfileStore } from '@/store/groupProfile';
+
+import type { UpdateGroupPromptParams } from '../../../types';
+
+export const UpdateGroupPromptStreaming = memo<BuiltinStreamingProps<UpdateGroupPromptParams>>(
+ ({ args }) => {
+ const { prompt } = args || {};
+ const setActiveTabId = useGroupProfileStore((s) => s.setActiveTabId);
+
+ // Switch to group tab when streaming group prompt
+ useEffect(() => {
+ setActiveTabId('group');
+ }, []);
+
+ if (!prompt) return null;
+
+ return (
+ <Block padding={4} variant={'outlined'} width="100%">
+ <Markdown animated variant={'chat'}>
+ {prompt}
+ </Markdown>
+ </Block>
+ );
+ },
+);
+
+UpdateGroupPromptStreaming.displayName = 'UpdateGroupPromptStreaming';
+
+export default UpdateGroupPromptStreaming;
diff --git a/packages/builtin-tool-group-agent-builder/src/client/Streaming/index.ts b/packages/builtin-tool-group-agent-builder/src/client/Streaming/index.ts
new file mode 100644
index 00000000000..0c34e1f979c
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/client/Streaming/index.ts
@@ -0,0 +1,22 @@
+import type { BuiltinStreaming } from '@lobechat/types';
+
+import { GroupAgentBuilderApiName } from '../../types';
+import { BatchCreateAgentsStreaming } from './BatchCreateAgents';
+import { UpdateAgentPromptStreaming } from './UpdateAgentPrompt';
+import { UpdateGroupPromptStreaming } from './UpdateGroupPrompt';
+
+/**
+ * Group Agent Builder Streaming Components Registry
+ *
+ * Streaming components render tool calls while they are
+ * still executing, allowing real-time feedback to users.
+ */
+export const GroupAgentBuilderStreamings: Record<string, BuiltinStreaming> = {
+ [GroupAgentBuilderApiName.batchCreateAgents]: BatchCreateAgentsStreaming as BuiltinStreaming,
+ [GroupAgentBuilderApiName.updateAgentPrompt]: UpdateAgentPromptStreaming as BuiltinStreaming,
+ [GroupAgentBuilderApiName.updateGroupPrompt]: UpdateGroupPromptStreaming as BuiltinStreaming,
+};
+
+export { BatchCreateAgentsStreaming } from './BatchCreateAgents';
+export { UpdateAgentPromptStreaming } from './UpdateAgentPrompt';
+export { UpdateGroupPromptStreaming } from './UpdateGroupPrompt';
diff --git a/packages/builtin-tool-group-agent-builder/src/client/index.ts b/packages/builtin-tool-group-agent-builder/src/client/index.ts
new file mode 100644
index 00000000000..5e87d072710
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/client/index.ts
@@ -0,0 +1,26 @@
+// Inspector components (customized tool call headers)
+export { GroupAgentBuilderInspectors } from './Inspector';
+export {
+ BatchCreateAgentsInspector,
+ CreateAgentInspector,
+ InviteAgentInspector,
+ RemoveAgentInspector,
+ SearchAgentInspector,
+ UpdateAgentPromptInspector,
+ UpdateGroupInspector,
+ UpdateGroupPromptInspector,
+} from './Inspector';
+
+// Render components (read-only result display)
+export { GroupAgentBuilderRenders } from './Render';
+
+// Streaming components (real-time tool execution feedback)
+export {
+ BatchCreateAgentsStreaming,
+ GroupAgentBuilderStreamings,
+ UpdateGroupPromptStreaming,
+} from './Streaming';
+
+// Re-export types and manifest for convenience
+export { GroupAgentBuilderManifest } from '../manifest';
+export * from '../types';
diff --git a/packages/builtin-tool-group-agent-builder/src/executor.ts b/packages/builtin-tool-group-agent-builder/src/executor.ts
new file mode 100644
index 00000000000..49be4b0ce41
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/executor.ts
@@ -0,0 +1,284 @@
+/**
+ * Group Agent Builder Executor
+ *
+ * Handles all group agent builder tool calls for configuring groups and their agents.
+ * Extends AgentBuilder functionality with group-specific operations.
+ */
+import type {
+ GetAvailableModelsParams,
+ InstallPluginParams,
+ SearchMarketToolsParams,
+} from '@lobechat/builtin-tool-agent-builder';
+import { AgentBuilderExecutionRuntime } from '@lobechat/builtin-tool-agent-builder/executionRuntime';
+import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@lobechat/types';
+
+import { GroupAgentBuilderExecutionRuntime } from './ExecutionRuntime';
+import {
+ type BatchCreateAgentsParams,
+ type CreateAgentParams,
+ GroupAgentBuilderApiName,
+ GroupAgentBuilderIdentifier,
+ type InviteAgentParams,
+ type RemoveAgentParams,
+ type SearchAgentParams,
+ type UpdateAgentConfigWithIdParams,
+ type UpdateAgentPromptParams,
+ type UpdateGroupParams,
+ type UpdateGroupPromptParams,
+} from './types';
+
+const agentBuilderRuntime = new AgentBuilderExecutionRuntime();
+const groupAgentBuilderRuntime = new GroupAgentBuilderExecutionRuntime();
+
+class GroupAgentBuilderExecutor extends BaseExecutor<typeof GroupAgentBuilderApiName> {
+ readonly identifier = GroupAgentBuilderIdentifier;
+ protected readonly apiEnum = GroupAgentBuilderApiName;
+
+ // ==================== Group Member Management ====================
+
+ searchAgent = async (params: SearchAgentParams): Promise<BuiltinToolResult> => {
+ const result = await groupAgentBuilderRuntime.searchAgent(params);
+ return {
+ content: result.content,
+ error: result.error
+ ? { body: result.error, message: String(result.error), type: 'RuntimeError' }
+ : undefined,
+ state: result.state,
+ success: result.success,
+ };
+ };
+
+ createAgent = async (
+ params: CreateAgentParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const groupId = ctx.groupId;
+
+ if (!groupId) {
+ return {
+ content: 'No active group found',
+ error: { message: 'No active group found', type: 'NoGroupContext' },
+ success: false,
+ };
+ }
+
+ const result = await groupAgentBuilderRuntime.createAgent(groupId, params);
+ return {
+ content: result.content,
+ error: result.error
+ ? { body: result.error, message: String(result.error), type: 'RuntimeError' }
+ : undefined,
+ state: result.state,
+ success: result.success,
+ };
+ };
+
+ batchCreateAgents = async (
+ params: BatchCreateAgentsParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const groupId = ctx.groupId;
+
+ if (!groupId) {
+ return {
+ content: 'No active group found',
+ error: { message: 'No active group found', type: 'NoGroupContext' },
+ success: false,
+ };
+ }
+
+ const result = await groupAgentBuilderRuntime.batchCreateAgents(groupId, params);
+ return {
+ content: result.content,
+ error: result.error
+ ? { body: result.error, message: String(result.error), type: 'RuntimeError' }
+ : undefined,
+ state: result.state,
+ success: result.success,
+ };
+ };
+
+ inviteAgent = async (
+ params: InviteAgentParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const groupId = ctx.groupId;
+
+ if (!groupId) {
+ return {
+ content: 'No active group found',
+ error: { message: 'No active group found', type: 'NoGroupContext' },
+ success: false,
+ };
+ }
+
+ const result = await groupAgentBuilderRuntime.inviteAgent(groupId, params);
+ return {
+ content: result.content,
+ error: result.error
+ ? { body: result.error, message: String(result.error), type: 'RuntimeError' }
+ : undefined,
+ state: result.state,
+ success: result.success,
+ };
+ };
+
+ removeAgent = async (
+ params: RemoveAgentParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const groupId = ctx.groupId;
+
+ if (!groupId) {
+ return {
+ content: 'No active group found',
+ error: { message: 'No active group found', type: 'NoGroupContext' },
+ success: false,
+ };
+ }
+
+ const result = await groupAgentBuilderRuntime.removeAgent(groupId, params);
+ return {
+ content: result.content,
+ error: result.error
+ ? { body: result.error, message: String(result.error), type: 'RuntimeError' }
+ : undefined,
+ state: result.state,
+ success: result.success,
+ };
+ };
+
+ // ==================== Group Configuration ====================
+
+ updateAgentPrompt = async (
+ params: UpdateAgentPromptParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const groupId = ctx.groupId;
+
+ if (!groupId) {
+ return {
+ content: 'No active group found',
+ error: { message: 'No active group found', type: 'NoGroupContext' },
+ success: false,
+ };
+ }
+
+ const result = await groupAgentBuilderRuntime.updateAgentPrompt(groupId, params);
+ return {
+ content: result.content,
+ error: result.error
+ ? { body: result.error, message: String(result.error), type: 'RuntimeError' }
+ : undefined,
+ state: result.state,
+ success: result.success,
+ };
+ };
+
+ updateGroup = async (params: UpdateGroupParams): Promise<BuiltinToolResult> => {
+ const result = await groupAgentBuilderRuntime.updateGroup(params);
+ return {
+ content: result.content,
+ error: result.error
+ ? { body: result.error, message: String(result.error), type: 'RuntimeError' }
+ : undefined,
+ state: result.state,
+ success: result.success,
+ };
+ };
+
+ updateGroupPrompt = async (params: UpdateGroupPromptParams): Promise<BuiltinToolResult> => {
+ const result = await groupAgentBuilderRuntime.updateGroupPrompt({
+ streaming: true,
+ ...params,
+ });
+ return {
+ content: result.content,
+ error: result.error
+ ? { body: result.error, message: String(result.error), type: 'RuntimeError' }
+ : undefined,
+ state: result.state,
+ success: result.success,
+ };
+ };
+
+ // ==================== Inherited Operations (for supervisor agent) ====================
+
+ getAvailableModels = async (params: GetAvailableModelsParams): Promise<BuiltinToolResult> => {
+ const result = await agentBuilderRuntime.getAvailableModels(params);
+ return {
+ content: result.content,
+ error: result.error
+ ? { body: result.error, message: String(result.error), type: 'RuntimeError' }
+ : undefined,
+ state: result.state,
+ success: result.success,
+ };
+ };
+
+ searchMarketTools = async (params: SearchMarketToolsParams): Promise<BuiltinToolResult> => {
+ const result = await agentBuilderRuntime.searchMarketTools(params);
+ return {
+ content: result.content,
+ error: result.error
+ ? { body: result.error, message: String(result.error), type: 'RuntimeError' }
+ : undefined,
+ state: result.state,
+ success: result.success,
+ };
+ };
+
+ updateConfig = async (
+ params: UpdateAgentConfigWithIdParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ // Use provided agentId or fall back to supervisor agent from context
+ const { agentId: paramAgentId, ...restParams } = params;
+ const agentId = paramAgentId ?? ctx.agentId;
+
+ if (!agentId) {
+ return {
+ content: 'No agent found. Please provide an agentId or ensure supervisor context is available.',
+ error: { message: 'No agent found', type: 'NoAgentContext' },
+ success: false,
+ };
+ }
+
+ const result = await agentBuilderRuntime.updateAgentConfig(agentId, restParams);
+ return {
+ content: result.content,
+ error: result.error
+ ? { body: result.error, message: String(result.error), type: 'RuntimeError' }
+ : undefined,
+ state: result.state,
+ success: result.success,
+ };
+ };
+
+ installPlugin = async (
+ params: InstallPluginParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const agentId = ctx.agentId;
+
+ if (!agentId) {
+ return {
+ content: 'No supervisor agent found',
+ error: { message: 'No supervisor agent found', type: 'NoAgentContext' },
+ success: false,
+ };
+ }
+
+ const result = await agentBuilderRuntime.installPlugin(agentId, params);
+ return {
+ content: result.content,
+ error: result.error
+ ? { body: result.error, message: String(result.error), type: 'RuntimeError' }
+ : undefined,
+ state: result.state,
+ success: result.success,
+ };
+ };
+}
+
+export const groupAgentBuilderExecutor = new GroupAgentBuilderExecutor();
diff --git a/packages/builtin-tool-group-agent-builder/src/index.ts b/packages/builtin-tool-group-agent-builder/src/index.ts
index 8ded2146b67..31124147ca2 100644
--- a/packages/builtin-tool-group-agent-builder/src/index.ts
+++ b/packages/builtin-tool-group-agent-builder/src/index.ts
@@ -1,16 +1,3 @@
export { GroupAgentBuilderManifest } from './manifest';
export { systemPrompt } from './systemRole';
-export {
- GroupAgentBuilderApiName,
- type GroupAgentBuilderApiNameType,
- GroupAgentBuilderIdentifier,
- type InviteAgentParams,
- type InviteAgentState,
- type RemoveAgentParams,
- type RemoveAgentState,
- type UpdateGroupConfigParams,
- type UpdateGroupConfigState,
- type UpdateGroupMetaParams,
- type UpdateGroupPromptParams,
- type UpdateGroupPromptState,
-} from './types';
+export * from './types';
diff --git a/packages/builtin-tool-group-agent-builder/src/manifest.ts b/packages/builtin-tool-group-agent-builder/src/manifest.ts
index 05bca5c9373..739dd10b564 100644
--- a/packages/builtin-tool-group-agent-builder/src/manifest.ts
+++ b/packages/builtin-tool-group-agent-builder/src/manifest.ts
@@ -6,6 +6,111 @@ import { GroupAgentBuilderApiName, GroupAgentBuilderIdentifier } from './types';
export const GroupAgentBuilderManifest: BuiltinToolManifest = {
api: [
// ==================== Group Member Management ====================
+ {
+ description:
+ "Search for agents that can be invited to the group. Returns agents from the user's collection. Use this to find suitable agents before inviting them.",
+ name: GroupAgentBuilderApiName.searchAgent,
+ parameters: {
+ properties: {
+ limit: {
+ default: 10,
+ description: 'Maximum number of results to return (default: 10, max: 20).',
+ maximum: 20,
+ minimum: 1,
+ type: 'number',
+ },
+ query: {
+ description:
+ 'Search query to find agents by name, description, or capabilities. Leave empty to browse all available agents.',
+ type: 'string',
+ },
+ },
+ required: [],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Create a new agent dynamically based on user requirements and add it to the group. Use this when no existing agent matches the needed expertise.',
+ humanIntervention: 'required',
+ name: GroupAgentBuilderApiName.createAgent,
+ parameters: {
+ properties: {
+ avatar: {
+ description: "An emoji or image URL for the agent's avatar (optional).",
+ type: 'string',
+ },
+ description: {
+ description: 'A brief description of what this agent does and its expertise.',
+ type: 'string',
+ },
+ systemRole: {
+ description:
+ "The system prompt that defines the agent's behavior, personality, and capabilities.",
+ type: 'string',
+ },
+ title: {
+ description: 'The display name for the new agent.',
+ type: 'string',
+ },
+ tools: {
+ description:
+ 'Array of tool identifiers to enable for this agent. Use identifiers from official_tools context (e.g., "lobe-cloud-sandbox", "web-crawler").',
+ items: { type: 'string' },
+ type: 'array',
+ },
+ },
+ required: ['title', 'systemRole'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Create multiple agents at once and add them to the group. Use this to efficiently set up a team of agents with different expertise.',
+ humanIntervention: 'required',
+ name: GroupAgentBuilderApiName.batchCreateAgents,
+ parameters: {
+ properties: {
+ agents: {
+ description: 'Array of agent definitions to create',
+ items: {
+ properties: {
+ /* eslint-disable sort-keys-fix/sort-keys-fix */
+ avatar: {
+ description: "An emoji or image URL for the agent's avatar (optional).",
+ type: 'string',
+ },
+ title: {
+ description: 'The display name for the new agent.',
+ type: 'string',
+ },
+ description: {
+ description: 'A brief description of what this agent does and its expertise.',
+ type: 'string',
+ },
+ systemRole: {
+ description:
+ "The system prompt that defines the agent's behavior, personality, and capabilities.",
+ type: 'string',
+ },
+ tools: {
+ description:
+ 'Array of tool identifiers to enable for this agent. Use identifiers from official_tools context (e.g., "lobe-cloud-sandbox", "web-crawler").',
+ items: { type: 'string' },
+ type: 'array',
+ },
+ /* eslint-enable sort-keys-fix/sort-keys-fix */
+ },
+ required: ['avatar', 'title', 'description', 'systemRole'],
+ type: 'object',
+ },
+ type: 'array',
+ },
+ },
+ required: ['agents'],
+ type: 'object',
+ },
+ },
{
description:
'Invite an existing agent to join the group. The agent will become a member and participate in group conversations.',
@@ -104,10 +209,14 @@ export const GroupAgentBuilderManifest: BuiltinToolManifest = {
},
{
description:
- 'Update supervisor agent configuration (model, provider, plugins, etc.). Only include fields you want to update.',
+ 'Update agent configuration (model, provider, plugins, etc.). If agentId is not provided, updates the supervisor agent.',
name: GroupAgentBuilderApiName.updateAgentConfig,
parameters: {
properties: {
+ agentId: {
+ description: 'The agent ID to update. If not provided, updates the supervisor agent.',
+ type: 'string',
+ },
config: {
description:
'Partial agent configuration object. Only include fields you want to update.',
@@ -139,7 +248,7 @@ export const GroupAgentBuilderManifest: BuiltinToolManifest = {
type: 'object',
},
togglePlugin: {
- description: 'Toggle a specific plugin on/off for the supervisor agent.',
+ description: 'Toggle a specific plugin on/off for the agent.',
properties: {
enabled: {
description: 'Whether to enable (true) or disable (false) the plugin.',
@@ -159,29 +268,27 @@ export const GroupAgentBuilderManifest: BuiltinToolManifest = {
},
},
{
- description:
- "Update the group's system prompt. This is the instruction that defines how agents in the group should collaborate and interact.",
- name: GroupAgentBuilderApiName.updatePrompt,
+ description: "Update a specific agent's system prompt (systemRole).",
+ name: GroupAgentBuilderApiName.updateAgentPrompt,
parameters: {
properties: {
- prompt: {
- description: 'The new group system prompt content. Supports markdown formatting.',
+ agentId: {
+ description: 'The agent ID to update.',
type: 'string',
},
- streaming: {
- description:
- 'Whether to use streaming mode for typewriter effect in the editor. Defaults to true.',
- type: 'boolean',
+ prompt: {
+ description: 'The new system prompt content. Supports markdown formatting.',
+ type: 'string',
},
},
- required: ['prompt'],
+ required: ['agentId', 'prompt'],
type: 'object',
},
},
{
description:
- "Update the group's configuration including opening message and opening questions. Use this to set the welcome experience when users start a new conversation with the group.",
- name: GroupAgentBuilderApiName.updateGroupConfig,
+ "Update the group's configuration and metadata. Use this to customize the group's appearance and welcome experience.",
+ name: GroupAgentBuilderApiName.updateGroup,
parameters: {
properties: {
config: {
@@ -202,8 +309,46 @@ export const GroupAgentBuilderManifest: BuiltinToolManifest = {
},
type: 'object',
},
+ meta: {
+ description: 'Partial metadata object. Only include fields you want to update.',
+ properties: {
+ avatar: {
+ description: "An emoji or image URL for the group's avatar.",
+ type: 'string',
+ },
+ backgroundColor: {
+ description: 'Background color for the group avatar (hex color code).',
+ type: 'string',
+ },
+ description: {
+ description: 'A brief description of the group.',
+ type: 'string',
+ },
+ title: {
+ description: 'The display name for the group.',
+ type: 'string',
+ },
+ },
+ type: 'object',
+ },
+ },
+ required: [],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ "Update the group's shared prompt/content. This content is shared with all group members and defines the group's goals, workflow, or other shared information.",
+ name: GroupAgentBuilderApiName.updateGroupPrompt,
+ parameters: {
+ properties: {
+ prompt: {
+ description:
+ "The new shared prompt/content for the group. Supports markdown formatting. This content will be visible to all group members and helps define the group's working context.",
+ type: 'string',
+ },
},
- required: ['config'],
+ required: ['prompt'],
type: 'object',
},
},
diff --git a/packages/builtin-tool-group-agent-builder/src/systemRole.ts b/packages/builtin-tool-group-agent-builder/src/systemRole.ts
index 27d428358d1..d04d75add43 100644
--- a/packages/builtin-tool-group-agent-builder/src/systemRole.ts
+++ b/packages/builtin-tool-group-agent-builder/src/systemRole.ts
@@ -11,9 +11,9 @@ export const systemPrompt = `You are a Group Configuration Assistant integrated
The injected context includes:
- **group_meta**: title, description
-- **group_config**: systemPrompt (group-level instruction), orchestratorModel, orchestratorProvider, responseOrder, responseSpeed
+- **group_config**: systemPrompt (group-level shared content)
- **group_members**: List of agents in the group with their names, avatars, and roles (including the supervisor agent)
-- **supervisor_agent**: The supervisor agent's configuration (model, provider, plugins)
+- **supervisor_agent**: The supervisor agent's configuration (model, provider, plugins, systemRole)
- **official_tools**: List of available official tools including built-in tools and Klavis integrations
You should use this context to understand the current state of the group and its members before making any modifications.
@@ -23,7 +23,10 @@ You should use this context to understand the current state of the group and its
You have access to tools that can modify group configurations:
**Group Member Management:**
+- **searchAgent**: Search for agents that can be invited to the group from the user's collection
- **inviteAgent**: Invite an existing agent to join the group by their agent ID
+- **createAgent**: Create a new agent dynamically and add it to the group. **IMPORTANT**: Always include appropriate tools based on the agent's role.
+- **batchCreateAgents**: Create multiple agents at once and add them to the group. **IMPORTANT**: Each agent should have role-appropriate tools.
- **removeAgent**: Remove an agent from the group (cannot remove the supervisor agent)
**Read Operations:**
@@ -31,37 +34,151 @@ You have access to tools that can modify group configurations:
- **searchMarketTools**: Search for tools (MCP plugins) in the marketplace for the supervisor agent
**Write Operations (for Group):**
-- **updatePrompt**: Update the group's system prompt (the instruction that guides how agents collaborate)
-- **updateGroupConfig**: Update group configuration including opening message and opening questions
+- **updateGroupPrompt**: Update the group's shared prompt (content shared by ALL group members)
+- **updateGroup**: Update group metadata and configuration including opening message and opening questions
-**Write Operations (for Supervisor Agent):**
-- **updateConfig**: Update supervisor agent configuration (model, provider, plugins, etc.)
-- **togglePlugin**: Enable or disable a specific plugin for the supervisor agent
+**Write Operations (for Agent):**
+- **updateAgentPrompt**: Update any agent's system prompt (requires agentId). Can be used for both supervisor and member agents.
+- **updateConfig**: Update agent configuration (model, provider, plugins, etc.). If agentId is not provided, updates the supervisor agent.
- **installPlugin**: Install and enable a plugin for the supervisor agent
</capabilities>
+<prompt_architecture>
+**IMPORTANT: There are TWO types of prompts in a group:**
+
+1. **Group Prompt** (updated via \`updateGroupPrompt\`):
+ - Shared content that ALL group members (including supervisor and sub-agents) can access
+ - Contains background knowledge, project context, shared guidelines, or reference materials
+ - **DO NOT include member information** - the system automatically injects group member details into the context
+ - Think of this as a "shared document" or "knowledge base" for the entire group
+
+2. **Agent Prompt** (updated via \`updateAgentPrompt\` with any agent's agentId):
+ - The system role/instruction for a specific agent (can be supervisor OR any member agent)
+ - For **supervisor agent**: defines orchestration logic, delegation strategy, coordination behavior
+ - For **member agents**: defines their expertise, personality, response style, and capabilities
+ - Each agent's prompt is private to that agent, NOT shared with other agents
+
+**When to use which:**
+- User wants to add shared context/knowledge → use \`updateGroupPrompt\`
+- User wants to change how a specific agent behaves → use \`updateAgentPrompt\` with that agent's ID
+- User mentions "group prompt", "shared content", "background info" → use \`updateGroupPrompt\`
+- User mentions "agent behavior", "agent prompt", specific agent name → use \`updateAgentPrompt\`
+</prompt_architecture>
+
+<supervisor_prompt_generation>
+**CRITICAL: Auto-generate Supervisor Prompt After Member Changes**
+
+After ANY member change (createAgent, batchCreateAgents, inviteAgent, removeAgent), you MUST automatically update the supervisor's prompt. Use the following template structure:
+
+**Supervisor Prompt Template:**
+\`\`\`
+You are the Supervisor of this group, responsible for coordinating and orchestrating conversations among team members.
+
+## Orchestration Strategy
+
+1. **Task Analysis**: When receiving a user request, first analyze what type of expertise is needed.
+
+2. **Delegation Rules**:
+ {Generate specific rules based on the actual members, for example:}
+ - For coding/technical questions → delegate to [Developer Agent]
+ - For design/UI discussions → delegate to [Designer Agent]
+ - For general questions or coordination → handle yourself
+
+3. **Collaboration Patterns**:
+ - For complex tasks requiring multiple expertise → coordinate sequential or parallel involvement
+ - Summarize and synthesize responses from multiple agents when needed
+
+4. **Fallback Handling**:
+ - If no specific agent fits → handle the request yourself
+ - If clarification needed → ask the user before delegating
+
+## Response Guidelines
+
+- Always acknowledge which agent(s) will handle the request
+- Provide context when delegating to help the agent understand the task
+- Synthesize multi-agent responses into coherent answers for the user
+\`\`\`
+
+**Generation Rules:**
+1. Analyze each member's title, description, and systemRole to understand their expertise
+2. Create specific delegation rules based on actual member capabilities
+3. Identify potential collaboration scenarios between members
+4. Keep the prompt concise but comprehensive
+5. Use the same language as the user's conversation
+</supervisor_prompt_generation>
+
+<agent_tools_assignment>
+**CRITICAL: Assign Appropriate Tools When Creating Agents**
+
+When creating agents (via \`createAgent\` or \`batchCreateAgents\`), you MUST analyze the agent's role and assign relevant tools from the \`official_tools\` context. Agents without proper tools cannot perform their specialized tasks effectively.
+
+**Tool Assignment Strategy:**
+1. **Analyze the agent's role**: What tasks will this agent perform?
+2. **Match tools to capabilities**: Select tools that enable those tasks
+3. **Include the tools array**: Always specify the \`tools\` parameter with appropriate tool identifiers
+
+**Common Tool Mappings (reference the actual \`official_tools\` context for available tools):**
+
+| Agent Role | Recommended Tools | Rationale |
+|------------|-------------------|-----------|
+| Researcher / Analyst | web-crawler, search tools | Need to gather and analyze information |
+| Developer / Coder | lobe-cloud-sandbox, code execution tools | Need to write and run code |
+| Data Scientist | lobe-cloud-sandbox, data analysis tools | Need computational environment |
+| Writer / Editor | web-crawler (for research) | May need reference materials |
+| Financial / Trading | relevant MCP integrations, sandbox | Need market data and calculations |
+| Designer | image generation tools | Need to create visual assets |
+
+**Example - Quant Trading Team:**
+- **Quant Researcher**: tools: ["web-crawler", "lobe-cloud-sandbox"] - for market research and data analysis
+- **Execution Specialist**: tools: ["trading-mcp", "lobe-cloud-sandbox"] - for executing trades and backtesting
+- **Risk Manager**: tools: ["lobe-cloud-sandbox"] - for risk calculations
+
+**Rules:**
+1. NEVER create an agent without considering what tools it needs
+2. Reference \`official_tools\` in the context to see available tool identifiers
+3. If a specialized tool doesn't exist, note this limitation to the user
+4. Tools enable agent capabilities - an agent without tools is limited to conversation only
+</agent_tools_assignment>
+
<workflow>
1. **Understand the request**: Listen carefully to what the user wants to configure
2. **Reference injected context**: Use the \`<current_group_context>\` to understand current state - no need to call read APIs
-3. **Make targeted changes**: Use the appropriate API based on whether you're modifying the group or the supervisor agent
-4. **Confirm changes**: Report what was changed and the new values
+3. **Distinguish prompt types**: Determine if the user wants to modify shared content (group prompt) or a specific agent's behavior (agent prompt)
+4. **Make targeted changes**: Use the appropriate API based on whether you're modifying the group or a specific agent
+5. **Update supervisor prompt after member changes**: **IMPORTANT** - After ANY member change (create, invite, or remove agent), you MUST automatically update the supervisor's prompt using \`updateAgentPrompt\` with the supervisor's agentId. Generate an appropriate orchestration prompt based on the current members.
+6. **Confirm changes**: Report what was changed and the new values
</workflow>
<guidelines>
1. **Use injected context**: The current group's config and member list are already available. Reference them directly instead of calling read APIs.
-2. **Distinguish group vs agent operations**:
- - Group-level: updatePrompt (group systemPrompt), inviteAgent, removeAgent
- - Supervisor agent-level: updateConfig, togglePlugin, installPlugin (for model, plugins, etc.)
-3. **Explain your changes**: When modifying configurations, explain what you're changing and why it might benefit the group collaboration.
-4. **Validate user intent**: For significant changes (like removing an agent), confirm with the user before proceeding.
-5. **Provide recommendations**: When users ask for advice, consider how changes affect multi-agent collaboration.
-6. **Use user's language**: Always respond in the same language the user is using.
-7. **Cannot remove supervisor**: The supervisor agent cannot be removed from the group - it's the orchestrator.
+2. **Distinguish group vs agent prompts**:
+ - Group prompt: Shared content for all members, NO member info needed (auto-injected)
+ - Agent prompt: Individual agent's system role (supervisor or member), requires agentId
+3. **Distinguish group vs agent operations**:
+ - Group-level: updateGroupPrompt, updateGroup, inviteAgent, removeAgent, batchCreateAgents
+ - Agent-level: updateAgentPrompt (requires agentId), updateConfig (agentId optional, defaults to supervisor), installPlugin
+4. **CRITICAL - Auto-update supervisor after member changes**: After ANY member change (create, invite, remove), you MUST automatically call \`updateAgentPrompt\` with supervisor's agentId to regenerate the orchestration prompt. This is NOT optional - the supervisor needs updated delegation rules to coordinate the team effectively.
+5. **CRITICAL - Assign tools when creating agents**: When using \`createAgent\` or \`batchCreateAgents\`, ALWAYS include appropriate \`tools\` based on the agent's role. Reference \`official_tools\` in the context for available tool identifiers. An agent without proper tools cannot perform specialized tasks.
+6. **Explain your changes**: When modifying configurations, explain what you're changing and why it might benefit the group collaboration.
+7. **Validate user intent**: For significant changes (like removing an agent), confirm with the user before proceeding.
+8. **Provide recommendations**: When users ask for advice, consider how changes affect multi-agent collaboration.
+9. **Use user's language**: Always respond in the same language the user is using.
+10. **Cannot remove supervisor**: The supervisor agent cannot be removed from the group - it's the orchestrator.
</guidelines>
<configuration_knowledge>
+**Group Prompt (Shared Content):**
+- Content that all group members can access and reference
+- Suitable for: project background, domain knowledge, shared guidelines, reference materials
+- NOT for: member lists (auto-injected), coordination rules (use agent prompt)
+
+**Agent Prompt (via updateAgentPrompt with agentId):**
+- Updates any agent's system prompt - both supervisor and member agents
+- **Supervisor agent**: defines orchestration logic, delegation strategy, coordination behavior
+- **Member agents**: defines their expertise, personality, response style, and capabilities
+- Each agent's prompt is private to that agent
+
**Group Configuration:**
-- systemPrompt: The group-level instruction that defines how agents should collaborate and interact
- orchestratorModel: The model used for orchestrating multi-agent conversations
- orchestratorProvider: The provider for the orchestrator model
- responseOrder: How agents respond ("sequential" or "natural")
@@ -69,64 +186,133 @@ You have access to tools that can modify group configurations:
- openingMessage: The welcome message shown when starting a new conversation with the group
- openingQuestions: Suggested questions to help users get started with the group conversation
-**Supervisor Agent Configuration:**
-- model: The AI model for the supervisor agent
+**Agent Configuration (via updateConfig):**
+- model: The AI model for the agent
- provider: The AI provider
-- plugins: Tools enabled for the supervisor agent
-- The supervisor orchestrates the conversation and coordinates other agents
+- plugins: Tools enabled for the agent
+- If agentId is not provided, updates the supervisor agent by default
**Group Members:**
- Each group has one supervisor agent and zero or more member agents
- Member agents can be invited or removed
- The supervisor agent cannot be removed (it's essential for group coordination)
-
-**System Prompt vs Agent Prompt:**
-- Group systemPrompt: Defines collaboration rules for the entire group
-- Agent systemRole: Individual agent's personality and expertise (not modified here)
</configuration_knowledge>
<examples>
-User: "帮我邀请一个 Agent 到群组"
-Action: Ask which agent they want to invite (need the agent ID), then use inviteAgent
+<example>
+User: "Invite an agent to the group"
+Action:
+1. Use searchAgent to find available agents, show the results to user
+2. Use inviteAgent with the selected agent ID
+3. **Then automatically** use updateAgentPrompt with supervisor's agentId to update orchestration prompt with the newly invited agent's delegation rules
+</example>
+
+<example>
+User: "Add a developer agent to help with coding"
+Action:
+1. Use searchAgent with query "developer" or "coding" to find relevant agents
+2. Use inviteAgent or createAgent if no suitable agent exists. If creating, include tools: ["lobe-cloud-sandbox"] for code execution
+3. **Then automatically** use updateAgentPrompt with supervisor's agentId to update orchestration prompt with the new developer agent's delegation rules
+</example>
+
+<example>
+User: "Create a marketing expert for this group"
+Action:
+1. Use createAgent with title "Marketing Expert", appropriate systemRole, description, and tools: ["web-crawler"] for research capabilities
+2. **Then automatically** use updateAgentPrompt with supervisor's agentId to update orchestration prompt, adding delegation rules for marketing-related tasks
+</example>
+
+<example>
+User: "Create 3 expert agents for me"
+Action:
+1. Use batchCreateAgents to create multiple agents at once with their respective titles, systemRoles, descriptions, and **appropriate tools for each agent's role**
+2. **Then automatically** use updateAgentPrompt with supervisor's agentId to generate orchestration prompt that includes delegation rules for all 3 new experts
+</example>
+<example>
+User: "Create a quant trading team"
+Action:
+1. Use batchCreateAgents with agents like:
+ - Quant Researcher: tools: ["web-crawler", "lobe-cloud-sandbox"] for market research and data analysis
+ - Execution Specialist: tools: ["lobe-cloud-sandbox"] for backtesting and trade simulation (note: if specific trading MCP is needed, check official_tools or recommend installing one)
+ - Risk Manager: tools: ["lobe-cloud-sandbox"] for risk calculations
+2. **Then automatically** use updateAgentPrompt with supervisor's agentId to generate orchestration prompt with delegation rules for quant workflows
+</example>
+
+<example>
User: "Remove the coding assistant from the group"
-Action: Check the group members in context, find the agent ID for "coding assistant", then use removeAgent
+Action:
+1. Check the group members in context, find the agent ID for "coding assistant"
+2. Use removeAgent to remove the agent
+3. **Then automatically** use updateAgentPrompt with supervisor's agentId to update orchestration prompt, removing the delegation rules for the removed agent
+</example>
+<example>
User: "What agents are in this group?"
Action: Reference the \`<group_members>\` from the injected context and display the list
+</example>
-User: "Change the group's system prompt to encourage more collaboration"
-Action: Reference the current systemPrompt from context, then use updatePrompt to update it
+<example>
+User: "Add some background information about our project to the group"
+Action: Use updateGroupPrompt to add the project context as shared content for all members
+</example>
-User: "帮我把主持人的模型改成 Claude"
-Action: Use updateConfig with { config: { model: "claude-sonnet-4-5-20250929", provider: "anthropic" } } for the supervisor agent
+<example>
+User: "Update the group's shared knowledge base"
+Action: Use updateGroupPrompt - this is shared content, do NOT include member information (auto-injected)
+</example>
-User: "Enable web browsing for the supervisor"
-Action: Use togglePlugin with pluginId "lobe-web-browsing" and enabled: true
+<example>
+User: "Change how the supervisor coordinates the team"
+Action: Use updateAgentPrompt with the supervisor's agentId to update orchestration logic
+</example>
-User: "What can the supervisor agent do?"
-Action: Reference the \`<supervisor_agent>\` config from the context, including model, plugins, etc.
+<example>
+User: "Make the supervisor more proactive in assigning tasks"
+Action: Use updateAgentPrompt with supervisor's agentId to update coordination strategy
+</example>
-User: "Set the response order to sequential"
-Action: This is a group-level config, use updatePrompt or mention this needs to be changed in group settings
+<example>
+User: "Update the coding assistant's prompt to focus more on Python"
+Action: Find the coding assistant's agentId from group_members context, then use updateAgentPrompt with that agentId
+</example>
-User: "帮我添加一些新的工具给这个群组"
+<example>
+User: "Modify the designer agent's prompt"
+Action: Find the designer agent's agentId from group_members context, then use updateAgentPrompt with that agentId
+</example>
+
+<example>
+User: "Change the supervisor's model to Claude"
+Action: Use updateConfig with { config: { model: "claude-sonnet-4-5-20250929", provider: "anthropic" } } for the supervisor agent
+</example>
+
+<example>
+User: "What can the supervisor agent do?"
+Action: Reference the \`<supervisor_agent>\` config from the context, including model, tools, etc.
+</example>
+
+<example>
+User: "Add some new tools to this group"
Action: Use searchMarketTools to find tools, then use installPlugin for the supervisor agent
+</example>
+<example>
User: "Set a welcome message for this group"
-Action: Use updateGroupConfig with { config: { openingMessage: "Welcome to the team! We're here to help you with your project." } }
-
-User: "帮我设置一些开场问题"
-Action: Use updateGroupConfig with { config: { openingQuestions: ["What project are you working on?", "How can we help you today?", "Do you have any specific questions?"] } }
+Action: Use updateGroup with { config: { openingMessage: "Welcome to the team! We're here to help you with your project." } }
+</example>
-User: "Remove the opening message"
-Action: Use updateGroupConfig with { config: { openingMessage: "" } }
+<example>
+User: "Set some opening questions"
+Action: Use updateGroup with { config: { openingQuestions: ["What project are you working on?", "How can we help you today?", "Do you have any specific questions?"] } }
+</example>
</examples>
<response_format>
- When showing configuration, format it in a clear, readable way using markdown
- When making changes, clearly state what was changed (before → after)
- Distinguish between group-level and agent-level changes
+- Clarify whether you're updating shared content (group prompt) or a specific agent's prompt
- Use bullet points for listing multiple items
- Keep responses concise but informative
</response_format>`;
diff --git a/packages/builtin-tool-group-agent-builder/src/types.ts b/packages/builtin-tool-group-agent-builder/src/types.ts
index 36a9afc112f..84e49b19cf2 100644
--- a/packages/builtin-tool-group-agent-builder/src/types.ts
+++ b/packages/builtin-tool-group-agent-builder/src/types.ts
@@ -1,3 +1,4 @@
+import type { UpdateAgentConfigParams } from '@lobechat/builtin-tool-agent-builder';
import type { MetaData } from '@lobechat/types';
/**
@@ -9,22 +10,29 @@ export const GroupAgentBuilderIdentifier = 'lobe-group-agent-builder';
* Group Agent Builder API Names
*/
export const GroupAgentBuilderApiName = {
+ // Group member management operations
+ batchCreateAgents: 'batchCreateAgents',
+ createAgent: 'createAgent',
+
// Read operations (inherited from AgentBuilder)
getAvailableModels: 'getAvailableModels',
+
// Write operations (inherited from AgentBuilder)
installPlugin: 'installPlugin',
- // Group-specific operations
inviteAgent: 'inviteAgent',
removeAgent: 'removeAgent',
+ searchAgent: 'searchAgent',
+
searchMarketTools: 'searchMarketTools',
updateAgentConfig: 'updateConfig',
- // Group config operations
- updateGroupConfig: 'updateGroupConfig',
- updatePrompt: 'updatePrompt',
+ // Group operations
+ updateAgentPrompt: 'updateAgentPrompt',
+ updateGroup: 'updateGroup',
+ updateGroupPrompt: 'updateGroupPrompt',
} as const;
export type GroupAgentBuilderApiNameType =
@@ -32,79 +40,99 @@ export type GroupAgentBuilderApiNameType =
// ============== Group-specific Parameter Types ==============
-export interface InviteAgentParams {
+export interface SearchAgentParams {
/**
- * Agent identifier to invite to the group
+ * Maximum number of results to return
*/
- agentId: string;
-}
-
-export interface RemoveAgentParams {
+ limit?: number;
/**
- * Agent identifier to remove from the group
+ * Search query to find agents by name or description
*/
- agentId: string;
+ query?: string;
}
-export interface UpdateGroupPromptParams {
+export interface CreateAgentParams {
/**
- * The new system prompt content for the group (markdown format)
+ * An emoji or image URL for the agent's avatar
*/
- prompt: string;
+ avatar?: string;
/**
- * Whether to use streaming mode for typewriter effect
+ * A brief description of what this agent does
*/
- streaming?: boolean;
+ description?: string;
+ /**
+ * The system prompt that defines the agent's behavior
+ */
+ systemRole: string;
+ /**
+ * The display name for the new agent
+ */
+ title: string;
+ /**
+ * List of tool identifiers to enable for this agent.
+ * Use the same identifiers as shown in official_tools context.
+ */
+ tools?: string[];
}
-export interface UpdateGroupMetaParams {
+export interface InviteAgentParams {
/**
- * Partial metadata to update for the group
+ * Agent identifier to invite to the group
*/
- meta?: Partial<Pick<MetaData, 'title' | 'description' | 'avatar' | 'backgroundColor' | 'tags'>>;
+ agentId: string;
}
-// ============== State Types (for Render components) ==============
-
-export interface InviteAgentState {
+export interface RemoveAgentParams {
/**
- * Agent identifier that was invited
+ * Agent identifier to remove from the group
*/
agentId: string;
+}
+
+export interface UpdateAgentPromptParams {
/**
- * Agent display name
+ * The agent ID to update
*/
- agentName?: string;
+ agentId: string;
/**
- * Whether the operation was successful
+ * The new system prompt content (markdown format)
*/
- success: boolean;
+ prompt: string;
}
-export interface RemoveAgentState {
+export interface UpdateAgentPromptState {
/**
- * Agent identifier that was removed
+ * The agent ID that was updated
*/
agentId: string;
/**
- * Agent display name
+ * The new prompt
*/
- agentName?: string;
+ newPrompt: string;
+ /**
+ * The previous prompt
+ */
+ previousPrompt?: string;
/**
* Whether the operation was successful
*/
success: boolean;
}
-export interface UpdateGroupPromptState {
- newPrompt: string;
- previousPrompt?: string;
- success: boolean;
+/**
+ * Extended UpdateAgentConfigParams with optional agentId for group context
+ */
+export interface UpdateAgentConfigWithIdParams extends UpdateAgentConfigParams {
+ /**
+ * The agent ID to update. If not provided, updates the supervisor agent.
+ */
+ agentId?: string;
}
-// ============== Group Config Types ==============
-
-export interface UpdateGroupConfigParams {
+/**
+ * Unified params for updating group (combines config and meta)
+ */
+export interface UpdateGroupParams {
/**
* Partial group configuration to update
*/
@@ -118,9 +146,13 @@ export interface UpdateGroupConfigParams {
*/
openingQuestions?: string[];
};
+ /**
+ * Partial metadata to update for the group
+ */
+ meta?: Partial<Pick<MetaData, 'avatar' | 'backgroundColor' | 'description' | 'tags' | 'title'>>;
}
-export interface UpdateGroupConfigState {
+export interface UpdateGroupState {
/**
* Whether the operation was successful
*/
@@ -128,8 +160,126 @@ export interface UpdateGroupConfigState {
/**
* The updated configuration values
*/
- updatedConfig: {
+ updatedConfig?: {
openingMessage?: string;
openingQuestions?: string[];
};
+ /**
+ * The updated metadata values
+ */
+ updatedMeta?: Partial<
+ Pick<MetaData, 'avatar' | 'backgroundColor' | 'description' | 'tags' | 'title'>
+ >;
+}
+
+export interface UpdateGroupPromptParams {
+ /**
+ * The new shared prompt/content for the group (markdown format)
+ */
+ prompt: string;
+ /**
+ * Whether to use streaming mode for typewriter effect
+ */
+ streaming?: boolean;
+}
+
+export interface UpdateGroupPromptState {
+ /**
+ * The new prompt
+ */
+ newPrompt: string;
+ /**
+ * The previous prompt
+ */
+ previousPrompt?: string;
+ /**
+ * Whether the operation was successful
+ */
+ success: boolean;
+}
+
+export interface BatchCreateAgentsParams {
+ /**
+ * Array of agents to create
+ */
+ agents: CreateAgentParams[];
+}
+
+export interface BatchCreateAgentsState {
+ /**
+ * Created agents info
+ */
+ agents: Array<{
+ agentId: string;
+ success: boolean;
+ title: string;
+ }>;
+ /**
+ * Number of agents that failed to create
+ */
+ failedCount: number;
+ /**
+ * Number of agents successfully created
+ */
+ successCount: number;
+}
+
+// ============== State Types (for Render components) ==============
+
+export interface SearchAgentResult {
+ avatar?: string;
+ description?: string;
+ id: string;
+ title: string;
+}
+
+export interface SearchAgentState {
+ agents: SearchAgentResult[];
+ query?: string;
+ total: number;
+}
+
+export interface CreateAgentState {
+ /**
+ * The ID of the created agent
+ */
+ agentId: string;
+ /**
+ * Whether the operation was successful
+ */
+ success: boolean;
+ /**
+ * The title of the created agent
+ */
+ title: string;
+}
+
+export interface InviteAgentState {
+ /**
+ * Agent identifier that was invited
+ */
+ agentId: string;
+ /**
+ * Agent display name
+ */
+ agentName?: string;
+ /**
+ * Whether the operation was successful
+ */
+ success: boolean;
+}
+
+export interface RemoveAgentState {
+ /**
+ * Agent identifier that was removed
+ */
+ agentId: string;
+ /**
+ * Agent display name
+ */
+ agentName?: string;
+ /**
+ * Whether the operation was successful
+ */
+ success: boolean;
}
diff --git a/packages/builtin-tool-group-management/src/client/Inspector/Broadcast/index.tsx b/packages/builtin-tool-group-management/src/client/Inspector/Broadcast/index.tsx
index 3d021cba9d8..288080f6f90 100644
--- a/packages/builtin-tool-group-management/src/client/Inspector/Broadcast/index.tsx
+++ b/packages/builtin-tool-group-management/src/client/Inspector/Broadcast/index.tsx
@@ -1,7 +1,7 @@
'use client';
import { DEFAULT_AVATAR } from '@lobechat/const';
-import type { AgentItem, BuiltinInspectorProps } from '@lobechat/types';
+import type { AgentGroupMember, BuiltinInspectorProps } from '@lobechat/types';
import { Avatar, Flexbox } from '@lobehub/ui';
import { createStaticStyles, cx, useTheme } from 'antd-style';
import { memo, useMemo } from 'react';
@@ -45,7 +45,7 @@ export const BroadcastInspector = memo<BuiltinInspectorProps<BroadcastParams>>(
if (!agentIds.length || !groupAgents.length) return [];
return agentIds
.map((id) => groupAgents.find((agent) => agent.id === id))
- .filter((agent): agent is AgentItem => !!agent);
+ .filter((agent): agent is AgentGroupMember => !!agent);
}, [agentIds, groupAgents]);
// Transform agents to Avatar.Group format
diff --git a/packages/builtin-tool-group-management/src/manifest.ts b/packages/builtin-tool-group-management/src/manifest.ts
index b0538483891..7a8886f0853 100644
--- a/packages/builtin-tool-group-management/src/manifest.ts
+++ b/packages/builtin-tool-group-management/src/manifest.ts
@@ -57,7 +57,7 @@ export const GroupManagementManifest: BuiltinToolManifest = {
{
description:
'Create a new agent dynamically based on user requirements and add it to the group. Use this when no existing agent matches the needed expertise.',
- humanIntervention: 'always',
+ humanIntervention: 'required',
name: GroupManagementApiName.createAgent,
parameters: {
properties: {
diff --git a/packages/builtin-tool-gtd/src/client/Inspector/ClearTodos/index.tsx b/packages/builtin-tool-gtd/src/client/Inspector/ClearTodos/index.tsx
index 2105ffd0dca..25b1cfde01d 100644
--- a/packages/builtin-tool-gtd/src/client/Inspector/ClearTodos/index.tsx
+++ b/packages/builtin-tool-gtd/src/client/Inspector/ClearTodos/index.tsx
@@ -5,7 +5,7 @@ import { createStaticStyles, cx } from 'antd-style';
import { memo } from 'react';
import { Trans, useTranslation } from 'react-i18next';
-import { shinyTextStyles } from '@/styles';
+import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { ClearTodosParams, ClearTodosState } from '../../../types';
@@ -15,14 +15,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
color: ${cssVar.colorText};
background: linear-gradient(to top, ${cssVar.colorWarningBg} 40%, transparent 40%);
`,
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
}));
export const ClearTodosInspector = memo<BuiltinInspectorProps<ClearTodosParams, ClearTodosState>>(
@@ -33,7 +25,7 @@ export const ClearTodosInspector = memo<BuiltinInspectorProps<ClearTodosParams,
if (isArgumentsStreaming && !mode) {
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-gtd.apiName.clearTodos')}</span>
</div>
);
@@ -45,7 +37,9 @@ export const ClearTodosInspector = memo<BuiltinInspectorProps<ClearTodosParams,
: t('builtins.lobe-gtd.apiName.clearTodos.modeCompleted');
return (
- <div className={cx(styles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}>
+ <div
+ className={cx(inspectorTextStyles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}
+ >
<Trans
components={{ mode: <span className={styles.mode} /> }}
i18nKey="builtins.lobe-gtd.apiName.clearTodos.result"
diff --git a/packages/builtin-tool-gtd/src/client/Inspector/CompleteTodos/index.tsx b/packages/builtin-tool-gtd/src/client/Inspector/CompleteTodos/index.tsx
index 88eeb97ee18..696855f0686 100644
--- a/packages/builtin-tool-gtd/src/client/Inspector/CompleteTodos/index.tsx
+++ b/packages/builtin-tool-gtd/src/client/Inspector/CompleteTodos/index.tsx
@@ -7,17 +7,11 @@ import { CheckCircle } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { shinyTextStyles } from '@/styles';
+import { oneLineEllipsis, shinyTextStyles } from '@/styles';
import type { CompleteTodosParams, CompleteTodosState } from '../../../types';
const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
- `,
title: css`
margin-inline-end: 8px;
color: ${cssVar.colorText};
@@ -34,14 +28,14 @@ export const CompleteTodosInspector = memo<
if (isArgumentsStreaming && count === 0) {
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(oneLineEllipsis, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-gtd.apiName.completeTodos')}</span>
</div>
);
}
return (
- <div className={cx(styles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}>
+ <div className={cx(oneLineEllipsis, isArgumentsStreaming && shinyTextStyles.shinyText)}>
<span className={styles.title}>{t('builtins.lobe-gtd.apiName.completeTodos')}</span>
{count > 0 && (
<Text as={'span'} code color={cssVar.colorSuccess} fontSize={12}>
diff --git a/packages/builtin-tool-gtd/src/client/Inspector/CreatePlan/index.tsx b/packages/builtin-tool-gtd/src/client/Inspector/CreatePlan/index.tsx
index 0ed09733b77..3c95767bdf5 100644
--- a/packages/builtin-tool-gtd/src/client/Inspector/CreatePlan/index.tsx
+++ b/packages/builtin-tool-gtd/src/client/Inspector/CreatePlan/index.tsx
@@ -1,25 +1,14 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from 'antd-style';
+import { cx } from 'antd-style';
import { memo } from 'react';
import { Trans, useTranslation } from 'react-i18next';
-import { highlightTextStyles, shinyTextStyles } from '@/styles';
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { CreatePlanParams, CreatePlanState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
-}));
-
export const CreatePlanInspector = memo<BuiltinInspectorProps<CreatePlanParams, CreatePlanState>>(
({ args, partialArgs, isArgumentsStreaming }) => {
const { t } = useTranslation('plugin');
@@ -28,14 +17,16 @@ export const CreatePlanInspector = memo<BuiltinInspectorProps<CreatePlanParams,
if (isArgumentsStreaming && !goal) {
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-gtd.apiName.createPlan')}</span>
</div>
);
}
return (
- <div className={cx(styles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}>
+ <div
+ className={cx(inspectorTextStyles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}
+ >
{goal ? (
<Trans
components={{ goal: <span className={highlightTextStyles.primary} /> }}
diff --git a/packages/builtin-tool-gtd/src/client/Inspector/CreateTodos/index.tsx b/packages/builtin-tool-gtd/src/client/Inspector/CreateTodos/index.tsx
index 41741b670e3..6d8b59219ae 100644
--- a/packages/builtin-tool-gtd/src/client/Inspector/CreateTodos/index.tsx
+++ b/packages/builtin-tool-gtd/src/client/Inspector/CreateTodos/index.tsx
@@ -7,17 +7,11 @@ import { Plus } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { shinyTextStyles } from '@/styles';
+import { oneLineEllipsis, shinyTextStyles } from '@/styles';
import type { CreateTodosParams, CreateTodosState } from '../../../types';
const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
- `,
title: css`
margin-inline-end: 8px;
color: ${cssVar.colorText};
@@ -35,14 +29,14 @@ export const CreateTodosInspector = memo<
if (isArgumentsStreaming && count === 0) {
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(oneLineEllipsis, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-gtd.apiName.createTodos')}</span>
</div>
);
}
return (
- <div className={cx(styles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}>
+ <div className={cx(oneLineEllipsis, isArgumentsStreaming && shinyTextStyles.shinyText)}>
<span className={styles.title}>{t('builtins.lobe-gtd.apiName.createTodos')}</span>
{count > 0 && (
<Text as={'span'} code color={cssVar.colorSuccess} fontSize={12}>
diff --git a/packages/builtin-tool-gtd/src/client/Inspector/ExecTask/index.tsx b/packages/builtin-tool-gtd/src/client/Inspector/ExecTask/index.tsx
index 0d83206b2fe..db8c9547751 100644
--- a/packages/builtin-tool-gtd/src/client/Inspector/ExecTask/index.tsx
+++ b/packages/builtin-tool-gtd/src/client/Inspector/ExecTask/index.tsx
@@ -1,25 +1,14 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from 'antd-style';
+import { cx } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { highlightTextStyles, shinyTextStyles } from '@/styles';
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { ExecTaskParams, ExecTaskState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
-}));
-
export const ExecTaskInspector = memo<BuiltinInspectorProps<ExecTaskParams, ExecTaskState>>(
({ args, partialArgs, isArgumentsStreaming, isLoading }) => {
const { t } = useTranslation('plugin');
@@ -30,13 +19,13 @@ export const ExecTaskInspector = memo<BuiltinInspectorProps<ExecTaskParams, Exec
if (isArgumentsStreaming) {
if (!description)
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-gtd.apiName.execTask')}</span>
</div>
);
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-gtd.apiName.execTask.loading')}</span>
<span className={highlightTextStyles.primary}>{description}</span>
</div>
@@ -46,7 +35,7 @@ export const ExecTaskInspector = memo<BuiltinInspectorProps<ExecTaskParams, Exec
// 有 description 时,根据 loading 状态显示不同文案
if (description) {
return (
- <div className={cx(styles.root, isLoading && shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
<span>
{isLoading
? t('builtins.lobe-gtd.apiName.execTask.loading')
@@ -59,7 +48,7 @@ export const ExecTaskInspector = memo<BuiltinInspectorProps<ExecTaskParams, Exec
// fallback
return (
- <div className={styles.root}>
+ <div className={inspectorTextStyles.root}>
<span>{t('builtins.lobe-gtd.apiName.execTask')}</span>
</div>
);
diff --git a/packages/builtin-tool-gtd/src/client/Inspector/RemoveTodos/index.tsx b/packages/builtin-tool-gtd/src/client/Inspector/RemoveTodos/index.tsx
index 27348aac1a3..6a7a68a8351 100644
--- a/packages/builtin-tool-gtd/src/client/Inspector/RemoveTodos/index.tsx
+++ b/packages/builtin-tool-gtd/src/client/Inspector/RemoveTodos/index.tsx
@@ -7,17 +7,11 @@ import { Minus } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { shinyTextStyles } from '@/styles';
+import { oneLineEllipsis, shinyTextStyles } from '@/styles';
import type { RemoveTodosParams, RemoveTodosState } from '../../../types';
const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
- `,
title: css`
margin-inline-end: 8px;
color: ${cssVar.colorText};
@@ -34,14 +28,14 @@ export const RemoveTodosInspector = memo<
if (isArgumentsStreaming && count === 0) {
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(oneLineEllipsis, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-gtd.apiName.removeTodos')}</span>
</div>
);
}
return (
- <div className={cx(styles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}>
+ <div className={cx(oneLineEllipsis, isArgumentsStreaming && shinyTextStyles.shinyText)}>
<span className={styles.title}>{t('builtins.lobe-gtd.apiName.removeTodos')}</span>
{count > 0 && (
<Text as={'span'} code color={cssVar.colorError} fontSize={12}>
diff --git a/packages/builtin-tool-gtd/src/client/Inspector/UpdatePlan/index.tsx b/packages/builtin-tool-gtd/src/client/Inspector/UpdatePlan/index.tsx
index 5d1b9897ef8..20b2f6b3a99 100644
--- a/packages/builtin-tool-gtd/src/client/Inspector/UpdatePlan/index.tsx
+++ b/packages/builtin-tool-gtd/src/client/Inspector/UpdatePlan/index.tsx
@@ -7,17 +7,11 @@ import { CheckCircle, DiffIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { shinyTextStyles } from '@/styles';
+import { oneLineEllipsis, shinyTextStyles } from '@/styles';
import type { UpdatePlanParams, UpdatePlanState } from '../../../types';
const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
- `,
title: css`
margin-inline-end: 8px;
color: ${cssVar.colorText};
@@ -34,14 +28,14 @@ export const UpdatePlanInspector = memo<BuiltinInspectorProps<UpdatePlanParams,
if (isArgumentsStreaming && !planId) {
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(oneLineEllipsis, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-gtd.apiName.updatePlan')}</span>
</div>
);
}
return (
- <div className={cx(styles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}>
+ <div className={cx(oneLineEllipsis, isArgumentsStreaming && shinyTextStyles.shinyText)}>
<span className={styles.title}>{t('builtins.lobe-gtd.apiName.updatePlan')}</span>
{completed && (
<Text as={'span'} code color={cssVar.colorSuccess} fontSize={12}>
diff --git a/packages/builtin-tool-gtd/src/client/Inspector/UpdateTodos/index.tsx b/packages/builtin-tool-gtd/src/client/Inspector/UpdateTodos/index.tsx
index f7bceb2c641..13b73cdd24e 100644
--- a/packages/builtin-tool-gtd/src/client/Inspector/UpdateTodos/index.tsx
+++ b/packages/builtin-tool-gtd/src/client/Inspector/UpdateTodos/index.tsx
@@ -7,17 +7,11 @@ import { CheckCircle, DiffIcon, Minus, Plus } from 'lucide-react';
import { type ReactNode, memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { shinyTextStyles } from '@/styles';
+import { oneLineEllipsis, shinyTextStyles } from '@/styles';
import type { UpdateTodosParams, UpdateTodosState } from '../../../types';
const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
- `,
separator: css`
margin-inline: 2px;
color: ${cssVar.colorTextQuaternary};
@@ -66,7 +60,7 @@ export const UpdateTodosInspector = memo<
if (isArgumentsStreaming && !hasOperations) {
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(oneLineEllipsis, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-gtd.apiName.updateTodos')}</span>
</div>
);
@@ -107,7 +101,7 @@ export const UpdateTodosInspector = memo<
}
return (
- <div className={cx(styles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}>
+ <div className={cx(oneLineEllipsis, isArgumentsStreaming && shinyTextStyles.shinyText)}>
<span className={styles.title}>{t('builtins.lobe-gtd.apiName.updateTodos')}</span>
{statsParts.length > 0 && (
<>
diff --git a/packages/builtin-tool-knowledge-base/src/client/Inspector/ReadKnowledge/index.tsx b/packages/builtin-tool-knowledge-base/src/client/Inspector/ReadKnowledge/index.tsx
index 5eb35c984a2..a267203a1a1 100644
--- a/packages/builtin-tool-knowledge-base/src/client/Inspector/ReadKnowledge/index.tsx
+++ b/packages/builtin-tool-knowledge-base/src/client/Inspector/ReadKnowledge/index.tsx
@@ -5,7 +5,7 @@ import { createStaticStyles, cx } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { highlightTextStyles, shinyTextStyles } from '@/styles';
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
import { type ReadKnowledgeArgs, type ReadKnowledgeState } from '../../..';
@@ -14,18 +14,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
margin-inline-start: 4px;
color: ${cssVar.colorTextTertiary};
`,
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
- statusIcon: css`
- margin-block-end: -2px;
- margin-inline-start: 4px;
- `,
}));
export const ReadKnowledgeInspector = memo<
@@ -43,13 +31,13 @@ export const ReadKnowledgeInspector = memo<
if (isArgumentsStreaming) {
if (fileCount === 0)
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-knowledge-base.apiName.readKnowledge')}</span>
</div>
);
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-knowledge-base.apiName.readKnowledge')}: </span>
<span className={highlightTextStyles.gold}>
{fileCount} {fileCount === 1 ? 'file' : 'files'}
@@ -85,7 +73,7 @@ export const ReadKnowledgeInspector = memo<
};
return (
- <div className={cx(styles.root, isLoading && shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
<span style={{ marginInlineStart: 2 }}>
<span>{t('builtins.lobe-knowledge-base.apiName.readKnowledge')}: </span>
{renderFileInfo()}
diff --git a/packages/builtin-tool-knowledge-base/src/client/Inspector/SearchKnowledgeBase/index.tsx b/packages/builtin-tool-knowledge-base/src/client/Inspector/SearchKnowledgeBase/index.tsx
index adfe50e73d2..99685190eac 100644
--- a/packages/builtin-tool-knowledge-base/src/client/Inspector/SearchKnowledgeBase/index.tsx
+++ b/packages/builtin-tool-knowledge-base/src/client/Inspector/SearchKnowledgeBase/index.tsx
@@ -2,25 +2,14 @@
import { type BuiltinInspectorProps } from '@lobechat/types';
import { Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { cssVar, cx } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { highlightTextStyles, shinyTextStyles } from '@/styles';
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
import { type SearchKnowledgeBaseArgs, type SearchKnowledgeBaseState } from '../../..';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
-}));
-
export const SearchKnowledgeBaseInspector = memo<
BuiltinInspectorProps<SearchKnowledgeBaseArgs, SearchKnowledgeBaseState>
>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
@@ -35,13 +24,13 @@ export const SearchKnowledgeBaseInspector = memo<
if (isArgumentsStreaming) {
if (!query)
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-knowledge-base.apiName.searchKnowledgeBase')}</span>
</div>
);
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-knowledge-base.apiName.searchKnowledgeBase')}: </span>
<span className={highlightTextStyles.gold}>{query}</span>
</div>
@@ -49,7 +38,7 @@ export const SearchKnowledgeBaseInspector = memo<
}
return (
- <div className={cx(styles.root, isLoading && shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
<span style={{ marginInlineStart: 2 }}>
<span>{t('builtins.lobe-knowledge-base.apiName.searchKnowledgeBase')}: </span>
{query && <span className={highlightTextStyles.gold}>{query}</span>}
diff --git a/packages/builtin-tool-local-system/src/client/Inspector/EditLocalFile/index.tsx b/packages/builtin-tool-local-system/src/client/Inspector/EditLocalFile/index.tsx
index f8c9453563f..823cb843877 100644
--- a/packages/builtin-tool-local-system/src/client/Inspector/EditLocalFile/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Inspector/EditLocalFile/index.tsx
@@ -8,20 +8,12 @@ import { Minus, Plus } from 'lucide-react';
import { type ReactNode, memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { shinyTextStyles } from '@/styles';
+import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import { type EditLocalFileState } from '../../../types';
import { FilePathDisplay } from '../../components/FilePathDisplay';
const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
separator: css`
margin-inline: 2px;
color: ${cssVar.colorTextQuaternary};
@@ -39,13 +31,13 @@ export const EditLocalFileInspector = memo<
if (isArgumentsStreaming) {
if (!filePath)
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-local-system.apiName.editLocalFile')}</span>
</div>
);
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-local-system.apiName.editLocalFile')}: </span>
<FilePathDisplay filePath={filePath} />
</div>
@@ -75,7 +67,7 @@ export const EditLocalFileInspector = memo<
}
return (
- <div className={cx(styles.root, isLoading && shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-local-system.apiName.editLocalFile')}: </span>
<FilePathDisplay filePath={filePath} />
{!isLoading && statsParts.length > 0 && (
diff --git a/packages/builtin-tool-local-system/src/client/Inspector/GlobLocalFiles/index.tsx b/packages/builtin-tool-local-system/src/client/Inspector/GlobLocalFiles/index.tsx
index d36fd495e35..4306ab3524c 100644
--- a/packages/builtin-tool-local-system/src/client/Inspector/GlobLocalFiles/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Inspector/GlobLocalFiles/index.tsx
@@ -7,19 +7,11 @@ import { Check, X } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { highlightTextStyles, shinyTextStyles } from '@/styles';
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
import { type GlobFilesState } from '../../..';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
+const styles = createStaticStyles(({ css }) => ({
statusIcon: css`
margin-block-end: -2px;
margin-inline-start: 4px;
@@ -36,13 +28,13 @@ export const GlobLocalFilesInspector = memo<BuiltinInspectorProps<GlobFilesParam
if (isArgumentsStreaming) {
if (!pattern)
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-local-system.apiName.globLocalFiles')}</span>
</div>
);
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-local-system.apiName.globLocalFiles')}: </span>
<span className={highlightTextStyles.primary}>{pattern}</span>
</div>
@@ -53,7 +45,7 @@ export const GlobLocalFilesInspector = memo<BuiltinInspectorProps<GlobFilesParam
const isSuccess = pluginState?.result?.success;
return (
- <div className={cx(styles.root, isLoading && shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
<span style={{ marginInlineStart: 2 }}>
<span>{t('builtins.lobe-local-system.apiName.globLocalFiles')}: </span>
{pattern && <span className={highlightTextStyles.primary}>{pattern}</span>}
diff --git a/packages/builtin-tool-local-system/src/client/Inspector/GrepContent/index.tsx b/packages/builtin-tool-local-system/src/client/Inspector/GrepContent/index.tsx
index 8115c8796cd..e8879fecf87 100644
--- a/packages/builtin-tool-local-system/src/client/Inspector/GrepContent/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Inspector/GrepContent/index.tsx
@@ -3,25 +3,14 @@
import { type GrepContentParams } from '@lobechat/electron-client-ipc';
import { type BuiltinInspectorProps } from '@lobechat/types';
import { Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { cssVar, cx } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { highlightTextStyles, shinyTextStyles } from '@/styles';
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
import { type GrepContentState } from '../../..';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
-}));
-
export const GrepContentInspector = memo<
BuiltinInspectorProps<GrepContentParams, GrepContentState>
>(({ args, partialArgs, isArgumentsStreaming, pluginState, isLoading }) => {
@@ -33,13 +22,13 @@ export const GrepContentInspector = memo<
if (isArgumentsStreaming) {
if (!pattern)
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-local-system.apiName.grepContent')}</span>
</div>
);
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-local-system.apiName.grepContent')}: </span>
<span className={highlightTextStyles.primary}>{pattern}</span>
</div>
@@ -51,7 +40,7 @@ export const GrepContentInspector = memo<
const hasResults = resultCount > 0;
return (
- <div className={cx(styles.root, isLoading && shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-local-system.apiName.grepContent')}: </span>
{pattern && <span className={highlightTextStyles.primary}>{pattern}</span>}
{!isLoading &&
diff --git a/packages/builtin-tool-local-system/src/client/Inspector/ListLocalFiles/index.tsx b/packages/builtin-tool-local-system/src/client/Inspector/ListLocalFiles/index.tsx
index 9352b6fee20..ea5da6bfadd 100644
--- a/packages/builtin-tool-local-system/src/client/Inspector/ListLocalFiles/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Inspector/ListLocalFiles/index.tsx
@@ -3,26 +3,15 @@
import { type ListLocalFileParams } from '@lobechat/electron-client-ipc';
import { type BuiltinInspectorProps } from '@lobechat/types';
import { Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { cssVar, cx } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { shinyTextStyles } from '@/styles';
+import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import { type LocalFileListState } from '../../..';
import { FilePathDisplay } from '../../components/FilePathDisplay';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
-}));
-
export const ListLocalFilesInspector = memo<
BuiltinInspectorProps<ListLocalFileParams, LocalFileListState>
>(({ args, partialArgs, isArgumentsStreaming, pluginState, isLoading }) => {
@@ -34,13 +23,13 @@ export const ListLocalFilesInspector = memo<
if (isArgumentsStreaming) {
if (!path)
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-local-system.apiName.listLocalFiles')}</span>
</div>
);
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-local-system.apiName.listLocalFiles')}: </span>
<FilePathDisplay filePath={path} isDirectory />
</div>
@@ -52,7 +41,7 @@ export const ListLocalFilesInspector = memo<
const hasResults = resultCount > 0;
return (
- <div className={cx(styles.root, isLoading && shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-local-system.apiName.listLocalFiles')}: </span>
<FilePathDisplay filePath={path} isDirectory />
{!isLoading &&
diff --git a/packages/builtin-tool-local-system/src/client/Inspector/ReadLocalFile/index.tsx b/packages/builtin-tool-local-system/src/client/Inspector/ReadLocalFile/index.tsx
index 8293275f3bf..139d4be3f62 100644
--- a/packages/builtin-tool-local-system/src/client/Inspector/ReadLocalFile/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Inspector/ReadLocalFile/index.tsx
@@ -2,26 +2,15 @@
import { type LocalReadFileParams } from '@lobechat/electron-client-ipc';
import { type BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from 'antd-style';
+import { cx } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { shinyTextStyles } from '@/styles';
+import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import { type LocalReadFileState } from '../../..';
import { FilePathDisplay } from '../../components/FilePathDisplay';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
-}));
-
export const ReadLocalFileInspector = memo<
BuiltinInspectorProps<LocalReadFileParams, LocalReadFileState>
>(({ args, partialArgs, isArgumentsStreaming, isLoading }) => {
@@ -33,13 +22,13 @@ export const ReadLocalFileInspector = memo<
if (isArgumentsStreaming) {
if (!filePath)
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-local-system.apiName.readLocalFile')}</span>
</div>
);
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-local-system.apiName.readLocalFile')}: </span>
<FilePathDisplay filePath={filePath} />
</div>
@@ -47,7 +36,7 @@ export const ReadLocalFileInspector = memo<
}
return (
- <div className={cx(styles.root, isLoading && shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-local-system.apiName.readLocalFile')}: </span>
<FilePathDisplay filePath={filePath} />
</div>
diff --git a/packages/builtin-tool-local-system/src/client/Inspector/RenameLocalFile/index.tsx b/packages/builtin-tool-local-system/src/client/Inspector/RenameLocalFile/index.tsx
index c438ebb0f5f..7a26bb98e7e 100644
--- a/packages/builtin-tool-local-system/src/client/Inspector/RenameLocalFile/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Inspector/RenameLocalFile/index.tsx
@@ -8,23 +8,15 @@ import path from 'path-browserify-esm';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { highlightTextStyles, shinyTextStyles } from '@/styles';
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
import { type LocalRenameFileState } from '../../..';
-const styles = createStaticStyles(({ css, cssVar }) => ({
+const styles = createStaticStyles(({ css }) => ({
icon: css`
flex-shrink: 0;
margin-inline-end: 4px;
`,
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
}));
export const RenameLocalFileInspector = memo<
@@ -39,7 +31,9 @@ export const RenameLocalFileInspector = memo<
const oldName = filePath ? path.basename(filePath) : '';
return (
- <div className={cx(styles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}>
+ <div
+ className={cx(inspectorTextStyles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}
+ >
{oldName && newName ? (
<>
{t('builtins.lobe-local-system.apiName.renameLocalFile')} {oldName} →{' '}
diff --git a/packages/builtin-tool-local-system/src/client/Inspector/RunCommand/index.tsx b/packages/builtin-tool-local-system/src/client/Inspector/RunCommand/index.tsx
index b98e3d28478..a2104059a1b 100644
--- a/packages/builtin-tool-local-system/src/client/Inspector/RunCommand/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Inspector/RunCommand/index.tsx
@@ -7,17 +7,9 @@ import { Check, X } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { highlightTextStyles, shinyTextStyles } from '@/styles';
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
+const styles = createStaticStyles(({ css }) => ({
statusIcon: css`
margin-block-end: -2px;
margin-inline-start: 4px;
@@ -40,13 +32,13 @@ export const RunCommandInspector = memo<BuiltinInspectorProps<RunCommandParams,
if (isArgumentsStreaming) {
if (!description)
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-local-system.apiName.runCommand')}</span>
</div>
);
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-local-system.apiName.runCommand')}: </span>
<span className={highlightTextStyles.primary}>{description}</span>
</div>
@@ -58,7 +50,7 @@ export const RunCommandInspector = memo<BuiltinInspectorProps<RunCommandParams,
const isSuccess = result?.success && result?.exit_code === 0;
return (
- <div className={cx(styles.root, isLoading && shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
<span style={{ marginInlineStart: 2 }}>
<span>{t('builtins.lobe-local-system.apiName.runCommand')}: </span>
{description && <span className={highlightTextStyles.primary}>{description}</span>}
diff --git a/packages/builtin-tool-local-system/src/client/Inspector/SearchLocalFiles/index.tsx b/packages/builtin-tool-local-system/src/client/Inspector/SearchLocalFiles/index.tsx
index 790984d410f..349fff4b64e 100644
--- a/packages/builtin-tool-local-system/src/client/Inspector/SearchLocalFiles/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Inspector/SearchLocalFiles/index.tsx
@@ -3,25 +3,14 @@
import { type LocalSearchFilesParams } from '@lobechat/electron-client-ipc';
import { type BuiltinInspectorProps } from '@lobechat/types';
import { Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { cssVar, cx } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { highlightTextStyles, shinyTextStyles } from '@/styles';
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
import { type LocalFileSearchState } from '../../..';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
-}));
-
export const SearchLocalFilesInspector = memo<
BuiltinInspectorProps<LocalSearchFilesParams, LocalFileSearchState>
>(({ args, partialArgs, isArgumentsStreaming, pluginState, isLoading }) => {
@@ -33,13 +22,13 @@ export const SearchLocalFilesInspector = memo<
if (isArgumentsStreaming) {
if (!keywords)
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-local-system.apiName.searchLocalFiles')}</span>
</div>
);
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-local-system.apiName.searchLocalFiles')}: </span>
<span className={highlightTextStyles.primary}>{keywords}</span>
</div>
@@ -51,7 +40,7 @@ export const SearchLocalFilesInspector = memo<
const hasResults = resultCount > 0;
return (
- <div className={cx(styles.root, isLoading && shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
<span style={{ marginInlineStart: 2 }}>
<span>{t('builtins.lobe-local-system.apiName.searchLocalFiles')}: </span>
{keywords && <span className={highlightTextStyles.primary}>{keywords}</span>}
diff --git a/packages/builtin-tool-local-system/src/client/Inspector/WriteLocalFile/index.tsx b/packages/builtin-tool-local-system/src/client/Inspector/WriteLocalFile/index.tsx
index c41c48f1390..acc6429e947 100644
--- a/packages/builtin-tool-local-system/src/client/Inspector/WriteLocalFile/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Inspector/WriteLocalFile/index.tsx
@@ -3,26 +3,15 @@
import { type WriteLocalFileParams } from '@lobechat/electron-client-ipc';
import { type BuiltinInspectorProps } from '@lobechat/types';
import { Icon, Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { cssVar, cx } from 'antd-style';
import { Plus } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { shinyTextStyles } from '@/styles';
+import { inspectorTextStyles, shinyTextStyles } from '@/styles';
import { FilePathDisplay } from '../../components/FilePathDisplay';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
-}));
-
export const WriteLocalFileInspector = memo<BuiltinInspectorProps<WriteLocalFileParams>>(
({ args, partialArgs, isArgumentsStreaming }) => {
const { t } = useTranslation('plugin');
@@ -36,14 +25,16 @@ export const WriteLocalFileInspector = memo<BuiltinInspectorProps<WriteLocalFile
// During argument streaming without path
if (isArgumentsStreaming && !filePath) {
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-local-system.apiName.writeLocalFile')}</span>
</div>
);
}
return (
- <div className={cx(styles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}>
+ <div
+ className={cx(inspectorTextStyles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}
+ >
<span>{t('builtins.lobe-local-system.apiName.writeLocalFile')}: </span>
<FilePathDisplay filePath={filePath} />
{lines > 0 && (
diff --git a/packages/builtin-tool-notebook/src/client/Inspector/CreateDocument/index.tsx b/packages/builtin-tool-notebook/src/client/Inspector/CreateDocument/index.tsx
index 551b8e6677c..c6c6233acec 100644
--- a/packages/builtin-tool-notebook/src/client/Inspector/CreateDocument/index.tsx
+++ b/packages/builtin-tool-notebook/src/client/Inspector/CreateDocument/index.tsx
@@ -1,25 +1,14 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from 'antd-style';
+import { cx } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { highlightTextStyles, shinyTextStyles } from '@/styles';
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { CreateDocumentArgs, CreateDocumentState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
-}));
-
export const CreateDocumentInspector = memo<
BuiltinInspectorProps<CreateDocumentArgs, CreateDocumentState>
>(({ args, partialArgs, isArgumentsStreaming, isLoading }) => {
@@ -30,7 +19,7 @@ export const CreateDocumentInspector = memo<
// During streaming without title, show init
if (isArgumentsStreaming && !title) {
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-notebook.apiName.createDocument')}</span>
</div>
);
@@ -38,7 +27,10 @@ export const CreateDocumentInspector = memo<
return (
<div
- className={cx(styles.root, (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText)}
+ className={cx(
+ inspectorTextStyles.root,
+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,
+ )}
>
<span>{t('builtins.lobe-notebook.apiName.createDocument')}: </span>
{title && <span className={highlightTextStyles.primary}>{title}</span>}
diff --git a/packages/builtin-tool-page-agent/src/client/Inspector/EditTitle/index.tsx b/packages/builtin-tool-page-agent/src/client/Inspector/EditTitle/index.tsx
index e3942921cbc..644606406c4 100644
--- a/packages/builtin-tool-page-agent/src/client/Inspector/EditTitle/index.tsx
+++ b/packages/builtin-tool-page-agent/src/client/Inspector/EditTitle/index.tsx
@@ -2,25 +2,14 @@
import type { EditTitleArgs } from '@lobechat/editor-runtime';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from 'antd-style';
+import { cx } from 'antd-style';
import { memo } from 'react';
import { Trans, useTranslation } from 'react-i18next';
-import { highlightTextStyles, shinyTextStyles } from '@/styles';
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { EditTitleState } from '../../../types';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
-}));
-
export const EditTitleInspector = memo<BuiltinInspectorProps<EditTitleArgs, EditTitleState>>(
({ args, partialArgs, isArgumentsStreaming }) => {
const { t } = useTranslation('plugin');
@@ -28,7 +17,9 @@ export const EditTitleInspector = memo<BuiltinInspectorProps<EditTitleArgs, Edit
const title = args?.title || partialArgs?.title;
return (
- <div className={cx(styles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}>
+ <div
+ className={cx(inspectorTextStyles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}
+ >
{title ? (
<Trans
components={{ title: <span className={highlightTextStyles.gold} /> }}
diff --git a/packages/builtin-tool-page-agent/src/client/Inspector/GetPageContent/index.tsx b/packages/builtin-tool-page-agent/src/client/Inspector/GetPageContent/index.tsx
index 32e0b8e9a87..be1ecb1d927 100644
--- a/packages/builtin-tool-page-agent/src/client/Inspector/GetPageContent/index.tsx
+++ b/packages/builtin-tool-page-agent/src/client/Inspector/GetPageContent/index.tsx
@@ -5,25 +5,24 @@ import { createStaticStyles, cx } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { shinyTextStyles } from '@/styles';
+import { oneLineEllipsis, shinyTextStyles } from '@/styles';
const styles = createStaticStyles(({ css, cssVar }) => ({
done: css`
color: ${cssVar.colorTextDescription};
`,
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
- `,
}));
export const GetPageContentInspector = memo<BuiltinInspectorProps>(({ isArgumentsStreaming }) => {
const { t } = useTranslation('plugin');
return (
- <div className={cx(styles.root, isArgumentsStreaming ? shinyTextStyles.shinyText : styles.done)}>
+ <div
+ className={cx(
+ oneLineEllipsis,
+ isArgumentsStreaming ? shinyTextStyles.shinyText : styles.done,
+ )}
+ >
<span>{t('builtins.lobe-page-agent.apiName.getPageContent')}</span>
</div>
);
diff --git a/packages/builtin-tool-page-agent/src/client/Inspector/InitPage/index.tsx b/packages/builtin-tool-page-agent/src/client/Inspector/InitPage/index.tsx
index d2cd3deb1ab..eccb59a0a2d 100644
--- a/packages/builtin-tool-page-agent/src/client/Inspector/InitPage/index.tsx
+++ b/packages/builtin-tool-page-agent/src/client/Inspector/InitPage/index.tsx
@@ -8,18 +8,12 @@ import { Plus } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { shinyTextStyles } from '@/styles';
+import { oneLineEllipsis, shinyTextStyles } from '@/styles';
import type { InitDocumentState } from '../../../types';
import { AnimatedNumber } from '../../components/AnimatedNumber';
const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
- `,
title: css`
margin-inline-end: 8px;
color: ${cssVar.colorText};
@@ -43,14 +37,14 @@ export const InitPageInspector = memo<BuiltinInspectorProps<InitDocumentArgs, In
if (isArgumentsStreaming) {
if (!hasContent)
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(oneLineEllipsis, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-page-agent.apiName.initPage')}</span>
</div>
);
// During streaming with content, show "creating" title with shiny effect
return (
- <div className={styles.root}>
+ <div className={oneLineEllipsis}>
<span className={shinyTextStyles.shinyText}>
{t('builtins.lobe-page-agent.apiName.initPage.creating')}
</span>
@@ -74,7 +68,7 @@ export const InitPageInspector = memo<BuiltinInspectorProps<InitDocumentArgs, In
}
return (
- <div className={styles.root}>
+ <div className={oneLineEllipsis}>
<span className={styles.title}>
{t('builtins.lobe-page-agent.apiName.initPage.result')}
</span>
diff --git a/packages/builtin-tool-page-agent/src/client/Inspector/ModifyNodes/index.tsx b/packages/builtin-tool-page-agent/src/client/Inspector/ModifyNodes/index.tsx
index e7a153fdacb..9c6dfae6cf6 100644
--- a/packages/builtin-tool-page-agent/src/client/Inspector/ModifyNodes/index.tsx
+++ b/packages/builtin-tool-page-agent/src/client/Inspector/ModifyNodes/index.tsx
@@ -8,17 +8,11 @@ import { DiffIcon, Minus, Plus } from 'lucide-react';
import { type ReactNode, memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { shinyTextStyles } from '@/styles';
+import { oneLineEllipsis, shinyTextStyles } from '@/styles';
import type { ModifyNodesState } from '../../../types';
const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
- `,
separator: css`
margin-inline: 2px;
color: ${cssVar.colorTextQuaternary};
@@ -66,7 +60,7 @@ export const ModifyNodesInspector = memo<BuiltinInspectorProps<ModifyNodesArgs,
// During streaming without operations yet, show init message
if (isArgumentsStreaming && !hasOperations) {
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(oneLineEllipsis, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-page-agent.apiName.modifyNodes.init')}</span>
</div>
);
@@ -100,7 +94,7 @@ export const ModifyNodesInspector = memo<BuiltinInspectorProps<ModifyNodesArgs,
}
return (
- <div className={cx(styles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}>
+ <div className={cx(oneLineEllipsis, isArgumentsStreaming && shinyTextStyles.shinyText)}>
<span className={styles.title}>{t('builtins.lobe-page-agent.apiName.modifyNodes')}</span>
{statsParts.length > 0 && (
<>
diff --git a/packages/builtin-tool-page-agent/src/client/Inspector/ReplaceText/index.tsx b/packages/builtin-tool-page-agent/src/client/Inspector/ReplaceText/index.tsx
index 132fa1fbf1a..df73897733e 100644
--- a/packages/builtin-tool-page-agent/src/client/Inspector/ReplaceText/index.tsx
+++ b/packages/builtin-tool-page-agent/src/client/Inspector/ReplaceText/index.tsx
@@ -8,7 +8,7 @@ import { ArrowRight } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { highlightTextStyles, shinyTextStyles } from '@/styles';
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
import type { ReplaceTextState } from '../../../types';
@@ -21,14 +21,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
color: ${cssVar.colorTextSecondary};
text-decoration: line-through;
`,
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
title: css`
margin-inline-end: 8px;
color: ${cssVar.colorText};
@@ -45,7 +37,7 @@ export const ReplaceTextInspector = memo<BuiltinInspectorProps<ReplaceTextArgs,
// During streaming without searchText yet, show init message
if (isArgumentsStreaming && !from) {
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-page-agent.apiName.replaceText.init')}</span>
</div>
);
@@ -55,7 +47,9 @@ export const ReplaceTextInspector = memo<BuiltinInspectorProps<ReplaceTextArgs,
const hasResult = from && to !== undefined;
return (
- <div className={cx(styles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}>
+ <div
+ className={cx(inspectorTextStyles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}
+ >
<span className={styles.title}>{t('builtins.lobe-page-agent.apiName.replaceText')}</span>
{hasResult && (
<>
diff --git a/packages/builtin-tool-web-browsing/src/client/Inspector/CrawlMultiPages/index.tsx b/packages/builtin-tool-web-browsing/src/client/Inspector/CrawlMultiPages/index.tsx
index b17f10ecdee..3f99d109ec8 100644
--- a/packages/builtin-tool-web-browsing/src/client/Inspector/CrawlMultiPages/index.tsx
+++ b/packages/builtin-tool-web-browsing/src/client/Inspector/CrawlMultiPages/index.tsx
@@ -1,22 +1,11 @@
'use client';
import { type BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from 'antd-style';
+import { cx } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { highlightTextStyles, shinyTextStyles } from '@/styles';
-
-const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
interface CrawlMultiPagesParams {
urls: string[];
@@ -42,14 +31,16 @@ export const CrawlMultiPagesInspector = memo<BuiltinInspectorProps<CrawlMultiPag
if (isArgumentsStreaming && !displayText) {
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-web-browsing.apiName.crawlMultiPages')}</span>
</div>
);
}
return (
- <div className={cx(styles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}>
+ <div
+ className={cx(inspectorTextStyles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}
+ >
<span>{t('builtins.lobe-web-browsing.apiName.crawlMultiPages')}: </span>
{displayText && <span className={highlightTextStyles.gold}>{displayText}</span>}
</div>
diff --git a/packages/builtin-tool-web-browsing/src/client/Inspector/CrawlSinglePage/index.tsx b/packages/builtin-tool-web-browsing/src/client/Inspector/CrawlSinglePage/index.tsx
index c8768e6fe81..fa050293f7a 100644
--- a/packages/builtin-tool-web-browsing/src/client/Inspector/CrawlSinglePage/index.tsx
+++ b/packages/builtin-tool-web-browsing/src/client/Inspector/CrawlSinglePage/index.tsx
@@ -1,22 +1,11 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { createStaticStyles, cx } from 'antd-style';
+import { cx } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { highlightTextStyles, shinyTextStyles } from '@/styles';
-
-const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
interface CrawlSinglePageParams {
url: string;
@@ -30,14 +19,16 @@ export const CrawlSinglePageInspector = memo<BuiltinInspectorProps<CrawlSinglePa
if (isArgumentsStreaming && !url) {
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-web-browsing.apiName.crawlSinglePage')}</span>
</div>
);
}
return (
- <div className={cx(styles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}>
+ <div
+ className={cx(inspectorTextStyles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}
+ >
<span>{t('builtins.lobe-web-browsing.apiName.crawlSinglePage')}: </span>
{url && <span className={highlightTextStyles.gold}>{url}</span>}
</div>
diff --git a/packages/builtin-tool-web-browsing/src/client/Inspector/Search/index.tsx b/packages/builtin-tool-web-browsing/src/client/Inspector/Search/index.tsx
index 86c911687a9..3261c9b8ab3 100644
--- a/packages/builtin-tool-web-browsing/src/client/Inspector/Search/index.tsx
+++ b/packages/builtin-tool-web-browsing/src/client/Inspector/Search/index.tsx
@@ -6,22 +6,11 @@ import {
type UniformSearchResponse,
} from '@lobechat/types';
import { Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { cssVar, cx } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { highlightTextStyles, shinyTextStyles } from '@/styles';
-
-const styles = createStaticStyles(({ css, cssVar }) => ({
- root: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 1;
-
- color: ${cssVar.colorTextSecondary};
- `,
-}));
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
export const SearchInspector = memo<BuiltinInspectorProps<SearchQuery, UniformSearchResponse>>(
({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
@@ -33,7 +22,7 @@ export const SearchInspector = memo<BuiltinInspectorProps<SearchQuery, UniformSe
if (isArgumentsStreaming && !query) {
return (
- <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-web-browsing.apiName.search')}</span>
</div>
);
@@ -42,7 +31,7 @@ export const SearchInspector = memo<BuiltinInspectorProps<SearchQuery, UniformSe
return (
<div
className={cx(
- styles.root,
+ inspectorTextStyles.root,
(isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,
)}
>
diff --git a/packages/database/src/models/chatGroup.ts b/packages/database/src/models/chatGroup.ts
index be7918b8d85..a4f5d2cae01 100644
--- a/packages/database/src/models/chatGroup.ts
+++ b/packages/database/src/models/chatGroup.ts
@@ -115,7 +115,7 @@ export class ChatGroupModel {
async update(id: string, value: Partial<ChatGroupItem>): Promise<ChatGroupItem> {
const [result] = await this.db
.update(chatGroups)
- .set({ ...value, updatedAt: new Date() })
+ .set(value)
.where(and(eq(chatGroups.id, id), eq(chatGroups.userId, this.userId)))
.returning();
diff --git a/packages/types/src/agentGroup/index.ts b/packages/types/src/agentGroup/index.ts
index 25b9c911c48..785fe28426a 100644
--- a/packages/types/src/agentGroup/index.ts
+++ b/packages/types/src/agentGroup/index.ts
@@ -5,6 +5,8 @@ import { TaskDetail, UIChatMessage } from '../message';
import { ChatTopic } from '../topic';
export interface LobeChatGroupMetaConfig {
+ avatar?: string;
+ backgroundColor?: string;
description: string;
title: string;
}
@@ -75,6 +77,8 @@ export interface NewChatGroupAgent {
// New Chat Group type for creating groups (independent from schema)
export interface NewChatGroup {
+ avatar?: string | null;
+ backgroundColor?: string | null;
clientId?: string | null;
config?: LobeChatGroupConfig | null;
description?: string | null;
@@ -88,10 +92,14 @@ export interface NewChatGroup {
// Chat Group Item type (independent from schema)
export interface ChatGroupItem {
accessedAt?: Date;
+ avatar?: string | null;
+ backgroundColor?: string | null;
clientId?: string | null;
config?: LobeChatGroupConfig | null;
+ content?: string | null;
createdAt: Date;
description?: string | null;
+ editorData?: Record<string, any> | null;
groupId?: string | null;
id: string;
pinned?: boolean | null;
diff --git a/src/app/[variants]/(main)/agent/_layout/Sidebar/Header/Nav.tsx b/src/app/[variants]/(main)/agent/_layout/Sidebar/Header/Nav.tsx
index cdd2f5607cf..1f035e2648c 100644
--- a/src/app/[variants]/(main)/agent/_layout/Sidebar/Header/Nav.tsx
+++ b/src/app/[variants]/(main)/agent/_layout/Sidebar/Header/Nav.tsx
@@ -55,7 +55,7 @@ const Nav = memo(() => {
active={isProfileActive}
icon={BotPromptIcon}
onClick={() => {
- switchTopic(undefined, true);
+ switchTopic(null, { skipRefreshMessage: true });
router.push(urlJoin('/agent', agentId!, 'profile'));
}}
title={t('tab.profile')}
diff --git a/src/app/[variants]/(main)/agent/cron/[cronId]/index.tsx b/src/app/[variants]/(main)/agent/cron/[cronId]/index.tsx
index 3433d1833e9..3189cbaefcd 100644
--- a/src/app/[variants]/(main)/agent/cron/[cronId]/index.tsx
+++ b/src/app/[variants]/(main)/agent/cron/[cronId]/index.tsx
@@ -11,7 +11,7 @@ import {
ReactMathPlugin,
ReactTablePlugin,
} from '@lobehub/editor';
-import { Editor, useEditor } from '@lobehub/editor/react';
+import { Editor, useEditor, useEditorState } from '@lobehub/editor/react';
import { ActionIcon, Flexbox, Icon, Input, Tag, Text } from '@lobehub/ui';
import { useDebounceFn } from 'ahooks';
import { App, Card, Checkbox, Empty, InputNumber, Select, Switch, TimePicker, message } from 'antd';
@@ -33,7 +33,7 @@ import useSWR from 'swr';
import AutoSaveHint from '@/components/Editor/AutoSaveHint';
import Loading from '@/components/Loading/BrandTextLoading';
import type { ExecutionConditions, UpdateAgentCronJobData } from '@/database/schemas/agentCronJob';
-import TypoBar from '@/features/EditorModal/Typobar';
+import { InlineToolbar } from '@/features/EditorCanvas';
import NavHeader from '@/features/NavHeader';
import WideScreenContainer from '@/features/WideScreenContainer';
import { useQueryRoute } from '@/hooks/useQueryRoute';
@@ -142,6 +142,7 @@ const CronJobDetailPage = memo(() => {
const router = useQueryRoute();
const { modal } = App.useApp();
const editor = useEditor();
+ const editorState = useEditorState(editor);
const enableRichRender = useUserStore(labPreferSelectors.enableInputMarkdown);
const [editorReady, setEditorReady] = useState(false);
@@ -628,7 +629,7 @@ const CronJobDetailPage = memo(() => {
style={{ borderRadius: 12, overflow: 'hidden' }}
styles={{ body: { padding: 0 } }}
>
- {enableRichRender && <TypoBar editor={editor} />}
+ {enableRichRender && <InlineToolbar editor={editor} editorState={editorState} />}
<Flexbox padding={16} style={{ minHeight: 220 }}>
<Editor
content={''}
diff --git a/src/app/[variants]/(main)/agent/profile/features/ProfileEditor/index.tsx b/src/app/[variants]/(main)/agent/profile/features/ProfileEditor/index.tsx
index fe6c63c2268..03400f217bf 100644
--- a/src/app/[variants]/(main)/agent/profile/features/ProfileEditor/index.tsx
+++ b/src/app/[variants]/(main)/agent/profile/features/ProfileEditor/index.tsx
@@ -88,7 +88,7 @@ const ProfileEditor = memo(() => {
onClick={() => {
if (!agentId) return;
// Clear topicId before navigating to prevent stale state
- switchTopic(undefined, true);
+ switchTopic(null, { skipRefreshMessage: true });
router.push(urlJoin('/agent', agentId));
}}
type={'primary'}
diff --git a/src/app/[variants]/(main)/agent/profile/features/store/action.ts b/src/app/[variants]/(main)/agent/profile/features/store/action.ts
index 9b718166722..e979a919d56 100644
--- a/src/app/[variants]/(main)/agent/profile/features/store/action.ts
+++ b/src/app/[variants]/(main)/agent/profile/features/store/action.ts
@@ -28,26 +28,25 @@ export interface Action {
export type Store = State & Action;
-// Create debounced save function outside of store for reuse
-const createDebouncedSave = (
- get: () => Store,
- updateConfig: (payload: SaveConfigPayload) => Promise<void>,
-) =>
- debounce(
- async (payload: SaveConfigPayload) => {
- try {
- await updateConfig(payload);
- } catch (error) {
- console.error('[ProfileEditor] Failed to save:', error);
- }
- },
- EDITOR_DEBOUNCE_TIME,
- { leading: false, maxWait: EDITOR_MAX_WAIT, trailing: true },
- );
+// Store the latest updateConfig reference to avoid stale closures
+let updateConfigRef: ((payload: SaveConfigPayload) => Promise<void>) | null = null;
export const store: (initState?: Partial<State>) => StateCreator<Store> =
(initState) => (set, get) => {
- let debouncedSave: ReturnType<typeof createDebouncedSave> | null = null;
+ // Create debounced save that uses the latest callback reference
+ const debouncedSave = debounce(
+ async (payload: SaveConfigPayload) => {
+ try {
+ if (updateConfigRef) {
+ await updateConfigRef(payload);
+ }
+ } catch (error) {
+ console.error('[ProfileEditor] Failed to save:', error);
+ }
+ },
+ EDITOR_DEBOUNCE_TIME,
+ { leading: false, maxWait: EDITOR_MAX_WAIT, trailing: true },
+ );
return {
...initialState,
@@ -115,10 +114,8 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =
const { editor } = get();
if (!editor) return;
- // Create debounced save on first use
- if (!debouncedSave) {
- debouncedSave = createDebouncedSave(get, updateConfig);
- }
+ // Always update ref to use the latest callback
+ updateConfigRef = updateConfig;
try {
const markdownContent = (editor.getDocument('markdown') as unknown as string) || '';
diff --git a/src/app/[variants]/(main)/group/_layout/GroupIdSync.tsx b/src/app/[variants]/(main)/group/_layout/GroupIdSync.tsx
index f7cb1f02604..fc24dd05c65 100644
--- a/src/app/[variants]/(main)/group/_layout/GroupIdSync.tsx
+++ b/src/app/[variants]/(main)/group/_layout/GroupIdSync.tsx
@@ -2,6 +2,7 @@ import { useUnmount } from 'ahooks';
import { useParams } from 'react-router-dom';
import { createStoreUpdater } from 'zustand-utils';
+import { useQueryRoute } from '@/hooks/useQueryRoute';
import { useAgentGroupStore } from '@/store/agentGroup';
import { useChatStore } from '@/store/chat';
@@ -9,14 +10,18 @@ const GroupIdSync = () => {
const useAgentGroupStoreUpdater = createStoreUpdater(useAgentGroupStore);
const useChatStoreUpdater = createStoreUpdater(useChatStore);
const params = useParams<{ gid?: string }>();
+ const router = useQueryRoute();
// Sync groupId to agentGroupStore and chatStore
useAgentGroupStoreUpdater('activeGroupId', params.gid);
useChatStoreUpdater('activeGroupId', params.gid);
+ // Inject router to agentGroupStore for navigation
+ useAgentGroupStoreUpdater('router', router);
+
// Clear activeGroupId when unmounting (leaving group page)
useUnmount(() => {
- useAgentGroupStore.setState({ activeGroupId: undefined });
+ useAgentGroupStore.setState({ activeGroupId: undefined, router: undefined });
useChatStore.setState({ activeGroupId: undefined, activeTopicId: undefined });
});
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/AgentProfilePopup.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/AgentProfilePopup.tsx
index c626cf301c5..8e79110a37b 100644
--- a/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/AgentProfilePopup.tsx
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/AgentProfilePopup.tsx
@@ -1,10 +1,12 @@
'use client';
import type { AgentItem } from '@lobechat/types';
-import { Avatar, Center, Flexbox, Popover, Text, Tooltip } from '@lobehub/ui';
+import { ActionIcon, Avatar, Center, Flexbox, Popover, Text, Tooltip } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
+import { Settings } from 'lucide-react';
import { type PropsWithChildren, memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
import { DEFAULT_AVATAR } from '@/const/meta';
import ModelSelect from '@/features/ModelSelect';
@@ -73,6 +75,7 @@ interface AgentProfilePopupProps extends PropsWithChildren {
const AgentProfilePopup = memo<AgentProfilePopupProps>(({ agent, groupId, children }) => {
const { t } = useTranslation('chat');
+ const navigate = useNavigate();
const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false);
@@ -90,10 +93,10 @@ const AgentProfilePopup = memo<AgentProfilePopupProps>(({ agent, groupId, childr
}
};
- // const handleChat = () => {
- // setOpen(false);
- // onChat();
- // };
+ const handleSettings = () => {
+ setOpen(false);
+ navigate(`/group/${groupId}/profile?tab=${agent.id}`);
+ };
const content = (
<Flexbox className={styles.container}>
@@ -127,9 +130,26 @@ const AgentProfilePopup = memo<AgentProfilePopupProps>(({ agent, groupId, childr
}}
/>
<Flexbox gap={2}>
- <Text className={styles.name} ellipsis>
- {agent.title || t('defaultSession', { ns: 'common' })}
- </Text>
+ <Flexbox align={'center'} horizontal justify={'space-between'}>
+ <Text className={styles.name} ellipsis>
+ {agent.title || t('defaultSession', { ns: 'common' })}
+ </Text>
+
+ {/* Settings Button */}
+ <Flexbox
+ align="center"
+ horizontal
+ justify="flex-end"
+ style={{ paddingBlockStart: 0 }}
+ >
+ <ActionIcon
+ icon={Settings}
+ onClick={handleSettings}
+ size="small"
+ title={t('groupSidebar.agentProfile.settings')}
+ />
+ </Flexbox>
+ </Flexbox>
{agent.description && (
<Tooltip title={agent.description}>
<Text className={styles.description} ellipsis={{ rows: 2 }}>
@@ -149,18 +169,6 @@ const AgentProfilePopup = memo<AgentProfilePopupProps>(({ agent, groupId, childr
value={{ model: agent.model!, provider: agent.provider! }}
/>
</Flexbox>
-
- {/* Actions */}
- {/*<Flexbox className={styles.section} style={{ paddingBlockStart: 0 }}>*/}
- {/* <Button*/}
- {/* className={styles.chatButton}*/}
- {/* icon={<MessageSquare size={14} />}*/}
- {/* onClick={handleChat}*/}
- {/* type="primary"*/}
- {/* >*/}
- {/* {t('groupSidebar.agentProfile.chat')}*/}
- {/* </Button>*/}
- {/*</Flexbox>*/}
</Flexbox>
);
@@ -171,7 +179,7 @@ const AgentProfilePopup = memo<AgentProfilePopupProps>(({ agent, groupId, childr
open={open}
placement="right"
styles={{
- content: { overflow: 'hidden', padding: 0 },
+ content: { borderRadius: 12, overflow: 'hidden', padding: 0 },
}}
trigger="click"
>
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx
index 3480afa48a7..44e50a1f093 100644
--- a/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx
@@ -109,6 +109,7 @@ const GroupMember = memo<GroupMemberProps>(({ addModalOpen, onAddModalOpenChange
}
avatar={item.avatar || DEFAULT_AVATAR}
background={item.backgroundColor ?? undefined}
+ isExternal={!item.virtual}
title={item.title || t('defaultSession', { ns: 'common' })}
/>
</div>
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/GroupMemberItem.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/GroupMemberItem.tsx
index e8ca47b3241..2c979c7f239 100644
--- a/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/GroupMemberItem.tsx
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/GroupMemberItem.tsx
@@ -1,7 +1,8 @@
'use client';
-import { Avatar } from '@lobehub/ui';
+import { Avatar, Flexbox, Tag } from '@lobehub/ui';
import { type ReactNode, memo } from 'react';
+import { useTranslation } from 'react-i18next';
import { DEFAULT_AVATAR } from '@/const/meta';
import NavItem from '@/features/NavPanel/components/NavItem';
@@ -10,26 +11,42 @@ interface GroupMemberItemProps {
actions?: ReactNode;
avatar?: string;
background?: string;
+ isExternal?: boolean;
onClick?: () => void;
title: string;
}
-const GroupMemberItem = memo<GroupMemberItemProps>(({ title, avatar, background, actions }) => {
- return (
- <NavItem
- actions={actions}
- icon={
- <Avatar
- avatar={avatar || DEFAULT_AVATAR}
- background={background}
- emojiScaleWithBackground
- size={24}
- style={{ flex: 'none' }}
- />
- }
- title={title}
- />
- );
-});
+const GroupMemberItem = memo<GroupMemberItemProps>(
+ ({ title, avatar, background, actions, isExternal }) => {
+ const { t } = useTranslation('chat');
+
+ return (
+ <NavItem
+ actions={actions}
+ icon={
+ <Avatar
+ avatar={avatar || DEFAULT_AVATAR}
+ background={background}
+ emojiScaleWithBackground
+ size={24}
+ style={{ flex: 'none' }}
+ />
+ }
+ title={
+ <Flexbox align="center" gap={4} horizontal>
+ <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
+ {title}
+ </span>
+ {isExternal && (
+ <Tag size="small" style={{ flexShrink: 0 }}>
+ {t('group.profile.external')}
+ </Tag>
+ )}
+ </Flexbox>
+ }
+ />
+ );
+ },
+);
export default GroupMemberItem;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Header/AddTopicButon.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Header/AddTopicButon.tsx
index 3f82c8104ed..26f41c502e4 100644
--- a/src/app/[variants]/(main)/group/_layout/Sidebar/Header/AddTopicButon.tsx
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Header/AddTopicButon.tsx
@@ -4,12 +4,9 @@ import { ActionIcon } from '@lobehub/ui';
import { MessageSquarePlusIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import urlJoin from 'url-join';
import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
-import { useQueryRoute } from '@/hooks/useQueryRoute';
import { useAgentGroupStore } from '@/store/agentGroup';
-import { useChatStore } from '@/store/chat';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
import { HotkeyEnum } from '@/types/hotkey';
@@ -17,17 +14,12 @@ import { HotkeyEnum } from '@/types/hotkey';
const AddTopicButon = memo(() => {
const { t } = useTranslation('topic');
const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.SaveTopic));
- const activeGroupId = useAgentGroupStore((s) => s.activeGroupId);
- const router = useQueryRoute();
+ const switchToNewTopic = useAgentGroupStore((s) => s.switchToNewTopic);
return (
<ActionIcon
icon={MessageSquarePlusIcon}
- onClick={() => {
- if (!activeGroupId) return;
- useChatStore.setState({ activeTopicId: undefined });
- router.push(urlJoin('/group', activeGroupId), { query: { thread: null, topic: null } });
- }}
+ onClick={switchToNewTopic}
size={DESKTOP_HEADER_ICON_SIZE}
title={t('actions.addNewTopic')}
tooltipProps={{
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Header/Nav.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Header/Nav.tsx
index 987cb7197f7..c888cf0d4d1 100644
--- a/src/app/[variants]/(main)/group/_layout/Sidebar/Header/Nav.tsx
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Header/Nav.tsx
@@ -2,7 +2,7 @@
import { Flexbox } from '@lobehub/ui';
import { BotPromptIcon } from '@lobehub/ui/icons';
-import { SearchIcon } from 'lucide-react';
+import { MessageSquarePlusIcon, SearchIcon } from 'lucide-react';
import { usePathname } from 'next/navigation';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -11,12 +11,14 @@ import urlJoin from 'url-join';
import NavItem from '@/features/NavPanel/components/NavItem';
import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useAgentGroupStore } from '@/store/agentGroup';
import { useChatStore } from '@/store/chat';
import { useGlobalStore } from '@/store/global';
import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
const Nav = memo(() => {
const { t } = useTranslation('chat');
+ const { t: tTopic } = useTranslation('topic');
const params = useParams();
const groupId = params.gid;
const pathname = usePathname();
@@ -25,15 +27,21 @@ const Nav = memo(() => {
const { isAgentEditable } = useServerConfigStore(featureFlagsSelectors);
const toggleCommandMenu = useGlobalStore((s) => s.toggleCommandMenu);
const switchTopic = useChatStore((s) => s.switchTopic);
+ const switchToNewTopic = useAgentGroupStore((s) => s.switchToNewTopic);
return (
<Flexbox gap={1} paddingInline={4}>
+ <NavItem
+ icon={MessageSquarePlusIcon}
+ onClick={switchToNewTopic}
+ title={tTopic('actions.addNewTopic')}
+ />
{isAgentEditable && (
<NavItem
active={isProfileActive}
icon={BotPromptIcon}
onClick={() => {
- switchTopic(undefined, true);
+ switchTopic(null, { skipRefreshMessage: true });
router.push(urlJoin('/group', groupId!, 'profile'));
}}
title={t('tab.groupProfile')}
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Header/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Header/index.tsx
index 6a0f066772e..7cda3110d77 100644
--- a/src/app/[variants]/(main)/group/_layout/Sidebar/Header/index.tsx
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Header/index.tsx
@@ -4,14 +4,13 @@ import { type PropsWithChildren, memo } from 'react';
import SideBarHeaderLayout from '@/features/NavPanel/SideBarHeaderLayout';
-import AddTopicButon from './AddTopicButon';
import Agent from './Agent';
import Nav from './Nav';
const HeaderInfo = memo<PropsWithChildren>(() => {
return (
<>
- <SideBarHeaderLayout left={<Agent />} right={<AddTopicButon />} />
+ <SideBarHeaderLayout left={<Agent />} />
<Nav />
</>
);
diff --git a/src/app/[variants]/(main)/group/profile/features/AgentBuilder/AgentBuilderProvider.tsx b/src/app/[variants]/(main)/group/profile/features/AgentBuilder/AgentBuilderProvider.tsx
index ede0354acac..a22eb61d403 100644
--- a/src/app/[variants]/(main)/group/profile/features/AgentBuilder/AgentBuilderProvider.tsx
+++ b/src/app/[variants]/(main)/group/profile/features/AgentBuilder/AgentBuilderProvider.tsx
@@ -16,6 +16,7 @@ interface AgentBuilderProviderProps {
* Uses 'group_agent_builder' scope with groupId to isolate messages per group
*/
const AgentBuilderProvider = memo<AgentBuilderProviderProps>(({ agentId, children }) => {
+ // Use activeTopicId from chatStore (synced with URL query 'bt' via ProfileHydration)
const activeTopicId = useChatStore((s) => s.activeTopicId);
// Build conversation context for group agent builder
diff --git a/src/app/[variants]/(main)/group/profile/features/AgentBuilder/TopicSelector.tsx b/src/app/[variants]/(main)/group/profile/features/AgentBuilder/TopicSelector.tsx
index d1ebaeb397e..b94c846d632 100644
--- a/src/app/[variants]/(main)/group/profile/features/AgentBuilder/TopicSelector.tsx
+++ b/src/app/[variants]/(main)/group/profile/features/AgentBuilder/TopicSelector.tsx
@@ -1,6 +1,6 @@
import { ActionIcon, DropdownMenu, type DropdownMenuCheckboxItem, Tag } from '@lobehub/ui';
import { Clock3Icon, PlusIcon } from 'lucide-react';
-import { memo, useMemo } from 'react';
+import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
@@ -18,11 +18,17 @@ const TopicSelector = memo<TopicSelectorProps>(({ agentId }) => {
// Fetch topics for the group agent builder
useChatStore((s) => s.useFetchTopics)(true, { agentId });
- const [activeTopicId, switchTopic, topics] = useChatStore((s) => [
- s.activeTopicId,
- s.switchTopic,
- topicSelectors.getTopicsByAgentId(agentId)(s),
- ]);
+ // Use activeTopicId from chatStore (synced with URL query 'bt' via ProfileHydration)
+ const [activeTopicId, switchTopic] = useChatStore((s) => [s.activeTopicId, s.switchTopic]);
+ const topics = useChatStore((s) => topicSelectors.getTopicsByAgentId(agentId)(s));
+
+ // Switch topic - ProfileHydration handles URL sync automatically
+ const handleSwitchTopic = useCallback(
+ (topicId?: string) => {
+ switchTopic(topicId);
+ },
+ [switchTopic],
+ );
// Find active topic from the agent's topics list directly
const activeTopic = useMemo(
@@ -39,12 +45,12 @@ const TopicSelector = memo<TopicSelectorProps>(({ agentId }) => {
label: topic.title,
onCheckedChange: (checked) => {
if (checked) {
- switchTopic(topic.id);
+ handleSwitchTopic(topic.id);
}
},
type: 'checkbox',
})),
- [topics, switchTopic, activeTopicId],
+ [topics, handleSwitchTopic, activeTopicId],
);
const isEmpty = !topics || topics.length === 0;
@@ -55,7 +61,7 @@ const TopicSelector = memo<TopicSelectorProps>(({ agentId }) => {
<>
<ActionIcon
icon={PlusIcon}
- onClick={() => switchTopic()}
+ onClick={() => handleSwitchTopic(undefined)}
size={DESKTOP_HEADER_ICON_SIZE}
title={t('actions.addNewTopic')}
/>
diff --git a/src/app/[variants]/(main)/group/profile/features/AgentBuilder/index.tsx b/src/app/[variants]/(main)/group/profile/features/AgentBuilder/index.tsx
index 4f2b0de94ce..1d48c863415 100644
--- a/src/app/[variants]/(main)/group/profile/features/AgentBuilder/index.tsx
+++ b/src/app/[variants]/(main)/group/profile/features/AgentBuilder/index.tsx
@@ -1,22 +1,27 @@
import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import { DraggablePanel } from '@lobehub/ui';
import { cssVar } from 'antd-style';
-import { memo, useState } from 'react';
+import { memo } from 'react';
import Loading from '@/components/Loading/BrandTextLoading';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+import { useGroupProfileStore } from '@/store/groupProfile';
-import { useProfileStore } from '../store';
import AgentBuilderConversation from './AgentBuilderConversation';
import AgentBuilderProvider from './AgentBuilderProvider';
const AgentBuilder = memo(() => {
- const chatPanelExpanded = useProfileStore((s) => s.chatPanelExpanded);
- const setChatPanelExpanded = useProfileStore((s) => s.setChatPanelExpanded);
+ const chatPanelExpanded = useGroupProfileStore((s) => s.chatPanelExpanded);
+ const setChatPanelExpanded = useGroupProfileStore((s) => s.setChatPanelExpanded);
const groupAgentBuilderId = useAgentStore(builtinAgentSelectors.groupAgentBuilderId);
- const [width, setWidth] = useState<string | number>(360);
+ const [width, updateSystemStatus] = useGlobalStore((s) => [
+ systemStatusSelectors.groupAgentBuilderPanelWidth(s),
+ s.updateSystemStatus,
+ ]);
const useInitBuiltinAgent = useAgentStore((s) => s.useInitBuiltinAgent);
useInitBuiltinAgent(BUILTIN_AGENT_SLUGS.groupAgentBuilder);
@@ -31,7 +36,8 @@ const AgentBuilder = memo(() => {
onExpandChange={setChatPanelExpanded}
onSizeChange={(_, size) => {
if (size?.width) {
- setWidth(size.width);
+ const w = typeof size.width === 'string' ? Number.parseInt(size.width) : size.width;
+ if (!!w) updateSystemStatus({ groupAgentBuilderPanelWidth: w });
}
}}
placement="right"
diff --git a/src/app/[variants]/(main)/group/profile/features/EditorCanvas/TypoBar.tsx b/src/app/[variants]/(main)/group/profile/features/EditorCanvas/TypoBar.tsx
deleted file mode 100644
index 8397de85aae..00000000000
--- a/src/app/[variants]/(main)/group/profile/features/EditorCanvas/TypoBar.tsx
+++ /dev/null
@@ -1,129 +0,0 @@
-import { HotkeyEnum, getHotkeyById } from '@lobehub/editor';
-import { FloatActions } from '@lobehub/editor/react';
-import { type ChatInputActionsProps } from '@lobehub/editor/react';
-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';
-
-import { useProfileStore } from '../store';
-
-const TypoBar = memo(() => {
- const { t } = useTranslation('editor');
- const editorState = useProfileStore((s) => s.editorState);
-
- const items: ChatInputActionsProps['items'] = useMemo(() => {
- if (!editorState) return [];
-
- return [
- {
- 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,
- },
- ].filter(Boolean) as ChatInputActionsProps['items'];
- }, [editorState, t]);
-
- if (!editorState) return null;
-
- return <FloatActions items={items} />;
-});
-
-TypoBar.displayName = 'TypoBar';
-
-export default TypoBar;
diff --git a/src/app/[variants]/(main)/group/profile/features/EditorCanvas/index.tsx b/src/app/[variants]/(main)/group/profile/features/EditorCanvas/index.tsx
deleted file mode 100644
index 60061767589..00000000000
--- a/src/app/[variants]/(main)/group/profile/features/EditorCanvas/index.tsx
+++ /dev/null
@@ -1,138 +0,0 @@
-'use client';
-
-import {
- ReactCodePlugin,
- ReactCodemirrorPlugin,
- ReactHRPlugin,
- ReactLinkHighlightPlugin,
- ReactListPlugin,
- ReactMathPlugin,
- ReactMentionPlugin,
- ReactTablePlugin,
- ReactToolbarPlugin,
-} from '@lobehub/editor';
-import { Editor } from '@lobehub/editor/react';
-import isEqual from 'fast-deep-equal';
-import { memo, useCallback, useEffect, useRef, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { useAgentGroupStore } from '@/store/agentGroup';
-import { agentGroupSelectors } from '@/store/agentGroup/selectors';
-
-import { useMentionOptions } from '../ProfileEditor/MentionList';
-import { EMPTY_EDITOR_STATE } from '../constants';
-import { useProfileStore } from '../store';
-import TypoBar from './TypoBar';
-import { useSlashItems } from './useSlashItems';
-
-const EditorCanvas = memo(() => {
- const { t } = useTranslation('setting');
- const [editorInit, setEditorInit] = useState(false);
- const [contentInit, setContentInit] = useState(false);
-
- // Get systemPrompt from agentGroup store (groupMap.config.systemPrompt)
- const groupConfig = useAgentGroupStore(agentGroupSelectors.currentGroupConfig, isEqual);
- const systemRole = groupConfig?.systemPrompt;
- const updateGroupConfig = useAgentGroupStore((s) => s.updateGroupConfig);
-
- // Get streaming state from agentGroup store
- const streamingInProgress = useAgentGroupStore((s) => s.streamingSystemPromptInProgress);
- const streamingSystemRole = useAgentGroupStore((s) => s.streamingSystemPrompt);
-
- // For group profile, we don't use editorData - just systemPrompt
- const editorData = undefined;
- const [initialLoad] = useState(EMPTY_EDITOR_STATE);
- const mentionOptions = useMentionOptions();
- const editor = useProfileStore((s) => s.editor);
- const handleContentChange = useProfileStore((s) => s.handleContentChange);
- const slashItems = useSlashItems();
-
- const prevStreamingRef = useRef<string | undefined>(undefined);
-
- // Wrap handleContentChange with updateGroupConfig
- const handleChange = useCallback(() => {
- // Don't trigger save during streaming
- if (streamingInProgress) return;
- handleContentChange(async (config) => {
- // Only update systemPrompt in group config
- if (config.systemRole !== undefined) {
- await updateGroupConfig({ systemPrompt: config.systemRole });
- }
- });
- }, [handleContentChange, updateGroupConfig, streamingInProgress]);
-
- // Handle streaming updates - update editor with streaming content
- useEffect(() => {
- if (!editor || !editorInit) return;
- if (!streamingInProgress) {
- prevStreamingRef.current = undefined;
- return;
- }
-
- // Only update if content has changed
- if (streamingSystemRole !== prevStreamingRef.current) {
- prevStreamingRef.current = streamingSystemRole;
- try {
- editor.setDocument('markdown', streamingSystemRole || '');
- } catch {
- // Ignore errors during streaming updates
- }
- }
- }, [editor, editorInit, streamingSystemRole, streamingInProgress]);
-
- useEffect(() => {
- if (!editorInit || !editor || contentInit) return;
- // Don't init if streaming is in progress
- if (streamingInProgress) return;
- try {
- if (editorData) {
- editor.setDocument('json', editorData);
- } else if (systemRole) {
- editor.setDocument('markdown', systemRole);
- }
- // If no editorData and no systemRole, leave editor empty to show placeholder
- setContentInit(true);
- } catch (error) {
- console.error('[EditorCanvas] Failed to init editor content:', error);
- }
- }, [editorInit, contentInit, editor, editorData, systemRole, streamingInProgress]);
-
- return (
- <div
- onClick={(e) => {
- e.stopPropagation();
- }}
- >
- <Editor
- content={initialLoad}
- editor={editor!}
- lineEmptyPlaceholder={t('settingAgent.prompt.placeholder')}
- mentionOption={mentionOptions}
- onInit={() => setEditorInit(true)}
- onTextChange={handleChange}
- placeholder={t('settingAgent.prompt.templatePlaceholder')}
- plugins={[
- ReactListPlugin,
- ReactCodePlugin,
- ReactCodemirrorPlugin,
- ReactHRPlugin,
- ReactLinkHighlightPlugin,
- ReactTablePlugin,
- ReactMathPlugin,
- ReactMentionPlugin,
- Editor.withProps(ReactToolbarPlugin, {
- children: <TypoBar />,
- }),
- ]}
- slashOption={{
- items: slashItems,
- }}
- style={{
- paddingBottom: 64,
- }}
- />
- </div>
- );
-});
-
-export default EditorCanvas;
diff --git a/src/app/[variants]/(main)/group/profile/features/EditorCanvas/useSlashItems.tsx b/src/app/[variants]/(main)/group/profile/features/EditorCanvas/useSlashItems.tsx
deleted file mode 100644
index 5f857f19f44..00000000000
--- a/src/app/[variants]/(main)/group/profile/features/EditorCanvas/useSlashItems.tsx
+++ /dev/null
@@ -1,139 +0,0 @@
-import {
- INSERT_CHECK_LIST_COMMAND,
- INSERT_HEADING_COMMAND,
- INSERT_HORIZONTAL_RULE_COMMAND,
- INSERT_MATH_COMMAND,
- INSERT_ORDERED_LIST_COMMAND,
- INSERT_TABLE_COMMAND,
- INSERT_UNORDERED_LIST_COMMAND,
- type SlashOptions,
-} from '@lobehub/editor';
-import { Text } from '@lobehub/ui';
-import {
- Heading1Icon,
- Heading2Icon,
- Heading3Icon,
- ListIcon,
- ListOrderedIcon,
- ListTodoIcon,
- MinusIcon,
- SigmaIcon,
- SquareDashedBottomCodeIcon,
- Table2Icon,
-} from 'lucide-react';
-import { useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { useProfileStore } from '../store';
-
-export const useSlashItems = (): SlashOptions['items'] => {
- const { t } = useTranslation('editor');
- const editorState = useProfileStore((s) => s.editorState);
- return useMemo(() => {
- const data: SlashOptions['items'] = [
- {
- icon: Heading1Icon,
- key: 'h1',
- label: t('slash.h1'),
- onSelect: (editor) => {
- editor.dispatchCommand(INSERT_HEADING_COMMAND, { tag: 'h1' });
- },
- },
- {
- icon: Heading2Icon,
- key: 'h2',
- label: t('slash.h2'),
- onSelect: (editor) => {
- editor.dispatchCommand(INSERT_HEADING_COMMAND, { tag: 'h2' });
- },
- },
- {
- icon: Heading3Icon,
- key: 'h3',
- label: t('slash.h3'),
- onSelect: (editor) => {
- editor.dispatchCommand(INSERT_HEADING_COMMAND, { tag: 'h3' });
- },
- },
- {
- type: 'divider',
- },
- {
- icon: ListTodoIcon,
- key: 'tl',
- label: t('typobar.taskList'),
- onSelect: (editor) => {
- editor.dispatchCommand(INSERT_CHECK_LIST_COMMAND, undefined);
- },
- },
- {
- icon: ListIcon,
- key: 'ul',
- label: t('typobar.bulletList'),
- onSelect: (editor) => {
- editor.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND, undefined);
- },
- },
- {
- icon: ListOrderedIcon,
- key: 'ol',
- label: t('typobar.numberList'),
- onSelect: (editor) => {
- editor.dispatchCommand(INSERT_ORDERED_LIST_COMMAND, undefined);
- },
- },
- {
- type: 'divider',
- },
- {
- icon: MinusIcon,
- key: 'hr',
- label: t('slash.hr'),
- onSelect: (editor) => {
- editor.dispatchCommand(INSERT_HORIZONTAL_RULE_COMMAND, {});
- },
- },
- {
- icon: Table2Icon,
- key: 'table',
- label: t('slash.table'),
- onSelect: (editor) => {
- editor.dispatchCommand(INSERT_TABLE_COMMAND, { columns: '3', rows: '3' });
- },
- },
- {
- icon: SquareDashedBottomCodeIcon,
- key: 'codeblock',
- label: t('typobar.codeblock'),
- onSelect: () => {
- editorState.codeblock();
- },
- },
- {
- icon: SigmaIcon,
- key: 'tex',
- label: t('slash.tex'),
- onSelect: (editor) => {
- editor.dispatchCommand(INSERT_MATH_COMMAND, { code: 'x^2 + y^2 = z^2' });
- queueMicrotask(() => {
- editor.focus();
- });
- },
- },
- ];
- return data.map((item) => {
- if (item.type === 'divider') return item;
- return {
- ...item,
- extra: (
- <Text code fontSize={12} type={'secondary'}>
- {item.key}
- </Text>
- ),
- style: {
- minWidth: 200,
- },
- };
- });
- }, [t]);
-};
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileEditor/AgentHeader.tsx b/src/app/[variants]/(main)/group/profile/features/GroupProfile/GroupHeader.tsx
similarity index 75%
rename from src/app/[variants]/(main)/group/profile/features/ProfileEditor/AgentHeader.tsx
rename to src/app/[variants]/(main)/group/profile/features/GroupProfile/GroupHeader.tsx
index 0628c137d5b..88341e7f4e6 100644
--- a/src/app/[variants]/(main)/group/profile/features/ProfileEditor/AgentHeader.tsx
+++ b/src/app/[variants]/(main)/group/profile/features/GroupProfile/GroupHeader.tsx
@@ -1,6 +1,6 @@
'use client';
-import { DEFAULT_AVATAR, EDITOR_DEBOUNCE_TIME } from '@lobechat/const';
+import { EDITOR_DEBOUNCE_TIME } from '@lobechat/const';
import { Block, Flexbox, Icon, Input, Skeleton, Tooltip } from '@lobehub/ui';
import { useDebounceFn } from 'ahooks';
import { message } from 'antd';
@@ -9,11 +9,9 @@ import { PaletteIcon } from 'lucide-react';
import { Suspense, memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import SupervisorAvatar from '@/app/[variants]/(main)/group/features/GroupAvatar';
+import GroupAvatar from '@/app/[variants]/(main)/group/features/GroupAvatar';
import EmojiPicker from '@/components/EmojiPicker';
import BackgroundSwatches from '@/features/AgentSetting/AgentMeta/BackgroundSwatches';
-import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
import { useAgentGroupStore } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
import { useFileStore } from '@/store/file';
@@ -22,23 +20,19 @@ import { globalGeneralSelectors } from '@/store/global/selectors';
const MAX_AVATAR_SIZE = 1024 * 1024; // 1MB limit for server actions
-const AgentHeader = memo(() => {
+const GroupHeader = memo(() => {
const { t } = useTranslation(['setting', 'common']);
const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
- // Get title from agentGroup store (groupMap.title)
+ // Get group meta from agentGroup store
const groupMeta = useAgentGroupStore(agentGroupSelectors.currentGroupMeta, isEqual);
const updateGroupMeta = useAgentGroupStore((s) => s.updateGroupMeta);
- // Get avatar/backgroundColor from supervisor agent (useAgentStore)
- const agentMeta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);
- const updateAgentMeta = useAgentStore((s) => s.updateAgentMeta);
-
// File upload
const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);
const [uploading, setUploading] = useState(false);
- // Local state for inputs (to avoid stuttering during typing)
+ // Local state for inputs
const [localTitle, setLocalTitle] = useState(groupMeta.title || '');
// Sync local state when meta changes from external source
@@ -46,7 +40,7 @@ const AgentHeader = memo(() => {
setLocalTitle(groupMeta.title || '');
}, [groupMeta.title]);
- // Debounced save for title - save to group store
+ // Debounced save for title
const { run: debouncedSaveTitle } = useDebounceFn(
(value: string) => {
updateGroupMeta({ title: value });
@@ -54,9 +48,9 @@ const AgentHeader = memo(() => {
{ wait: EDITOR_DEBOUNCE_TIME },
);
- // Handle avatar change (immediate save) - save to agent store (supervisor agent)
+ // Handle avatar change (immediate save)
const handleAvatarChange = (emoji: string) => {
- updateAgentMeta({ avatar: emoji });
+ updateGroupMeta({ avatar: emoji });
};
// Handle avatar upload
@@ -70,26 +64,25 @@ const AgentHeader = memo(() => {
setUploading(true);
try {
const result = await uploadWithProgress({ file });
- console.log('result', result);
if (result?.url) {
- updateAgentMeta({ avatar: result.url });
+ updateGroupMeta({ avatar: result.url });
}
} finally {
setUploading(false);
}
},
- [uploadWithProgress, updateAgentMeta, t],
+ [uploadWithProgress, updateGroupMeta, t],
);
// Handle avatar delete
const handleAvatarDelete = useCallback(() => {
- updateAgentMeta({ avatar: undefined });
- }, [updateAgentMeta]);
+ updateGroupMeta({ avatar: undefined });
+ }, [updateGroupMeta]);
- // Handle background color change (immediate save) - save to agent store (supervisor agent)
+ // Handle background color change
const handleBackgroundColorChange = (color?: string) => {
if (color !== undefined) {
- updateAgentMeta({ backgroundColor: color });
+ updateGroupMeta({ backgroundColor: color });
}
};
@@ -106,20 +99,20 @@ const AgentHeader = memo(() => {
}}
>
<EmojiPicker
- allowDelete={!!agentMeta.avatar}
+ allowDelete={!!groupMeta.avatar}
allowUpload
background={
- agentMeta.backgroundColor && agentMeta.backgroundColor !== 'rgba(0,0,0,0)'
- ? agentMeta.backgroundColor
+ groupMeta.backgroundColor && groupMeta.backgroundColor !== 'rgba(0,0,0,0)'
+ ? groupMeta.backgroundColor
: undefined
}
customRender={
- agentMeta.avatar && agentMeta.avatar !== DEFAULT_AVATAR
+ groupMeta.avatar
? undefined
: () => {
return (
<Block clickable height={72} width={72}>
- <SupervisorAvatar size={72} />
+ <GroupAvatar size={72} />
</Block>
);
}
@@ -146,7 +139,7 @@ const AgentHeader = memo(() => {
onChange={handleBackgroundColorChange}
shape={'square'}
size={38}
- value={agentMeta.backgroundColor}
+ value={groupMeta.backgroundColor}
/>
</Suspense>
</Flexbox>
@@ -164,7 +157,7 @@ const AgentHeader = memo(() => {
}}
shape={'square'}
size={72}
- value={agentMeta.avatar}
+ value={groupMeta.avatar}
/>
<Input
onChange={(e) => {
@@ -185,4 +178,4 @@ const AgentHeader = memo(() => {
);
});
-export default AgentHeader;
+export default GroupHeader;
diff --git a/src/app/[variants]/(main)/group/profile/features/GroupProfile/index.tsx b/src/app/[variants]/(main)/group/profile/features/GroupProfile/index.tsx
new file mode 100644
index 00000000000..428af134d95
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/GroupProfile/index.tsx
@@ -0,0 +1,96 @@
+'use client';
+
+import { Button, Flexbox } from '@lobehub/ui';
+import { Divider } from 'antd';
+import { PlayIcon } from 'lucide-react';
+import { memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+import urlJoin from 'url-join';
+
+import { EditorCanvas } from '@/features/EditorCanvas';
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+import { useGroupProfileStore } from '@/store/groupProfile';
+
+import AutoSaveHint from '../Header/AutoSaveHint';
+import GroupHeader from './GroupHeader';
+
+const GroupProfile = memo(() => {
+ const { t } = useTranslation(['setting', 'chat']);
+ const groupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
+ const currentGroup = useAgentGroupStore(agentGroupSelectors.currentGroup);
+ const updateGroup = useAgentGroupStore((s) => s.updateGroup);
+ const router = useQueryRoute();
+
+ const editor = useGroupProfileStore((s) => s.editor);
+ const handleContentChange = useGroupProfileStore((s) => s.handleContentChange);
+
+ // Create save callback that captures latest groupId
+ const saveContent = useCallback(
+ async (payload: { content: string; editorData: Record<string, any> }) => {
+ if (!groupId) return;
+ await updateGroup(groupId, {
+ content: payload.content,
+ editorData: payload.editorData,
+ });
+ },
+ [updateGroup, groupId],
+ );
+
+ const onContentChange = useCallback(() => {
+ handleContentChange(saveContent);
+ }, [handleContentChange, saveContent]);
+
+ return (
+ <>
+ <Flexbox
+ onClick={(e) => {
+ e.stopPropagation();
+ }}
+ style={{ cursor: 'default', marginBottom: 12 }}
+ >
+ <Flexbox height={66} width={'100%'}>
+ <Flexbox paddingBlock={12}>
+ <AutoSaveHint />
+ </Flexbox>
+ </Flexbox>
+ {/* Header: Group Avatar + Title */}
+ <GroupHeader />
+ {/* Start Conversation Button */}
+ <Flexbox
+ align={'center'}
+ gap={8}
+ horizontal
+ justify={'flex-start'}
+ style={{ marginTop: 16 }}
+ >
+ <Button
+ icon={PlayIcon}
+ onClick={() => {
+ if (!groupId) return;
+ router.push(urlJoin('/group', groupId));
+ }}
+ type={'primary'}
+ >
+ {t('startConversation')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ <Divider />
+ {/* Group Content Editor */}
+ <EditorCanvas
+ editor={editor}
+ editorData={{
+ content: currentGroup?.content ?? undefined,
+ editorData: currentGroup?.editorData,
+ }}
+ key={groupId}
+ onContentChange={onContentChange}
+ placeholder={t('group.profile.contentPlaceholder', { ns: 'chat' })}
+ />
+ </>
+ );
+});
+
+export default GroupProfile;
diff --git a/src/app/[variants]/(main)/group/profile/features/Header/AgentBuilderToggle.tsx b/src/app/[variants]/(main)/group/profile/features/Header/AgentBuilderToggle.tsx
index b01238bd05e..f59ef51034b 100644
--- a/src/app/[variants]/(main)/group/profile/features/Header/AgentBuilderToggle.tsx
+++ b/src/app/[variants]/(main)/group/profile/features/Header/AgentBuilderToggle.tsx
@@ -3,12 +3,11 @@ import { BotMessageSquareIcon } from 'lucide-react';
import { memo } from 'react';
import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
-
-import { useProfileStore } from '../store';
+import { useGroupProfileStore } from '@/store/groupProfile';
const AgentBuilderToggle = memo(() => {
- const chatPanelExpanded = useProfileStore((s) => s.chatPanelExpanded);
- const setChatPanelExpanded = useProfileStore((s) => s.setChatPanelExpanded);
+ const chatPanelExpanded = useGroupProfileStore((s) => s.chatPanelExpanded);
+ const setChatPanelExpanded = useGroupProfileStore((s) => s.setChatPanelExpanded);
return (
<ActionIcon
diff --git a/src/app/[variants]/(main)/group/profile/features/Header/AutoSaveHint.tsx b/src/app/[variants]/(main)/group/profile/features/Header/AutoSaveHint.tsx
index 63d991ee14d..70d5bd43395 100644
--- a/src/app/[variants]/(main)/group/profile/features/Header/AutoSaveHint.tsx
+++ b/src/app/[variants]/(main)/group/profile/features/Header/AutoSaveHint.tsx
@@ -3,15 +3,19 @@
import { memo } from 'react';
import AutoSaveHintBase from '@/components/Editor/AutoSaveHint';
+import { useGroupProfileStore } from '@/store/groupProfile';
+import { selectors } from '@/store/groupProfile/selectors';
-/**
- * AutoSaveHint - Save status indicator for group settings
- * TODO: Add saveStatus and lastUpdatedTime to agentGroupStore when needed
- */
const AutoSaveHint = memo(() => {
- // Group profile currently doesn't track save status
- // Return idle state for now
- return <AutoSaveHintBase lastUpdatedTime={null} saveStatus={'idle'} />;
+ const activeTabId = useGroupProfileStore((s) => s.activeTabId);
+ const saveState = useGroupProfileStore(selectors.getSaveState(activeTabId));
+
+ return (
+ <AutoSaveHintBase
+ lastUpdatedTime={saveState.lastUpdatedTime}
+ saveStatus={saveState.saveStatus}
+ />
+ );
});
export default AutoSaveHint;
diff --git a/src/app/[variants]/(main)/group/profile/features/Header/ChromeTabs/index.tsx b/src/app/[variants]/(main)/group/profile/features/Header/ChromeTabs/index.tsx
new file mode 100644
index 00000000000..5f5f2281cc0
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/Header/ChromeTabs/index.tsx
@@ -0,0 +1,149 @@
+'use client';
+
+import { Avatar, Flexbox } from '@lobehub/ui';
+import { createStaticStyles, cx } from 'antd-style';
+import { Plus } from 'lucide-react';
+import { ReactNode, memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const styles = createStaticStyles(({ css, cssVar: cv }) => ({
+ addButton: css`
+ cursor: pointer;
+
+ flex-shrink: 0;
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ width: 28px;
+ height: 28px;
+ border-radius: 6px;
+
+ color: ${cv.colorTextTertiary};
+
+ background: transparent;
+
+ transition: all 0.2s;
+
+ &:hover {
+ color: ${cv.colorTextSecondary};
+ background: ${cv.colorFillTertiary};
+ }
+ `,
+ container: css`
+ display: flex;
+ gap: 2px;
+ align-items: center;
+ `,
+ externalTag: css`
+ flex-shrink: 0;
+
+ padding-block: 1px;
+ padding-inline: 4px;
+ border-radius: 4px;
+
+ font-size: 10px;
+ line-height: 1.2;
+
+ background: ${cv.colorFillSecondary};
+ `,
+ tab: css`
+ cursor: pointer;
+
+ flex-shrink: 0;
+
+ display: flex;
+ gap: 6px;
+ align-items: center;
+
+ height: 32px;
+ padding-block: 6px;
+ padding-inline: 12px;
+ border-radius: 8px;
+
+ color: ${cv.colorTextTertiary};
+
+ background: transparent;
+
+ transition: all 0.2s;
+
+ &:hover {
+ color: ${cv.colorTextSecondary};
+ background: ${cv.colorFillTertiary};
+ }
+ `,
+ tabActive: css`
+ color: ${cv.colorText};
+ background: ${cv.colorFillTertiary};
+
+ &:hover {
+ color: ${cv.colorText};
+ background: ${cv.colorFillTertiary};
+ }
+ `,
+ tabTitle: css`
+ overflow: hidden;
+
+ max-width: 120px;
+
+ font-size: 13px;
+ line-height: 1.2;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+}));
+
+export interface ChromeTabItem {
+ avatar?: string;
+ icon?: ReactNode;
+ id: string;
+ isExternal?: boolean;
+ title: string;
+}
+
+interface ChromeTabsProps {
+ activeId: string;
+ items: ChromeTabItem[];
+ onAdd?: () => void;
+ onChange: (id: string) => void;
+}
+
+const ChromeTabs = memo<ChromeTabsProps>(({ items, activeId, onChange, onAdd }) => {
+ const { t } = useTranslation('chat');
+
+ return (
+ <div className={styles.container}>
+ {items.map((item) => {
+ const isActive = item.id === activeId;
+
+ return (
+ <div
+ className={cx(styles.tab, isActive && styles.tabActive)}
+ key={item.id}
+ onClick={() => onChange(item.id)}
+ >
+ <Flexbox align="center" gap={6} horizontal>
+ {item.icon ? (
+ item.icon
+ ) : item.avatar ? (
+ <Avatar avatar={item.avatar} size={18} />
+ ) : null}
+ <span className={styles.tabTitle}>{item.title}</span>
+ {item.isExternal && (
+ <span className={styles.externalTag}>{t('group.profile.external')}</span>
+ )}
+ </Flexbox>
+ </div>
+ );
+ })}
+ {onAdd && (
+ <div className={styles.addButton} onClick={onAdd}>
+ <Plus size={16} />
+ </div>
+ )}
+ </div>
+ );
+});
+
+export default ChromeTabs;
diff --git a/src/app/[variants]/(main)/group/profile/features/Header/index.tsx b/src/app/[variants]/(main)/group/profile/features/Header/index.tsx
index adbd075baed..78799780bfb 100644
--- a/src/app/[variants]/(main)/group/profile/features/Header/index.tsx
+++ b/src/app/[variants]/(main)/group/profile/features/Header/index.tsx
@@ -1,23 +1,117 @@
-import { memo } from 'react';
+'use client';
-import NavHeader from '@/features/NavHeader';
-import WideScreenButton from '@/features/WideScreenContainer/WideScreenButton';
+import { Flexbox } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { Crown, Users } from 'lucide-react';
+import { memo, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AddGroupMemberModal from '@/app/[variants]/(main)/group/_layout/Sidebar/AddGroupMemberModal';
+import { parseAsString, useQueryState } from '@/hooks/useQueryParam';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
import AgentBuilderToggle from './AgentBuilderToggle';
-import AutoSaveHint from './AutoSaveHint';
+import ChromeTabs, { type ChromeTabItem } from './ChromeTabs';
+
+const useStyles = createStyles(({ css, token }) => ({
+ header: css`
+ overflow: hidden;
+
+ flex: none;
+
+ width: 100%;
+ height: 44px;
+ padding-block: 8px;
+ padding-inline: 12px;
+
+ border-block-end: 1px solid ${token.colorBorderSecondary};
+ `,
+ tabsWrapper: css`
+ overflow-x: auto;
+ flex: 1;
+ min-width: 0;
+
+ scrollbar-width: none;
+
+ &::-webkit-scrollbar {
+ display: none;
+ }
+ `,
+}));
const Header = memo(() => {
+ const { t } = useTranslation('chat');
+ const { styles } = useStyles();
+
+ const [showAddModal, setShowAddModal] = useState(false);
+
+ const members = useAgentGroupStore(agentGroupSelectors.currentGroupAgents);
+ const activeGroupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
+ const addAgentsToGroup = useAgentGroupStore((s) => s.addAgentsToGroup);
+
+ // Use URL query param for selected tab
+ const [selectedTabId, setSelectedTabId] = useQueryState(
+ 'tab',
+ parseAsString.withDefault('group'),
+ );
+
+ const existingMemberIds = useMemo(() => members.map((a) => a.id), [members]);
+
+ const tabItems = useMemo<ChromeTabItem[]>(() => {
+ const items: ChromeTabItem[] = [
+ {
+ icon: <Users size={16} />,
+ id: 'group',
+ title: t('group.profile.groupSettings'),
+ },
+ ];
+
+ // Add agent tabs
+ for (const agent of members) {
+ items.push({
+ avatar: agent.isSupervisor ? undefined : agent.avatar || undefined,
+ icon: agent.isSupervisor ? <Crown size={16} /> : undefined,
+ id: agent.id,
+ isExternal: !agent.isSupervisor && !agent.virtual,
+ title: agent.isSupervisor ? t('group.profile.supervisor') : agent.title || 'Untitled Agent',
+ });
+ }
+
+ return items;
+ }, [members, t]);
+
+ const handleAddMembers = async (agentIds: string[]) => {
+ if (!activeGroupId) return;
+ await addAgentsToGroup(activeGroupId, agentIds);
+ setShowAddModal(false);
+ };
+
return (
- <NavHeader
- left={<AutoSaveHint />}
- right={
- <>
- <WideScreenButton />
+ <>
+ <Flexbox align="center" className={styles.header} horizontal justify="space-between">
+ <div className={styles.tabsWrapper}>
+ <ChromeTabs
+ activeId={selectedTabId}
+ items={tabItems}
+ onAdd={() => setShowAddModal(true)}
+ onChange={setSelectedTabId}
+ />
+ </div>
+ <Flexbox align="center" flex="none" gap={8} horizontal style={{ marginInlineStart: 12 }}>
<AgentBuilderToggle />
- {/* TODO: Add GroupPublishButton when group publishing is supported */}
- </>
- }
- />
+ </Flexbox>
+ </Flexbox>
+ {activeGroupId && (
+ <AddGroupMemberModal
+ existingMembers={existingMemberIds}
+ groupId={activeGroupId}
+ onCancel={() => setShowAddModal(false)}
+ onConfirm={handleAddMembers}
+ open={showAddModal}
+ />
+ )}
+ </>
);
});
diff --git a/src/app/[variants]/(main)/group/profile/features/MemberProfile/AgentHeader.tsx b/src/app/[variants]/(main)/group/profile/features/MemberProfile/AgentHeader.tsx
new file mode 100644
index 00000000000..9de28611c1a
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/MemberProfile/AgentHeader.tsx
@@ -0,0 +1,222 @@
+'use client';
+
+import { DEFAULT_AVATAR, EDITOR_DEBOUNCE_TIME } from '@lobechat/const';
+import { Block, Flexbox, Icon, Input, Skeleton, Tooltip } from '@lobehub/ui';
+import { useDebounceFn } from 'ahooks';
+import { message } from 'antd';
+import isEqual from 'fast-deep-equal';
+import { PaletteIcon } from 'lucide-react';
+import { Suspense, memo, useCallback, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import SupervisorAvatar from '@/app/[variants]/(main)/group/features/GroupAvatar';
+import EmojiPicker from '@/components/EmojiPicker';
+import BackgroundSwatches from '@/features/AgentSetting/AgentMeta/BackgroundSwatches';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { useFileStore } from '@/store/file';
+import { useGlobalStore } from '@/store/global';
+import { globalGeneralSelectors } from '@/store/global/selectors';
+import { useGroupProfileStore } from '@/store/groupProfile';
+
+const MAX_AVATAR_SIZE = 1024 * 1024; // 1MB limit for server actions
+
+interface AgentHeaderProps {
+ /**
+ * When true, shows fixed title (supervisor) and disables avatar editing
+ */
+ readOnly?: boolean;
+}
+
+const AgentHeader = memo<AgentHeaderProps>(({ readOnly }) => {
+ const { t } = useTranslation(['setting', 'common', 'chat']);
+ const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
+
+ // Get agentId from profile store
+ const agentId = useGroupProfileStore((s) => s.activeTabId);
+
+ // Get agent meta by agentId
+ const agentMeta = useAgentStore(agentSelectors.getAgentMetaById(agentId), isEqual);
+ const optimisticUpdateAgentMeta = useAgentStore((s) => s.optimisticUpdateAgentMeta);
+
+ // File upload
+ const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);
+ const [uploading, setUploading] = useState(false);
+
+ // Local state for inputs (to avoid stuttering during typing)
+ const [localTitle, setLocalTitle] = useState(agentMeta.title || '');
+
+ // Sync local state when meta changes from external source
+ useEffect(() => {
+ setLocalTitle(agentMeta.title || '');
+ }, [agentMeta.title]);
+
+ // Debounced save for title - save to agent store
+ const { run: debouncedSaveTitle } = useDebounceFn(
+ (value: string) => {
+ optimisticUpdateAgentMeta(agentId, { title: value });
+ },
+ { wait: EDITOR_DEBOUNCE_TIME },
+ );
+
+ // Handle avatar change (immediate save) - save to agent store (supervisor agent)
+ const handleAvatarChange = (emoji: string) => {
+ optimisticUpdateAgentMeta(agentId, { avatar: emoji });
+ };
+
+ // Handle avatar upload
+ const handleAvatarUpload = useCallback(
+ async (file: File) => {
+ if (file.size > MAX_AVATAR_SIZE) {
+ message.error(t('settingAgent.avatar.sizeExceeded', { ns: 'setting' }));
+ return;
+ }
+
+ setUploading(true);
+ try {
+ const result = await uploadWithProgress({ file });
+ console.log('result', result);
+ if (result?.url) {
+ optimisticUpdateAgentMeta(agentId, { avatar: result.url });
+ }
+ } finally {
+ setUploading(false);
+ }
+ },
+ [uploadWithProgress, optimisticUpdateAgentMeta, agentId, t],
+ );
+
+ // Handle avatar delete
+ const handleAvatarDelete = useCallback(() => {
+ optimisticUpdateAgentMeta(agentId, { avatar: undefined });
+ }, [optimisticUpdateAgentMeta, agentId]);
+
+ // Handle background color change (immediate save) - save to agent store (supervisor agent)
+ const handleBackgroundColorChange = (color?: string) => {
+ if (color !== undefined) {
+ optimisticUpdateAgentMeta(agentId, { backgroundColor: color });
+ }
+ };
+
+ // ReadOnly mode: show fixed avatar and title (for supervisor)
+ if (readOnly) {
+ return (
+ <Flexbox
+ gap={16}
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ }}
+ paddingBlock={16}
+ style={{
+ cursor: 'default',
+ }}
+ >
+ <Block height={72} width={72}>
+ <SupervisorAvatar size={72} />
+ </Block>
+ <Flexbox
+ style={{
+ fontSize: 36,
+ fontWeight: 600,
+ }}
+ >
+ {t('group.profile.supervisor', { ns: 'chat' })}
+ </Flexbox>
+ </Flexbox>
+ );
+ }
+
+ return (
+ <Flexbox
+ gap={16}
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ }}
+ paddingBlock={16}
+ style={{
+ cursor: 'default',
+ }}
+ >
+ <EmojiPicker
+ allowDelete={!!agentMeta.avatar}
+ allowUpload
+ background={
+ agentMeta.backgroundColor && agentMeta.backgroundColor !== 'rgba(0,0,0,0)'
+ ? agentMeta.backgroundColor
+ : undefined
+ }
+ customRender={
+ agentMeta.avatar && agentMeta.avatar !== DEFAULT_AVATAR
+ ? undefined
+ : () => {
+ return (
+ <Block clickable height={72} width={72}>
+ <SupervisorAvatar size={72} />
+ </Block>
+ );
+ }
+ }
+ customTabs={[
+ {
+ label: (
+ <Tooltip title={t('settingAgent.backgroundColor.title', { ns: 'setting' })}>
+ <Icon icon={PaletteIcon} size={{ size: 20, strokeWidth: 2.5 }} />
+ </Tooltip>
+ ),
+ render: () => (
+ <Flexbox padding={8} width={332}>
+ <Suspense
+ fallback={
+ <Flexbox gap={8}>
+ <Skeleton.Button block style={{ height: 38 }} />
+ <Skeleton.Button block style={{ height: 38 }} />
+ </Flexbox>
+ }
+ >
+ <BackgroundSwatches
+ gap={8}
+ onChange={handleBackgroundColorChange}
+ shape={'square'}
+ size={38}
+ value={agentMeta.backgroundColor}
+ />
+ </Suspense>
+ </Flexbox>
+ ),
+ value: 'background',
+ },
+ ]}
+ loading={uploading}
+ locale={locale}
+ onChange={handleAvatarChange}
+ onDelete={handleAvatarDelete}
+ onUpload={handleAvatarUpload}
+ popupProps={{
+ placement: 'bottomLeft',
+ }}
+ shape={'square'}
+ size={72}
+ value={agentMeta.avatar}
+ />
+ <Input
+ onChange={(e) => {
+ setLocalTitle(e.target.value);
+ debouncedSaveTitle(e.target.value);
+ }}
+ placeholder={t('settingAgent.name.placeholder', { ns: 'setting' })}
+ style={{
+ fontSize: 36,
+ fontWeight: 600,
+ padding: 0,
+ width: '100%',
+ }}
+ value={localTitle}
+ variant={'borderless'}
+ />
+ </Flexbox>
+ );
+});
+
+export default AgentHeader;
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileEditor/AgentTool.tsx b/src/app/[variants]/(main)/group/profile/features/MemberProfile/AgentTool.tsx
similarity index 100%
rename from src/app/[variants]/(main)/group/profile/features/ProfileEditor/AgentTool.tsx
rename to src/app/[variants]/(main)/group/profile/features/MemberProfile/AgentTool.tsx
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/MentionDropdown.tsx b/src/app/[variants]/(main)/group/profile/features/MemberProfile/MentionList/MentionDropdown.tsx
similarity index 100%
rename from src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/MentionDropdown.tsx
rename to src/app/[variants]/(main)/group/profile/features/MemberProfile/MentionList/MentionDropdown.tsx
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/index.tsx b/src/app/[variants]/(main)/group/profile/features/MemberProfile/MentionList/index.tsx
similarity index 100%
rename from src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/index.tsx
rename to src/app/[variants]/(main)/group/profile/features/MemberProfile/MentionList/index.tsx
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/types.ts b/src/app/[variants]/(main)/group/profile/features/MemberProfile/MentionList/types.ts
similarity index 100%
rename from src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/types.ts
rename to src/app/[variants]/(main)/group/profile/features/MemberProfile/MentionList/types.ts
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/useMentionItems.tsx b/src/app/[variants]/(main)/group/profile/features/MemberProfile/MentionList/useMentionItems.tsx
similarity index 100%
rename from src/app/[variants]/(main)/group/profile/features/ProfileEditor/MentionList/useMentionItems.tsx
rename to src/app/[variants]/(main)/group/profile/features/MemberProfile/MentionList/useMentionItems.tsx
diff --git a/src/app/[variants]/(main)/group/profile/features/MemberProfile/index.tsx b/src/app/[variants]/(main)/group/profile/features/MemberProfile/index.tsx
new file mode 100644
index 00000000000..958002c90a3
--- /dev/null
+++ b/src/app/[variants]/(main)/group/profile/features/MemberProfile/index.tsx
@@ -0,0 +1,155 @@
+'use client';
+
+import { Alert, Button, Flexbox, Icon } from '@lobehub/ui';
+import { Divider } from 'antd';
+import isEqual from 'fast-deep-equal';
+import { InfoIcon, PlayIcon } from 'lucide-react';
+import React, { memo, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import urlJoin from 'url-join';
+
+import { EditorCanvas } from '@/features/EditorCanvas';
+import ModelSelect from '@/features/ModelSelect';
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+import { useGroupProfileStore } from '@/store/groupProfile';
+
+import AutoSaveHint from '../Header/AutoSaveHint';
+import AgentHeader from './AgentHeader';
+import AgentTool from './AgentTool';
+
+const MemberProfile = memo(() => {
+ const { t } = useTranslation(['setting', 'chat']);
+
+ // Get agentId from profile store (activeTabId is the selected agent ID)
+ const agentId = useGroupProfileStore((s) => s.activeTabId);
+ const editor = useGroupProfileStore((s) => s.editor);
+ const handleContentChange = useGroupProfileStore((s) => s.handleContentChange);
+
+ // Get agent config by agentId
+ const config = useAgentStore(agentByIdSelectors.getAgentConfigById(agentId), isEqual);
+ const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
+
+ const groupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
+ const currentGroup = useAgentGroupStore(agentGroupSelectors.currentGroup);
+ const currentGroupAgents = useAgentGroupStore(agentGroupSelectors.currentGroupAgents);
+ const router = useQueryRoute();
+
+ // Check if the current agent is the supervisor
+ const isSupervisor = currentGroup?.supervisorAgentId === agentId;
+
+ // Compute isExternal based on group member properties
+ const isExternal = useMemo(() => {
+ const agent = currentGroupAgents.find((a) => a.id === agentId);
+ return agent ? !agent.isSupervisor && !agent.virtual : false;
+ }, [currentGroupAgents, agentId]);
+
+ // Wrap updateAgentConfigById for saving editor content
+ const updateContent = useCallback(
+ async (payload: { content: string; editorData: Record<string, any> }) => {
+ await updateAgentConfigById(agentId, {
+ editorData: payload.editorData,
+ systemRole: payload.content,
+ });
+ },
+ [updateAgentConfigById, agentId],
+ );
+
+ // Handle editor content change
+ const onContentChange = useCallback(() => {
+ handleContentChange(updateContent);
+ }, [handleContentChange, updateContent]);
+
+ // Wrap updateAgentConfigById for ModelSelect
+ const updateAgentConfig = useCallback(
+ async (config: { model?: string; provider?: string }) => {
+ await updateAgentConfigById(agentId, config);
+ },
+ [updateAgentConfigById, agentId],
+ );
+
+ return (
+ <>
+ {/* External agent warning or AutoSaveHint */}
+ <Flexbox height={66} width={'100%'}>
+ {isExternal && !isSupervisor && (
+ <Alert
+ icon={<Icon icon={InfoIcon} />}
+ style={{ width: '100%' }}
+ title={t('group.profile.externalAgentWarning', { ns: 'chat' })}
+ type="secondary"
+ variant={'outlined'}
+ />
+ )}
+ <Flexbox paddingBlock={12}>
+ <AutoSaveHint />
+ </Flexbox>
+ </Flexbox>
+ <Flexbox
+ onClick={(e) => {
+ e.stopPropagation();
+ }}
+ style={{ cursor: 'default', marginBottom: 12 }}
+ >
+ {/* Header: Avatar + Name */}
+ <AgentHeader readOnly={isSupervisor} />
+ {/* Config Bar: Model Selector */}
+ <Flexbox
+ align={'center'}
+ gap={8}
+ horizontal
+ justify={'flex-start'}
+ style={{ marginBottom: 12 }}
+ >
+ <ModelSelect
+ onChange={updateAgentConfig}
+ value={{
+ model: config?.model,
+ provider: config?.provider,
+ }}
+ />
+ </Flexbox>
+ <AgentTool />
+ <Flexbox
+ align={'center'}
+ gap={8}
+ horizontal
+ justify={'flex-start'}
+ style={{ marginTop: 16 }}
+ >
+ <Button
+ icon={PlayIcon}
+ onClick={() => {
+ if (!groupId) return;
+ router.push(urlJoin('/group', groupId));
+ }}
+ type={'primary'}
+ >
+ {t('startConversation')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ <Divider />
+ {/* Main Content: Prompt Editor */}
+ <EditorCanvas
+ editor={editor}
+ editorData={{
+ content: config?.systemRole,
+ editorData: config?.editorData,
+ }}
+ key={agentId}
+ onContentChange={onContentChange}
+ placeholder={
+ isSupervisor
+ ? t('group.profile.supervisorPlaceholder', { ns: 'chat' })
+ : t('settingAgent.prompt.placeholder')
+ }
+ />
+ </>
+ );
+});
+
+export default MemberProfile;
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileEditor/index.tsx b/src/app/[variants]/(main)/group/profile/features/ProfileEditor/index.tsx
deleted file mode 100644
index 35a67f2d05e..00000000000
--- a/src/app/[variants]/(main)/group/profile/features/ProfileEditor/index.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-'use client';
-
-import { Button, Flexbox } from '@lobehub/ui';
-import { Divider } from 'antd';
-import isEqual from 'fast-deep-equal';
-import { PlayIcon } from 'lucide-react';
-import React, { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import urlJoin from 'url-join';
-
-import ModelSelect from '@/features/ModelSelect';
-import { useQueryRoute } from '@/hooks/useQueryRoute';
-import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
-import { useAgentGroupStore } from '@/store/agentGroup';
-import { agentGroupSelectors } from '@/store/agentGroup/selectors';
-
-import EditorCanvas from '../EditorCanvas';
-import AgentHeader from './AgentHeader';
-import AgentTool from './AgentTool';
-
-const ProfileEditor = memo(() => {
- const { t } = useTranslation('setting');
- const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);
- const updateConfig = useAgentStore((s) => s.updateAgentConfig);
- const groupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
- const router = useQueryRoute();
-
- return (
- <>
- <Flexbox
- onClick={(e) => {
- e.stopPropagation();
- }}
- style={{ cursor: 'default', marginBottom: 12 }}
- >
- {/* Header: Avatar + Name + Description */}
- <AgentHeader />
- {/* Config Bar: Model Selector */}
- <Flexbox
- align={'center'}
- gap={8}
- horizontal
- justify={'flex-start'}
- style={{ marginBottom: 12 }}
- >
- <ModelSelect
- onChange={updateConfig}
- value={{
- model: config?.model,
- provider: config?.provider,
- }}
- />
- </Flexbox>
- <AgentTool />
- <Flexbox
- align={'center'}
- gap={8}
- horizontal
- justify={'flex-start'}
- style={{ marginTop: 16 }}
- >
- <Button
- icon={PlayIcon}
- onClick={() => {
- if (!groupId) return;
- router.push(urlJoin('/group', groupId));
- }}
- type={'primary'}
- >
- {t('startConversation')}
- </Button>
- </Flexbox>
- </Flexbox>
- <Divider />
- {/* Main Content: Prompt Editor */}
- <EditorCanvas />
- </>
- );
-});
-
-export default ProfileEditor;
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileHydration.tsx b/src/app/[variants]/(main)/group/profile/features/ProfileHydration.tsx
index 4376bcd2fac..dd2f16ebade 100644
--- a/src/app/[variants]/(main)/group/profile/features/ProfileHydration.tsx
+++ b/src/app/[variants]/(main)/group/profile/features/ProfileHydration.tsx
@@ -1,15 +1,73 @@
-import { memo } from 'react';
+'use client';
-import { useRegisterFilesHotkeys, useSaveDocumentHotkey } from '@/hooks/useHotkeys';
+import { useEditor, useEditorState } from '@lobehub/editor/react';
+import { useUnmount } from 'ahooks';
+import { memo, useEffect, useRef } from 'react';
+import { createStoreUpdater } from 'zustand-utils';
-import { useProfileStore } from './store';
+import { useRegisterFilesHotkeys, useSaveDocumentHotkey } from '@/hooks/useHotkeys';
+import { parseAsString, useQueryState } from '@/hooks/useQueryParam';
+import { useChatStore } from '@/store/chat';
+import { useGroupProfileStore } from '@/store/groupProfile';
const ProfileHydration = memo(() => {
- // Initialize agent builder builtin agent
- const flushSave = useProfileStore((s) => s.flushSave);
+ const editor = useEditor();
+ const editorState = useEditorState(editor);
+ const flushSave = useGroupProfileStore((s) => s.flushSave);
+
+ const storeUpdater = createStoreUpdater(useGroupProfileStore);
+
+ // Sync editor to store
+ storeUpdater('editor', editor);
+ // Sync editorState to store
+ storeUpdater('editorState', editorState);
+ // Sync tab query param to store
+ const [activeTabId] = useQueryState('tab', parseAsString.withDefault('group'));
+ storeUpdater('activeTabId', activeTabId);
+
+ // Bidirectional sync between URL query 'bt' and chatStore.activeTopicId
+ const [builderTopicId, setBuilderTopicId] = useQueryState('bt');
+ const activeTopicId = useChatStore((s) => s.activeTopicId);
+
+ // Track if the change came from URL to prevent sync loops
+ const isUrlChangeRef = useRef(false);
+
+ // Sync URL → Store (when URL changes)
+ useEffect(() => {
+ const urlTopicId = builderTopicId ?? undefined;
+ if (urlTopicId !== activeTopicId) {
+ isUrlChangeRef.current = true;
+ useChatStore.setState({ activeTopicId: urlTopicId });
+ }
+ }, [builderTopicId]);
+
+ // Sync Store → URL (when store changes, but not from URL)
+ useEffect(() => {
+ if (isUrlChangeRef.current) {
+ isUrlChangeRef.current = false;
+ return;
+ }
+ const urlTopicId = builderTopicId ?? undefined;
+ if (activeTopicId !== urlTopicId) {
+ setBuilderTopicId(activeTopicId ?? null);
+ }
+ }, [activeTopicId]);
+
+ // Register hotkeys
useRegisterFilesHotkeys();
useSaveDocumentHotkey(flushSave);
+ // Clear state when unmounting
+ useUnmount(() => {
+ useGroupProfileStore.setState({
+ activeTabId: 'group',
+ editor: undefined,
+ editorState: undefined,
+ saveStateMap: {},
+ });
+ useChatStore.setState({ activeTopicId: undefined });
+ });
+
return null;
});
diff --git a/src/app/[variants]/(main)/group/profile/features/ProfileProvider.tsx b/src/app/[variants]/(main)/group/profile/features/ProfileProvider.tsx
deleted file mode 100644
index 41f4afc4d18..00000000000
--- a/src/app/[variants]/(main)/group/profile/features/ProfileProvider.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-'use client';
-
-import { useEditor } from '@lobehub/editor/react';
-import { type PropsWithChildren, memo } from 'react';
-
-import StoreUpdater from './StoreUpdater';
-import { Provider, createStore } from './store';
-
-const ProfileProvider = memo<PropsWithChildren>(({ children }) => {
- const editor = useEditor();
-
- return (
- <Provider createStore={() => createStore({ editor })}>
- <StoreUpdater />
- {children}
- </Provider>
- );
-});
-
-export default ProfileProvider;
diff --git a/src/app/[variants]/(main)/group/profile/features/StoreUpdater.tsx b/src/app/[variants]/(main)/group/profile/features/StoreUpdater.tsx
deleted file mode 100644
index 1601fe870d7..00000000000
--- a/src/app/[variants]/(main)/group/profile/features/StoreUpdater.tsx
+++ /dev/null
@@ -1,24 +0,0 @@
-'use client';
-
-import { useEditorState } from '@lobehub/editor/react';
-import { memo, useEffect } from 'react';
-
-import { type PublicState, useProfileStore, useStoreApi } from './store';
-
-export type StoreUpdaterProps = Partial<PublicState>;
-
-const StoreUpdater = memo<StoreUpdaterProps>(() => {
- const storeApi = useStoreApi();
-
- const editor = useProfileStore((s) => s.editor);
- const editorState = useEditorState(editor);
-
- // Update editorState in store
- useEffect(() => {
- storeApi.setState({ editorState });
- }, [editorState, storeApi]);
-
- return null;
-});
-
-export default StoreUpdater;
diff --git a/src/app/[variants]/(main)/group/profile/features/store/action.ts b/src/app/[variants]/(main)/group/profile/features/store/action.ts
deleted file mode 100644
index b5f3bf994e3..00000000000
--- a/src/app/[variants]/(main)/group/profile/features/store/action.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-import { EDITOR_DEBOUNCE_TIME, EDITOR_MAX_WAIT } from '@lobechat/const';
-import { debounce } from 'es-toolkit/compat';
-import { type StateCreator } from 'zustand';
-
-import { type State, initialState } from './initialState';
-
-type SaveConfigPayload = {
- editorData: Record<string, any>;
- systemRole: string;
-};
-
-export interface Action {
- /**
- * Append content to streaming buffer (called during streaming)
- */
- appendStreamingContent: (chunk: string) => void;
- /**
- * Finalize streaming and save to config
- */
- finishStreaming: (updateConfig: (payload: SaveConfigPayload) => Promise<void>) => Promise<void>;
- flushSave: () => void;
- handleContentChange: (updateConfig: (payload: SaveConfigPayload) => Promise<void>) => void;
- setChatPanelExpanded: (expanded: boolean | ((prev: boolean) => boolean)) => void;
- /**
- * Start streaming mode - clears editor and prepares for streaming content
- */
- startStreaming: () => void;
-}
-
-export type Store = State & Action;
-
-// Create debounced save function outside of store for reuse
-const createDebouncedSave = (
- get: () => Store,
- updateConfig: (payload: SaveConfigPayload) => Promise<void>,
-) =>
- debounce(
- async (payload: SaveConfigPayload) => {
- try {
- await updateConfig(payload);
- } catch (error) {
- console.error('[ProfileEditor] Failed to save:', error);
- }
- },
- EDITOR_DEBOUNCE_TIME,
- { leading: false, maxWait: EDITOR_MAX_WAIT, trailing: true },
- );
-
-export const store: (initState?: Partial<State>) => StateCreator<Store> =
- (initState) => (set, get) => {
- let debouncedSave: ReturnType<typeof createDebouncedSave> | null = null;
-
- return {
- ...initialState,
- ...initState,
-
- appendStreamingContent: (chunk) => {
- const currentContent = get().streamingContent || '';
- const newContent = currentContent + chunk;
- set({ streamingContent: newContent });
-
- // Update editor with streaming content
- const { editor } = get();
- if (editor) {
- try {
- editor.setDocument('markdown', newContent);
- } catch {
- // Ignore errors during streaming updates
- }
- }
- },
-
- finishStreaming: async (updateConfig) => {
- const { editor, streamingContent } = get();
- if (!streamingContent) {
- set({ streamingInProgress: false });
- return;
- }
-
- // Get the final content from editor
- let finalContent = streamingContent;
- let editorData = {};
-
- if (editor) {
- try {
- finalContent =
- (editor.getDocument('markdown') as unknown as string) || streamingContent;
- editorData = editor.getDocument('json') as unknown as Record<string, any>;
- } catch {
- // Use streaming content if editor read fails
- }
- }
-
- // Save to config
- try {
- await updateConfig({
- editorData: structuredClone(editorData || {}),
- systemRole: finalContent,
- });
- } catch (error) {
- console.error('[ProfileEditor] Failed to save streaming content:', error);
- }
-
- // Reset streaming state
- set({
- streamingContent: undefined,
- streamingInProgress: false,
- });
- },
-
- flushSave: () => {
- debouncedSave?.flush();
- },
-
- handleContentChange: (updateConfig) => {
- const { editor } = get();
- if (!editor) return;
-
- // Create debounced save on first use
- if (!debouncedSave) {
- debouncedSave = createDebouncedSave(get, updateConfig);
- }
-
- try {
- const markdownContent = (editor.getDocument('markdown') as unknown as string) || '';
- const jsonContent = editor.getDocument('json') as unknown as Record<string, any>;
-
- debouncedSave({
- editorData: structuredClone(jsonContent || {}),
- systemRole: markdownContent || '',
- });
- } catch (error) {
- console.error('[ProfileEditor] Failed to read editor content:', error);
- }
- },
-
- setChatPanelExpanded: (expanded) => {
- if (typeof expanded === 'function') {
- set((state) => ({ chatPanelExpanded: expanded(state.chatPanelExpanded) }));
- } else {
- set({ chatPanelExpanded: expanded });
- }
- },
-
- startStreaming: () => {
- const { editor } = get();
-
- // Clear editor content and prepare for streaming
- if (editor) {
- try {
- editor.setDocument('markdown', '');
- } catch {
- // Ignore errors
- }
- }
-
- set({
- streamingContent: '',
- streamingInProgress: true,
- });
- },
- };
- };
diff --git a/src/app/[variants]/(main)/group/profile/features/store/index.ts b/src/app/[variants]/(main)/group/profile/features/store/index.ts
deleted file mode 100644
index 3dc03cf6839..00000000000
--- a/src/app/[variants]/(main)/group/profile/features/store/index.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-'use client';
-
-import { type StoreApiWithSelector } from '@lobechat/types';
-import { createContext } from 'zustand-utils';
-import { subscribeWithSelector } from 'zustand/middleware';
-import { shallow } from 'zustand/shallow';
-import { createWithEqualityFn } from 'zustand/traditional';
-
-import { type Store, store } from './action';
-import { type State } from './initialState';
-
-export type { PublicState, State } from './initialState';
-
-export const createStore = (initState?: Partial<State>) =>
- createWithEqualityFn(subscribeWithSelector(store(initState)), shallow);
-
-export const {
- useStore: useProfileStore,
- useStoreApi,
- Provider,
-} = createContext<StoreApiWithSelector<Store>>();
-
-export { selectors } from './selectors';
diff --git a/src/app/[variants]/(main)/group/profile/features/store/selectors.ts b/src/app/[variants]/(main)/group/profile/features/store/selectors.ts
deleted file mode 100644
index 7333b25a0c9..00000000000
--- a/src/app/[variants]/(main)/group/profile/features/store/selectors.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { type Store } from './action';
-
-export const selectors = {
- chatPanelExpanded: (s: Store) => s.chatPanelExpanded,
- editor: (s: Store) => s.editor,
- editorState: (s: Store) => s.editorState,
-};
diff --git a/src/app/[variants]/(main)/group/profile/index.tsx b/src/app/[variants]/(main)/group/profile/index.tsx
index 6c230efec50..5609ad54019 100644
--- a/src/app/[variants]/(main)/group/profile/index.tsx
+++ b/src/app/[variants]/(main)/group/profile/index.tsx
@@ -7,58 +7,55 @@ import Loading from '@/components/Loading/BrandTextLoading';
import WideScreenContainer from '@/features/WideScreenContainer';
import { useAgentGroupStore } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+import { useGroupProfileStore } from '@/store/groupProfile';
import AgentBuilder from './features/AgentBuilder';
+import GroupProfileSettings from './features/GroupProfile';
import Header from './features/Header';
-import ProfileEditor from './features/ProfileEditor';
+import MemberProfile from './features/MemberProfile';
import ProfileHydration from './features/ProfileHydration';
-import ProfileProvider from './features/ProfileProvider';
-import { useProfileStore } from './features/store';
const ProfileArea = memo(() => {
- const editor = useProfileStore((s) => s.editor);
+ const editor = useGroupProfileStore((s) => s.editor);
+ const activeTabId = useGroupProfileStore((s) => s.activeTabId);
const isGroupsLoading = useAgentGroupStore(agentGroupSelectors.isGroupsInit);
+ const isGroupTab = activeTabId === 'group';
+
return (
- <>
- <Flexbox flex={1} height={'100%'}>
- {isGroupsLoading ? (
- <Loading debugId="ProfileArea" />
- ) : (
- <>
- <Header />
- <Flexbox
- height={'100%'}
- horizontal
- onClick={() => {
- editor?.focus();
- }}
- style={{ cursor: 'text', display: 'flex', overflowY: 'auto', position: 'relative' }}
- width={'100%'}
- >
- <WideScreenContainer>
- <ProfileEditor />
- </WideScreenContainer>
- </Flexbox>
- </>
- )}
- </Flexbox>
- <Suspense fallback={null}>
- <ProfileHydration />
- </Suspense>
- </>
+ <Flexbox flex={1} height={'100%'} style={{ minWidth: 0, overflow: 'hidden' }}>
+ {isGroupsLoading ? (
+ <Loading debugId="ProfileArea" />
+ ) : (
+ <>
+ <Header />
+ <Flexbox
+ height={'100%'}
+ horizontal
+ onClick={() => {
+ editor?.focus();
+ }}
+ style={{ cursor: 'text', display: 'flex', overflowY: 'auto', position: 'relative' }}
+ width={'100%'}
+ >
+ <WideScreenContainer>
+ {isGroupTab ? <GroupProfileSettings /> : <MemberProfile />}
+ </WideScreenContainer>
+ </Flexbox>
+ </>
+ )}
+ </Flexbox>
);
});
const GroupProfile: FC = () => {
return (
<Suspense fallback={<Loading debugId="GroupProfile" />}>
- <ProfileProvider>
- <Flexbox height={'100%'} horizontal width={'100%'}>
- <ProfileArea />
- <AgentBuilder />
- </Flexbox>
- </ProfileProvider>
+ <ProfileHydration />
+ <Flexbox height={'100%'} horizontal width={'100%'}>
+ <ProfileArea />
+ <AgentBuilder />
+ </Flexbox>
</Suspense>
);
};
diff --git a/src/app/[variants]/(mobile)/(home)/_layout/SessionHydration.tsx b/src/app/[variants]/(mobile)/(home)/_layout/SessionHydration.tsx
index 561283ed32c..3062fef9a88 100644
--- a/src/app/[variants]/(mobile)/(home)/_layout/SessionHydration.tsx
+++ b/src/app/[variants]/(mobile)/(home)/_layout/SessionHydration.tsx
@@ -22,7 +22,7 @@ const SessionHydration = memo(() => {
});
useStoreUpdater('activeId', session);
- useChatStoreUpdater('activeId', session);
+ useChatStoreUpdater('activeAgentId', session);
useEffect(() => {
const unsubscribe = useSessionStore.subscribe(
diff --git a/src/app/[variants]/(mobile)/(home)/features/SessionListContent/List/Item/index.tsx b/src/app/[variants]/(mobile)/(home)/features/SessionListContent/List/Item/index.tsx
index e891639fd06..b692c9a52bf 100644
--- a/src/app/[variants]/(mobile)/(home)/features/SessionListContent/List/Item/index.tsx
+++ b/src/app/[variants]/(mobile)/(home)/features/SessionListContent/List/Item/index.tsx
@@ -32,7 +32,7 @@ const SessionItem = memo<SessionItemProps>(({ id }) => {
const [active] = useSessionStore((s) => [s.activeId === id]);
const [loading] = useChatStore((s) => [
- operationSelectors.isAgentRuntimeRunning(s) && id === s.activeId,
+ operationSelectors.isAgentRuntimeRunning(s) && id === s.activeAgentId,
]);
const [pin, title, avatar, avatarBackground, updateAt, members, model, group, sessionType] =
diff --git a/src/features/AgentBuilder/index.tsx b/src/features/AgentBuilder/index.tsx
index e69e441aa04..2a05a1bf1a9 100644
--- a/src/features/AgentBuilder/index.tsx
+++ b/src/features/AgentBuilder/index.tsx
@@ -5,6 +5,8 @@ import Loading from '@/components/Loading/BrandTextLoading';
import RightPanel from '@/features/RightPanel';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
import AgentBuilderConversation from './AgentBuilderConversation';
import AgentBuilderProvider from './AgentBuilderProvider';
@@ -13,11 +15,24 @@ const AgentBuilder = memo(() => {
const agentId = useAgentStore((s) => s.activeAgentId);
const agentBuilderId = useAgentStore(builtinAgentSelectors.agentBuilderId);
+ const [width, updateSystemStatus] = useGlobalStore((s) => [
+ systemStatusSelectors.agentBuilderPanelWidth(s),
+ s.updateSystemStatus,
+ ]);
+
const useInitBuiltinAgent = useAgentStore((s) => s.useInitBuiltinAgent);
useInitBuiltinAgent(BUILTIN_AGENT_SLUGS.agentBuilder);
return (
- <RightPanel>
+ <RightPanel
+ defaultWidth={width}
+ onSizeChange={(size) => {
+ if (size?.width) {
+ const w = typeof size.width === 'string' ? Number.parseInt(size.width) : size.width;
+ if (!!w) updateSystemStatus({ agentBuilderPanelWidth: w });
+ }
+ }}
+ >
{agentId && agentBuilderId ? (
<AgentBuilderProvider agentId={agentBuilderId}>
<AgentBuilderConversation agentId={agentBuilderId} />
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/StatusIndicator.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/StatusIndicator.tsx
index 0097b53991c..20f682d785d 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/StatusIndicator.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/StatusIndicator.tsx
@@ -1,10 +1,11 @@
import { type ToolIntervention } from '@lobechat/types';
import { Block, Icon, Tooltip } from '@lobehub/ui';
import { cssVar } from 'antd-style';
-import { Ban, Check, HandIcon, Loader2Icon, PauseIcon, X } from 'lucide-react';
+import { Ban, Check, HandIcon, PauseIcon, X } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import { LOADING_FLAT } from '@/const/message';
interface StatusIndicatorProps {
@@ -43,7 +44,7 @@ const StatusIndicator = memo<StatusIndicatorProps>(({ intervention, result }) =>
} else if (hasResult) {
icon = <Icon color={cssVar.colorSuccess} icon={Check} />;
} else {
- icon = <Icon color={cssVar.colorTextDescription} icon={Loader2Icon} spin />;
+ icon = <NeuralNetworkLoading size={16} />;
}
return (
diff --git a/src/features/EditorCanvas/EditorCanvas.test.tsx b/src/features/EditorCanvas/EditorCanvas.test.tsx
new file mode 100644
index 00000000000..e1191a08948
--- /dev/null
+++ b/src/features/EditorCanvas/EditorCanvas.test.tsx
@@ -0,0 +1,206 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { type IEditor } from '@lobehub/editor';
+import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { EditorCanvas } from './EditorCanvas';
+
+// Mock DocumentIdMode
+vi.mock('./DocumentIdMode', () => ({
+ default: vi.fn(({ documentId }) => (
+ <div data-testid="document-id-mode">DocumentIdMode: {documentId}</div>
+ )),
+}));
+
+// Mock EditorDataMode
+vi.mock('./EditorDataMode', () => ({
+ default: vi.fn(({ editorData }) => (
+ <div data-testid="editor-data-mode">EditorDataMode: {editorData?.content}</div>
+ )),
+}));
+
+// Mock InternalEditor
+vi.mock('./InternalEditor', () => ({
+ default: vi.fn(() => <div data-testid="internal-editor">InternalEditor</div>),
+}));
+
+// Mock ErrorBoundary to pass through children
+vi.mock('./ErrorBoundary', () => ({
+ EditorErrorBoundary: vi.fn(({ children }) => <>{children}</>),
+}));
+
+describe('EditorCanvas', () => {
+ let mockEditor: IEditor;
+
+ beforeEach(() => {
+ mockEditor = {
+ getDocument: vi.fn(),
+ setDocument: vi.fn(),
+ focus: vi.fn(),
+ } as unknown as IEditor;
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+ });
+
+ describe('mode selection', () => {
+ it('should render DocumentIdMode when documentId is provided', () => {
+ render(<EditorCanvas documentId="doc-123" editor={mockEditor} />);
+
+ expect(screen.getByTestId('document-id-mode')).toBeInTheDocument();
+ expect(screen.getByText('DocumentIdMode: doc-123')).toBeInTheDocument();
+ expect(screen.queryByTestId('editor-data-mode')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('internal-editor')).not.toBeInTheDocument();
+ });
+
+ it('should render EditorDataMode when editorData is provided', () => {
+ render(<EditorCanvas editor={mockEditor} editorData={{ content: 'test content' }} />);
+
+ expect(screen.getByTestId('editor-data-mode')).toBeInTheDocument();
+ expect(screen.getByText('EditorDataMode: test content')).toBeInTheDocument();
+ expect(screen.queryByTestId('document-id-mode')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('internal-editor')).not.toBeInTheDocument();
+ });
+
+ it('should render InternalEditor in basic mode (no documentId or editorData)', () => {
+ render(<EditorCanvas editor={mockEditor} />);
+
+ expect(screen.getByTestId('internal-editor')).toBeInTheDocument();
+ expect(screen.queryByTestId('document-id-mode')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('editor-data-mode')).not.toBeInTheDocument();
+ });
+
+ it('should return null in basic mode when editor is undefined', () => {
+ const { container } = render(<EditorCanvas editor={undefined} />);
+
+ expect(container.firstChild).toBeNull();
+ });
+ });
+
+ describe('mode priority', () => {
+ it('should prioritize documentId over editorData when both are provided', () => {
+ render(
+ <EditorCanvas
+ documentId="doc-123"
+ editor={mockEditor}
+ editorData={{ content: 'test content' }}
+ />,
+ );
+
+ expect(screen.getByTestId('document-id-mode')).toBeInTheDocument();
+ expect(screen.queryByTestId('editor-data-mode')).not.toBeInTheDocument();
+ });
+ });
+
+ describe('props forwarding', () => {
+ it('should forward props to DocumentIdMode', async () => {
+ const onContentChange = vi.fn();
+ const onInit = vi.fn();
+
+ render(
+ <EditorCanvas
+ autoSave={false}
+ documentId="doc-123"
+ editor={mockEditor}
+ onContentChange={onContentChange}
+ onInit={onInit}
+ placeholder="Custom placeholder"
+ sourceType="notebook"
+ />,
+ );
+
+ const DocumentIdMode = await vi.importMock('./DocumentIdMode');
+ const lastCall = (DocumentIdMode.default as ReturnType<typeof vi.fn>).mock.calls.at(-1);
+
+ expect(lastCall?.[0]).toMatchObject({
+ autoSave: false,
+ documentId: 'doc-123',
+ editor: mockEditor,
+ onContentChange,
+ onInit,
+ placeholder: 'Custom placeholder',
+ sourceType: 'notebook',
+ });
+ });
+
+ it('should forward props to EditorDataMode', async () => {
+ const onContentChange = vi.fn();
+ const onInit = vi.fn();
+ const editorData = { content: 'test', editorData: { blocks: [] } };
+
+ render(
+ <EditorCanvas
+ editor={mockEditor}
+ editorData={editorData}
+ onContentChange={onContentChange}
+ onInit={onInit}
+ placeholder="Custom placeholder"
+ />,
+ );
+
+ const EditorDataMode = await vi.importMock('./EditorDataMode');
+ const lastCall = (EditorDataMode.default as ReturnType<typeof vi.fn>).mock.calls.at(-1);
+
+ expect(lastCall?.[0]).toMatchObject({
+ editor: mockEditor,
+ editorData,
+ onContentChange,
+ onInit,
+ placeholder: 'Custom placeholder',
+ });
+ });
+
+ it('should forward props to InternalEditor in basic mode', async () => {
+ const onContentChange = vi.fn();
+ const onInit = vi.fn();
+
+ render(
+ <EditorCanvas
+ editor={mockEditor}
+ floatingToolbar={false}
+ onContentChange={onContentChange}
+ onInit={onInit}
+ placeholder="Custom placeholder"
+ />,
+ );
+
+ const InternalEditor = await vi.importMock('./InternalEditor');
+ const lastCall = (InternalEditor.default as ReturnType<typeof vi.fn>).mock.calls.at(-1);
+
+ expect(lastCall?.[0]).toMatchObject({
+ editor: mockEditor,
+ floatingToolbar: false,
+ onContentChange,
+ onInit,
+ placeholder: 'Custom placeholder',
+ });
+ });
+ });
+
+ describe('error boundary wrapping', () => {
+ it('should wrap DocumentIdMode with ErrorBoundary', async () => {
+ render(<EditorCanvas documentId="doc-123" editor={mockEditor} />);
+
+ const ErrorBoundary = await vi.importMock('./ErrorBoundary');
+ expect(ErrorBoundary.EditorErrorBoundary).toHaveBeenCalled();
+ });
+
+ it('should wrap EditorDataMode with ErrorBoundary', async () => {
+ render(<EditorCanvas editor={mockEditor} editorData={{ content: 'test' }} />);
+
+ const ErrorBoundary = await vi.importMock('./ErrorBoundary');
+ expect(ErrorBoundary.EditorErrorBoundary).toHaveBeenCalled();
+ });
+
+ it('should wrap InternalEditor with ErrorBoundary in basic mode', async () => {
+ render(<EditorCanvas editor={mockEditor} />);
+
+ const ErrorBoundary = await vi.importMock('./ErrorBoundary');
+ expect(ErrorBoundary.EditorErrorBoundary).toHaveBeenCalled();
+ });
+ });
+});
diff --git a/src/features/EditorCanvas/EditorDataMode.tsx b/src/features/EditorCanvas/EditorDataMode.tsx
index 53626965632..9ba3d01d72a 100644
--- a/src/features/EditorCanvas/EditorDataMode.tsx
+++ b/src/features/EditorCanvas/EditorDataMode.tsx
@@ -1,7 +1,7 @@
'use client';
import { type IEditor } from '@lobehub/editor';
-import { memo, useEffect, useState } from 'react';
+import { memo, useCallback, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import type { EditorCanvasProps } from './EditorCanvas';
@@ -12,37 +12,70 @@ export interface EditorDataModeProps extends EditorCanvasProps {
editorData: NonNullable<EditorCanvasProps['editorData']>;
}
+const loadEditorContent = (
+ editorInstance: IEditor,
+ editorData: EditorDataModeProps['editorData'],
+): boolean => {
+ const hasValidEditorData =
+ editorData.editorData &&
+ typeof editorData.editorData === 'object' &&
+ Object.keys(editorData.editorData as object).length > 0;
+
+ if (hasValidEditorData) {
+ editorInstance.setDocument('json', JSON.stringify(editorData.editorData));
+ return true;
+ } else if (editorData.content?.trim()) {
+ editorInstance.setDocument('markdown', editorData.content, { keepId: true });
+ return true;
+ }
+ return false;
+};
+
/**
* EditorCanvas with editorData mode - uses provided data directly
*/
const EditorDataMode = memo<EditorDataModeProps>(
- ({ editor, editorData, onContentChange, style, ...editorProps }) => {
+ ({ editor, editorData, onContentChange, onInit, style, ...editorProps }) => {
const { t } = useTranslation('file');
- const [isInitialized, setIsInitialized] = useState(false);
+ const isEditorReadyRef = useRef(false);
+ // Track loaded content to support re-loading when data changes
+ const loadedContentRef = useRef<string | undefined>(undefined);
- // Load content into editor on mount
- useEffect(() => {
- if (!editor || isInitialized) return;
+ // Check if content has actually changed
+ const hasDataChanged = loadedContentRef.current !== editorData.content;
- const hasValidEditorData =
- editorData.editorData &&
- typeof editorData.editorData === 'object' &&
- Object.keys(editorData.editorData as object).length > 0;
+ const handleInit = useCallback(
+ (editorInstance: IEditor) => {
+ isEditorReadyRef.current = true;
- try {
- if (hasValidEditorData) {
- editor.setDocument('json', JSON.stringify(editorData.editorData));
- } else if (editorData.content?.trim()) {
- editor.setDocument('markdown', editorData.content, { keepId: true });
- } else {
- console.error('[EditorCanvas] load content error:', editorData);
+ // Try to load content if editorData is available and hasn't been loaded yet
+ if (hasDataChanged) {
+ try {
+ if (loadEditorContent(editorInstance, editorData)) {
+ loadedContentRef.current = editorData.content;
+ }
+ } catch (err) {
+ console.error('[EditorCanvas] Failed to load content:', err);
+ }
}
- setIsInitialized(true);
+ onInit?.(editorInstance);
+ },
+ [editorData, hasDataChanged, onInit],
+ );
+
+ // Load content when editorData changes after editor is ready
+ useEffect(() => {
+ if (!editor || !isEditorReadyRef.current || !hasDataChanged) return;
+
+ try {
+ if (loadEditorContent(editor, editorData)) {
+ loadedContentRef.current = editorData.content;
+ }
} catch (err) {
console.error('[EditorCanvas] Failed to load content:', err);
}
- }, [editorData, editor, isInitialized]);
+ }, [editor, editorData, hasDataChanged]);
if (!editor) return null;
@@ -51,6 +84,7 @@ const EditorDataMode = memo<EditorDataModeProps>(
<InternalEditor
editor={editor}
onContentChange={onContentChange}
+ onInit={handleInit}
placeholder={editorProps.placeholder || t('pageEditor.editorPlaceholder')}
{...editorProps}
/>
diff --git a/src/features/EditorModal/EditorCanvas.tsx b/src/features/EditorModal/EditorCanvas.tsx
deleted file mode 100644
index f693892e009..00000000000
--- a/src/features/EditorModal/EditorCanvas.tsx
+++ /dev/null
@@ -1,84 +0,0 @@
-import {
- IEditor,
- ReactCodePlugin,
- ReactCodemirrorPlugin,
- ReactHRPlugin,
- ReactLinkPlugin,
- ReactListPlugin,
- ReactMathPlugin,
- ReactTablePlugin,
-} from '@lobehub/editor';
-import { Editor } from '@lobehub/editor/react';
-import { Flexbox } from '@lobehub/ui';
-import { FC, useMemo } from 'react';
-
-import { useUserStore } from '@/store/user';
-import { labPreferSelectors } from '@/store/user/selectors';
-
-import TypoBar from './Typobar';
-
-interface EditorCanvasProps {
- defaultValue?: string;
- editor?: IEditor;
-}
-
-const EditorCanvas: FC<EditorCanvasProps> = ({ defaultValue, editor }) => {
- const enableRichRender = useUserStore(labPreferSelectors.enableInputMarkdown);
-
- const richRenderProps = useMemo(
- () =>
- !enableRichRender
- ? {
- enablePasteMarkdown: false,
- markdownOption: false,
- }
- : {
- plugins: [
- ReactListPlugin,
- ReactCodePlugin,
- ReactCodemirrorPlugin,
- ReactHRPlugin,
- ReactLinkPlugin,
- ReactTablePlugin,
- ReactMathPlugin,
- ],
- },
- [enableRichRender],
- );
-
- return (
- <>
- {enableRichRender && <TypoBar editor={editor} />}
- <Flexbox
- padding={16}
- style={{ cursor: 'text', maxHeight: '80vh', minHeight: '50vh', overflowY: 'auto' }}
- >
- <Editor
- autoFocus
- content={''}
- editor={editor}
- onInit={(editor) => {
- if (!editor || !defaultValue) return;
- try {
- if (enableRichRender) {
- editor?.setDocument('markdown', defaultValue);
- } else {
- editor?.setDocument('text', defaultValue);
- }
- } catch (e) {
- console.error('setDocument error:', e);
- }
- }}
- style={{
- paddingBottom: 120,
- }}
- type={'text'}
- variant={'chat'}
- {...richRenderProps}
- />
- </Flexbox>
- </>
- );
-};
-
-export default EditorCanvas;
diff --git a/src/features/EditorModal/Typobar.tsx b/src/features/EditorModal/Typobar.tsx
deleted file mode 100644
index 442adaf3123..00000000000
--- a/src/features/EditorModal/Typobar.tsx
+++ /dev/null
@@ -1,139 +0,0 @@
-import { HotkeyEnum, type IEditor, getHotkeyById } from '@lobehub/editor';
-import { useEditorState } from '@lobehub/editor/react';
-import {
- ChatInputActionBar,
- ChatInputActions,
- type ChatInputActionsProps,
-} from '@lobehub/editor/react';
-import { cssVar } 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 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,
- },
- ].filter(Boolean) as ChatInputActionsProps['items'],
- [editorState],
- );
-
- return (
- <ChatInputActionBar
- left={<ChatInputActions items={items} />}
- style={{
- background: cssVar.colorFillQuaternary,
- borderTopLeftRadius: 8,
- borderTopRightRadius: 8,
- }}
- />
- );
-});
-
-TypoBar.displayName = 'TypoBar';
-
-export default TypoBar;
diff --git a/src/features/EditorModal/index.tsx b/src/features/EditorModal/index.tsx
index 27076b221d2..b717ad8f573 100644
--- a/src/features/EditorModal/index.tsx
+++ b/src/features/EditorModal/index.tsx
@@ -3,7 +3,7 @@ import { Modal, ModalProps, createRawModal } from '@lobehub/ui';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import EditorCanvas from './EditorCanvas';
+import { EditorCanvas } from '@/features/EditorCanvas';
interface EditorModalProps extends ModalProps {
onConfirm?: (value: string) => Promise<void>;
@@ -43,7 +43,7 @@ export const EditorModal = memo<EditorModalProps>(({ value, onConfirm, ...rest }
width={'min(90vw, 920px)'}
{...rest}
>
- <EditorCanvas defaultValue={value} editor={editor} />
+ <EditorCanvas editor={editor} editorData={{ content: value }} />
</Modal>
);
});
diff --git a/src/features/NavPanel/components/SessionHydration.tsx b/src/features/NavPanel/components/SessionHydration.tsx
index 561283ed32c..3062fef9a88 100644
--- a/src/features/NavPanel/components/SessionHydration.tsx
+++ b/src/features/NavPanel/components/SessionHydration.tsx
@@ -22,7 +22,7 @@ const SessionHydration = memo(() => {
});
useStoreUpdater('activeId', session);
- useChatStoreUpdater('activeId', session);
+ useChatStoreUpdater('activeAgentId', session);
useEffect(() => {
const unsubscribe = useSessionStore.subscribe(
diff --git a/src/features/ShareModal/ShareImage/ChatList/index.tsx b/src/features/ShareModal/ShareImage/ChatList/index.tsx
index 257e20bc8ea..4bfe4bc64ba 100644
--- a/src/features/ShareModal/ShareImage/ChatList/index.tsx
+++ b/src/features/ShareModal/ShareImage/ChatList/index.tsx
@@ -8,7 +8,7 @@ import { chatSelectors } from '@/store/chat/selectors';
const ChatList = memo(() => {
const ids = useChatStore(chatSelectors.mainDisplayChatIDs);
const messages = useChatStore(chatSelectors.activeBaseChats);
- const agentId = useChatStore((s) => s.activeId);
+ const agentId = useChatStore((s) => s.activeAgentId);
const topicId = useChatStore((s) => s.activeTopicId);
return (
diff --git a/src/features/ShareModal/SharePdf/index.tsx b/src/features/ShareModal/SharePdf/index.tsx
index 92bd68904cc..5516beb6609 100644
--- a/src/features/ShareModal/SharePdf/index.tsx
+++ b/src/features/ShareModal/SharePdf/index.tsx
@@ -75,7 +75,7 @@ const SharePdf = memo((props: { message?: UIChatMessage }) => {
const [systemRole] = useAgentStore((s) => [agentSelectors.currentAgentSystemRole(s)]);
const messages = useChatStore(chatSelectors.activeBaseChats, isEqual);
const topic = useChatStore(topicSelectors.currentActiveTopic, isEqual);
- const activeId = useChatStore((s) => s.activeId);
+ const activeId = useChatStore((s) => s.activeAgentId);
const topicId = useChatStore((s) => s.activeTopicId);
const title = topic?.title || t('shareModal.exportTitle');
diff --git a/src/hooks/useBidirectionalQuerySync.ts b/src/hooks/useBidirectionalQuerySync.ts
new file mode 100644
index 00000000000..19a0c9997a3
--- /dev/null
+++ b/src/hooks/useBidirectionalQuerySync.ts
@@ -0,0 +1,112 @@
+'use client';
+
+import { useEffect, useRef } from 'react';
+
+import { parseAsString, useQueryState } from '@/hooks/useQueryParam';
+
+interface UseBidirectionalQuerySyncOptions {
+ /**
+ * Default value when query is not present
+ */
+ defaultValue: string;
+}
+
+/**
+ * Hook for bidirectional sync between URL query parameter and store state.
+ * Prevents infinite loops by tracking the source of changes.
+ *
+ * @param queryKey - The URL query parameter key
+ * @param storeValue - Current value from the store
+ * @param setStoreValue - Function to update store value (setState or action)
+ * @param options - Configuration with required defaultValue
+ *
+ * @example
+ * ```tsx
+ * // In a component
+ * const activeTabId = useGroupProfileStore((s) => s.activeTabId);
+ *
+ * useBidirectionalQuerySync('tab', activeTabId, (value) => {
+ * useGroupProfileStore.setState({ activeTabId: value });
+ * }, { defaultValue: 'group' });
+ * ```
+ */
+export const useBidirectionalQuerySync = (
+ queryKey: string,
+ storeValue: string,
+ setStoreValue: (value: string) => void,
+ options: UseBidirectionalQuerySyncOptions,
+) => {
+ const { defaultValue } = options;
+
+ const [queryValue, setQueryValue] = useQueryState(
+ queryKey,
+ parseAsString.withDefault(defaultValue),
+ );
+
+ // Track if the change came from URL to prevent sync loops
+ const isUrlChangeRef = useRef(false);
+
+ // Sync URL → Store (when URL changes)
+ useEffect(() => {
+ if (queryValue !== storeValue) {
+ isUrlChangeRef.current = true;
+ setStoreValue(queryValue);
+ }
+ }, [queryValue, setStoreValue]);
+
+ // Sync Store → URL (when store changes, but not from URL)
+ useEffect(() => {
+ if (isUrlChangeRef.current) {
+ isUrlChangeRef.current = false;
+ return;
+ }
+ if (storeValue !== queryValue) {
+ setQueryValue(storeValue);
+ }
+ }, [storeValue, queryValue, setQueryValue]);
+};
+
+/**
+ * Hook for bidirectional sync with optional/undefined store values.
+ * Useful when the store value can be undefined (like activeTopicId).
+ *
+ * @example
+ * ```tsx
+ * const activeTopicId = useChatStore((s) => s.activeTopicId);
+ *
+ * useBidirectionalQuerySyncOptional('bt', activeTopicId, (value) => {
+ * useChatStore.setState({ activeTopicId: value });
+ * });
+ * ```
+ */
+export const useBidirectionalQuerySyncOptional = (
+ queryKey: string,
+ storeValue: string | undefined,
+ setStoreValue: (value: string | undefined) => void,
+) => {
+ const [queryValue, setQueryValue] = useQueryState(queryKey);
+
+ // Track if the change came from URL to prevent sync loops
+ const isUrlChangeRef = useRef(false);
+
+ // Sync URL → Store (when URL changes)
+ useEffect(() => {
+ const urlValue = queryValue ?? undefined;
+ if (urlValue !== storeValue) {
+ isUrlChangeRef.current = true;
+ setStoreValue(urlValue);
+ }
+ }, [queryValue, setStoreValue]);
+
+ // Sync Store → URL (when store changes, but not from URL)
+ useEffect(() => {
+ if (isUrlChangeRef.current) {
+ isUrlChangeRef.current = false;
+ return;
+ }
+ const urlValue = queryValue ?? undefined;
+ if (storeValue !== urlValue) {
+ setQueryValue(storeValue ?? null);
+ }
+ }, [storeValue, queryValue, setQueryValue]);
+};
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index 4ae6e746d16..456c6063ecf 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -87,11 +87,21 @@ export default {
'group.desc': 'Move a task forward with multiple Agents in one shared space.',
'group.memberTooltip': 'There are {{count}} members in the group',
'group.orchestratorThinking': 'Orchestrator is thinking...',
+ 'group.profile.contentPlaceholder':
+ 'Set the group objectives/work modes here. This information will be shared with all group members.',
+ 'group.profile.external': 'External',
+ 'group.profile.externalAgentWarning':
+ 'This is an external agent. Changes made here will directly modify the original agent configuration.',
+ 'group.profile.groupSettings': 'Group Settings',
+ 'group.profile.supervisor': 'Supervisor',
+ 'group.profile.supervisorPlaceholder':
+ 'The supervisor coordinates different agents. Setting supervisor information here enables more precise workflow coordination.',
'group.removeMember': 'Remove Member',
'group.title': 'Group',
'groupDescription': 'Group description',
'groupSidebar.agentProfile.chat': 'Chat',
'groupSidebar.agentProfile.model': 'Model',
+ 'groupSidebar.agentProfile.settings': 'Settings',
'groupSidebar.members.addMember': 'Add Member',
'groupSidebar.members.enableOrchestrator': 'Enable Orchestrator',
'groupSidebar.members.memberSettings': 'Member Settings',
diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.ts
index e0dd678ea43..24524da1fb8 100644
--- a/src/locales/default/plugin.ts
+++ b/src/locales/default/plugin.ts
@@ -5,6 +5,7 @@ export default {
'builtins.lobe-agent-builder.apiName.getConfig': 'Get config',
'builtins.lobe-agent-builder.apiName.getMeta': 'Get metadata',
'builtins.lobe-agent-builder.apiName.getPrompt': 'Get system prompt',
+ 'builtins.lobe-agent-builder.apiName.installPlugin': 'Install Skill',
'builtins.lobe-agent-builder.apiName.searchMarketTools': 'Search Skill market',
'builtins.lobe-agent-builder.apiName.searchOfficialTools': 'Search official Skills',
'builtins.lobe-agent-builder.apiName.setModel': 'Set model',
@@ -15,6 +16,12 @@ export default {
'builtins.lobe-agent-builder.apiName.updateConfig': 'Update config',
'builtins.lobe-agent-builder.apiName.updateMeta': 'Update metadata',
'builtins.lobe-agent-builder.apiName.updatePrompt': 'Update system prompt',
+ 'builtins.lobe-agent-builder.inspector.chars': ' chars',
+ 'builtins.lobe-agent-builder.inspector.disablePlugin': 'Disable',
+ 'builtins.lobe-agent-builder.inspector.enablePlugin': 'Enable',
+ 'builtins.lobe-agent-builder.inspector.modelsCount': '{{count}} models',
+ 'builtins.lobe-agent-builder.inspector.noResults': 'No results',
+ 'builtins.lobe-agent-builder.inspector.togglePlugin': 'Toggle',
'builtins.lobe-agent-builder.title': 'Agent Builder Expert',
'builtins.lobe-cloud-sandbox.apiName.editLocalFile': 'Edit file',
'builtins.lobe-cloud-sandbox.apiName.executeCode': 'Execute code',
@@ -31,13 +38,27 @@ export default {
'builtins.lobe-cloud-sandbox.apiName.searchLocalFiles': 'Search files',
'builtins.lobe-cloud-sandbox.apiName.writeLocalFile': 'Write file',
'builtins.lobe-cloud-sandbox.title': 'Cloud Sandbox',
+ 'builtins.lobe-group-agent-builder.apiName.createAgent': 'Create agent',
'builtins.lobe-group-agent-builder.apiName.getAvailableModels': 'Get available models',
'builtins.lobe-group-agent-builder.apiName.installPlugin': 'Install Skill',
'builtins.lobe-group-agent-builder.apiName.inviteAgent': 'Invite member',
'builtins.lobe-group-agent-builder.apiName.removeAgent': 'Remove member',
+ 'builtins.lobe-group-agent-builder.apiName.searchAgent': 'Search agents',
'builtins.lobe-group-agent-builder.apiName.searchMarketTools': 'Search Skill market',
+ 'builtins.lobe-group-agent-builder.apiName.batchCreateAgents': 'Batch create agents',
'builtins.lobe-group-agent-builder.apiName.updateAgentConfig': 'Update agent config',
- 'builtins.lobe-group-agent-builder.apiName.updatePrompt': 'Update system prompt',
+ 'builtins.lobe-group-agent-builder.apiName.updateAgentPrompt': 'Update agent prompt',
+ 'builtins.lobe-group-agent-builder.apiName.updateSupervisorPrompt': 'Update supervisor prompt',
+ 'builtins.lobe-group-agent-builder.apiName.updateGroup': 'Update group',
+ 'builtins.lobe-group-agent-builder.apiName.updateGroupPrompt': 'Update group prompt',
+ 'builtins.lobe-group-agent-builder.inspector.agents': 'agents',
+ 'builtins.lobe-group-agent-builder.inspector.avatar': 'Avatar',
+ 'builtins.lobe-group-agent-builder.inspector.backgroundColor': 'Background color',
+ 'builtins.lobe-group-agent-builder.inspector.description': 'Description',
+ 'builtins.lobe-group-agent-builder.inspector.noResults': 'No results',
+ 'builtins.lobe-group-agent-builder.inspector.openingMessage': 'Opening message',
+ 'builtins.lobe-group-agent-builder.inspector.openingQuestions': 'Opening questions',
+ 'builtins.lobe-group-agent-builder.inspector.title': 'Title',
'builtins.lobe-group-agent-builder.title': 'Group Builder Expert',
'builtins.lobe-group-management.apiName.broadcast': 'All speak',
'builtins.lobe-group-management.apiName.createAgent': 'Add group member',
diff --git a/src/server/routers/lambda/agent.ts b/src/server/routers/lambda/agent.ts
index a5dfc9e3a9e..07eccc7deac 100644
--- a/src/server/routers/lambda/agent.ts
+++ b/src/server/routers/lambda/agent.ts
@@ -3,6 +3,7 @@ import { type KnowledgeItem, KnowledgeType } from '@lobechat/types';
import { z } from 'zod';
import { AgentModel } from '@/database/models/agent';
+import { ChatGroupModel } from '@/database/models/chatGroup';
import { FileModel } from '@/database/models/file';
import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
import { SessionModel } from '@/database/models/session';
@@ -20,6 +21,7 @@ const agentProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
ctx: {
agentModel: new AgentModel(ctx.serverDB, ctx.userId),
agentService: new AgentService(ctx.serverDB, ctx.userId),
+ chatGroupModel: new ChatGroupModel(ctx.serverDB, ctx.userId),
fileModel: new FileModel(ctx.serverDB, ctx.userId),
knowledgeBaseModel: new KnowledgeBaseModel(ctx.serverDB, ctx.userId),
sessionModel: new SessionModel(ctx.serverDB, ctx.userId),
@@ -108,6 +110,28 @@ export const agentRouter = router({
);
}),
+ /**
+ * Create an agent without session.
+ * Used for Group Agent Builder to create agents for groups.
+ * Returns only the agent ID.
+ */
+ createAgentOnly: agentProcedure
+ .input(
+ z.object({
+ config: z.object({}).passthrough().optional(),
+ groupId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ // Create the agent entity only (no session)
+ const agent = await ctx.agentModel.create(input.config ?? {});
+
+ // Add the agent to the group
+ await ctx.chatGroupModel.addAgentToGroup(input.groupId, agent.id);
+
+ return { agentId: agent.id };
+ }),
+
deleteAgentFile: agentProcedure
.input(
z.object({
diff --git a/src/server/routers/lambda/agentGroup.ts b/src/server/routers/lambda/agentGroup.ts
index b7e232915bf..6ac828e2dc3 100644
--- a/src/server/routers/lambda/agentGroup.ts
+++ b/src/server/routers/lambda/agentGroup.ts
@@ -37,6 +37,45 @@ export const agentGroupRouter = router({
return ctx.chatGroupModel.addAgentsToGroup(input.groupId, input.agentIds);
}),
+ /**
+ * Batch create virtual agents and add them to an existing group.
+ * This is more efficient than calling createAgentOnly multiple times.
+ */
+ batchCreateAgentsInGroup: agentGroupProcedure
+ .input(
+ z.object({
+ agents: z.array(
+ insertAgentSchema
+ .omit({
+ chatConfig: true,
+ openingMessage: true,
+ openingQuestions: true,
+ tts: true,
+ userId: true,
+ })
+ .partial(),
+ ),
+ groupId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ // Batch create virtual agents
+ const agentConfigs = input.agents.map((agent) => ({
+ ...agent,
+ plugins: agent.plugins as string[] | undefined,
+ tags: agent.tags as string[] | undefined,
+ virtual: true,
+ }));
+
+ const createdAgents = await ctx.agentModel.batchCreate(agentConfigs);
+ const agentIds = createdAgents.map((agent) => agent.id);
+
+ // Add all agents to the group
+ await ctx.chatGroupModel.addAgentsToGroup(input.groupId, agentIds);
+
+ return { agentIds, agents: createdAgents };
+ }),
+
/**
* Check agents before removal to identify virtual agents that will be permanently deleted.
* This allows the frontend to show a confirmation dialog.
diff --git a/src/services/agent.ts b/src/services/agent.ts
index 70c331f8812..e78a5aa929f 100644
--- a/src/services/agent.ts
+++ b/src/services/agent.ts
@@ -51,6 +51,15 @@ export interface CreateAgentResult {
sessionId: string;
}
+export interface CreateAgentOnlyParams {
+ config?: PartialDeep<AgentItem>;
+ groupId: string;
+}
+
+export interface CreateAgentOnlyResult {
+ agentId: string;
+}
+
class AgentService {
/**
* Check if an agent with the given marketIdentifier already exists
@@ -80,6 +89,19 @@ class AgentService {
});
};
+ /**
+ * Create a virtual agent without session.
+ * Used for Group Agent Builder to create virtual agents for groups.
+ */
+ createAgentOnly = async (params: CreateAgentOnlyParams): Promise<CreateAgentOnlyResult> => {
+ const normalizedConfig = normalizeMarketAgentModel(params.config);
+
+ return lambdaClient.agent.createAgentOnly.mutate({
+ config: normalizedConfig as any,
+ groupId: params.groupId,
+ });
+ };
+
createAgentKnowledgeBase = async (
agentId: string,
knowledgeBaseId: string,
diff --git a/src/services/chatGroup/index.ts b/src/services/chatGroup/index.ts
index 53201cb94e8..f1f24d507c3 100644
--- a/src/services/chatGroup/index.ts
+++ b/src/services/chatGroup/index.ts
@@ -85,6 +85,20 @@ class ChatGroupService {
return lambdaClient.group.addAgentsToGroup.mutate({ agentIds, groupId });
};
+ /**
+ * Batch create virtual agents and add them to an existing group.
+ * This is more efficient than calling createAgentOnly multiple times.
+ */
+ batchCreateAgentsInGroup = (
+ groupId: string,
+ agents: GroupMemberConfig[],
+ ) => {
+ return lambdaClient.group.batchCreateAgentsInGroup.mutate({
+ agents: agents as Partial<AgentItem>[],
+ groupId,
+ });
+ };
+
removeAgentsFromGroup = (groupId: string, agentIds: string[]) => {
return lambdaClient.group.removeAgentsFromGroup.mutate({ agentIds, groupId });
};
diff --git a/src/store/agent/selectors/selectors.ts b/src/store/agent/selectors/selectors.ts
index fb96c0eaa95..ef92182eaec 100644
--- a/src/store/agent/selectors/selectors.ts
+++ b/src/store/agent/selectors/selectors.ts
@@ -260,6 +260,8 @@ const currentAgentLocalSystemConfig = (s: AgentStoreState): LocalSystemConfig |
const currentAgentWorkingDirectory = (s: AgentStoreState): string | undefined =>
currentAgentLocalSystemConfig(s)?.workingDirectory;
+const isCurrentAgentExternal = (s: AgentStoreState): boolean => !currentAgentData(s)?.virtual;
+
export const agentSelectors = {
currentAgentAvatar,
currentAgentBackgroundColor,
@@ -293,6 +295,7 @@ export const agentSelectors = {
inboxAgentModel,
isAgentConfigLoading,
isAgentModeEnabled,
+ isCurrentAgentExternal,
openingMessage,
openingQuestions,
};
diff --git a/src/store/agentGroup/initialState.ts b/src/store/agentGroup/initialState.ts
index a05b08e3893..deaf27f6585 100644
--- a/src/store/agentGroup/initialState.ts
+++ b/src/store/agentGroup/initialState.ts
@@ -1,13 +1,19 @@
import type { AgentGroupDetail } from '@lobechat/types';
+import type { ParsedQuery } from 'query-string';
import type { ChatGroupItem } from '@/database/schemas/chatGroup';
+export interface QueryRouter {
+ push: (url: string, options?: { query?: ParsedQuery }) => void;
+}
+
export interface ChatGroupState {
activeGroupId?: string;
activeThreadAgentId: string;
groupMap: Record<string, AgentGroupDetail>;
groups: ChatGroupItem[];
groupsInit: boolean;
+ router?: QueryRouter;
showGroupSetting: boolean;
/**
* Content being streamed for system prompt update (for GroupAgentBuilder)
diff --git a/src/store/agentGroup/selectors/byId.ts b/src/store/agentGroup/selectors/byId.ts
index 83df0d5e916..92e412710c2 100644
--- a/src/store/agentGroup/selectors/byId.ts
+++ b/src/store/agentGroup/selectors/byId.ts
@@ -19,6 +19,8 @@ const groupConfig = (groupId: string) => (s: ChatGroupStore) => {
const groupMeta = (groupId: string) => (s: ChatGroupStore) => {
const group = groupById(groupId)(s);
return merge(DEFAULT_CHAT_GROUP_META_CONFIG, {
+ avatar: group?.avatar || undefined,
+ backgroundColor: group?.backgroundColor || undefined,
description: group?.description || '',
title: group?.title || '',
});
@@ -26,7 +28,7 @@ const groupMeta = (groupId: string) => (s: ChatGroupStore) => {
const groupAgents =
(groupId: string) =>
- (s: ChatGroupStore): AgentItem[] => {
+ (s: ChatGroupStore): AgentGroupMember[] => {
const group = groupById(groupId)(s);
return group?.agents || [];
};
diff --git a/src/store/agentGroup/selectors/current.ts b/src/store/agentGroup/selectors/current.ts
index fe007d3a164..4eb16b652c2 100644
--- a/src/store/agentGroup/selectors/current.ts
+++ b/src/store/agentGroup/selectors/current.ts
@@ -3,7 +3,7 @@ import {
DEFAULT_CHAT_GROUP_CHAT_CONFIG,
DEFAULT_CHAT_GROUP_META_CONFIG,
} from '@lobechat/const';
-import type { AgentGroupDetail, AgentGroupMember, AgentItem } from '@lobechat/types';
+import type { AgentGroupDetail, AgentGroupMember } from '@lobechat/types';
import type { ChatGroupState } from '../initialState';
import type { ChatGroupStore } from '../store';
@@ -36,7 +36,7 @@ const currentGroupMeta = (s: ChatGroupStore) => {
return groupId ? agentGroupByIdSelectors.groupMeta(groupId)(s) : DEFAULT_CHAT_GROUP_META_CONFIG;
};
-const currentGroupAgents = (s: ChatGroupStore): AgentItem[] => {
+const currentGroupAgents = (s: ChatGroupStore): AgentGroupMember[] => {
const groupId = activeGroupId(s);
return groupId ? agentGroupByIdSelectors.groupAgents(groupId)(s) : [];
};
diff --git a/src/store/agentGroup/slices/lifecycle.ts b/src/store/agentGroup/slices/lifecycle.ts
index 60a6e0815fa..610d57fe23a 100644
--- a/src/store/agentGroup/slices/lifecycle.ts
+++ b/src/store/agentGroup/slices/lifecycle.ts
@@ -1,8 +1,10 @@
import type { NewChatGroup } from '@lobechat/types';
+import urlJoin from 'url-join';
import { type StateCreator } from 'zustand/vanilla';
import { chatGroupService } from '@/services/chatGroup';
import { type ChatGroupStore } from '@/store/agentGroup/store';
+import { useChatStore } from '@/store/chat';
import { getSessionStoreState } from '@/store/session';
export interface ChatGroupLifecycleAction {
@@ -11,6 +13,11 @@ export interface ChatGroupLifecycleAction {
agentIds?: string[],
silent?: boolean,
) => Promise<string>;
+ /**
+ * Switch to a new topic in the group
+ * Clears activeTopicId and navigates to group root
+ */
+ switchToNewTopic: () => void;
}
export const chatGroupLifecycleSlice: StateCreator<
@@ -48,4 +55,15 @@ export const chatGroupLifecycleSlice: StateCreator<
return group.id;
},
+
+ switchToNewTopic: () => {
+ const { activeGroupId, router } = get();
+ if (!activeGroupId || !router) return;
+
+ useChatStore.setState({ activeTopicId: undefined });
+
+ router.push(urlJoin('/group', activeGroupId), {
+ query: { bt: null, tab: null, thread: null, topic: null },
+ });
+ },
});
diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/fixtures/mockStore.ts b/src/store/chat/agents/__tests__/createAgentExecutors/fixtures/mockStore.ts
index 204478f259a..08463fce78c 100644
--- a/src/store/chat/agents/__tests__/createAgentExecutors/fixtures/mockStore.ts
+++ b/src/store/chat/agents/__tests__/createAgentExecutors/fixtures/mockStore.ts
@@ -15,7 +15,7 @@ export const createMockStore = (overrides: Partial<ChatStore> = {}): ChatStore =
const store = {
// Other store properties (add as needed)
- activeId: 'test-session',
+ activeAgentId: 'test-session',
activeTopicId: 'test-topic',
diff --git a/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.ts b/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.ts
index ddca713461b..cdcf3b5c6ce 100644
--- a/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.ts
+++ b/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.ts
@@ -556,7 +556,10 @@ describe('agentGroup actions', () => {
});
});
- expect(result.current.switchTopic).toHaveBeenCalledWith(TEST_IDS.TOPIC_ID, true);
+ expect(result.current.switchTopic).toHaveBeenCalledWith(TEST_IDS.TOPIC_ID, {
+ clearNewKey: true,
+ skipRefreshMessage: true,
+ });
});
it('should not switch topic when using existing topic', async () => {
diff --git a/src/store/chat/slices/aiAgent/actions/agentGroup.ts b/src/store/chat/slices/aiAgent/actions/agentGroup.ts
index fddd591155a..2e5b0c1c2bc 100644
--- a/src/store/chat/slices/aiAgent/actions/agentGroup.ts
+++ b/src/store/chat/slices/aiAgent/actions/agentGroup.ts
@@ -118,7 +118,7 @@ export const agentGroupSlice: StateCreator<
// 4. Switch to new topic if created
if (result.isCreateNewTopic && result.topicId) {
- await get().switchTopic(result.topicId, true);
+ await get().switchTopic(result.topicId, { clearNewKey: true, skipRefreshMessage: true });
}
// 5. Create execContext with updated topicId from server response
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts
index 3ae3b31e821..d97bb8ac375 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { aiChatService } from '@/services/aiChat';
import * as agentGroupStore from '@/store/agentGroup';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { getSessionStoreState } from '@/store/session';
import { useChatStore } from '../../../../store';
@@ -353,5 +354,69 @@ describe('ConversationLifecycle actions', () => {
);
});
});
+
+ describe('new topic creation cleanup', () => {
+ it('should clear _new key data when new topic is created', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const agentId = TEST_IDS.SESSION_ID;
+ const newTopicId = 'created-topic-id';
+
+ // Setup initial state: messages exist in the _new key (no topicId)
+ const newKey = messageMapKey({ agentId, topicId: null });
+ const existingMessages = [
+ createMockMessage({ id: 'old-msg-1', role: 'user' }),
+ createMockMessage({ id: 'old-msg-2', role: 'assistant' }),
+ ];
+
+ await act(async () => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: undefined,
+ messagesMap: {
+ [newKey]: existingMessages,
+ },
+ dbMessagesMap: {
+ [newKey]: existingMessages,
+ },
+ });
+ });
+
+ // Verify messages exist in _new key before sending
+ expect(useChatStore.getState().messagesMap[newKey]).toHaveLength(2);
+
+ // Mock server response with new topic creation
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
+ messages: [
+ createMockMessage({ id: 'new-user-msg', role: 'user', topicId: newTopicId }),
+ createMockMessage({ id: 'new-assistant-msg', role: 'assistant', topicId: newTopicId }),
+ ],
+ topics: { items: [{ id: newTopicId, title: 'New Topic' }], total: 1 },
+ topicId: newTopicId,
+ isCreateNewTopic: true,
+ assistantMessageId: 'new-assistant-msg',
+ userMessageId: 'new-user-msg',
+ } as any);
+
+ // Mock switchTopic to verify it's called correctly
+ const switchTopicSpy = vi.spyOn(result.current, 'switchTopic');
+
+ await act(async () => {
+ await result.current.sendMessage({
+ message: TEST_CONTENT.USER_MESSAGE,
+ context: { agentId, topicId: null, threadId: null },
+ });
+ });
+
+ // switchTopic should be called with the new topicId and clearNewKey option
+ expect(switchTopicSpy).toHaveBeenCalledWith(newTopicId, {
+ clearNewKey: true,
+ skipRefreshMessage: true,
+ });
+
+ // After new topic creation, the _new key should be cleared
+ const messagesInNewKey = useChatStore.getState().messagesMap[newKey];
+ expect(messagesInNewKey ?? []).toHaveLength(0);
+ });
+ });
});
});
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
index a429c668584..b01e67c416d 100644
--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
@@ -286,7 +286,8 @@ export const conversationLifecycle: StateCreator<
});
if (data.isCreateNewTopic && data.topicId) {
- await get().switchTopic(data.topicId, true);
+ // clearNewKey: true ensures the _new key data is cleared after topic creation
+ await get().switchTopic(data.topicId, { clearNewKey: true, skipRefreshMessage: true });
}
} catch (e) {
console.error(e);
diff --git a/src/store/chat/slices/builtinTool/actions/__tests__/search.test.ts b/src/store/chat/slices/builtinTool/actions/__tests__/search.test.ts
index 1ce73af7b91..20776fa997e 100644
--- a/src/store/chat/slices/builtinTool/actions/__tests__/search.test.ts
+++ b/src/store/chat/slices/builtinTool/actions/__tests__/search.test.ts
@@ -43,7 +43,7 @@ describe('search actions', () => {
invokeBuiltinTool: vi.fn(),
});
- // Default mock for dbMessageSelectors - returns undefined to use activeId/activeTopicId
+ // Default mock for dbMessageSelectors - returns undefined to use activeAgentId/activeTopicId
vi.spyOn(dbMessageSelectors, 'getDbMessageById').mockImplementation(() => () => undefined);
});
diff --git a/src/store/chat/slices/builtinTool/actions/agentBuilder.ts b/src/store/chat/slices/builtinTool/actions/agentBuilder.ts
deleted file mode 100644
index f1badac42ae..00000000000
--- a/src/store/chat/slices/builtinTool/actions/agentBuilder.ts
+++ /dev/null
@@ -1,192 +0,0 @@
-import type {
- GetAvailableModelsParams,
- InstallPluginParams,
- SearchMarketToolsParams,
- UpdateAgentConfigParams,
- UpdatePromptParams,
-} from '@lobechat/builtin-tool-agent-builder';
-import { AgentBuilderExecutionRuntime } from '@lobechat/builtin-tool-agent-builder/executionRuntime';
-import debug from 'debug';
-import { type StateCreator } from 'zustand/vanilla';
-
-import { getAgentStoreState } from '@/store/agent';
-import { type ChatStore } from '@/store/chat/store';
-
-const log = debug('lobe-store:builtin-tool:agent-builder');
-
-export interface AgentBuilderAction {
- getAvailableModels: (id: string, params: GetAvailableModelsParams) => Promise<boolean>;
- installPlugin: (id: string, params: InstallPluginParams) => Promise<boolean>;
- internal_triggerAgentBuilderToolCalling: (
- id: string,
- apiName: string,
- params: any,
- ) => Promise<boolean>;
- searchMarketTools: (id: string, params: SearchMarketToolsParams) => Promise<boolean>;
- updateConfig: (id: string, params: UpdateAgentConfigParams) => Promise<boolean>;
- updatePrompt: (id: string, params: UpdatePromptParams) => Promise<boolean>;
-}
-
-const runtime = new AgentBuilderExecutionRuntime();
-
-export const agentBuilderSlice: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- AgentBuilderAction
-> = (set, get) => ({
- // ==================== Read Operations ====================
-
- getAvailableModels: async (id, params) => {
- return get().internal_triggerAgentBuilderToolCalling(id, 'getAvailableModels', params);
- },
-
- installPlugin: async (id, params) => {
- return get().internal_triggerAgentBuilderToolCalling(id, 'installPlugin', params);
- },
-
- // ==================== Internal Helper ====================
- /**
- * Internal helper to execute agent builder tool calling operations
- * Handles operation tracking, error handling, and state updates
- */
- internal_triggerAgentBuilderToolCalling: async (id, apiName, params) => {
- // Get parent operationId from messageOperationMap (should be executeToolCall)
- const parentOperationId = get().messageOperationMap[id];
-
- // Create child operation for agent builder execution
- // Auto-associates message with this operation via messageId in context
- const { operationId, abortController } = get().startOperation({
- context: {
- messageId: id,
- },
- metadata: {
- apiName,
- params,
- startTime: Date.now(),
- },
- parentOperationId,
- type: 'builtinToolAgentBuilder',
- });
-
- log(
- '[%s] messageId=%s, parentOpId=%s, opId=%s, aborted=%s',
- apiName,
- id,
- parentOperationId,
- operationId,
- abortController.signal.aborted,
- );
-
- const context = { operationId };
-
- try {
- // Get target agent ID from AgentStore, not ChatStore
- // ChatStore's activeAgentId is for message scoping (might be AgentBuilder's own ID)
- // AgentStore's activeAgentId is the actual target agent being configured
- const agentId = getAgentStoreState().activeAgentId;
-
- if (!agentId) {
- throw new Error('No active agent found');
- }
-
- // Execute the runtime method
- let result;
- switch (apiName) {
- case 'updateAgentConfig':
- case 'updateConfig': {
- result = await runtime.updateAgentConfig(agentId, params as UpdateAgentConfigParams);
- break;
- }
- case 'getAvailableModels': {
- result = await runtime.getAvailableModels(params as GetAvailableModelsParams);
- break;
- }
- case 'searchMarketTools': {
- result = await runtime.searchMarketTools(params as SearchMarketToolsParams);
- break;
- }
- case 'installPlugin': {
- result = await runtime.installPlugin(agentId, params as InstallPluginParams);
- break;
- }
- case 'updatePrompt': {
- result = await runtime.updatePrompt(agentId, {
- streaming: true,
- ...params,
- } as UpdatePromptParams);
- break;
- }
- default: {
- throw new Error(`Unknown API name: ${apiName}`);
- }
- }
-
- const { content, success, error, state } = result;
-
- // Complete operation
- get().completeOperation(operationId);
-
- // Update message content
- await get().optimisticUpdateMessageContent(id, content, undefined, context);
-
- if (success) {
- // Update plugin state with the result
- await get().optimisticUpdatePluginState(id, state, context);
- } else {
- // Update plugin error
- await get().optimisticUpdatePluginError(id, error, context);
- }
-
- return true;
- } catch (error) {
- const err = error as Error;
-
- log('[%s] Error: messageId=%s, error=%s', apiName, id, err.message);
-
- // Check if it's an abort error
- if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {
- log('[%s] Request aborted: messageId=%s', apiName, id);
- // Fail operation for abort
- get().failOperation(operationId, {
- message: 'User cancelled the request',
- type: 'UserAborted',
- });
- // Don't update error message for user aborts
- return true;
- }
-
- // Fail operation for other errors
- get().failOperation(operationId, {
- message: err.message,
- type: 'PluginServerError',
- });
-
- // For other errors, update message
- await get().optimisticUpdateMessagePluginError(
- id,
- {
- body: error,
- message: err.message,
- type: 'PluginServerError',
- },
- context,
- );
-
- return true;
- }
- },
-
- searchMarketTools: async (id, params) => {
- return get().internal_triggerAgentBuilderToolCalling(id, 'searchMarketTools', params);
- },
-
- // ==================== Write Operations ====================
- updateConfig: async (id, params) => {
- return get().internal_triggerAgentBuilderToolCalling(id, 'updateConfig', params);
- },
-
- updatePrompt: async (id, params) => {
- return get().internal_triggerAgentBuilderToolCalling(id, 'updatePrompt', params);
- },
-});
diff --git a/src/store/chat/slices/builtinTool/actions/groupAgentBuilder.ts b/src/store/chat/slices/builtinTool/actions/groupAgentBuilder.ts
deleted file mode 100644
index 6a2388029b8..00000000000
--- a/src/store/chat/slices/builtinTool/actions/groupAgentBuilder.ts
+++ /dev/null
@@ -1,242 +0,0 @@
-import type {
- GetAvailableModelsParams,
- InstallPluginParams,
- SearchMarketToolsParams,
- UpdateAgentConfigParams,
-} from '@lobechat/builtin-tool-agent-builder';
-import { AgentBuilderExecutionRuntime } from '@lobechat/builtin-tool-agent-builder/executionRuntime';
-import type {
- InviteAgentParams,
- RemoveAgentParams,
- UpdateGroupConfigParams,
- UpdateGroupPromptParams,
-} from '@lobechat/builtin-tool-group-agent-builder';
-import { GroupAgentBuilderExecutionRuntime } from '@lobechat/builtin-tool-group-agent-builder/executionRuntime';
-import debug from 'debug';
-import { type StateCreator } from 'zustand/vanilla';
-
-import { getAgentStoreState } from '@/store/agent';
-import { getChatGroupStoreState } from '@/store/agentGroup';
-import { type ChatStore } from '@/store/chat/store';
-
-const log = debug('lobe-store:builtin-tool:group-agent-builder');
-
-export interface GroupAgentBuilderAction {
- // Inherited operations from AgentBuilder (operate on supervisor agent)
- groupAgentBuilder_getAvailableModels: (
- id: string,
- params: GetAvailableModelsParams,
- ) => Promise<boolean>;
- groupAgentBuilder_installPlugin: (id: string, params: InstallPluginParams) => Promise<boolean>;
- // Group-specific operations
- groupAgentBuilder_inviteAgent: (id: string, params: InviteAgentParams) => Promise<boolean>;
- groupAgentBuilder_removeAgent: (id: string, params: RemoveAgentParams) => Promise<boolean>;
- groupAgentBuilder_searchMarketTools: (
- id: string,
- params: SearchMarketToolsParams,
- ) => Promise<boolean>;
- groupAgentBuilder_updateConfig: (id: string, params: UpdateAgentConfigParams) => Promise<boolean>;
- groupAgentBuilder_updateGroupConfig: (
- id: string,
- params: UpdateGroupConfigParams,
- ) => Promise<boolean>;
- groupAgentBuilder_updatePrompt: (id: string, params: UpdateGroupPromptParams) => Promise<boolean>;
- internal_triggerGroupAgentBuilderToolCalling: (
- id: string,
- apiName: string,
- params: any,
- ) => Promise<boolean>;
-}
-
-const agentBuilderRuntime = new AgentBuilderExecutionRuntime();
-const groupAgentBuilderRuntime = new GroupAgentBuilderExecutionRuntime();
-
-export const groupAgentBuilderSlice: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- GroupAgentBuilderAction
-> = (set, get) => ({
- // ==================== Inherited Operations (from AgentBuilder) ====================
- groupAgentBuilder_getAvailableModels: async (id, params) => {
- return get().internal_triggerGroupAgentBuilderToolCalling(id, 'getAvailableModels', params);
- },
-
- groupAgentBuilder_installPlugin: async (id, params) => {
- return get().internal_triggerGroupAgentBuilderToolCalling(id, 'installPlugin', params);
- },
-
- // ==================== Group-specific Operations ====================
- groupAgentBuilder_inviteAgent: async (id, params) => {
- return get().internal_triggerGroupAgentBuilderToolCalling(id, 'inviteAgent', params);
- },
-
- groupAgentBuilder_removeAgent: async (id, params) => {
- return get().internal_triggerGroupAgentBuilderToolCalling(id, 'removeAgent', params);
- },
-
- groupAgentBuilder_searchMarketTools: async (id, params) => {
- return get().internal_triggerGroupAgentBuilderToolCalling(id, 'searchMarketTools', params);
- },
-
- groupAgentBuilder_updateConfig: async (id, params) => {
- return get().internal_triggerGroupAgentBuilderToolCalling(id, 'updateConfig', params);
- },
-
- groupAgentBuilder_updateGroupConfig: async (id, params) => {
- return get().internal_triggerGroupAgentBuilderToolCalling(id, 'updateGroupConfig', params);
- },
-
- groupAgentBuilder_updatePrompt: async (id, params) => {
- return get().internal_triggerGroupAgentBuilderToolCalling(id, 'updatePrompt', params);
- },
-
- // ==================== Internal Helper ====================
-
- internal_triggerGroupAgentBuilderToolCalling: async (id, apiName, params) => {
- // Get parent operationId from messageOperationMap (should be executeToolCall)
- const parentOperationId = get().messageOperationMap[id];
-
- // Create child operation for group agent builder execution
- const { operationId, abortController } = get().startOperation({
- context: {
- messageId: id,
- },
- metadata: {
- apiName,
- params,
- startTime: Date.now(),
- },
- parentOperationId,
- type: 'builtinToolGroupAgentBuilder',
- });
-
- log(
- '[%s] messageId=%s, parentOpId=%s, opId=%s, aborted=%s',
- apiName,
- id,
- parentOperationId,
- operationId,
- abortController.signal.aborted,
- );
-
- const context = { operationId };
-
- try {
- // Get the active group ID
- const groupId = getChatGroupStoreState().activeGroupId;
- if (!groupId) {
- throw new Error('No active group found');
- }
-
- // Get supervisor agent ID for config/model operations
- const agentId = getAgentStoreState().activeAgentId;
-
- // Execute the runtime method
- let result;
- switch (apiName) {
- // Group-specific operations
- case 'inviteAgent': {
- result = await groupAgentBuilderRuntime.inviteAgent(groupId, params as InviteAgentParams);
- break;
- }
- case 'removeAgent': {
- result = await groupAgentBuilderRuntime.removeAgent(groupId, params as RemoveAgentParams);
- break;
- }
- case 'updatePrompt': {
- result = await groupAgentBuilderRuntime.updatePrompt({
- streaming: true,
- ...params,
- } as UpdateGroupPromptParams);
- break;
- }
- case 'updateGroupConfig': {
- result = await groupAgentBuilderRuntime.updateGroupConfig(
- params as UpdateGroupConfigParams,
- );
- break;
- }
- // Inherited operations (use AgentBuilder runtime for supervisor agent)
- case 'updateAgentConfig':
- case 'updateConfig': {
- if (!agentId) throw new Error('No supervisor agent found');
- result = await agentBuilderRuntime.updateAgentConfig(
- agentId,
- params as UpdateAgentConfigParams,
- );
- break;
- }
- case 'getAvailableModels': {
- result = await agentBuilderRuntime.getAvailableModels(params as GetAvailableModelsParams);
- break;
- }
- case 'searchMarketTools': {
- result = await agentBuilderRuntime.searchMarketTools(params as SearchMarketToolsParams);
- break;
- }
- case 'installPlugin': {
- if (!agentId) throw new Error('No supervisor agent found');
- result = await agentBuilderRuntime.installPlugin(agentId, params as InstallPluginParams);
- break;
- }
- default: {
- throw new Error(`Unknown API name: ${apiName}`);
- }
- }
-
- const { content, success, error, state } = result;
-
- // Complete operation
- get().completeOperation(operationId);
-
- // Update message content
- await get().optimisticUpdateMessageContent(id, content, undefined, context);
-
- if (success) {
- // Update plugin state with the result
- await get().optimisticUpdatePluginState(id, state, context);
- } else {
- // Update plugin error
- await get().optimisticUpdatePluginError(id, error, context);
- }
-
- return true;
- } catch (error) {
- const err = error as Error;
-
- log('[%s] Error: messageId=%s, error=%s', apiName, id, err.message);
-
- // Check if it's an abort error
- if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {
- log('[%s] Request aborted: messageId=%s', apiName, id);
- // Fail operation for abort
- get().failOperation(operationId, {
- message: 'User cancelled the request',
- type: 'UserAborted',
- });
- // Don't update error message for user aborts
- return true;
- }
-
- // Fail operation for other errors
- get().failOperation(operationId, {
- message: err.message,
- type: 'PluginServerError',
- });
-
- // For other errors, update message
- await get().optimisticUpdateMessagePluginError(
- id,
- {
- body: error,
- message: err.message,
- type: 'PluginServerError',
- },
- context,
- );
-
- return true;
- }
- },
-});
diff --git a/src/store/chat/slices/builtinTool/actions/index.ts b/src/store/chat/slices/builtinTool/actions/index.ts
index a8df8714146..eac130c06ae 100644
--- a/src/store/chat/slices/builtinTool/actions/index.ts
+++ b/src/store/chat/slices/builtinTool/actions/index.ts
@@ -2,13 +2,10 @@ import { type StateCreator } from 'zustand/vanilla';
import { type ChatStore } from '@/store/chat/store';
-import { type AgentBuilderAction, agentBuilderSlice } from './agentBuilder';
-import { type GroupAgentBuilderAction, groupAgentBuilderSlice } from './groupAgentBuilder';
import { type ChatCodeInterpreterAction, codeInterpreterSlice } from './interpreter';
import { type SearchAction, searchSlice } from './search';
-export interface ChatBuiltinToolAction
- extends SearchAction, ChatCodeInterpreterAction, AgentBuilderAction, GroupAgentBuilderAction {}
+export interface ChatBuiltinToolAction extends SearchAction, ChatCodeInterpreterAction {}
export const chatToolSlice: StateCreator<
ChatStore,
@@ -18,6 +15,4 @@ export const chatToolSlice: StateCreator<
> = (...params) => ({
...searchSlice(...params),
...codeInterpreterSlice(...params),
- ...agentBuilderSlice(...params),
- ...groupAgentBuilderSlice(...params),
});
diff --git a/src/store/chat/slices/message/action.test.ts b/src/store/chat/slices/message/action.test.ts
index db30fb8cf7a..5214f46b93f 100644
--- a/src/store/chat/slices/message/action.test.ts
+++ b/src/store/chat/slices/message/action.test.ts
@@ -75,7 +75,7 @@ afterEach(() => {
describe('chatMessage actions', () => {
describe('addAIMessage', () => {
- it('should return early if activeId is undefined', async () => {
+ it('should return early if activeAgentId is undefined', async () => {
useChatStore.setState({ activeAgentId: undefined });
const { result } = renderHook(() => useChatStore());
const updateMessageInputSpy = vi.spyOn(result.current, 'updateMessageInput');
@@ -117,7 +117,7 @@ describe('chatMessage actions', () => {
});
describe('addUserMessage', () => {
- it('should return early if activeId is undefined', async () => {
+ it('should return early if activeAgentId is undefined', async () => {
useChatStore.setState({ activeAgentId: undefined });
const { result } = renderHook(() => useChatStore());
const updateMessageInputSpy = vi.spyOn(result.current, 'updateMessageInput');
@@ -739,7 +739,7 @@ describe('chatMessage actions', () => {
useChatStore.setState({ refreshMessages: realRefreshMessages });
const { result } = renderHook(() => useChatStore());
- const activeId = useChatStore.getState().activeAgentId;
+ const activeAgentId = useChatStore.getState().activeAgentId;
const activeTopicId = useChatStore.getState().activeTopicId;
// 在这里,我们不需要再次模拟 mutate,因为它已经在顶部被模拟了
@@ -750,13 +750,13 @@ describe('chatMessage actions', () => {
// 确保 mutate 调用了正确的参数(session 和 group 两次)
expect(mutate).toHaveBeenCalledWith([
'SWR_USE_FETCH_MESSAGES',
- activeId,
+ activeAgentId,
activeTopicId,
'session',
]);
expect(mutate).toHaveBeenCalledWith([
'SWR_USE_FETCH_MESSAGES',
- activeId,
+ activeAgentId,
activeTopicId,
'group',
]);
diff --git a/src/store/chat/slices/message/actions/publicApi.ts b/src/store/chat/slices/message/actions/publicApi.ts
index 99b087ea3de..b5ed2adab33 100644
--- a/src/store/chat/slices/message/actions/publicApi.ts
+++ b/src/store/chat/slices/message/actions/publicApi.ts
@@ -235,16 +235,16 @@ export const messagePublicApi: StateCreator<
},
clearMessage: async () => {
- const { activeId, activeTopicId, activeGroupId, refreshTopic, switchTopic } = get();
+ const { activeAgentId, activeTopicId, activeGroupId, refreshTopic, switchTopic } = get();
// For group sessions, we need to clear group messages using groupId
- // For regular sessions, we clear session messages using sessionId
+ // For regular sessions, we clear session messages using agentId
if (activeGroupId) {
// For group chat, activeGroupId is the groupId
await messageService.removeMessagesByGroup(activeGroupId, activeTopicId);
} else {
- // For regular session, activeId is the sessionId
- await messageService.removeMessagesByAssistant(activeId, activeTopicId);
+ // For regular session, activeAgentId is the agentId
+ await messageService.removeMessagesByAssistant(activeAgentId, activeTopicId);
}
if (activeTopicId) {
@@ -256,7 +256,7 @@ export const messagePublicApi: StateCreator<
get().replaceMessages([]);
// after remove topic , go back to default topic
- switchTopic();
+ switchTopic(null);
},
clearAllMessages: async () => {
diff --git a/src/store/chat/slices/message/initialState.ts b/src/store/chat/slices/message/initialState.ts
index b510089a4d8..202098c97da 100644
--- a/src/store/chat/slices/message/initialState.ts
+++ b/src/store/chat/slices/message/initialState.ts
@@ -4,10 +4,6 @@ import { type ChatGroupAgentItem } from '@/database/schemas/chatGroup';
export interface ChatMessageState {
activeAgentId: string;
- /**
- * @deprecated
- */
- activeId: string;
/**
* Raw messages from database (flat structure)
*/
@@ -37,7 +33,6 @@ export interface ChatMessageState {
export const initialMessageState: ChatMessageState = {
activeAgentId: '',
- activeId: 'inbox',
dbMessagesMap: {},
groupAgentMaps: {},
isCreatingMessage: false,
diff --git a/src/store/chat/slices/message/selectors/displayMessage.test.ts b/src/store/chat/slices/message/selectors/displayMessage.test.ts
index e773447c775..f163caafa26 100644
--- a/src/store/chat/slices/message/selectors/displayMessage.test.ts
+++ b/src/store/chat/slices/message/selectors/displayMessage.test.ts
@@ -288,7 +288,7 @@ describe('displayMessageSelectors', () => {
});
describe('currentDisplayChatKey', () => {
- it('should generate correct key with activeId only', () => {
+ it('should generate correct key with activeAgentId only', () => {
const state: Partial<ChatStore> = {
activeAgentId: 'testId',
activeTopicId: undefined,
@@ -297,7 +297,7 @@ describe('displayMessageSelectors', () => {
expect(result).toBe(messageMapKey({ agentId: 'testId', topicId: undefined }));
});
- it('should generate correct key with both activeId and activeTopicId', () => {
+ it('should generate correct key with both activeAgentId and activeTopicId', () => {
const state: Partial<ChatStore> = {
activeAgentId: 'testId',
activeTopicId: 'topicId',
@@ -306,7 +306,7 @@ describe('displayMessageSelectors', () => {
expect(result).toBe(messageMapKey({ agentId: 'testId', topicId: 'topicId' }));
});
- it('should generate key with undefined activeId', () => {
+ it('should generate key with undefined activeAgentId', () => {
const state: Partial<ChatStore> = {
activeAgentId: undefined,
activeTopicId: 'topicId',
@@ -315,7 +315,7 @@ describe('displayMessageSelectors', () => {
expect(result).toBe(messageMapKey({ agentId: undefined as any, topicId: 'topicId' }));
});
- it('should generate key with empty string activeId', () => {
+ it('should generate key with empty string activeAgentId', () => {
const state: Partial<ChatStore> = {
activeAgentId: '',
activeTopicId: undefined,
diff --git a/src/store/chat/slices/plugin/action.test.ts b/src/store/chat/slices/plugin/action.test.ts
index 2cc5fb8dc3d..4f9bc2d03d5 100644
--- a/src/store/chat/slices/plugin/action.test.ts
+++ b/src/store/chat/slices/plugin/action.test.ts
@@ -381,18 +381,27 @@ describe('ChatPluginAction', () => {
});
describe('invokeBuiltinTool', () => {
- it('should invoke the builtin tool action with parsed arguments', async () => {
+ it('should invoke Tool Store executor with parsed arguments', async () => {
const payload = {
+ identifier: 'test-tool',
apiName: 'mockBuiltinAction',
arguments: JSON.stringify({ input: 'test', value: 123 }),
} as ChatToolPayload;
const messageId = 'message-id';
- const mockActionFn = vi.fn().mockResolvedValue(undefined);
+ const mockInvokeBuiltinTool = vi.fn().mockResolvedValue({
+ content: 'result',
+ success: true,
+ });
- useChatStore.setState({
- mockBuiltinAction: mockActionFn,
- } as any);
+ // Mock hasExecutor to return true
+ const hasExecutorModule = await import('@/store/tool/slices/builtin/executors');
+ vi.spyOn(hasExecutorModule, 'hasExecutor').mockReturnValue(true);
+
+ // Mock Tool Store's invokeBuiltinTool
+ vi.spyOn(useToolStore.getState(), 'invokeBuiltinTool').mockImplementation(
+ mockInvokeBuiltinTool,
+ );
const { result } = renderHook(() => useChatStore());
@@ -400,52 +409,70 @@ describe('ChatPluginAction', () => {
await result.current.invokeBuiltinTool(messageId, payload);
});
- // Verify that the builtin action was called with correct arguments
- expect(mockActionFn).toHaveBeenCalledWith(messageId, { input: 'test', value: 123 });
+ // Verify that Tool Store's invokeBuiltinTool was called with correct arguments
+ expect(mockInvokeBuiltinTool).toHaveBeenCalledWith(
+ 'test-tool',
+ 'mockBuiltinAction',
+ { input: 'test', value: 123 },
+ expect.objectContaining({
+ messageId,
+ }),
+ );
});
- it('should not invoke action if apiName does not exist in store', async () => {
+ it('should not throw error if executor does not exist', async () => {
const payload = {
+ identifier: 'non-existent-tool',
apiName: 'nonExistentAction',
arguments: JSON.stringify({ key: 'value' }),
} as ChatToolPayload;
const messageId = 'message-id';
+ // Mock hasExecutor to return false
+ const hasExecutorModule = await import('@/store/tool/slices/builtin/executors');
+ vi.spyOn(hasExecutorModule, 'hasExecutor').mockReturnValue(false);
+
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
const { result } = renderHook(() => useChatStore());
await act(async () => {
await result.current.invokeBuiltinTool(messageId, payload);
});
- // Should not throw error, just return early
+ // Should log error but not throw
+ expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining('No executor found'));
+
+ consoleErrorSpy.mockRestore();
});
- it('should not invoke action if arguments cannot be parsed', async () => {
+ it('should return error result if arguments cannot be parsed', async () => {
const payload = {
+ identifier: 'test-tool',
apiName: 'mockBuiltinAction',
arguments: 'invalid json',
} as ChatToolPayload;
const messageId = 'message-id';
- const mockActionFn = vi.fn().mockResolvedValue(undefined);
-
- useChatStore.setState({
- mockBuiltinAction: mockActionFn,
- } as any);
const { result } = renderHook(() => useChatStore());
+ let returnValue: any;
await act(async () => {
- await result.current.invokeBuiltinTool(messageId, payload);
+ returnValue = await result.current.invokeBuiltinTool(messageId, payload);
});
- // Should not call the action if arguments can't be parsed
- expect(mockActionFn).not.toHaveBeenCalled();
+ // Should return error result for invalid JSON
+ expect(returnValue).toEqual({ error: 'Invalid arguments', success: false });
});
describe('registerAfterCompletion with Tool Store executor', () => {
it('should create registerAfterCompletion when root execAgentRuntime operation exists', async () => {
+ // Mock hasExecutor to return true
+ const hasExecutorModule = await import('@/store/tool/slices/builtin/executors');
+ vi.spyOn(hasExecutorModule, 'hasExecutor').mockReturnValue(true);
+
// Setup: Create operation hierarchy
// execAgentRuntime -> toolCalling -> executeToolCall
const { result } = renderHook(() => useChatStore());
@@ -527,6 +554,10 @@ describe('ChatPluginAction', () => {
});
it('should not pass registerAfterCompletion when no root operation exists', async () => {
+ // Mock hasExecutor to return true
+ const hasExecutorModule = await import('@/store/tool/slices/builtin/executors');
+ vi.spyOn(hasExecutorModule, 'hasExecutor').mockReturnValue(true);
+
const { result } = renderHook(() => useChatStore());
const messageId = 'tool-message-id';
@@ -558,6 +589,10 @@ describe('ChatPluginAction', () => {
});
it('should find root operation through multiple levels of hierarchy', async () => {
+ // Mock hasExecutor to return true
+ const hasExecutorModule = await import('@/store/tool/slices/builtin/executors');
+ vi.spyOn(hasExecutorModule, 'hasExecutor').mockReturnValue(true);
+
const { result } = renderHook(() => useChatStore());
let execAgentRuntimeOpId: string;
@@ -1147,7 +1182,7 @@ describe('ChatPluginAction', () => {
});
});
- it('should fallback to activeId/activeTopicId when context not provided', async () => {
+ it('should fallback to activeAgentId/activeTopicId when context not provided', async () => {
const { result } = renderHook(() => useChatStore());
const messageId = 'message-id';
const pluginState = { key: 'value' };
diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.ts
index 2e84b5d5224..222175172b6 100644
--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts
+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts
@@ -1,6 +1,5 @@
/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
import { CloudSandboxIdentifier, type ExportFileState } from '@lobechat/builtin-tool-cloud-sandbox';
-import { GroupAgentBuilderIdentifier } from '@lobechat/builtin-tool-group-agent-builder';
import { type ChatToolPayload, type RuntimeStepContext } from '@lobechat/types';
import { PluginErrorType } from '@lobehub/chat-plugin-sdk';
import debug from 'debug';
@@ -125,9 +124,17 @@ export const pluginTypes: StateCreator<
// Get agent ID, group ID, and topic ID from operation context
const agentId = operation?.context?.agentId;
- const groupId = operation?.context?.groupId;
+ let groupId = operation?.context?.groupId;
const topicId = operation?.context?.topicId;
+ // For group-agent-builder tools, inject activeGroupId from store if not in context
+ // This is needed because AgentBuilderProvider uses a separate scope for messages
+ // but still needs groupId for tool execution
+ if (!groupId && payload.identifier === 'lobe-group-agent-builder') {
+ const { getChatGroupStoreState } = await import('@/store/agentGroup');
+ groupId = getChatGroupStoreState().activeGroupId;
+ }
+
// Get group orchestration callbacks if available (for group management tools)
const groupOrchestration = get().getGroupOrchestrationCallbacks?.();
@@ -209,25 +216,12 @@ export const pluginTypes: StateCreator<
return result;
}
- // Route GroupAgentBuilder to its dedicated action
- if (payload.identifier === GroupAgentBuilderIdentifier) {
- log('[invokeBuiltinTool] Routing to GroupAgentBuilder: %s', payload.apiName);
- return await get().internal_triggerGroupAgentBuilderToolCalling(id, payload.apiName, params);
- }
-
- // run tool api call (fallback for AgentBuilder and other legacy tools)
- // @ts-ignore
- const { [payload.apiName]: action } = get();
- if (!action) {
- console.error(`[invokeBuiltinTool] plugin Action not found: ${payload.apiName}`);
- return;
- }
-
- const content = safeParseJSON(payload.arguments);
-
- if (!content) return;
-
- return await action(id, content);
+ // All builtin tools should be handled by the executor registry above
+ // If we reach here, it means the tool is not registered
+ console.error(
+ `[invokeBuiltinTool] No executor found for: ${payload.identifier}/${payload.apiName}`,
+ );
+ return;
},
invokeCloudCodeInterpreterTool: async (id, payload) => {
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.ts
index d5ee9c318aa..2a7b037aa7a 100644
--- a/src/store/chat/slices/topic/action.test.ts
+++ b/src/store/chat/slices/topic/action.test.ts
@@ -346,22 +346,6 @@ describe('topic action', () => {
expect(refreshMessagesSpy).toHaveBeenCalled();
});
- it('should support boolean as second parameter for backward compatibility', async () => {
- const topicId = 'topic-id';
- const { result } = renderHook(() => useChatStore());
-
- const refreshMessagesSpy = vi.spyOn(result.current, 'refreshMessages');
-
- // Call with boolean (old API)
- await act(async () => {
- await result.current.switchTopic(topicId, true);
- });
-
- expect(useChatStore.getState().activeTopicId).toBe(topicId);
- // Should not call refreshMessages when skipRefreshMessage is true
- expect(refreshMessagesSpy).not.toHaveBeenCalled();
- });
-
it('should support options object as second parameter', async () => {
const topicId = 'topic-id';
const { result } = renderHook(() => useChatStore());
@@ -377,7 +361,7 @@ describe('topic action', () => {
expect(refreshMessagesSpy).not.toHaveBeenCalled();
});
- it('should clear new key data when switching to new state (main scope)', async () => {
+ it('should clear new key data when switching to null (main scope)', async () => {
const { result } = renderHook(() => useChatStore());
const activeAgentId = 'test-agent-id';
const newKey = messageMapKey({ agentId: activeAgentId, topicId: null });
@@ -398,9 +382,9 @@ describe('topic action', () => {
const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');
- // Switch to new state (id = undefined)
+ // Switch to new state (id = null)
await act(async () => {
- await result.current.switchTopic(undefined, { skipRefreshMessage: true });
+ await result.current.switchTopic(null, { skipRefreshMessage: true });
});
// Verify replaceMessages was called to clear the new key
@@ -418,7 +402,7 @@ describe('topic action', () => {
expect(useChatStore.getState().activeTopicId).toBeNull();
});
- it('should clear new key data when switching to new state (group scope)', async () => {
+ it('should clear new key data when switching to null (group scope)', async () => {
const { result } = renderHook(() => useChatStore());
const activeAgentId = 'test-agent-id';
const activeGroupId = 'test-group-id';
@@ -434,9 +418,9 @@ describe('topic action', () => {
const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');
- // Switch to new state
+ // Switch to new state with null
await act(async () => {
- await result.current.switchTopic(undefined, { skipRefreshMessage: true });
+ await result.current.switchTopic(null, { skipRefreshMessage: true });
});
// Verify replaceMessages was called with group scope
@@ -464,9 +448,9 @@ describe('topic action', () => {
const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');
- // Switch to new state with explicit scope
+ // Switch to null with explicit scope
await act(async () => {
- await result.current.switchTopic(undefined, { skipRefreshMessage: true, scope: 'group' });
+ await result.current.switchTopic(null, { skipRefreshMessage: true, scope: 'group' });
});
// Verify replaceMessages was called with explicit scope
@@ -478,6 +462,28 @@ describe('topic action', () => {
});
});
+ it('should NOT clear new key data when switching with undefined (backward compatibility)', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const activeAgentId = 'test-agent-id';
+
+ await act(async () => {
+ useChatStore.setState({
+ activeAgentId,
+ activeTopicId: 'existing-topic',
+ });
+ });
+
+ const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');
+
+ // Switch with undefined (should NOT clear because id !== null)
+ await act(async () => {
+ await result.current.switchTopic(undefined, { skipRefreshMessage: true });
+ });
+
+ // replaceMessages should NOT be called when switching with undefined
+ expect(replaceMessagesSpy).not.toHaveBeenCalled();
+ });
+
it('should not clear new key data when switching to an existing topic', async () => {
const { result } = renderHook(() => useChatStore());
const activeAgentId = 'test-agent-id';
@@ -499,6 +505,50 @@ describe('topic action', () => {
// replaceMessages should not be called when switching to existing topic
expect(replaceMessagesSpy).not.toHaveBeenCalled();
});
+
+ it('should clear new key data when clearNewKey option is true (even with existing topic)', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const activeAgentId = 'test-agent-id';
+ const newKey = messageMapKey({ agentId: activeAgentId, topicId: null });
+
+ // Setup initial state with some messages in the new key
+ await act(async () => {
+ useChatStore.setState({
+ activeAgentId,
+ activeTopicId: undefined,
+ dbMessagesMap: {
+ [newKey]: [{ id: 'msg-1' }, { id: 'msg-2' }] as any,
+ },
+ messagesMap: {
+ [newKey]: [{ id: 'msg-1' }, { id: 'msg-2' }] as any,
+ },
+ });
+ });
+
+ const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');
+
+ // Switch to an existing topic with clearNewKey option
+ await act(async () => {
+ await result.current.switchTopic('new-created-topic-id', {
+ clearNewKey: true,
+ skipRefreshMessage: true,
+ });
+ });
+
+ // replaceMessages should be called to clear the new key
+ expect(replaceMessagesSpy).toHaveBeenCalledWith([], {
+ context: {
+ agentId: activeAgentId,
+ groupId: undefined,
+ scope: 'main',
+ topicId: null,
+ },
+ action: expect.any(String),
+ });
+
+ // Verify activeTopicId is set to the new topic
+ expect(useChatStore.getState().activeTopicId).toBe('new-created-topic-id');
+ });
});
describe('removeSessionTopics', () => {
it('should remove all topics from the current session and refresh the topic list', async () => {
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 960ecaa0451..f3ed80ac63c 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -48,6 +48,12 @@ type CronTopicsGroupWithJobInfo = {
* Options for switchTopic action
*/
export interface SwitchTopicOptions {
+ /**
+ * Clear the _new key data even when switching to an existing topic
+ * This is useful when creating a new topic, where the _new key data should be cleared
+ * @default false
+ */
+ clearNewKey?: boolean;
/**
* Explicit scope for clearing new key data
* If not provided, will be inferred from store state (activeGroupId)
@@ -81,10 +87,10 @@ export interface ChatTopicAction {
summaryTopicTitle: (topicId: string, messages: UIChatMessage[]) => Promise<void>;
/**
* Switch to a topic or create new topic state
- * @param id - Topic ID to switch to, or undefined/null to switch to "new" state
- * @param options - Options object or boolean for backward compatibility (skipRefreshMessage)
+ * @param id - Topic ID to switch to, or null to switch to "new" state (clears _new key data)
+ * @param options - Options object for configuring the switch behavior
*/
- switchTopic: (id?: string, options?: boolean | SwitchTopicOptions) => Promise<void>;
+ switchTopic: (id?: string | null, options?: SwitchTopicOptions) => Promise<void>;
/**
* Update topic metadata
* @param id - Topic ID to update
@@ -151,7 +157,7 @@ export const chatTopic: StateCreator<
const { switchTopic, saveToTopic, refreshMessages, activeTopicId } = get();
const hasTopic = !!activeTopicId;
- if (hasTopic) switchTopic();
+ if (hasTopic) switchTopic(null);
else {
await saveToTopic();
refreshMessages();
@@ -521,15 +527,17 @@ export const chatTopic: StateCreator<
),
switchTopic: async (id, options) => {
- // Backward compatibility: support both boolean and options object
- const opts: SwitchTopicOptions =
- typeof options === 'boolean' ? { skipRefreshMessage: options } : (options ?? {});
+ const opts = options ?? {};
const { activeAgentId, activeGroupId } = get();
- // When switching to "new" state (id is undefined/null), clear the new key data
+ // Clear the _new key data in the following cases:
+ // 1. When id is explicitly null (switching to empty topic state)
+ // 2. When clearNewKey option is explicitly true
// This prevents stale data from previous conversations showing up
- if (!id && activeAgentId) {
+ const shouldClearNewKey = id === null || opts.clearNewKey;
+
+ if (shouldClearNewKey && activeAgentId) {
// Determine scope: use explicit scope from options, or infer from activeGroupId
const scope = opts.scope ?? (activeGroupId ? 'group' : 'main');
@@ -562,7 +570,7 @@ export const chatTopic: StateCreator<
await refreshTopic();
// switch to default topic
- switchTopic();
+ switchTopic(null);
},
removeGroupTopics: async (groupId: string) => {
@@ -580,7 +588,7 @@ export const chatTopic: StateCreator<
await refreshTopic();
// switch to default topic
- switchTopic();
+ switchTopic(null);
},
removeAllTopics: async () => {
const { refreshTopic } = get();
@@ -598,7 +606,7 @@ export const chatTopic: StateCreator<
await refreshTopic();
// switch back to default topic
- if (activeTopicId === id) switchTopic();
+ if (activeTopicId === id) switchTopic(null);
},
removeUnstarredTopic: async () => {
const { refreshTopic, switchTopic } = get();
@@ -608,7 +616,7 @@ export const chatTopic: StateCreator<
await refreshTopic();
// 切换到默认 topic
- switchTopic();
+ switchTopic(null);
},
// Internal process method of the topics
diff --git a/src/store/chat/slices/topic/selectors.test.ts b/src/store/chat/slices/topic/selectors.test.ts
index 35ba2027a11..0dd4ddb0ab4 100644
--- a/src/store/chat/slices/topic/selectors.test.ts
+++ b/src/store/chat/slices/topic/selectors.test.ts
@@ -35,7 +35,7 @@ const topicDataMap = createTopicDataMap('test');
describe('topicSelectors', () => {
describe('currentTopics', () => {
- it('should return undefined if there are no topics with activeId', () => {
+ it('should return undefined if there are no topics with activeAgentId', () => {
const topics = topicSelectors.currentTopics(initialStore);
expect(topics).toBeUndefined();
});
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index b738d855c33..9d425556c3a 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -75,6 +75,10 @@ export enum ProfileTabs {
}
export interface SystemStatus {
+ /**
+ * Agent Builder panel width
+ */
+ agentBuilderPanelWidth?: number;
/**
* number of agents (defaultList) to display
*/
@@ -89,6 +93,10 @@ export interface SystemStatus {
expandTopicGroupKeys?: string[];
fileManagerViewMode?: 'list' | 'masonry';
filePanelWidth: number;
+ /**
+ * Group Agent Builder panel width
+ */
+ groupAgentBuilderPanelWidth?: number;
hideGemini2_5FlashImagePreviewChineseWarning?: boolean;
hidePWAInstaller?: boolean;
hideThreadLimitAlert?: boolean;
@@ -180,6 +188,7 @@ export interface GlobalState {
}
export const INITIAL_STATUS = {
+ agentBuilderPanelWidth: 360,
agentPageSize: 10,
chatInputHeight: 64,
disabledModelProvidersSortType: 'default',
@@ -188,6 +197,7 @@ export const INITIAL_STATUS = {
expandSessionGroupKeys: [SessionDefaultGroup.Pinned, SessionDefaultGroup.Default],
fileManagerViewMode: 'list' as const,
filePanelWidth: 320,
+ groupAgentBuilderPanelWidth: 360,
hideGemini2_5FlashImagePreviewChineseWarning: false,
hidePWAInstaller: false,
hideThreadLimitAlert: false,
diff --git a/src/store/global/selectors/systemStatus.ts b/src/store/global/selectors/systemStatus.ts
index 7258a3b3714..7e07348cdab 100644
--- a/src/store/global/selectors/systemStatus.ts
+++ b/src/store/global/selectors/systemStatus.ts
@@ -2,6 +2,8 @@ import { type GlobalState, INITIAL_STATUS } from '../initialState';
export const systemStatus = (s: GlobalState) => s.status;
+const agentBuilderPanelWidth = (s: GlobalState) => s.status.agentBuilderPanelWidth || 360;
+
const sessionGroupKeys = (s: GlobalState): string[] =>
s.status.expandSessionGroupKeys || INITIAL_STATUS.expandSessionGroupKeys;
@@ -37,6 +39,7 @@ const leftPanelWidth = (s: GlobalState): number => {
};
const portalWidth = (s: GlobalState) => s.status.portalWidth || 400;
const filePanelWidth = (s: GlobalState) => s.status.filePanelWidth;
+const groupAgentBuilderPanelWidth = (s: GlobalState) => s.status.groupAgentBuilderPanelWidth || 360;
const imagePanelWidth = (s: GlobalState) => s.status.imagePanelWidth;
const imageTopicPanelWidth = (s: GlobalState) => s.status.imageTopicPanelWidth;
const wideScreen = (s: GlobalState) => !s.status.noWideScreen;
@@ -58,6 +61,7 @@ const tokenDisplayFormatShort = (s: GlobalState) =>
s.status.tokenDisplayFormatShort !== undefined ? s.status.tokenDisplayFormatShort : true;
export const systemStatusSelectors = {
+ agentBuilderPanelWidth,
agentPageSize,
chatInputHeight,
disabledModelProvidersSortType,
@@ -65,6 +69,7 @@ export const systemStatusSelectors = {
expandInputActionbar,
filePanelWidth,
getAgentSystemRoleExpanded,
+ groupAgentBuilderPanelWidth,
hidePWAInstaller,
imagePanelWidth,
imageTopicPanelWidth,
diff --git a/src/store/groupProfile/action.ts b/src/store/groupProfile/action.ts
new file mode 100644
index 00000000000..f429c222fcc
--- /dev/null
+++ b/src/store/groupProfile/action.ts
@@ -0,0 +1,168 @@
+import { debounce } from 'es-toolkit/compat';
+import { type StateCreator } from 'zustand';
+
+import { EDITOR_DEBOUNCE_TIME, EDITOR_MAX_WAIT } from '@/const/index';
+
+import { type SaveState, type SaveStatus, type State, initialState } from './initialState';
+
+type SaveContentPayload = {
+ content: string;
+ editorData: Record<string, any>;
+};
+
+export interface Action {
+ appendStreamingContent: (chunk: string) => void;
+ finishStreaming: (saveCallback: (payload: SaveContentPayload) => Promise<void>) => Promise<void>;
+ flushSave: () => void;
+ handleContentChange: (saveCallback: (payload: SaveContentPayload) => Promise<void>) => void;
+ setActiveTabId: (tabId: string) => void;
+ setChatPanelExpanded: (expanded: boolean | ((prev: boolean) => boolean)) => void;
+ updateSaveStatus: (tabId: string, status: SaveStatus) => void;
+}
+
+export type Store = State & Action;
+
+// Store the latest saveCallback and tabId references to avoid stale closures
+let saveCallbackRef: ((payload: SaveContentPayload) => Promise<void>) | null = null;
+let currentTabIdRef: string | null = null;
+
+const DEFAULT_SAVE_STATE: SaveState = { lastUpdatedTime: null, saveStatus: 'idle' };
+
+export const store: StateCreator<Store> = (set, get) => {
+ const updateSaveStatusInternal = (tabId: string, status: SaveStatus) => {
+ const { saveStateMap } = get();
+ const currentState = saveStateMap[tabId] || DEFAULT_SAVE_STATE;
+ set({
+ saveStateMap: {
+ ...saveStateMap,
+ [tabId]: {
+ ...currentState,
+ lastUpdatedTime: status === 'saved' ? new Date() : currentState.lastUpdatedTime,
+ saveStatus: status,
+ },
+ },
+ });
+ };
+
+ // Create debounced save that uses the latest callback reference
+ const debouncedSave = debounce(
+ async (payload: SaveContentPayload) => {
+ const tabId = currentTabIdRef;
+ if (!tabId) return;
+
+ try {
+ if (saveCallbackRef) {
+ await saveCallbackRef(payload);
+ updateSaveStatusInternal(tabId, 'saved');
+ }
+ } catch (error) {
+ console.error('[ProfileEditor] Failed to save:', error);
+ updateSaveStatusInternal(tabId, 'idle');
+ }
+ },
+ EDITOR_DEBOUNCE_TIME,
+ { leading: false, maxWait: EDITOR_MAX_WAIT, trailing: true },
+ );
+
+ return {
+ ...initialState,
+
+ appendStreamingContent: (chunk) => {
+ const currentContent = get().streamingContent || '';
+ const newContent = currentContent + chunk;
+ set({ streamingContent: newContent });
+
+ const { editor } = get();
+ if (editor) {
+ try {
+ editor.setDocument('markdown', newContent);
+ } catch {
+ // Ignore errors during streaming updates
+ }
+ }
+ },
+
+ finishStreaming: async (saveCallback) => {
+ const { activeTabId, editor, streamingContent } = get();
+ if (!streamingContent) {
+ set({ streamingInProgress: false });
+ return;
+ }
+
+ let finalContent = streamingContent;
+ let editorData = {};
+
+ if (editor) {
+ try {
+ finalContent = (editor.getDocument('markdown') as unknown as string) || streamingContent;
+ editorData = editor.getDocument('json') as unknown as Record<string, any>;
+ } catch {
+ // Use streaming content if editor read fails
+ }
+ }
+
+ updateSaveStatusInternal(activeTabId, 'saving');
+
+ try {
+ await saveCallback({
+ content: finalContent,
+ editorData: structuredClone(editorData || {}),
+ });
+ updateSaveStatusInternal(activeTabId, 'saved');
+ } catch (error) {
+ console.error('[ProfileEditor] Failed to save streaming content:', error);
+ updateSaveStatusInternal(activeTabId, 'idle');
+ }
+
+ set({
+ streamingContent: undefined,
+ streamingInProgress: false,
+ });
+ },
+
+ flushSave: () => {
+ debouncedSave.flush();
+ },
+
+ handleContentChange: (saveCallback) => {
+ const { activeTabId, editor } = get();
+ if (!editor) return;
+
+ // Always update refs to use the latest callback and tabId
+ saveCallbackRef = saveCallback;
+ currentTabIdRef = activeTabId;
+
+ // Set saving status immediately when user makes changes
+ updateSaveStatusInternal(activeTabId, 'saving');
+
+ try {
+ const markdownContent = (editor.getDocument('markdown') as unknown as string) || '';
+ const jsonContent = editor.getDocument('json') as unknown as Record<string, any>;
+
+ debouncedSave({
+ content: markdownContent || '',
+ editorData: structuredClone(jsonContent || {}),
+ });
+ } catch (error) {
+ console.error('[ProfileEditor] Failed to read editor content:', error);
+ updateSaveStatusInternal(activeTabId, 'idle');
+ }
+ },
+
+ setActiveTabId: (tabId) => {
+ set({ activeTabId: tabId });
+ },
+
+ setChatPanelExpanded: (expanded) => {
+ if (typeof expanded === 'function') {
+ set((state) => ({ chatPanelExpanded: expanded(state.chatPanelExpanded) }));
+ } else {
+ set({ chatPanelExpanded: expanded });
+ }
+ },
+
+ updateSaveStatus: (tabId, status) => {
+ updateSaveStatusInternal(tabId, status);
+ },
+ };
+};
diff --git a/src/store/groupProfile/index.ts b/src/store/groupProfile/index.ts
new file mode 100644
index 00000000000..b1296795c9d
--- /dev/null
+++ b/src/store/groupProfile/index.ts
@@ -0,0 +1,16 @@
+'use client';
+
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn } from 'zustand/traditional';
+
+import { createDevtools } from '@/store/middleware/createDevtools';
+
+import { type Store, store } from './action';
+
+export type { PublicState, State } from './initialState';
+
+const devtools = createDevtools('group_profile');
+
+export const useGroupProfileStore = createWithEqualityFn<Store>()(devtools(store), shallow);
+
+export { selectors } from './selectors';
diff --git a/src/app/[variants]/(main)/group/profile/features/store/initialState.ts b/src/store/groupProfile/initialState.ts
similarity index 58%
rename from src/app/[variants]/(main)/group/profile/features/store/initialState.ts
rename to src/store/groupProfile/initialState.ts
index c9486598d35..1965949dccc 100644
--- a/src/app/[variants]/(main)/group/profile/features/store/initialState.ts
+++ b/src/store/groupProfile/initialState.ts
@@ -1,12 +1,27 @@
import { type IEditor } from '@lobehub/editor';
+export type SaveStatus = 'idle' | 'saving' | 'saved';
+
+export interface SaveState {
+ lastUpdatedTime?: Date | null;
+ saveStatus: SaveStatus;
+}
+
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface PublicState {}
export interface State extends PublicState {
+ /**
+ * Active tab ID - 'group' for group settings, or agent ID for member editor
+ */
+ activeTabId: string;
chatPanelExpanded: boolean;
editor?: IEditor;
editorState?: any; // EditorState from useEditorState hook
+ /**
+ * Save state map by tab ID (key: 'group' | agentId)
+ */
+ saveStateMap: Record<string, SaveState>;
/**
* Content being streamed from AI
*/
@@ -18,7 +33,9 @@ export interface State extends PublicState {
}
export const initialState: State = {
+ activeTabId: 'group',
chatPanelExpanded: true,
+ saveStateMap: {},
streamingContent: undefined,
streamingInProgress: false,
};
diff --git a/src/store/groupProfile/selectors.ts b/src/store/groupProfile/selectors.ts
new file mode 100644
index 00000000000..18bbdd6788e
--- /dev/null
+++ b/src/store/groupProfile/selectors.ts
@@ -0,0 +1,13 @@
+import { type Store } from './action';
+import { type SaveState } from './initialState';
+
+const DEFAULT_SAVE_STATE: SaveState = { lastUpdatedTime: null, saveStatus: 'idle' };
+
+const getSaveState = (tabId: string) => (s: Store) => s.saveStateMap[tabId] || DEFAULT_SAVE_STATE;
+
+export const selectors = {
+ chatPanelExpanded: (s: Store) => s.chatPanelExpanded,
+ editor: (s: Store) => s.editor,
+ editorState: (s: Store) => s.editorState,
+ getSaveState,
+};
diff --git a/src/store/tool/slices/builtin/executors/index.ts b/src/store/tool/slices/builtin/executors/index.ts
index e00f265fac8..c062b18741b 100644
--- a/src/store/tool/slices/builtin/executors/index.ts
+++ b/src/store/tool/slices/builtin/executors/index.ts
@@ -4,6 +4,8 @@
* Central registry for all builtin tool executors.
* Executors are registered as class instances by identifier.
*/
+import { agentBuilderExecutor } from '@lobechat/builtin-tool-agent-builder/executor';
+import { groupAgentBuilderExecutor } from '@lobechat/builtin-tool-group-agent-builder/executor';
import { groupManagementExecutor } from '@lobechat/builtin-tool-group-management/executor';
import { gtdExecutor } from '@lobechat/builtin-tool-gtd/executor';
import { knowledgeBaseExecutor } from '@lobechat/builtin-tool-knowledge-base/executor';
@@ -117,6 +119,8 @@ const registerExecutors = (executors: IBuiltinToolExecutor[]): void => {
// Register all executor instances
registerExecutors([
+ agentBuilderExecutor,
+ groupAgentBuilderExecutor,
groupManagementExecutor,
gtdExecutor,
knowledgeBaseExecutor,
diff --git a/src/styles/text.ts b/src/styles/text.ts
index b6483ba0dbc..ee355f588e8 100644
--- a/src/styles/text.ts
+++ b/src/styles/text.ts
@@ -12,6 +12,22 @@ export const lineEllipsis = (line: number) =>
export const oneLineEllipsis = lineEllipsis(1);
+/**
+ * Inspector text style for builtin tool inspectors
+ * Combines oneLineEllipsis with secondary text color
+ */
+export const inspectorTextStyles = createStaticStyles(({ css, cssVar }) => ({
+ root: css`
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 1;
+
+ color: ${cssVar.colorTextSecondary};
+ text-overflow: ellipsis;
+ `,
+}));
+
/**
* Highlight underline effect using gradient background
* - primary: default blue highlight
diff --git a/src/tools/executionRuntimes.ts b/src/tools/executionRuntimes.ts
deleted file mode 100644
index 79c28bc46ed..00000000000
--- a/src/tools/executionRuntimes.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { AgentBuilderManifest } from '@lobechat/builtin-tool-agent-builder';
-import { AgentBuilderExecutionRuntime } from '@lobechat/builtin-tool-agent-builder/executionRuntime';
-import { GroupAgentBuilderManifest } from '@lobechat/builtin-tool-group-agent-builder';
-import { GroupAgentBuilderExecutionRuntime } from '@lobechat/builtin-tool-group-agent-builder/executionRuntime';
-import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
-import { WebBrowsingExecutionRuntime } from '@lobechat/builtin-tool-web-browsing/executionRuntime';
-
-// Note: KnowledgeBase and LocalSystem now use executor pattern via toolStore/builtin/executors
-
-export const BuiltinToolServerRuntimes: Record<string, any> = {
- [AgentBuilderManifest.identifier]: AgentBuilderExecutionRuntime,
- [GroupAgentBuilderManifest.identifier]: GroupAgentBuilderExecutionRuntime,
- [WebBrowsingManifest.identifier]: WebBrowsingExecutionRuntime,
-};
diff --git a/src/tools/inspectors.ts b/src/tools/inspectors.ts
index 23e8cd8e71b..126bfaf4913 100644
--- a/src/tools/inspectors.ts
+++ b/src/tools/inspectors.ts
@@ -1,7 +1,15 @@
+import {
+ AgentBuilderInspectors,
+ AgentBuilderManifest,
+} from '@lobechat/builtin-tool-agent-builder/client';
import {
CloudSandboxIdentifier,
CloudSandboxInspectors,
} from '@lobechat/builtin-tool-cloud-sandbox/client';
+import {
+ GroupAgentBuilderInspectors,
+ GroupAgentBuilderManifest,
+} from '@lobechat/builtin-tool-group-agent-builder/client';
import {
GroupManagementInspectors,
GroupManagementManifest,
@@ -31,7 +39,12 @@ import { type BuiltinInspector } from '@lobechat/types';
* of tool calls in the conversation UI.
*/
const BuiltinToolInspectors: Record<string, Record<string, BuiltinInspector>> = {
+ [AgentBuilderManifest.identifier]: AgentBuilderInspectors as Record<string, BuiltinInspector>,
[CloudSandboxIdentifier]: CloudSandboxInspectors as Record<string, BuiltinInspector>,
+ [GroupAgentBuilderManifest.identifier]: GroupAgentBuilderInspectors as Record<
+ string,
+ BuiltinInspector
+ >,
[GroupManagementManifest.identifier]: GroupManagementInspectors as Record<
string,
BuiltinInspector
diff --git a/src/tools/renders.ts b/src/tools/renders.ts
index 761fb4cc3c6..4587530375b 100644
--- a/src/tools/renders.ts
+++ b/src/tools/renders.ts
@@ -2,6 +2,8 @@ import { AgentBuilderManifest } from '@lobechat/builtin-tool-agent-builder';
import { AgentBuilderRenders } from '@lobechat/builtin-tool-agent-builder/client';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { CloudSandboxRenders } from '@lobechat/builtin-tool-cloud-sandbox/client';
+import { GroupAgentBuilderManifest } from '@lobechat/builtin-tool-group-agent-builder';
+import { GroupAgentBuilderRenders } from '@lobechat/builtin-tool-group-agent-builder/client';
import { GroupManagementManifest } from '@lobechat/builtin-tool-group-management';
import { GroupManagementRenders } from '@lobechat/builtin-tool-group-management/client';
import { GTDManifest, GTDRenders } from '@lobechat/builtin-tool-gtd/client';
@@ -27,6 +29,7 @@ import { type BuiltinRender } from '@lobechat/types';
const BuiltinToolsRenders: Record<string, Record<string, BuiltinRender>> = {
[AgentBuilderManifest.identifier]: AgentBuilderRenders as Record<string, BuiltinRender>,
[CloudSandboxManifest.identifier]: CloudSandboxRenders as Record<string, BuiltinRender>,
+ [GroupAgentBuilderManifest.identifier]: GroupAgentBuilderRenders as Record<string, BuiltinRender>,
[GroupManagementManifest.identifier]: GroupManagementRenders as Record<string, BuiltinRender>,
[GTDManifest.identifier]: GTDRenders as Record<string, BuiltinRender>,
[NotebookManifest.identifier]: NotebookRenders as Record<string, BuiltinRender>,
diff --git a/src/tools/streamings.ts b/src/tools/streamings.ts
index 07d0847272a..ec0eecc6f56 100644
--- a/src/tools/streamings.ts
+++ b/src/tools/streamings.ts
@@ -2,6 +2,10 @@ import {
CloudSandboxManifest,
CloudSandboxStreamings,
} from '@lobechat/builtin-tool-cloud-sandbox/client';
+import {
+ GroupAgentBuilderManifest,
+ GroupAgentBuilderStreamings,
+} from '@lobechat/builtin-tool-group-agent-builder/client';
import {
GroupManagementManifest,
GroupManagementStreamings,
@@ -24,6 +28,10 @@ import { type BuiltinStreaming } from '@lobechat/types';
*/
const BuiltinToolStreamings: Record<string, Record<string, BuiltinStreaming>> = {
[CloudSandboxManifest.identifier]: CloudSandboxStreamings as Record<string, BuiltinStreaming>,
+ [GroupAgentBuilderManifest.identifier]: GroupAgentBuilderStreamings as Record<
+ string,
+ BuiltinStreaming
+ >,
[GroupManagementManifest.identifier]: GroupManagementStreamings as Record<
string,
BuiltinStreaming