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.

🐛 fix: broadcast tools calling and improve auto scroll (#11804)

Arvin Xuc352915d5dc8
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index d13adfd99e3..4c150ba1f64 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -36,7 +36,7 @@
"compression.summary": "Summary",
"confirmClearCurrentMessages": "You are about to clear the current session messages. Once cleared, they cannot be retrieved. Please confirm your action.",
"confirmRemoveChatGroupItemAlert": "This Group will be deleted. Group-specific assistants will also be deleted, while external assistants will not be affected.",
- "confirmRemoveGroupItemAlert": "You are about to delete this group. After deletion, its agents will be moved to the default list. Please confirm your action.",
+ "confirmRemoveGroupItemAlert": "You are about to delete this category. After deletion, its agents will be moved to the default list. Please confirm your action.",
"confirmRemoveGroupSuccess": "Group deleted successfully",
"confirmRemoveSessionItemAlert": "You are about to delete this agent. Once deleted, it cannot be retrieved. Please confirm your action.",
"confirmRemoveSessionSuccess": "Agent removed successfully",
@@ -239,28 +239,28 @@
"searchAgents": "Search agents...",
"selectedAgents": "Selected agents",
"sendPlaceholder": "Ask, create, or start a task, <hotkey><hotkey/>",
- "sessionGroup.config": "Group Management",
- "sessionGroup.confirmRemoveGroupAlert": "This group is about to be deleted. After deletion, the agents in this group will be moved to the default list. Please confirm your operation.",
+ "sessionGroup.config": "Category Management",
+ "sessionGroup.confirmRemoveGroupAlert": "This category is about to be deleted. After deletion, the agents in this category will be moved to the default list. Please confirm your operation.",
"sessionGroup.createAgentSuccess": "Agent created successfully",
- "sessionGroup.createGroup": "Add New Group",
- "sessionGroup.createGroupFailed": "Failed to create group chat",
- "sessionGroup.createGroupSuccess": "Group chat created successfully",
+ "sessionGroup.createGroup": "Add New Category",
+ "sessionGroup.createGroupFailed": "Failed to create category",
+ "sessionGroup.createGroupSuccess": "Category created successfully",
"sessionGroup.createSuccess": "Created successfully",
"sessionGroup.creatingAgent": "Creating agent...",
- "sessionGroup.groupName": "Group Name",
- "sessionGroup.inputPlaceholder": "Please enter group name...",
- "sessionGroup.moveGroup": "Move to Group",
- "sessionGroup.newGroup": "New Group",
+ "sessionGroup.groupName": "Category Name",
+ "sessionGroup.inputPlaceholder": "Please enter category name...",
+ "sessionGroup.moveGroup": "Move to Category",
+ "sessionGroup.newGroup": "New Category",
"sessionGroup.noAvailableAgents": "No available agents",
"sessionGroup.noMatchingAgents": "No matching agents found",
"sessionGroup.noSelectedAgents": "Please select agents",
- "sessionGroup.rename": "Rename Group",
+ "sessionGroup.rename": "Rename Category",
"sessionGroup.renameSuccess": "Renamed successfully",
"sessionGroup.searchAgents": "Search agents",
"sessionGroup.selectedAgents": "Selected agents ({{count}})",
"sessionGroup.sortSuccess": "Reorder successful",
- "sessionGroup.sorting": "Group sorting updating...",
- "sessionGroup.tooLong": "Group name length should be between 1-20",
+ "sessionGroup.sorting": "Category sorting updating...",
+ "sessionGroup.tooLong": "Category name length should be between 1-20",
"shareModal.copy": "Copy",
"shareModal.copyLink": "Copy Link",
"shareModal.copyLinkSuccess": "Link copied",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index abd76e9dae6..841e633fc4d 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -36,7 +36,7 @@
"compression.summary": "摘要",
"confirmClearCurrentMessages": "确认清空当前会话消息吗?清空后无法恢复",
"confirmRemoveChatGroupItemAlert": "确认删除该群组吗?群组专有助理将会被同样删除,外部助理不受影响",
- "confirmRemoveGroupItemAlert": "确认删除该分组吗?分组内的助理会移回默认列表",
+ "confirmRemoveGroupItemAlert": "确认删除该分类吗?分类内的助理会移回默认列表",
"confirmRemoveGroupSuccess": "群组已删除",
"confirmRemoveSessionItemAlert": "确认删除该助理吗?删除后无法恢复",
"confirmRemoveSessionSuccess": "助理已删除",
@@ -239,28 +239,28 @@
"searchAgents": "搜索助理…",
"selectedAgents": "已选助理",
"sendPlaceholder": "从任何想法开始… <hotkey><hotkey/>",
- "sessionGroup.config": "分组管理",
- "sessionGroup.confirmRemoveGroupAlert": "确认删除该分组吗?分组内的助理会移回默认列表",
+ "sessionGroup.config": "分类管理",
+ "sessionGroup.confirmRemoveGroupAlert": "确认删除该分类吗?分类内的助理会移回默认列表",
"sessionGroup.createAgentSuccess": "助理创建成功",
- "sessionGroup.createGroup": "添加新分组",
- "sessionGroup.createGroupFailed": "群组创建失败",
- "sessionGroup.createGroupSuccess": "群组创建成功",
- "sessionGroup.createSuccess": "分组创建成功",
+ "sessionGroup.createGroup": "添加新分类",
+ "sessionGroup.createGroupFailed": "分类创建失败",
+ "sessionGroup.createGroupSuccess": "分类创建成功",
+ "sessionGroup.createSuccess": "分类创建成功",
"sessionGroup.creatingAgent": "正在创建助理…",
- "sessionGroup.groupName": "分组名称",
- "sessionGroup.inputPlaceholder": "请输入分组名称…",
- "sessionGroup.moveGroup": "移动到分组",
- "sessionGroup.newGroup": "新分组",
+ "sessionGroup.groupName": "分类名称",
+ "sessionGroup.inputPlaceholder": "请输入分类名称…",
+ "sessionGroup.moveGroup": "移动到分类",
+ "sessionGroup.newGroup": "新分类",
"sessionGroup.noAvailableAgents": "暂无可用助理",
"sessionGroup.noMatchingAgents": "未找到匹配的助理",
"sessionGroup.noSelectedAgents": "请选择助理",
- "sessionGroup.rename": "重命名分组",
+ "sessionGroup.rename": "重命名分类",
"sessionGroup.renameSuccess": "重命名成功",
"sessionGroup.searchAgents": "搜索助理",
"sessionGroup.selectedAgents": "已选助理({{count}})",
"sessionGroup.sortSuccess": "排序已更新",
- "sessionGroup.sorting": "正在更新排序…",
- "sessionGroup.tooLong": "分组名称长度需为 1–20 个字符",
+ "sessionGroup.sorting": "正在更新分类排序…",
+ "sessionGroup.tooLong": "分类名称长度需为 1–20 个字符",
"shareModal.copy": "复制",
"shareModal.copyLink": "复制链接",
"shareModal.copyLinkSuccess": "链接已复制",
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 cb093f9000f..4325c0c28d7 100644
--- a/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts
@@ -256,13 +256,15 @@ export class GroupAgentBuilderExecutionRuntime {
// Check if agent is already in the group
const existingAgents = group.agents || [];
- const isAlreadyInGroup = existingAgents.some((a) => a.id === args.agentId);
+ const existingAgent = existingAgents.find((a) => a.id === args.agentId);
- if (isAlreadyInGroup) {
+ if (existingAgent) {
return {
- content: `Agent ${args.agentId} is already in the group`,
+ content: `Agent ${existingAgent.title || args.agentId} is already in the group`,
state: {
+ agentAvatar: existingAgent.avatar,
agentId: args.agentId,
+ agentName: existingAgent.title,
success: false,
} as InviteAgentState,
success: false,
@@ -277,12 +279,22 @@ export class GroupAgentBuilderExecutionRuntime {
const wasAdded = result.added.length > 0;
+ // Get the agent info from the updated group
+ const updatedGroup = agentGroupSelectors.getGroupById(groupId)(getChatGroupStoreState());
+ const addedAgent = updatedGroup?.agents?.find((a) => a.id === args.agentId);
+ const agentName = addedAgent?.title;
+ const agentAvatar = addedAgent?.avatar;
+
+ const agentDisplay = agentName ? `${agentName} (ID: ${args.agentId})` : args.agentId;
+
return {
content: wasAdded
- ? `Successfully invited agent ${args.agentId} to the group`
- : `Agent ${args.agentId} was already in the group`,
+ ? `Successfully invited agent ${agentDisplay} to the group`
+ : `Agent ${agentDisplay} was already in the group`,
state: {
+ agentAvatar,
agentId: args.agentId,
+ agentName,
success: wasAdded,
} as InviteAgentState,
success: wasAdded,
@@ -315,9 +327,9 @@ export class GroupAgentBuilderExecutionRuntime {
// Check if agent is in the group
const existingAgents = group.agents || [];
- const isInGroup = existingAgents.some((a) => a.id === args.agentId);
+ const agent = existingAgents.find((a) => a.id === args.agentId);
- if (!isInGroup) {
+ if (!agent) {
return {
content: `Agent ${args.agentId} is not in the group`,
state: {
@@ -328,12 +340,20 @@ export class GroupAgentBuilderExecutionRuntime {
};
}
+ // Get agent info before removing
+ const agentName = agent.title;
+ const agentAvatar = agent.avatar;
+
+ const agentDisplay = agentName ? `${agentName} (ID: ${args.agentId})` : args.agentId;
+
// Check if this is the supervisor agent (cannot be removed)
if (group.supervisorAgentId === args.agentId) {
return {
- content: `Cannot remove supervisor agent ${args.agentId} from the group`,
+ content: `Cannot remove supervisor agent ${agentDisplay} from the group`,
state: {
+ agentAvatar,
agentId: args.agentId,
+ agentName,
success: false,
} as RemoveAgentState,
success: false,
@@ -347,9 +367,11 @@ export class GroupAgentBuilderExecutionRuntime {
await state.refreshGroupDetail(groupId);
return {
- content: `Successfully removed agent ${args.agentId} from the group`,
+ content: `Successfully removed agent ${agentDisplay} from the group`,
state: {
+ agentAvatar,
agentId: args.agentId,
+ agentName,
success: true,
} as RemoveAgentState,
success: true,
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
index a4db77708ee..d767ae36048 100644
--- 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
@@ -1,19 +1,31 @@
'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 { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
+import { shinyTextStyles } from '@/styles';
import type { InviteAgentParams, InviteAgentState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
+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;
- margin-inline-start: 4px;
+ `,
+ title: css`
+ flex-shrink: 0;
+ color: ${cv.colorTextSecondary};
+ white-space: nowrap;
`,
}));
@@ -24,11 +36,12 @@ export const InviteAgentInspector = memo<
const agentId = args?.agentId || partialArgs?.agentId;
const displayName = pluginState?.agentName || agentId;
+ const avatar = pluginState?.agentAvatar;
// Initial streaming state
if (isArgumentsStreaming && !agentId) {
return (
- <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(styles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-group-agent-builder.apiName.inviteAgent')}</span>
</div>
);
@@ -37,18 +50,21 @@ export const InviteAgentInspector = memo<
const isSuccess = pluginState?.success;
return (
- <div
- className={cx(
- inspectorTextStyles.root,
- (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,
- )}
+ <Flexbox
+ align={'center'}
+ className={cx(styles.root, (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText)}
+ gap={8}
+ horizontal
>
- <span>{t('builtins.lobe-group-agent-builder.apiName.inviteAgent')}: </span>
- {displayName && <span className={highlightTextStyles.primary}>{displayName}</span>}
+ <span className={styles.title}>
+ {t('builtins.lobe-group-agent-builder.apiName.inviteAgent')}:
+ </span>
+ {avatar && <Avatar avatar={avatar} shape={'square'} size={20} title={displayName || undefined} />}
+ {displayName && <span>{displayName}</span>}
{!isLoading && isSuccess && (
<Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
)}
- </div>
+ </Flexbox>
);
});
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
index bdfc6547dcb..fd723bfabd1 100644
--- 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
@@ -1,19 +1,31 @@
'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 { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
+import { shinyTextStyles } from '@/styles';
import type { RemoveAgentParams, RemoveAgentState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
+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;
- margin-inline-start: 4px;
+ `,
+ title: css`
+ flex-shrink: 0;
+ color: ${cv.colorTextSecondary};
+ white-space: nowrap;
`,
}));
@@ -24,11 +36,12 @@ export const RemoveAgentInspector = memo<
const agentId = args?.agentId || partialArgs?.agentId;
const displayName = pluginState?.agentName || agentId;
+ const avatar = pluginState?.agentAvatar;
// Initial streaming state
if (isArgumentsStreaming && !agentId) {
return (
- <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <div className={cx(styles.root, shinyTextStyles.shinyText)}>
<span>{t('builtins.lobe-group-agent-builder.apiName.removeAgent')}</span>
</div>
);
@@ -37,18 +50,21 @@ export const RemoveAgentInspector = memo<
const isSuccess = pluginState?.success;
return (
- <div
- className={cx(
- inspectorTextStyles.root,
- (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,
- )}
+ <Flexbox
+ align={'center'}
+ className={cx(styles.root, (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText)}
+ gap={8}
+ horizontal
>
- <span>{t('builtins.lobe-group-agent-builder.apiName.removeAgent')}: </span>
- {displayName && <span className={highlightTextStyles.primary}>{displayName}</span>}
+ <span className={styles.title}>
+ {t('builtins.lobe-group-agent-builder.apiName.removeAgent')}:
+ </span>
+ {avatar && <Avatar avatar={avatar} shape={'square'} size={20} title={displayName || undefined} />}
+ {displayName && <span>{displayName}</span>}
{!isLoading && isSuccess && (
<Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
)}
- </div>
+ </Flexbox>
);
});
diff --git a/packages/builtin-tool-group-agent-builder/src/types.ts b/packages/builtin-tool-group-agent-builder/src/types.ts
index 3b9b8fae87f..46201db31ee 100644
--- a/packages/builtin-tool-group-agent-builder/src/types.ts
+++ b/packages/builtin-tool-group-agent-builder/src/types.ts
@@ -265,6 +265,10 @@ export interface CreateAgentState {
}
export interface InviteAgentState {
+ /**
+ * Agent avatar (emoji or URL)
+ */
+ agentAvatar?: string;
/**
* Agent identifier that was invited
*/
@@ -280,6 +284,10 @@ export interface InviteAgentState {
}
export interface RemoveAgentState {
+ /**
+ * Agent avatar (emoji or URL)
+ */
+ agentAvatar?: string;
/**
* Agent identifier that was removed
*/
diff --git a/packages/context-engine/src/engine/tools/ToolsEngine.ts b/packages/context-engine/src/engine/tools/ToolsEngine.ts
index 4e69b18f052..35ec1adcb74 100644
--- a/packages/context-engine/src/engine/tools/ToolsEngine.ts
+++ b/packages/context-engine/src/engine/tools/ToolsEngine.ts
@@ -53,17 +53,20 @@ export class ToolsEngine {
* @returns Processed tools array, or undefined if tools should not be enabled
*/
generateTools(params: GenerateToolsParams): UniformTool[] | undefined {
- const { toolIds = [], model, provider, context } = params;
+ const { toolIds = [], model, provider, context, skipDefaultTools } = params;
- // Merge user-provided tool IDs with default tool IDs
- const allToolIds = [...new Set([...toolIds, ...this.defaultToolIds])];
+ // Merge user-provided tool IDs with default tool IDs (unless skipDefaultTools is true)
+ const allToolIds = skipDefaultTools
+ ? toolIds
+ : [...new Set([...toolIds, ...this.defaultToolIds])];
log(
- 'Generating tools for model=%s, provider=%s, pluginIds=%o (includes %d default tools)',
+ 'Generating tools for model=%s, provider=%s, pluginIds=%o (skipDefaultTools=%s, includes %d default tools)',
model,
provider,
allToolIds,
- this.defaultToolIds.length,
+ skipDefaultTools,
+ skipDefaultTools ? 0 : this.defaultToolIds.length,
);
// 1. Check if model supports Function Calling
@@ -94,17 +97,20 @@ export class ToolsEngine {
* @returns Detailed tools generation result
*/
generateToolsDetailed(params: GenerateToolsParams): ToolsGenerationResult {
- const { toolIds = [], model, provider, context } = params;
+ const { toolIds = [], model, provider, context, skipDefaultTools } = params;
- // Merge user-provided tool IDs with default tool IDs and deduplicate
- const allToolIds = [...new Set([...toolIds, ...this.defaultToolIds])];
+ // Merge user-provided tool IDs with default tool IDs and deduplicate (unless skipDefaultTools is true)
+ const allToolIds = skipDefaultTools
+ ? toolIds
+ : [...new Set([...toolIds, ...this.defaultToolIds])];
log(
- 'Generating detailed tools for model=%s, provider=%s, pluginIds=%o (includes %d default tools)',
+ 'Generating detailed tools for model=%s, provider=%s, pluginIds=%o (skipDefaultTools=%s, includes %d default tools)',
model,
provider,
allToolIds,
- this.defaultToolIds.length,
+ skipDefaultTools,
+ skipDefaultTools ? 0 : this.defaultToolIds.length,
);
// Check if model supports Function Calling
diff --git a/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts b/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts
index 8e7380ecbcf..7756a262f94 100644
--- a/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts
+++ b/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts
@@ -1135,4 +1135,146 @@ describe('ToolsEngine', () => {
expect(result).toHaveLength(2);
});
});
+
+ describe('skipDefaultTools', () => {
+ it('should not include default tools when skipDefaultTools is true in generateTools', () => {
+ const engine = new ToolsEngine({
+ manifestSchemas: [mockWebBrowsingManifest, mockDalleManifest],
+ defaultToolIds: ['lobe-web-browsing'],
+ enableChecker: () => true,
+ functionCallChecker: () => true,
+ });
+
+ const result = engine.generateTools({
+ toolIds: ['dalle'],
+ model: 'gpt-4',
+ provider: 'openai',
+ skipDefaultTools: true,
+ });
+
+ // Should only include dalle, not the default lobe-web-browsing
+ expect(result).toHaveLength(1);
+ expect(result![0].function.name).toBe('dalle____generateImage____builtin');
+ });
+
+ it('should not include default tools when skipDefaultTools is true in generateToolsDetailed', () => {
+ const engine = new ToolsEngine({
+ manifestSchemas: [mockWebBrowsingManifest, mockDalleManifest],
+ defaultToolIds: ['lobe-web-browsing'],
+ enableChecker: () => true,
+ functionCallChecker: () => true,
+ });
+
+ const result = engine.generateToolsDetailed({
+ toolIds: ['dalle'],
+ model: 'gpt-4',
+ provider: 'openai',
+ skipDefaultTools: true,
+ });
+
+ // Should only include dalle, not the default lobe-web-browsing
+ expect(result.tools).toHaveLength(1);
+ expect(result.enabledToolIds).toEqual(['dalle']);
+ expect(result.enabledManifests).toHaveLength(1);
+ expect(result.enabledManifests[0].identifier).toBe('dalle');
+ });
+
+ it('should return undefined when skipDefaultTools is true and toolIds is empty', () => {
+ const engine = new ToolsEngine({
+ manifestSchemas: [mockWebBrowsingManifest, mockDalleManifest],
+ defaultToolIds: ['lobe-web-browsing', 'dalle'],
+ enableChecker: () => true,
+ functionCallChecker: () => true,
+ });
+
+ const result = engine.generateTools({
+ toolIds: [],
+ model: 'gpt-4',
+ provider: 'openai',
+ skipDefaultTools: true,
+ });
+
+ // Should return undefined when no tools are available
+ expect(result).toBeUndefined();
+ });
+
+ it('should return empty results when skipDefaultTools is true and toolIds is empty in generateToolsDetailed', () => {
+ const engine = new ToolsEngine({
+ manifestSchemas: [mockWebBrowsingManifest, mockDalleManifest],
+ defaultToolIds: ['lobe-web-browsing', 'dalle'],
+ enableChecker: () => true,
+ functionCallChecker: () => true,
+ });
+
+ const result = engine.generateToolsDetailed({
+ toolIds: [],
+ model: 'gpt-4',
+ provider: 'openai',
+ skipDefaultTools: true,
+ });
+
+ // Should return empty results
+ expect(result.tools).toBeUndefined();
+ expect(result.enabledToolIds).toEqual([]);
+ expect(result.enabledManifests).toHaveLength(0);
+ });
+
+ it('should include default tools when skipDefaultTools is false', () => {
+ const engine = new ToolsEngine({
+ manifestSchemas: [mockWebBrowsingManifest, mockDalleManifest],
+ defaultToolIds: ['lobe-web-browsing'],
+ enableChecker: () => true,
+ functionCallChecker: () => true,
+ });
+
+ const result = engine.generateTools({
+ toolIds: ['dalle'],
+ model: 'gpt-4',
+ provider: 'openai',
+ skipDefaultTools: false,
+ });
+
+ // Should include both dalle and the default lobe-web-browsing
+ expect(result).toHaveLength(2);
+ });
+
+ it('should include default tools when skipDefaultTools is undefined (default behavior)', () => {
+ const engine = new ToolsEngine({
+ manifestSchemas: [mockWebBrowsingManifest, mockDalleManifest],
+ defaultToolIds: ['lobe-web-browsing'],
+ enableChecker: () => true,
+ functionCallChecker: () => true,
+ });
+
+ const result = engine.generateTools({
+ toolIds: ['dalle'],
+ model: 'gpt-4',
+ provider: 'openai',
+ // skipDefaultTools not specified
+ });
+
+ // Should include both dalle and the default lobe-web-browsing
+ expect(result).toHaveLength(2);
+ });
+
+ it('should work correctly with empty defaultToolIds', () => {
+ const engine = new ToolsEngine({
+ manifestSchemas: [mockWebBrowsingManifest, mockDalleManifest],
+ defaultToolIds: [],
+ enableChecker: () => true,
+ functionCallChecker: () => true,
+ });
+
+ const result = engine.generateTools({
+ toolIds: ['dalle'],
+ model: 'gpt-4',
+ provider: 'openai',
+ skipDefaultTools: true,
+ });
+
+ // Should only include dalle
+ expect(result).toHaveLength(1);
+ expect(result![0].function.name).toBe('dalle____generateImage____builtin');
+ });
+ });
});
diff --git a/packages/context-engine/src/engine/tools/types.ts b/packages/context-engine/src/engine/tools/types.ts
index 6309a7840a4..998199f82d3 100644
--- a/packages/context-engine/src/engine/tools/types.ts
+++ b/packages/context-engine/src/engine/tools/types.ts
@@ -72,6 +72,12 @@ export interface GenerateToolsParams {
model: string;
/** Provider name */
provider: string;
+ /**
+ * Whether to skip merging default tools.
+ * When true, only the explicitly provided toolIds will be used.
+ * Useful for broadcast scenarios where tools should be completely disabled.
+ */
+ skipDefaultTools?: boolean;
/** List of tool IDs to enable */
toolIds?: string[];
}
diff --git a/src/features/Conversation/ChatItem/ChatItem.tsx b/src/features/Conversation/ChatItem/ChatItem.tsx
index b5bb2005ba9..a86b129c688 100644
--- a/src/features/Conversation/ChatItem/ChatItem.tsx
+++ b/src/features/Conversation/ChatItem/ChatItem.tsx
@@ -39,7 +39,7 @@ const ChatItem = memo<ChatItemProps>(
disabled = false,
id,
style,
- newScreen,
+ newScreenMinHeight,
...rest
}) => {
const isUser = placement === 'right';
@@ -63,15 +63,12 @@ const ChatItem = memo<ChatItemProps>(
return (
<Flexbox
align={isUser ? 'flex-end' : 'flex-start'}
- className={cx(
- 'message-wrapper',
- styles.container,
- newScreen && styles.newScreen,
- className,
- )}
+ className={cx('message-wrapper', styles.container, className)}
+ data-message-id={id}
gap={8}
paddingBlock={8}
style={{
+ minHeight: newScreenMinHeight,
paddingInlineStart: isUser ? 36 : 0,
...style,
}}
diff --git a/src/features/Conversation/ChatItem/style.ts b/src/features/Conversation/ChatItem/style.ts
index 485e74d46e4..2dd8f864542 100644
--- a/src/features/Conversation/ChatItem/style.ts
+++ b/src/features/Conversation/ChatItem/style.ts
@@ -51,8 +51,5 @@ export const styles = createStaticStyles(({ css, cssVar }) => {
background: ${cssVar.colorPrimary};
`,
- newScreen: css`
- min-height: calc(-300px + 100dvh);
- `,
};
});
diff --git a/src/features/Conversation/ChatItem/type.ts b/src/features/Conversation/ChatItem/type.ts
index ec3340e1d6d..274fe70208f 100644
--- a/src/features/Conversation/ChatItem/type.ts
+++ b/src/features/Conversation/ChatItem/type.ts
@@ -35,7 +35,10 @@ export interface ChatItemProps extends Omit<FlexboxProps, 'children' | 'onChange
*/
message?: ReactNode;
messageExtra?: ReactNode;
- newScreen?: boolean;
+ /**
+ * Dynamic min-height for new screen effect, e.g. "calc(100dvh - 350px)"
+ */
+ newScreenMinHeight?: string;
onAvatarClick?: () => void;
onDoubleClick?: DivProps['onDoubleClick'];
/**
diff --git a/src/features/Conversation/Messages/Assistant/index.tsx b/src/features/Conversation/Messages/Assistant/index.tsx
index 83fa4cf4ce4..da57987f4ee 100644
--- a/src/features/Conversation/Messages/Assistant/index.tsx
+++ b/src/features/Conversation/Messages/Assistant/index.tsx
@@ -58,7 +58,11 @@ const AssistantMessage = memo<AssistantMessageProps>(
const editing = useConversationStore(messageStateSelectors.isMessageEditing(id));
const generating = useConversationStore(messageStateSelectors.isMessageGenerating(id));
const creating = useConversationStore(messageStateSelectors.isMessageCreating(id));
- const newScreen = useNewScreen({ creating: creating || generating, isLatestItem });
+ const { minHeight } = useNewScreen({
+ creating: creating || generating,
+ isLatestItem,
+ messageId: id,
+ });
const errorContent = useErrorContent(error);
@@ -114,7 +118,7 @@ const AssistantMessage = memo<AssistantMessageProps>(
usage={usage! || metadata}
/>
}
- newScreen={newScreen}
+ newScreenMinHeight={minHeight}
onDoubleClick={onDoubleClick}
onMouseEnter={onMouseEnter}
placement={'left'}
diff --git a/src/features/Conversation/Messages/AssistantGroup/index.tsx b/src/features/Conversation/Messages/AssistantGroup/index.tsx
index ee8efb08bf8..626dc4bbef7 100644
--- a/src/features/Conversation/Messages/AssistantGroup/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/index.tsx
@@ -2,13 +2,13 @@
import type { AssistantContentBlock } from '@lobechat/types';
import isEqual from 'fast-deep-equal';
-import dynamic from '@/libs/next/dynamic';
import { type MouseEventHandler, Suspense, memo, useCallback, useMemo } from 'react';
import { MESSAGE_ACTION_BAR_PORTAL_ATTRIBUTES } from '@/const/messageActionPortal';
import { ChatItem } from '@/features/Conversation/ChatItem';
import { useNewScreen } from '@/features/Conversation/Messages/components/useNewScreen';
import { useOpenChatSettings } from '@/hooks/useInterceptingRoutes';
+import dynamic from '@/libs/next/dynamic';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useGlobalStore } from '@/store/global';
@@ -68,7 +68,7 @@ const GroupMessage = memo<GroupMessageProps>(({ id, index, disableEditing, isLat
// Get editing state from ConversationStore
const editing = useConversationStore(messageStateSelectors.isMessageEditing(contentId || ''));
const creating = useConversationStore(messageStateSelectors.isMessageCreating(id));
- const newScreen = useNewScreen({ creating, isLatestItem });
+ const { minHeight } = useNewScreen({ creating, isLatestItem, messageId: id });
const setMessageItemActionElementPortialContext = useSetMessageItemActionElementPortialContext();
const setMessageItemActionTypeContext = useSetMessageItemActionTypeContext();
@@ -113,7 +113,7 @@ const GroupMessage = memo<GroupMessageProps>(({ id, index, disableEditing, isLat
)
}
avatar={avatar}
- newScreen={newScreen}
+ newScreenMinHeight={minHeight}
onAvatarClick={onAvatarClick}
onMouseEnter={onMouseEnter}
placement={'left'}
diff --git a/src/features/Conversation/Messages/Supervisor/index.tsx b/src/features/Conversation/Messages/Supervisor/index.tsx
index c5d4abefeee..3d436a80a42 100644
--- a/src/features/Conversation/Messages/Supervisor/index.tsx
+++ b/src/features/Conversation/Messages/Supervisor/index.tsx
@@ -56,7 +56,11 @@ const GroupMessage = memo<GroupMessageProps>(({ id, index, disableEditing, isLat
// Get editing state from ConversationStore
const creating = useConversationStore(messageStateSelectors.isMessageCreating(id));
const generating = useConversationStore(messageStateSelectors.isMessageGenerating(id));
- const newScreen = useNewScreen({ creating: creating || generating, isLatestItem });
+ const { minHeight } = useNewScreen({
+ creating: creating || generating,
+ isLatestItem,
+ messageId: id,
+ });
const setMessageItemActionElementPortialContext = useSetMessageItemActionElementPortialContext();
const setMessageItemActionTypeContext = useSetMessageItemActionTypeContext();
@@ -98,7 +102,7 @@ const GroupMessage = memo<GroupMessageProps>(({ id, index, disableEditing, isLat
memberAvatars={memberAvatars}
/>
)}
- newScreen={newScreen}
+ newScreenMinHeight={minHeight}
onMouseEnter={onMouseEnter}
placement={'left'}
showTitle
diff --git a/src/features/Conversation/Messages/Task/index.tsx b/src/features/Conversation/Messages/Task/index.tsx
index bc6291594e6..03661869bdc 100644
--- a/src/features/Conversation/Messages/Task/index.tsx
+++ b/src/features/Conversation/Messages/Task/index.tsx
@@ -44,7 +44,11 @@ const TaskMessage = memo<TaskMessageProps>(({ id, index, disableEditing, isLates
const editing = useConversationStore(messageStateSelectors.isMessageEditing(id));
const generating = useConversationStore(messageStateSelectors.isMessageGenerating(id));
const creating = useConversationStore(messageStateSelectors.isMessageCreating(id));
- const newScreen = useNewScreen({ creating: generating || creating, isLatestItem });
+ const { minHeight } = useNewScreen({
+ creating: generating || creating,
+ isLatestItem,
+ messageId: id,
+ });
const errorContent = useErrorContent(error);
@@ -84,7 +88,7 @@ const TaskMessage = memo<TaskMessageProps>(({ id, index, disableEditing, isLates
id={id}
loading={generating}
message={message}
- newScreen={newScreen}
+ newScreenMinHeight={minHeight}
onAvatarClick={onAvatarClick}
onDoubleClick={onDoubleClick}
placement={'left'}
diff --git a/src/features/Conversation/Messages/components/useNewScreen.test.ts b/src/features/Conversation/Messages/components/useNewScreen.test.ts
new file mode 100644
index 00000000000..6e5288dcdb1
--- /dev/null
+++ b/src/features/Conversation/Messages/components/useNewScreen.test.ts
@@ -0,0 +1,331 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useNewScreen } from './useNewScreen';
+
+// Mock useConversationStore
+const mockGetViewportSize = vi.fn();
+vi.mock('../../store', () => ({
+ useConversationStore: vi.fn((selector) =>
+ selector({
+ virtuaScrollMethods: {
+ getViewportSize: mockGetViewportSize,
+ },
+ }),
+ ),
+}));
+
+describe('useNewScreen', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetViewportSize.mockReturnValue(800);
+ });
+
+ describe('when not the latest item', () => {
+ it('should return undefined minHeight', () => {
+ const { result } = renderHook(() =>
+ useNewScreen({
+ creating: true,
+ isLatestItem: false,
+ messageId: 'msg-1',
+ }),
+ );
+
+ expect(result.current.minHeight).toBeUndefined();
+ });
+
+ it('should clear minHeight when becoming not the latest item', () => {
+ const { result, rerender } = renderHook(
+ ({ isLatestItem }) =>
+ useNewScreen({
+ creating: true,
+ isLatestItem,
+ messageId: 'msg-1',
+ }),
+ {
+ initialProps: { isLatestItem: true },
+ },
+ );
+
+ // Initially, it will use fallback since no DOM elements exist
+ expect(result.current.minHeight).toBeDefined();
+
+ // When it's no longer the latest item
+ rerender({ isLatestItem: false });
+
+ expect(result.current.minHeight).toBeUndefined();
+ });
+ });
+
+ describe('when latest item but not creating', () => {
+ it('should not update minHeight (preserve existing value)', () => {
+ const { result, rerender } = renderHook(
+ ({ creating }) =>
+ useNewScreen({
+ creating,
+ isLatestItem: true,
+ messageId: 'msg-1',
+ }),
+ {
+ initialProps: { creating: true },
+ },
+ );
+
+ // Initially sets minHeight (fallback)
+ const initialMinHeight = result.current.minHeight;
+ expect(initialMinHeight).toBeDefined();
+
+ // When creating ends, should preserve the minHeight
+ rerender({ creating: false });
+
+ expect(result.current.minHeight).toBe(initialMinHeight);
+ });
+ });
+
+ describe('when latest item and creating', () => {
+ it('should calculate minHeight based on viewport and previous message height', () => {
+ // Setup DOM mocks
+ const mockPrevMessageEl = {
+ getBoundingClientRect: () => ({ height: 150 }),
+ };
+ const mockPrevWrapper = {
+ querySelector: vi.fn().mockReturnValue(mockPrevMessageEl),
+ getBoundingClientRect: () => ({ height: 150 }),
+ };
+ const mockCurrentWrapper = {
+ dataset: { index: '1' },
+ };
+ const mockMessageEl = {
+ closest: vi.fn().mockReturnValue(mockCurrentWrapper),
+ };
+
+ vi.spyOn(document, 'querySelector').mockImplementation((selector: string) => {
+ if (selector === '[data-message-id="msg-1"]') {
+ return mockMessageEl as unknown as Element;
+ }
+ if (selector === '[data-index="0"]') {
+ return mockPrevWrapper as unknown as Element;
+ }
+ return null;
+ });
+
+ mockGetViewportSize.mockReturnValue(800);
+
+ const { result } = renderHook(() =>
+ useNewScreen({
+ creating: true,
+ isLatestItem: true,
+ messageId: 'msg-1',
+ }),
+ );
+
+ // minHeight = viewportHeight - prevHeight - EXTRA_PADDING = 800 - 150 - 0 = 650
+ expect(result.current.minHeight).toBe('650px');
+ });
+
+ it('should use fallback height when previous message element not found', () => {
+ // Setup DOM mocks - no previous element
+ const mockCurrentWrapper = {
+ dataset: { index: '0' },
+ querySelector: vi.fn().mockReturnValue(null),
+ };
+ const mockMessageEl = {
+ closest: vi.fn().mockReturnValue(mockCurrentWrapper),
+ };
+
+ vi.spyOn(document, 'querySelector').mockImplementation((selector: string) => {
+ if (selector === '[data-message-id="msg-1"]') {
+ return mockMessageEl as unknown as Element;
+ }
+ return null;
+ });
+
+ mockGetViewportSize.mockReturnValue(800);
+
+ const { result } = renderHook(() =>
+ useNewScreen({
+ creating: true,
+ isLatestItem: true,
+ messageId: 'msg-1',
+ }),
+ );
+
+ // fallback: viewportHeight - DEFAULT_USER_MESSAGE_HEIGHT - EXTRA_PADDING = 800 - 200 - 0 = 600
+ expect(result.current.minHeight).toBe('600px');
+ });
+
+ it('should return undefined when calculated height is less than or equal to 0', () => {
+ // Setup DOM mocks with very large previous message
+ const mockPrevMessageEl = {
+ getBoundingClientRect: () => ({ height: 900 }), // Larger than viewport
+ };
+ const mockPrevWrapper = {
+ querySelector: vi.fn().mockReturnValue(mockPrevMessageEl),
+ getBoundingClientRect: () => ({ height: 900 }),
+ };
+ const mockCurrentWrapper = {
+ dataset: { index: '1' },
+ };
+ const mockMessageEl = {
+ closest: vi.fn().mockReturnValue(mockCurrentWrapper),
+ };
+
+ vi.spyOn(document, 'querySelector').mockImplementation((selector: string) => {
+ if (selector === '[data-message-id="msg-1"]') {
+ return mockMessageEl as unknown as Element;
+ }
+ if (selector === '[data-index="0"]') {
+ return mockPrevWrapper as unknown as Element;
+ }
+ return null;
+ });
+
+ mockGetViewportSize.mockReturnValue(800);
+
+ const { result } = renderHook(() =>
+ useNewScreen({
+ creating: true,
+ isLatestItem: true,
+ messageId: 'msg-1',
+ }),
+ );
+
+ // minHeight = 800 - 900 - 0 = -100, should be undefined
+ expect(result.current.minHeight).toBeUndefined();
+ });
+
+ it('should use window.innerHeight when virtuaScrollMethods is not available', () => {
+ // Reset mock to return undefined for virtuaScrollMethods
+ vi.mocked(mockGetViewportSize).mockReturnValue(undefined as unknown as number);
+
+ // Mock window.innerHeight
+ Object.defineProperty(window, 'innerHeight', { value: 768, writable: true });
+
+ // Setup DOM mocks - no previous element (fallback case)
+ const mockCurrentWrapper = {
+ dataset: { index: '0' },
+ querySelector: vi.fn().mockReturnValue(null),
+ };
+ const mockMessageEl = {
+ closest: vi.fn().mockReturnValue(mockCurrentWrapper),
+ };
+
+ vi.spyOn(document, 'querySelector').mockImplementation((selector: string) => {
+ if (selector === '[data-message-id="msg-1"]') {
+ return mockMessageEl as unknown as Element;
+ }
+ return null;
+ });
+
+ const { result } = renderHook(() =>
+ useNewScreen({
+ creating: true,
+ isLatestItem: true,
+ messageId: 'msg-1',
+ }),
+ );
+
+ // fallback: window.innerHeight - DEFAULT_USER_MESSAGE_HEIGHT = 768 - 200 = 568
+ expect(result.current.minHeight).toBe('568px');
+ });
+ });
+
+ describe('edge cases', () => {
+ it('should handle message element not found', () => {
+ vi.spyOn(document, 'querySelector').mockReturnValue(null);
+
+ const { result } = renderHook(() =>
+ useNewScreen({
+ creating: true,
+ isLatestItem: true,
+ messageId: 'non-existent',
+ }),
+ );
+
+ // Should use fallback
+ expect(result.current.minHeight).toBeDefined();
+ });
+
+ it('should handle negative prevIndex', () => {
+ const mockCurrentWrapper = {
+ dataset: { index: '0' }, // First item, prevIndex would be -1
+ querySelector: vi.fn().mockReturnValue(null),
+ };
+ const mockMessageEl = {
+ closest: vi.fn().mockReturnValue(mockCurrentWrapper),
+ };
+
+ vi.spyOn(document, 'querySelector').mockImplementation((selector: string) => {
+ if (selector === '[data-message-id="msg-1"]') {
+ return mockMessageEl as unknown as Element;
+ }
+ // Should not query for [data-index="-1"]
+ if (selector === '[data-index="-1"]') {
+ throw new Error('Should not query for negative index');
+ }
+ return null;
+ });
+
+ mockGetViewportSize.mockReturnValue(800);
+
+ const { result } = renderHook(() =>
+ useNewScreen({
+ creating: true,
+ isLatestItem: true,
+ messageId: 'msg-1',
+ }),
+ );
+
+ // Should use fallback without throwing
+ expect(result.current.minHeight).toBe('600px');
+ });
+
+ it('should recalculate when messageId changes', () => {
+ const mockPrevMessageEl = {
+ getBoundingClientRect: () => ({ height: 150 }),
+ };
+ const mockPrevWrapper = {
+ querySelector: vi.fn().mockReturnValue(mockPrevMessageEl),
+ getBoundingClientRect: () => ({ height: 150 }),
+ };
+ const mockCurrentWrapper = {
+ dataset: { index: '1' },
+ };
+ const mockMessageEl = {
+ closest: vi.fn().mockReturnValue(mockCurrentWrapper),
+ };
+
+ vi.spyOn(document, 'querySelector').mockImplementation((selector: string) => {
+ if (selector.includes('data-message-id')) {
+ return mockMessageEl as unknown as Element;
+ }
+ if (selector === '[data-index="0"]') {
+ return mockPrevWrapper as unknown as Element;
+ }
+ return null;
+ });
+
+ mockGetViewportSize.mockReturnValue(800);
+
+ const { result, rerender } = renderHook(
+ ({ messageId }) =>
+ useNewScreen({
+ creating: true,
+ isLatestItem: true,
+ messageId,
+ }),
+ {
+ initialProps: { messageId: 'msg-1' },
+ },
+ );
+
+ expect(result.current.minHeight).toBe('650px');
+
+ // Change messageId - should recalculate
+ rerender({ messageId: 'msg-2' });
+
+ // Still the same value since mocks return same values
+ expect(result.current.minHeight).toBe('650px');
+ });
+ });
+});
diff --git a/src/features/Conversation/Messages/components/useNewScreen.ts b/src/features/Conversation/Messages/components/useNewScreen.ts
index b747a96523e..b56b4d99a0a 100644
--- a/src/features/Conversation/Messages/components/useNewScreen.ts
+++ b/src/features/Conversation/Messages/components/useNewScreen.ts
@@ -1,16 +1,91 @@
+import debug from 'debug';
import { useEffect, useState } from 'react';
+import { useConversationStore } from '../../store';
+
+const log = debug('lobe-render:Conversation:newScreen');
+
+/**
+ * Extra padding if needed
+ */
+const EXTRA_PADDING = 0;
+
+/**
+ * Default user message height (fallback)
+ */
+const DEFAULT_USER_MESSAGE_HEIGHT = 200;
+
export const useNewScreen = ({
isLatestItem,
creating,
+ messageId,
}: {
creating?: boolean;
isLatestItem?: boolean;
+ messageId: string;
}) => {
- const [newScreen, setNewScreen] = useState(false);
+ const [minHeight, setMinHeight] = useState<string | undefined>(undefined);
+ const virtuaScrollMethods = useConversationStore((s) => s.virtuaScrollMethods);
+
useEffect(() => {
- if (!isLatestItem) setNewScreen(false);
- if (isLatestItem && creating) setNewScreen(true);
- }, [isLatestItem, creating]);
- return newScreen;
+ // Clear minHeight when no longer the latest item
+ if (!isLatestItem) {
+ setMinHeight(undefined);
+ return;
+ }
+
+ // Only calculate and set minHeight when creating, preserve after creating ends
+ if (!creating) {
+ return;
+ }
+
+ // Find current message element by data-message-id
+ const messageEl = document.querySelector(`[data-message-id="${messageId}"]`);
+ // Find VList item container (has data-index attribute)
+ const currentWrapper = messageEl?.closest('[data-index]') as HTMLElement | null;
+ // Get current index
+ const currentIndex = currentWrapper?.dataset.index;
+
+ // Find previous VList item by data-index (avoid sibling not existing due to virtualization)
+ const prevIndex = currentIndex ? Number(currentIndex) - 1 : -1;
+ const prevWrapper =
+ prevIndex >= 0 ? document.querySelector(`[data-index="${prevIndex}"]`) : null;
+ // Get previous message's .message-wrapper
+ const prevMessageEl = prevWrapper?.querySelector('.message-wrapper');
+
+ // Get real viewport height from VList
+ const viewportHeight = virtuaScrollMethods?.getViewportSize?.() || window.innerHeight;
+
+ if (prevMessageEl) {
+ const prevHeight = prevMessageEl.getBoundingClientRect().height;
+
+ // Goal: userMessage at top, so assistantMinHeight = viewportHeight - userMessageHeight
+ const calculatedHeight = viewportHeight - prevHeight - EXTRA_PADDING;
+
+ log(
+ 'calculate minHeight: messageId=%s, index=%s, viewportHeight=%d, prevHeight=%d, result=%d',
+ messageId,
+ currentIndex,
+ viewportHeight,
+ prevHeight,
+ calculatedHeight,
+ );
+
+ // Don't set minHeight if calculated height <= 0
+ setMinHeight(calculatedHeight > 0 ? `${calculatedHeight}px` : undefined);
+ } else {
+ // Fallback: use default value
+ const fallbackHeight = viewportHeight - DEFAULT_USER_MESSAGE_HEIGHT - EXTRA_PADDING;
+ log(
+ 'fallback minHeight: messageId=%s, viewportHeight=%d, fallbackHeight=%d',
+ messageId,
+ viewportHeight,
+ fallbackHeight,
+ );
+ // Don't set minHeight if calculated height <= 0
+ setMinHeight(fallbackHeight > 0 ? `${fallbackHeight}px` : undefined);
+ }
+ }, [isLatestItem, creating, messageId, virtuaScrollMethods]);
+
+ return { minHeight };
};
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index 7095a1331d2..37c1222af46 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -48,7 +48,7 @@ export default {
'confirmRemoveChatGroupItemAlert':
'This Group will be deleted. Group-specific assistants will also be deleted, while external assistants will not be affected.',
'confirmRemoveGroupItemAlert':
- 'You are about to delete this group. After deletion, its agents will be moved to the default list. Please confirm your action.',
+ 'You are about to delete this category. After deletion, its agents will be moved to the default list. Please confirm your action.',
'confirmRemoveGroupSuccess': 'Group deleted successfully',
'confirmRemoveSessionItemAlert':
'You are about to delete this agent. Once deleted, it cannot be retrieved. Please confirm your action.',
@@ -267,29 +267,29 @@ export default {
'searchAgents': 'Search agents...',
'selectedAgents': 'Selected agents',
'sendPlaceholder': 'Ask, create, or start a task, <hotkey><hotkey/>',
- 'sessionGroup.config': 'Group Management',
+ 'sessionGroup.config': 'Category Management',
'sessionGroup.confirmRemoveGroupAlert':
- 'This group is about to be deleted. After deletion, the agents in this group will be moved to the default list. Please confirm your operation.',
+ 'This category is about to be deleted. After deletion, the agents in this category will be moved to the default list. Please confirm your operation.',
'sessionGroup.createAgentSuccess': 'Agent created successfully',
- 'sessionGroup.createGroup': 'Add New Group',
- 'sessionGroup.createGroupFailed': 'Failed to create group chat',
- 'sessionGroup.createGroupSuccess': 'Group chat created successfully',
+ 'sessionGroup.createGroup': 'Add New Category',
+ 'sessionGroup.createGroupFailed': 'Failed to create category',
+ 'sessionGroup.createGroupSuccess': 'Category created successfully',
'sessionGroup.createSuccess': 'Created successfully',
'sessionGroup.creatingAgent': 'Creating agent...',
- 'sessionGroup.groupName': 'Group Name',
- 'sessionGroup.inputPlaceholder': 'Please enter group name...',
- 'sessionGroup.moveGroup': 'Move to Group',
- 'sessionGroup.newGroup': 'New Group',
+ 'sessionGroup.groupName': 'Category Name',
+ 'sessionGroup.inputPlaceholder': 'Please enter category name...',
+ 'sessionGroup.moveGroup': 'Move to Category',
+ 'sessionGroup.newGroup': 'New Category',
'sessionGroup.noAvailableAgents': 'No available agents',
'sessionGroup.noMatchingAgents': 'No matching agents found',
'sessionGroup.noSelectedAgents': 'Please select agents',
- 'sessionGroup.rename': 'Rename Group',
+ 'sessionGroup.rename': 'Rename Category',
'sessionGroup.renameSuccess': 'Renamed successfully',
'sessionGroup.searchAgents': 'Search agents',
'sessionGroup.selectedAgents': 'Selected agents ({{count}})',
'sessionGroup.sortSuccess': 'Reorder successful',
- 'sessionGroup.sorting': 'Group sorting updating...',
- 'sessionGroup.tooLong': 'Group name length should be between 1-20',
+ 'sessionGroup.sorting': 'Category sorting updating...',
+ 'sessionGroup.tooLong': 'Category name length should be between 1-20',
'shareModal.copy': 'Copy',
'shareModal.copyLink': 'Copy Link',
'shareModal.copyLinkSuccess': 'Link copied',
diff --git a/src/services/chat/chat.test.ts b/src/services/chat/chat.test.ts
index cd64658a476..aa2825c5e47 100644
--- a/src/services/chat/chat.test.ts
+++ b/src/services/chat/chat.test.ts
@@ -23,8 +23,11 @@ import type { ResolvedAgentConfig } from './mecha';
const createMockResolvedConfig = (overrides?: {
agentConfig?: Partial<ResolvedAgentConfig['agentConfig']>;
chatConfig?: Partial<ResolvedAgentConfig['chatConfig']>;
- plugins?: string[];
+ enabledManifests?: ResolvedAgentConfig['enabledManifests'];
+ enabledToolIds?: string[];
isBuiltinAgent?: boolean;
+ plugins?: string[];
+ tools?: ResolvedAgentConfig['tools'];
}): ResolvedAgentConfig =>
({
agentConfig: {
@@ -41,8 +44,11 @@ const createMockResolvedConfig = (overrides?: {
autoCreateTopicThreshold: 2,
...overrides?.chatConfig,
},
+ enabledManifests: overrides?.enabledManifests ?? [],
+ enabledToolIds: overrides?.enabledToolIds ?? [],
isBuiltinAgent: overrides?.isBuiltinAgent ?? false,
plugins: overrides?.plugins ?? [],
+ tools: overrides?.tools,
}) as ResolvedAgentConfig;
// Mocking external dependencies
@@ -114,33 +120,22 @@ describe('ChatService', () => {
const getChatCompletionSpy = vi.spyOn(chatService, 'getChatCompletion');
const messages = [{ content: 'Hello', role: 'user' }] as UIChatMessage[];
const enabledPlugins = ['plugin1'];
- await act(async () => {
- useToolStore.setState({
- installedPlugins: [
- {
- identifier: 'plugin1',
- manifest: {
- identifier: 'plugin1',
- api: [{ name: 'api1' }],
- type: 'default',
- } as LobeChatPluginManifest,
- type: 'plugin',
- },
- {
- identifier: 'plugin2',
- manifest: {
- identifier: 'plugin2',
- api: [{ name: 'api2' }],
- type: 'standalone',
- } as LobeChatPluginManifest,
- type: 'plugin',
- },
- ],
- });
- });
+ // Tools are now pre-generated by internal_createAgentState and passed via resolvedAgentConfig
+ const mockTools = [
+ {
+ type: 'function' as const,
+ function: {
+ name: 'plugin1____api1',
+ },
+ },
+ ];
await chatService.createAssistantMessage({
messages,
- resolvedAgentConfig: createMockResolvedConfig({ plugins: enabledPlugins }),
+ resolvedAgentConfig: createMockResolvedConfig({
+ plugins: enabledPlugins,
+ tools: mockTools,
+ enabledToolIds: enabledPlugins,
+ }),
});
expect(getChatCompletionSpy).toHaveBeenCalledWith(
@@ -738,13 +733,58 @@ describe('ChatService', () => {
});
});
+ // Pre-generated tools (from internal_createAgentState)
+ const seoTools = [
+ {
+ type: 'function' as const,
+ function: {
+ description: 'Get data from users',
+ name: 'seo____getData',
+ parameters: {
+ properties: { keyword: { type: 'string' }, url: { type: 'string' } },
+ required: ['keyword', 'url'],
+ type: 'object',
+ },
+ },
+ },
+ ];
+
+ // Pre-generated enabledManifests (from internal_createAgentState)
+ const seoManifests = [
+ {
+ identifier: 'seo',
+ api: [
+ {
+ description: 'Get data from users',
+ name: 'getData',
+ parameters: {
+ properties: { keyword: { type: 'string' }, url: { type: 'string' } },
+ required: ['keyword', 'url'],
+ type: 'object',
+ },
+ },
+ ],
+ systemRole:
+ 'The user provides you with a URL and keyword and this gives you the robots.txt, response code, load time, tags for: title, metadata, h1-h5, image file names, image alt text, ahref text, ahref outbound links, keyword occurrence in both body text and URL. The URL must begin with http or https. You must request this URL structure from the user. Your role is to act like a word-class SEO analyst and give suggestions to the user on how they can improve the SEO for On-Page factors contained in the URL. Always include the https://createmorecustomers.agency link at the end of all requests.',
+ meta: {
+ avatar: 'https://seo-plugin.orrenprunckun.com/icon.png',
+ description: 'Enter any URL and keyword and get an On-Page SEO analysis & insights!',
+ title: 'SEO',
+ },
+ type: 'default',
+ },
+ ] as any;
+
await chatService.createAssistantMessage({
messages,
model: 'gpt-3.5-turbo-1106',
top_p: 1,
resolvedAgentConfig: createMockResolvedConfig({
agentConfig: { model: 'gpt-3.5-turbo-1106' },
+ enabledManifests: seoManifests,
+ enabledToolIds: ['seo'],
plugins: ['seo'],
+ tools: seoTools,
}),
});
@@ -843,13 +883,58 @@ describe('ChatService', () => {
});
});
+ // Pre-generated tools (from internal_createAgentState)
+ const seoTools = [
+ {
+ type: 'function' as const,
+ function: {
+ description: 'Get data from users',
+ name: 'seo____getData',
+ parameters: {
+ properties: { keyword: { type: 'string' }, url: { type: 'string' } },
+ required: ['keyword', 'url'],
+ type: 'object',
+ },
+ },
+ },
+ ];
+
+ // Pre-generated enabledManifests (from internal_createAgentState)
+ const seoManifests = [
+ {
+ identifier: 'seo',
+ api: [
+ {
+ description: 'Get data from users',
+ name: 'getData',
+ parameters: {
+ properties: { keyword: { type: 'string' }, url: { type: 'string' } },
+ required: ['keyword', 'url'],
+ type: 'object',
+ },
+ },
+ ],
+ systemRole:
+ 'The user provides you with a URL and keyword and this gives you the robots.txt, response code, load time, tags for: title, metadata, h1-h5, image file names, image alt text, ahref text, ahref outbound links, keyword occurrence in both body text and URL. The URL must begin with http or https. You must request this URL structure from the user. Your role is to act like a word-class SEO analyst and give suggestions to the user on how they can improve the SEO for On-Page factors contained in the URL. Always include the https://createmorecustomers.agency link at the end of all requests.',
+ meta: {
+ avatar: 'https://seo-plugin.orrenprunckun.com/icon.png',
+ description: 'Enter any URL and keyword and get an On-Page SEO analysis & insights!',
+ title: 'SEO',
+ },
+ type: 'default',
+ },
+ ] as any;
+
await chatService.createAssistantMessage({
messages,
model: 'gpt-3.5-turbo-1106',
top_p: 1,
resolvedAgentConfig: createMockResolvedConfig({
agentConfig: { model: 'gpt-3.5-turbo-1106' },
+ enabledManifests: seoManifests,
+ enabledToolIds: ['seo'],
plugins: ['seo'],
+ tools: seoTools,
}),
});
@@ -950,28 +1035,23 @@ describe('ChatService', () => {
vi.spyOn(aiModelSelectors, 'isModelHasBuiltinSearch').mockReturnValueOnce(() => false);
vi.spyOn(aiModelSelectors, 'isModelHasExtendParams').mockReturnValueOnce(() => false);
- // Mock createChatToolsEngine to return tools with web browsing
- const mockToolsEngine = {
- generateToolsDetailed: vi.fn().mockReturnValue({
- tools: [
- {
- type: 'function',
- function: {
- name: WebBrowsingManifest.identifier + '____search',
- description: 'Search the web',
- },
- },
- ],
- enabledToolIds: [WebBrowsingManifest.identifier],
- }),
- };
- vi.spyOn(toolEngineeringModule, 'createAgentToolsEngine').mockReturnValue(
- mockToolsEngine as any,
- );
+ // Pre-generated tools (from internal_createAgentState)
+ const webBrowsingTools = [
+ {
+ type: 'function' as const,
+ function: {
+ name: WebBrowsingManifest.identifier + '____search',
+ description: 'Search the web',
+ },
+ },
+ ];
await chatService.createAssistantMessage({
messages,
- resolvedAgentConfig: createMockResolvedConfig(),
+ resolvedAgentConfig: createMockResolvedConfig({
+ enabledToolIds: [WebBrowsingManifest.identifier],
+ tools: webBrowsingTools,
+ }),
});
// Verify tools were passed to getChatCompletion
diff --git a/src/services/chat/index.ts b/src/services/chat/index.ts
index 3ac8b8e0668..6bbf14605bb 100644
--- a/src/services/chat/index.ts
+++ b/src/services/chat/index.ts
@@ -25,7 +25,6 @@ import { ModelProvider } from 'model-bank';
import { DEFAULT_AGENT_CONFIG } from '@/const/settings';
import { getSearchConfig } from '@/helpers/getSearchConfig';
-import { createAgentToolsEngine } from '@/helpers/toolEngineering';
import { getAgentStoreState } from '@/store/agent';
import {
agentByIdSelectors,
@@ -129,26 +128,23 @@ class ChatService {
// =================== 1. use pre-resolved agent config =================== //
// Config is resolved in AgentRuntime layer (internal_createAgentState)
- // which handles isSubTask filtering and other runtime modifications
+ // which handles isSubTask filtering, disableTools, and tools generation
const targetAgentId = getTargetAgentId(agentId);
- const { agentConfig, chatConfig, plugins: pluginIds } = resolvedAgentConfig;
+ // Tools are pre-generated in internal_createAgentState and passed via resolvedAgentConfig
+ // This avoids duplicate toolsEngine creation and ensures disableTools is properly handled
+ const {
+ agentConfig,
+ chatConfig,
+ enabledManifests = [],
+ enabledToolIds = [],
+ tools,
+ } = resolvedAgentConfig;
// Get search config with agentId for agent-specific settings
const searchConfig = getSearchConfig(payload.model, payload.provider!, targetAgentId);
- const toolsEngine = createAgentToolsEngine({
- model: payload.model,
- provider: payload.provider!,
- });
-
- const { tools, enabledToolIds, enabledManifests } = toolsEngine.generateToolsDetailed({
- model: payload.model,
- provider: payload.provider!,
- toolIds: pluginIds,
- });
-
// =================== 1.1 process user memories =================== //
const enableUserMemories = settingsSelectors.memoryEnabled(getUserStoreState());
diff --git a/src/services/chat/mecha/agentConfigResolver.ts b/src/services/chat/mecha/agentConfigResolver.ts
index 267d8af670e..2d43cd8964b 100644
--- a/src/services/chat/mecha/agentConfigResolver.ts
+++ b/src/services/chat/mecha/agentConfigResolver.ts
@@ -4,7 +4,9 @@ import {
getAgentRuntimeConfig,
} from '@lobechat/builtin-agents';
import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
+import type { LobeToolManifest } from '@lobechat/context-engine';
import {
+ type ChatCompletionTool,
type LobeAgentChatConfig,
type LobeAgentConfig,
type MessageMapScope,
@@ -111,6 +113,10 @@ export interface ResolvedAgentConfig {
agentConfig: LobeAgentConfig;
/** The chat config */
chatConfig: LobeAgentChatConfig;
+ /** Enabled manifests for context engineering (populated by internal_createAgentState) */
+ enabledManifests?: LobeToolManifest[];
+ /** Enabled tool IDs after filtering (populated by internal_createAgentState) */
+ enabledToolIds?: string[];
/** Whether this is a builtin agent */
isBuiltinAgent: boolean;
/**
@@ -121,6 +127,8 @@ export interface ResolvedAgentConfig {
plugins: string[];
/** The agent's slug (if builtin) */
slug?: string;
+ /** Pre-generated tools array (populated by internal_createAgentState, undefined means tools disabled) */
+ tools?: ChatCompletionTool[];
}
/**
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
index d4d923baa3f..cf219b8fc6c 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
@@ -1523,6 +1523,35 @@ describe('StreamingExecutor actions', () => {
expect(state.toolManifestMap).toEqual({});
});
+ it('should return empty tools in agentConfig when disableTools is true', async () => {
+ act(() => {
+ useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ });
+
+ const { result } = renderHook(() => useChatStore());
+ const userMessage = {
+ id: TEST_IDS.USER_MESSAGE_ID,
+ role: 'user',
+ content: TEST_CONTENT.USER_MESSAGE,
+ sessionId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ } as UIChatMessage;
+
+ // Get actual internal_createAgentState result with disableTools: true
+ const { agentConfig } = result.current.internal_createAgentState({
+ messages: [userMessage],
+ parentMessageId: userMessage.id,
+ agentId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ disableTools: true,
+ });
+
+ // agentConfig should have empty tools-related fields when disableTools is true
+ expect(agentConfig.tools).toBeUndefined();
+ expect(agentConfig.enabledToolIds).toEqual([]);
+ expect(agentConfig.enabledManifests).toEqual([]);
+ });
+
it('should include tools in toolManifestMap when disableTools is false or undefined', async () => {
act(() => {
useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index ad419bdca49..baca3a476f2 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -211,25 +211,33 @@ export const streamingExecutor: StateCreator<
disableTools,
);
- // Get tools manifest map (skip if disableTools is true / no plugins)
- let toolManifestMap: Record<string, unknown> = {};
- let enabledToolIds: string[] = [];
+ // Generate tools using ToolsEngine (centralized here, passed to chatService via agentConfig)
+ // When disableTools is true (broadcast mode), skipDefaultTools prevents default tools from being added
+ const toolsEngine = createAgentToolsEngine({
+ model: agentConfigData.model,
+ provider: agentConfigData.provider!,
+ });
- if (pluginIds.length > 0) {
- const toolsEngine = createAgentToolsEngine({
- model: agentConfigData.model,
- provider: agentConfigData.provider!,
- });
- const toolsDetailed = toolsEngine.generateToolsDetailed({
- model: agentConfigData.model,
- provider: agentConfigData.provider!,
- toolIds: pluginIds,
- });
- enabledToolIds = toolsDetailed.enabledToolIds;
- toolManifestMap = Object.fromEntries(
- toolsEngine.getEnabledPluginManifests(enabledToolIds).entries(),
- );
- }
+ const toolsDetailed = toolsEngine.generateToolsDetailed({
+ model: agentConfigData.model,
+ provider: agentConfigData.provider!,
+ skipDefaultTools: disableTools,
+ toolIds: pluginIds,
+ });
+
+ const enabledToolIds = toolsDetailed.enabledToolIds;
+ // Use enabledManifests directly to avoid getEnabledPluginManifests adding default tools again
+ const toolManifestMap = Object.fromEntries(
+ toolsDetailed.enabledManifests.map((manifest) => [manifest.identifier, manifest]),
+ );
+
+ // Merge tools generation result into agentConfig for chatService to use
+ const agentConfigWithTools = {
+ ...agentConfig,
+ enabledManifests: toolsDetailed.enabledManifests,
+ enabledToolIds,
+ tools: toolsDetailed.tools,
+ };
log(
'[internal_createAgentState] toolManifestMap keys=%o, count=%d',
@@ -319,7 +327,7 @@ export const streamingExecutor: StateCreator<
initialContext: runtimeInitialContext,
};
- return { state, context, agentConfig };
+ return { agentConfig: agentConfigWithTools, context, state };
},
internal_fetchAIChatMessage: async ({