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: support chat mode and redesign chat input action bar (#14774)

Arvin Xue0d20e86fc83
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 83b73679e35..2c205755264 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -42,6 +42,16 @@
"builtinCopilot": "Built-in Copilot",
"chatList.expandMessage": "Expand Message",
"chatList.longMessageDetail": "View Details",
+ "chatMode.agent": "Agent",
+ "chatMode.agentCap.env": "Runtime env",
+ "chatMode.agentCap.files": "File access",
+ "chatMode.agentCap.memory": "Memory",
+ "chatMode.agentCap.tools": "Tool calls",
+ "chatMode.agentCap.web": "Web search",
+ "chatMode.agentDesc": "Agent can use tools and environment to complete tasks automatically",
+ "chatMode.chat": "Chat",
+ "chatMode.chatDesc": "No runtime environment or autonomy; uses fewer tokens",
+ "chatMode.select": "Switch Mode",
"claudeCodeInstallGuide.actions.openDocs": "Open Install Guide",
"claudeCodeInstallGuide.actions.openSystemTools": "Open System Tools",
"claudeCodeInstallGuide.afterInstall": "After installing, run Claude Code once to sign in, then retry your message or click Re-detect in System Tools.",
@@ -60,6 +70,7 @@
"cliAuthGuide.runCommand": "Run this in Terminal",
"cliAuthGuide.title": "Sign in to {{name}}",
"cliRateLimitGuide.actions.openSystemTools": "Open System Tools",
+ "cliRateLimitGuide.actions.retry": "Retry",
"cliRateLimitGuide.afterReset": "Wait until the reset time, then retry your message. If you are using API authorization, you can also check your provider quota and billing status.",
"cliRateLimitGuide.desc": "{{name}} has reached its current usage limit and cannot continue this run right now.",
"cliRateLimitGuide.limitType": "Limit window",
@@ -142,7 +153,7 @@
"extendParams.title": "Model Extension Features",
"extendParams.urlContext.desc": "When enabled, web links will be automatically parsed to retrieve the actual webpage context content",
"extendParams.urlContext.title": "Extract Webpage Link Content",
- "followUpPlaceholder": "Follow up. @ to assign tasks to other agents.",
+ "followUpPlaceholder": "Follow up.",
"followUpPlaceholderHeterogeneous": "Follow up.",
"group.desc": "Move a task forward with multiple Agents in one shared space.",
"group.memberTooltip": "There are {{count}} members in the group",
@@ -224,6 +235,8 @@
"knowledgeBase.allFiles": "All Files",
"knowledgeBase.allLibraries": "All Libraries",
"knowledgeBase.disabled": "Library chat isn’t available in this deployment. Switch to a server-side database, or use {{cloud}}.",
+ "knowledgeBase.files": "Files",
+ "knowledgeBase.libraries": "Libraries",
"knowledgeBase.library.action.add": "Add",
"knowledgeBase.library.action.detail": "Details",
"knowledgeBase.library.action.remove": "Remove",
@@ -327,6 +340,15 @@
"pageSelection.reference": "Selected Text",
"pin": "Pin",
"pinOff": "Unpin",
+ "plus.addSkills": "Add Skills...",
+ "plus.search.appSearch": "Smart Search",
+ "plus.search.appSearchDesc": "LobeHub optimized search service, delivering best retrieval results.",
+ "plus.search.modelSearch": "Provider Search",
+ "plus.search.modelSearchDesc": "May cause unexpected behavior when enabled, not recommended.",
+ "plus.search.off": "Off",
+ "plus.search.offDesc": "",
+ "plus.title": "Add",
+ "plus.tooltip": "Add files, skills, and more context...",
"rag.referenceChunks": "Reference Source",
"rag.userQuery.actions.delete": "Delete Query Rewrite",
"rag.userQuery.actions.regenerate": "Regenerate Query",
@@ -358,6 +380,8 @@
"searchAgents": "Search agents...",
"selectedAgents": "Selected agents",
"sendPlaceholder": "Ask, create, or start a task, <hotkey><hotkey/>",
+ "sendPlaceholderChat": "Ask, search, or brainstorm, <hotkey><hotkey/>",
+ "sendPlaceholderChatWithAgentAssignment": "Ask, search, or brainstorm. @ to bring in other agents.",
"sendPlaceholderHeterogeneous": "Describe a task or ask a question to {{name}}",
"sendPlaceholderWithAgentAssignment": "Ask, create, or start a task. @ to assign tasks to other agents.",
"sessionGroup.config": "Category Management",
@@ -735,6 +759,7 @@
"untitledAgent": "Untitled Agent",
"untitledGroup": "Untitled Group",
"updateAgent": "Update Agent Information",
+ "upload.action.fileOrImageUpload": "Upload File or Image",
"upload.action.fileUpload": "Upload File",
"upload.action.folderUpload": "Upload Folder",
"upload.action.imageDisabled": "The current model does not support visual recognition. Please switch models to use this feature.",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 70390a294d7..3c83394e794 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -899,7 +899,12 @@
"tab.uploadZip": "Upload Zip",
"tab.uploadZip.desc": "Upload a local .zip or .skill file",
"tab.usage": "Usage",
+ "tools.activation.auto": "Auto",
+ "tools.activation.auto.desc": "Smart",
+ "tools.activation.pinned": "Pinned",
+ "tools.activation.pinned.desc": "Always On",
"tools.add": "Add Skill",
+ "tools.builtins.configure": "Configure",
"tools.builtins.find-skills.description": "Helps users discover and install agent skills when they ask \"how do I do X\", \"find a skill for X\", or want to extend capabilities",
"tools.builtins.find-skills.title": "Find Skills",
"tools.builtins.groupName": "Built-ins",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index d10639115ac..bcc76778d11 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -42,6 +42,16 @@
"builtinCopilot": "内置 Copilot",
"chatList.expandMessage": "展开消息",
"chatList.longMessageDetail": "查看详情",
+ "chatMode.agent": "智能体",
+ "chatMode.agentCap.env": "运行环境",
+ "chatMode.agentCap.files": "文件访问",
+ "chatMode.agentCap.memory": "记忆",
+ "chatMode.agentCap.tools": "工具调用",
+ "chatMode.agentCap.web": "联网搜索",
+ "chatMode.agentDesc": "智能体可以使用工具和运行环境自动完成任务",
+ "chatMode.chat": "对话",
+ "chatMode.chatDesc": "不启用运行环境和自主执行,更省 Token",
+ "chatMode.select": "切换模式",
"claudeCodeInstallGuide.actions.openDocs": "打开安装指南",
"claudeCodeInstallGuide.actions.openSystemTools": "打开系统工具",
"claudeCodeInstallGuide.afterInstall": "安装完成后,请先运行一次 Claude Code 完成登录,然后重试刚才的消息,或在系统工具中点击“重新检测”。",
@@ -60,6 +70,7 @@
"cliAuthGuide.runCommand": "在终端执行",
"cliAuthGuide.title": "登录 {{name}}",
"cliRateLimitGuide.actions.openSystemTools": "打开系统工具",
+ "cliRateLimitGuide.actions.retry": "重试",
"cliRateLimitGuide.afterReset": "请等到重置时间后再重试这条消息。如果你当前使用的是 API 授权,也可以检查对应提供商的额度和计费状态。",
"cliRateLimitGuide.desc": "{{name}} 已达到当前使用上限,这次运行暂时无法继续。",
"cliRateLimitGuide.limitType": "限制周期",
@@ -142,7 +153,7 @@
"extendParams.title": "模型扩展功能",
"extendParams.urlContext.desc": "开启后会自动解析网页链接,提取网页内容作为上下文",
"extendParams.urlContext.title": "提取网页链接内容",
- "followUpPlaceholder": "继续跟进。使用 @ 分配任务给其他智能体。",
+ "followUpPlaceholder": "继续跟进。",
"followUpPlaceholderHeterogeneous": "继续跟进。",
"group.desc": "在同一对话空间,让多个助理一起推进任务",
"group.memberTooltip": "群组内有 {{count}} 名成员",
@@ -224,6 +235,8 @@
"knowledgeBase.allFiles": "全部文件",
"knowledgeBase.allLibraries": "全部资源库",
"knowledgeBase.disabled": "当前部署模式不支持资源库对话。可切换到服务端数据库部署,或使用 {{cloud}} 服务",
+ "knowledgeBase.files": "文件",
+ "knowledgeBase.libraries": "资源库",
"knowledgeBase.library.action.add": "添加",
"knowledgeBase.library.action.detail": "详情",
"knowledgeBase.library.action.remove": "移除",
@@ -327,6 +340,15 @@
"pageSelection.reference": "选中文本",
"pin": "置顶",
"pinOff": "取消置顶",
+ "plus.addSkills": "添加技能...",
+ "plus.search.appSearch": "智能检索",
+ "plus.search.appSearchDesc": "LobeHub 专属调优的搜索服务,检索效果最佳。",
+ "plus.search.modelSearch": "Provider 内置搜索",
+ "plus.search.modelSearchDesc": "开启后往往会导致异常表现,不建议使用。",
+ "plus.search.off": "关闭",
+ "plus.search.offDesc": "",
+ "plus.title": "添加",
+ "plus.tooltip": "添加文件、技能和更多上下文...",
"rag.referenceChunks": "引用源",
"rag.userQuery.actions.delete": "删除 Query 重写",
"rag.userQuery.actions.regenerate": "重新生成 Query",
@@ -358,6 +380,8 @@
"searchAgents": "搜索助理…",
"selectedAgents": "已选助理",
"sendPlaceholder": "从任何想法开始… <hotkey><hotkey/>",
+ "sendPlaceholderChat": "提问、搜索或头脑风暴… <hotkey><hotkey/>",
+ "sendPlaceholderChatWithAgentAssignment": "提问、搜索或头脑风暴。@ 召唤其他智能体加入。",
"sendPlaceholderHeterogeneous": "描述任务或向 {{name}} 提问",
"sendPlaceholderWithAgentAssignment": "提问、创建或开始任务。使用 @ 分配任务给其他智能体。",
"sessionGroup.config": "分类管理",
@@ -735,6 +759,7 @@
"untitledAgent": "未命名助理",
"untitledGroup": "未命名群组",
"updateAgent": "更新助理信息",
+ "upload.action.fileOrImageUpload": "上传文件或图片",
"upload.action.fileUpload": "上传文件",
"upload.action.folderUpload": "上传文件夹",
"upload.action.imageDisabled": "当前模型不支持视觉识别。请切换模型后再试",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 61fbbd4d73a..71dec2bf85e 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -899,7 +899,12 @@
"tab.uploadZip": "上传 Zip",
"tab.uploadZip.desc": "上传本地 .zip 或 .skill 文件",
"tab.usage": "用量",
+ "tools.activation.auto": "自动",
+ "tools.activation.auto.desc": "智能调用",
+ "tools.activation.pinned": "固定启用",
+ "tools.activation.pinned.desc": "始终注入",
"tools.add": "集成技能",
+ "tools.builtins.configure": "配置",
"tools.builtins.find-skills.description": "当用户询问“我该如何做 X”、“帮我找一个能做 X 的技能”或希望扩展能力时,帮助用户发现并安装助手技能",
"tools.builtins.find-skills.title": "查找技能",
"tools.builtins.groupName": "内置技能",
diff --git a/packages/agent-tracing/src/viewer/index.ts b/packages/agent-tracing/src/viewer/index.ts
index 129e8415cf0..e9b1ebccbd6 100644
--- a/packages/agent-tracing/src/viewer/index.ts
+++ b/packages/agent-tracing/src/viewer/index.ts
@@ -63,6 +63,7 @@ export function resolveCeSnapshot(
/** @deprecated Use resolveCeSnapshot instead. */
export const resolveCeEvent = resolveCeSnapshot;
+
/**
* Resolve messages for a step, supporting both legacy (full) and incremental (delta) formats.
*/
diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.ts
index 16675f89820..bec0ad2ae3e 100644
--- a/packages/builtin-tools/src/index.ts
+++ b/packages/builtin-tools/src/index.ts
@@ -66,6 +66,24 @@ export const manualModeExcludeToolIds = [
SkillStoreManifest.identifier,
];
+/**
+ * Tool IDs allowed when the agent runs in chat mode
+ * (`chatConfig.enableAgentMode === false`). Each one still passes through
+ * its own runtime gate (e.g. knowledge base requires `hasEnabledKnowledgeBases`,
+ * memory requires the global memory setting, web-browsing requires search
+ * enabled) — this list is the strict outer whitelist.
+ *
+ * In chat mode, both the server `createServerAgentToolsEngine` and the
+ * frontend `createAgentToolsEngine` build their rules from ONLY these
+ * identifiers, drop user plugins / `alwaysOnToolIds` entirely, and disable
+ * `allowExplicitActivation` so the activator can't smuggle other tools in.
+ */
+export const chatModeAllowedToolIds = [
+ KnowledgeBaseManifest.identifier,
+ MemoryManifest.identifier,
+ WebBrowsingManifest.identifier,
+];
+
/**
* Tool IDs whose enabled state is decided by runtime / system conditions
* (e.g. cloud runtime, agent has documents attached, knowledge base configured,
diff --git a/packages/const/src/settings/agent.ts b/packages/const/src/settings/agent.ts
index 60f2412c333..3b6979f248c 100644
--- a/packages/const/src/settings/agent.ts
+++ b/packages/const/src/settings/agent.ts
@@ -25,6 +25,7 @@ export const DEFAULT_AGENT_SEARCH_FC_MODEL = {
export const DEFAULT_AGENT_CHAT_CONFIG: LobeAgentChatConfig = {
autoCreateTopicThreshold: 2,
+ enableAgentMode: true,
enableAutoCreateTopic: true,
enableCompressHistory: true,
enableContextCompression: true,
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
index f63e1835e0c..e23f1a40940 100644
--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -138,6 +138,7 @@ export class MessagesEngine {
provider,
systemRole,
inputTemplate,
+ enableAgentMode,
enableHistoryCount,
historyCount,
forceFinish,
@@ -173,7 +174,6 @@ export class MessagesEngine {
} = this.params;
const isAgentBuilderEnabled = !!agentBuilderContext;
- const isAgentManagementEnabled = !!agentManagementContext;
const isGroupAgentBuilderEnabled = !!groupAgentBuilderContext;
const isAgentGroupEnabled = agentGroup?.agentMap && Object.keys(agentGroup.agentMap).length > 0;
@@ -183,7 +183,14 @@ export class MessagesEngine {
const hasSelectedSkills = (selectedSkills?.length ?? 0) > 0;
const hasSelectedTools = (selectedTools?.length ?? 0) > 0;
- const hasAgentDocuments = !!agentDocuments && agentDocuments.length > 0;
+ // Chat mode (`enableAgentMode === false`) suppresses agentic-only injectors:
+ // skill discovery (<available_skills>), agent documents, and the
+ // agent-management context (<current_agent> + <available_agents>).
+ // Anything else — system role, knowledge bases, memory, web-browsing tool
+ // prompts — remains untouched.
+ const isAgentMode = enableAgentMode !== false;
+ const isAgentManagementEnabled = !!agentManagementContext && isAgentMode;
+ const hasAgentDocuments = !!agentDocuments && agentDocuments.length > 0 && isAgentMode;
// Page editor is enabled if either direct pageContentContext or initialContext.pageEditor is provided
const isPageEditorEnabled = !!pageContentContext || !!initialContext?.pageEditor;
const hasActiveTopicDocument = !!initialContext?.activeTopicDocument;
@@ -236,9 +243,12 @@ export class MessagesEngine {
}),
// System date
new SystemDateProvider({ enabled: isSystemDateEnabled, timezone }),
- // Skill context (available skills list + activated skill content)
+ // Skill context (available skills list + activated skill content).
+ // Disabled in chat mode — pairs with the tools-engine gate so the LLM
+ // sees neither the manifests nor the discovery prompt.
new SkillContextProvider({
- enabled: !!(skillsConfig?.enabledSkills && skillsConfig.enabledSkills.length > 0),
+ enabled:
+ isAgentMode && !!(skillsConfig?.enabledSkills && skillsConfig.enabledSkills.length > 0),
enabledSkills: skillsConfig?.enabledSkills,
}),
// Tool system role (tool manifests and API definitions)
diff --git a/packages/context-engine/src/engine/messages/types.ts b/packages/context-engine/src/engine/messages/types.ts
index 6f1636486fa..be6dc96ba09 100644
--- a/packages/context-engine/src/engine/messages/types.ts
+++ b/packages/context-engine/src/engine/messages/types.ts
@@ -223,6 +223,13 @@ export interface MessagesEngineParams {
timezone?: string | null;
// ========== Agent configuration ==========
+ /**
+ * Whether the agent runs in agent mode. When explicitly `false` (chat mode)
+ * the engine force-disables agentic-only injectors — skills (`<available_skills>`)
+ * and agent documents — regardless of whether their data is supplied.
+ * Undefined / true → agent mode (default).
+ */
+ enableAgentMode?: boolean;
/** Whether to enable history message count limit */
enableHistoryCount?: boolean;
/** Force finish flag: when true, injects summary prompt for max-steps completion */
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index ee8611563b7..539c0304407 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -1,4 +1,9 @@
-import type { ChatTopicMetadata, DBMessageItem, TopicRankItem } from '@lobechat/types';
+import type {
+ ChatTopicMetadata,
+ ChatTopicStatus,
+ DBMessageItem,
+ TopicRankItem,
+} from '@lobechat/types';
import type { SQL } from 'drizzle-orm';
import { and, count, desc, eq, gt, gte, inArray, isNull, lte, ne, not, or, sql } from 'drizzle-orm';
@@ -106,7 +111,7 @@ export class TopicModel {
excludeStatuses && excludeStatuses.length > 0
? or(
isNull(topics.status),
- not(inArray(topics.status, excludeStatuses as ('active' | 'completed' | 'archived')[])),
+ not(inArray(topics.status, excludeStatuses as ChatTopicStatus[])),
)
: undefined;
diff --git a/packages/database/src/schemas/topic.ts b/packages/database/src/schemas/topic.ts
index 0180572cebb..db8fb18d330 100644
--- a/packages/database/src/schemas/topic.ts
+++ b/packages/database/src/schemas/topic.ts
@@ -42,7 +42,9 @@ export const topics = pgTable(
metadata: jsonb('metadata').$type<ChatTopicMetadata | undefined>(),
trigger: text('trigger'), // 'cron' | 'chat' | 'api' | 'eval' - topic creation trigger source
mode: text('mode'), // 'temp' | 'test' | 'default' - topic usage scenario
- status: text('status', { enum: ['active', 'completed', 'archived'] }),
+ status: text('status', {
+ enum: ['active', 'running', 'paused', 'failed', 'completed', 'archived'],
+ }),
completedAt: timestamptz('completed_at'),
...timestamps,
},
diff --git a/packages/types/src/agent/chatConfig.ts b/packages/types/src/agent/chatConfig.ts
index 9d8a8f7c3ba..51958ac5b1d 100644
--- a/packages/types/src/agent/chatConfig.ts
+++ b/packages/types/src/agent/chatConfig.ts
@@ -43,6 +43,12 @@ export interface LobeAgentChatConfig extends AgentMemoryChatConfig, AgentSelfIte
* Whether to enable adaptive thinking (Claude Opus 4.6)
*/
enableAdaptiveThinking?: boolean;
+ /**
+ * Whether the agent runs in agent mode (full tool access) vs chat mode
+ * (only runtime-managed tools like KB / memory / web-browsing).
+ * Treat undefined as `true` — agent mode is the default.
+ */
+ enableAgentMode?: boolean;
enableAutoCreateTopic?: boolean;
/**
* Whether to auto-scroll during AI streaming output
@@ -200,6 +206,7 @@ export const AgentChatConfigSchema = z
disableContextCaching: z.boolean().optional(),
effort: z.enum(['low', 'medium', 'high', 'max']).optional(),
enableAdaptiveThinking: z.boolean().optional(),
+ enableAgentMode: z.boolean().optional(),
enableAutoCreateTopic: z.boolean().optional(),
enableAutoScrollOnStreaming: z.boolean().optional(),
enableCompressHistory: z.boolean().optional(),
diff --git a/packages/types/src/agent/item.ts b/packages/types/src/agent/item.ts
index b27bc02f308..60de0376303 100644
--- a/packages/types/src/agent/item.ts
+++ b/packages/types/src/agent/item.ts
@@ -24,7 +24,6 @@ export interface LobeAgentConfig {
* Used to save the complete state of the rich text editor, including special nodes like mention
*/
editorData?: any;
- enableAgentMode?: boolean;
fewShots?: FewShots;
files?: FileItem[];
id?: string;
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index ddf094bdb92..387bbe687d0 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -168,7 +168,7 @@ export interface ChatTopicSummary {
provider: string;
}
-export type ChatTopicStatus = 'active' | 'completed' | 'archived';
+export type ChatTopicStatus = 'active' | 'running' | 'paused' | 'failed' | 'completed' | 'archived';
export interface ChatTopic extends Omit<BaseDataModel, 'meta'> {
completedAt?: Date | null;
diff --git a/src/features/ChatInput/ActionBar/AgentMode/index.tsx b/src/features/ChatInput/ActionBar/AgentMode/index.tsx
index 7519fa641a2..519555997c8 100644
--- a/src/features/ChatInput/ActionBar/AgentMode/index.tsx
+++ b/src/features/ChatInput/ActionBar/AgentMode/index.tsx
@@ -1,38 +1,220 @@
-import { ActionIcon } from '@lobehub/ui';
-import { Bot } from 'lucide-react';
-import { memo } from 'react';
+import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import {
+ ChevronDownIcon,
+ FolderIcon,
+ InfinityIcon,
+ MessageCircleIcon,
+ SearchIcon,
+ TerminalIcon,
+ WrenchIcon,
+} from 'lucide-react';
+import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
+import { useToggleAgentMode } from '@/features/ChatInput/hooks/useToggleAgentMode';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
-const AgentModeToggle = memo(() => {
+const styles = createStaticStyles(({ css }) => ({
+ activeOption: css`
+ background: ${cssVar.colorFillSecondary};
+ `,
+ agentTooltip: css`
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ min-width: 160px;
+ `,
+ agentTooltipCap: css`
+ display: flex;
+ gap: 6px;
+ align-items: center;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ agentTooltipTitle: css`
+ margin-block-end: 2px;
+ font-size: 12px;
+ font-weight: 600;
+ color: ${cssVar.colorText};
+ `,
+ button: css`
+ cursor: pointer;
+
+ display: flex;
+ gap: 6px;
+ align-items: center;
+
+ height: 28px;
+ padding-inline: 8px;
+ border-radius: 999px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorFillTertiary};
+
+ transition: all 0.2s;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillSecondary};
+ }
+ `,
+ option: css`
+ cursor: pointer;
+
+ width: 100%;
+ padding-block: 10px;
+ padding-inline: 8px;
+ border-radius: ${cssVar.borderRadius};
+
+ transition: background-color 0.2s;
+
+ &:hover {
+ background: ${cssVar.colorFillSecondary};
+ }
+ `,
+ optionDesc: css`
+ font-size: 12px;
+ line-height: 1.4;
+ color: ${cssVar.colorTextDescription};
+ `,
+ optionIcon: css`
+ flex-shrink: 0;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadius};
+ background: ${cssVar.colorBgElevated};
+ `,
+ optionTitle: css`
+ font-size: 14px;
+ font-weight: 500;
+ line-height: 1.4;
+ color: ${cssVar.colorText};
+ `,
+}));
+
+const AGENT_CAPS = [
+ { icon: WrenchIcon, key: 'tools' },
+ { icon: SearchIcon, key: 'web' },
+ { icon: FolderIcon, key: 'files' },
+ { icon: TerminalIcon, key: 'env' },
+] as const;
+
+const AgentMode = memo(() => {
const { t } = useTranslation('chat');
const agentId = useAgentId();
- const [enableAgentMode, updateAgentConfigById] = useAgentStore((s) => [
- agentByIdSelectors.getAgentEnableModeById(agentId)(s),
- s.updateAgentConfigById,
- ]);
+ const toggleAgentMode = useToggleAgentMode();
+ const [open, setOpen] = useState(false);
- const handleToggle = (checked: boolean) => {
- updateAgentConfigById(agentId, { enableAgentMode: checked });
- };
+ const enableAgentMode = useAgentStore(agentByIdSelectors.getAgentEnableModeById(agentId));
+
+ const currentMode = enableAgentMode ? 'agent' : 'chat';
+ const CurrentIcon = enableAgentMode ? InfinityIcon : MessageCircleIcon;
+
+ const handleSelect = useCallback(
+ async (mode: 'chat' | 'agent') => {
+ setOpen(false);
+ await toggleAgentMode(mode === 'agent');
+ },
+ [toggleAgentMode],
+ );
+
+ const agentTooltip = (
+ <div className={styles.agentTooltip}>
+ <div className={styles.agentTooltipTitle}>{t('chatMode.agent')}</div>
+ {AGENT_CAPS.map(({ key, icon }) => (
+ <div className={styles.agentTooltipCap} key={key}>
+ <Icon icon={icon} size={12} />
+ {t(`chatMode.agentCap.${key}`)}
+ </div>
+ ))}
+ </div>
+ );
+
+ const chatTooltip = t('chatMode.chatDesc');
+
+ const popoverContent = (
+ <Flexbox gap={4} style={{ maxWidth: 320, minWidth: 280 }}>
+ <Flexbox
+ horizontal
+ align="center"
+ className={cx(styles.option, currentMode === 'agent' && styles.activeOption)}
+ gap={12}
+ onClick={() => handleSelect('agent')}
+ >
+ <Flexbox
+ align="center"
+ className={styles.optionIcon}
+ height={32}
+ justify="center"
+ width={32}
+ >
+ <Icon icon={InfinityIcon} size={16} />
+ </Flexbox>
+ <Flexbox flex={1}>
+ <div className={styles.optionTitle}>{t('chatMode.agent')}</div>
+ <div className={styles.optionDesc}>{t('chatMode.agentDesc')}</div>
+ </Flexbox>
+ </Flexbox>
+
+ <Flexbox
+ horizontal
+ align="center"
+ className={cx(styles.option, currentMode === 'chat' && styles.activeOption)}
+ gap={12}
+ onClick={() => handleSelect('chat')}
+ >
+ <Flexbox
+ align="center"
+ className={styles.optionIcon}
+ height={32}
+ justify="center"
+ width={32}
+ >
+ <Icon icon={MessageCircleIcon} size={16} />
+ </Flexbox>
+ <Flexbox flex={1}>
+ <div className={styles.optionTitle}>{t('chatMode.chat')}</div>
+ <div className={styles.optionDesc}>{t('chatMode.chatDesc')}</div>
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ );
+
+ const button = (
+ <div className={styles.button}>
+ <Icon icon={CurrentIcon} size={14} />
+ <span>{t(`chatMode.${currentMode}`)}</span>
+ <Icon icon={ChevronDownIcon} size={12} />
+ </div>
+ );
return (
- <ActionIcon
- icon={Bot}
- title={t('agentMode.title', { defaultValue: 'Agent Mode' })}
- style={{
- color: enableAgentMode ? 'var(--colorPrimary)' : undefined,
- }}
- onClick={() => {
- handleToggle(!enableAgentMode);
+ <Popover
+ content={popoverContent}
+ open={open}
+ placement="bottomLeft"
+ trigger="click"
+ styles={{
+ content: { border: `1px solid ${cssVar.colorBorderSecondary}`, padding: 4 },
}}
- />
+ onOpenChange={setOpen}
+ >
+ <div>
+ {open ? (
+ button
+ ) : (
+ <Tooltip title={enableAgentMode ? agentTooltip : chatTooltip}>{button}</Tooltip>
+ )}
+ </div>
+ </Popover>
);
});
-AgentModeToggle.displayName = 'AgentModeToggle';
+AgentMode.displayName = 'AgentMode';
-export default AgentModeToggle;
+export default AgentMode;
diff --git a/src/features/ChatInput/ActionBar/Knowledge/index.tsx b/src/features/ChatInput/ActionBar/Knowledge/index.tsx
index fbdc4aeb189..1ccc8b19f68 100644
--- a/src/features/ChatInput/ActionBar/Knowledge/index.tsx
+++ b/src/features/ChatInput/ActionBar/Knowledge/index.tsx
@@ -1,6 +1,6 @@
import { LOBE_CHAT_CLOUD } from '@lobechat/business-const';
import { LibraryBig } from 'lucide-react';
-import { memo, Suspense, useState } from 'react';
+import { memo, Suspense } from 'react';
import { useTranslation } from 'react-i18next';
import TipGuide from '@/components/TipGuide';
@@ -21,9 +21,8 @@ const Knowledge = memo(() => {
preferenceSelectors.showUploadFileInKnowledgeBaseTip(s),
s.updateGuideState,
]);
- const [updating, setUpdating] = useState(false);
- const items = useControls({ openAttachKnowledgeModal, setUpdating });
+ const { items } = useControls({ openAttachKnowledgeModal });
if (!enableKnowledgeBase) return null;
if (!enableKnowledge)
@@ -39,7 +38,6 @@ const Knowledge = memo(() => {
const content = (
<Action
icon={LibraryBig}
- loading={updating}
showTooltip={false}
title={t('knowledgeBase.title')}
dropdown={{
diff --git a/src/features/ChatInput/ActionBar/Knowledge/useControls.tsx b/src/features/ChatInput/ActionBar/Knowledge/useControls.tsx
index 7400c6f6588..f759bcdc018 100644
--- a/src/features/ChatInput/ActionBar/Knowledge/useControls.tsx
+++ b/src/features/ChatInput/ActionBar/Knowledge/useControls.tsx
@@ -12,12 +12,17 @@ import { agentByIdSelectors } from '@/store/agent/selectors';
import { useAgentId } from '../../hooks/useAgentId';
import CheckboxItem from '../components/CheckboxWithLoading';
+const labelMaxWidth = 'min(400px, 56vw)';
+
+export interface KnowledgeControls {
+ enabledCount: number;
+ items: ItemType[];
+}
+
export const useControls = ({
openAttachKnowledgeModal,
- setUpdating,
}: {
openAttachKnowledgeModal: () => void;
- setUpdating: (updating: boolean) => void;
}) => {
const { t } = useTranslation('chat');
const agentId = useAgentId();
@@ -32,63 +37,80 @@ export const useControls = ({
s.toggleFile,
s.toggleKnowledgeBase,
]);
+ const enabledCount =
+ files.filter((item) => item.enabled).length +
+ knowledgeBases.filter((item) => item.enabled).length;
- const items: ItemType[] = [
- {
- children: [
- // first the files
- ...files.map((item) => ({
- icon: <FileIcon fileName={item.name} fileType={item.type} size={20} />,
- key: item.id,
- label: (
- <CheckboxItem
- checked={item.enabled}
- id={item.id}
- label={item.name}
- onUpdate={async (id, enabled) => {
- setUpdating(true);
- await toggleFile(id, enabled);
- setUpdating(false);
- }}
- />
- ),
- })),
+ const libraryItems = knowledgeBases.map((item) => ({
+ icon: <RepoIcon />,
+ key: item.id,
+ label: (
+ <CheckboxItem
+ checked={item.enabled}
+ id={item.id}
+ label={item.name}
+ labelMaxWidth={labelMaxWidth}
+ onUpdate={async (id, enabled) => {
+ await toggleKnowledgeBase(id, enabled);
+ }}
+ />
+ ),
+ }));
- // then the knowledge bases
- ...knowledgeBases.map((item) => ({
- icon: <RepoIcon />,
- key: item.id,
- label: (
- <CheckboxItem
- checked={item.enabled}
- id={item.id}
- label={item.name}
- onUpdate={async (id, enabled) => {
- setUpdating(true);
- await toggleKnowledgeBase(id, enabled);
- setUpdating(false);
- }}
- />
- ),
- })),
- ],
- key: 'relativeFilesOrLibraries',
- label: t('knowledgeBase.relativeFilesOrLibraries'),
- type: 'group',
- },
- {
- type: 'divider',
- },
+ const fileItems = files.map((item) => ({
+ icon: <FileIcon fileName={item.name} fileType={item.type} size={20} />,
+ key: item.id,
+ label: (
+ <CheckboxItem
+ checked={item.enabled}
+ id={item.id}
+ label={item.name}
+ labelMaxWidth={labelMaxWidth}
+ onUpdate={async (id, enabled) => {
+ await toggleFile(id, enabled);
+ }}
+ />
+ ),
+ }));
+
+ const relatedGroups: ItemType[] = [
+ ...(libraryItems.length > 0
+ ? [
+ {
+ children: libraryItems,
+ key: 'relativeLibraries',
+ label: t('knowledgeBase.libraries'),
+ type: 'group' as const,
+ },
+ ]
+ : []),
+ ...(libraryItems.length > 0 && fileItems.length > 0 ? [{ type: 'divider' as const }] : []),
+ ...(fileItems.length > 0
+ ? [
+ {
+ children: fileItems,
+ key: 'relativeFiles',
+ label: t('knowledgeBase.files'),
+ type: 'group' as const,
+ },
+ ]
+ : []),
+ ];
+
+ const items: ItemType[] = [
+ ...relatedGroups,
+ ...(relatedGroups.length > 0 ? [{ type: 'divider' as const }] : []),
{
+ closeOnClick: true,
extra: <Icon icon={ArrowRight} />,
icon: LibraryBig,
key: 'knowledge-base-store',
- label: t('knowledgeBase.viewMore'),
+ label: <span data-fixed-menu-footer>{t('knowledgeBase.viewMore')}</span>,
onClick: () => {
openAttachKnowledgeModal();
},
},
];
- return items;
+ return { enabledCount, items } satisfies KnowledgeControls;
};
diff --git a/src/features/ChatInput/ActionBar/Model/index.tsx b/src/features/ChatInput/ActionBar/Model/index.tsx
index 583987ceb4e..f080019e0a1 100644
--- a/src/features/ChatInput/ActionBar/Model/index.tsx
+++ b/src/features/ChatInput/ActionBar/Model/index.tsx
@@ -1,35 +1,19 @@
-import { LoadingOutlined } from '@ant-design/icons';
import { ModelIcon } from '@lobehub/icons';
-import { Center, Flexbox } from '@lobehub/ui';
-import { Spin } from 'antd';
-import { createStaticStyles, cx } from 'antd-style';
-import { Settings2Icon } from 'lucide-react';
-import { memo, Suspense, useCallback } from 'react';
-import { useTranslation } from 'react-i18next';
+import { Center } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { memo, useCallback } from 'react';
import ModelSwitchPanel from '@/features/ModelSwitchPanel';
-import ModelDetailPanel from '@/features/ModelSwitchPanel/components/ModelDetailPanel';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
-import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
-import { useUserStore } from '@/store/user';
-import { userGeneralSettingsSelectors } from '@/store/user/selectors';
import { useAgentId } from '../../hooks/useAgentId';
-import Action from '../components/Action';
import { useActionBarContext } from '../context';
const styles = createStaticStyles(({ css, cssVar }) => ({
- container: css`
- border-radius: 24px;
- background: ${cssVar.colorFillTertiary};
+ icon: css`
+ transition: scale 400ms cubic-bezier(0.215, 0.61, 0.355, 1);
`,
- icon: cx(
- 'model-switch',
- css`
- transition: scale 400ms cubic-bezier(0.215, 0.61, 0.355, 1);
- `,
- ),
model: css`
cursor: pointer;
border-radius: 24px;
@@ -39,24 +23,17 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}
:active {
- .model-switch {
+ div {
scale: 0.8;
}
}
`,
- modelWithControl: css`
- border-radius: 24px;
-
- :hover {
- background: ${cssVar.colorFillTertiary};
- }
- `,
}));
const ModelSwitch = memo(() => {
- const { t } = useTranslation('chat');
- const { dropdownPlacement } = useActionBarContext();
- const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);
+ const { actionSize, dropdownPlacement } = useActionBarContext();
+ const blockSize = actionSize?.blockSize ?? 32;
+ const iconSize = actionSize?.size ?? 20;
const agentId = useAgentId();
const [model, provider, updateAgentConfigById] = useAgentStore((s) => [
@@ -65,12 +42,6 @@ const ModelSwitch = memo(() => {
s.updateAgentConfigById,
]);
- const isModelHasExtendParams = useAiInfraStore(
- aiModelSelectors.isModelHasExtendParams(model, provider),
- );
-
- const showExtendParams = isDevMode && isModelHasExtendParams;
-
const handleModelChange = useCallback(
async (params: { model: string; provider: string }) => {
await updateAgentConfigById(agentId, params);
@@ -79,53 +50,18 @@ const ModelSwitch = memo(() => {
);
return (
- <Flexbox horizontal align={'center'} className={showExtendParams ? styles.container : ''}>
- <ModelSwitchPanel
- model={model}
- placement={dropdownPlacement}
- provider={provider}
- onModelChange={handleModelChange}
- >
- <Center
- className={cx(styles.model, showExtendParams && styles.modelWithControl)}
- height={36}
- width={36}
- >
- <div className={styles.icon}>
- <ModelIcon model={model} size={22} />
- </div>
- </Center>
- </ModelSwitchPanel>
-
- {showExtendParams && (
- <Action
- icon={Settings2Icon}
- showTooltip={false}
- style={{ borderRadius: 24, marginInlineStart: -4 }}
- title={t('extendParams.title')}
- popover={{
- content: (
- <Suspense
- fallback={
- <Flexbox
- align={'center'}
- justify={'center'}
- style={{ minHeight: 100, width: '100%' }}
- >
- <Spin indicator={<LoadingOutlined spin />} />
- </Flexbox>
- }
- >
- <ModelDetailPanel model={model} provider={provider} />
- </Suspense>
- ),
- maxWidth: 400,
- minWidth: 400,
- placement: 'topLeft',
- }}
- />
- )}
- </Flexbox>
+ <ModelSwitchPanel
+ model={model}
+ placement={dropdownPlacement}
+ provider={provider}
+ onModelChange={handleModelChange}
+ >
+ <Center className={styles.model} height={blockSize} width={blockSize}>
+ <div className={styles.icon}>
+ <ModelIcon model={model} size={iconSize} />
+ </div>
+ </Center>
+ </ModelSwitchPanel>
);
});
diff --git a/src/features/ChatInput/ActionBar/ModelLabel/index.tsx b/src/features/ChatInput/ActionBar/ModelLabel/index.tsx
new file mode 100644
index 00000000000..3153bf4ff41
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/ModelLabel/index.tsx
@@ -0,0 +1,78 @@
+import { Center, Flexbox } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { ChevronDownIcon } from 'lucide-react';
+import { memo, useCallback } from 'react';
+
+import ModelSwitchPanel from '@/features/ModelSwitchPanel';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import { useActionBarContext } from '../context';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ chevron: css`
+ color: ${cssVar.colorTextQuaternary};
+ `,
+ name: css`
+ overflow: hidden;
+
+ max-width: 160px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ trigger: css`
+ cursor: pointer;
+ border-radius: 6px;
+
+ :hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+}));
+
+const ModelLabel = memo(() => {
+ const { dropdownPlacement } = useActionBarContext();
+
+ const agentId = useAgentId();
+ const [model, provider, updateAgentConfigById] = useAgentStore((s) => [
+ agentByIdSelectors.getAgentModelById(agentId)(s),
+ agentByIdSelectors.getAgentModelProviderById(agentId)(s),
+ s.updateAgentConfigById,
+ ]);
+
+ const enabledModel = useAiInfraStore(aiModelSelectors.getEnabledModelById(model, provider));
+ const displayName = enabledModel?.displayName || model;
+
+ const handleModelChange = useCallback(
+ async (params: { model: string; provider: string }) => {
+ await updateAgentConfigById(agentId, params);
+ },
+ [agentId, updateAgentConfigById],
+ );
+
+ return (
+ <ModelSwitchPanel
+ model={model}
+ openOnHover={false}
+ placement={dropdownPlacement}
+ provider={provider}
+ onModelChange={handleModelChange}
+ >
+ <Center horizontal className={styles.trigger} height={28} paddingInline={6}>
+ <Flexbox horizontal align={'center'} gap={2}>
+ <span className={styles.name}>{displayName}</span>
+ <ChevronDownIcon className={styles.chevron} size={12} />
+ </Flexbox>
+ </Center>
+ </ModelSwitchPanel>
+ );
+});
+
+ModelLabel.displayName = 'ModelLabel';
+
+export default ModelLabel;
diff --git a/src/features/ChatInput/ActionBar/Params/Controls.tsx b/src/features/ChatInput/ActionBar/Params/Controls.tsx
index c70d06d265a..a909d4d787d 100644
--- a/src/features/ChatInput/ActionBar/Params/Controls.tsx
+++ b/src/features/ChatInput/ActionBar/Params/Controls.tsx
@@ -1,23 +1,22 @@
-import { type FormItemProps } from '@lobehub/ui';
-import { Checkbox, Flexbox, Form, SliderWithInput, Tag } from '@lobehub/ui';
+import { DEFAULT_AGENT_CONFIG } from '@lobechat/const';
+import { Flexbox, Icon, SliderWithInput } from '@lobehub/ui';
import { Form as AntdForm, Switch } from 'antd';
-import { createStaticStyles } from 'antd-style';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
import { debounce } from 'es-toolkit/compat';
import isEqual from 'fast-deep-equal';
-import { type ComponentType } from 'react';
-import { memo, useCallback, useEffect, useRef } from 'react';
+import { ChevronDown, ChevronUp } from 'lucide-react';
+import type { ReactNode } from 'react';
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import type { PartialDeep } from 'type-fest';
import InfoTooltip from '@/components/InfoTooltip';
-import {
- FrequencyPenalty,
- PresencePenalty,
- Temperature,
- TopP,
-} from '@/features/ModelParamsControl';
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+import ControlsForm from '@/features/ModelSwitchPanel/components/ControlsForm';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
-import { useServerConfigStore } from '@/store/serverConfig';
+import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
+import type { LobeAgentConfig } from '@/types/agent';
import { useAgentId } from '../../hooks/useAgentId';
import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
@@ -25,73 +24,325 @@ import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
interface ControlsProps {
setUpdating: (updating: boolean) => void;
updating: boolean;
+ variant?: 'popover' | 'sidebar';
}
type ParamKey = 'temperature' | 'top_p' | 'presence_penalty' | 'frequency_penalty';
type ParamLabelKey =
- | 'settingModel.temperature.title'
- | 'settingModel.topP.title'
- | 'settingModel.presencePenalty.title'
- | 'settingModel.frequencyPenalty.title';
+ | 'settingModel.params.panel.creativity'
+ | 'settingModel.params.panel.openness'
+ | 'settingModel.params.panel.topicDivergence'
+ | 'settingModel.params.panel.vocabularyRichness';
type ParamDescKey =
- | 'settingModel.temperature.desc'
- | 'settingModel.topP.desc'
+ | 'settingModel.frequencyPenalty.desc'
| 'settingModel.presencePenalty.desc'
- | 'settingModel.frequencyPenalty.desc';
+ | 'settingModel.temperature.desc'
+ | 'settingModel.topP.desc';
+
+interface SliderConfig {
+ max: number;
+ min: number;
+ step: number;
+ unlimitedInput?: boolean;
+}
+
+const styles = createStaticStyles(({ css }) => ({
+ advancedContent: css`
+ display: flex;
+ flex-direction: column;
-const styles = createStaticStyles(({ css, cssVar }) => ({
- checkbox: css`
- .ant-checkbox-inner {
- border-radius: 4px;
+ .control-row {
+ border-block-start: 1px solid ${cssVar.colorSplit};
}
- &:hover .ant-checkbox-inner {
- border-color: ${cssVar.colorPrimary};
+ .control-row:first-child {
+ border-block-start: none;
}
`,
+ sectionHeader: css`
+ cursor: pointer;
+
+ width: calc(100% + 16px);
+ margin-inline: -8px;
+ padding-block: 12px;
+ padding-inline: 8px;
+ border: none;
+ border-radius: 10px;
+
+ font: inherit;
+ font-size: 12px;
+ font-weight: 500;
+ color: ${cssVar.colorTextSecondary};
+ text-align: start;
+
+ background: transparent;
+
+ transition: color 0.2s ease;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ }
+
+ &:hover .section-header-label {
+ color: ${cssVar.colorText};
+ }
+
+ &:focus-visible {
+ outline: 1px solid ${cssVar.colorBorder};
+ outline-offset: 2px;
+ }
+ `,
+ body: css`
+ overflow-y: auto;
+ overscroll-behavior: contain;
+ display: flex;
+ flex: 1 1 auto;
+ flex-direction: column;
+
+ min-height: 0;
+ padding-block-end: 4px;
+ padding-inline: 12px;
+ `,
+ commonSection: css`
+ display: flex;
+ flex-direction: column;
+ padding-block: 0;
+ `,
+ divider: css`
+ height: 1px;
+ background: ${cssVar.colorSplit};
+ `,
+ form: css`
+ margin: 0;
+ `,
+ header: css`
+ display: flex;
+ gap: 12px;
+ align-items: center;
+ justify-content: space-between;
+
+ padding-block: 16px;
+ padding-inline: 12px;
+ border-block-end: 1px solid ${cssVar.colorSplit};
+
+ font-size: 14px;
+ font-weight: 600;
+ line-height: 1.4;
+ color: ${cssVar.colorText};
+ `,
+ headerLoading: css`
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+
+ width: 18px;
+ height: 18px;
+
+ color: ${cssVar.colorTextTertiary};
+ `,
+ headerTitle: css`
+ overflow: hidden;
+ min-width: 0;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
label: css`
user-select: none;
+
+ min-width: 0;
+
+ font-size: 13px;
+ font-weight: 500;
+ line-height: 20px;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ labelMain: css`
+ flex-wrap: wrap;
+ min-width: 0;
+ `,
+ muted: css`
+ .control-label {
+ color: ${cssVar.colorTextTertiary};
+ }
`,
- sliderWrapper: css`
+ modelConfigSection: css`
+ padding-block: 12px;
+
+ .ant-form {
+ margin: 0;
+ }
+
+ .ant-form-item {
+ padding-block: 12px;
+ }
+
+ .ant-form-item-row {
+ gap: 10px;
+ }
+
+ .ant-form-item-label > label {
+ font-size: 13px;
+ font-weight: 500;
+ line-height: 20px;
+ color: ${cssVar.colorTextSecondary};
+ }
+
+ .ant-form-item-label > label div {
+ color: ${cssVar.colorTextSecondary};
+ }
+
+ .ant-form-item-label > label small,
+ .ant-form-item-label > label small *:not(a) {
+ font-size: 12px;
+ font-weight: 400;
+ line-height: 18px;
+ color: ${cssVar.colorTextTertiary};
+ }
+
+ .ant-form-item:first-child {
+ padding-block-start: 0;
+ }
+
+ .ant-form-item:last-child {
+ padding-block-end: 0;
+ }
+
+ .ant-divider {
+ display: none;
+ }
+ `,
+ panel: css`
+ overflow: hidden;
display: flex;
- gap: 16px;
- align-items: center;
+ flex-direction: column;
+
+ width: min(384px, 100%);
+ max-height: 50vh;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 16px;
+
+ background: ${cssVar.colorBgElevated};
+ box-shadow: ${cssVar.boxShadowSecondary};
+
+ .ant-switch {
+ min-width: 28px;
+ background: ${cssVar.colorFillSecondary};
+ }
+
+ .ant-switch .ant-switch-handle::before {
+ background: ${cssVar.colorBgElevated};
+ }
+
+ .ant-switch.ant-switch-checked {
+ background: ${cssVar.colorText};
+ }
+
+ .ant-form-item {
+ margin: 0;
+ }
+ `,
+ sidebarPanel: css`
width: 100%;
+ height: 100%;
+ max-height: none;
+ border: none;
+ border-radius: 0;
+
+ background: transparent;
+ box-shadow: none;
`,
-}));
+ rowControl: css`
+ width: 100%;
+ `,
+ rowRoot: css`
+ padding-block: 12px;
+ `,
+ tag: css`
+ user-select: none;
-// Wrapper component to handle checkbox + slider
-interface ParamControlWrapperProps {
- checked: boolean;
- Component: ComponentType<any>;
- disabled: boolean;
- onChange?: (value: number) => void;
- onToggle: (checked: boolean) => void;
- styles: any;
- value?: number;
-}
+ align-self: flex-start;
-const ParamControlWrapper = memo<ParamControlWrapperProps>(
- ({ Component, value, onChange, disabled, checked, onToggle, styles }) => {
- return (
- <div className={styles.sliderWrapper}>
- <Checkbox
- checked={checked}
- className={styles.checkbox}
- onClick={(e) => {
- e.stopPropagation();
- onToggle(!checked);
- }}
- />
- <div style={{ flex: 1 }}>
- <Component disabled={disabled} value={value} onChange={onChange} />
- </div>
- </div>
- );
- },
-);
+ width: fit-content;
+ padding-block: 2px;
+ padding-inline: 7px;
+ border-radius: 999px;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 10px;
+ font-weight: 500;
+ line-height: 1.2;
+ color: ${cssVar.colorTextQuaternary};
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ tooltipContent: css`
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ max-width: 240px;
+ `,
+ slider: css`
+ width: 100%;
+
+ .ant-slider {
+ margin-block: 0;
+ margin-inline: 0;
+ }
+
+ .ant-slider-rail {
+ background: ${cssVar.colorFillQuaternary};
+ }
+
+ .ant-slider-track {
+ background: ${cssVar.colorTextSecondary};
+ }
+
+ .ant-slider-handle::after {
+ background: ${cssVar.colorBgElevated};
+ box-shadow: 0 0 0 2px ${cssVar.colorTextSecondary};
+ }
+
+ .ant-slider-handle:hover::after,
+ .ant-slider-handle:focus::after,
+ .ant-slider-handle:active::after {
+ box-shadow: 0 0 0 3px ${cssVar.colorTextSecondary};
+ }
+
+ .ant-input-number,
+ .ant-input-number-affix-wrapper {
+ overflow: hidden;
+
+ height: 28px;
+ border: none;
+ border-radius: 10px;
+
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorFillTertiary};
+ box-shadow: none;
+ }
+
+ .ant-input-number:hover,
+ .ant-input-number-focused,
+ .ant-input-number-affix-wrapper:hover,
+ .ant-input-number-affix-wrapper-focused {
+ background: ${cssVar.colorFillSecondary};
+ box-shadow: none;
+ }
+
+ .ant-input-number-input {
+ height: 28px;
+ padding-inline: 6px;
+
+ font-size: 13px;
+ color: ${cssVar.colorTextSecondary};
+ text-align: center;
+ }
+ `,
+}));
const PARAM_NAME_MAP: Record<ParamKey, (string | number)[]> = {
frequency_penalty: ['params', 'frequency_penalty'],
@@ -109,50 +360,173 @@ const PARAM_DEFAULTS: Record<ParamKey, number> = {
const PARAM_CONFIG = {
frequency_penalty: {
- Component: FrequencyPenalty,
descKey: 'settingModel.frequencyPenalty.desc',
- labelKey: 'settingModel.frequencyPenalty.title',
+ labelKey: 'settingModel.params.panel.vocabularyRichness',
+ slider: { max: 2, min: -2, step: 0.1 },
tag: 'frequency_penalty',
},
presence_penalty: {
- Component: PresencePenalty,
descKey: 'settingModel.presencePenalty.desc',
- labelKey: 'settingModel.presencePenalty.title',
+ labelKey: 'settingModel.params.panel.topicDivergence',
+ slider: { max: 2, min: -2, step: 0.1 },
tag: 'presence_penalty',
},
temperature: {
- Component: Temperature,
descKey: 'settingModel.temperature.desc',
- labelKey: 'settingModel.temperature.title',
+ labelKey: 'settingModel.params.panel.creativity',
+ slider: { max: 2, min: 0, step: 0.1 },
tag: 'temperature',
},
top_p: {
- Component: TopP,
descKey: 'settingModel.topP.desc',
- labelKey: 'settingModel.topP.title',
+ labelKey: 'settingModel.params.panel.openness',
+ slider: { max: 1, min: 0, step: 0.1 },
tag: 'top_p',
},
} satisfies Record<
ParamKey,
{
- Component: ComponentType<any>;
descKey: ParamDescKey;
labelKey: ParamLabelKey;
+ slider: SliderConfig;
tag: string;
}
>;
-const Controls = memo<ControlsProps>(({ setUpdating, updating }) => {
- const { t } = useTranslation('setting');
- const mobile = useServerConfigStore((s) => s.isMobile);
+const PARAM_ORDER: ParamKey[] = ['temperature', 'top_p', 'frequency_penalty', 'presence_penalty'];
+
+const ADVANCED_OPEN_STORAGE_KEY = 'lobehub-chat-input-params-advanced-open';
+const MODEL_CONFIG_OPEN_STORAGE_KEY = 'lobehub-chat-input-params-model-config-open';
+
+const getStoredOpen = (storageKey: string) => {
+ if (typeof window === 'undefined') return false;
+
+ return window.localStorage.getItem(storageKey) === 'true';
+};
+
+const setStoredOpen = (storageKey: string, open: boolean) => {
+ if (typeof window === 'undefined') return;
+
+ window.localStorage.setItem(storageKey, String(open));
+};
+
+interface ControlLabelProps {
+ tag?: string;
+ title: string;
+ tooltip?: string;
+}
+
+const ControlLabel = memo<ControlLabelProps>(({ title, tooltip, tag }) => (
+ <Flexbox align={'flex-start'} className={cx(styles.label, 'control-label')} gap={6}>
+ <Flexbox horizontal align={'center'} className={styles.labelMain} gap={6}>
+ {title}
+ {tooltip && (
+ <InfoTooltip
+ title={
+ <div className={styles.tooltipContent}>
+ {tag && <span className={styles.tag}>{tag}</span>}
+ <span>{tooltip}</span>
+ </div>
+ }
+ />
+ )}
+ </Flexbox>
+ </Flexbox>
+));
+
+interface ControlRowProps {
+ action: ReactNode;
+ children?: ReactNode;
+ muted?: boolean;
+ tag?: string;
+ title: string;
+ tooltip?: string;
+}
+
+const ControlRow = memo<ControlRowProps>(({ action, children, muted, tag, title, tooltip }) => (
+ <Flexbox className={cx('control-row', styles.rowRoot, muted && styles.muted)} gap={10}>
+ <Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>
+ <ControlLabel tag={tag} title={title} tooltip={tooltip} />
+ {action}
+ </Flexbox>
+ {children && <div className={styles.rowControl}>{children}</div>}
+ </Flexbox>
+));
+
+interface SectionHeaderProps {
+ onToggle: () => void;
+ open: boolean;
+ title: string;
+}
+
+const SectionHeader = memo<SectionHeaderProps>(({ onToggle, open, title }) => (
+ <button aria-expanded={open} className={styles.sectionHeader} type="button" onClick={onToggle}>
+ <Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>
+ <span className={cx(styles.label, 'section-header-label')}>{title}</span>
+ <Icon icon={open ? ChevronUp : ChevronDown} size={18} />
+ </Flexbox>
+ </button>
+));
+
+interface SliderFieldProps extends SliderConfig {
+ inputWidth?: number;
+ onChange: (value: number) => void;
+ value?: number;
+}
+
+const SliderField = memo<SliderFieldProps>(
+ ({ value, onChange, min, max, step, unlimitedInput, inputWidth = 56 }) => (
+ <SliderWithInput
+ changeOnWheel
+ className={styles.slider}
+ controls={false}
+ gap={10}
+ max={max}
+ min={min}
+ size={'small'}
+ step={step}
+ style={{ height: 28 }}
+ unlimitedInput={unlimitedInput}
+ value={value}
+ styles={{
+ input: {
+ maxWidth: inputWidth,
+ },
+ }}
+ onChange={onChange}
+ />
+ ),
+);
+
+const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popover' }) => {
+ const { t } = useTranslation(['setting', 'components']);
const agentId = useAgentId();
const { updateAgentConfig } = useUpdateAgentConfig();
- const config = useAgentStore((s) => agentByIdSelectors.getAgentConfigById(agentId)(s), isEqual);
- const [form] = Form.useForm();
+ const config = useAgentStore(
+ (s) => agentByIdSelectors.getAgentConfigById(agentId)(s) || DEFAULT_AGENT_CONFIG,
+ isEqual,
+ );
+ const agentModel = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));
+ const agentProvider = useAgentStore((s) =>
+ agentByIdSelectors.getAgentModelProviderById(agentId)(s),
+ );
+ const enableAgentMode = useAgentStore(agentByIdSelectors.getAgentEnableModeById(agentId));
+ const hasModelConfig = useAiInfraStore(
+ aiModelSelectors.isModelHasExtendParams(agentModel ?? '', agentProvider ?? ''),
+ );
+ const [form] = AntdForm.useForm();
+ const [advancedOpen, setAdvancedOpen] = useState(() => getStoredOpen(ADVANCED_OPEN_STORAGE_KEY));
+ const [modelConfigOpen, setModelConfigOpen] = useState(() =>
+ getStoredOpen(MODEL_CONFIG_OPEN_STORAGE_KEY),
+ );
+ const [, refreshFormValues] = useState(0);
- const enableMaxTokens = AntdForm.useWatch(['chatConfig', 'enableMaxTokens'], form);
- const enableHistoryCount = AntdForm.useWatch(['chatConfig', 'enableHistoryCount'], form);
+ const enableContextCompression = form.getFieldValue(['chatConfig', 'enableContextCompression']);
+ const enableMaxTokens = form.getFieldValue(['chatConfig', 'enableMaxTokens']);
+ const enableHistoryCount = form.getFieldValue(['chatConfig', 'enableHistoryCount']);
+ const historyCountValue = form.getFieldValue(['chatConfig', 'historyCount']);
+ const maxTokensValue = form.getFieldValue(['params', 'max_tokens']);
const { frequency_penalty, presence_penalty, temperature, top_p } = config.params ?? {};
const historyCountFromStore = useAgentStore((s) =>
@@ -181,6 +555,7 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating }) => {
if (typeof frequency_penalty === 'number') {
lastValuesRef.current.frequency_penalty = frequency_penalty;
}
+ refreshFormValues((value) => value + 1);
}, [config, form, frequency_penalty, presence_penalty, temperature, top_p]);
// Sync history count values to form
@@ -195,32 +570,13 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating }) => {
historyCount: historyCountFromStore,
},
});
+ refreshFormValues((value) => value + 1);
}, [form, enableHistoryCountFromStore, historyCountFromStore, updating]);
- const temperatureValue = AntdForm.useWatch(PARAM_NAME_MAP.temperature, form);
- const topPValue = AntdForm.useWatch(PARAM_NAME_MAP.top_p, form);
- const presencePenaltyValue = AntdForm.useWatch(PARAM_NAME_MAP.presence_penalty, form);
- const frequencyPenaltyValue = AntdForm.useWatch(PARAM_NAME_MAP.frequency_penalty, form);
-
- useEffect(() => {
- if (typeof temperatureValue === 'number') lastValuesRef.current.temperature = temperatureValue;
- }, [temperatureValue]);
-
- useEffect(() => {
- if (typeof topPValue === 'number') lastValuesRef.current.top_p = topPValue;
- }, [topPValue]);
-
- useEffect(() => {
- if (typeof presencePenaltyValue === 'number') {
- lastValuesRef.current.presence_penalty = presencePenaltyValue;
- }
- }, [presencePenaltyValue]);
-
- useEffect(() => {
- if (typeof frequencyPenaltyValue === 'number') {
- lastValuesRef.current.frequency_penalty = frequencyPenaltyValue;
- }
- }, [frequencyPenaltyValue]);
+ const temperatureValue = form.getFieldValue(PARAM_NAME_MAP.temperature);
+ const topPValue = form.getFieldValue(PARAM_NAME_MAP.top_p);
+ const presencePenaltyValue = form.getFieldValue(PARAM_NAME_MAP.presence_penalty);
+ const frequencyPenaltyValue = form.getFieldValue(PARAM_NAME_MAP.frequency_penalty);
const enabledMap: Record<ParamKey, boolean> = {
frequency_penalty: typeof frequencyPenaltyValue === 'number',
@@ -228,6 +584,9 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating }) => {
temperature: typeof temperatureValue === 'number',
top_p: typeof topPValue === 'number',
};
+ const panelTitle = enableAgentMode
+ ? t('settingModel.params.panel.agentTitle')
+ : t('settingModel.params.panel.title');
const handleToggle = useCallback(
async (key: ParamKey, enabled: boolean) => {
@@ -248,189 +607,241 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating }) => {
newValue = nextValue;
form.setFieldValue(namePath, nextValue);
}
+ refreshFormValues((value) => value + 1);
// Save changes immediately - manually construct config object to ensure latest values are used
setUpdating(true);
- const currentValues = form.getFieldsValue();
- const prevParams = (currentValues.params ?? {}) as Record<ParamKey, number | undefined>;
- const currentParams: Record<ParamKey, number | undefined> = { ...prevParams };
+ const currentValues = form.getFieldsValue(true) as PartialDeep<LobeAgentConfig>;
+ const prevParams = (currentValues.params ?? {}) as Partial<
+ Record<ParamKey, null | number | undefined>
+ >;
+ const currentParams: Partial<Record<ParamKey, null | number | undefined>> = {
+ ...prevParams,
+ };
if (newValue === undefined) {
// Explicitly delete the property instead of setting it to undefined
// This ensures the Form state stays in sync
delete currentParams[key];
// Use null as a disabled marker (the database preserves null, and the frontend uses it to determine checkbox state)
- currentParams[key] = null as any;
+ currentParams[key] = null;
} else {
currentParams[key] = newValue;
}
const updatedConfig = {
...currentValues,
- params: currentParams,
- };
+ params: currentParams as LobeAgentConfig['params'],
+ } satisfies PartialDeep<LobeAgentConfig>;
- await updateAgentConfig(updatedConfig);
- setUpdating(false);
+ try {
+ await updateAgentConfig(updatedConfig);
+ } finally {
+ setUpdating(false);
+ }
},
- [form, setUpdating, updateAgentConfig],
+ [form, refreshFormValues, setUpdating, updateAgentConfig],
);
- // Use useMemo to ensure the debounce function is only created once
- const handleValuesChange = useCallback(
- debounce(async (values) => {
- setUpdating(true);
- await updateAgentConfig(values);
- setUpdating(false);
- }, 500),
+ const handleValuesChange = useMemo(
+ () =>
+ debounce(async (values: PartialDeep<LobeAgentConfig>) => {
+ setUpdating(true);
+ try {
+ await updateAgentConfig(values);
+ } finally {
+ setUpdating(false);
+ }
+ }, 500),
[updateAgentConfig, setUpdating],
);
- const baseItems: FormItemProps[] = (Object.keys(PARAM_CONFIG) as ParamKey[]).map((key) => {
- const meta = PARAM_CONFIG[key];
- const Component = meta.Component;
- const enabled = enabledMap[key];
-
- return {
- children: (
- <ParamControlWrapper
- Component={Component}
- checked={enabled}
- disabled={!enabled}
- styles={styles}
- value={form.getFieldValue(PARAM_NAME_MAP[key])}
- onToggle={(checked) => handleToggle(key, checked)}
- />
- ),
- label: (
- <Flexbox horizontal align={'center'} className={styles.label} gap={8}>
- {t(meta.labelKey)}
- <InfoTooltip title={t(meta.descKey)} />
- </Flexbox>
- ),
- name: PARAM_NAME_MAP[key],
- tag: meta.tag,
- } satisfies FormItemProps;
- });
-
- // MaxTokens items
- const maxTokensItems: FormItemProps[] = [
- {
- children: <Switch />,
- label: (
- <Flexbox horizontal align={'center'} className={styles.label} gap={8}>
- {t('settingModel.enableMaxTokens.title')}
- </Flexbox>
- ),
- name: ['chatConfig', 'enableMaxTokens'],
- tag: 'max_tokens',
- valuePropName: 'checked',
- },
- ...(enableMaxTokens
- ? [
- {
- children: <SliderWithInput unlimitedInput max={32_000} min={0} step={100} />,
- label: (
- <Flexbox horizontal align={'center'} className={styles.label} gap={8}>
- {t('settingModel.maxTokens.title')}
- <InfoTooltip title={t('settingModel.maxTokens.desc')} />
- </Flexbox>
- ),
- name: ['params', 'max_tokens'],
- tag: 'max_tokens',
- } satisfies FormItemProps,
- ]
- : []),
- ];
-
- // Context Compression items
- const contextCompressionItems: FormItemProps[] = [
- {
- children: <Switch />,
- label: (
- <Flexbox horizontal align={'center'} className={styles.label} gap={8}>
- {t('settingModel.enableContextCompression.title')}
- <InfoTooltip title={t('settingModel.enableContextCompression.desc')} />
- </Flexbox>
- ),
- name: ['chatConfig', 'enableContextCompression'],
- tag: 'compression',
- valuePropName: 'checked',
- },
- ];
-
- // History Count items
- const historyCountItems: FormItemProps[] = [
- {
- children: <Switch />,
- label: (
- <Flexbox horizontal align={'center'} className={styles.label} gap={8}>
- {t('settingChat.enableHistoryCount.title')}
- <InfoTooltip title={t('settingChat.historyCount.desc')} />
- </Flexbox>
- ),
- name: ['chatConfig', 'enableHistoryCount'],
- tag: 'history',
- valuePropName: 'checked',
+ const handleFieldChange = useCallback(
+ (namePath: (string | number)[], value: boolean | number) => {
+ form.setFieldValue(namePath, value);
+ if (
+ namePath[0] === 'params' &&
+ typeof namePath[1] === 'string' &&
+ namePath[1] in PARAM_NAME_MAP &&
+ typeof value === 'number'
+ ) {
+ lastValuesRef.current[namePath[1] as ParamKey] = value;
+ }
+ refreshFormValues((current) => current + 1);
+ handleValuesChange(form.getFieldsValue(true) as PartialDeep<LobeAgentConfig>);
},
- ...(enableHistoryCount
- ? [
- {
- children: (
- <SliderWithInput
- max={20}
- min={0}
- step={1}
- unlimitedInput={true}
- styles={{
- input: {
- maxWidth: 64,
- },
- }}
- />
- ),
- label: (
- <Flexbox horizontal align={'center'} className={styles.label} gap={8}>
- {t('settingChat.historyCount.title')}
- <InfoTooltip title={t('settingChat.historyCount.desc')} />
- </Flexbox>
- ),
- name: ['chatConfig', 'historyCount'],
- tag: 'history',
- } satisfies FormItemProps,
- ]
- : []),
- ];
-
- const allItems = [
- ...baseItems,
- ...maxTokensItems,
- ...contextCompressionItems,
- ...historyCountItems,
- ];
+ [form, handleValuesChange, refreshFormValues],
+ );
+
+ const handleAdvancedOpenChange = useCallback(() => {
+ setAdvancedOpen((open) => {
+ const nextOpen = !open;
+ setStoredOpen(ADVANCED_OPEN_STORAGE_KEY, nextOpen);
+ return nextOpen;
+ });
+ }, []);
+
+ const handleModelConfigOpenChange = useCallback(() => {
+ setModelConfigOpen((open) => {
+ const nextOpen = !open;
+ setStoredOpen(MODEL_CONFIG_OPEN_STORAGE_KEY, nextOpen);
+ return nextOpen;
+ });
+ }, []);
return (
- <Form
- form={form}
- initialValues={config}
- itemMinWidth={220}
- itemsType={'flat'}
- items={
- mobile
- ? allItems
- : allItems.map(({ tag, ...item }) => ({
- ...item,
- desc: <Tag size={'small'}>{tag}</Tag>,
- }))
- }
- styles={{
- group: {
- background: 'transparent',
- paddingBottom: 12,
- },
- }}
- onValuesChange={handleValuesChange}
- />
+ <div className={styles.form}>
+ <div className={cx(styles.panel, variant === 'sidebar' && styles.sidebarPanel)}>
+ <div className={styles.header}>
+ <span className={styles.headerTitle}>{panelTitle}</span>
+ {updating && (
+ <div className={styles.headerLoading}>
+ <NeuralNetworkLoading size={18} />
+ </div>
+ )}
+ </div>
+ <div className={styles.body}>
+ <div className={styles.commonSection}>
+ <ControlRow
+ tag="compression"
+ title={t('settingModel.params.panel.contextCompression')}
+ tooltip={t('settingModel.enableContextCompression.desc')}
+ action={
+ <Switch
+ checked={Boolean(enableContextCompression)}
+ size={'small'}
+ onChange={(checked) => {
+ handleFieldChange(['chatConfig', 'enableContextCompression'], checked);
+ }}
+ />
+ }
+ />
+ <ControlRow
+ tag="history"
+ title={t('settingModel.params.panel.historyLimit')}
+ tooltip={t('settingChat.historyCount.desc')}
+ action={
+ <Switch
+ checked={Boolean(enableHistoryCount)}
+ size={'small'}
+ onChange={(checked) => {
+ handleFieldChange(['chatConfig', 'enableHistoryCount'], checked);
+ }}
+ />
+ }
+ >
+ {enableHistoryCount && (
+ <SliderField
+ unlimitedInput
+ inputWidth={56}
+ max={20}
+ min={0}
+ step={1}
+ value={typeof historyCountValue === 'number' ? historyCountValue : 0}
+ onChange={(value) => {
+ handleFieldChange(['chatConfig', 'historyCount'], value);
+ }}
+ />
+ )}
+ </ControlRow>
+ </div>
+ {hasModelConfig && (
+ <>
+ <div className={styles.divider} />
+ <SectionHeader
+ open={modelConfigOpen}
+ title={t('ModelSwitchPanel.detail.config', { ns: 'components' })}
+ onToggle={handleModelConfigOpenChange}
+ />
+ {modelConfigOpen && (
+ <div className={styles.modelConfigSection}>
+ <ControlsForm
+ model={agentModel}
+ provider={agentProvider}
+ onUpdatingChange={setUpdating}
+ />
+ </div>
+ )}
+ </>
+ )}
+ {!enableAgentMode && (
+ <>
+ <div className={styles.divider} />
+ <SectionHeader
+ open={advancedOpen}
+ title={t('settingModel.params.panel.advanced')}
+ onToggle={handleAdvancedOpenChange}
+ />
+ {advancedOpen && (
+ <div className={styles.advancedContent}>
+ {PARAM_ORDER.map((key) => {
+ const meta = PARAM_CONFIG[key];
+ const enabled = enabledMap[key];
+
+ return (
+ <ControlRow
+ key={key}
+ muted={!enabled}
+ tag={meta.tag}
+ title={t(meta.labelKey)}
+ tooltip={t(meta.descKey)}
+ action={
+ <Switch
+ checked={enabled}
+ size={'small'}
+ onChange={(checked) => {
+ handleToggle(key, checked);
+ }}
+ />
+ }
+ >
+ {enabled && (
+ <SliderField
+ value={form.getFieldValue(PARAM_NAME_MAP[key])}
+ onChange={(value) => {
+ handleFieldChange(PARAM_NAME_MAP[key], value);
+ }}
+ {...meta.slider}
+ />
+ )}
+ </ControlRow>
+ );
+ })}
+ <ControlRow
+ tag="max_tokens"
+ title={t('settingModel.params.panel.responseLength')}
+ tooltip={t('settingModel.maxTokens.desc')}
+ action={
+ <Switch
+ checked={Boolean(enableMaxTokens)}
+ size={'small'}
+ onChange={(checked) => {
+ handleFieldChange(['chatConfig', 'enableMaxTokens'], checked);
+ }}
+ />
+ }
+ >
+ {enableMaxTokens && (
+ <SliderField
+ unlimitedInput
+ inputWidth={64}
+ max={32_000}
+ min={0}
+ step={100}
+ value={typeof maxTokensValue === 'number' ? maxTokensValue : 0}
+ onChange={(value) => {
+ handleFieldChange(['params', 'max_tokens'], value);
+ }}
+ />
+ )}
+ </ControlRow>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ </div>
);
});
diff --git a/src/features/ChatInput/ActionBar/Params/index.tsx b/src/features/ChatInput/ActionBar/Params/index.tsx
index dd8649b4c17..592c9fafe6e 100644
--- a/src/features/ChatInput/ActionBar/Params/index.tsx
+++ b/src/features/ChatInput/ActionBar/Params/index.tsx
@@ -1,4 +1,4 @@
-import { SlidersHorizontal } from 'lucide-react';
+import { Settings2Icon } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -17,16 +17,24 @@ const Params = memo(() => {
const [updating, setUpdating] = useState(false);
const { t } = useTranslation('setting');
- if (isLoading) return <Action disabled icon={SlidersHorizontal} />;
+ if (isLoading) return <Action disabled icon={Settings2Icon} />;
return (
<Action
- icon={SlidersHorizontal}
- loading={updating}
+ icon={Settings2Icon}
showTooltip={false}
title={t('settingModel.params.title')}
popover={{
content: <Controls setUpdating={setUpdating} updating={updating} />,
+ maxWidth: 384,
+ minWidth: 384,
+ styles: {
+ content: {
+ borderRadius: 16,
+ overflow: 'hidden',
+ padding: 0,
+ },
+ },
}}
/>
);
diff --git a/src/features/ChatInput/ActionBar/Plus/index.tsx b/src/features/ChatInput/ActionBar/Plus/index.tsx
new file mode 100644
index 00000000000..a559fc4706a
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Plus/index.tsx
@@ -0,0 +1,593 @@
+'use client';
+
+import { validateVideoFileSize } from '@lobechat/utils/client';
+import type { IconProps } from '@lobehub/ui';
+import { Icon, Popover } from '@lobehub/ui';
+import { BrainOffIcon, GlobeOffIcon, SkillsIcon } from '@lobehub/ui/icons';
+import { Upload } from 'antd';
+import { css, cssVar, cx } from 'antd-style';
+import {
+ Brain,
+ CheckIcon,
+ CloudCog,
+ FileUp,
+ Globe,
+ LibraryBig,
+ PlusIcon,
+ SearchCheck,
+ Store,
+ TypeIcon,
+} from 'lucide-react';
+import type { ReactNode } from 'react';
+import { memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { message } from '@/components/AntdStaticMethods';
+import { openAttachKnowledgeModal } from '@/features/LibraryModal';
+import { createSkillStoreModal } from '@/features/SkillStore';
+import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';
+import { useVisualMediaUploadAbility } from '@/hooks/useVisualMediaUploadAbility';
+import { useAgentStore } from '@/store/agent';
+import {
+ agentByIdSelectors,
+ agentSelectors,
+ chatConfigByIdSelectors,
+} from '@/store/agent/selectors';
+import { aiModelSelectors, aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
+import { useFileStore } from '@/store/file';
+import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
+import { useChatInputStore } from '../../store';
+import Action from '../components/Action';
+import { type ActionDropdownMenuItems } from '../components/ActionDropdown';
+import { useControls as useKnowledgeControls } from '../Knowledge/useControls';
+import { useMemoryEnabled } from '../Memory/useMemoryEnabled';
+import { useControls as useToolsControls } from '../Tools/useControls';
+
+const hotArea = css`
+ &::before {
+ content: '';
+ position: absolute;
+ inset: 0;
+ background-color: transparent;
+ }
+`;
+
+const activeLabel = css`
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ justify-content: space-between;
+
+ width: 100%;
+
+ color: inherit;
+
+ span {
+ overflow: hidden;
+ min-width: 0;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+`;
+
+const optionLabel = css`
+ display: flex;
+ gap: 12px;
+ align-items: center;
+ justify-content: space-between;
+
+ width: 100%;
+ min-width: 220px;
+
+ .title {
+ line-height: 1.25;
+ }
+
+ .desc {
+ margin-block-start: 3px;
+
+ font-size: 12px;
+ line-height: 1.35;
+ color: ${cssVar.colorTextDescription};
+ white-space: normal;
+ }
+`;
+
+const searchOptionRow = css`
+ display: flex;
+ gap: 10px;
+ align-items: center;
+
+ width: 100%;
+ min-width: 220px;
+ max-width: 320px;
+
+ .title {
+ line-height: 1.25;
+ }
+
+ .desc {
+ margin-block-start: 3px;
+
+ font-size: 12px;
+ line-height: 1.35;
+ color: ${cssVar.colorTextDescription};
+ white-space: normal;
+ }
+`;
+
+const searchIconBox = css`
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+
+ width: 36px;
+ height: 36px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 8px;
+
+ background: ${cssVar.colorBgContainer};
+`;
+
+const labelWithChip = css`
+ display: inline-flex;
+ gap: 8px;
+ align-items: center;
+`;
+
+const countChip = css`
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+
+ min-width: 18px;
+ height: 18px;
+ padding-block: 0;
+ padding-inline: 6px;
+ border-radius: 9px;
+
+ font-size: 11px;
+ line-height: 18px;
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorFillSecondary};
+`;
+
+const activeIcon = (icon: IconProps['icon'], active?: boolean): IconProps['icon'] =>
+ active ? <Icon color={cssVar.colorInfo} icon={icon} size={16} /> : icon;
+
+type DropdownItemWithPopover = NonNullable<ActionDropdownMenuItems>[number] & {
+ label?: ReactNode;
+ popoverContent?: unknown;
+};
+
+const CLOSE_TOOL_DETAIL_POPOVER_EVENT = 'lobe-chat-tool-detail-popover-close';
+
+interface PopoverLabelProps {
+ label: ReactNode;
+ popoverContent: ReactNode;
+}
+
+const PopoverLabel = memo<PopoverLabelProps>(({ label, popoverContent }) => {
+ const [open, setOpen] = useState(false);
+ const suppressUntilRef = useRef(0);
+
+ useEffect(() => {
+ const close = () => {
+ suppressUntilRef.current = Date.now() + 600;
+ setOpen(false);
+ };
+ window.addEventListener(CLOSE_TOOL_DETAIL_POPOVER_EVENT, close);
+
+ return () => window.removeEventListener(CLOSE_TOOL_DETAIL_POPOVER_EVENT, close);
+ }, []);
+
+ const handleOpenChange = useCallback((nextOpen: boolean) => {
+ if (nextOpen && Date.now() < suppressUntilRef.current) return;
+
+ setOpen(nextOpen);
+ }, []);
+
+ return (
+ <Popover
+ arrow={false}
+ content={popoverContent}
+ mouseEnterDelay={0.25}
+ open={open}
+ placement={'rightTop'}
+ positionerProps={{ sideOffset: 10 }}
+ styles={{ content: { padding: 0 } }}
+ onOpenChange={handleOpenChange}
+ >
+ <span
+ style={{ display: 'block', width: '100%' }}
+ onClickCapture={() => setOpen(false)}
+ onContextMenuCapture={() => setOpen(false)}
+ >
+ {label}
+ </span>
+ </Popover>
+ );
+});
+
+PopoverLabel.displayName = 'PopoverLabel';
+
+const wrapPopoverLabel = (label: ReactNode, popoverContent?: unknown) => {
+ if (!popoverContent) return label;
+
+ return <PopoverLabel label={label} popoverContent={popoverContent as ReactNode} />;
+};
+
+const stripPopoverContent = (items?: ActionDropdownMenuItems): ActionDropdownMenuItems =>
+ items?.map((item) => {
+ if (!item) return item;
+ if ('type' in item && item.type === 'divider') return item;
+
+ const nextItem = { ...(item as DropdownItemWithPopover) };
+ const popoverContent = nextItem.popoverContent;
+ delete nextItem.popoverContent;
+
+ if ('children' in nextItem && nextItem.children) {
+ return { ...nextItem, children: stripPopoverContent(nextItem.children) };
+ }
+
+ if ('label' in nextItem) {
+ nextItem.label = wrapPopoverLabel(nextItem.label, popoverContent);
+ }
+
+ return nextItem;
+ }) ?? [];
+
+const PlusAction = memo(() => {
+ const { t } = useTranslation('chat');
+ const { t: tEditor } = useTranslation('editor');
+ const { t: tSetting } = useTranslation('setting');
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const [dropdownOpen, setDropdownOpen] = useState(false);
+
+ const upload = useFileStore((s) => s.uploadChatFiles);
+ const { enableKnowledgeBase } = useServerConfigStore(featureFlagsSelectors);
+
+ const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));
+ const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));
+ const isAgentModeEnabled = useAgentStore(agentSelectors.isAgentModeEnabled);
+ const skillActivateMode = useAgentStore((s) =>
+ chatConfigByIdSelectors.getSkillActivateModeById(agentId)(s),
+ );
+ const [searchMode, useModelBuiltinSearch] = useAgentStore((s) => [
+ chatConfigByIdSelectors.getSearchModeById(agentId)(s),
+ chatConfigByIdSelectors.getUseModelBuiltinSearchById(agentId)(s),
+ ]);
+
+ const isMemoryEnabled = useMemoryEnabled(agentId);
+ const [showTypoBar, setShowTypoBar] = useChatInputStore((s) => [s.showTypoBar, s.setShowTypoBar]);
+ const { canUploadImage, canUploadVideo } = useVisualMediaUploadAbility(model, provider);
+ const enableFC = useModelSupportToolUse(model, provider);
+ const { enabledCount: knowledgeEnabledCount, items: knowledgeItems } = useKnowledgeControls({
+ openAttachKnowledgeModal,
+ });
+ const {
+ autoCount: skillAutoCount,
+ editPluginDrawer: skillEditPluginDrawer,
+ marketItems: skillItems,
+ pinnedCount: skillPinnedCount,
+ } = useToolsControls();
+
+ const isModelBuiltinSearchInternal = useAiInfraStore(
+ aiModelSelectors.isModelBuiltinSearchInternal(model, provider),
+ );
+ const isModelHasBuiltinSearch = useAiInfraStore(
+ aiModelSelectors.isModelHasBuiltinSearchConfig(model, provider),
+ );
+ const isProviderHasBuiltinSearch = useAiInfraStore(
+ aiProviderSelectors.isProviderHasBuiltinSearchConfig(provider),
+ );
+ const showProviderSearch =
+ !isModelBuiltinSearchInternal && (isModelHasBuiltinSearch || isProviderHasBuiltinSearch);
+
+ // Derived active search option
+ const activeSearchOption: 'off' | 'app' | 'provider' =
+ searchMode === 'off' ? 'off' : useModelBuiltinSearch ? 'provider' : 'app';
+
+ const handleToggleMemory = useCallback(async () => {
+ await updateAgentChatConfig({ memory: { enabled: !isMemoryEnabled } });
+ }, [isMemoryEnabled, updateAgentChatConfig]);
+
+ const handleSelectSearch = useCallback(
+ async (option: 'off' | 'app' | 'provider') => {
+ if (option === 'off') {
+ await updateAgentChatConfig({ searchMode: 'off', useModelBuiltinSearch: false });
+ } else if (option === 'app') {
+ await updateAgentChatConfig({ searchMode: 'auto', useModelBuiltinSearch: false });
+ } else {
+ await updateAgentChatConfig({ searchMode: 'auto', useModelBuiltinSearch: true });
+ }
+ },
+ [updateAgentChatConfig],
+ );
+
+ const handleOpenTools = useCallback(() => {
+ setDropdownOpen(false);
+ createSkillStoreModal();
+ }, []);
+
+ const items: ActionDropdownMenuItems = useMemo(() => {
+ const renderActive = (label: string, active: boolean) =>
+ active ? (
+ <div className={cx(activeLabel)}>
+ <span>{label}</span>
+ <Icon icon={CheckIcon} size={14} />
+ </div>
+ ) : (
+ label
+ );
+
+ const renderOption = (title: string, description: string, active: boolean) => (
+ <div className={cx(optionLabel)}>
+ <div>
+ <div className="title">{title}</div>
+ {description && <div className="desc">{description}</div>}
+ </div>
+ {active && <Icon icon={CheckIcon} size={14} />}
+ </div>
+ );
+
+ const renderSearchOption = (
+ icon: ReactNode,
+ title: string,
+ description: string,
+ active: boolean,
+ ) => (
+ <div className={cx(searchOptionRow)}>
+ <div className={cx(searchIconBox)}>{icon}</div>
+ <div style={{ flex: 1, minWidth: 0 }}>
+ <div className="title">{title}</div>
+ {description && <div className="desc">{description}</div>}
+ </div>
+ {active && <Icon icon={CheckIcon} size={14} />}
+ </div>
+ );
+
+ const renderLabelWithCount = (label: string, count: number, prefix?: string) =>
+ count > 0 || prefix ? (
+ <span className={cx(labelWithChip)}>
+ <span>{label}</span>
+ <span className={cx(countChip)}>{prefix ? `${prefix} | ${count}` : count}</span>
+ </span>
+ ) : (
+ label
+ );
+
+ const skillMenuItems = stripPopoverContent(skillItems as ActionDropdownMenuItems);
+
+ const uploadItems: ActionDropdownMenuItems = [
+ {
+ closeOnClick: false,
+ icon: FileUp,
+ key: 'upload-file-or-image',
+ label: (
+ <Upload
+ multiple
+ showUploadList={false}
+ beforeUpload={async (file) => {
+ if (file.type.startsWith('image') && !canUploadImage) return false;
+ if (file.type.startsWith('video') && !canUploadVideo) return false;
+ const validation = validateVideoFileSize(file);
+ if (!validation.isValid) {
+ message.error(
+ t('upload.validation.videoSizeExceeded', { actualSize: validation.actualSize }),
+ );
+ return false;
+ }
+ setDropdownOpen(false);
+ await upload([file]);
+ return false;
+ }}
+ >
+ <div className={cx(hotArea)}>{t('upload.action.fileOrImageUpload')}</div>
+ </Upload>
+ ),
+ },
+ ];
+
+ // In auto mode every installed skill is callable, so show pinned + auto.
+ // In manual mode only the pinned ones are active, so show pinned only.
+ const activeSkillCount =
+ skillActivateMode === 'auto' ? skillPinnedCount + skillAutoCount : skillPinnedCount;
+
+ const toolsItems: ActionDropdownMenuItems =
+ isAgentModeEnabled && enableFC
+ ? [
+ { type: 'divider' },
+ {
+ children: skillMenuItems,
+ icon: activeIcon(SkillsIcon, activeSkillCount > 0),
+ key: 'tools',
+ label: renderLabelWithCount(
+ tSetting('tools.title'),
+ activeSkillCount,
+ tSetting(
+ skillActivateMode === 'auto'
+ ? 'tools.skillActivateMode.auto.title'
+ : 'tools.skillActivateMode.manual.title',
+ ),
+ ),
+ },
+ {
+ icon: Store,
+ key: 'add-skills',
+ label: t('plus.addSkills'),
+ onClick: handleOpenTools,
+ },
+ ]
+ : [];
+
+ const capabilityItems: ActionDropdownMenuItems = [
+ { type: 'divider' },
+ // Rich text toolbar toggle
+ {
+ icon: TypeIcon,
+ key: 'typo',
+ label: renderActive(
+ tEditor(showTypoBar ? 'actions.typobar.off' : 'actions.typobar.on'),
+ Boolean(showTypoBar),
+ ),
+ onClick: () => setShowTypoBar(!showTypoBar),
+ },
+ { type: 'divider' },
+ // Memory toggle
+ {
+ icon: activeIcon(isMemoryEnabled ? Brain : BrainOffIcon, Boolean(isMemoryEnabled)),
+ key: 'memory',
+ label: renderActive(t('memory.title'), Boolean(isMemoryEnabled)),
+ onClick: handleToggleMemory,
+ },
+ // Web search: simple toggle when 2 options, submenu when 3
+ ...(showProviderSearch
+ ? [
+ {
+ children: [
+ {
+ key: 'search-off',
+ label: renderSearchOption(
+ <Icon icon={GlobeOffIcon} size={18} />,
+ t('plus.search.off'),
+ t('plus.search.offDesc'),
+ activeSearchOption === 'off',
+ ),
+ onClick: () => handleSelectSearch('off'),
+ },
+ {
+ key: 'search-app',
+ label: renderSearchOption(
+ <Icon
+ color={activeSearchOption === 'app' ? cssVar.colorInfo : undefined}
+ icon={SearchCheck}
+ size={18}
+ />,
+ t('plus.search.appSearch'),
+ t('plus.search.appSearchDesc'),
+ activeSearchOption === 'app',
+ ),
+ onClick: () => handleSelectSearch('app'),
+ },
+ {
+ key: 'search-provider',
+ label: renderSearchOption(
+ <Icon
+ color={activeSearchOption === 'provider' ? cssVar.colorInfo : undefined}
+ icon={CloudCog}
+ size={18}
+ />,
+ t('plus.search.modelSearch'),
+ t('plus.search.modelSearchDesc'),
+ activeSearchOption === 'provider',
+ ),
+ onClick: () => handleSelectSearch('provider'),
+ },
+ ],
+ icon: activeIcon(
+ activeSearchOption === 'off' ? GlobeOffIcon : Globe,
+ activeSearchOption !== 'off',
+ ),
+ key: 'search-group',
+ label: t('search.title'),
+ } as ActionDropdownMenuItems[number],
+ ]
+ : [
+ {
+ icon: activeIcon(
+ activeSearchOption === 'off' ? GlobeOffIcon : Globe,
+ activeSearchOption !== 'off',
+ ),
+ key: 'search-toggle',
+ label: renderActive(t('search.title'), activeSearchOption !== 'off'),
+ onClick: () => handleSelectSearch(activeSearchOption === 'off' ? 'app' : 'off'),
+ } as ActionDropdownMenuItems[number],
+ ]),
+ ...toolsItems,
+ ];
+
+ const knowledgeSectionItems: ActionDropdownMenuItems = enableKnowledgeBase
+ ? [
+ {
+ children: knowledgeItems,
+ icon: activeIcon(LibraryBig, knowledgeEnabledCount > 0),
+ key: 'knowledge-base',
+ label: renderLabelWithCount(t('knowledgeBase.title'), knowledgeEnabledCount),
+ } as ActionDropdownMenuItems[number],
+ ]
+ : [];
+
+ return [...uploadItems, ...knowledgeSectionItems, ...capabilityItems];
+ }, [
+ activeSearchOption,
+ canUploadImage,
+ canUploadVideo,
+ enableFC,
+ enableKnowledgeBase,
+ handleOpenTools,
+ handleSelectSearch,
+ handleToggleMemory,
+ isAgentModeEnabled,
+ isMemoryEnabled,
+ knowledgeEnabledCount,
+ setShowTypoBar,
+ showProviderSearch,
+ showTypoBar,
+ skillActivateMode,
+ skillAutoCount,
+ skillPinnedCount,
+ knowledgeItems,
+ t,
+ tEditor,
+ tSetting,
+ skillItems,
+ upload,
+ ]);
+
+ return (
+ <>
+ <Action
+ icon={PlusIcon}
+ open={dropdownOpen}
+ size={{ blockSize: 32, borderRadius: 16, size: 18 }}
+ title={t('plus.tooltip')}
+ tooltipProps={{ placement: 'top' }}
+ dropdown={{
+ menu: { items },
+ minWidth: 220,
+ placement: 'topLeft',
+ }}
+ onOpenChange={setDropdownOpen}
+ />
+ {skillEditPluginDrawer}
+ </>
+ );
+});
+
+PlusAction.displayName = 'PlusAction';
+
+const Plus = memo(() => (
+ <Suspense
+ fallback={
+ <Action
+ disabled
+ icon={PlusIcon}
+ size={{ blockSize: 32, borderRadius: 16, size: 18 }}
+ title=""
+ />
+ }
+ >
+ <PlusAction />
+ </Suspense>
+));
+
+Plus.displayName = 'Plus';
+
+export default Plus;
diff --git a/src/features/ChatInput/ActionBar/Token/TokenTag.tsx b/src/features/ChatInput/ActionBar/Token/TokenTag.tsx
index 6281f3b3ecd..03483315f8a 100644
--- a/src/features/ChatInput/ActionBar/Token/TokenTag.tsx
+++ b/src/features/ChatInput/ActionBar/Token/TokenTag.tsx
@@ -21,21 +21,22 @@ import { useUserStore } from '@/store/user';
import { userGeneralSettingsSelectors } from '@/store/user/selectors';
import { useAgentId } from '../../hooks/useAgentId';
+import { useChatInputStore } from '../../store';
import ActionPopover from '../components/ActionPopover';
import TokenProgress from './TokenProgress';
const toolNameResolver = new ToolNameResolver();
-interface TokenTagProps {
- total: string;
-}
-const Token = memo<TokenTagProps>(({ total: messageString }) => {
+const Token = memo(() => {
const { t } = useTranslation(['chat', 'components']);
- const [input, historySummary] = useChatStore((s) => [
- s.inputMessage,
- topicSelectors.currentActiveTopicSummary(s)?.content || '',
+ const [input, contextWindowMessages] = useChatInputStore((s) => [
+ s.markdownContent,
+ s.contextWindowMessages,
]);
+ const historySummary = useChatStore(
+ (s) => topicSelectors.currentActiveTopicSummary(s)?.content || '',
+ );
const agentId = useAgentId();
const [systemRole, model, provider] = useAgentStore((s) => {
@@ -89,8 +90,10 @@ const Token = memo<TokenTagProps>(({ total: messageString }) => {
// Chat usage token
const inputTokenCount = useTokenCount(input);
- // Use messageString directly (from displayMessageSelectors.mainAIChatsMessageString)
- // which correctly handles group chats via currentDisplayChatKey (includes groupId)
+ const messageString =
+ contextWindowMessages
+ ?.map((message) => (typeof message.content === 'string' ? message.content : ''))
+ .join('') || '';
const chatsToken = useTokenCount(messageString) + inputTokenCount;
// SystemRole token
@@ -188,6 +191,10 @@ const Token = memo<TokenTagProps>(({ total: messageString }) => {
maxValue={maxTokens}
mode={'used'}
value={totalToken}
+ size={{
+ blockSize: 32,
+ size: 18,
+ }}
text={{
overload: t('tokenTag.overload'),
remained: t('tokenTag.remained'),
diff --git a/src/features/ChatInput/ActionBar/Token/index.tsx b/src/features/ChatInput/ActionBar/Token/index.tsx
index cf91475316d..b6f11012840 100644
--- a/src/features/ChatInput/ActionBar/Token/index.tsx
+++ b/src/features/ChatInput/ActionBar/Token/index.tsx
@@ -3,8 +3,6 @@ import { memo } from 'react';
import { useModelHasContextWindowToken } from '@/hooks/useModelHasContextWindowToken';
import dynamic from '@/libs/next/dynamic';
-import { useChatStore } from '@/store/chat';
-import { displayMessageSelectors, threadSelectors } from '@/store/chat/selectors';
const LargeTokenContent = dynamic(() => import('./TokenTag'), { ssr: false });
@@ -14,22 +12,14 @@ const Token = memo<PropsWithChildren>(({ children }) => {
return showTag && children;
});
-export const MainToken = memo(() => {
- const total = useChatStore(displayMessageSelectors.mainAIChatsMessageString);
-
+const ContextWindow = memo(() => {
return (
<Token>
- <LargeTokenContent total={total} />
+ <LargeTokenContent />
</Token>
);
});
-export const PortalToken = memo(() => {
- const total = useChatStore(threadSelectors.portalDisplayChatsString);
+ContextWindow.displayName = 'ContextWindow';
- return (
- <Token>
- <LargeTokenContent total={total} />
- </Token>
- );
-});
+export default ContextWindow;
diff --git a/src/features/ChatInput/ActionBar/Tools/PopoverContent.tsx b/src/features/ChatInput/ActionBar/Tools/PopoverContent.tsx
index 747d08aa213..caae6e3cea8 100644
--- a/src/features/ChatInput/ActionBar/Tools/PopoverContent.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/PopoverContent.tsx
@@ -13,12 +13,12 @@ import ToolsList, { toolsListStyles } from './ToolsList';
const styles = createStaticStyles(({ css }) => ({
footer: css`
padding: 4px;
- border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ border-block-start: 1px solid ${cssVar.colorFill};
`,
header: css`
padding-block: 8px;
padding-inline: 8px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ border-block-end: 1px solid ${cssVar.colorFill};
`,
trailingIcon: css`
opacity: 0.5;
diff --git a/src/features/ChatInput/ActionBar/Tools/ToolsList.tsx b/src/features/ChatInput/ActionBar/Tools/ToolsList.tsx
index 1618c46d84a..65c41e8ed96 100644
--- a/src/features/ChatInput/ActionBar/Tools/ToolsList.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/ToolsList.tsx
@@ -3,10 +3,12 @@ import { Flexbox, Icon, Popover, Text } from '@lobehub/ui';
import { Divider } from 'antd';
import { createStaticStyles, cssVar } from 'antd-style';
import type { ReactNode } from 'react';
-import { Fragment, isValidElement, memo, useCallback, useState } from 'react';
+import { Fragment, isValidElement, memo, useCallback, useEffect, useRef, useState } from 'react';
import { useScrollSignal } from './ScrollSignalContext';
+const CLOSE_TOOL_DETAIL_POPOVER_EVENT = 'lobe-chat-tool-detail-popover-close';
+
export const toolsListStyles = createStaticStyles(({ css }) => ({
groupLabel: css`
padding-block: 12px 4px;
@@ -70,6 +72,7 @@ const DividerItem = memo<{ index: number }>(({ index }) => (
const RegularItem = memo<{ index: number; item: ToolItemData }>(({ item, index }) => {
const [open, setOpen] = useState(false);
+ const suppressUntilRef = useRef(0);
// Close hover popover whenever the surrounding list scrolls — avoids the
// detail panel hovering in mid-air after its anchor row has moved away.
@@ -79,6 +82,22 @@ const RegularItem = memo<{ index: number; item: ToolItemData }>(({ item, index }
}, []),
);
+ // Close hover popover when a policy menu (or other consumer) signals it —
+ // prevents the detail panel from overlapping the policy menu opened from the "..." button.
+ useEffect(() => {
+ const close = () => {
+ suppressUntilRef.current = Date.now() + 600;
+ setOpen(false);
+ };
+ window.addEventListener(CLOSE_TOOL_DETAIL_POPOVER_EVENT, close);
+ return () => window.removeEventListener(CLOSE_TOOL_DETAIL_POPOVER_EVENT, close);
+ }, []);
+
+ const handleOpenChange = useCallback((nextOpen: boolean) => {
+ if (nextOpen && Date.now() < suppressUntilRef.current) return;
+ setOpen(nextOpen);
+ }, []);
+
const iconNode = item.icon ? (
isValidElement(item.icon) ? (
item.icon
@@ -112,7 +131,7 @@ const RegularItem = memo<{ index: number; item: ToolItemData }>(({ item, index }
placement={'rightTop'}
positionerProps={{ sideOffset: 8 }}
styles={{ content: { padding: 0 } }}
- onOpenChange={setOpen}
+ onOpenChange={handleOpenChange}
>
{row}
</Popover>
diff --git a/src/features/ChatInput/ActionBar/Tools/index.tsx b/src/features/ChatInput/ActionBar/Tools/index.tsx
index 0eb7851d369..88db7c4a91c 100644
--- a/src/features/ChatInput/ActionBar/Tools/index.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/index.tsx
@@ -1,5 +1,5 @@
import { Blocks } from 'lucide-react';
-import { memo, Suspense, useCallback, useState } from 'react';
+import { memo, Suspense, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { createSkillStoreModal } from '@/features/SkillStore';
@@ -14,10 +14,7 @@ import { useControls } from './useControls';
const Tools = memo(() => {
const { t } = useTranslation('setting');
- const [updating, setUpdating] = useState(false);
- const { marketItems } = useControls({
- setUpdating,
- });
+ const { marketItems, editPluginDrawer } = useControls();
const agentId = useAgentId();
const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));
@@ -36,7 +33,6 @@ const Tools = memo(() => {
<Suspense fallback={<Action disabled icon={Blocks} title={t('tools.title')} />}>
<Action
icon={Blocks}
- loading={updating}
showTooltip={false}
title={t('tools.title')}
popover={{
@@ -50,6 +46,7 @@ const Tools = memo(() => {
},
}}
/>
+ {editPluginDrawer}
</Suspense>
);
});
diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.tsx b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
index 935afef032a..ddc26b6e0e7 100644
--- a/src/features/ChatInput/ActionBar/Tools/useControls.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
@@ -4,13 +4,32 @@ import {
RECOMMENDED_SKILLS,
RecommendedSkillType,
} from '@lobechat/const';
-import { type ItemType } from '@lobehub/ui';
-import { Avatar, Icon } from '@lobehub/ui';
+import type { ItemType } from '@lobehub/ui';
+import { Avatar, Icon, Popover, SearchBar, stopPropagation, Tag, Tooltip } from '@lobehub/ui';
+import { confirmModal } from '@lobehub/ui/base-ui';
import { McpIcon, SkillsIcon } from '@lobehub/ui/icons';
+import { Switch } from 'antd';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
import isEqual from 'fast-deep-equal';
-import { useMemo } from 'react';
+import {
+ BadgeCheck,
+ Check,
+ ChevronDown,
+ ChevronRight,
+ MoreHorizontal,
+ Package,
+ Pin,
+ Settings,
+ Trash2,
+ Wrench,
+ Zap,
+} from 'lucide-react';
+import type { ReactNode } from 'react';
+import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+import DevModal from '@/features/PluginDevModal';
import { useCheckPluginsIsInstalled } from '@/hooks/useCheckPluginsIsInstalled';
import { useFetchInstalledPlugins } from '@/hooks/useFetchInstalledPlugins';
import { useAgentStore } from '@/store/agent';
@@ -24,8 +43,11 @@ import {
lobehubSkillStoreSelectors,
pluginSelectors,
} from '@/store/tool/selectors';
+import { KlavisServerStatus } from '@/store/tool/slices/klavisStore';
+import { LobehubSkillStatus } from '@/store/tool/slices/lobehubSkillStore/types';
import { useAgentId } from '../../hooks/useAgentId';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
import KlavisServerItem from './KlavisServerItem';
import KlavisSkillIcon from './KlavisSkillIcon';
import LobehubSkillIcon from './LobehubSkillIcon';
@@ -35,16 +57,360 @@ import MarketSkillIcon from './MarketSkillIcon';
import ToolItem from './ToolItem';
import ToolItemDetailPopover from './ToolItemDetailPopover';
-const SKILL_ICON_SIZE = 20;
+const SKILL_ICON_SIZE = 18;
+const CLOSE_TOOL_DETAIL_POPOVER_EVENT = 'lobe-chat-tool-detail-popover-close';
+
+const officialTag = (
+ <Tooltip placement={'top'} title={'LobeHub'}>
+ <Tag color={'success'} icon={<Icon icon={BadgeCheck} />} size={'small'} />
+ </Tooltip>
+);
+
+type SkillPolicyMode = 'auto' | 'pinned';
+
+interface SkillDeleteConfig {
+ displayName: string;
+ onDelete: () => Promise<void> | void;
+}
+
+interface SkillConfigureConfig {
+ onConfigure: () => void;
+}
+
+type SkillMenuItem = NonNullable<ItemType> & {
+ popoverContent?: ReactNode;
+ searchText?: string;
+};
+
+const styles = createStaticStyles(({ css }) => ({
+ activationGroupHeader: css`
+ cursor: pointer;
+
+ display: flex;
+ gap: 12px;
+ align-items: center;
+ justify-content: space-between;
+
+ width: 100%;
+ min-width: 0;
+ padding-block: 4px;
+ `,
+ activationGroupChevron: css`
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+
+ width: 24px;
+ height: 24px;
+
+ color: ${cssVar.colorTextTertiary};
+ `,
+ activationGroupTitle: css`
+ display: flex;
+ gap: 7px;
+ align-items: center;
+
+ min-width: 0;
+ min-height: 18px;
+ `,
+ activationGroupTitleBlock: css`
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ min-width: 0;
+ `,
+ activationGroupTitleText: css`
+ overflow: hidden;
+
+ min-width: 0;
+
+ font-size: 14px;
+ font-weight: 500;
+ color: ${cssVar.colorText};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ count: css`
+ flex: none;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ activationGroupActions: css`
+ display: flex;
+ flex: none;
+ gap: 8px;
+ align-items: center;
+ `,
+ switchWrap: css`
+ display: inline-flex;
+ flex: none;
+ align-items: center;
+ `,
+ iconAuto: css`
+ color: ${cssVar.colorInfo};
+ `,
+ iconDefault: css`
+ color: ${cssVar.colorTextTertiary};
+ `,
+ iconPinned: css`
+ color: ${cssVar.colorInfo};
+ `,
+ policyButton: css`
+ cursor: pointer;
+
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+
+ width: 24px;
+ height: 24px;
+ padding: 0;
+ border: 0;
+ border-radius: 6px;
+
+ color: ${cssVar.colorTextTertiary};
+
+ background: transparent;
+
+ transition:
+ color 0.2s,
+ background 0.2s;
+
+ &:hover {
+ color: ${cssVar.colorTextSecondary};
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ deleteButton: css`
+ cursor: pointer;
+
+ display: flex;
+ gap: 10px;
+ align-items: center;
+
+ width: 100%;
+ min-height: 36px;
+ padding-block: 8px;
+ padding-inline: 10px;
+ border: 0;
+ border-radius: 6px;
+
+ font-size: 14px;
+ line-height: 20px;
+ color: ${cssVar.colorError};
+
+ background: transparent;
+
+ transition: background 150ms ${cssVar.motionEaseOut};
+
+ &:hover {
+ background: ${cssVar.colorErrorBg};
+ }
+ `,
+ deleteDivider: css`
+ height: 1px;
+ margin-block: 2px;
+ margin-inline: 4px;
+ background: ${cssVar.colorBorderSecondary};
+ `,
+ deleteIcon: css`
+ color: ${cssVar.colorError};
+ `,
+ policyCheck: css`
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+
+ width: 16px;
+ height: 16px;
+
+ color: ${cssVar.colorInfo};
+ `,
+ policyItem: css`
+ cursor: pointer;
+
+ display: flex;
+ gap: 10px;
+ align-items: center;
+
+ width: 100%;
+ min-height: 36px;
+ padding-block: 8px;
+ padding-inline: 10px;
+ border: 0;
+ border-radius: 6px;
-export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean) => void }) => {
+ font-size: 14px;
+ line-height: 20px;
+ color: ${cssVar.colorText};
+
+ background: transparent;
+
+ transition: background 150ms ${cssVar.motionEaseOut};
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ policyItemIcon: css`
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+
+ width: 16px;
+ height: 16px;
+ `,
+ policyPanel: css`
+ min-width: 132px;
+ padding: 4px;
+ border-radius: ${cssVar.borderRadius};
+
+ background: ${cssVar.colorBgElevated};
+ box-shadow:
+ 0 0 15px 0 #00000008,
+ 0 2px 30px 0 #00000014;
+ `,
+ policyText: css`
+ flex: 1;
+ text-align: start;
+ `,
+ search: css`
+ width: 100%;
+ `,
+ searchBox: css`
+ display: flex;
+ align-items: center;
+
+ height: 36px;
+ padding-inline: 10px;
+ border-radius: 10px;
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ toolLabel: css`
+ display: flex;
+ flex: 1;
+ gap: 6px;
+ align-items: center;
+
+ min-width: 0;
+ `,
+ toolLabelText: css`
+ overflow: hidden;
+ flex: 0 1 auto;
+
+ min-width: 0;
+
+ line-height: 1.4;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ toolRow: css`
+ display: flex;
+ gap: 16px;
+ align-items: center;
+ justify-content: space-between;
+
+ width: 100%;
+ min-width: 0;
+ `,
+ typeTag: css`
+ display: inline-flex;
+ flex: none;
+ align-items: center;
+
+ padding-block: 1px;
+ padding-inline: 4px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 4px;
+
+ color: ${cssVar.colorTextTertiary};
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ statsFooter: css`
+ display: flex;
+ gap: 14px;
+ align-items: center;
+ width: 100%;
+ `,
+ statsSettingsButton: css`
+ cursor: pointer;
+
+ display: inline-flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+
+ width: 24px;
+ height: 24px;
+ margin-inline-start: auto;
+ padding: 0;
+ border: 0;
+ border-radius: 6px;
+
+ color: ${cssVar.colorTextTertiary};
+
+ background: transparent;
+
+ transition:
+ color 0.2s,
+ background 0.2s;
+
+ &:hover {
+ color: ${cssVar.colorTextSecondary};
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ statsItem: css`
+ display: inline-flex;
+ gap: 5px;
+ align-items: center;
+
+ font-size: 12px;
+ line-height: 18px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+}));
+
+export const useControls = () => {
const { t } = useTranslation('setting');
const agentId = useAgentId();
+ const navigate = useNavigate();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const [pinnedOpen, setPinnedOpen] = useState(true);
+ const [autoOpen, setAutoOpen] = useState(true);
+ const [policyOpenId, setPolicyOpenId] = useState<string | null>(null);
+ const [searchKeyword, setSearchKeyword] = useState('');
+ const [autoModeLoading, setAutoModeLoading] = useState(false);
const list = useToolStore(pluginSelectors.installedPluginMetaList, isEqual);
+ const [
+ uninstallPlugin,
+ removeKlavisServer,
+ deleteAgentSkill,
+ installCustomPlugin,
+ updateNewCustomPlugin,
+ uninstallBuiltinTool,
+ ] = useToolStore((s) => [
+ s.uninstallCustomPlugin,
+ s.removeKlavisServer,
+ s.deleteAgentSkill,
+ s.installCustomPlugin,
+ s.updateNewCustomPlugin,
+ s.uninstallBuiltinTool,
+ ]);
+ const [editingPluginId, setEditingPluginId] = useState<string | null>(null);
+ const editingCustomPlugin = useToolStore(
+ pluginSelectors.getCustomPluginById(editingPluginId ?? ''),
+ isEqual,
+ );
const [checked, togglePlugin] = useAgentStore((s) => [
agentByIdSelectors.getAgentPluginsById(agentId)(s),
s.togglePlugin,
]);
+ const checkedSet = useMemo(() => new Set(checked), [checked]);
// In manual skill-activate mode, surface hidden builtin tools (web-browsing,
// cloud-sandbox, knowledge-base, etc.) so users can explicitly enable/disable them.
// In auto mode the activator handles those tools transparently, so they remain hidden.
@@ -53,6 +419,7 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
const isManualSkillMode = useAgentStore(
(s) => chatConfigByIdSelectors.getSkillActivateModeById(agentId)(s) === 'manual',
);
+ const isAutoSkillMode = !isManualSkillMode;
const builtinList = useToolStore(
isManualSkillMode
? builtinToolSelectors.metaListIncludingHidden
@@ -61,6 +428,234 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
);
const plugins = useAgentStore((s) => agentByIdSelectors.getAgentPluginsById(agentId)(s));
+ const updateSkillPolicy = useCallback(
+ async (id: string, mode: SkillPolicyMode) => {
+ const shouldPin = mode === 'pinned';
+ if (checkedSet.has(id) === shouldPin) return;
+
+ await togglePlugin(id, shouldPin);
+ },
+ [checkedSet, togglePlugin],
+ );
+
+ const openSkillPolicyMenu = useCallback((id: string) => {
+ if (typeof window !== 'undefined') {
+ window.dispatchEvent(new Event(CLOSE_TOOL_DETAIL_POPOVER_EVENT));
+ }
+ setPolicyOpenId(id);
+ }, []);
+
+ const renderPolicyMenu = useCallback(
+ (id: string, deleteConfig?: SkillDeleteConfig, configureConfig?: SkillConfigureConfig) => {
+ const mode: SkillPolicyMode = checkedSet.has(id) ? 'pinned' : 'auto';
+ const renderCheck = (value: SkillPolicyMode) =>
+ mode === value ? (
+ <span className={cx(styles.policyCheck)}>
+ <Icon icon={Check} size={14} />
+ </span>
+ ) : (
+ <span className={cx(styles.policyCheck)} />
+ );
+
+ const renderPolicyItem = (value: SkillPolicyMode, icon: ReactNode) => (
+ <button
+ className={cx(styles.policyItem)}
+ type="button"
+ onClick={async (event) => {
+ event.stopPropagation();
+ setPolicyOpenId(null);
+ await updateSkillPolicy(id, value);
+ }}
+ >
+ <span className={cx(styles.policyItemIcon)}>{icon}</span>
+ <span className={cx(styles.policyText)}>{t(`tools.activation.${value}`)}</span>
+ {renderCheck(value)}
+ </button>
+ );
+
+ const content = (
+ <div
+ className={cx(styles.policyPanel)}
+ onClick={(event) => event.stopPropagation()}
+ onContextMenu={(event) => event.stopPropagation()}
+ >
+ {renderPolicyItem(
+ 'pinned',
+ <Icon
+ className={cx(mode === 'pinned' ? styles.iconPinned : styles.iconDefault)}
+ icon={Pin}
+ size={15}
+ />,
+ )}
+ {renderPolicyItem(
+ 'auto',
+ <Icon
+ className={cx(mode === 'auto' ? styles.iconAuto : styles.iconDefault)}
+ icon={Zap}
+ size={15}
+ />,
+ )}
+ {(configureConfig || deleteConfig) && <div className={cx(styles.deleteDivider)} />}
+ {configureConfig && (
+ <button
+ className={cx(styles.policyItem)}
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ setPolicyOpenId(null);
+ configureConfig.onConfigure();
+ }}
+ >
+ <span className={cx(styles.policyItemIcon)}>
+ <Icon icon={Wrench} size={15} />
+ </span>
+ <span className={cx(styles.policyText)}>{t('tools.builtins.configure')}</span>
+ </button>
+ )}
+ {deleteConfig && (
+ <button
+ className={cx(styles.deleteButton)}
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ setPolicyOpenId(null);
+ confirmModal({
+ content: t('tools.builtins.uninstallConfirm.desc', {
+ name: deleteConfig.displayName,
+ }),
+ okButtonProps: { danger: true },
+ onOk: async () => {
+ await deleteConfig.onDelete();
+ },
+ title: t('tools.builtins.uninstallConfirm.title', {
+ name: deleteConfig.displayName,
+ }),
+ });
+ }}
+ >
+ <span className={cx(styles.policyItemIcon)}>
+ <Icon className={cx(styles.deleteIcon)} icon={Trash2} size={15} />
+ </span>
+ <span className={cx(styles.policyText)}>{t('tools.builtins.uninstall')}</span>
+ </button>
+ )}
+ </div>
+ );
+
+ return (
+ <Popover
+ arrow={false}
+ content={content}
+ open={policyOpenId === id}
+ placement="rightTop"
+ positionerProps={{ sideOffset: 8 }}
+ styles={{ content: { padding: 0 } }}
+ trigger="click"
+ onOpenChange={(open) => (open ? openSkillPolicyMenu(id) : setPolicyOpenId(null))}
+ >
+ <button
+ aria-label={t('tools.skillActivateMode.title')}
+ className={cx(styles.policyButton)}
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ if (typeof window !== 'undefined') {
+ window.dispatchEvent(new Event(CLOSE_TOOL_DETAIL_POPOVER_EVENT));
+ }
+ }}
+ onContextMenu={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ openSkillPolicyMenu(id);
+ }}
+ onPointerDown={(event) => {
+ event.stopPropagation();
+ if (typeof window !== 'undefined') {
+ window.dispatchEvent(new Event(CLOSE_TOOL_DETAIL_POPOVER_EVENT));
+ }
+ }}
+ onPointerEnter={() => {
+ if (typeof window !== 'undefined') {
+ window.dispatchEvent(new Event(CLOSE_TOOL_DETAIL_POPOVER_EVENT));
+ }
+ }}
+ >
+ <Icon icon={MoreHorizontal} size={15} />
+ </button>
+ </Popover>
+ );
+ },
+ [checkedSet, openSkillPolicyMenu, policyOpenId, t, updateSkillPolicy],
+ );
+
+ const renderToolLabel = useCallback(
+ (
+ id: string,
+ label: ReactNode,
+ action: ReactNode,
+ badge?: ReactNode,
+ icon?: ReactNode,
+ extraTag?: ReactNode,
+ ) => (
+ <span
+ className={cx(styles.toolRow)}
+ onContextMenu={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ openSkillPolicyMenu(id);
+ }}
+ >
+ <span className={cx(styles.toolLabel)}>
+ {icon}
+ <span className={cx(styles.toolLabelText)}>{label}</span>
+ {extraTag}
+ {badge && <span className={cx(styles.typeTag)}>{badge}</span>}
+ </span>
+ {action}
+ </span>
+ ),
+ [openSkillPolicyMenu],
+ );
+
+ const createManagedSkillItem = useCallback(
+ ({
+ badge,
+ configureConfig,
+ deleteConfig,
+ extraTag,
+ icon,
+ id,
+ popoverContent,
+ searchText,
+ title,
+ }: {
+ badge?: ReactNode;
+ configureConfig?: SkillConfigureConfig;
+ deleteConfig?: SkillDeleteConfig;
+ extraTag?: ReactNode;
+ icon: ReactNode;
+ id: string;
+ popoverContent?: ReactNode;
+ searchText?: string;
+ title: ReactNode;
+ }): SkillMenuItem =>
+ ({
+ closeOnClick: false,
+ key: id,
+ label: renderToolLabel(
+ id,
+ title,
+ renderPolicyMenu(id, deleteConfig, configureConfig),
+ badge,
+ icon,
+ extraTag,
+ ),
+ popoverContent,
+ searchText: searchText || String(title || id),
+ }) as SkillMenuItem,
+ [renderPolicyMenu, renderToolLabel],
+ );
+
// Klavis-related state
const allKlavisServers = useToolStore(klavisStoreSelectors.getServers, isEqual);
const isKlavisEnabledInEnv = useServerConfigStore(serverConfigSelectors.enableKlavis);
@@ -98,9 +693,12 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
useFetchLobehubSkillConnections(isLobehubSkillEnabled);
// Get connected server by identifier
- const getServerByName = (identifier: string) => {
- return allKlavisServers.find((server) => server.identifier === identifier);
- };
+ const getServerByName = useCallback(
+ (identifier: string) => {
+ return allKlavisServers.find((server) => server.identifier === identifier);
+ },
+ [allKlavisServers],
+ );
// Get all Klavis server type identifier sets (used for filtering builtinList)
// Using KLAVIS_SERVER_TYPES instead of connected servers here, because we want to filter out all possible Klavis types
@@ -163,19 +761,12 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
? KLAVIS_SERVER_TYPES.filter(
(type) =>
installedKlavisIds.has(type.identifier) || recommendedKlavisIds.has(type.identifier),
- ).map((type) => ({
- icon: <KlavisSkillIcon icon={type.icon} label={type.label} size={SKILL_ICON_SIZE} />,
- key: type.identifier,
- label: (
- <KlavisServerItem
- agentId={agentId}
- identifier={type.identifier}
- label={type.label}
- server={getServerByName(type.identifier)}
- serverName={type.serverName}
- />
- ),
- popoverContent: (
+ ).map((type) => {
+ const server = getServerByName(type.identifier);
+ const icon = (
+ <KlavisSkillIcon icon={type.icon} label={type.label} size={SKILL_ICON_SIZE} />
+ );
+ const popoverContent = (
<ToolItemDetailPopover
icon={<KlavisSkillIcon icon={type.icon} label={type.label} size={36} />}
identifier={type.identifier}
@@ -185,10 +776,51 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
defaultValue: type.description,
})}
/>
- ),
- }))
+ );
+
+ if (server?.status === KlavisServerStatus.CONNECTED) {
+ return createManagedSkillItem({
+ badge: <Icon icon={McpIcon} size={12} />,
+ deleteConfig: {
+ displayName: type.label,
+ onDelete: () => removeKlavisServer(server.identifier),
+ },
+ extraTag: type.author === 'LobeHub' ? officialTag : undefined,
+ icon,
+ id: server.identifier,
+ popoverContent,
+ searchText: `${type.label} ${server.identifier}`,
+ title: type.label,
+ });
+ }
+
+ return {
+ icon,
+ key: type.identifier,
+ label: (
+ <KlavisServerItem
+ agentId={agentId}
+ identifier={type.identifier}
+ label={type.label}
+ server={server}
+ serverName={type.serverName}
+ />
+ ),
+ popoverContent,
+ searchText: type.label,
+ };
+ })
: [],
- [isKlavisEnabledInEnv, allKlavisServers, installedKlavisIds, recommendedKlavisIds, agentId, t],
+ [
+ isKlavisEnabledInEnv,
+ installedKlavisIds,
+ recommendedKlavisIds,
+ agentId,
+ t,
+ createManagedSkillItem,
+ getServerByName,
+ removeKlavisServer,
+ ],
);
// LobeHub Skill Provider list items - only show installed or recommended
@@ -198,23 +830,16 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
? LOBEHUB_SKILL_PROVIDERS.filter(
(provider) =>
installedLobehubIds.has(provider.id) || recommendedLobehubIds.has(provider.id),
- ).map((provider) => ({
- icon: (
+ ).map((provider) => {
+ const server = allLobehubSkillServers.find((s) => s.identifier === provider.id);
+ const icon = (
<LobehubSkillIcon
icon={provider.icon}
label={provider.label}
size={SKILL_ICON_SIZE}
/>
- ),
- key: provider.id, // Use provider.id as key, consistent with pluginId
- label: (
- <LobehubSkillServerItem
- agentId={agentId}
- label={provider.label}
- provider={provider.id}
- />
- ),
- popoverContent: (
+ );
+ const popoverContent = (
<ToolItemDetailPopover
icon={<LobehubSkillIcon icon={provider.icon} label={provider.label} size={36} />}
identifier={provider.id}
@@ -224,8 +849,34 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
defaultValue: provider.description,
})}
/>
- ),
- }))
+ );
+
+ if (server?.status === LobehubSkillStatus.CONNECTED || server?.isConnected) {
+ return createManagedSkillItem({
+ badge: <Icon icon={McpIcon} size={12} />,
+ extraTag: provider.author === 'LobeHub' ? officialTag : undefined,
+ icon,
+ id: server.identifier,
+ popoverContent,
+ searchText: `${provider.label} ${server.identifier}`,
+ title: provider.label,
+ });
+ }
+
+ return {
+ icon,
+ key: provider.id, // Use provider.id as key, consistent with pluginId
+ label: (
+ <LobehubSkillServerItem
+ agentId={agentId}
+ label={provider.label}
+ provider={provider.id}
+ />
+ ),
+ popoverContent,
+ searchText: provider.label,
+ };
+ })
: [],
[
isLobehubSkillEnabled,
@@ -234,84 +885,79 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
recommendedLobehubIds,
agentId,
t,
+ createManagedSkillItem,
],
);
// Builtin tool list items (excluding Klavis and LobeHub Skill)
const builtinItems = useMemo(
() =>
- filteredBuiltinList.map((item) => ({
- icon: (
- <Avatar
- avatar={item.meta.avatar}
- shape={'square'}
- size={SKILL_ICON_SIZE}
- style={{ flex: 'none' }}
- />
- ),
- key: item.identifier,
- label: (
- <ToolItem
- checked={checked.includes(item.identifier)}
- id={item.identifier}
- label={item.meta?.title}
- onUpdate={async () => {
- setUpdating(true);
- await togglePlugin(item.identifier);
- setUpdating(false);
- }}
- />
- ),
- popoverContent: (
+ filteredBuiltinList.map((item) => {
+ const title = t(`tools.builtins.${item.identifier}.title` as any, {
+ defaultValue: item.meta?.title || item.identifier,
+ });
+ const icon = item.meta?.avatar ? (
+ <Avatar avatar={item.meta.avatar} shape={'square'} size={SKILL_ICON_SIZE} />
+ ) : (
+ <Icon icon={SkillsIcon} size={SKILL_ICON_SIZE} />
+ );
+ const popoverContent = (
<ToolItemDetailPopover
identifier={item.identifier}
sourceLabel={t('skillStore.tabs.lobehub')}
+ title={title}
description={t(`tools.builtins.${item.identifier}.description` as any, {
defaultValue: item.meta?.description || '',
})}
icon={
- <Avatar
- avatar={item.meta.avatar}
- shape={'square'}
- size={36}
- style={{ flex: 'none', marginInlineEnd: 0 }}
- />
+ item.meta?.avatar ? (
+ <Avatar
+ avatar={item.meta.avatar}
+ shape={'square'}
+ size={36}
+ style={{ flex: 'none', marginInlineEnd: 0 }}
+ />
+ ) : (
+ <Icon icon={SkillsIcon} size={36} />
+ )
}
- title={t(`tools.builtins.${item.identifier}.title` as any, {
- defaultValue: item.meta?.title || item.identifier,
- })}
/>
- ),
- })),
- [filteredBuiltinList, checked, togglePlugin, setUpdating, t],
+ );
+
+ return createManagedSkillItem({
+ badge: <Icon icon={Wrench} size={12} />,
+ deleteConfig: {
+ displayName: title,
+ onDelete: () => uninstallBuiltinTool(item.identifier),
+ },
+ extraTag: officialTag,
+ icon,
+ id: item.identifier,
+ popoverContent,
+ searchText: `${title} ${item.identifier}`,
+ title,
+ });
+ }),
+ [filteredBuiltinList, t, createManagedSkillItem, uninstallBuiltinTool],
);
// Builtin Agent Skills list items (grouped under LobeHub)
const builtinAgentSkillItems = useMemo(
() =>
- installedBuiltinSkills.map((skill) => ({
- icon: skill.avatar ? (
+ installedBuiltinSkills.map((skill) => {
+ const title = t(`tools.builtins.${skill.identifier}.title` as any, {
+ defaultValue: skill.name,
+ });
+ const icon = skill.avatar ? (
<Avatar avatar={skill.avatar} shape={'square'} size={SKILL_ICON_SIZE} />
) : (
<Icon icon={SkillsIcon} size={SKILL_ICON_SIZE} />
- ),
- key: skill.identifier,
- label: (
- <ToolItem
- checked={checked.includes(skill.identifier)}
- id={skill.identifier}
- label={skill.name}
- onUpdate={async () => {
- setUpdating(true);
- await togglePlugin(skill.identifier);
- setUpdating(false);
- }}
- />
- ),
- popoverContent: (
+ );
+ const popoverContent = (
<ToolItemDetailPopover
identifier={skill.identifier}
sourceLabel={t('skillStore.tabs.lobehub')}
+ title={title}
description={t(`tools.builtins.${skill.identifier}.description` as any, {
defaultValue: skill.description,
})}
@@ -327,66 +973,60 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
<Icon icon={SkillsIcon} size={36} />
)
}
- title={t(`tools.builtins.${skill.identifier}.title` as any, {
- defaultValue: skill.name,
- })}
/>
- ),
- })),
- [installedBuiltinSkills, checked, togglePlugin, setUpdating, t],
+ );
+
+ return createManagedSkillItem({
+ badge: <Icon icon={SkillsIcon} size={12} />,
+ extraTag: officialTag,
+ icon,
+ id: skill.identifier,
+ popoverContent,
+ searchText: `${title} ${skill.identifier}`,
+ title,
+ });
+ }),
+ [installedBuiltinSkills, t, createManagedSkillItem],
);
// Market Agent Skills list items (grouped under Community)
const marketAgentSkillItems = useMemo(
() =>
- marketAgentSkills.map((skill) => ({
- icon: (
+ marketAgentSkills.map((skill) => {
+ const icon = (
<MarketSkillIcon identifier={skill.identifier} name={skill.name} size={SKILL_ICON_SIZE} />
- ),
- key: skill.identifier,
- label: (
- <ToolItem
- checked={checked.includes(skill.identifier)}
- id={skill.identifier}
- label={skill.name}
- onUpdate={async () => {
- setUpdating(true);
- await togglePlugin(skill.identifier);
- setUpdating(false);
- }}
- />
- ),
- popoverContent: (
+ );
+ const popoverContent = (
<MarketAgentSkillPopoverContent
description={skill.description}
identifier={skill.identifier}
name={skill.name}
sourceLabel={t('skillStore.tabs.community')}
/>
- ),
- })),
- [marketAgentSkills, checked, togglePlugin, setUpdating, t],
+ );
+
+ return createManagedSkillItem({
+ badge: <Icon icon={SkillsIcon} size={12} />,
+ deleteConfig: {
+ displayName: skill.name,
+ onDelete: () => deleteAgentSkill(skill.id),
+ },
+ icon,
+ id: skill.identifier,
+ popoverContent,
+ searchText: `${skill.name} ${skill.identifier}`,
+ title: skill.name,
+ });
+ }),
+ [marketAgentSkills, t, createManagedSkillItem, deleteAgentSkill],
);
// User Agent Skills list items (grouped under Custom)
const userAgentSkillItems = useMemo(
() =>
- userAgentSkills.map((skill) => ({
- icon: <Icon icon={SkillsIcon} size={SKILL_ICON_SIZE} />,
- key: skill.identifier,
- label: (
- <ToolItem
- checked={checked.includes(skill.identifier)}
- id={skill.identifier}
- label={skill.name}
- onUpdate={async () => {
- setUpdating(true);
- await togglePlugin(skill.identifier);
- setUpdating(false);
- }}
- />
- ),
- popoverContent: (
+ userAgentSkills.map((skill) => {
+ const icon = <Icon icon={SkillsIcon} size={SKILL_ICON_SIZE} />;
+ const popoverContent = (
<ToolItemDetailPopover
description={skill.description}
icon={<Icon icon={SkillsIcon} size={36} />}
@@ -394,9 +1034,22 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
sourceLabel={t('skillStore.tabs.custom')}
title={skill.name}
/>
- ),
- })),
- [userAgentSkills, checked, togglePlugin, setUpdating, t],
+ );
+
+ return createManagedSkillItem({
+ badge: <Icon icon={SkillsIcon} size={12} />,
+ deleteConfig: {
+ displayName: skill.name,
+ onDelete: () => deleteAgentSkill(skill.id),
+ },
+ icon,
+ id: skill.identifier,
+ popoverContent,
+ searchText: `${skill.name} ${skill.identifier}`,
+ title: skill.name,
+ });
+ }),
+ [userAgentSkills, t, createManagedSkillItem, deleteAgentSkill],
);
// Skills list items (including LobeHub Skill and Klavis)
@@ -440,48 +1093,57 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
// Function to map plugins to list items
const mapPluginToItem = (item: (typeof list)[0]) => {
- const isMcp = item?.avatar === 'MCP_AVATAR' || !item?.avatar;
+ const isMcp = item?.runtimeType === 'mcp';
+ const hasRealAvatar = !!item?.avatar && item.avatar !== 'MCP_AVATAR';
const isCustom = item.type === 'customPlugin';
- return {
- icon: isMcp ? (
- <Icon icon={McpIcon} size={SKILL_ICON_SIZE} />
- ) : (
- <Avatar avatar={item.avatar} shape={'square'} size={SKILL_ICON_SIZE} />
- ),
- key: item.identifier,
- label: (
- <ToolItem
- checked={checked.includes(item.identifier)}
- id={item.identifier}
- label={item.title}
- onUpdate={async () => {
- setUpdating(true);
- await togglePlugin(item.identifier);
- setUpdating(false);
- }}
- />
- ),
- popoverContent: (
- <ToolItemDetailPopover
- description={item.description}
- identifier={item.identifier}
- sourceLabel={isCustom ? t('skillStore.tabs.custom') : t('skillStore.tabs.community')}
- title={item.title}
- icon={
- isMcp ? (
- <Icon icon={McpIcon} size={36} />
- ) : (
- <Avatar
- avatar={item.avatar}
- shape={'square'}
- size={36}
- style={{ flex: 'none', marginInlineEnd: 0 }}
- />
- )
- }
- />
- ),
- };
+ const icon = hasRealAvatar ? (
+ <Avatar avatar={item.avatar} shape={'square'} size={SKILL_ICON_SIZE} />
+ ) : (
+ <Icon icon={McpIcon} size={SKILL_ICON_SIZE} />
+ );
+ const popoverContent = (
+ <ToolItemDetailPopover
+ description={item.description}
+ identifier={item.identifier}
+ sourceLabel={isCustom ? t('skillStore.tabs.custom') : t('skillStore.tabs.community')}
+ title={item.title}
+ icon={
+ hasRealAvatar ? (
+ <Avatar
+ avatar={item.avatar}
+ shape={'square'}
+ size={36}
+ style={{ flex: 'none', marginInlineEnd: 0 }}
+ />
+ ) : (
+ <Icon icon={McpIcon} size={36} />
+ )
+ }
+ />
+ );
+
+ return createManagedSkillItem({
+ badge: isMcp ? <Icon icon={McpIcon} size={12} /> : undefined,
+ configureConfig: isCustom
+ ? { onConfigure: () => setEditingPluginId(item.identifier) }
+ : undefined,
+ deleteConfig: {
+ displayName: item.title ?? item.identifier,
+ onDelete: () => uninstallPlugin(item.identifier),
+ },
+ extraTag: isCustom ? (
+ <Tag color={'warning'} icon={<Icon icon={Package} />} size={'small'}>
+ {t('store.customPlugin', { ns: 'plugin' })}
+ </Tag>
+ ) : item.author === 'LobeHub' ? (
+ officialTag
+ ) : undefined,
+ icon,
+ id: item.identifier,
+ popoverContent,
+ searchText: `${item.title} ${item.identifier}`,
+ title: item.title,
+ });
};
// Build LobeHub group children (including Builtin Agent Skills, builtin tools, and LobeHub Skill/Klavis)
@@ -506,39 +1168,189 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
...customPlugins.map(mapPluginToItem),
];
- // Items for the market tab
+ const normalizedSearchKeyword = searchKeyword.trim().toLowerCase();
+ const allSkillItems = [
+ ...lobehubGroupChildren,
+ ...communityGroupChildren,
+ ...customGroupChildren,
+ ].filter(
+ (item): item is SkillMenuItem =>
+ Boolean(item) && (item as { type?: string }).type !== 'divider',
+ );
+ const filterBySearch = (items: SkillMenuItem[]) => {
+ if (!normalizedSearchKeyword) return items;
+
+ return items.filter((item) =>
+ String(item.searchText || item.key || '')
+ .toLowerCase()
+ .includes(normalizedSearchKeyword),
+ );
+ };
+ const allPinnedItems = allSkillItems.filter((item) => checkedSet.has(String(item.key)));
+ const allAutoItems = allSkillItems.filter((item) => !checkedSet.has(String(item.key)));
+ const pinnedItems = filterBySearch(allPinnedItems);
+ const autoItems = filterBySearch(allAutoItems);
+
+ const renderActivationGroupLabel = ({
+ autoSwitch,
+ icon,
+ open,
+ title,
+ onToggle,
+ }: {
+ autoSwitch?: boolean;
+ icon: ReactNode;
+ open: boolean;
+ title: string;
+ onToggle: () => void;
+ }) => (
+ <div
+ data-skill-activation-group
+ className={cx(styles.activationGroupHeader)}
+ role="button"
+ tabIndex={0}
+ onClick={(event) => {
+ event.stopPropagation();
+ onToggle();
+ }}
+ >
+ <div className={cx(styles.activationGroupTitleBlock)}>
+ {icon}
+ <span className={cx(styles.activationGroupTitleText)}>{title}</span>
+ </div>
+ <div className={cx(styles.activationGroupActions)}>
+ {autoSwitch && (
+ <span
+ className={cx(styles.switchWrap)}
+ onClick={(event) => {
+ event.stopPropagation();
+ }}
+ >
+ <Switch
+ checked={isAutoSkillMode}
+ loading={autoModeLoading}
+ size="small"
+ onClick={(_, event) => event.stopPropagation()}
+ onChange={async (checked, event) => {
+ event?.stopPropagation?.();
+ setAutoModeLoading(true);
+ try {
+ await updateAgentChatConfig({
+ skillActivateMode: checked ? 'auto' : 'manual',
+ });
+ } finally {
+ setAutoModeLoading(false);
+ }
+ }}
+ />
+ </span>
+ )}
+ <div className={cx(styles.activationGroupChevron)}>
+ <Icon icon={open ? ChevronDown : ChevronRight} size={13} />
+ </div>
+ </div>
+ </div>
+ );
+
const marketItems: ItemType[] = [
- // LobeHub group
- ...(lobehubGroupChildren.length > 0
+ {
+ children: [],
+ key: 'skill-search',
+ label: (
+ <div
+ data-skill-menu-search
+ className={cx(styles.search)}
+ onClick={stopPropagation}
+ onKeyDown={stopPropagation}
+ >
+ <div className={cx(styles.searchBox)}>
+ <SearchBar
+ allowClear
+ placeholder={t('tools.search')}
+ size="small"
+ style={{ flex: 1 }}
+ value={searchKeyword}
+ variant="borderless"
+ onChange={(event) => setSearchKeyword(event.target.value)}
+ onKeyDown={stopPropagation}
+ />
+ </div>
+ </div>
+ ),
+ type: 'group' as const,
+ },
+ ...(pinnedItems.length > 0
? [
{
- children: lobehubGroupChildren,
- key: 'lobehub',
- label: t('skillStore.tabs.lobehub'),
+ children: pinnedOpen ? pinnedItems : [],
+ key: 'pinned',
+ label: renderActivationGroupLabel({
+ icon: <Icon icon={Pin} size={14} />,
+ open: pinnedOpen,
+ title: t('tools.activation.pinned'),
+ onToggle: () => setPinnedOpen((open) => !open),
+ }),
type: 'group' as const,
- },
+ } as ItemType,
]
: []),
- // Community group
- ...(communityGroupChildren.length > 0
+ ...(pinnedItems.length > 0 && autoItems.length > 0
? [
{
- children: communityGroupChildren,
- key: 'community',
- label: t('skillStore.tabs.community'),
- type: 'group' as const,
- },
+ key: 'skill-activation-divider',
+ type: 'divider' as const,
+ } as ItemType,
]
: []),
- // Custom group (only shown when there are custom plugins)
- ...(customGroupChildren.length > 0
+ ...(autoItems.length > 0
? [
{
- children: customGroupChildren,
- key: 'custom',
- label: t('skillStore.tabs.custom'),
+ children: autoOpen ? autoItems : [],
+ key: 'auto',
+ label: renderActivationGroupLabel({
+ autoSwitch: true,
+ icon: <Icon icon={Zap} size={14} />,
+ open: autoOpen,
+ title: t('tools.activation.auto'),
+ onToggle: () => setAutoOpen((open) => !open),
+ }),
type: 'group' as const,
- },
+ } as ItemType,
+ ]
+ : []),
+ ...(allSkillItems.length > 0
+ ? [
+ {
+ closeOnClick: false,
+ key: 'skill-stats-footer',
+ label: (
+ <span data-fixed-menu-footer data-skill-stats>
+ <div className={cx(styles.statsFooter)}>
+ <span className={cx(styles.statsItem)}>
+ <Icon icon={Pin} size={12} />
+ {allPinnedItems.length}
+ </span>
+ <span className={cx(styles.statsItem)}>
+ <Icon icon={Zap} size={12} />
+ {allAutoItems.length}
+ </span>
+ <Tooltip placement="top" title={t('tools.plugins.management')}>
+ <button
+ aria-label={t('tools.plugins.management')}
+ className={cx(styles.statsSettingsButton)}
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ navigate('/settings/skill');
+ }}
+ >
+ <Icon icon={Settings} size={14} />
+ </button>
+ </Tooltip>
+ </div>
+ </span>
+ ),
+ } as ItemType,
]
: []),
];
@@ -551,13 +1363,10 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
const enabledBuiltinItems = filteredBuiltinList
.filter((item) => checked.includes(item.identifier))
.map((item) => ({
- icon: (
- <Avatar
- avatar={item.meta.avatar}
- shape={'square'}
- size={SKILL_ICON_SIZE}
- style={{ flex: 'none' }}
- />
+ icon: item.meta?.avatar ? (
+ <Avatar avatar={item.meta.avatar} shape={'square'} size={SKILL_ICON_SIZE} />
+ ) : (
+ <Icon icon={SkillsIcon} size={SKILL_ICON_SIZE} />
),
key: item.identifier,
label: (
@@ -566,9 +1375,7 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
id={item.identifier}
label={item.meta?.title}
onUpdate={async () => {
- setUpdating(true);
await togglePlugin(item.identifier);
- setUpdating(false);
}}
/>
),
@@ -580,12 +1387,16 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
defaultValue: item.meta?.description || '',
})}
icon={
- <Avatar
- avatar={item.meta.avatar}
- shape={'square'}
- size={36}
- style={{ flex: 'none', marginInlineEnd: 0 }}
- />
+ item.meta?.avatar ? (
+ <Avatar
+ avatar={item.meta.avatar}
+ shape={'square'}
+ size={36}
+ style={{ flex: 'none', marginInlineEnd: 0 }}
+ />
+ ) : (
+ <Icon icon={SkillsIcon} size={36} />
+ )
}
title={t(`tools.builtins.${item.identifier}.title` as any, {
defaultValue: item.meta?.title || item.identifier,
@@ -623,9 +1434,7 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
id={skill.identifier}
label={skill.name}
onUpdate={async () => {
- setUpdating(true);
await togglePlugin(skill.identifier);
- setUpdating(false);
}}
/>
),
@@ -682,12 +1491,12 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
const enabledCommunityPlugins = communityPlugins
.filter((item) => checked.includes(item.identifier))
.map((item) => {
- const isMcp = item?.avatar === 'MCP_AVATAR' || !item?.avatar;
+ const hasRealAvatar = !!item?.avatar && item.avatar !== 'MCP_AVATAR';
return {
- icon: isMcp ? (
- <Icon icon={McpIcon} size={SKILL_ICON_SIZE} />
- ) : (
+ icon: hasRealAvatar ? (
<Avatar avatar={item.avatar} shape={'square'} size={SKILL_ICON_SIZE} />
+ ) : (
+ <Icon icon={McpIcon} size={SKILL_ICON_SIZE} />
),
key: item.identifier,
label: (
@@ -696,9 +1505,7 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
id={item.identifier}
label={item.title}
onUpdate={async () => {
- setUpdating(true);
await togglePlugin(item.identifier);
- setUpdating(false);
}}
/>
),
@@ -709,15 +1516,15 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
sourceLabel={t('skillStore.tabs.community')}
title={item.title}
icon={
- isMcp ? (
- <Icon icon={McpIcon} size={36} />
- ) : (
+ hasRealAvatar ? (
<Avatar
avatar={item.avatar}
shape={'square'}
size={36}
style={{ flex: 'none', marginInlineEnd: 0 }}
/>
+ ) : (
+ <Icon icon={McpIcon} size={36} />
)
}
/>
@@ -729,12 +1536,12 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
const enabledCustomPlugins = customPlugins
.filter((item) => checked.includes(item.identifier))
.map((item) => {
- const isMcp = item?.avatar === 'MCP_AVATAR' || !item?.avatar;
+ const hasRealAvatar = !!item?.avatar && item.avatar !== 'MCP_AVATAR';
return {
- icon: isMcp ? (
- <Icon icon={McpIcon} size={SKILL_ICON_SIZE} />
- ) : (
+ icon: hasRealAvatar ? (
<Avatar avatar={item.avatar} shape={'square'} size={SKILL_ICON_SIZE} />
+ ) : (
+ <Icon icon={McpIcon} size={SKILL_ICON_SIZE} />
),
key: item.identifier,
label: (
@@ -743,9 +1550,7 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
id={item.identifier}
label={item.title}
onUpdate={async () => {
- setUpdating(true);
await togglePlugin(item.identifier);
- setUpdating(false);
}}
/>
),
@@ -756,15 +1561,15 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
sourceLabel={t('skillStore.tabs.custom')}
title={item.title}
icon={
- isMcp ? (
- <Icon icon={McpIcon} size={36} />
- ) : (
+ hasRealAvatar ? (
<Avatar
avatar={item.avatar}
shape={'square'}
size={36}
style={{ flex: 'none', marginInlineEnd: 0 }}
/>
+ ) : (
+ <Icon icon={McpIcon} size={36} />
)
}
/>
@@ -786,9 +1591,7 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
id={skill.identifier}
label={skill.name}
onUpdate={async () => {
- setUpdating(true);
await togglePlugin(skill.identifier);
- setUpdating(false);
}}
/>
),
@@ -825,9 +1628,7 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
id={skill.identifier}
label={skill.name}
onUpdate={async () => {
- setUpdating(true);
await togglePlugin(skill.identifier);
- setUpdating(false);
}}
/>
),
@@ -865,9 +1666,34 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)
lobehubSkillItems,
checked,
togglePlugin,
- setUpdating,
t,
]);
- return { installedPluginItems, marketItems };
+ const editPluginDrawer = (
+ <DevModal
+ mode={'edit'}
+ open={!!editingPluginId}
+ value={editingCustomPlugin}
+ onValueChange={updateNewCustomPlugin}
+ onDelete={() => {
+ if (editingPluginId) uninstallPlugin(editingPluginId);
+ setEditingPluginId(null);
+ }}
+ onOpenChange={(open) => {
+ if (!open) setEditingPluginId(null);
+ }}
+ onSave={async (devPlugin) => {
+ await installCustomPlugin(devPlugin);
+ setEditingPluginId(null);
+ }}
+ />
+ );
+
+ return {
+ autoCount: allAutoItems.length,
+ editPluginDrawer,
+ installedPluginItems,
+ marketItems,
+ pinnedCount: allPinnedItems.length,
+ };
};
diff --git a/src/features/ChatInput/ActionBar/components/Action.tsx b/src/features/ChatInput/ActionBar/components/Action.tsx
index 43df8696d27..b91f586afcd 100644
--- a/src/features/ChatInput/ActionBar/components/Action.tsx
+++ b/src/features/ChatInput/ActionBar/components/Action.tsx
@@ -36,6 +36,7 @@ const Action = memo<ActionProps>(
trigger,
disabled,
onClick,
+ size,
...rest
}) => {
const [show, setShow] = useMergeState(false, {
@@ -62,9 +63,10 @@ const Action = memo<ActionProps>(
}}
{...rest}
size={
- actionSize ?? {
- blockSize: 36,
- size: 20,
+ actionSize ??
+ size ?? {
+ blockSize: 32,
+ size: 18,
}
}
/>
diff --git a/src/features/ChatInput/ActionBar/components/ActionDropdown.tsx b/src/features/ChatInput/ActionBar/components/ActionDropdown.tsx
index b85c560f0f0..46e49e94f24 100644
--- a/src/features/ChatInput/ActionBar/components/ActionDropdown.tsx
+++ b/src/features/ChatInput/ActionBar/components/ActionDropdown.tsx
@@ -15,7 +15,7 @@ import {
DropdownMenuTrigger,
renderDropdownMenuItems,
} from '@lobehub/ui';
-import { createStaticStyles, cx } from 'antd-style';
+import { createGlobalStyle, createStaticStyles, cssVar, cx } from 'antd-style';
import { type CSSProperties, type ReactNode } from 'react';
import {
isValidElement,
@@ -42,6 +42,110 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
+const SubmenuScrollStyle = createGlobalStyle`
+ /* base-ui DropdownMenu.Item reserves an indicator slot (empty aria-hidden
+ span) for checkbox/radio variants. Our menu items don't use it, so the
+ empty slot only contributes left whitespace. Collapse it across both
+ the top-level menu and any nested submenu popups. */
+ [role='menu'] [role='menuitem'] > * > span[aria-hidden='true']:empty,
+ [role='menu'] [role='menuitem'] > span[aria-hidden='true']:empty {
+ display: none;
+ }
+
+ [data-submenu] > [role='menu'] {
+ will-change: auto;
+
+ /* Submenus have 0ms animation, so disabling compositing is safe.
+ Both will-change:transform AND the inherited transform: scaleY(1) from
+ Menu.Positioner ('& > *' rule) create a new containing block, which
+ breaks position:sticky for descendants and lets items leak below the
+ popup. Disable both for submenus where animation is already 0ms. */
+ transform: none !important;
+
+ overflow: hidden auto;
+ overscroll-behavior: contain;
+
+ width: 360px;
+ max-height: min(50vh, 640px);
+ padding-block-end: 4px;
+ }
+
+ /* base-ui menu-item internal containers are flex by default but don't set
+ min-width:0, which blocks descendant text-overflow:ellipsis from working.
+ Force min-width:0 down the chain so long titles can truncate. */
+ [data-submenu] > [role='menu'] [role='menuitem'] > *,
+ [data-submenu] > [role='menu'] [role='menuitem'] > * > * {
+ min-width: 0;
+ }
+
+ /* Align base-ui separator color with the stats-footer's border-block-start
+ (colorBorderSecondary) so all dividers in the menu look consistent. */
+ [data-submenu] > [role='menu'] [role='separator'] {
+ background: ${cssVar.colorBorderSecondary};
+ }
+
+ /* base-ui group label is rendered inside a [role='presentation'] with its
+ own default vertical padding, which stacks with our activationGroupHeader
+ padding and inflates the gap above/below group headers. Reset only the
+ vertical padding for skill activation groups; other groups (e.g. the
+ Knowledge submenu's Libraries/Files headers) keep their default padding. */
+ [data-submenu] > [role='menu'] [role='group']:has([data-skill-activation-group]) > [role='presentation'] {
+ padding-block: 0;
+ }
+
+ [data-submenu] > [role='menu']:has([role='menuitem']:has([data-fixed-menu-footer])) {
+ padding-block-end: 0 !important;
+ }
+
+ [data-submenu] > [role='menu'] [role='menuitem']:has([data-fixed-menu-footer]) {
+ position: sticky;
+ z-index: 2;
+ inset-block-end: 0;
+
+ min-height: 0;
+ padding-block: 8px 12px !important;
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 0;
+
+ background: ${cssVar.colorBgElevated};
+ }
+
+ [data-submenu] > [role='menu'] [role='menuitem']:has([data-fixed-menu-footer]) > * {
+ display: flex;
+ align-items: center;
+
+ width: 100%;
+ min-height: 36px;
+ padding-block: 4px;
+ border-radius: ${cssVar.borderRadiusSM};
+ }
+
+ [data-submenu] > [role='menu'] [role='menuitem']:has([data-skill-stats]) {
+ cursor: default;
+ padding-block: 0 !important;
+ }
+
+ [data-submenu] > [role='menu'] [role='group']:has([data-skill-menu-search]) > *:has([data-skill-menu-search]) {
+ padding-block: 6px 4px !important;
+ padding-inline: 8px !important;
+ }
+
+ [data-submenu] > [role='menu'] [role='menuitem']:has([data-fixed-menu-footer]):hover,
+ [data-submenu] > [role='menu'] [role='menuitem']:has([data-fixed-menu-footer])[data-highlighted] {
+ background: ${cssVar.colorBgElevated};
+ }
+
+ [data-submenu] > [role='menu'] [role='menuitem']:has([data-fixed-menu-footer]):hover > *,
+ [data-submenu] > [role='menu'] [role='menuitem']:has([data-fixed-menu-footer])[data-highlighted] > * {
+ background: ${cssVar.colorFillTertiary};
+ }
+
+ [data-submenu] > [role='menu'] [role='menuitem']:has([data-skill-stats]):hover > *,
+ [data-submenu] > [role='menu'] [role='menuitem']:has([data-skill-stats])[data-highlighted] > * {
+ background: transparent;
+ }
+`;
+
export type ActionDropdownMenuItem = MenuItemType;
export type ActionDropdownMenuItems = MenuProps<ActionDropdownMenuItem>['items'];
@@ -101,6 +205,10 @@ const ActionDropdown = memo<ActionDropdownProps>(
const handleOpenChange = useCallback(
(nextOpen: boolean, details: Parameters<NonNullable<typeof onOpenChange>>[1]) => {
+ if (!nextOpen && (details as { reason?: string })?.reason === 'sibling-open') {
+ (details as { cancel?: () => void })?.cancel?.();
+ return;
+ }
onOpenChange?.(nextOpen, details);
if (open === undefined) setUncontrolledOpen(nextOpen);
},
@@ -146,9 +254,23 @@ const ActionDropdown = memo<ActionDropdownProps>(
}
if ('children' in item && item.children) {
+ const originalOnOpenChange = (item as { onOpenChange?: unknown }).onOpenChange as
+ | ((open: boolean, details: unknown) => void)
+ | undefined;
return {
...item,
children: decorateMenuItems(item.children),
+ onOpenChange: (subOpen: boolean, details: unknown) => {
+ if (!subOpen) {
+ const reason = (details as { reason?: string })?.reason;
+ if (reason === 'sibling-open' || reason === 'focus-out') {
+ (details as { cancel?: () => void })?.cancel?.();
+ return;
+ }
+ }
+ originalOnOpenChange?.(subOpen, details);
+ },
+ type: 'submenu',
};
}
const itemOnClick = 'onClick' in item ? item.onClick : undefined;
@@ -188,10 +310,11 @@ const ActionDropdown = memo<ActionDropdownProps>(
menuItemsRef.current = nextItems;
return nextItems;
- }, [decorateMenuItems, isOpen, menu.items, prefetch]);
+ }, [decorateMenuItems, isOpen, menu, prefetch]);
const menuContent = useMemo(() => {
if (!popupRender) return renderedItems;
+
return popupRender(renderedItems ?? null);
}, [popupRender, renderedItems]);
@@ -263,30 +386,33 @@ const ActionDropdown = memo<ActionDropdownProps>(
}, [portalContainer]);
return (
- <DropdownMenuRoot
- {...rest}
- defaultOpen={defaultOpen}
- open={open}
- onOpenChange={handleOpenChange}
- onOpenChangeComplete={handleOpenChangeComplete}
- >
- <DropdownMenuTrigger className={styles.trigger} {...resolvedTriggerProps}>
- {children}
- </DropdownMenuTrigger>
- <DropdownMenuPortal container={resolvedPortalContainer} {...restPortalProps}>
- <DropdownMenuPositioner
- {...positionerProps}
- hoverTrigger={Boolean(resolvedTriggerProps?.openOnHover)}
- placement={isMobile ? 'top' : placement}
- >
- <DropdownMenuPopup {...resolvedPopupProps}>
- <Suspense fallback={<DebugNode trace="ActionDropdown > popup" />}>
- {menuContent}
- </Suspense>
- </DropdownMenuPopup>
- </DropdownMenuPositioner>
- </DropdownMenuPortal>
- </DropdownMenuRoot>
+ <>
+ <SubmenuScrollStyle />
+ <DropdownMenuRoot
+ {...rest}
+ defaultOpen={defaultOpen}
+ open={open}
+ onOpenChange={handleOpenChange}
+ onOpenChangeComplete={handleOpenChangeComplete}
+ >
+ <DropdownMenuTrigger className={styles.trigger} {...resolvedTriggerProps}>
+ {children}
+ </DropdownMenuTrigger>
+ <DropdownMenuPortal container={resolvedPortalContainer} {...restPortalProps}>
+ <DropdownMenuPositioner
+ {...positionerProps}
+ hoverTrigger={Boolean(resolvedTriggerProps?.openOnHover)}
+ placement={isMobile ? 'top' : placement}
+ >
+ <DropdownMenuPopup {...resolvedPopupProps}>
+ <Suspense fallback={<DebugNode trace="ActionDropdown > popup" />}>
+ {menuContent}
+ </Suspense>
+ </DropdownMenuPopup>
+ </DropdownMenuPositioner>
+ </DropdownMenuPortal>
+ </DropdownMenuRoot>
+ </>
);
},
);
diff --git a/src/features/ChatInput/ActionBar/components/CheckboxWithLoading.tsx b/src/features/ChatInput/ActionBar/components/CheckboxWithLoading.tsx
index 31deed5e04c..d9829a826db 100644
--- a/src/features/ChatInput/ActionBar/components/CheckboxWithLoading.tsx
+++ b/src/features/ChatInput/ActionBar/components/CheckboxWithLoading.tsx
@@ -1,6 +1,6 @@
import { Center, Checkbox, Flexbox, Icon } from '@lobehub/ui';
import { Loader2 } from 'lucide-react';
-import { type ReactNode } from 'react';
+import { type CSSProperties, type ReactNode } from 'react';
import { memo, useState } from 'react';
export interface CheckboxItemProps {
@@ -8,12 +8,14 @@ export interface CheckboxItemProps {
hasPadding?: boolean;
id: string;
label?: ReactNode;
+ labelMaxWidth?: CSSProperties['maxWidth'];
onUpdate: (id: string, enabled: boolean) => Promise<void>;
}
const CheckboxItem = memo<CheckboxItemProps>(
- ({ id, onUpdate, label, checked, hasPadding = true }) => {
+ ({ id, onUpdate, label, checked, hasPadding = true, labelMaxWidth }) => {
const [loading, setLoading] = useState(false);
+ const labelContent = label || id;
const updateState = async () => {
setLoading(true);
@@ -30,16 +32,28 @@ const CheckboxItem = memo<CheckboxItemProps>(
style={
hasPadding
? {
+ minWidth: 0,
paddingLeft: 8,
}
- : void 0
+ : { minWidth: 0 }
}
onClick={async (e) => {
e.stopPropagation();
updateState();
}}
>
- {label || id}
+ <span
+ title={typeof labelContent === 'string' ? labelContent : undefined}
+ style={{
+ maxWidth: labelMaxWidth,
+ minWidth: 0,
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ }}
+ >
+ {labelContent}
+ </span>
{loading ? (
<Center width={18}>
<Icon spin icon={Loader2} />
diff --git a/src/features/ChatInput/ActionBar/config.ts b/src/features/ChatInput/ActionBar/config.ts
index 17cd095da3f..1da3c41d836 100644
--- a/src/features/ChatInput/ActionBar/config.ts
+++ b/src/features/ChatInput/ActionBar/config.ts
@@ -4,12 +4,14 @@ import History from './History';
import Memory from './Memory';
import Mention from './Mention';
import Model from './Model';
+import ModelLabel from './ModelLabel';
import Params from './Params';
+import Plus from './Plus';
import PromptTransform from './PromptTransform';
import SaveTopic from './SaveTopic';
import Search from './Search';
import STT from './STT';
-import { MainToken, PortalToken } from './Token';
+import ContextWindow from './Token';
import Tools from './Tools';
import Typo from './Typo';
import Upload from './Upload';
@@ -17,14 +19,15 @@ import Upload from './Upload';
export const actionMap = {
agentMode: AgentMode,
clear: Clear,
+ contextWindow: ContextWindow,
fileUpload: Upload,
+ plus: Plus,
history: History,
- mainToken: MainToken,
memory: Memory,
mention: Mention,
model: Model,
+ modelLabel: ModelLabel,
params: Params,
- portalToken: PortalToken,
promptTransform: PromptTransform,
saveTopic: SaveTopic,
search: Search,
diff --git a/src/features/ChatInput/ActionBar/index.tsx b/src/features/ChatInput/ActionBar/index.tsx
index 042a18ef55e..0970c0a2008 100644
--- a/src/features/ChatInput/ActionBar/index.tsx
+++ b/src/features/ChatInput/ActionBar/index.tsx
@@ -24,7 +24,7 @@ const mapActionsToItems = (keys: ActionKeys[]): ChatInputActionsProps['items'] =
}
const Render = actionMap[actionKey];
return {
- alwaysDisplay: actionKey === 'mainToken',
+ alwaysDisplay: actionKey === 'contextWindow',
children: <Render key={actionKey} />,
key: actionKey,
};
@@ -80,6 +80,7 @@ const ActionToolbar = memo<ActionToolbarProps>(
defaultGroupCollapse={true}
groupCollapse={!expandInputActionbar}
items={items}
+ style={{ paddingLeft: 6 }}
onGroupCollapseChange={(v) => {
toggleExpandInputActionbar(!v);
}}
diff --git a/src/features/ChatInput/ChatInputProvider.tsx b/src/features/ChatInput/ChatInputProvider.tsx
index fa9fddab843..9ad0ea400c9 100644
--- a/src/features/ChatInput/ChatInputProvider.tsx
+++ b/src/features/ChatInput/ChatInputProvider.tsx
@@ -14,6 +14,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(
({
agentId,
children,
+ contextWindowMessages,
disableMention,
disableSlash,
leftActions,
@@ -37,6 +38,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(
createStore={() =>
createStore({
allowExpand,
+ contextWindowMessages,
disableMention,
disableSlash,
editor,
@@ -55,6 +57,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(
agentId={agentId}
allowExpand={allowExpand}
chatInputEditorRef={chatInputEditorRef}
+ contextWindowMessages={contextWindowMessages}
disableMention={disableMention}
disableSlash={disableSlash}
getMessages={getMessages}
diff --git a/src/features/ChatInput/InputEditor/Placeholder.tsx b/src/features/ChatInput/InputEditor/Placeholder.tsx
index 596a84d4ca3..be8d0c116db 100644
--- a/src/features/ChatInput/InputEditor/Placeholder.tsx
+++ b/src/features/ChatInput/InputEditor/Placeholder.tsx
@@ -3,6 +3,9 @@ import { combineKeys, Flexbox, Hotkey } from '@lobehub/ui';
import { memo } from 'react';
import { Trans, useTranslation } from 'react-i18next';
+import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
import { useUserStore } from '@/store/user';
import { preferenceSelectors } from '@/store/user/selectors';
@@ -22,6 +25,9 @@ const Placeholder = memo<PlaceholderProps>(
: combineKeys([KeyEnum.Mod, KeyEnum.Enter]);
const { t } = useTranslation('chat');
+ const agentId = useAgentId();
+ const enableAgentMode = useAgentStore(agentByIdSelectors.getAgentEnableModeById(agentId));
+
const isHeterogeneous = !!heterogeneousName;
if (variant === 'followUp') {
@@ -34,9 +40,13 @@ const Placeholder = memo<PlaceholderProps>(
const i18nKey = isHeterogeneous
? 'sendPlaceholderHeterogeneous'
- : showAgentAssignmentHint
- ? 'sendPlaceholderWithAgentAssignment'
- : 'sendPlaceholder';
+ : enableAgentMode
+ ? showAgentAssignmentHint
+ ? 'sendPlaceholderWithAgentAssignment'
+ : 'sendPlaceholder'
+ : showAgentAssignmentHint
+ ? 'sendPlaceholderChatWithAgentAssignment'
+ : 'sendPlaceholderChat';
return (
<Flexbox horizontal align={'center'} as={'span'} gap={4} wrap={'wrap'}>
diff --git a/src/features/ChatInput/RuntimeConfig/ModeSelector.tsx b/src/features/ChatInput/RuntimeConfig/ModeSelector.tsx
new file mode 100644
index 00000000000..371f4964e2a
--- /dev/null
+++ b/src/features/ChatInput/RuntimeConfig/ModeSelector.tsx
@@ -0,0 +1,218 @@
+import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import {
+ ChevronDownIcon,
+ FolderIcon,
+ InfinityIcon,
+ MessageCircleIcon,
+ SearchIcon,
+ TerminalIcon,
+ WrenchIcon,
+} from 'lucide-react';
+import { memo, useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
+import { useToggleAgentMode } from '@/features/ChatInput/hooks/useToggleAgentMode';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+
+const styles = createStaticStyles(({ css }) => ({
+ activeOption: css`
+ background: ${cssVar.colorFillSecondary};
+ `,
+ agentTooltip: css`
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ min-width: 160px;
+ `,
+ agentTooltipCap: css`
+ display: flex;
+ gap: 6px;
+ align-items: center;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ agentTooltipTitle: css`
+ margin-block-end: 2px;
+ font-size: 12px;
+ font-weight: 600;
+ color: ${cssVar.colorText};
+ `,
+ button: css`
+ cursor: pointer;
+
+ display: flex;
+ gap: 6px;
+ align-items: center;
+
+ height: 28px;
+ padding-inline: 8px;
+ border-radius: 6px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+
+ transition: all 0.2s;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillSecondary};
+ }
+ `,
+ option: css`
+ cursor: pointer;
+
+ width: 100%;
+ padding-block: 10px;
+ padding-inline: 8px;
+ border-radius: ${cssVar.borderRadius};
+
+ transition: background-color 0.2s;
+
+ &:hover {
+ background: ${cssVar.colorFillSecondary};
+ }
+ `,
+ optionDesc: css`
+ font-size: 12px;
+ line-height: 1.4;
+ color: ${cssVar.colorTextDescription};
+ `,
+ optionIcon: css`
+ flex-shrink: 0;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadius};
+ background: ${cssVar.colorBgElevated};
+ `,
+ optionTitle: css`
+ font-size: 14px;
+ font-weight: 500;
+ line-height: 1.4;
+ color: ${cssVar.colorText};
+ `,
+}));
+
+const AGENT_CAPS = [
+ { icon: WrenchIcon, key: 'tools' },
+ { icon: SearchIcon, key: 'web' },
+ { icon: FolderIcon, key: 'files' },
+ { icon: TerminalIcon, key: 'env' },
+] as const;
+
+const ModeSelector = memo(() => {
+ const { t } = useTranslation('chat');
+ const agentId = useAgentId();
+ const toggleAgentMode = useToggleAgentMode();
+ const [open, setOpen] = useState(false);
+
+ const enableAgentMode = useAgentStore(agentByIdSelectors.getAgentEnableModeById(agentId));
+
+ const currentMode = enableAgentMode ? 'agent' : 'chat';
+ const CurrentIcon = enableAgentMode ? InfinityIcon : MessageCircleIcon;
+
+ const handleSelect = useCallback(
+ async (mode: 'chat' | 'agent') => {
+ setOpen(false);
+ await toggleAgentMode(mode === 'agent');
+ },
+ [toggleAgentMode],
+ );
+
+ const agentTooltip = (
+ <div className={styles.agentTooltip}>
+ <div className={styles.agentTooltipTitle}>{t('chatMode.agent')}</div>
+ {AGENT_CAPS.map(({ key, icon }) => (
+ <div className={styles.agentTooltipCap} key={key}>
+ <Icon icon={icon} size={12} />
+ {t(`chatMode.agentCap.${key}`)}
+ </div>
+ ))}
+ </div>
+ );
+
+ const chatTooltip = t('chatMode.chatDesc');
+
+ const popoverContent = (
+ <Flexbox gap={4} style={{ maxWidth: 320, minWidth: 280 }}>
+ <Flexbox
+ horizontal
+ align="center"
+ className={cx(styles.option, currentMode === 'agent' && styles.activeOption)}
+ gap={12}
+ onClick={() => handleSelect('agent')}
+ >
+ <Flexbox
+ align="center"
+ className={styles.optionIcon}
+ height={32}
+ justify="center"
+ width={32}
+ >
+ <Icon icon={InfinityIcon} size={16} />
+ </Flexbox>
+ <Flexbox flex={1}>
+ <div className={styles.optionTitle}>{t('chatMode.agent')}</div>
+ <div className={styles.optionDesc}>{t('chatMode.agentDesc')}</div>
+ </Flexbox>
+ </Flexbox>
+
+ <Flexbox
+ horizontal
+ align="center"
+ className={cx(styles.option, currentMode === 'chat' && styles.activeOption)}
+ gap={12}
+ onClick={() => handleSelect('chat')}
+ >
+ <Flexbox
+ align="center"
+ className={styles.optionIcon}
+ height={32}
+ justify="center"
+ width={32}
+ >
+ <Icon icon={MessageCircleIcon} size={16} />
+ </Flexbox>
+ <Flexbox flex={1}>
+ <div className={styles.optionTitle}>{t('chatMode.chat')}</div>
+ <div className={styles.optionDesc}>{t('chatMode.chatDesc')}</div>
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ );
+
+ const button = (
+ <div className={styles.button}>
+ <Icon icon={CurrentIcon} size={14} />
+ <span>{t(`chatMode.${currentMode}`)}</span>
+ <Icon icon={ChevronDownIcon} size={12} />
+ </div>
+ );
+
+ return (
+ <Popover
+ content={popoverContent}
+ open={open}
+ placement="topLeft"
+ trigger="click"
+ styles={{
+ content: { border: `1px solid ${cssVar.colorBorderSecondary}`, padding: 4 },
+ }}
+ onOpenChange={setOpen}
+ >
+ <div>
+ {open ? (
+ button
+ ) : (
+ <Tooltip title={enableAgentMode ? agentTooltip : chatTooltip}>{button}</Tooltip>
+ )}
+ </div>
+ </Popover>
+ );
+});
+
+ModeSelector.displayName = 'ModeSelector';
+
+export default ModeSelector;
diff --git a/src/features/ChatInput/RuntimeConfig/index.tsx b/src/features/ChatInput/RuntimeConfig/index.tsx
index b23876357ab..c45e0006ec1 100644
--- a/src/features/ChatInput/RuntimeConfig/index.tsx
+++ b/src/features/ChatInput/RuntimeConfig/index.tsx
@@ -20,11 +20,14 @@ import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selec
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
+import ContextWindow from '../ActionBar/Token';
import { useAgentId } from '../hooks/useAgentId';
import { useUpdateAgentConfig } from '../hooks/useUpdateAgentConfig';
+import { useChatInputStore } from '../store';
import ApprovalMode from './ApprovalMode';
import CloudRepoSwitcher from './CloudRepoSwitcher';
import GitStatus from './GitStatus';
+import ModeSelector from './ModeSelector';
import { useRepoType } from './useRepoType';
import WorkingDirectory from './WorkingDirectory';
@@ -104,11 +107,15 @@ const RuntimeConfig = memo(() => {
const { updateAgentChatConfig } = useUpdateAgentConfig();
const [dirPopoverOpen, setDirPopoverOpen] = useState(false);
const [modePopoverOpen, setModePopoverOpen] = useState(false);
+ const showContextWindow = useChatInputStore((s) =>
+ s.rightActions.flat().includes('contextWindow'),
+ );
- const [isLoading, runtimeMode, isHeterogeneous] = useAgentStore((s) => [
+ const [isLoading, runtimeMode, isHeterogeneous, enableAgentMode] = useAgentStore((s) => [
agentByIdSelectors.isAgentConfigLoadingById(agentId)(s),
chatConfigByIdSelectors.getRuntimeModeById(agentId)(s),
agentId ? agentByIdSelectors.isAgentHeterogeneousById(agentId)(s) : false,
+ agentByIdSelectors.getAgentEnableModeById(agentId)(s),
]);
const topicWorkingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);
@@ -275,29 +282,36 @@ const RuntimeConfig = memo(() => {
return (
<Flexbox horizontal align={'center'} className={styles.bar} justify={'space-between'}>
- {/* Left: Runtime env + working directory */}
+ {/* Left: Chat mode switcher + (agent-only) runtime env + working directory */}
<Flexbox horizontal align={'center'} gap={4}>
- <Popover
- content={modeContent}
- open={modePopoverOpen}
- placement="top"
- styles={{ content: { padding: 4 } }}
- trigger="click"
- onOpenChange={setModePopoverOpen}
- >
- <div>
- {modePopoverOpen ? (
- modeButton
- ) : (
- <Tooltip title={t('runtimeEnv.selectMode')}>{modeButton}</Tooltip>
- )}
- </div>
- </Popover>
- {rightContent()}
+ <ModeSelector />
+ {enableAgentMode && (
+ <>
+ <Popover
+ content={modeContent}
+ open={modePopoverOpen}
+ placement="top"
+ styles={{ content: { padding: 4 } }}
+ trigger="click"
+ onOpenChange={setModePopoverOpen}
+ >
+ <div>
+ {modePopoverOpen ? (
+ modeButton
+ ) : (
+ <Tooltip title={t('runtimeEnv.selectMode')}>{modeButton}</Tooltip>
+ )}
+ </div>
+ </Popover>
+ {rightContent()}
+ </>
+ )}
</Flexbox>
- {/* Right: Permission control */}
- <ApprovalMode />
+ <Flexbox horizontal align={'center'} gap={4}>
+ {enableAgentMode && <ApprovalMode />}
+ {showContextWindow && <ContextWindow />}
+ </Flexbox>
</Flexbox>
);
});
diff --git a/src/features/ChatInput/SendArea/index.tsx b/src/features/ChatInput/SendArea/index.tsx
index b71ba09a1a7..bca4807438b 100644
--- a/src/features/ChatInput/SendArea/index.tsx
+++ b/src/features/ChatInput/SendArea/index.tsx
@@ -19,12 +19,15 @@ const SendArea = memo(() => {
const rightActions = useChatInputStore((s) => s.rightActions, isEqual);
const items = useMemo(
- () => mapActionsToItems((rightActions as ActionKey[]) || []),
+ () =>
+ mapActionsToItems(
+ ((rightActions as ActionKey[]) || []).filter((actionKey) => actionKey !== 'contextWindow'),
+ ),
[rightActions],
);
return (
- <Flexbox horizontal align={'center'} flex={'none'} gap={6}>
+ <Flexbox horizontal align={'center'} flex={'none'} gap={12}>
{allowExpand && <ExpandButton />}
{items}
<SendButton />
diff --git a/src/features/ChatInput/StoreUpdater.tsx b/src/features/ChatInput/StoreUpdater.tsx
index 9a655c0ea10..02e12cd90cc 100644
--- a/src/features/ChatInput/StoreUpdater.tsx
+++ b/src/features/ChatInput/StoreUpdater.tsx
@@ -17,6 +17,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(
({
agentId,
chatInputEditorRef,
+ contextWindowMessages,
disableMention,
disableSlash,
mobile,
@@ -36,6 +37,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(
const editor = useChatInputEditor();
useStoreUpdater('agentId', agentId);
+ useStoreUpdater('contextWindowMessages', contextWindowMessages);
useStoreUpdater('mobile', mobile!);
useStoreUpdater('mentionItems', mentionItems);
useStoreUpdater('leftActions', leftActions!);
diff --git a/src/features/ChatInput/hooks/useToggleAgentMode.ts b/src/features/ChatInput/hooks/useToggleAgentMode.ts
new file mode 100644
index 00000000000..ee3a6542cb6
--- /dev/null
+++ b/src/features/ChatInput/hooks/useToggleAgentMode.ts
@@ -0,0 +1,21 @@
+'use client';
+
+import { useCallback } from 'react';
+
+import { useUpdateAgentConfig } from './useUpdateAgentConfig';
+
+/**
+ * Toggle between chat mode and agent mode.
+ *
+ * The flag is stored on `chatConfig.enableAgentMode` so it persists (chat_config
+ * is a jsonb column) and is readable on the server. The `plugins` array is left
+ * untouched — chat mode is enforced at the runtime tools engine layer.
+ */
+export const useToggleAgentMode = () => {
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+
+ return useCallback(
+ (enable: boolean) => updateAgentChatConfig({ enableAgentMode: enable }),
+ [updateAgentChatConfig],
+ );
+};
diff --git a/src/features/ChatInput/store/initialState.ts b/src/features/ChatInput/store/initialState.ts
index ac74b4831b9..56108fc3b03 100644
--- a/src/features/ChatInput/store/initialState.ts
+++ b/src/features/ChatInput/store/initialState.ts
@@ -28,9 +28,14 @@ export const initialSendButtonState: SendButtonProps = {
export type SlashPlacement = 'top' | 'bottom';
+export interface ContextWindowMessage {
+ content: string;
+}
+
export interface PublicState {
agentId?: string;
allowExpand?: boolean;
+ contextWindowMessages?: ContextWindowMessage[];
/**
* Disable @ mention trigger (no menu, no agent-assignment hint in placeholder)
*/
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index a8c78eba48e..0d487da3f70 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -5,7 +5,7 @@ import { type ChatInputActionsProps } from '@lobehub/editor/react';
import { type MenuProps } from '@lobehub/ui';
import { Alert, Flexbox } from '@lobehub/ui';
import { type ReactNode } from 'react';
-import { memo, useCallback, useEffect, useRef } from 'react';
+import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { type ActionKeys } from '@/features/ChatInput';
@@ -20,12 +20,7 @@ import { fileChatSelectors, useFileStore } from '@/store/file';
import WideScreenContainer from '../../WideScreenContainer';
import InterventionBar from '../InterventionBar';
-import {
- dataSelectors,
- messageStateSelectors,
- useConversationStore,
- useConversationStoreApi,
-} from '../store';
+import { dataSelectors, messageStateSelectors, useConversationStore } from '../store';
import TodoProgress from '../TodoProgress';
import QueueTray from './QueueTray';
import { getConversationChatInputUiState } from './utils';
@@ -33,21 +28,13 @@ import { getConversationChatInputUiState } from './utils';
/** Max recent messages to feed into auto-complete context (≈10 conversation turns) */
const MAX_CONTEXT_MESSAGES = 25;
-const useGetMessages = () => {
- const storeApi = useConversationStoreApi();
- return useCallback(
- () =>
- dataSelectors
- .dbMessages(storeApi.getState())
- .filter((m) => m.role === 'user' || m.role === 'assistant' || m.role === 'tool')
- .slice(-MAX_CONTEXT_MESSAGES)
- .map((m) => ({
- content: typeof m.content === 'string' ? m.content : '',
- role: m.role as 'user' | 'assistant' | 'system',
- })),
- [storeApi],
- );
-};
+const toChatInputMessages = (messages: ReturnType<typeof dataSelectors.dbMessages>) =>
+ messages
+ .filter((m) => m.role === 'user' || m.role === 'assistant' || m.role === 'tool')
+ .map((m) => ({
+ content: typeof m.content === 'string' ? m.content : '',
+ role: m.role as 'user' | 'assistant' | 'system',
+ }));
export interface ChatInputProps {
/**
@@ -169,7 +156,12 @@ const ChatInput = memo<ChatInputProps>(
}) => {
const { t } = useTranslation('chat');
- const getMessages = useGetMessages();
+ const dbMessages = useConversationStore(dataSelectors.dbMessages);
+ const contextWindowMessages = useMemo(() => toChatInputMessages(dbMessages), [dbMessages]);
+ const getMessages = useCallback(
+ () => contextWindowMessages.slice(-MAX_CONTEXT_MESSAGES),
+ [contextWindowMessages],
+ );
// ConversationStore state
const context = useConversationStore((s) => s.context);
@@ -347,6 +339,7 @@ const ChatInput = memo<ChatInputProps>(
<ChatInputProvider
agentId={agentId}
allowExpand={allowExpand}
+ contextWindowMessages={contextWindowMessages}
disableMention={disableMention}
disableSlash={disableSlash}
getMessages={getMessages}
diff --git a/src/features/Conversation/Error/index.test.tsx b/src/features/Conversation/Error/index.test.tsx
index d031ae05c14..38d3945807f 100644
--- a/src/features/Conversation/Error/index.test.tsx
+++ b/src/features/Conversation/Error/index.test.tsx
@@ -110,6 +110,14 @@ vi.mock('@/store/serverConfig', () => ({
useServerConfigStore: (selector: (s: unknown) => unknown) => selector({}),
}));
+vi.mock('@/features/Conversation/store', () => ({
+ useConversationStore: (selector: (state: unknown) => unknown) =>
+ selector({
+ deleteMessage: vi.fn(),
+ regenerateAssistantMessage: vi.fn(),
+ }),
+}));
+
describe('ErrorMessageExtra', () => {
it('renders the auth guide when the refreshed error is missing type but still carries session code', () => {
render(
diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsx
index f5d4647a0c4..b43f30aa861 100644
--- a/src/features/Conversation/Error/index.tsx
+++ b/src/features/Conversation/Error/index.tsx
@@ -6,7 +6,7 @@ import { type ChatMessageError, type ErrorType, type IToolErrorType } from '@lob
import { ChatErrorType } from '@lobechat/types';
import { type AlertProps } from '@lobehub/ui';
import { Block, Highlighter, Skeleton } from '@lobehub/ui';
-import { memo, useMemo } from 'react';
+import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
@@ -14,6 +14,7 @@ import useBusinessErrorAlertConfig from '@/business/client/hooks/useBusinessErro
import useBusinessErrorContent from '@/business/client/hooks/useBusinessErrorContent';
import useRenderBusinessChatErrorMessageExtra from '@/business/client/hooks/useRenderBusinessChatErrorMessageExtra';
import ErrorContent from '@/features/Conversation/ChatItem/components/ErrorContent';
+import { useConversationStore } from '@/features/Conversation/store';
import HeterogeneousAgentStatusGuide from '@/features/Electron/HeterogeneousAgent/StatusGuide';
import { useProviderName } from '@/hooks/useProviderName';
import dynamic from '@/libs/next/dynamic';
@@ -182,12 +183,24 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data, onRe
const sessionErrorBody = error?.body;
const rawErrorMessage = getRawErrorMessage(error) || alertError?.message;
+ const regenerateAssistantMessage = useConversationStore((s) => s.regenerateAssistantMessage);
+ const deleteMessage = useConversationStore((s) => s.deleteMessage);
+ const handleRetryAgentMessage = useCallback(() => {
+ if (onRegenerate) {
+ onRegenerate();
+ return;
+ }
+ regenerateAssistantMessage(data.id);
+ if (data.error) deleteMessage(data.id);
+ }, [data.error, data.id, deleteMessage, onRegenerate, regenerateAssistantMessage]);
+
if (isHeterogeneousAgentStatusGuideError(sessionErrorBody)) {
return (
<HeterogeneousAgentStatusGuide
agentType={sessionErrorBody.agentType}
error={sessionErrorBody}
onOpenSystemTools={() => navigate('/settings/system-tools')}
+ onRetry={handleRetryAgentMessage}
/>
);
}
diff --git a/src/features/Conversation/Messages/components/ContentLoading.tsx b/src/features/Conversation/Messages/components/ContentLoading.tsx
index 578eb45289b..576af4a5acd 100644
--- a/src/features/Conversation/Messages/components/ContentLoading.tsx
+++ b/src/features/Conversation/Messages/components/ContentLoading.tsx
@@ -22,12 +22,13 @@ const ContentLoading = memo<ContentLoadingProps>(({ id }) => {
const { t } = useTranslation('chat');
const runningOp = useChatStore(operationSelectors.getDeepestRunningOperationByMessage(id));
- const [elapsedSeconds, setElapsedSeconds] = useState(0);
- const [startTime, setStartTime] = useState(runningOp?.metadata?.startTime);
-
+ const startTime = runningOp?.metadata?.startTime;
const operationType = runningOp?.type as OperationType | undefined;
- // Track elapsed time, reset when operation type changes
+ const [elapsedSeconds, setElapsedSeconds] = useState(() =>
+ startTime ? Math.floor((Date.now() - startTime) / 1000) : 0,
+ );
+
useEffect(() => {
if (!startTime) {
setElapsedSeconds(0);
@@ -35,8 +36,7 @@ const ContentLoading = memo<ContentLoadingProps>(({ id }) => {
}
const updateElapsed = () => {
- const elapsed = Math.floor((Date.now() - startTime) / 1000);
- setElapsedSeconds(elapsed);
+ setElapsedSeconds(Math.floor((Date.now() - startTime) / 1000));
};
updateElapsed();
@@ -45,11 +45,6 @@ const ContentLoading = memo<ContentLoadingProps>(({ id }) => {
return () => clearInterval(interval);
}, [startTime]);
- useEffect(() => {
- setElapsedSeconds(0);
- setStartTime(Date.now());
- }, [operationType, id]);
-
// Heterogeneous agents interpolate their display name (e.g. "Claude Code is running")
// so the user can tell which external agent is working.
const getOperationLabel = () => {
diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/GuideActions.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/GuideActions.tsx
index 2735ea540ea..8ad4dd30933 100644
--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/GuideActions.tsx
+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/GuideActions.tsx
@@ -1,31 +1,41 @@
import { isDesktop } from '@lobechat/const';
import { Button, Flexbox } from '@lobehub/ui';
-import { ExternalLink, Settings2 } from 'lucide-react';
+import { ExternalLink, RotateCcw, Settings2 } from 'lucide-react';
import { electronSystemService } from '@/services/electron/system';
interface GuideActionsProps {
docsUrl?: string;
onOpenSystemTools?: () => void;
+ onRetry?: () => void;
openDocsLabel?: string;
openSystemToolsLabel?: string;
+ retryLabel?: string;
showDocs?: boolean;
}
const GuideActions = ({
docsUrl,
onOpenSystemTools,
+ onRetry,
openDocsLabel,
openSystemToolsLabel,
+ retryLabel,
showDocs = false,
}: GuideActionsProps) => {
const showDocsButton = showDocs && Boolean(docsUrl && openDocsLabel);
const showSystemToolsButton = Boolean(onOpenSystemTools && openSystemToolsLabel);
+ const showRetryButton = Boolean(onRetry && retryLabel);
- if (!showDocsButton && !showSystemToolsButton) return null;
+ if (!showDocsButton && !showSystemToolsButton && !showRetryButton) return null;
return (
<Flexbox horizontal gap={8} justify="flex-end" style={{ flexWrap: 'wrap' }}>
+ {showRetryButton && (
+ <Button icon={<RotateCcw size={14} />} size="small" onClick={onRetry}>
+ {retryLabel}
+ </Button>
+ )}
{showSystemToolsButton && (
<Button icon={<Settings2 size={14} />} size="small" onClick={onOpenSystemTools}>
{openSystemToolsLabel}
diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx
index 1eac745a924..6b784c44d0d 100644
--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx
+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx
@@ -10,7 +10,7 @@ import RateLimitState from './states/RateLimitState';
import type { HeterogeneousAgentStatusGuideProps } from './types';
const HeterogeneousAgentStatusGuide = memo<HeterogeneousAgentStatusGuideProps>(
- ({ agentType = 'codex', error, onOpenSystemTools, variant = 'inline' }) => {
+ ({ agentType = 'codex', error, onOpenSystemTools, onRetry, variant = 'inline' }) => {
const config = resolveHeterogeneousAgentGuideConfig({
agentType,
errorAgentType: error?.agentType,
@@ -19,6 +19,7 @@ const HeterogeneousAgentStatusGuide = memo<HeterogeneousAgentStatusGuideProps>(
config,
error,
onOpenSystemTools,
+ onRetry,
variant,
};
diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/states/RateLimitState.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/RateLimitState.tsx
index 18fdb066044..0df51b2b1a3 100644
--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/states/RateLimitState.tsx
+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/RateLimitState.tsx
@@ -17,6 +17,7 @@ const RateLimitState = ({
config,
error,
onOpenSystemTools,
+ onRetry,
variant,
}: HeterogeneousAgentGuideStateProps) => {
const { t, i18n } = useTranslation('chat');
@@ -92,8 +93,12 @@ const RateLimitState = ({
variant={variant}
actions={
<GuideActions
- openSystemToolsLabel={t('cliRateLimitGuide.actions.openSystemTools')}
- onOpenSystemTools={onOpenSystemTools}
+ retryLabel={t('cliRateLimitGuide.actions.retry')}
+ openSystemToolsLabel={
+ onRetry ? undefined : t('cliRateLimitGuide.actions.openSystemTools')
+ }
+ onOpenSystemTools={onRetry ? undefined : onOpenSystemTools}
+ onRetry={onRetry}
/>
}
>
diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts b/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts
index 91f28bf7e59..1b52bf2fe61 100644
--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts
+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts
@@ -7,6 +7,7 @@ export interface HeterogeneousAgentStatusGuideProps {
agentType?: string;
error?: HeterogeneousAgentSessionError | null;
onOpenSystemTools?: () => void;
+ onRetry?: () => void;
variant?: HeterogeneousAgentStatusGuideVariant;
}
@@ -27,5 +28,6 @@ export interface HeterogeneousAgentGuideStateProps {
config: HeterogeneousAgentGuideConfig;
error?: HeterogeneousAgentSessionError | null;
onOpenSystemTools?: () => void;
+ onRetry?: () => void;
variant: HeterogeneousAgentStatusGuideVariant;
}
diff --git a/src/features/ModelSwitchPanel/components/ControlsForm/ContextCachingSwitch.tsx b/src/features/ModelSwitchPanel/components/ControlsForm/ContextCachingSwitch.tsx
index 39b53381cdb..cb6cce47dd2 100644
--- a/src/features/ModelSwitchPanel/components/ControlsForm/ContextCachingSwitch.tsx
+++ b/src/features/ModelSwitchPanel/components/ControlsForm/ContextCachingSwitch.tsx
@@ -9,6 +9,7 @@ interface ContextCachingSwitchProps {
const ContextCachingSwitch = memo<ContextCachingSwitchProps>(({ value, onChange }) => {
return (
<Switch
+ size={'small'}
value={!value}
onChange={(checked) => {
onChange?.(!checked);
diff --git a/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsx b/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsx
index a73e5a5805b..d8b4c85a147 100644
--- a/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsx
+++ b/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsx
@@ -43,6 +43,7 @@ import ThinkingSlider from './ThinkingSlider';
interface ControlsFormProps {
model?: string;
+ onUpdatingChange?: (updating: boolean) => void;
provider?: string;
}
@@ -60,434 +61,441 @@ const resolveEnableReasoningInitialValue = (config: LobeAgentChatConfig) => {
return undefined;
};
-const ControlsForm = memo<ControlsFormProps>(({ model: modelProp, provider: providerProp }) => {
- const { t } = useTranslation('chat');
- const agentId = useAgentId();
- const { updateAgentChatConfig } = useUpdateAgentConfig();
- const [agentModel, agentProvider] = useAgentStore((s) => [
- agentByIdSelectors.getAgentModelById(agentId)(s),
- agentByIdSelectors.getAgentModelProviderById(agentId)(s),
- ]);
- const model = modelProp ?? agentModel;
- const provider = providerProp ?? agentProvider;
- const [form] = Form.useForm();
+const ControlsForm = memo<ControlsFormProps>(
+ ({ model: modelProp, onUpdatingChange, provider: providerProp }) => {
+ const { t } = useTranslation('chat');
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const [agentModel, agentProvider] = useAgentStore((s) => [
+ agentByIdSelectors.getAgentModelById(agentId)(s),
+ agentByIdSelectors.getAgentModelProviderById(agentId)(s),
+ ]);
+ const model = modelProp ?? agentModel;
+ const provider = providerProp ?? agentProvider;
+ const [form] = Form.useForm();
- const config = useAgentStore(
- (s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s),
- isEqual,
- );
+ const config = useAgentStore(
+ (s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s),
+ isEqual,
+ );
- const modelExtendParams = useAiInfraStore(aiModelSelectors.modelExtendParams(model, provider));
- const initialValues = useMemo(() => {
- const enableReasoningInitialValue = resolveEnableReasoningInitialValue(config);
+ const modelExtendParams = useAiInfraStore(aiModelSelectors.modelExtendParams(model, provider));
+ const initialValues = useMemo(() => {
+ const enableReasoningInitialValue = resolveEnableReasoningInitialValue(config);
- return {
- ...config,
- enableReasoning: enableReasoningInitialValue,
- };
- }, [config]);
+ return {
+ ...config,
+ enableReasoning: enableReasoningInitialValue,
+ };
+ }, [config]);
- useEffect(() => {
- form.setFieldsValue(initialValues);
- }, [form, initialValues]);
+ useEffect(() => {
+ form.setFieldsValue(initialValues);
+ }, [form, initialValues]);
- const enableReasoningValue =
- AntdForm.useWatch(['enableReasoning'], form) ?? initialValues.enableReasoning;
+ const enableReasoningValue =
+ AntdForm.useWatch(['enableReasoning'], form) ?? initialValues.enableReasoning;
- const screens = Grid.useBreakpoint();
- const isNarrow = !screens.sm;
- const gpt52ReasoningEffortDefaultValue = model === 'gpt-5.5' ? 'medium' : 'none';
+ const screens = Grid.useBreakpoint();
+ const isNarrow = !screens.sm;
+ const gpt52ReasoningEffortDefaultValue = model === 'gpt-5.5' ? 'medium' : 'none';
- const descWide = { display: 'inline-block', width: 300 } as const;
- const descNarrow = {
- display: 'block',
- maxWidth: '100%',
- whiteSpace: 'normal',
- } as const;
+ const descWide = { display: 'inline-block', width: 300 } as const;
+ const descNarrow = {
+ display: 'block',
+ maxWidth: '100%',
+ whiteSpace: 'normal',
+ } as const;
- const items = [
- {
- children: <ContextCachingSwitch />,
- desc: (
- <span style={isNarrow ? descNarrow : descWide}>
- <Trans i18nKey={'extendParams.disableContextCaching.desc'} ns={'chat'}>
- 单条对话生成成本最高可降低 90%,响应速度提升 4 倍(
- <a
- href={'https://www.anthropic.com/news/prompt-caching?utm_source=lobechat'}
- rel="noreferrer nofollow"
- target="_blank"
- >
- 了解更多
- </a>
- )。开启后将自动禁用历史记录限制
- </Trans>
- </span>
- ),
- label: t('extendParams.disableContextCaching.title'),
- layout: isNarrow ? 'vertical' : 'horizontal',
- minWidth: undefined,
- name: 'disableContextCaching',
- },
- {
- children: <Switch />,
- desc: (
- <span style={isNarrow ? descNarrow : descWide}>
- <Trans i18nKey={'extendParams.enableReasoning.desc'} ns={'chat'}>
- 开启后模型会先进行推理,适合复杂问题。
- </Trans>
- </span>
- ),
- label: t('extendParams.enableReasoning.title'),
- layout: isNarrow ? 'vertical' : 'horizontal',
- minWidth: undefined,
- name: 'enableReasoning',
- },
- {
- children: <Switch />,
- desc: isNarrow ? (
- <span style={descNarrow}>{t('extendParams.enableAdaptiveThinking.desc')}</span>
- ) : (
- t('extendParams.enableAdaptiveThinking.desc')
- ),
- label: t('extendParams.enableAdaptiveThinking.title'),
- layout: isNarrow ? 'vertical' : 'horizontal',
- minWidth: undefined,
- name: 'enableAdaptiveThinking',
- },
- (enableReasoningValue || modelExtendParams?.includes('reasoningBudgetToken')) && {
- children: <ReasoningTokenSlider />,
- label: t('extendParams.reasoningBudgetToken.title'),
- layout: 'vertical',
- minWidth: undefined,
- name: 'reasoningBudgetToken',
- style: {
- paddingBottom: 0,
+ const items = [
+ {
+ children: <ContextCachingSwitch />,
+ desc: (
+ <span style={isNarrow ? descNarrow : descWide}>
+ <Trans i18nKey={'extendParams.disableContextCaching.desc'} ns={'chat'}>
+ 单条对话生成成本最高可降低 90%,响应速度提升 4 倍(
+ <a
+ href={'https://www.anthropic.com/news/prompt-caching?utm_source=lobechat'}
+ rel="noreferrer nofollow"
+ target="_blank"
+ >
+ 了解更多
+ </a>
+ )。开启后将自动禁用历史记录限制
+ </Trans>
+ </span>
+ ),
+ label: t('extendParams.disableContextCaching.title'),
+ layout: isNarrow ? 'vertical' : 'horizontal',
+ minWidth: undefined,
+ name: 'disableContextCaching',
},
- },
- modelExtendParams?.includes('reasoningBudgetToken32k') && {
- children: <ReasoningTokenSlider32k />,
- label: t('extendParams.reasoningBudgetToken.title'),
- layout: 'vertical',
- minWidth: undefined,
- name: 'reasoningBudgetToken32k',
- style: {
- paddingBottom: 0,
+ {
+ children: <Switch size={'small'} />,
+ desc: (
+ <span style={isNarrow ? descNarrow : descWide}>
+ <Trans i18nKey={'extendParams.enableReasoning.desc'} ns={'chat'}>
+ 开启后模型会先进行推理,适合复杂问题。
+ </Trans>
+ </span>
+ ),
+ label: t('extendParams.enableReasoning.title'),
+ layout: isNarrow ? 'vertical' : 'horizontal',
+ minWidth: undefined,
+ name: 'enableReasoning',
},
- },
- modelExtendParams?.includes('reasoningBudgetToken80k') && {
- children: <ReasoningTokenSlider80k />,
- label: t('extendParams.reasoningBudgetToken.title'),
- layout: 'vertical',
- minWidth: undefined,
- name: 'reasoningBudgetToken80k',
- style: {
- paddingBottom: 0,
+ {
+ children: <Switch size={'small'} />,
+ desc: isNarrow ? (
+ <span style={descNarrow}>{t('extendParams.enableAdaptiveThinking.desc')}</span>
+ ) : (
+ t('extendParams.enableAdaptiveThinking.desc')
+ ),
+ label: t('extendParams.enableAdaptiveThinking.title'),
+ layout: isNarrow ? 'vertical' : 'horizontal',
+ minWidth: undefined,
+ name: 'enableAdaptiveThinking',
},
- },
- {
- children: <DeepSeekReasoningEffortSlider />,
- label: t('extendParams.reasoningEffort.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'deepseekV4ReasoningEffort',
- style: {
- paddingBottom: 0,
+ (enableReasoningValue || modelExtendParams?.includes('reasoningBudgetToken')) && {
+ children: <ReasoningTokenSlider />,
+ label: t('extendParams.reasoningBudgetToken.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'reasoningBudgetToken',
+ style: {
+ paddingBottom: 0,
+ },
},
- },
- {
- children: <ReasoningEffortSlider />,
- desc: 'reasoning_effort',
- label: t('extendParams.reasoningEffort.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'reasoningEffort',
- style: {
- paddingBottom: 0,
+ modelExtendParams?.includes('reasoningBudgetToken32k') && {
+ children: <ReasoningTokenSlider32k />,
+ label: t('extendParams.reasoningBudgetToken.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'reasoningBudgetToken32k',
+ style: {
+ paddingBottom: 0,
+ },
},
- },
- {
- children: <EffortSlider />,
- desc: isNarrow ? (
- <span style={descNarrow}>{t('extendParams.effort.desc')}</span>
- ) : (
- t('extendParams.effort.desc')
- ),
- label: t('extendParams.effort.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'effort',
- style: {
- paddingBottom: 0,
+ modelExtendParams?.includes('reasoningBudgetToken80k') && {
+ children: <ReasoningTokenSlider80k />,
+ label: t('extendParams.reasoningBudgetToken.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'reasoningBudgetToken80k',
+ style: {
+ paddingBottom: 0,
+ },
},
- },
- {
- children: <Opus47EffortSlider />,
- desc: isNarrow ? (
- <span style={descNarrow}>{t('extendParams.effort.desc')}</span>
- ) : (
- t('extendParams.effort.desc')
- ),
- label: t('extendParams.effort.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'opus47Effort',
- style: {
- paddingBottom: 0,
+ {
+ children: <DeepSeekReasoningEffortSlider />,
+ label: t('extendParams.reasoningEffort.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'deepseekV4ReasoningEffort',
+ style: {
+ paddingBottom: 0,
+ },
},
- },
- {
- children: <GPT5ReasoningEffortSlider />,
- desc: 'reasoning_effort',
- label: t('extendParams.reasoningEffort.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'gpt5ReasoningEffort',
- style: {
- paddingBottom: 0,
+ {
+ children: <ReasoningEffortSlider />,
+ desc: 'reasoning_effort',
+ label: t('extendParams.reasoningEffort.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'reasoningEffort',
+ style: {
+ paddingBottom: 0,
+ },
},
- },
- {
- children: <GPT51ReasoningEffortSlider />,
- desc: 'reasoning_effort',
- label: t('extendParams.reasoningEffort.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'gpt5_1ReasoningEffort',
- style: {
- paddingBottom: 0,
+ {
+ children: <EffortSlider />,
+ desc: isNarrow ? (
+ <span style={descNarrow}>{t('extendParams.effort.desc')}</span>
+ ) : (
+ t('extendParams.effort.desc')
+ ),
+ label: t('extendParams.effort.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'effort',
+ style: {
+ paddingBottom: 0,
+ },
},
- },
- {
- children: <GPT52ReasoningEffortSlider defaultValue={gpt52ReasoningEffortDefaultValue} />,
- desc: 'reasoning_effort',
- label: t('extendParams.reasoningEffort.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'gpt5_2ReasoningEffort',
- style: {
- paddingBottom: 0,
+ {
+ children: <Opus47EffortSlider />,
+ desc: isNarrow ? (
+ <span style={descNarrow}>{t('extendParams.effort.desc')}</span>
+ ) : (
+ t('extendParams.effort.desc')
+ ),
+ label: t('extendParams.effort.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'opus47Effort',
+ style: {
+ paddingBottom: 0,
+ },
},
- },
- {
- children: <GPT52ProReasoningEffortSlider />,
- desc: 'reasoning_effort',
- label: t('extendParams.reasoningEffort.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'gpt5_2ProReasoningEffort',
- style: {
- paddingBottom: 0,
+ {
+ children: <GPT5ReasoningEffortSlider />,
+ desc: 'reasoning_effort',
+ label: t('extendParams.reasoningEffort.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'gpt5ReasoningEffort',
+ style: {
+ paddingBottom: 0,
+ },
},
- },
- {
- children: <Grok420ReasoningEffortSlider />,
- desc: 'reasoning_effort',
- label: t('extendParams.reasoningEffort.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'grok4_20ReasoningEffort',
- style: {
- paddingBottom: 0,
+ {
+ children: <GPT51ReasoningEffortSlider />,
+ desc: 'reasoning_effort',
+ label: t('extendParams.reasoningEffort.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'gpt5_1ReasoningEffort',
+ style: {
+ paddingBottom: 0,
+ },
},
- },
- {
- children: <Grok43ReasoningEffortSlider />,
- desc: 'reasoning_effort',
- label: t('extendParams.reasoningEffort.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'grok4_3ReasoningEffort',
- style: {
- paddingBottom: 0,
+ {
+ children: <GPT52ReasoningEffortSlider defaultValue={gpt52ReasoningEffortDefaultValue} />,
+ desc: 'reasoning_effort',
+ label: t('extendParams.reasoningEffort.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'gpt5_2ReasoningEffort',
+ style: {
+ paddingBottom: 0,
+ },
},
- },
- {
- children: <Hy3ReasoningEffortSlider />,
- desc: 'reasoning_effort',
- label: t('extendParams.reasoningEffort.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'hy3ReasoningEffort',
- style: {
- paddingBottom: 0,
+ {
+ children: <GPT52ProReasoningEffortSlider />,
+ desc: 'reasoning_effort',
+ label: t('extendParams.reasoningEffort.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'gpt5_2ProReasoningEffort',
+ style: {
+ paddingBottom: 0,
+ },
},
- },
- {
- children: <CodexMaxReasoningEffortSlider />,
- desc: 'reasoning_effort',
- label: t('extendParams.reasoningEffort.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'codexMaxReasoningEffort',
- style: {
- paddingBottom: 0,
+ {
+ children: <Grok420ReasoningEffortSlider />,
+ desc: 'reasoning_effort',
+ label: t('extendParams.reasoningEffort.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'grok4_20ReasoningEffort',
+ style: {
+ paddingBottom: 0,
+ },
},
- },
- {
- children: <TextVerbositySlider />,
- desc: 'text_verbosity',
- label: t('extendParams.textVerbosity.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'textVerbosity',
- style: {
- paddingBottom: 0,
+ {
+ children: <Grok43ReasoningEffortSlider />,
+ desc: 'reasoning_effort',
+ label: t('extendParams.reasoningEffort.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'grok4_3ReasoningEffort',
+ style: {
+ paddingBottom: 0,
+ },
},
- },
- {
- children: <ThinkingBudgetSlider />,
- label: t('extendParams.thinkingBudget.title'),
- layout: 'vertical',
- minWidth: undefined,
- name: 'thinkingBudget',
- style: {
- paddingBottom: 0,
+ {
+ children: <Hy3ReasoningEffortSlider />,
+ desc: 'reasoning_effort',
+ label: t('extendParams.reasoningEffort.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'hy3ReasoningEffort',
+ style: {
+ paddingBottom: 0,
+ },
},
- tag: 'thinkingBudget',
- },
- {
- children: <Switch />,
- desc: isNarrow ? (
- <span style={descNarrow}>{t('extendParams.urlContext.desc')}</span>
- ) : (
- t('extendParams.urlContext.desc')
- ),
- label: t('extendParams.urlContext.title'),
- layout: isNarrow ? 'vertical' : 'horizontal',
- minWidth: undefined,
- name: 'urlContext',
- style: undefined,
- tag: 'urlContext',
- },
- {
- children: <ThinkingSlider />,
- label: t('extendParams.thinking.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'thinking',
- style: {
- paddingBottom: 0,
+ {
+ children: <CodexMaxReasoningEffortSlider />,
+ desc: 'reasoning_effort',
+ label: t('extendParams.reasoningEffort.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'codexMaxReasoningEffort',
+ style: {
+ paddingBottom: 0,
+ },
},
- },
- {
- children: <ThinkingLevelSlider />,
- label: t('extendParams.thinkingLevel.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'thinkingLevel',
- style: {
- paddingBottom: 0,
+ {
+ children: <TextVerbositySlider />,
+ desc: 'text_verbosity',
+ label: t('extendParams.textVerbosity.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'textVerbosity',
+ style: {
+ paddingBottom: 0,
+ },
},
- desc: 'thinkingLevel',
- },
- {
- children: <ThinkingLevel2Slider />,
- label: t('extendParams.thinkingLevel.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'thinkingLevel2',
- style: {
- paddingBottom: 0,
+ {
+ children: <ThinkingBudgetSlider />,
+ label: t('extendParams.thinkingBudget.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'thinkingBudget',
+ style: {
+ paddingBottom: 0,
+ },
+ tag: 'thinkingBudget',
},
- desc: 'thinkingLevel',
- },
- {
- children: <ThinkingLevel3Slider />,
- label: t('extendParams.thinkingLevel.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'thinkingLevel3',
- style: {
- paddingBottom: 0,
+ {
+ children: <Switch size={'small'} />,
+ desc: isNarrow ? (
+ <span style={descNarrow}>{t('extendParams.urlContext.desc')}</span>
+ ) : (
+ t('extendParams.urlContext.desc')
+ ),
+ label: t('extendParams.urlContext.title'),
+ layout: isNarrow ? 'vertical' : 'horizontal',
+ minWidth: undefined,
+ name: 'urlContext',
+ style: undefined,
+ tag: 'urlContext',
},
- desc: 'thinkingLevel',
- },
- {
- children: <ThinkingLevel4Slider />,
- label: t('extendParams.thinkingLevel.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'thinkingLevel4',
- style: {
- paddingBottom: 0,
+ {
+ children: <ThinkingSlider />,
+ label: t('extendParams.thinking.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'thinking',
+ style: {
+ paddingBottom: 0,
+ },
},
- desc: 'thinkingLevel',
- },
- {
- children: <ThinkingLevel5Slider />,
- label: t('extendParams.thinkingLevel.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'thinkingLevel5',
- style: {
- paddingBottom: 0,
+ {
+ children: <ThinkingLevelSlider />,
+ label: t('extendParams.thinkingLevel.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'thinkingLevel',
+ style: {
+ paddingBottom: 0,
+ },
+ desc: 'thinkingLevel',
},
- desc: 'thinkingLevel',
- },
- {
- children: <ImageAspectRatioSelect />,
- label: t('extendParams.imageAspectRatio.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'imageAspectRatio',
- style: {
- paddingBottom: 0,
+ {
+ children: <ThinkingLevel2Slider />,
+ label: t('extendParams.thinkingLevel.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'thinkingLevel2',
+ style: {
+ paddingBottom: 0,
+ },
+ desc: 'thinkingLevel',
},
- desc: 'aspectRatio',
- },
- {
- children: <ImageAspectRatio2Select />,
- label: t('extendParams.imageAspectRatio.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'imageAspectRatio2',
- style: {
- paddingBottom: 0,
+ {
+ children: <ThinkingLevel3Slider />,
+ label: t('extendParams.thinkingLevel.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'thinkingLevel3',
+ style: {
+ paddingBottom: 0,
+ },
+ desc: 'thinkingLevel',
},
- desc: 'aspectRatio',
- },
- {
- children: <ImageResolutionSlider />,
- label: t('extendParams.imageResolution.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'imageResolution',
- style: {
- paddingBottom: 0,
+ {
+ children: <ThinkingLevel4Slider />,
+ label: t('extendParams.thinkingLevel.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'thinkingLevel4',
+ style: {
+ paddingBottom: 0,
+ },
+ desc: 'thinkingLevel',
},
- desc: 'imageSize',
- },
- {
- children: <ImageResolution2Slider />,
- label: t('extendParams.imageResolution.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: 'imageResolution2',
- style: {
- paddingBottom: 0,
+ {
+ children: <ThinkingLevel5Slider />,
+ label: t('extendParams.thinkingLevel.title'),
+ layout: 'vertical',
+ minWidth: undefined,
+ name: 'thinkingLevel5',
+ style: {
+ paddingBottom: 0,
+ },
+ desc: 'thinkingLevel',
},
- desc: 'imageSize',
- },
- ].filter(Boolean) as FormItemProps[];
+ {
+ children: <ImageAspectRatioSelect />,
+ label: t('extendParams.imageAspectRatio.title'),
+ layout: 'horizontal',
+ minWidth: undefined,
+ name: 'imageAspectRatio',
+ style: {
+ paddingBottom: 0,
+ },
+ desc: 'aspectRatio',
+ },
+ {
+ children: <ImageAspectRatio2Select />,
+ label: t('extendParams.imageAspectRatio.title'),
+ layout: 'horizontal',
+ minWidth: undefined,
+ name: 'imageAspectRatio2',
+ style: {
+ paddingBottom: 0,
+ },
+ desc: 'aspectRatio',
+ },
+ {
+ children: <ImageResolutionSlider />,
+ label: t('extendParams.imageResolution.title'),
+ layout: 'horizontal',
+ minWidth: undefined,
+ name: 'imageResolution',
+ style: {
+ paddingBottom: 0,
+ },
+ desc: 'imageSize',
+ },
+ {
+ children: <ImageResolution2Slider />,
+ label: t('extendParams.imageResolution.title'),
+ layout: 'horizontal',
+ minWidth: undefined,
+ name: 'imageResolution2',
+ style: {
+ paddingBottom: 0,
+ },
+ desc: 'imageSize',
+ },
+ ].filter(Boolean) as FormItemProps[];
- return (
- <Form
- form={form}
- initialValues={initialValues}
- itemsType={'flat'}
- size={'small'}
- style={{ fontSize: 12 }}
- variant={'borderless'}
- items={
- (modelExtendParams || [])
- .map((item: any) => items.find((i) => i.name === item))
- .filter(Boolean) as FormItemProps[]
- }
- onValuesChange={async (values) => {
- await updateAgentChatConfig(values);
- }}
- />
- );
-});
+ return (
+ <Form
+ form={form}
+ initialValues={initialValues}
+ itemsType={'flat'}
+ size={'small'}
+ style={{ fontSize: 12 }}
+ variant={'borderless'}
+ items={
+ (modelExtendParams || [])
+ .map((item: any) => items.find((i) => i.name === item))
+ .filter(Boolean) as FormItemProps[]
+ }
+ onValuesChange={async (values) => {
+ onUpdatingChange?.(true);
+ try {
+ await updateAgentChatConfig(values);
+ } finally {
+ onUpdatingChange?.(false);
+ }
+ }}
+ />
+ );
+ },
+);
export default ControlsForm;
diff --git a/src/features/ModelSwitchPanel/components/ControlsForm/LevelSlider.tsx b/src/features/ModelSwitchPanel/components/ControlsForm/LevelSlider.tsx
index e95deb4b9ee..1c78e921f06 100644
--- a/src/features/ModelSwitchPanel/components/ControlsForm/LevelSlider.tsx
+++ b/src/features/ModelSwitchPanel/components/ControlsForm/LevelSlider.tsx
@@ -1,10 +1,89 @@
import { Flexbox } from '@lobehub/ui';
import { Slider } from 'antd';
-import { type SliderSingleProps } from 'antd/es/slider';
-import { type CSSProperties } from 'react';
+import type { SliderSingleProps } from 'antd/es/slider';
+import { createStaticStyles, cx } from 'antd-style';
+import type { CSSProperties, ReactNode } from 'react';
import { memo, useMemo } from 'react';
import useMergeState from 'use-merge-value';
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ label: css`
+ cursor: pointer;
+
+ padding: 0;
+ border: none;
+
+ font: inherit;
+ font-size: 12px;
+ line-height: 16px;
+ color: ${cssVar.colorTextTertiary};
+ text-align: center;
+ overflow-wrap: anywhere;
+
+ background: transparent;
+
+ transition: color 0.2s ease;
+
+ &:hover {
+ color: ${cssVar.colorTextSecondary};
+ }
+
+ &:focus-visible {
+ border-radius: 6px;
+ outline: 1px solid ${cssVar.colorBorder};
+ outline-offset: 2px;
+ }
+ `,
+ labels: css`
+ display: grid;
+ gap: 8px;
+ width: 100%;
+ `,
+ root: css`
+ width: 100%;
+ `,
+ selectedLabel: css`
+ color: ${cssVar.colorText};
+ `,
+ slider: css`
+ width: 100%;
+ padding-inline: 6px;
+
+ .ant-slider {
+ margin-block: 2px 0;
+ margin-inline: 0;
+ }
+
+ .ant-slider-rail {
+ background: ${cssVar.colorFillQuaternary};
+ }
+
+ .ant-slider-track {
+ background: ${cssVar.colorTextSecondary};
+ }
+
+ .ant-slider-dot {
+ border-color: ${cssVar.colorTextTertiary};
+ background: ${cssVar.colorBgElevated};
+ }
+
+ .ant-slider-dot-active {
+ border-color: ${cssVar.colorTextSecondary};
+ }
+
+ .ant-slider-handle::after {
+ background: ${cssVar.colorBgElevated};
+ box-shadow: 0 0 0 2px ${cssVar.colorTextSecondary};
+ }
+
+ .ant-slider-handle:hover::after,
+ .ant-slider-handle:focus::after,
+ .ant-slider-handle:active::after {
+ box-shadow: 0 0 0 3px ${cssVar.colorTextSecondary};
+ }
+ `,
+}));
+
export interface LevelSliderProps<T extends string = string> {
/**
* Default value when uncontrolled
@@ -32,6 +111,38 @@ export interface LevelSliderProps<T extends string = string> {
value?: T;
}
+interface LevelOption<T extends string> {
+ label: ReactNode;
+ style?: CSSProperties;
+ value: T;
+}
+
+const getMinimumWidth = (levelCount: number, customMinWidth: CSSProperties['minWidth']) => {
+ const minimumWidth = levelCount >= 5 ? 260 : levelCount === 4 ? 220 : 180;
+
+ if (customMinWidth === undefined) return minimumWidth;
+
+ return typeof customMinWidth === 'number'
+ ? Math.max(customMinWidth, minimumWidth)
+ : customMinWidth;
+};
+
+const resolveMark = (
+ mark: NonNullable<SliderSingleProps['marks']>[number] | undefined,
+ fallback: string,
+): { label: ReactNode; style?: CSSProperties } => {
+ if (!mark) return { label: fallback };
+
+ if (typeof mark === 'object' && 'label' in mark) {
+ return {
+ label: mark.label ?? fallback,
+ style: mark.style,
+ };
+ }
+
+ return { label: mark as ReactNode };
+};
+
function LevelSlider<T extends string = string>({
levels,
value,
@@ -48,17 +159,18 @@ function LevelSlider<T extends string = string>({
value,
});
- const marks = useMemo(() => {
- if (customMarks) return customMarks;
- const result: SliderSingleProps['marks'] = {};
- levels.forEach((level, index) => {
- result[index] = level;
- });
- return result;
- }, [customMarks, levels]);
+ const options = useMemo(
+ () =>
+ levels.map<LevelOption<T>>((level, index) => ({
+ ...resolveMark(customMarks?.[index], level),
+ value: level,
+ })),
+ [customMarks, levels],
+ );
const currentIndex = levels.indexOf(currentLevel);
const sliderValue = currentIndex === -1 ? Math.floor(levels.length / 2) : currentIndex;
+ const { minWidth: customMinWidth, ...restStyle } = style ?? {};
const handleChange = (index: number) => {
const newLevel = levels[index];
@@ -69,15 +181,17 @@ function LevelSlider<T extends string = string>({
return (
<Flexbox
- horizontal
- align={'center'}
- gap={12}
- paddingInline={'0 20px'}
- style={{ minWidth: 200, width: '100%', ...style }}
+ className={styles.root}
+ gap={8}
+ style={{
+ ...restStyle,
+ minWidth: getMinimumWidth(levels.length, customMinWidth),
+ width: '100%',
+ }}
>
- <Flexbox flex={1}>
+ <div className={styles.slider}>
<Slider
- marks={marks}
+ dots
max={levels.length - 1}
min={0}
step={1}
@@ -85,7 +199,30 @@ function LevelSlider<T extends string = string>({
value={sliderValue}
onChange={handleChange}
/>
- </Flexbox>
+ </div>
+ <div
+ className={styles.labels}
+ style={{ gridTemplateColumns: `repeat(${levels.length}, minmax(0, 1fr))` }}
+ >
+ {options.map((option, index) => {
+ const selected = index === sliderValue;
+
+ return (
+ <button
+ aria-current={selected ? 'true' : undefined}
+ className={cx(styles.label, selected && styles.selectedLabel)}
+ key={option.value}
+ style={option.style}
+ type="button"
+ onClick={() => {
+ setCurrentLevel(option.value);
+ }}
+ >
+ {option.label}
+ </button>
+ );
+ })}
+ </div>
</Flexbox>
);
}
diff --git a/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx b/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx
index 3b04f27eea7..20bf35c2fc6 100644
--- a/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx
+++ b/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx
@@ -27,7 +27,6 @@ import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useEnabledChatModels } from '@/hooks/useEnabledChatModels';
-import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
import { useGlobalStore } from '@/store/global';
import type { ModelDetailPanelExpandedKey } from '@/store/global/initialState';
import { systemStatusSelectors } from '@/store/global/selectors';
@@ -40,8 +39,6 @@ import {
getTextOutputUnitRate,
} from '@/utils/index';
-import ControlsForm from './ControlsForm';
-
const styles = createStaticStyles(({ css, cssVar }) => ({
actionText: css`
font-size: 14px;
@@ -51,21 +48,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
padding-block-end: 8px;
`,
- extraControls: css`
- padding: 8px;
-
- .ant-form-item:first-child {
- padding-block: 0 4px;
- }
-
- .ant-form-item:last-child {
- padding-block: 4px 0;
- }
-
- .ant-divider {
- display: none;
- }
- `,
row: css`
padding-block: 4px;
padding-inline: 8px;
@@ -299,23 +281,19 @@ const ModelDetailPanel: FC<ModelDetailPanelProps> = memo(
return providerData?.children.find((m) => m.id === modelId);
}, [enabledList, modelId, provider]);
- const hasExtendParams = useAiInfraStore(
- aiModelSelectors.isModelHasExtendParams(modelId ?? '', provider ?? ''),
- );
-
const expandedKeys = useGlobalStore(systemStatusSelectors.modelDetailPanelExpandedKeys);
const updateExpandedKeys = useGlobalStore((s) => s.updateModelDetailPanelExpandedKeys);
- const hasPricing = !!model?.pricing;
- const formatPrice = hasPricing ? getPrice(model!.pricing!) : null;
+ const pricing = model?.pricing;
+ const hasPricing = !!pricing;
+ const formatPrice = pricing ? getPrice(pricing) : null;
const pricingGroups = useMemo(
- () => (hasPricing ? groupPricingUnits(model!.pricing!.units) : []),
- [hasPricing, model?.pricing],
+ () => (pricing ? groupPricingUnits(pricing.units) : []),
+ [pricing],
);
const approximatePriceLabel = useMemo(() => {
- if (!hasPricing || !model?.pricing || !pricingMode) return null;
- const pricing = model.pricing;
+ if (!pricing || !pricingMode) return null;
const currency = pricing.currency as ModelPriceCurrency | undefined;
if (pricingMode === 'image' && typeof pricing.approximatePricePerImage === 'number') {
const amount = formatPriceByCurrency(pricing.approximatePricePerImage, currency);
@@ -332,7 +310,7 @@ const ModelDetailPanel: FC<ModelDetailPanelProps> = memo(
});
}
return null;
- }, [hasPricing, model?.pricing, pricingMode, t]);
+ }, [pricing, pricingMode, t]);
if (!model) return null;
@@ -345,7 +323,7 @@ const ModelDetailPanel: FC<ModelDetailPanelProps> = memo(
return (
<Flexbox className={styles.container}>
{/* Sections */}
- {(hasPricing || hasContext || hasAbilities || (hasExtendParams && !pricingMode)) && (
+ {(hasPricing || hasContext || hasAbilities) && (
<Accordion
expandedKeys={expandedKeys}
gap={8}
@@ -554,32 +532,6 @@ const ModelDetailPanel: FC<ModelDetailPanelProps> = memo(
</Flexbox>
</AccordionItem>
)}
- {/* Model Config (agent chat only; requires ChatInput zustand provider) */}
- {hasExtendParams && provider && !pricingMode && (
- <AccordionItem
- itemKey="config"
- paddingBlock={6}
- paddingInline={8}
- title={
- <Flexbox horizontal align={'center'} gap={8}>
- <div
- style={{
- background: '#52c41a',
- borderRadius: 2,
- flexShrink: 0,
- height: 14,
- width: 3,
- }}
- />
- <span className={styles.titleText}>{t('ModelSwitchPanel.detail.config')}</span>
- </Flexbox>
- }
- >
- <div className={styles.extraControls}>
- <ControlsForm model={model.id} provider={provider} />
- </div>
- </AccordionItem>
- )}
</Accordion>
)}
</Flexbox>
diff --git a/src/features/Portal/Thread/Chat/index.tsx b/src/features/Portal/Thread/Chat/index.tsx
index ce2189c52ac..853e04b43de 100644
--- a/src/features/Portal/Thread/Chat/index.tsx
+++ b/src/features/Portal/Thread/Chat/index.tsx
@@ -97,7 +97,9 @@ const ThreadChatContent = memo<ThreadChatContentProps>(({ isSubagentThread }) =>
<ChatList itemContent={itemContent} />
</Flexbox>
</Suspense>
- {!isSubagentThread && <ChatInput leftActions={['typo', 'stt', 'portalToken']} />}
+ {!isSubagentThread && (
+ <ChatInput leftActions={['typo', 'stt']} rightActions={['contextWindow']} />
+ )}
</>
);
});
diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.ts
index 5a457e9b245..007e0193bdf 100644
--- a/src/helpers/toolEngineering/index.ts
+++ b/src/helpers/toolEngineering/index.ts
@@ -6,7 +6,7 @@ import { KnowledgeBaseManifest } from '@lobechat/builtin-tool-knowledge-base';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { MemoryManifest } from '@lobechat/builtin-tool-memory';
import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
-import { alwaysOnToolIds, defaultToolIds } from '@lobechat/builtin-tools';
+import { alwaysOnToolIds, chatModeAllowedToolIds, defaultToolIds } from '@lobechat/builtin-tools';
import { createEnableChecker, type PluginEnableChecker } from '@lobechat/context-engine';
import { ToolsEngine } from '@lobechat/context-engine';
import { type ChatCompletionTool, type ToolManifest, type WorkingModel } from '@lobechat/types';
@@ -125,11 +125,45 @@ export const createAgentToolsEngine = (
const searchConfig = getSearchConfig(workingModel.model, workingModel.provider);
const agentState = getAgentStoreState();
const userPlugins = agentSelectors.currentAgentPlugins(agentState);
+ const isChatMode =
+ agentChatConfigSelectors.currentChatConfig(agentState).enableAgentMode === false;
+
+ // Each entry below still respects its own runtime gate; in chat mode this
+ // is the entire whitelist. `allowExplicitActivation` and user plugins /
+ // `alwaysOnToolIds` are deliberately omitted in chat mode so the activator
+ // can't smuggle additional tools in.
+ const kbEnabled = agentSelectors.hasEnabledKnowledgeBases(agentState);
+ const memoryEnabled =
+ agentChatConfigSelectors.currentChatConfig(agentState).memory?.enabled ??
+ settingsSelectors.memoryEnabled(useUserStore.getState());
+ const webBrowsingEnabled = searchConfig.useApplicationBuiltinSearchTool;
+
+ const chatModeRules = {
+ [KnowledgeBaseManifest.identifier]: kbEnabled,
+ [MemoryManifest.identifier]: memoryEnabled,
+ [WebBrowsingManifest.identifier]: webBrowsingEnabled,
+ };
+
+ const agentModeRules = {
+ // Runtime-resolved plugins (from agentConfigResolver for the effective agent,
+ // may include sub-agent/group/page scope plugins not on the active agent)
+ ...(pluginIds && Object.fromEntries(pluginIds.map((id) => [id, true]))),
+ // User-selected plugins (from the active agent)
+ ...Object.fromEntries(userPlugins.map((id) => [id, true])),
+ // Always-on builtin tools
+ ...Object.fromEntries(alwaysOnToolIds.map((id) => [id, true])),
+ // System-level rules (may override user selection for specific tools)
+ [CloudSandboxManifest.identifier]: agentChatConfigSelectors.isCloudSandboxEnabled(agentState),
+ [KnowledgeBaseManifest.identifier]: kbEnabled,
+ [LocalSystemManifest.identifier]: agentChatConfigSelectors.isLocalSystemEnabled(agentState),
+ [MemoryManifest.identifier]: memoryEnabled,
+ [WebBrowsingManifest.identifier]: webBrowsingEnabled,
+ };
return createToolsEngine({
- defaultToolIds,
+ defaultToolIds: isChatMode ? chatModeAllowedToolIds : defaultToolIds,
enableChecker: createEnableChecker({
- allowExplicitActivation: true,
+ allowExplicitActivation: !isChatMode,
platformFilter: ({ pluginId }) => {
const toolStoreState = getToolStoreState();
const installedPlugin = pluginSelectors.getInstalledPluginById(pluginId)(toolStoreState);
@@ -144,24 +178,7 @@ export const createAgentToolsEngine = (
return undefined; // fall through to rules
},
- rules: {
- // Runtime-resolved plugins (from agentConfigResolver for the effective agent,
- // may include sub-agent/group/page scope plugins not on the active agent)
- ...(pluginIds && Object.fromEntries(pluginIds.map((id) => [id, true]))),
- // User-selected plugins (from the active agent)
- ...Object.fromEntries(userPlugins.map((id) => [id, true])),
- // Always-on builtin tools
- ...Object.fromEntries(alwaysOnToolIds.map((id) => [id, true])),
- // System-level rules (may override user selection for specific tools)
- [CloudSandboxManifest.identifier]:
- agentChatConfigSelectors.isCloudSandboxEnabled(agentState),
- [KnowledgeBaseManifest.identifier]: agentSelectors.hasEnabledKnowledgeBases(agentState),
- [LocalSystemManifest.identifier]: agentChatConfigSelectors.isLocalSystemEnabled(agentState),
- [MemoryManifest.identifier]:
- agentChatConfigSelectors.currentChatConfig(agentState).memory?.enabled ??
- settingsSelectors.memoryEnabled(useUserStore.getState()),
- [WebBrowsingManifest.identifier]: searchConfig.useApplicationBuiltinSearchTool,
- },
+ rules: isChatMode ? chatModeRules : agentModeRules,
}),
});
};
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index 241400ca216..8ae7d3eea5a 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -204,6 +204,8 @@ export default {
'knowledgeBase.library.action.detail': 'Details',
'knowledgeBase.library.action.remove': 'Remove',
'knowledgeBase.library.title': 'Files / Libraries',
+ 'knowledgeBase.files': 'Files',
+ 'knowledgeBase.libraries': 'Libraries',
'knowledgeBase.relativeFilesOrLibraries': 'Related Files/Libraries',
'knowledgeBase.title': 'Library',
'knowledgeBase.uploadGuide': "Uploaded files can be viewed in the 'Resources' section.",
@@ -298,6 +300,7 @@ export default {
'cliAuthGuide.runCommand': 'Run this in Terminal',
'cliAuthGuide.title': 'Sign in to {{name}}',
'cliRateLimitGuide.actions.openSystemTools': 'Open System Tools',
+ 'cliRateLimitGuide.actions.retry': 'Retry',
'cliRateLimitGuide.afterReset':
'Wait until the reset time, then retry your message. If you are using API authorization, you can also check your provider quota and billing status.',
'cliRateLimitGuide.desc':
@@ -368,6 +371,26 @@ export default {
'memory.title': 'Memory',
'search.grounding.imageSearchQueries': 'Image Search Keywords',
'search.grounding.imageTitle': 'Found {{count}} images',
+ 'chatMode.agent': 'Agent',
+ 'plus.search.appSearch': 'Smart Search',
+ 'plus.search.appSearchDesc':
+ 'LobeHub optimized search service, delivering best retrieval results.',
+ 'plus.search.modelSearch': 'Provider Search',
+ 'plus.search.modelSearchDesc': 'May cause unexpected behavior when enabled, not recommended.',
+ 'plus.search.off': 'Off',
+ 'plus.search.offDesc': '',
+ 'plus.addSkills': 'Add Skills...',
+ 'plus.title': 'Add',
+ 'plus.tooltip': 'Add files, skills, and more context...',
+ 'chatMode.agentCap.env': 'Runtime env',
+ 'chatMode.agentCap.files': 'File access',
+ 'chatMode.agentCap.memory': 'Memory',
+ 'chatMode.agentCap.tools': 'Tool calls',
+ 'chatMode.agentCap.web': 'Web search',
+ 'chatMode.agentDesc': 'Agent can use tools and environment to complete tasks automatically',
+ 'chatMode.chat': 'Chat',
+ 'chatMode.chatDesc': 'No runtime environment or autonomy; uses fewer tokens',
+ 'chatMode.select': 'Switch Mode',
'runtimeEnv.mode.cloud': 'Cloud Sandbox',
'runtimeEnv.mode.cloudDesc': 'Run in a secure cloud sandbox',
'runtimeEnv.mode.local': 'Local',
@@ -392,9 +415,12 @@ export default {
'searchAgentPlaceholder': 'Search agents...',
'searchAgents': 'Search agents...',
'selectedAgents': 'Selected agents',
- 'followUpPlaceholder': 'Follow up. @ to assign tasks to other agents.',
+ 'followUpPlaceholder': 'Follow up.',
'followUpPlaceholderHeterogeneous': 'Follow up.',
'sendPlaceholder': 'Ask, create, or start a task, <hotkey><hotkey/>',
+ 'sendPlaceholderChat': 'Ask, search, or brainstorm, <hotkey><hotkey/>',
+ 'sendPlaceholderChatWithAgentAssignment':
+ 'Ask, search, or brainstorm. @ to bring in other agents.',
'sendPlaceholderHeterogeneous': 'Describe a task or ask a question to {{name}}',
'sendPlaceholderWithAgentAssignment':
'Ask, create, or start a task. @ to assign tasks to other agents.',
@@ -796,6 +822,7 @@ export default {
'untitledGroup': 'Untitled Group',
'updateAgent': 'Update Agent Information',
'upload.action.fileUpload': 'Upload File',
+ 'upload.action.fileOrImageUpload': 'Upload File or Image',
'upload.action.folderUpload': 'Upload Folder',
'upload.action.imageDisabled':
'The current model does not support visual recognition. Please switch models to use this feature.',
diff --git a/src/locales/default/setting.ts b/src/locales/default/setting.ts
index 89d57426241..f1bbebe6f2b 100644
--- a/src/locales/default/setting.ts
+++ b/src/locales/default/setting.ts
@@ -740,6 +740,17 @@ export default {
'settingModel.model.desc': '{{provider}} model',
'settingModel.model.title': 'Model',
'settingModel.params.title': 'Advanced Parameters',
+ 'settingModel.params.panel.advanced': 'Advanced Settings',
+ 'settingModel.params.panel.agentTitle': 'Agent Advanced Settings',
+ 'settingModel.params.panel.contextCompression': 'Auto-compress Context',
+ 'settingModel.params.panel.creativity': 'Creativity',
+ 'settingModel.params.panel.historyLimit': 'Limit History Messages',
+ 'settingModel.params.panel.openness': 'Openness',
+ 'settingModel.params.panel.responseLength': 'Limit Response Length',
+ 'settingModel.params.panel.tab': 'Params',
+ 'settingModel.params.panel.title': 'Chat Parameter Settings',
+ 'settingModel.params.panel.topicDivergence': 'Topic Divergence',
+ 'settingModel.params.panel.vocabularyRichness': 'Vocabulary Richness',
'settingModel.presencePenalty.desc':
'The higher the value, the more inclined to use different expressions and avoid concept repetition; the lower the value, the more inclined to use repeated concepts or narratives, resulting in more consistent expression.',
'settingModel.presencePenalty.title': 'Expression Divergence',
@@ -1145,6 +1156,7 @@ When I am ___, I need ___
'tools.builtins.task.description':
'Task management and execution — create, track, review, and complete tasks via CLI.',
'tools.builtins.task.title': 'Task',
+ 'tools.builtins.configure': 'Configure',
'tools.builtins.notInstalled': 'Not Installed',
'tools.builtins.uninstall': 'Uninstall',
'tools.builtins.uninstallConfirm.desc':
@@ -1362,6 +1374,10 @@ When I am ___, I need ___
'tools.plugins.noEnabled': 'No skills enabled',
'tools.plugins.store': 'Add skill',
'tools.search': 'Search skills...',
+ 'tools.activation.auto': 'Auto',
+ 'tools.activation.auto.desc': 'Smart',
+ 'tools.activation.pinned': 'Pinned',
+ 'tools.activation.pinned.desc': 'Always On',
'tools.skillActivateMode.auto.desc':
'AI can autonomously activate tools, run skills, and install new skills from the store',
'tools.skillActivateMode.auto.title': 'Auto',
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
index acc723d73a8..0940459b8a9 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
@@ -180,6 +180,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, meta
});
const isCompleted = status === 'completed';
+ const isRunning = status === 'running';
const hasUnread = id && isUnreadCompleted;
const unreadIcon = (
@@ -234,7 +235,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, meta
href={href}
title={title === '...' ? <DotsLoading gap={3} size={4} /> : title}
icon={(() => {
- if (isLoading) {
+ if (isLoading || isRunning) {
return (
<RingLoadingIcon
ringColor={loadingRingColor}
diff --git a/src/routes/(main)/agent/features/Conversation/Header/ParamsPanelToggle/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/ParamsPanelToggle/index.tsx
new file mode 100644
index 00000000000..0cb5695cd1c
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/Header/ParamsPanelToggle/index.tsx
@@ -0,0 +1,57 @@
+'use client';
+
+import { ActionIcon } from '@lobehub/ui';
+import { Settings2Icon } from 'lucide-react';
+import { memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useLocation } from 'react-router-dom';
+
+import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+
+const ParamsPanelToggle = memo(() => {
+ const { t } = useTranslation('setting');
+ const { pathname } = useLocation();
+ const isHetero = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);
+ const [showRightPanel, workingSidebarTab, setWorkingSidebarTab, toggleRightPanel] =
+ useGlobalStore((s) => [
+ systemStatusSelectors.showRightPanel(s),
+ s.status.workingSidebarTab,
+ s.setWorkingSidebarTab,
+ s.toggleRightPanel,
+ ]);
+
+ const active = showRightPanel && workingSidebarTab === 'params';
+
+ const handleClick = useCallback(() => {
+ if (active) {
+ toggleRightPanel(false);
+ return;
+ }
+
+ setWorkingSidebarTab('params');
+ toggleRightPanel(true);
+ }, [active, setWorkingSidebarTab, toggleRightPanel]);
+
+ if (isHetero || pathname.startsWith('/popup')) return null;
+
+ return (
+ <ActionIcon
+ active={active}
+ icon={Settings2Icon}
+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}
+ title={t('settingModel.params.panel.title')}
+ tooltipProps={{
+ placement: 'bottom',
+ }}
+ onClick={handleClick}
+ />
+ );
+});
+
+ParamsPanelToggle.displayName = 'ParamsPanelToggle';
+
+export default ParamsPanelToggle;
diff --git a/src/routes/(main)/agent/features/Conversation/Header/WorkingPanelToggle/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/WorkingPanelToggle/index.tsx
index dcc72ca0ed9..da57a6534ba 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/WorkingPanelToggle/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/WorkingPanelToggle/index.tsx
@@ -17,6 +17,7 @@ const WorkingPanelToggle = memo(() => {
systemStatusSelectors.showRightPanel(s),
s.toggleRightPanel,
]);
+ const setWorkingSidebarTab = useGlobalStore((s) => s.setWorkingSidebarTab);
// The popup window has no WorkingSidebar — hide the toggle to avoid a
// button that does nothing visible.
@@ -29,7 +30,10 @@ const WorkingPanelToggle = memo(() => {
icon={PanelRightOpenIcon}
size={DESKTOP_HEADER_ICON_SMALL_SIZE}
title={t('workingPanel.title')}
- onClick={() => toggleRightPanel(true)}
+ onClick={() => {
+ setWorkingSidebarTab('review');
+ toggleRightPanel(true);
+ }}
/>
);
});
diff --git a/src/routes/(main)/agent/features/Conversation/Header/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/index.tsx
index d8ed9e06b24..d257b84ce82 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/index.tsx
@@ -12,6 +12,7 @@ import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
import HeaderActions from './HeaderActions';
+import ParamsPanelToggle from './ParamsPanelToggle';
import ShareButton from './ShareButton';
import Tags from './Tags';
import WorkingPanelToggle from './WorkingPanelToggle';
@@ -76,6 +77,7 @@ const Header = memo(() => {
<OpenInAppButton workingDirectory={effectiveWorkingDirectory} />
)}
<ShareButton />
+ <ParamsPanelToggle />
<WorkingPanelToggle />
</Flexbox>
}
diff --git a/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx
index 1dfa4ce6981..8fa903c27a4 100644
--- a/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx
@@ -13,8 +13,8 @@ import { userGeneralSettingsSelectors } from '@/store/user/selectors';
import { useSendMenuItems } from './useSendMenuItems';
-const emptyRightActions: ActionKeys[] = [];
-const promptTransformRightActions: ActionKeys[] = ['promptTransform'];
+const contextWindowRightActions: ActionKeys[] = ['contextWindow'];
+const promptTransformRightActions: ActionKeys[] = ['promptTransform', 'contextWindow'];
/**
* MainChatInput
@@ -32,21 +32,11 @@ const MainChatInput = memo(() => {
const provider = useAgentStore(agentSelectors.currentAgentModelProvider);
const isAgentConfigLoading = useAgentStore(agentSelectors.isAgentConfigLoading);
const supportsImageOutput = useModelSupportImageOutput(model, provider);
- const rightActions = supportsImageOutput ? promptTransformRightActions : emptyRightActions;
+ const rightActions = supportsImageOutput
+ ? promptTransformRightActions
+ : contextWindowRightActions;
- const leftActions: ActionKeys[] = useMemo(
- () => [
- 'model',
- 'search',
- 'memory',
- 'fileUpload',
- 'tools',
- 'typo',
- ...(isDevMode ? (['params'] as ActionKeys[]) : []),
- 'mainToken',
- ],
- [isDevMode],
- );
+ const leftActions: ActionKeys[] = useMemo(() => ['model', 'plus'], []);
return (
<ChatInput
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ParamsSection/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ParamsSection/index.tsx
new file mode 100644
index 00000000000..d6465f26f7a
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ParamsSection/index.tsx
@@ -0,0 +1,20 @@
+import { memo, useState } from 'react';
+
+import Controls from '@/features/ChatInput/ActionBar/Params/Controls';
+import { createStore, Provider } from '@/features/ChatInput/store';
+import { useAgentStore } from '@/store/agent';
+
+const ParamsSection = memo(() => {
+ const agentId = useAgentStore((s) => s.activeAgentId) || '';
+ const [updating, setUpdating] = useState(false);
+
+ return (
+ <Provider createStore={() => createStore({ agentId })} key={agentId}>
+ <Controls setUpdating={setUpdating} updating={updating} variant="sidebar" />
+ </Provider>
+ );
+});
+
+ParamsSection.displayName = 'AgentWorkingSidebarParamsSection';
+
+export default ParamsSection;
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.test.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.test.tsx
index 3198df126e8..5ff2105b526 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.test.tsx
@@ -161,11 +161,11 @@ vi.mock('@/store/agent/selectors', () => ({
(state: { agentWorkingDirectoryById?: Record<string, string | undefined> }) =>
state.agentWorkingDirectoryById?.[agentId],
},
+ agentSelectors: {
+ isCurrentAgentHeterogeneous: (_state: Record<string, unknown>) => false,
+ },
chatConfigByIdSelectors: {
- isLocalSystemEnabledById:
- (_agentId: string) =>
- (_state: Record<string, unknown>) =>
- true,
+ isLocalSystemEnabledById: (_agentId: string) => (_state: Record<string, unknown>) => true,
},
}));
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
index 2ad973a4f70..35eb84d42b5 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
@@ -1,14 +1,18 @@
-import { ActionIcon, Flexbox, Text } from '@lobehub/ui';
+import { ActionIcon, Flexbox } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { PanelRightCloseIcon } from 'lucide-react';
-import { memo } from 'react';
+import { lazy, memo } from 'react';
import { useTranslation } from 'react-i18next';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import { useRepoType } from '@/features/ChatInput/RuntimeConfig/useRepoType';
import RightPanel from '@/features/RightPanel';
import { useAgentStore } from '@/store/agent';
-import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
+import {
+ agentByIdSelectors,
+ agentSelectors,
+ chatConfigByIdSelectors,
+} from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
import { useGlobalStore } from '@/store/global';
@@ -18,6 +22,8 @@ import ProgressSection from './ProgressSection';
import ResourcesSection from './ResourcesSection';
import Review from './Review';
+const ParamsSection = lazy(() => import('./ParamsSection'));
+
const styles = createStaticStyles(({ css, cssVar }) => ({
body: css`
overflow-y: auto;
@@ -67,10 +73,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
-type Tab = 'review' | 'resources' | 'files';
+type Tab = 'files' | 'params' | 'review' | 'resources';
const AgentWorkingSidebar = memo(() => {
- const { t } = useTranslation('chat');
+ const { t } = useTranslation(['chat', 'setting']);
const toggleRightPanel = useGlobalStore((s) => s.toggleRightPanel);
const setWorkingSidebarTab = useGlobalStore((s) => s.setWorkingSidebarTab);
const storedTab = useGlobalStore((s) => s.status.workingSidebarTab);
@@ -82,15 +88,15 @@ const AgentWorkingSidebar = memo(() => {
const isLocalSystemEnabled = useAgentStore((s) =>
activeAgentId ? chatConfigByIdSelectors.isLocalSystemEnabledById(activeAgentId)(s) : false,
);
+ const isHetero = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);
const workingDirectory = topicWorkingDirectory || agentWorkingDirectory;
const repoType = useRepoType(workingDirectory);
const filesAvailable = isLocalSystemEnabled && !!workingDirectory;
const reviewAvailable = isLocalSystemEnabled && !!workingDirectory && !!repoType;
- // Topic metadata is preferred for resuming a coding session, but Review and
- // Files are project-scoped and should also work before a topic has bound
- // metadata. Fall back to a still-visible tab when the stored choice is gone.
+ const paramsAvailable = !isHetero;
const resolveActiveTab = (): Tab => {
+ if (storedTab === 'params' && paramsAvailable) return 'params';
if (storedTab === 'review' && reviewAvailable) return 'review';
if (storedTab === 'files' && filesAvailable) return 'files';
if (storedTab === 'resources') return 'resources';
@@ -111,39 +117,42 @@ const AgentWorkingSidebar = memo(() => {
justify={'space-between'}
paddingInline={4}
>
- {reviewAvailable || filesAvailable ? (
- <div className={styles.tabs}>
+ <div className={styles.tabs}>
+ <button
+ className={`${styles.tab} ${activeTab === 'resources' ? styles.tabActive : ''}`}
+ type="button"
+ onClick={() => setWorkingSidebarTab('resources')}
+ >
+ {t('workingPanel.space')}
+ </button>
+ {reviewAvailable && (
<button
- className={`${styles.tab} ${activeTab === 'resources' ? styles.tabActive : ''}`}
+ className={`${styles.tab} ${activeTab === 'review' ? styles.tabActive : ''}`}
type="button"
- onClick={() => setWorkingSidebarTab('resources')}
+ onClick={() => setWorkingSidebarTab('review')}
>
- {t('workingPanel.space')}
+ {t('workingPanel.review.title')}
</button>
- {reviewAvailable && (
- <button
- className={`${styles.tab} ${activeTab === 'review' ? styles.tabActive : ''}`}
- type="button"
- onClick={() => setWorkingSidebarTab('review')}
- >
- {t('workingPanel.review.title')}
- </button>
- )}
- {filesAvailable && (
- <button
- className={`${styles.tab} ${activeTab === 'files' ? styles.tabActive : ''}`}
- type="button"
- onClick={() => setWorkingSidebarTab('files')}
- >
- {t('workingPanel.files.title')}
- </button>
- )}
- </div>
- ) : (
- <Flexbox paddingInline={8}>
- <Text strong>{t('workingPanel.space')}</Text>
- </Flexbox>
- )}
+ )}
+ {filesAvailable && (
+ <button
+ className={`${styles.tab} ${activeTab === 'files' ? styles.tabActive : ''}`}
+ type="button"
+ onClick={() => setWorkingSidebarTab('files')}
+ >
+ {t('workingPanel.files.title')}
+ </button>
+ )}
+ {paramsAvailable && (
+ <button
+ className={`${styles.tab} ${activeTab === 'params' ? styles.tabActive : ''}`}
+ type="button"
+ onClick={() => setWorkingSidebarTab('params')}
+ >
+ {t('settingModel.params.panel.tab', { ns: 'setting' })}
+ </button>
+ )}
+ </div>
<ActionIcon
icon={PanelRightCloseIcon}
size={DESKTOP_HEADER_ICON_SMALL_SIZE}
@@ -151,6 +160,11 @@ const AgentWorkingSidebar = memo(() => {
/>
</Flexbox>
<Flexbox className={styles.body} width={'100%'}>
+ {paramsAvailable && activeTab === 'params' && (
+ <Flexbox className={styles.pane}>
+ <ParamsSection />
+ </Flexbox>
+ )}
{reviewAvailable && (
<Flexbox className={activeTab === 'review' ? styles.pane : styles.paneHidden}>
<Review workingDirectory={workingDirectory} />
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx
index 61aa7e08cd3..1d0d9337383 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx
@@ -152,6 +152,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, stat
});
const isCompleted = status === 'completed';
+ const isRunning = status === 'running';
const hasUnread = id && isUnreadCompleted;
const infoColor = cssVar.colorInfo;
@@ -236,7 +237,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, stat
href={!editing ? href : undefined}
title={title === '...' ? <DotsLoading gap={3} size={4} /> : title}
icon={(() => {
- if (isLoading) {
+ if (isLoading || isRunning) {
return (
<Icon spin icon={Loader2Icon} size={'small'} style={{ color: cssVar.colorWarning }} />
);
diff --git a/src/routes/(main)/group/features/Conversation/MainChatInput/GroupChat.tsx b/src/routes/(main)/group/features/Conversation/MainChatInput/GroupChat.tsx
index d1662a0b124..376a7e61dbd 100644
--- a/src/routes/(main)/group/features/Conversation/MainChatInput/GroupChat.tsx
+++ b/src/routes/(main)/group/features/Conversation/MainChatInput/GroupChat.tsx
@@ -19,17 +19,11 @@ import { aiChatSelectors } from '@/store/chat/selectors';
import MessageFromUrl from './MessageFromUrl';
import { useSendMenuItems } from './useSendMenuItems';
-const leftActions: ActionKeys[] = [
- 'typo',
- 'fileUpload',
- '---',
- ['tools', 'params', 'clear'],
- 'mainToken',
-];
+const leftActions: ActionKeys[] = ['typo', 'fileUpload', '---', ['tools', 'params', 'clear']];
const dmLeftActions: ActionKeys[] = ['typo', 'fileUpload', '---', ['stt']];
-const rightActions: ActionKeys[] = [];
+const rightActions: ActionKeys[] = ['contextWindow'];
/**
* Message Editor for Group Chat along with DM Portal
@@ -78,7 +72,7 @@ const Desktop = memo((props: { targetMemberId?: string }) => {
metadata: { id: member.id },
})),
];
- }, [currentGroupMembers]);
+ }, [currentGroupMembers, t]);
const sendMenuItems = useSendMenuItems();
diff --git a/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsx b/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsx
index 5b67404de74..72669c44e71 100644
--- a/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsx
+++ b/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsx
@@ -16,10 +16,9 @@ const leftActions: ActionKeys[] = [
'tools',
'---',
['typo', 'params', 'clear'],
- 'mainToken',
];
-const rightActions: ActionKeys[] = [];
+const rightActions: ActionKeys[] = ['contextWindow'];
/**
* MainChatInput
diff --git a/src/routes/(main)/home/features/InputArea/index.tsx b/src/routes/(main)/home/features/InputArea/index.tsx
index b2f00a47006..e180cb27bba 100644
--- a/src/routes/(main)/home/features/InputArea/index.tsx
+++ b/src/routes/(main)/home/features/InputArea/index.tsx
@@ -20,7 +20,8 @@ import SkillInstallBanner, { SKILL_INSTALL_BANNER_ID } from './SkillInstallBanne
import StarterList from './StarterList';
import { useSend } from './useSend';
-const leftActions: ActionKeys[] = ['model', 'search', 'fileUpload', 'tools'];
+const leftActions: ActionKeys[] = ['agentMode', 'plus'];
+const rightActions: ActionKeys[] = ['modelLabel'];
type BannerKind = 'skill' | 'botIntegration' | 'messenger';
@@ -126,6 +127,7 @@ const InputArea = () => {
agentId={agentId}
allowExpand={false}
leftActions={leftActions}
+ rightActions={rightActions}
slashPlacement="bottom"
chatInputEditorRef={(instance) => {
if (!instance) return;
diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
index d43a9795901..415877f5157 100644
--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
@@ -658,10 +658,13 @@ export const createRuntimeExecutors = (
},
userMemory: state.metadata?.userMemory,
- // Skills configuration for <available_skills> injection
+ // Skills configuration for <available_skills> injection.
+ // In chat mode the MessagesEngine force-disables this injector via
+ // its `enableAgentMode` param — no extra gate needed here.
...(resolvedSkills?.enabledSkills?.length && {
skillsConfig: { enabledSkills: resolvedSkills.enabledSkills },
}),
+ enableAgentMode: agentConfig.chatConfig?.enableAgentMode,
// Topic reference summaries
...(topicReferences && { topicReferences }),
diff --git a/src/server/modules/Mecha/AgentToolsEngine/index.ts b/src/server/modules/Mecha/AgentToolsEngine/index.ts
index c03fb710607..da12eeab5f4 100644
--- a/src/server/modules/Mecha/AgentToolsEngine/index.ts
+++ b/src/server/modules/Mecha/AgentToolsEngine/index.ts
@@ -17,7 +17,12 @@ import { MemoryManifest } from '@lobechat/builtin-tool-memory';
import { MessageManifest } from '@lobechat/builtin-tool-message';
import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
-import { alwaysOnToolIds, builtinTools, defaultToolIds } from '@lobechat/builtin-tools';
+import {
+ alwaysOnToolIds,
+ builtinTools,
+ chatModeAllowedToolIds,
+ defaultToolIds,
+} from '@lobechat/builtin-tools';
import { createEnableChecker, type LobeToolManifest } from '@lobechat/context-engine';
import { ToolsEngine } from '@lobechat/context-engine';
import { type RuntimeEnvMode, type RuntimePlatform } from '@lobechat/types';
@@ -163,9 +168,10 @@ export const createServerAgentToolsEngine = (
const searchMode = agentConfig.chatConfig?.searchMode ?? 'auto';
const isSearchEnabled = searchMode !== 'off';
+ const isChatMode = agentConfig.chatConfig?.enableAgentMode === false;
log(
- 'Creating agent tools engine model=%s provider=%s searchMode=%s platform=%s runtimeMode=%s additionalManifests=%d hasClientExecutor=%s hasDeviceProxy=%s canUseDevice=%s',
+ 'Creating agent tools engine model=%s provider=%s searchMode=%s platform=%s runtimeMode=%s additionalManifests=%d hasClientExecutor=%s hasDeviceProxy=%s canUseDevice=%s isChatMode=%s',
model,
provider,
searchMode,
@@ -175,8 +181,61 @@ export const createServerAgentToolsEngine = (
hasClientExecutor,
hasDeviceProxy,
canUseDevice,
+ isChatMode,
);
+ // Chat mode: strict outer whitelist. Drop user plugins, alwaysOn tools, and
+ // every other runtime-managed rule. Each entry below still passes through
+ // its own runtime gate (KB needs enabled bases, memory needs global toggle,
+ // web-browsing needs search on). `allowExplicitActivation` is off so the
+ // activator can't smuggle anything else in.
+ const chatModeRules = {
+ [KnowledgeBaseManifest.identifier]: hasEnabledKnowledgeBases,
+ [MemoryManifest.identifier]: globalMemoryEnabled,
+ [WebBrowsingManifest.identifier]: isSearchEnabled,
+ };
+
+ const agentModeRules = {
+ // User-selected plugins
+ ...Object.fromEntries((agentConfig.plugins ?? []).map((id) => [id, true])),
+ // Always-on builtin tools
+ ...Object.fromEntries(alwaysOnToolIds.map((id) => [id, true])),
+ // System-level rules (may override user selection for specific tools)
+ [CloudSandboxManifest.identifier]: runtimeMode === 'cloud',
+ [KnowledgeBaseManifest.identifier]: hasEnabledKnowledgeBases,
+ // Local-system: gated by `canUseDevice` (resolveDeviceAccessPolicy)
+ // first — keeps external bot senders out before runtime checks even
+ // run. Then user must have opted into local runtime on this platform
+ // (`runtimeMode === 'local'`), AND one execution channel must exist:
+ // - `hasClientExecutor` — Phase 6.4 dispatch over the Agent Gateway
+ // WS that this request is already riding on; no extra server-side
+ // prerequisite needed;
+ // - legacy device-proxy with an online & auto-activated device.
+ [LocalSystemManifest.identifier]:
+ canUseDevice &&
+ !disableLocalSystem &&
+ runtimeMode === 'local' &&
+ (hasClientExecutor ||
+ (hasDeviceProxy && !!deviceContext?.deviceOnline && !!deviceContext?.autoActivated)),
+ [MemoryManifest.identifier]: globalMemoryEnabled,
+ // Only auto-enable in bot conversations; otherwise let user's plugin selection take effect
+ ...(isBotConversation && { [MessageManifest.identifier]: true }),
+ // Remote-device proxy: shown only when the server has a proxy but
+ // no specific device is auto-activated yet (user must pick). When
+ // the caller itself can execute `executor: 'client'` tools, the
+ // proxy is redundant — local-system goes directly to the caller.
+ //
+ // `canUseDevice` is the first short-circuit: external bot senders
+ // (and unconfigured bot owners) never reach the proxy, both because
+ // it would let them poke at the owner's machine AND because its
+ // systemRole would otherwise leak the device list into the LLM
+ // context — see the gated injection in `aiAgent.execAgent`.
+ [RemoteDeviceManifest.identifier]:
+ canUseDevice && hasDeviceProxy && !deviceContext?.autoActivated && !hasClientExecutor,
+ [AgentDocumentsManifest.identifier]: hasAgentDocuments,
+ [WebBrowsingManifest.identifier]: isSearchEnabled,
+ };
+
return createServerToolsEngine(context, {
// Pass additional manifests (e.g., LobeHub Skills)
additionalManifests,
@@ -186,7 +245,7 @@ export const createServerAgentToolsEngine = (
// gates below (LOBE-8768).
builtinTools: buildAllowedBuiltinTools({ canUseDevice, disableLocalSystem }),
// Add default tools based on configuration
- defaultToolIds,
+ defaultToolIds: isChatMode ? chatModeAllowedToolIds : defaultToolIds,
// Post-merge wall: a plugin or Skill/Klavis manifest claiming a
// device identifier survives `buildAllowedBuiltinTools` (which only
// filters the builtin source). Excluding the identifiers here drops
@@ -194,48 +253,10 @@ export const createServerAgentToolsEngine = (
// resolve them regardless of which manifest source declared them.
excludeIdentifiers: canUseDevice ? undefined : DEVICE_TOOL_IDENTIFIERS,
enableChecker: createEnableChecker({
- // Allow lobe-activator to dynamically enable tools at runtime (e.g., lobe-creds, lobe-cron)
- allowExplicitActivation: true,
- rules: {
- // User-selected plugins
- ...Object.fromEntries((agentConfig.plugins ?? []).map((id) => [id, true])),
- // Always-on builtin tools
- ...Object.fromEntries(alwaysOnToolIds.map((id) => [id, true])),
- // System-level rules (may override user selection for specific tools)
- [CloudSandboxManifest.identifier]: runtimeMode === 'cloud',
- [KnowledgeBaseManifest.identifier]: hasEnabledKnowledgeBases,
- // Local-system: gated by `canUseDevice` (resolveDeviceAccessPolicy)
- // first — keeps external bot senders out before runtime checks even
- // run. Then user must have opted into local runtime on this platform
- // (`runtimeMode === 'local'`), AND one execution channel must exist:
- // - `hasClientExecutor` — Phase 6.4 dispatch over the Agent Gateway
- // WS that this request is already riding on; no extra server-side
- // prerequisite needed;
- // - legacy device-proxy with an online & auto-activated device.
- [LocalSystemManifest.identifier]:
- canUseDevice &&
- !disableLocalSystem &&
- runtimeMode === 'local' &&
- (hasClientExecutor ||
- (hasDeviceProxy && !!deviceContext?.deviceOnline && !!deviceContext?.autoActivated)),
- [MemoryManifest.identifier]: globalMemoryEnabled,
- // Only auto-enable in bot conversations; otherwise let user's plugin selection take effect
- ...(isBotConversation && { [MessageManifest.identifier]: true }),
- // Remote-device proxy: shown only when the server has a proxy but
- // no specific device is auto-activated yet (user must pick). When
- // the caller itself can execute `executor: 'client'` tools, the
- // proxy is redundant — local-system goes directly to the caller.
- //
- // `canUseDevice` is the first short-circuit: external bot senders
- // (and unconfigured bot owners) never reach the proxy, both because
- // it would let them poke at the owner's machine AND because its
- // systemRole would otherwise leak the device list into the LLM
- // context — see the gated injection in `aiAgent.execAgent`.
- [RemoteDeviceManifest.identifier]:
- canUseDevice && hasDeviceProxy && !deviceContext?.autoActivated && !hasClientExecutor,
- [AgentDocumentsManifest.identifier]: hasAgentDocuments,
- [WebBrowsingManifest.identifier]: isSearchEnabled,
- },
+ // Allow lobe-activator to dynamically enable tools at runtime (e.g., lobe-creds, lobe-cron).
+ // Disabled in chat mode so the activator can't bypass the whitelist.
+ allowExplicitActivation: !isChatMode,
+ rules: isChatMode ? chatModeRules : agentModeRules,
}),
});
};
diff --git a/src/server/modules/Mecha/AgentToolsEngine/types.ts b/src/server/modules/Mecha/AgentToolsEngine/types.ts
index 5726e38c97c..64c47136f27 100644
--- a/src/server/modules/Mecha/AgentToolsEngine/types.ts
+++ b/src/server/modules/Mecha/AgentToolsEngine/types.ts
@@ -54,6 +54,12 @@ export interface ServerCreateAgentToolsEngineParams {
agentConfig: {
/** Optional agent chat config */
chatConfig?: {
+ /**
+ * When explicitly `false`, the agent runs in chat mode — the engine
+ * builds rules from `chatModeAllowedToolIds` only and ignores
+ * `plugins` and `alwaysOnToolIds`. Undefined / true → agent mode.
+ */
+ enableAgentMode?: boolean;
runtimeEnv?: RuntimeEnvConfig;
searchMode?: 'off' | 'on' | 'auto';
};
diff --git a/src/server/modules/Mecha/ContextEngineering/index.ts b/src/server/modules/Mecha/ContextEngineering/index.ts
index 9dec2895ef8..6ca29b28351 100644
--- a/src/server/modules/Mecha/ContextEngineering/index.ts
+++ b/src/server/modules/Mecha/ContextEngineering/index.ts
@@ -54,6 +54,7 @@ export const serverMessagesEngine = async ({
provider,
systemRole,
inputTemplate,
+ enableAgentMode,
enableHistoryCount,
forceFinish,
historyCount,
@@ -87,6 +88,7 @@ export const serverMessagesEngine = async ({
},
// Agent configuration
+ enableAgentMode,
enableHistoryCount,
// File context refs must stay stable; media URLs are sent through structured parts.
diff --git a/src/server/modules/Mecha/ContextEngineering/types.ts b/src/server/modules/Mecha/ContextEngineering/types.ts
index 169b2df9bc9..16731b9a096 100644
--- a/src/server/modules/Mecha/ContextEngineering/types.ts
+++ b/src/server/modules/Mecha/ContextEngineering/types.ts
@@ -95,6 +95,13 @@ export interface ServerMessagesEngineParams {
onboardingContext?: OnboardingContext;
// ========== Agent configuration ==========
+ /**
+ * Whether the agent runs in agent mode. When explicitly `false` (chat mode)
+ * the engine force-disables skills and agent-document injectors. Undefined /
+ * true → agent mode.
+ */
+ enableAgentMode?: boolean;
+
/** Whether to enable history message count limit */
enableHistoryCount?: boolean;
diff --git a/src/server/routers/lambda/topic.ts b/src/server/routers/lambda/topic.ts
index e730617b389..b4dc4b371b3 100644
--- a/src/server/routers/lambda/topic.ts
+++ b/src/server/routers/lambda/topic.ts
@@ -552,7 +552,10 @@ export const topicRouter = router({
})
.optional(),
sessionId: z.string().optional(),
- status: z.enum(['active', 'completed', 'archived']).nullable().optional(),
+ status: z
+ .enum(['active', 'running', 'paused', 'failed', 'completed', 'archived'])
+ .nullable()
+ .optional(),
title: z.string().optional(),
}),
}),
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index c22e87b5616..6442dbbc93a 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -677,6 +677,10 @@ export const contextEngineering = async ({
selectedSkills: initialContext?.selectedSkills,
selectedTools: initialContext?.selectedTools,
+ // Pass enableAgentMode through; MessagesEngine force-disables skills /
+ // agent-document injectors when this is `false` (chat mode).
+ enableAgentMode: agentChatConfigSelectors.currentChatConfig(agentStoreState).enableAgentMode,
+
// Skills configuration
// In auto mode: expose all installed skills so the AI can discover and activate them
// In manual mode: only expose user-selected skills (filtered by pluginIds)
diff --git a/src/store/agent/selectors/agentByIdSelectors.ts b/src/store/agent/selectors/agentByIdSelectors.ts
index f3c3e2b41a1..8e20c8f465f 100644
--- a/src/store/agent/selectors/agentByIdSelectors.ts
+++ b/src/store/agent/selectors/agentByIdSelectors.ts
@@ -54,31 +54,26 @@ const isAgentConfigLoadingById = (agentId: string) => (s: AgentStoreState) =>
!agentId || !s.agentMap[agentId];
/**
- * Get agent mode by agentId
- * Now reads from chatConfig.agentMode and chatConfig.enableAgentMode
+ * Get agent mode by agentId.
+ * Agent mode is the default — only an explicit `chatConfig.enableAgentMode === false`
+ * collapses the agent to chat mode.
*/
const getAgentModeById =
(agentId: string) =>
(s: AgentStoreState): AgentMode | undefined => {
- const config = agentSelectors.getAgentConfigById(agentId)(s);
-
- // Fallback: convert enableAgentMode to mode
- if (config?.enableAgentMode) {
- return 'auto';
- }
-
- return undefined;
+ const chatConfig = agentSelectors.getAgentConfigById(agentId)(s)?.chatConfig;
+ return chatConfig?.enableAgentMode === false ? undefined : 'auto';
};
/**
- * Check if agent mode is enabled by agentId
- * Supports backward compatibility with deprecated enableAgentMode field
+ * Check if agent mode is enabled by agentId.
+ * Defaults to true; only explicit `chatConfig.enableAgentMode === false` returns false.
*/
const getAgentEnableModeById =
(agentId: string) =>
(s: AgentStoreState): boolean => {
- const mode = getAgentModeById(agentId)(s);
- return mode !== undefined;
+ const chatConfig = agentSelectors.getAgentConfigById(agentId)(s)?.chatConfig;
+ return chatConfig?.enableAgentMode !== false;
};
/**
diff --git a/src/store/agent/selectors/selectors.ts b/src/store/agent/selectors/selectors.ts
index 00a71352000..8a98286da6d 100644
--- a/src/store/agent/selectors/selectors.ts
+++ b/src/store/agent/selectors/selectors.ts
@@ -239,18 +239,13 @@ const openingMessage = (s: AgentStoreState) => currentAgentConfig(s)?.openingMes
// ========== Agent Mode Config ============== //
/**
- * Get current agent's mode
- * Now reads from chatConfig.agentMode and chatConfig.enableAgentMode
+ * Get current agent's mode.
+ * Agent mode is the default — only an explicit `chatConfig.enableAgentMode === false`
+ * collapses the agent to chat mode.
*/
const currentAgentMode = (s: AgentStoreState): AgentMode | undefined => {
- const config = currentAgentConfig(s);
-
- // Fallback: convert enableAgentMode to mode
- if (config?.enableAgentMode) {
- return 'auto';
- }
-
- return undefined;
+ const chatConfig = currentAgentConfig(s)?.chatConfig;
+ return chatConfig?.enableAgentMode === false ? undefined : 'auto';
};
/**
diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.ts
index b14db34f0a5..2348d303877 100644
--- a/src/store/chat/slices/aiChat/actions/gateway.ts
+++ b/src/store/chat/slices/aiChat/actions/gateway.ts
@@ -390,6 +390,7 @@ export class GatewayActionImpl {
if (result.topicId) {
this.#get().internal_updateTopicLoading(result.topicId, true);
+ void this.#get().updateTopicStatus?.(result.topicId, 'running');
}
// Create a dedicated operation for gateway execution with correct context.
@@ -437,6 +438,7 @@ export class GatewayActionImpl {
this.#get().completeOperation(gatewayOpId);
if (result.topicId) {
this.#get().internal_updateTopicLoading(result.topicId, false);
+ void this.#get().updateTopicStatus?.(result.topicId, 'active');
// Clear running operation from topic metadata (best-effort from frontend;
// if browser was closed, reconnect logic will handle stale entries)
topicService
@@ -526,6 +528,7 @@ export class GatewayActionImpl {
onSessionComplete: () => {
this.#get().completeOperation(gatewayOpId);
this.#get().internal_updateTopicLoading(topicId, false);
+ void this.#get().updateTopicStatus?.(topicId, 'active');
topicService.updateTopicMetadata(topicId, { runningOperation: null }).catch(() => {});
},
operationId,
diff --git a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
index aad20d6fea1..20e50de646b 100644
--- a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
+++ b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
@@ -261,6 +261,10 @@ export const createGatewayEventHandler = (
if (data?.phase === 'human_approval' && data.requiresApproval && data.pendingToolsCalling) {
void notifyDesktopHumanApprovalRequired(get, context);
+ // Persist a paused marker so the sidebar reflects "waiting on user" across reload.
+ // Resume back to 'running' is free: approve / reject both spawn a new op via the
+ // executor entries, which already write 'running'.
+ if (context.topicId) void get().updateTopicStatus?.(context.topicId, 'paused');
}
break;
diff --git a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts
index 8576a414222..87e07bf205d 100644
--- a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts
@@ -14,6 +14,7 @@ import type { SubagentEventContext, ToolCallPayload } from '@lobechat/heterogene
import type {
ChatMessageError,
ChatToolPayload,
+ ChatTopicStatus,
ConversationContext,
HeterogeneousProviderConfig,
MessageMapScope,
@@ -1054,6 +1055,7 @@ export const executeHeterogeneousAgent = async (
messageError: ChatMessageError,
options?: { clearContent?: boolean },
) => {
+ writeTopicStatus('failed');
get().internal_toggleToolCallingStreaming(currentAssistantMessageId, undefined);
get().completeOperation(operationId);
@@ -1175,6 +1177,10 @@ export const executeHeterogeneousAgent = async (
workingDirectory: workingDirectory ?? '',
});
};
+ const writeTopicStatus = (status: ChatTopicStatus): void => {
+ if (!context.topicId) return;
+ void get().updateTopicStatus?.(context.topicId, status);
+ };
const retryWithoutResume = (error: unknown): boolean => {
if (
resumeFallbackTriggered ||
@@ -1295,6 +1301,8 @@ export const executeHeterogeneousAgent = async (
agentSessionId = result.sessionId;
if (!agentSessionId) throw new Error('Agent session returned no sessionId');
+ writeTopicStatus('running');
+
// Register cancel hook on the operation — when the user hits Stop, the op
// framework calls this; we SIGINT the CC process via the main-process IPC
// so the CLI exits instead of running to completion off-screen.
@@ -1762,6 +1770,7 @@ export const executeHeterogeneousAgent = async (
clearContent: shouldClearTerminalErrorContent,
});
} else {
+ writeTopicStatus('active');
// NOW forward the deferred terminal event — handler will fetchAndReplaceMessages
// and pick up the final persisted state.
const terminal: AgentStreamEvent = deferredTerminalEvent ?? {
@@ -1822,7 +1831,10 @@ export const executeHeterogeneousAgent = async (
// If the error came from a user-initiated cancel (SIGINT → non-zero
// exit), don't surface it as a runtime error toast — the operation is
// already marked cancelled and the partial content is persisted above.
- if (isAborted()) return;
+ if (isAborted()) {
+ writeTopicStatus('active');
+ return;
+ }
await persistTerminalError(messageError, { clearContent: shouldClearTerminalErrorContent });
},
@@ -1910,7 +1922,10 @@ export const executeHeterogeneousAgent = async (
completed = true;
// `sendPrompt` rejects when the CLI exits non-zero, which is how SIGINT
// lands here too. If the user cancelled, don't surface an error.
- if (isAborted()) return;
+ if (isAborted()) {
+ writeTopicStatus('active');
+ return;
+ }
const messageError = toHeterogeneousAgentMessageError(error, adapterType);
await persistTerminalError(messageError, {
clearContent: shouldSuppressTerminalErrorEcho(accumulatedContent, messageError),
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 1a80bf50d84..55d95a82638 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -20,7 +20,7 @@ import { useGlobalStore } from '@/store/global';
import { type StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
import { systemAgentSelectors, userGeneralSettingsSelectors } from '@/store/user/selectors';
-import { type ChatTopic, type CreateTopicParams } from '@/types/topic';
+import { type ChatTopic, type ChatTopicStatus, type CreateTopicParams } from '@/types/topic';
import { merge } from '@/utils/merge';
import { setNamespace } from '@/utils/storeDebug';
@@ -309,6 +309,22 @@ export class ChatTopicActionImpl {
await this.#get().internal_updateTopic(id, { title });
};
+ /**
+ * Persist the topic's status. Optimistically updates the in-memory map so the
+ * sidebar reflects the change immediately; persistence runs fire-and-forget so
+ * a transient network blip never tears down the agent run that owns the write.
+ */
+ updateTopicStatus = async (id: string, status: ChatTopicStatus): Promise<void> => {
+ const topic = topicSelectors.getTopicById(id)(this.#get());
+ if (!topic || topic.status === status) return;
+
+ this.#get().internal_dispatchTopic({ type: 'updateTopic', id, value: { status } });
+
+ await topicService.updateTopic(id, { status }).catch((err) => {
+ console.error('[updateTopicStatus] persist failed:', err);
+ });
+ };
+
autoRenameTopicTitle = async (id: string): Promise<void> => {
const { activeAgentId: agentId, summaryTopicTitle, internal_updateTopicLoading } = this.#get();
diff --git a/src/store/global/actions/workspacePane.ts b/src/store/global/actions/workspacePane.ts
index 4a1e52f79d5..0fb5bfbca5e 100644
--- a/src/store/global/actions/workspacePane.ts
+++ b/src/store/global/actions/workspacePane.ts
@@ -3,7 +3,7 @@ import { produce } from 'immer';
import { INBOX_SESSION_ID } from '@/const/session';
import { SESSION_CHAT_URL } from '@/const/url';
import type { GlobalStore } from '@/store/global';
-import type { ModelDetailPanelExpandedKey } from '@/store/global/initialState';
+import type { ModelDetailPanelExpandedKey, WorkingSidebarTab } from '@/store/global/initialState';
import type { StoreSetter } from '@/store/types';
import { getStableNavigate } from '@/utils/stableNavigate';
import { setNamespace } from '@/utils/storeDebug';
@@ -123,7 +123,7 @@ export class GlobalWorkspacePaneActionImpl {
this.#get().updateSystemStatus({ showSystemRole }, n('toggleMobileTopic', newValue));
};
- setWorkingSidebarTab = (tab: 'resources' | 'review' | 'files'): void => {
+ setWorkingSidebarTab = (tab: WorkingSidebarTab): void => {
if (this.#get().status.workingSidebarTab === tab) return;
this.#get().updateSystemStatus({ workingSidebarTab: tab }, n('setWorkingSidebarTab', tab));
};
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index 6780620acaf..091df9df01b 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -39,6 +39,8 @@ export enum GroupSettingsTabs {
Settings = 'settings',
}
+export type WorkingSidebarTab = 'files' | 'params' | 'resources' | 'review';
+
export enum SettingsTabs {
About = 'about',
Advanced = 'advanced',
@@ -274,7 +276,7 @@ export interface SystemStatus {
* Lifted to global so external triggers (e.g. the diff badge in the input bar)
* can switch the panel to "review" when revealing the right panel.
*/
- workingSidebarTab?: 'resources' | 'review' | 'files';
+ workingSidebarTab?: WorkingSidebarTab;
zenMode?: boolean;
}
diff --git a/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap b/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap
index de550581074..a8790469ef8 100644
--- a/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap
+++ b/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap
@@ -105,6 +105,7 @@ exports[`settingsSelectors > defaultAgent > should merge DEFAULT_AGENT and s.set
"config": {
"chatConfig": {
"autoCreateTopicThreshold": 2,
+ "enableAgentMode": true,
"enableAutoCreateTopic": true,
"enableCompressHistory": true,
"enableContextCompression": true,
@@ -149,6 +150,7 @@ exports[`settingsSelectors > defaultAgentConfig > should merge DEFAULT_AGENT_CON
{
"chatConfig": {
"autoCreateTopicThreshold": 2,
+ "enableAgentMode": true,
"enableAutoCreateTopic": true,
"enableCompressHistory": true,
"enableContextCompression": true,