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(chat): separate skill selection from tool configuration (#23271)

AmAzing-ae0ae38831fc
diff --git a/.agents/ux/lobe-design-rules.md b/.agents/ux/lobe-design-rules.md
index 29291350494..cf7253941a9 100644
--- a/.agents/ux/lobe-design-rules.md
+++ b/.agents/ux/lobe-design-rules.md
@@ -169,3 +169,17 @@ Enforcement: visual review of the actual icon and localized label at the target
On a dedicated instruction-editing page, place view-mode switches alongside the page title, not in an extra toolbar row inside the input boundary. The editor's boundary should identify where to type without becoming the page's strongest visual element on focus. Use the neutral outlined surface; do not turn its entire perimeter into a primary-colored focus frame. Preserve the editor caret and the mode buttons' keyboard focus indicators.
Enforcement: `EditorCanvas/index.test.tsx` checks that both mode controls remain outside the outlined input surface. Inspect the page at rest and while editing. Source: user correction on the Agent instruction editor: moving mode switches into the frame wasted a writing row, and a black focus border was too prominent.
+
+## LOBE-UX-024 — Conversation skill lists are invocation pickers
+
+User, device, project and Agent skill rows share the default skill glyph, not marketplace/custom avatars. This applies to conversation invocation lists; the agent's skill configuration page may show community skills' publisher icons via `MarketSkillIcon`, with the default skill glyph as fallback. Clicking a row in a conversation inserts the skill into the composer. Do not add per-row file counts or view/rename/delete actions, including right-click equivalents; section totals may remain.
+
+The conversation sidebar is not a full capability inventory: do not automatically add builtin instruction bundles when removing them from the Tools picker. Preserve their runtime configuration and existing slash/profile entry points where available; exposing them here is a separate product decision.
+
+Enforcement: `SkillsList` owns the glyph and exposes neither custom icons, file counts nor management-action props. `AgentDocumentsGroup.test.tsx` checks the real list's click/keyboard behavior and the absence of hover/context-menu management controls; `UserLevelSkills.test.ts` guards source-independent row data.
+
+User-skill enablement belongs in a separate management view entered through the section's settings icon (with a tooltip and accessible name). Keep the section collapsible when adding that action: use the Accordion action slot outside its trigger, and keep settings reachable while collapsed. `AgentDocumentsGroup.test.tsx` exercises the real section's collapse/expand and independent settings entry. In that view, checkboxes represent the pending enabled set: keep search, scoped bulk selection, and Save/Cancel; do not add saved-state Enabled/Disabled tabs that duplicate or conflict with the draft. `useUserSkillsManagement.test.ts` guards selection visibility and persistence across search.
+
+The title itself states the task and scope: “Choose the skills this agent can use” / 「选择当前助理可以使用的技能」. Merge useful explanatory copy into that title rather than dropping the scope or repeating it in a subtitle. Counts describe selected skills, not checked boxes; do not foreground checkbox mechanics or add uninstall disclaimers to this selection surface. Fixed-height virtual skill lists use the same row-height constant for the rendered rows, virtualizer, and short-list viewport, rather than reserving an estimated extra row.
+
+Source: user corrections while simplifying the conversation Skills panel, including removal of redundant status tabs, the text management button, and checkbox-centric copy.
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 85453247cf1..f240d65fc52 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2049,7 +2049,7 @@
"platformAgent.deviceGuard.platformUnavailable.title": "{{name}} not available",
"platformAgent.deviceGuard.refresh": "Refresh",
"plus.addAttachments": "Attachments",
- "plus.addSkills": "Add Skills...",
+ "plus.contextTooltip": "Add files, tools, and more context…",
"plus.search.appSearch": "Smart Search",
"plus.search.appSearchDesc": "LobeHub optimized search service, delivering best retrieval results.",
"plus.search.modelSearch": "Provider Search",
@@ -2057,7 +2057,6 @@
"plus.search.off": "Off",
"plus.search.offDesc": "",
"plus.title": "Add",
- "plus.tooltip": "Add files, skills, and more context...",
"processExplorer.copyPid": "Copy PID",
"processExplorer.filter": "Filter",
"processExplorer.gpu": "GPU",
@@ -3978,10 +3977,6 @@
"workingPanel.search.role.assistant": "Assistant",
"workingPanel.search.role.user": "You",
"workingPanel.search.title": "Search",
- "workingPanel.skills.actions.comingSoon": "Coming soon",
- "workingPanel.skills.actions.delete": "Delete",
- "workingPanel.skills.actions.rename": "Rename",
- "workingPanel.skills.actions.view": "View",
"workingPanel.skills.convert.action": "Convert",
"workingPanel.skills.convert.descriptionLabel": "Description",
"workingPanel.skills.convert.descriptionPlaceholder": "Describe when this skill should be used, so the agent knows when to load it.",
@@ -3996,19 +3991,18 @@
"workingPanel.skills.convert.title": "Convert document to skill",
"workingPanel.skills.convert.titleLabel": "Title",
"workingPanel.skills.convert.titlePlaceholder": "e.g. Weekly Report",
- "workingPanel.skills.delete.agentConfirm": "Remove the skill “{{name}}” from this agent? This cannot be undone.",
- "workingPanel.skills.delete.error": "Failed to delete skill",
- "workingPanel.skills.delete.success": "Skill deleted",
- "workingPanel.skills.delete.title": "Delete skill?",
- "workingPanel.skills.delete.userConfirm": "Uninstall the skill “{{name}}”? This cannot be undone.",
"workingPanel.skills.detail.title": "Skill details",
"workingPanel.skills.empty": "No skills available",
+ "workingPanel.skills.manage.noPermission": "You do not have permission to change skills for this agent.",
+ "workingPanel.skills.manage.noneEnabled": "No skills selected. Use the settings icon to choose skills.",
+ "workingPanel.skills.manage.save": "Save",
+ "workingPanel.skills.manage.saveFailed": "Could not save changes. Your selections are kept; try saving again.",
+ "workingPanel.skills.manage.selectResults": "Select all results ({{count}})",
+ "workingPanel.skills.manage.selected": "Selected skills: {{count}}",
+ "workingPanel.skills.manage.title": "Choose the skills this agent can use",
+ "workingPanel.skills.manage.unsaved": "Unsaved changes",
"workingPanel.skills.manualOnly": "Manual only",
"workingPanel.skills.noSearchResults": "No matching skills",
- "workingPanel.skills.rename.action": "Rename",
- "workingPanel.skills.rename.error": "Failed to rename skill",
- "workingPanel.skills.rename.placeholder": "Skill name",
- "workingPanel.skills.rename.title": "Rename skill",
"workingPanel.skills.searchPlaceholder": "Filter skills...",
"workingPanel.skills.section.agent": "Agent skills",
"workingPanel.skills.section.device": "Device skills",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 95642cf1ab2..bbad6bb5dee 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -2438,7 +2438,6 @@
"tools.activation.pinned": "Pinned",
"tools.activation.pinned.desc": "Always On",
"tools.add": "Add Skill",
- "tools.addSkillOrConnector": "Add Skills / Connectors",
"tools.builtins.builtin-dashboard.description": "Build live monitoring widgets from sandboxed scripts, preview them with real data and put them on dashboards",
"tools.builtins.builtin-dashboard.title": "Dashboards",
"tools.builtins.configure": "Configure",
@@ -2615,7 +2614,6 @@
"tools.connectorPolicy.options.onlyAdmins": "Owners and admins",
"tools.connectorPolicy.title": "Who can manage connectors",
"tools.connectorPolicy.updateFailed": "Couldn't update who can manage connectors. Please try again.",
- "tools.disabled": "The current model does not support function calls and cannot use the skill",
"tools.legacyConnector.configure": "Configure",
"tools.legacyConnector.upgradeDesc": "This connector still uses the legacy plugin format. Configure it to finish upgrading, then manage its tool permissions here.",
"tools.lobehubSkill.authorize": "Authorize",
@@ -2643,6 +2641,10 @@
"tools.noConfigurablePermissions": "This skill does not expose configurable tool permissions.",
"tools.notInstalled": "Not Installed",
"tools.notInstalledWarning": "This skill is not currently installed, which may affect agent functionality.",
+ "tools.picker.disabled": "This model does not support tool calling.",
+ "tools.picker.management": "Manage tools",
+ "tools.picker.search": "Search tools…",
+ "tools.picker.title": "Tools",
"tools.plugins.enabled": "Enabled: {{num}}",
"tools.plugins.groupName": "Skills",
"tools.plugins.management": "Skill Management",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 90be49bd14f..849560f6d33 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2049,7 +2049,7 @@
"platformAgent.deviceGuard.platformUnavailable.title": "{{name}} 不可用",
"platformAgent.deviceGuard.refresh": "刷新",
"plus.addAttachments": "附件",
- "plus.addSkills": "添加技能...",
+ "plus.contextTooltip": "添加文件、工具和更多上下文…",
"plus.search.appSearch": "智能检索",
"plus.search.appSearchDesc": "LobeHub 专属调优的搜索服务,检索效果最佳。",
"plus.search.modelSearch": "Provider 内置搜索",
@@ -2057,7 +2057,6 @@
"plus.search.off": "关闭",
"plus.search.offDesc": "",
"plus.title": "添加",
- "plus.tooltip": "添加文件、技能和更多上下文...",
"processExplorer.copyPid": "复制 PID",
"processExplorer.filter": "筛选",
"processExplorer.gpu": "GPU",
@@ -3978,10 +3977,6 @@
"workingPanel.search.role.assistant": "助理",
"workingPanel.search.role.user": "你",
"workingPanel.search.title": "搜索",
- "workingPanel.skills.actions.comingSoon": "即将支持",
- "workingPanel.skills.actions.delete": "删除",
- "workingPanel.skills.actions.rename": "重命名",
- "workingPanel.skills.actions.view": "查看",
"workingPanel.skills.convert.action": "转换",
"workingPanel.skills.convert.descriptionLabel": "描述",
"workingPanel.skills.convert.descriptionPlaceholder": "描述这个技能在什么场景下使用,让智能体知道何时加载它。",
@@ -3996,19 +3991,18 @@
"workingPanel.skills.convert.title": "将文档转换为技能",
"workingPanel.skills.convert.titleLabel": "标题",
"workingPanel.skills.convert.titlePlaceholder": "例如 周报",
- "workingPanel.skills.delete.agentConfirm": "确定从当前智能体移除技能「{{name}}」?此操作不可撤销。",
- "workingPanel.skills.delete.error": "删除技能失败",
- "workingPanel.skills.delete.success": "技能已删除",
- "workingPanel.skills.delete.title": "删除技能?",
- "workingPanel.skills.delete.userConfirm": "确定卸载技能「{{name}}」?此操作不可撤销。",
"workingPanel.skills.detail.title": "技能详情",
"workingPanel.skills.empty": "暂无可用技能",
+ "workingPanel.skills.manage.noPermission": "你没有修改此助理技能的权限。",
+ "workingPanel.skills.manage.noneEnabled": "暂无已选技能,点击设置图标进行选择。",
+ "workingPanel.skills.manage.save": "保存",
+ "workingPanel.skills.manage.saveFailed": "保存失败,已保留选择,请重试保存。",
+ "workingPanel.skills.manage.selectResults": "全选搜索结果({{count}} 项)",
+ "workingPanel.skills.manage.selected": "已选 {{count}} 个技能",
+ "workingPanel.skills.manage.title": "选择当前助理可以使用的技能",
+ "workingPanel.skills.manage.unsaved": "尚未保存",
"workingPanel.skills.manualOnly": "仅手动",
"workingPanel.skills.noSearchResults": "没有匹配的技能",
- "workingPanel.skills.rename.action": "重命名",
- "workingPanel.skills.rename.error": "重命名技能失败",
- "workingPanel.skills.rename.placeholder": "技能名称",
- "workingPanel.skills.rename.title": "重命名技能",
"workingPanel.skills.searchPlaceholder": "筛选技能...",
"workingPanel.skills.section.agent": "智能体技能",
"workingPanel.skills.section.device": "设备技能",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 1926d6ddfac..b5666458412 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -2438,7 +2438,6 @@
"tools.activation.pinned": "固定启用",
"tools.activation.pinned.desc": "始终注入",
"tools.add": "集成技能",
- "tools.addSkillOrConnector": "添加技能 / 连接器",
"tools.builtins.builtin-dashboard.description": "用沙箱脚本构建实时监控组件,用真实数据试运行预览,并添加到看板",
"tools.builtins.builtin-dashboard.title": "看板",
"tools.builtins.configure": "配置",
@@ -2615,7 +2614,6 @@
"tools.connectorPolicy.options.onlyAdmins": "仅 Owner 和管理员",
"tools.connectorPolicy.title": "连接器管理权限",
"tools.connectorPolicy.updateFailed": "没能更新连接器管理权限,请重试",
- "tools.disabled": "当前模型不支持函数调用,无法使用技能",
"tools.legacyConnector.configure": "配置",
"tools.legacyConnector.upgradeDesc": "此连接器仍在使用旧的插件格式。点击「配置」完成升级后,即可在此管理它的工具权限。",
"tools.lobehubSkill.authorize": "授权",
@@ -2643,6 +2641,10 @@
"tools.noConfigurablePermissions": "此技能未提供可配置的工具权限。",
"tools.notInstalled": "未安装",
"tools.notInstalledWarning": "当前技能暂未安装,可能会影响助理使用",
+ "tools.picker.disabled": "当前模型不支持工具调用。",
+ "tools.picker.management": "工具管理",
+ "tools.picker.search": "搜索工具…",
+ "tools.picker.title": "工具",
"tools.plugins.enabled": "已启用 {{num}}",
"tools.plugins.groupName": "三方技能",
"tools.plugins.management": "技能管理",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 87e647da47e..2845efad1ae 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1813,9 +1813,8 @@ export default {
'plus.search.off': 'Off',
'plus.search.offDesc': '',
'plus.addAttachments': 'Attachments',
- 'plus.addSkills': 'Add Skills...',
'plus.title': 'Add',
- 'plus.tooltip': 'Add files, skills, and more context...',
+ 'plus.contextTooltip': 'Add files, tools, and more context…',
'chatMode.agentCap.env': 'Runtime env',
'chatMode.agentCap.files': 'File access',
'chatMode.agentCap.memory': 'Memory',
@@ -4185,10 +4184,6 @@ export default {
'workingPanel.localFile.publish.version': 'Publish this version',
'workingPanel.localFile.tooLarge': 'File too large to preview',
'workingPanel.localFile.truncated': 'File preview truncated to {{limit}} characters',
- 'workingPanel.skills.actions.comingSoon': 'Coming soon',
- 'workingPanel.skills.actions.delete': 'Delete',
- 'workingPanel.skills.actions.rename': 'Rename',
- 'workingPanel.skills.actions.view': 'View',
'workingPanel.skills.convert.action': 'Convert',
'workingPanel.skills.convert.descriptionLabel': 'Description',
'workingPanel.skills.convert.descriptionPlaceholder':
@@ -4207,26 +4202,26 @@ export default {
'workingPanel.skills.convert.title': 'Convert document to skill',
'workingPanel.skills.convert.titleLabel': 'Title',
'workingPanel.skills.convert.titlePlaceholder': 'e.g. Weekly Report',
- 'workingPanel.skills.delete.agentConfirm':
- 'Remove the skill “{{name}}” from this agent? This cannot be undone.',
- 'workingPanel.skills.delete.error': 'Failed to delete skill',
- 'workingPanel.skills.delete.success': 'Skill deleted',
- 'workingPanel.skills.delete.title': 'Delete skill?',
- 'workingPanel.skills.delete.userConfirm':
- 'Uninstall the skill “{{name}}”? This cannot be undone.',
'workingPanel.skills.detail.title': 'Skill details',
'workingPanel.skills.empty': 'No skills available',
'workingPanel.skills.manualOnly': 'Manual only',
'workingPanel.skills.noSearchResults': 'No matching skills',
- 'workingPanel.skills.rename.action': 'Rename',
- 'workingPanel.skills.rename.error': 'Failed to rename skill',
- 'workingPanel.skills.rename.placeholder': 'Skill name',
- 'workingPanel.skills.rename.title': 'Rename skill',
'workingPanel.skills.searchPlaceholder': 'Filter skills...',
'workingPanel.skills.section.agent': 'Agent skills',
'workingPanel.skills.section.device': 'Device skills',
'workingPanel.skills.section.project': 'Project skills',
'workingPanel.skills.section.user': 'User skills',
+ 'workingPanel.skills.manage.noneEnabled':
+ 'No skills selected. Use the settings icon to choose skills.',
+ 'workingPanel.skills.manage.noPermission':
+ 'You do not have permission to change skills for this agent.',
+ 'workingPanel.skills.manage.save': 'Save',
+ 'workingPanel.skills.manage.saveFailed':
+ 'Could not save changes. Your selections are kept; try saving again.',
+ 'workingPanel.skills.manage.selected': 'Selected skills: {{count}}',
+ 'workingPanel.skills.manage.selectResults': 'Select all results ({{count}})',
+ 'workingPanel.skills.manage.title': 'Choose the skills this agent can use',
+ 'workingPanel.skills.manage.unsaved': 'Unsaved changes',
'workingPanel.skills.title': 'Skills',
'workingPanel.files.openNeedsTopic':
'Send a message first — this environment’s files open once the conversation has a session.',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index fa388a8e5c4..7e796256c22 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -4295,7 +4295,6 @@ When I am ___, I need ___
'workspaceSetting.tab.connector': 'Connectors',
'workspaceSetting.tab.skill': 'Skills',
'tools.add': 'Add Skill',
- 'tools.addSkillOrConnector': 'Add Skills / Connectors',
'tools.noConfigurablePermissions': 'This skill does not expose configurable tool permissions.',
'tools.legacyConnector.configure': 'Configure',
'tools.legacyConnector.upgradeDesc':
@@ -4431,7 +4430,6 @@ When I am ___, I need ___
'Are you sure you want to uninstall {{name}}? This skill will be removed from the current agent.',
'tools.builtins.uninstallConfirm.title': 'Uninstall {{name}}',
'tools.builtins.uninstalled': 'Uninstalled',
- 'tools.disabled': 'The current model does not support function calls and cannot use the skill',
'tools.composio.addServer': 'Add Server',
'tools.composio.authCompleted': 'Authentication Completed',
'tools.composio.authFailed': 'Authentication Failed',
@@ -4665,6 +4663,10 @@ When I am ___, I need ___
'tools.notInstalled': 'Not Installed',
'tools.notInstalledWarning':
'This skill is not currently installed, which may affect agent functionality.',
+ 'tools.picker.disabled': 'This model does not support tool calling.',
+ 'tools.picker.management': 'Manage tools',
+ 'tools.picker.search': 'Search tools…',
+ 'tools.picker.title': 'Tools',
'tools.plugins.enabled': 'Enabled: {{num}}',
'tools.plugins.groupName': 'Skills',
'tools.plugins.management': 'Skill Management',
diff --git a/public/static/app-images/agent_gateway_dark.webp b/public/static/app-images/agent_gateway_dark.webp
deleted file mode 100644
index 05619d1153e..00000000000
Binary files a/public/static/app-images/agent_gateway_dark.webp and /dev/null differ
diff --git a/public/static/app-images/agent_gateway_light.webp b/public/static/app-images/agent_gateway_light.webp
deleted file mode 100644
index 787b54cae4b..00000000000
Binary files a/public/static/app-images/agent_gateway_light.webp and /dev/null differ
diff --git a/src/components/MarketSkillIcon/index.tsx b/src/components/MarketSkillIcon/index.tsx
index 6ee1430c497..680ed7ce690 100644
--- a/src/components/MarketSkillIcon/index.tsx
+++ b/src/components/MarketSkillIcon/index.tsx
@@ -1,5 +1,5 @@
import { Avatar } from '@lobehub/ui';
-import { memo } from 'react';
+import { memo, type ReactNode } from 'react';
import { useDiscoverStore } from '@/store/discover';
import { skillSelectors } from '@/store/discover/selectors';
@@ -7,6 +7,8 @@ import { skillSelectors } from '@/store/discover/selectors';
export const SKILL_ICON_SIZE = 20;
interface MarketSkillIconProps {
+ /** Optional placeholder while loading or when no publisher icon is available. */
+ fallback?: ReactNode;
identifier: string;
name?: string;
size?: number;
@@ -21,11 +23,13 @@ interface MarketSkillIconProps {
* is not present in the market (e.g. user-imported skills from a custom URL).
*/
const MarketSkillIcon = memo<MarketSkillIconProps>(
- ({ identifier, name, size = SKILL_ICON_SIZE }) => {
+ ({ fallback, identifier, name, size = SKILL_ICON_SIZE }) => {
const useFetchSkillDetail = useDiscoverStore((s) => s.useFetchSkillDetail);
const { queryKey } = useFetchSkillDetail({ identifier });
const data = useDiscoverStore(skillSelectors.skillDetail(queryKey));
+ if (!data?.icon && fallback !== undefined) return fallback;
+
return (
<Avatar
avatar={data?.icon || name || identifier}
diff --git a/src/features/ChatInput/ActionBar/Params/Controls.tsx b/src/features/ChatInput/ActionBar/Params/Controls.tsx
index bf6bf943a9c..e54131e8950 100644
--- a/src/features/ChatInput/ActionBar/Params/Controls.tsx
+++ b/src/features/ChatInput/ActionBar/Params/Controls.tsx
@@ -42,6 +42,7 @@ import { useChatInputResourceAccess } from '../../hooks/useChatInputResourceAcce
import { useEffectiveAgentMode } from '../../hooks/useEffectiveAgentMode';
import { useToggleAgentMode } from '../../hooks/useToggleAgentMode';
import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
+import { useGatewayMode } from './useGatewayMode';
import { useParamsModelConfig } from './useParamsModelConfig';
interface ControlsProps {
@@ -413,6 +414,7 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
const { t } = useTranslation(['setting', 'components', 'chat']);
const agentId = useAgentId();
const toggleAgentMode = useToggleAgentMode();
+ const gatewayMode = useGatewayMode();
const { canUseResource } = useChatInputResourceAccess();
const { canSelectAgentMode, currentMode, isAgentModeUnavailable } =
useEffectiveAgentMode(agentId);
@@ -755,6 +757,21 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
})
}
/>
+ {gatewayMode.available && (
+ <ControlRow
+ title={t('gatewayMode.cardTitle', { ns: 'chat' })}
+ tooltip={t('gatewayMode.desc', { ns: 'chat' })}
+ action={
+ <Switch
+ aria-label={t('gatewayMode.cardTitle', { ns: 'chat' })}
+ checked={gatewayMode.enabled}
+ loading={gatewayMode.loading}
+ size={'small'}
+ onChange={gatewayMode.onChange}
+ />
+ }
+ />
+ )}
<ControlRow
tag="compression"
title={t('settingModel.params.panel.contextCompression')}
diff --git a/src/features/ChatInput/ActionBar/Params/useGatewayMode.test.ts b/src/features/ChatInput/ActionBar/Params/useGatewayMode.test.ts
new file mode 100644
index 00000000000..aeaded4edcc
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Params/useGatewayMode.test.ts
@@ -0,0 +1,118 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useGatewayMode } from './useGatewayMode';
+
+const mocks = vi.hoisted(() => ({
+ agentId: 'agent-1',
+ canConfigureResource: true,
+ defaultDisabled: undefined as boolean | undefined,
+ disabledByAgent: {} as Record<string, boolean | undefined>,
+ serverEnabled: true,
+ updateAgentChatConfig: vi.fn(),
+}));
+
+vi.mock('../../hooks/useAgentId', () => ({ useAgentId: () => mocks.agentId }));
+vi.mock('../../hooks/useChatInputResourceAccess', () => ({
+ useChatInputResourceAccess: () => ({ canConfigureResource: mocks.canConfigureResource }),
+}));
+vi.mock('../../hooks/useUpdateAgentConfig', () => ({
+ useUpdateAgentConfig: () => ({ updateAgentChatConfig: mocks.updateAgentChatConfig }),
+}));
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: object) => unknown) => selector({}),
+}));
+vi.mock('@/store/agent/selectors', () => ({
+ chatConfigByIdSelectors: {
+ getChatConfigById: (agentId: string) => () => ({
+ disableGatewayMode: mocks.disabledByAgent[agentId],
+ }),
+ },
+}));
+vi.mock('@/store/serverConfig', () => ({
+ serverConfigSelectors: { enableGatewayMode: () => mocks.serverEnabled },
+ useServerConfigStore: (selector: (state: object) => unknown) => selector({}),
+}));
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (state: object) => unknown) => selector({}),
+}));
+vi.mock('@/store/user/selectors', () => ({
+ settingsSelectors: {
+ defaultAgentConfig: () => ({ chatConfig: { disableGatewayMode: mocks.defaultDisabled } }),
+ },
+}));
+
+describe('advanced parameters gateway mode', () => {
+ beforeEach(() => {
+ mocks.agentId = 'agent-1';
+ mocks.canConfigureResource = true;
+ mocks.defaultDisabled = undefined;
+ mocks.disabledByAgent = {};
+ mocks.serverEnabled = true;
+ mocks.updateAgentChatConfig.mockReset().mockResolvedValue(undefined);
+ });
+
+ it.each([
+ [undefined, undefined, true],
+ [undefined, true, false],
+ [undefined, false, true],
+ [false, true, true],
+ [true, false, false],
+ ])('preserves agent=%s / default=%s as enabled=%s', (agent, defaults, enabled) => {
+ mocks.disabledByAgent['agent-1'] = agent;
+ mocks.defaultDisabled = defaults;
+ const { result } = renderHook(() => useGatewayMode());
+
+ expect(result.current.enabled).toBe(enabled);
+ expect(result.current.available).toBe(true);
+ expect(mocks.updateAgentChatConfig).not.toHaveBeenCalled();
+ });
+
+ it('follows the composer agent rather than another agent configuration', () => {
+ mocks.disabledByAgent = { 'agent-1': true, 'agent-2': false };
+ const { result, rerender } = renderHook(() => useGatewayMode());
+ expect(result.current.enabled).toBe(false);
+
+ mocks.agentId = 'agent-2';
+ rerender();
+ expect(result.current.enabled).toBe(true);
+ });
+
+ it.each([true, false])(
+ 'saves enabled=%s using the existing inverted config field',
+ async (enabled) => {
+ const { result } = renderHook(() => useGatewayMode());
+
+ await act(async () => result.current.onChange(enabled));
+
+ expect(mocks.updateAgentChatConfig).toHaveBeenCalledWith({ disableGatewayMode: !enabled });
+ expect(result.current.loading).toBe(false);
+ },
+ );
+
+ it.each(['server', 'permission', 'agent'] as const)(
+ 'hides the control and prevents writes when %s is unavailable',
+ async (gate) => {
+ if (gate === 'server') mocks.serverEnabled = false;
+ if (gate === 'permission') mocks.canConfigureResource = false;
+ if (gate === 'agent') mocks.agentId = '';
+ const { result } = renderHook(() => useGatewayMode());
+
+ expect(result.current.available).toBe(false);
+ await act(async () => result.current.onChange(false));
+ expect(mocks.updateAgentChatConfig).not.toHaveBeenCalled();
+ },
+ );
+
+ it('clears saving feedback after a failed write without changing the stored selection', async () => {
+ mocks.updateAgentChatConfig.mockRejectedValueOnce(new Error('Save failed'));
+ const { result } = renderHook(() => useGatewayMode());
+
+ await act(async () => {
+ await expect(result.current.onChange(false)).rejects.toThrow('Save failed');
+ });
+
+ expect(result.current.loading).toBe(false);
+ expect(result.current.enabled).toBe(true);
+ });
+});
diff --git a/src/features/ChatInput/ActionBar/Params/useGatewayMode.ts b/src/features/ChatInput/ActionBar/Params/useGatewayMode.ts
new file mode 100644
index 00000000000..210ec79880c
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Params/useGatewayMode.ts
@@ -0,0 +1,43 @@
+import { useState } from 'react';
+
+import { useAgentStore } from '@/store/agent';
+import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
+import { useUserStore } from '@/store/user';
+import { settingsSelectors } from '@/store/user/selectors';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import { useChatInputResourceAccess } from '../../hooks/useChatInputResourceAccess';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
+
+export const useGatewayMode = () => {
+ const agentId = useAgentId();
+ const { canConfigureResource } = useChatInputResourceAccess();
+ const serverEnabled = useServerConfigStore(serverConfigSelectors.enableGatewayMode);
+ const defaultDisabled = useUserStore(
+ (s) => settingsSelectors.defaultAgentConfig(s).chatConfig?.disableGatewayMode,
+ );
+ const agentDisabled = useAgentStore(
+ (s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s).disableGatewayMode,
+ );
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const [loading, setLoading] = useState(false);
+ const available = Boolean(agentId && serverEnabled && canConfigureResource);
+
+ const onChange = async (enabled: boolean) => {
+ if (!available) return;
+ setLoading(true);
+ try {
+ await updateAgentChatConfig({ disableGatewayMode: !enabled });
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return {
+ available,
+ enabled: (agentDisabled ?? defaultDisabled) !== true,
+ loading,
+ onChange,
+ };
+};
diff --git a/src/features/ChatInput/ActionBar/Plus/index.tsx b/src/features/ChatInput/ActionBar/Plus/index.tsx
index 52452006d5c..73921db31ac 100644
--- a/src/features/ChatInput/ActionBar/Plus/index.tsx
+++ b/src/features/ChatInput/ActionBar/Plus/index.tsx
@@ -7,7 +7,6 @@ import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import {
CheckIcon,
- Cloud,
FileUp,
LibraryBig,
PlusIcon,
@@ -19,29 +18,22 @@ import type { ReactNode } from 'react';
import { memo, Suspense, useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
-import { imageUrl } from '@/const/url';
import { openAttachKnowledgeModal } from '@/features/LibraryModal';
-import { useIsDark } from '@/hooks/useIsDark';
import { useMediaUploadAbility } from '@/hooks/useMediaUploadAbility';
import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
-import {
- featureFlagsSelectors,
- serverConfigSelectors,
- useServerConfigStore,
-} from '@/store/serverConfig';
+import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useUserStore } from '@/store/user';
-import { labPreferSelectors, settingsSelectors } from '@/store/user/selectors';
+import { labPreferSelectors } from '@/store/user/selectors';
import { useAgentId } from '../../hooks/useAgentId';
import { useChatInputResourceAccess } from '../../hooks/useChatInputResourceAccess';
import { useChatInputUpload } from '../../hooks/useChatInputUpload';
import { useEffectiveModel } from '../../hooks/useEffectiveModel';
import { useLargeFileLocalPath } from '../../hooks/useLargeFileLocalPath';
-import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
import { insertGoalTag } from '../../InputEditor/ActionTag/goalTag';
import { useChatInputStore } from '../../store';
import { type ActionDropdownMenuItems } from '../components/ActionDropdown';
@@ -50,6 +42,7 @@ import SubmenuChevron from '../components/SubmenuChevron';
import { useDetailPopoverState } from '../components/useDetailPopoverState';
import { useControls as useKnowledgeControls } from '../Knowledge/useControls';
import { useControls as useToolsControls } from '../Tools/useControls';
+import { useSkillsMenuItem } from './useSkillsMenuItem';
const styles = stylex.create({
activeLabel: {
@@ -81,23 +74,6 @@ const styles = stylex.create({
backgroundColor: cssVar.colorFillSecondary,
backgroundImage: 'none',
},
- gatewayBody: { padding: '12px' },
- gatewayCard: { overflow: 'hidden', width: '280px', borderRadius: '8px' },
- gatewayCover: {
- display: 'block',
- width: '100%',
- height: '148px',
- objectFit: 'cover',
- backgroundColor: cssVar.colorFillTertiary,
- backgroundImage: 'none',
- },
- gatewayDesc: {
- marginBlockStart: '6px',
- fontSize: '12px',
- lineHeight: 1.5,
- color: cssVar.colorTextSecondary,
- },
- gatewayTitle: { fontSize: '14px', fontWeight: 600, lineHeight: 1.35 },
hotArea: {
'::before': {
content: '""',
@@ -206,20 +182,14 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
const { t } = useTranslation('chat');
const { t: tEditor } = useTranslation('editor');
const { t: tSetting } = useTranslation('setting');
- const isDark = useIsDark();
const agentId = useAgentId();
const { canConfigureResource } = useChatInputResourceAccess();
- const { updateAgentChatConfig } = useUpdateAgentConfig();
// Goal creation is lab-gated while the product surface is being rolled out.
const enableGoals = useUserStore(labPreferSelectors.enableGoals);
const upload = useChatInputUpload();
const { enableKnowledgeBase } = useServerConfigStore(featureFlagsSelectors);
- const enableGatewayMode = useServerConfigStore(serverConfigSelectors.enableGatewayMode);
- const defaultDisableGatewayMode = useUserStore(
- (s) => settingsSelectors.defaultAgentConfig(s).chatConfig?.disableGatewayMode,
- );
const { model, provider } = useEffectiveModel(agentId);
const isAgentModeEnabled = useAgentStore(agentSelectors.isAgentModeEnabled);
@@ -235,10 +205,6 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
const skillActivateMode = useAgentStore((s) =>
chatConfigByIdSelectors.getSkillActivateModeById(agentId)(s),
);
- const disableGatewayMode = useAgentStore(
- (s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s).disableGatewayMode,
- );
- const isGatewayModeEnabled = (disableGatewayMode ?? defaultDisableGatewayMode) !== true;
const [showTypoBar, setShowTypoBar] = useChatInputStore((s) => [s.showTypoBar, s.setShowTypoBar]);
const editor = useChatInputStore((s) => s.editor);
@@ -259,6 +225,7 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
items: knowledgeItems,
} = useKnowledgeControls({ openAttachKnowledgeModal: handleOpenKnowledge });
const closeDropdown = useCallback(() => close(), [close]);
+ const skillsMenuItem = useSkillsMenuItem(closeDropdown);
const {
autoCount: skillAutoCount,
isPolicyMenuOpen: isSkillPolicyMenuOpen,
@@ -268,13 +235,6 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
pinnedCount: skillPinnedCount,
} = useToolsControls({ closeDropdown });
- const handleToggleGatewayMode = useCallback(
- async (checked: boolean) => {
- await updateAgentChatConfig({ disableGatewayMode: checked ? false : true });
- },
- [updateAgentChatConfig],
- );
-
const handleToggleParams = useCallback(() => {
close();
if (isParamsPanelActive) {
@@ -295,30 +255,16 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
label
);
- const renderLabelWithCount = (label: string, count: number, prefix?: string) =>
- count > 0 || prefix ? (
+ const renderLabelWithCount = (label: string, count: number) =>
+ count > 0 ? (
<span {...stylex.props(styles.labelWithChip)}>
<span>{label}</span>
- <span {...stylex.props(styles.countChip)}>{prefix ? `${prefix} | ${count}` : count}</span>
+ <span {...stylex.props(styles.countChip)}>{count}</span>
</span>
) : (
label
);
- const gatewayModeInfo = (
- <div {...stylex.props(styles.gatewayCard)}>
- <img
- alt=""
- {...stylex.props(styles.gatewayCover)}
- src={imageUrl(isDark ? 'agent_gateway_dark.webp' : 'agent_gateway_light.webp')}
- />
- <div {...stylex.props(styles.gatewayBody)}>
- <div {...stylex.props(styles.gatewayTitle)}>{t('gatewayMode.cardTitle')}</div>
- <div {...stylex.props(styles.gatewayDesc)}>{t('gatewayMode.desc')}</div>
- </div>
- </div>
- );
-
// The row detail card and the "..." policy menu anchor to the same right edge,
// so leaving hover live lets a neighbouring row's card open on top of the menu
// and swallow the click meant for it.
@@ -382,32 +328,7 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
header: skillMarketHeader,
icon: SkillsIcon,
key: 'tools',
- label: renderLabelWithCount(
- tSetting('tools.title'),
- activeSkillCount,
- tSetting(
- skillActivateMode === 'auto'
- ? 'tools.skillActivateMode.auto.title'
- : 'tools.skillActivateMode.manual.title',
- ),
- ),
- } as ActionDropdownMenuItems[number],
- ]
- : [];
-
- // Agent Gateway sits below the formatting toolbar (grouped with advanced
- // params), gated on the resource-configuration permission.
- const gatewayItem: ActionDropdownMenuItems =
- canConfigureResource && enableGatewayMode
- ? [
- {
- checked: isGatewayModeEnabled,
- icon: Cloud,
- key: 'gateway-mode',
- // Brand name — same in every language, so no i18n.
- label: <PopoverLabel label={'Agent Gateway'} popoverContent={gatewayModeInfo} />,
- onCheckedChange: handleToggleGatewayMode,
- type: 'switch',
+ label: renderLabelWithCount(tSetting('tools.picker.title'), activeSkillCount),
} as ActionDropdownMenuItems[number],
]
: [];
@@ -415,10 +336,15 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
// Memory and web search are activation entries of the Tools popover now: they
// live in its "Auto" group, can be disabled there, and carry their own settings,
// so this menu only owns the route to them.
- const coreItems: ActionDropdownMenuItems = canConfigureResource ? [...toolsItems] : [];
+ // Selecting a skill adds composer context; unlike tool configuration, it
+ // does not require resource-edit permission or model function calling.
+ const coreItems: ActionDropdownMenuItems = [
+ ...(canConfigureResource ? toolsItems : []),
+ skillsMenuItem,
+ ];
- // Formatting toolbar is always available; Agent Gateway + advanced params
- // only when the user can configure resources.
+ // Formatting toolbar is always available; advanced params only when the
+ // user can configure resources.
const formatItems: ActionDropdownMenuItems = [
// Formatting toolbar toggle — trailing switch; toggle by clicking the switch or the whole row
{
@@ -429,8 +355,6 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
onCheckedChange: (checked: boolean) => setShowTypoBar(checked),
type: 'switch',
},
- // Agent Gateway directly below the formatting toolbar.
- ...gatewayItem,
// Advanced parameter settings — only when resources can be configured.
...(canConfigureResource
? [
@@ -496,7 +420,7 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
: [];
// Grouped with a single divider only between non-empty groups:
- // [attachments] | [memory · search · skills] | [set goal] | [formatting · gateway · params]
+ // [attachments] | [tools · skills] | [set goal] | [formatting · params]
const menuGroups: ActionDropdownMenuItems[] = [
attachmentsItems,
coreItems,
@@ -515,13 +439,9 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
canUploadAudio,
editor,
enableFC,
- enableGatewayMode,
enableKnowledgeBase,
- handleToggleGatewayMode,
handleToggleParams,
isAgentModeEnabled,
- isDark,
- isGatewayModeEnabled,
isParamsPanelActive,
isSkillPolicyMenuOpen,
knowledgeEnabledCount,
@@ -538,6 +458,7 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
skillItems,
skillMarketFooter,
skillMarketHeader,
+ skillsMenuItem,
upload,
routeLargeFilesToLocalPaths,
close,
@@ -558,11 +479,11 @@ const PlusAction = memo(() => {
<ChatInputAction
icon={PlusIcon}
size={{ blockSize: 32, borderRadius: 16, size: 18 }}
- title={t('plus.tooltip')}
+ title={t('plus.contextTooltip')}
tooltipProps={{ placement: 'top' }}
dropdown={{
menu: { useItems: usePlusMenuItems },
- minWidth: 220,
+ minWidth: 196,
placement: 'topLeft',
}}
/>
diff --git a/src/features/ChatInput/ActionBar/Plus/useSkillsMenuItem.test.ts b/src/features/ChatInput/ActionBar/Plus/useSkillsMenuItem.test.ts
new file mode 100644
index 00000000000..2c72b587d8a
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Plus/useSkillsMenuItem.test.ts
@@ -0,0 +1,80 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useGlobalStore } from '@/store/global';
+import { initialState } from '@/store/global/initialState';
+
+import { useSkillsMenuItem } from './useSkillsMenuItem';
+
+vi.mock('@/utils/client/switchLang', () => ({ switchLang: vi.fn() }));
+
+vi.mock('react-i18next', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+const initialStore = useGlobalStore.getState();
+let persistedStatus: string | null;
+
+beforeEach(() => {
+ persistedStatus = localStorage.getItem('LOBE_SYSTEM_STATUS');
+ useGlobalStore.setState({
+ isStatusInit: true,
+ status: {
+ ...initialState.status,
+ showRightPanel: false,
+ showWorkingOverview: true,
+ workingSidebarTab: 'files',
+ },
+ });
+});
+
+afterEach(() => {
+ useGlobalStore.setState(initialStore, true);
+ if (persistedStatus === null) localStorage.removeItem('LOBE_SYSTEM_STATUS');
+ else localStorage.setItem('LOBE_SYSTEM_STATUS', persistedStatus);
+ vi.restoreAllMocks();
+});
+
+describe('useSkillsMenuItem', () => {
+ it('closes the composer menu before opening the skills sidebar', () => {
+ const close = vi.fn(() => {
+ expect(useGlobalStore.getState().status.showRightPanel).toBe(false);
+ });
+ const { result } = renderHook(() => useSkillsMenuItem(close));
+
+ act(() => result.current.onClick());
+
+ expect(close).toHaveBeenCalledOnce();
+ expect(useGlobalStore.getState().status).toMatchObject({
+ showRightPanel: true,
+ showWorkingOverview: false,
+ workingSidebarTab: 'skills',
+ workingSidebarTabRequest: { tab: 'skills' },
+ });
+ });
+
+ it('switches an already open sidebar from another tab to skills', () => {
+ useGlobalStore.setState({
+ status: { ...useGlobalStore.getState().status, showRightPanel: true },
+ });
+ const { result } = renderHook(() => useSkillsMenuItem(vi.fn()));
+
+ act(() => result.current.onClick());
+
+ expect(useGlobalStore.getState().status.showRightPanel).toBe(true);
+ expect(useGlobalStore.getState().status.workingSidebarTab).toBe('skills');
+ });
+
+ it('keeps skills open on repeated clicks rather than toggling the panel closed', () => {
+ const close = vi.fn();
+ const { result } = renderHook(() => useSkillsMenuItem(close));
+
+ act(() => result.current.onClick());
+ act(() => result.current.onClick());
+
+ expect(close).toHaveBeenCalledTimes(2);
+ expect(useGlobalStore.getState().status.showRightPanel).toBe(true);
+ expect(useGlobalStore.getState().status.workingSidebarTab).toBe('skills');
+ });
+});
diff --git a/src/features/ChatInput/ActionBar/Plus/useSkillsMenuItem.ts b/src/features/ChatInput/ActionBar/Plus/useSkillsMenuItem.ts
new file mode 100644
index 00000000000..8ffbb584c92
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Plus/useSkillsMenuItem.ts
@@ -0,0 +1,21 @@
+import { type MenuItemType } from '@lobehub/ui';
+import { SkillsIcon } from '@lobehub/ui/icons';
+import { useTranslation } from 'react-i18next';
+
+import { useGlobalStore } from '@/store/global';
+
+/** Hand off from the composer menu to the existing skill-selection sidebar. */
+export const useSkillsMenuItem = (close: () => void) => {
+ const { t } = useTranslation('chat');
+ const openWorkingSidebar = useGlobalStore((s) => s.openWorkingSidebar);
+
+ return {
+ icon: SkillsIcon,
+ key: 'skills',
+ label: t('workingPanel.resources.filter.skills'),
+ onClick: () => {
+ close();
+ openWorkingSidebar('skills');
+ },
+ } satisfies MenuItemType;
+};
diff --git a/src/features/ChatInput/ActionBar/Tools/PopoverContent.tsx b/src/features/ChatInput/ActionBar/Tools/PopoverContent.tsx
index c6cf9ca9938..d19eff5c2e1 100644
--- a/src/features/ChatInput/ActionBar/Tools/PopoverContent.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/PopoverContent.tsx
@@ -2,12 +2,14 @@ import { type ItemType } from '@lobehub/ui';
import { Flexbox, Icon, SearchBar, stopPropagation, usePopoverContext } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
-import { Pin, Settings, Store, Zap } from 'lucide-react';
+import { Pin, Settings, Zap } from 'lucide-react';
import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { buildAgentProfileTabPath } from '@/features/AgentProfileTabs/tabOptions';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useAgentId } from '../../hooks/useAgentId';
import { ScrollSignalProvider } from './ScrollSignalContext';
import SkillActivateMode from './SkillActivateMode';
import ToolsList from './ToolsList';
@@ -53,22 +55,6 @@ const styles = stylex.create({
lineHeight: '18px',
color: cssVar.colorTextTertiary,
},
- storeButton: {
- cursor: 'pointer',
- display: 'inline-flex',
- flex: 'none',
- gap: '4px',
- alignItems: 'center',
- height: '28px',
- paddingInline: '8px',
- borderStyle: 'none',
- borderRadius: '6px',
- fontSize: '13px',
- color: { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorText },
- backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },
- backgroundImage: { 'default': 'none', ':hover': 'none' },
- transition: 'color 0.2s, background 0.2s',
- },
});
const filterItems = (items: ItemType[], keyword: string): ItemType[] => {
@@ -100,13 +86,13 @@ interface PopoverContentProps {
autoCount: number;
detailPopoverDisabled?: boolean;
items: ItemType[];
- onOpenStore: () => void;
pinnedCount: number;
}
const PopoverContent = memo<PopoverContentProps>(
- ({ autoCount, detailPopoverDisabled, items, onOpenStore, pinnedCount }) => {
+ ({ autoCount, detailPopoverDisabled, items, pinnedCount }) => {
const { t } = useTranslation('setting');
+ const agentId = useAgentId();
const navigate = useWorkspaceAwareNavigate();
const [searchKeyword, setSearchKeyword] = useState('');
@@ -127,7 +113,7 @@ const PopoverContent = memo<PopoverContentProps>(
>
<SearchBar
allowClear
- placeholder={t('tools.search')}
+ placeholder={t('tools.picker.search')}
size="small"
style={{ flex: 1 }}
value={searchKeyword}
@@ -156,23 +142,14 @@ const PopoverContent = memo<PopoverContentProps>(
</span>
<Flexbox horizontal align="center" gap={2} style={{ marginInlineStart: 'auto' }}>
<button
- {...stylex.props(styles.storeButton)}
- type="button"
- onClick={() => {
- closePopover();
- onOpenStore();
- }}
- >
- <Icon icon={Store} size={14} />
- {t('tools.addSkillOrConnector')}
- </button>
- <button
- aria-label={t('tools.plugins.management')}
+ aria-label={t('tools.picker.management')}
{...stylex.props(styles.iconButton)}
+ disabled={!agentId}
type="button"
onClick={() => {
+ if (!agentId) return;
closePopover();
- navigate('/settings/connector');
+ navigate(buildAgentProfileTabPath(agentId, 'tools'));
}}
>
<Icon icon={Settings} size={14} />
diff --git a/src/features/ChatInput/ActionBar/Tools/index.tsx b/src/features/ChatInput/ActionBar/Tools/index.tsx
index cae545dbc21..78e998b02af 100644
--- a/src/features/ChatInput/ActionBar/Tools/index.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/index.tsx
@@ -1,8 +1,7 @@
import { Blocks } from 'lucide-react';
-import { memo, Suspense, useCallback } from 'react';
+import { memo, Suspense } from 'react';
import { useTranslation } from 'react-i18next';
-import { createSkillStoreModal } from '@/features/SkillStore';
import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';
import { useAgentId } from '../../hooks/useAgentId';
@@ -20,21 +19,22 @@ const Tools = memo(() => {
const enableFC = useModelSupportToolUse(model, provider);
- const handleOpenStore = useCallback(() => {
- createSkillStoreModal();
- }, []);
-
if (!enableFC)
return (
- <ChatInputAction disabled icon={Blocks} showTooltip={true} title={t('tools.disabled')} />
+ <ChatInputAction
+ disabled
+ icon={Blocks}
+ showTooltip={true}
+ title={t('tools.picker.disabled')}
+ />
);
return (
- <Suspense fallback={<ChatInputAction disabled icon={Blocks} title={t('tools.title')} />}>
+ <Suspense fallback={<ChatInputAction disabled icon={Blocks} title={t('tools.picker.title')} />}>
<ChatInputAction
icon={Blocks}
showTooltip={false}
- title={t('tools.title')}
+ title={t('tools.picker.title')}
popover={{
content: (
<PopoverContent
@@ -42,7 +42,6 @@ const Tools = memo(() => {
detailPopoverDisabled={isPolicyMenuOpen}
items={marketItems}
pinnedCount={pinnedCount}
- onOpenStore={handleOpenStore}
/>
),
maxWidth: 320,
diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.test.ts b/src/features/ChatInput/ActionBar/Tools/useControls.test.ts
new file mode 100644
index 00000000000..64e08c3b167
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Tools/useControls.test.ts
@@ -0,0 +1,204 @@
+import type { ItemType } from '@lobehub/ui';
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useControls } from './useControls';
+
+const mocks = vi.hoisted(() => ({
+ agentId: 'agent-1',
+ navigate: vi.fn(),
+ builtinSkills: [
+ { identifier: 'lobe-agent-browser', name: 'Agent Browser' },
+ { identifier: 'lobe-artifacts', name: 'Artifacts' },
+ { identifier: 'lobehub', name: 'LobeHub' },
+ ],
+ checked: [] as string[],
+ mode: 'auto',
+ plugins: [] as { identifier: string; mode: string }[],
+ skills: [
+ { id: 'market-row', identifier: 'excel-analysis', name: 'Excel Analysis', source: 'market' },
+ { id: 'user-row', identifier: 'custom-writing', name: 'Custom Writing', source: 'user' },
+ ],
+ togglePlugin: vi.fn(),
+ setPluginMode: vi.fn(),
+}));
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('../../hooks/useAgentId', () => ({ useAgentId: () => mocks.agentId }));
+vi.mock('../../hooks/useEffectiveModel', () => ({
+ useEffectiveModel: () => ({ model: 'model', provider: 'provider' }),
+}));
+vi.mock('../../hooks/useUpdateAgentConfig', () => ({
+ useUpdateAgentConfig: () => ({ updateAgentChatConfig: vi.fn() }),
+}));
+vi.mock('../Memory/useMemoryEnabled', () => ({ useMemoryEnabled: () => false }));
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => mocks.navigate,
+}));
+vi.mock('@/features/Connectors/CustomConnectorModal/useConnectorConfigure', () => ({
+ useConnectorConfigure: () => () => undefined,
+}));
+vi.mock('@/hooks/useFetchInstalledPlugins', () => ({ useFetchInstalledPlugins: vi.fn() }));
+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: unknown) => unknown) =>
+ selector({ setPluginMode: mocks.setPluginMode, togglePlugin: mocks.togglePlugin }),
+}));
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgentConfigById: () => () => ({ plugins: mocks.plugins }),
+ getAgentPluginsById: () => () => mocks.checked,
+ },
+ chatConfigByIdSelectors: {
+ getSearchModeById: () => () => 'off',
+ getSkillActivateModeById: () => () => mocks.mode,
+ },
+}));
+vi.mock('@/store/aiInfra', () => ({
+ aiModelSelectors: { isModelBuiltinSearchInternal: () => () => false },
+ useAiInfraStore: (selector: (state: unknown) => unknown) => selector({}),
+}));
+vi.mock('@/store/serverConfig', () => ({
+ serverConfigSelectors: { enableComposio: () => false, enableLobehubSkill: () => false },
+ useServerConfigStore: (selector: (state: unknown) => unknown) => selector({}),
+}));
+vi.mock('@/store/tool', () => ({
+ useToolStore: (selector: (state: unknown) => unknown) =>
+ selector({
+ isConnectorsInit: true,
+ useFetchAgentSkills: vi.fn(),
+ useFetchLobehubSkillConnections: vi.fn(),
+ useFetchUninstalledBuiltinTools: vi.fn(),
+ useFetchUserComposioConnections: vi.fn(),
+ }),
+}));
+vi.mock('@/store/tool/selectors', () => ({
+ agentSkillsSelectors: {
+ getMarketAgentSkills: () => mocks.skills.filter((skill) => skill.source === 'market'),
+ getUserAgentSkills: () => mocks.skills.filter((skill) => skill.source === 'user'),
+ },
+ builtinToolSelectors: {
+ fixedDisplayMetaList: () => () => [],
+ installedBuiltinSkills: () => mocks.builtinSkills,
+ // The real metadata inventory mixes tools and skill manifests.
+ metaList: () => [
+ { identifier: 'builtin-tool', meta: { title: 'Builtin Tool' } },
+ ...mocks.builtinSkills,
+ ...mocks.skills,
+ ],
+ metaListIncludingHidden: () => [
+ { identifier: 'builtin-tool', meta: { title: 'Builtin Tool' } },
+ ...mocks.builtinSkills,
+ ...mocks.skills,
+ ],
+ },
+ composioStoreSelectors: { getServers: () => [] },
+ lobehubSkillStoreSelectors: { getServers: () => [] },
+ pluginSelectors: {
+ installedPluginMetaList: () => [
+ { identifier: 'community-mcp', title: 'Community MCP', type: 'plugin' },
+ { identifier: 'custom-mcp', title: 'Custom MCP', type: 'customPlugin' },
+ ],
+ },
+}));
+vi.mock('@/store/tool/slices/connector', () => ({
+ connectorSelectors: { userMcpConnectors: () => [] },
+}));
+
+const leafKeys = (items: ItemType[]): string[] =>
+ items.flatMap((item) => {
+ if (!item || item.type === 'divider') return [];
+ if ('children' in item) return leafKeys(item.children ?? []);
+ return [String(item.key)];
+ });
+
+const toolIds = ['builtin-tool', 'community-mcp', 'custom-mcp'];
+const libraryIds = [
+ 'excel-analysis',
+ 'custom-writing',
+ 'lobe-agent-browser',
+ 'lobe-artifacts',
+ 'lobehub',
+];
+
+describe('chat input tool picker', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.agentId = 'agent-1';
+ mocks.checked = [];
+ mocks.plugins = [];
+ mocks.mode = 'auto';
+ });
+
+ it('offers only tool management in the footer, without an add-tools action', () => {
+ const { result } = renderHook(() => useControls());
+
+ expect(result.current.marketFooter?.type).toBe('button');
+ expect(result.current.marketFooter?.props['aria-label']).toBe('tools.picker.management');
+ });
+
+ it('closes the menu before navigating to the composer agent tools profile', () => {
+ mocks.agentId = 'composer-agent';
+ const closeDropdown = vi.fn();
+ const { result } = renderHook(() => useControls({ closeDropdown }));
+
+ act(() => result.current.marketFooter?.props.onClick({ stopPropagation: vi.fn() }));
+
+ expect(mocks.navigate).toHaveBeenCalledWith('/agent/composer-agent/tools');
+ expect(closeDropdown).toHaveBeenCalledOnce();
+ expect(closeDropdown.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.navigate.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('does not navigate to an invalid profile while the agent is unresolved', () => {
+ mocks.agentId = '';
+ const closeDropdown = vi.fn();
+ const { result } = renderHook(() => useControls({ closeDropdown }));
+
+ expect(result.current.marketFooter?.props.disabled).toBe(true);
+ act(() => result.current.marketFooter?.props.onClick({ stopPropagation: vi.fn() }));
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ expect(closeDropdown).not.toHaveBeenCalled();
+ });
+
+ it.each(['pinned', 'auto', 'disabled'])(
+ 'excludes builtin and user skills in %s mode, including counts',
+ (mode) => {
+ mocks.plugins = libraryIds.map((identifier) => ({ identifier, mode }));
+ mocks.checked = mode === 'pinned' ? libraryIds : [];
+ const { result } = renderHook(() => useControls());
+
+ const keys = leafKeys(result.current.marketItems);
+ expect(keys).toEqual(expect.arrayContaining(toolIds));
+ for (const id of libraryIds) expect(keys).not.toContain(id);
+ expect(result.current.pinnedCount).toBe(0);
+ expect(result.current.autoCount).toBe(toolIds.length);
+ expect(mocks.togglePlugin).not.toHaveBeenCalled();
+ expect(mocks.setPluginMode).not.toHaveBeenCalled();
+ },
+ );
+
+ it('also excludes builtin and user skills from the installed picker in manual mode', () => {
+ mocks.mode = 'manual';
+ mocks.checked = [...toolIds, ...libraryIds];
+ mocks.plugins = mocks.checked.map((identifier) => ({ identifier, mode: 'pinned' }));
+ const { result } = renderHook(() => useControls());
+
+ expect(leafKeys(result.current.installedPluginItems)).toEqual(expect.arrayContaining(toolIds));
+ for (const id of libraryIds) {
+ expect(leafKeys(result.current.marketItems)).not.toContain(id);
+ expect(leafKeys(result.current.installedPluginItems)).not.toContain(id);
+ }
+ expect(result.current.pinnedCount).toBe(toolIds.length);
+ });
+
+ it.each(['Excel Analysis', 'lobe-agent-browser', 'lobe-artifacts', 'lobehub'])(
+ 'does not reveal skills through search for %s',
+ (value) => {
+ const { result } = renderHook(() => useControls());
+ act(() => result.current.marketHeader.props.onChange({ target: { value } }));
+ expect(leafKeys(result.current.marketItems)).toEqual([]);
+ },
+ );
+});
diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.tsx b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
index 822f2bcfe2e..32461042982 100644
--- a/src/features/ChatInput/ActionBar/Tools/useControls.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
@@ -27,7 +27,6 @@ import {
Package,
Pin,
Settings,
- Store,
Trash2,
Wrench,
Zap,
@@ -36,10 +35,9 @@ import type { ReactNode } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import MarketSkillIcon from '@/components/MarketSkillIcon';
+import { buildAgentProfileTabPath } from '@/features/AgentProfileTabs/tabOptions';
import { useConnectorConfigure } from '@/features/Connectors/CustomConnectorModal/useConnectorConfigure';
import { openPluginEditDrawer } from '@/features/PluginDevModal/imperative';
-import { createSkillStoreModal } from '@/features/SkillStore';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useFetchInstalledPlugins } from '@/hooks/useFetchInstalledPlugins';
import { usePermission } from '@/hooks/usePermission';
@@ -77,7 +75,6 @@ import { SKILL_ICON_SIZE } from './constants';
import { resolveDisabledIds, resolveImplicitMode } from './librarySkillPolicy';
import LobehubSkillIcon from './LobehubSkillIcon';
import LobehubSkillServerItem from './LobehubSkillServerItem';
-import MarketAgentSkillPopoverContent from './MarketAgentSkillPopoverContent';
import SkillRow from './SkillRow';
import ToolItem from './ToolItem';
import ToolItemDetailPopover from './ToolItemDetailPopover';
@@ -160,13 +157,11 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
const { allowed: canEdit } = usePermission('edit_own_content');
const list = useToolStore(pluginSelectors.installedPluginMetaList, isEqual);
const uninstallPluginRow = usePluginRowUninstall();
- const [removeComposioConnection, deleteAgentSkill, uninstallBuiltinTool, deleteConnector] =
- useToolStore((s) => [
- s.removeComposioConnection,
- s.deleteAgentSkill,
- s.uninstallBuiltinTool,
- s.deleteConnector,
- ]);
+ const [removeComposioConnection, uninstallBuiltinTool, deleteConnector] = useToolStore((s) => [
+ s.removeComposioConnection,
+ s.uninstallBuiltinTool,
+ s.deleteConnector,
+ ]);
const [checked, togglePlugin, setPluginMode] = useAgentStore((s) => [
// Pinned identifiers only (getAgentPluginsById already excludes disabled).
agentByIdSelectors.getAgentPluginsById(agentId)(s),
@@ -626,7 +621,8 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
return ids;
}, [installedBuiltinSkills, marketAgentSkills, userAgentSkills]);
- // Filter out connectors and skills from builtinList (they are displayed separately)
+ // The metadata inventory includes both tools and skill manifests. Exclude
+ // every skill here; connectors still have their own dedicated rows.
const filteredBuiltinList = useMemo(() => {
const list = builtinList.filter((item) => !connectorIdentifiers.has(item.identifier));
return list.filter((item) => !allSkillIdentifiers.has(item.identifier));
@@ -1048,117 +1044,6 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
[createManagedSkillItem, fixedDisplayList, t],
);
- // Builtin Agent Skills list items (grouped under LobeHub)
- const builtinAgentSkillItems = useMemo(
- () =>
- 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} />
- );
- 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,
- })}
- icon={
- skill.avatar ? (
- <Avatar
- avatar={skill.avatar}
- shape={'square'}
- size={36}
- style={{ flex: 'none', marginInlineEnd: 0 }}
- />
- ) : (
- <Icon icon={SkillsIcon} size={36} />
- )
- }
- />
- );
-
- 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) => {
- const icon = (
- <MarketSkillIcon identifier={skill.identifier} name={skill.name} size={SKILL_ICON_SIZE} />
- );
- const popoverContent = (
- <MarketAgentSkillPopoverContent
- description={skill.description}
- identifier={skill.identifier}
- name={skill.name}
- sourceLabel={t('skillStore.tabs.community')}
- />
- );
-
- 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) => {
- const icon = <Icon icon={SkillsIcon} size={SKILL_ICON_SIZE} />;
- const popoverContent = (
- <ToolItemDetailPopover
- description={skill.description}
- icon={<Icon icon={SkillsIcon} size={36} />}
- identifier={skill.identifier}
- sourceLabel={t('skillStore.tabs.custom')}
- title={skill.name}
- />
- );
-
- 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],
- );
-
// Connector MCP list items (custom ones and marketplace installs).
// Toggling adds the connector identifier to agents.plugins[] — the same field
// the runtime resolves connectors from, so they become callable immediately.
@@ -1305,25 +1190,14 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
});
};
- // Build LobeHub group children (including Builtin Agent Skills, builtin tools, and LobeHub Skill/Composio)
- const lobehubGroupChildren: ItemType[] = [
- // 1. Builtin Agent Skills
- ...builtinAgentSkillItems,
- // 2. Builtin tools
- ...builtinItems,
- // 3. LobeHub Skill and Composio (as builtin skills)
- ...skillItems,
- ];
+ // Only builtin tools and service integrations belong in this activation picker.
+ const lobehubGroupChildren: ItemType[] = [...builtinItems, ...skillItems];
- // Build Community group children (Market Agent Skills + community plugins)
- const communityGroupChildren: ItemType[] = [
- ...marketAgentSkillItems,
- ...communityPlugins.map(mapPluginToItem),
- ];
+ // User-installed skills are selected in the Skills panel, not enabled here.
+ const communityGroupChildren: ItemType[] = communityPlugins.map(mapPluginToItem);
- // Build Custom group children (User Agent Skills + custom plugins + custom connectors)
+ // Custom MCP plugins and connectors remain configurable from this picker.
const customGroupChildren: ItemType[] = [
- ...userAgentSkillItems,
...customPlugins.map(mapPluginToItem),
...customConnectorItems,
];
@@ -1365,22 +1239,10 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
const capabilityDisabledItems = capabilityItems.filter(
(item) => !checkedSet.has(String(item.key)) && disabledCapabilityIds.has(String(item.key)),
);
- // LobeHub's own Agent Skills (Artifacts, …) — the rows the capability rows follow.
- const builtinAgentSkillIds = useMemo(
- () => new Set(installedBuiltinSkills.map((skill) => skill.identifier)),
- [installedBuiltinSkills],
- );
const activeSkillItems = allSkillItems.filter(
(item) => !checkedSet.has(String(item.key)) && !disabledIdSet.has(String(item.key)),
);
- const isAgentSkillItem = (item: SkillMenuItem) => builtinAgentSkillIds.has(String(item.key));
- // Capability rows sit after LobeHub's Agent Skills and before the remaining
- // integrations, so the group still opens with the skills the user installed.
- const allAutoItems = [
- ...activeSkillItems.filter((item) => isAgentSkillItem(item)),
- ...capabilityAutoItems,
- ...activeSkillItems.filter((item) => !isAgentSkillItem(item)),
- ];
+ const allAutoItems = [...capabilityAutoItems, ...activeSkillItems];
const allDisabledItems = [
...capabilityDisabledItems,
...allSkillItems.filter((item) => disabledIdSet.has(String(item.key))),
@@ -1470,7 +1332,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
<SearchBar
allowClear
className="lobe-skill-submenu-search"
- placeholder={t('tools.search')}
+ placeholder={t('tools.picker.search')}
size="small"
style={{ width: '100%' }}
value={searchKeyword}
@@ -1483,34 +1345,21 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
const marketFooter =
allSkillItems.length > 0 || fixedItems.length > 0 ? (
- <>
- <button
- aria-label={t('plus.addSkills', { ns: 'chat' })}
- {...stylex.props(styles.addSkillRow)}
- type="button"
- onClick={(event) => {
- event.stopPropagation();
- closeDropdown?.();
- createSkillStoreModal();
- }}
- >
- <Icon icon={Store} size={SKILL_ICON_SIZE} />
- <span {...stylex.props(styles.addSkillLabel)}>{t('plus.addSkills', { ns: 'chat' })}</span>
- </button>
- <button
- aria-label={t('tools.plugins.management')}
- {...stylex.props(styles.addSkillRow)}
- type="button"
- onClick={(event) => {
- event.stopPropagation();
- closeDropdown?.();
- navigate('/settings/connector');
- }}
- >
- <Icon icon={Settings} size={SKILL_ICON_SIZE} />
- <span {...stylex.props(styles.addSkillLabel)}>{t('tools.plugins.management')}</span>
- </button>
- </>
+ <button
+ aria-label={t('tools.picker.management')}
+ {...stylex.props(styles.addSkillRow)}
+ disabled={!agentId}
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ if (!agentId) return;
+ closeDropdown?.();
+ navigate(buildAgentProfileTabPath(agentId, 'tools'));
+ }}
+ >
+ <Icon icon={Settings} size={SKILL_ICON_SIZE} />
+ <span {...stylex.props(styles.addSkillLabel)}>{t('tools.picker.management')}</span>
+ </button>
) : undefined;
const marketItems: ItemType[] = [
@@ -1646,65 +1495,12 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
// Merge enabled LobeHub Skill and Composio (as builtin skills)
const enabledSkillItems = [...connectedLobehubSkillItems, ...connectedComposioItems];
- // Enabled Builtin Agent Skills
- const enabledBuiltinAgentSkillItems = installedBuiltinSkills
- .filter((skill) => checked.includes(skill.identifier))
- .map((skill) => ({
- 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={true}
- disabled={!canEdit}
- id={skill.identifier}
- label={skill.name}
- onUpdate={async () => {
- if (!canEdit) return;
- await togglePlugin(skill.identifier);
- }}
- />
- ),
- popoverContent: (
- <ToolItemDetailPopover
- identifier={skill.identifier}
- sourceLabel={t('skillStore.tabs.lobehub')}
- description={t(`tools.builtins.${skill.identifier}.description` as any, {
- defaultValue: skill.description,
- })}
- icon={
- skill.avatar ? (
- <Avatar
- avatar={skill.avatar}
- shape={'square'}
- size={36}
- style={{ flex: 'none', marginInlineEnd: 0 }}
- />
- ) : (
- <Icon icon={SkillsIcon} size={36} />
- )
- }
- title={t(`tools.builtins.${skill.identifier}.title` as any, {
- defaultValue: skill.name,
- })}
- />
- ),
- }));
-
- // Build builtin tools group children (including Builtin Agent Skills, builtin tools, and LobeHub Skill/Composio)
+ // Installed builtin tools and service integrations, without Skill instruction bundles.
const allBuiltinItems: ItemType[] = [
- // 1. Builtin Agent Skills
- ...enabledBuiltinAgentSkillItems,
- // 2. Builtin tools
...enabledBuiltinItems,
- // 3. divider (if there are builtin tools and skill items)
...(enabledBuiltinItems.length > 0 && enabledSkillItems.length > 0
? [{ key: 'installed-divider-builtin-skill', type: 'divider' as const }]
: []),
- // 4. LobeHub Skill and Composio
...enabledSkillItems,
];
@@ -1811,38 +1607,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
};
});
- // Enabled Market Agent Skills
- const enabledMarketAgentSkillItems = marketAgentSkills
- .filter((skill) => checked.includes(skill.identifier))
- .map((skill) => ({
- icon: (
- <MarketSkillIcon identifier={skill.identifier} name={skill.name} size={SKILL_ICON_SIZE} />
- ),
- key: skill.identifier,
- label: (
- <ToolItem
- checked={true}
- disabled={!canEdit}
- id={skill.identifier}
- label={skill.name}
- onUpdate={async () => {
- if (!canEdit) return;
- await togglePlugin(skill.identifier);
- }}
- />
- ),
- popoverContent: (
- <MarketAgentSkillPopoverContent
- description={skill.description}
- identifier={skill.identifier}
- name={skill.name}
- sourceLabel={t('skillStore.tabs.community')}
- />
- ),
- }));
-
- // Community group (Market Agent Skills + community plugins)
- const allCommunityItems = [...enabledMarketAgentSkillItems, ...enabledCommunityPlugins];
+ const allCommunityItems = enabledCommunityPlugins;
if (allCommunityItems.length > 0) {
installedItems.push({
children: allCommunityItems,
@@ -1852,37 +1617,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
});
}
- // Enabled User Agent Skills
- const enabledUserAgentSkillItems = userAgentSkills
- .filter((skill) => checked.includes(skill.identifier))
- .map((skill) => ({
- icon: <Icon icon={SkillsIcon} size={SKILL_ICON_SIZE} />,
- key: skill.identifier,
- label: (
- <ToolItem
- checked={true}
- disabled={!canEdit}
- id={skill.identifier}
- label={skill.name}
- onUpdate={async () => {
- if (!canEdit) return;
- await togglePlugin(skill.identifier);
- }}
- />
- ),
- popoverContent: (
- <ToolItemDetailPopover
- description={skill.description}
- icon={<Icon icon={SkillsIcon} size={36} />}
- identifier={skill.identifier}
- sourceLabel={t('skillStore.tabs.custom')}
- title={skill.name}
- />
- ),
- }));
-
- // Custom group (User Agent Skills + custom plugins)
- const allCustomItems = [...enabledUserAgentSkillItems, ...enabledCustomPlugins];
+ const allCustomItems = enabledCustomPlugins;
if (allCustomItems.length > 0) {
installedItems.push({
children: allCustomItems,
@@ -1895,9 +1630,6 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
return installedItems;
}, [
filteredBuiltinList,
- installedBuiltinSkills,
- marketAgentSkills,
- userAgentSkills,
communityPlugins,
customPlugins,
composioServerItems,
diff --git a/src/features/ChatInput/ActionBar/components/ActionDropdown.tsx b/src/features/ChatInput/ActionBar/components/ActionDropdown.tsx
index ab20b99f0ad..6767dd1ed12 100644
--- a/src/features/ChatInput/ActionBar/components/ActionDropdown.tsx
+++ b/src/features/ChatInput/ActionBar/components/ActionDropdown.tsx
@@ -375,7 +375,7 @@ const ActionDropdown = memo<ActionDropdownProps>(
minHeight,
minWidth: isMobile ? undefined : minWidth,
overflowX: 'hidden',
- overflowY: 'scroll',
+ overflowY: 'auto',
width: isMobile ? '100vw' : undefined,
};
const popupStyle = popupProps?.style;
diff --git a/src/features/ChatInput/InputEditor/ActionTag/command.test.ts b/src/features/ChatInput/InputEditor/ActionTag/command.test.ts
new file mode 100644
index 00000000000..ac0ca463268
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ActionTag/command.test.ts
@@ -0,0 +1,116 @@
+import {
+ $createParagraphNode,
+ $createTextNode,
+ $getRoot,
+ $nodesOfType,
+ createEditor,
+} from 'lexical';
+import { describe, expect, it } from 'vitest';
+
+import { $createActionTagNode, ActionTagNode } from './ActionTagNode';
+import { INSERT_ACTION_TAG_COMMAND, registerActionTagCommand } from './command';
+
+const skill = {
+ category: 'skill' as const,
+ label: 'Writing',
+ skipIfExists: true,
+ type: 'writing',
+};
+
+const createTestEditor = () => {
+ const editor = createEditor({
+ nodes: [ActionTagNode],
+ onError: (error) => {
+ throw error;
+ },
+ });
+ registerActionTagCommand(editor);
+ editor.update(
+ () => {
+ const paragraph = $createParagraphNode().append($createTextNode('Draft text'));
+ $getRoot().append(paragraph);
+ paragraph.selectEnd();
+ },
+ { discrete: true },
+ );
+ return editor;
+};
+
+const readTags = (editor: ReturnType<typeof createEditor>) =>
+ editor.read(() =>
+ $nodesOfType(ActionTagNode).map((node) => ({
+ category: node.actionCategory,
+ label: node.actionLabel,
+ type: node.actionType,
+ })),
+ );
+
+describe('skill insertion deduplication', () => {
+ it('inserts only once on rapid repeated clicks and keeps the draft text', () => {
+ const editor = createTestEditor();
+ editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, skill);
+ editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, skill);
+
+ expect(readTags(editor)).toEqual([{ category: 'skill', label: 'Writing', type: 'writing' }]);
+ expect(editor.read(() => $getRoot().getTextContent())).toContain('Draft text');
+ });
+
+ it('recognizes an existing tag in another paragraph regardless of its label', () => {
+ const editor = createTestEditor();
+ editor.update(
+ () => {
+ $getRoot().append(
+ $createParagraphNode().append($createActionTagNode('writing', 'skill', 'Old title')),
+ );
+ },
+ { discrete: true },
+ );
+
+ editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, skill);
+
+ expect(readTags(editor)).toEqual([{ category: 'skill', label: 'Old title', type: 'writing' }]);
+ });
+
+ it('allows reinsertion after removing the tag', () => {
+ const editor = createTestEditor();
+ editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, skill);
+ editor.update(
+ () => {
+ for (const node of $nodesOfType(ActionTagNode)) node.remove();
+ $getRoot().selectEnd();
+ },
+ { discrete: true },
+ );
+ expect(readTags(editor)).toHaveLength(0);
+
+ editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, skill);
+ expect(readTags(editor)).toHaveLength(1);
+ });
+
+ it('keeps different identifiers and skill categories independent', () => {
+ const editor = createTestEditor();
+ editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, skill);
+ editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, { ...skill, type: 'another-skill' });
+ editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, { ...skill, category: 'projectSkill' });
+ editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, { ...skill, category: 'agentSkill' });
+
+ expect(readTags(editor)).toHaveLength(4);
+ });
+
+ it.each(['projectSkill', 'agentSkill'] as const)('deduplicates %s tags too', (category) => {
+ const editor = createTestEditor();
+ editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, { ...skill, category });
+ editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, { ...skill, category });
+
+ expect(readTags(editor)).toHaveLength(1);
+ });
+
+ it('does not change callers that allow repeated tags', () => {
+ const editor = createTestEditor();
+ const payload = { category: skill.category, label: skill.label, type: skill.type };
+ editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, payload);
+ editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, payload);
+
+ expect(readTags(editor)).toHaveLength(2);
+ });
+});
diff --git a/src/features/ChatInput/InputEditor/ActionTag/command.ts b/src/features/ChatInput/InputEditor/ActionTag/command.ts
index b5b7943b474..b3e0a97a7ce 100644
--- a/src/features/ChatInput/InputEditor/ActionTag/command.ts
+++ b/src/features/ChatInput/InputEditor/ActionTag/command.ts
@@ -3,18 +3,21 @@ import {
$createParagraphNode,
$insertNodes,
$isRootOrShadowRoot,
+ $nodesOfType,
COMMAND_PRIORITY_HIGH,
createCommand,
type LexicalCommand,
type LexicalEditor,
} from 'lexical';
-import { $createActionTagNode } from './ActionTagNode';
+import { $createActionTagNode, ActionTagNode } from './ActionTagNode';
import type { ActionTagCategory, ActionTagType } from './types';
export interface InsertActionTagPayload {
category: ActionTagCategory;
label: string;
+ /** Keep at most one tag with this category and identifier in the current draft. */
+ skipIfExists?: boolean;
type: ActionTagType;
}
@@ -27,6 +30,17 @@ export function registerActionTagCommand(editor: LexicalEditor): () => void {
INSERT_ACTION_TAG_COMMAND,
(payload) => {
editor.update(() => {
+ // Check the live update, not a cached snapshot, so rapid clicks are atomic
+ // and removing a chip immediately allows it to be inserted again.
+ if (
+ payload.skipIfExists &&
+ $nodesOfType(ActionTagNode).some(
+ (node) => node.actionCategory === payload.category && node.actionType === payload.type,
+ )
+ ) {
+ return;
+ }
+
const node = $createActionTagNode(payload.type, payload.category, payload.label);
$insertNodes([node]);
if ($isRootOrShadowRoot(node.getParentOrThrow())) {
diff --git a/src/features/ChatInput/InputEditor/ActionTag/skillDragData.ts b/src/features/ChatInput/InputEditor/ActionTag/skillDragData.ts
index c3029b3f72c..d6208eca73f 100644
--- a/src/features/ChatInput/InputEditor/ActionTag/skillDragData.ts
+++ b/src/features/ChatInput/InputEditor/ActionTag/skillDragData.ts
@@ -99,14 +99,8 @@ const setSkillDragImage = (event: React.DragEvent, label: string): void => {
zIndex: '9999',
});
- // Row layout is: [chevron svg] [skill icon svg] [name] [count] [row actions].
- // The hover action buttons (view / rename / delete) stay in the DOM even when
- // hidden, so exclude them before taking the last svg — otherwise we'd grab the
- // trailing Trash2 action icon instead of the skill icon.
- const svgs = Array.from(host.querySelectorAll('svg')).filter(
- (svg) => !svg.closest('.skill-row-actions'),
- );
- const iconSvg = svgs.at(-1);
+ // The only row glyphs are the optional tree chevron and the shared skill icon.
+ const iconSvg = Array.from(host.querySelectorAll('svg')).at(-1);
if (iconSvg) {
const iconClone = iconSvg.cloneNode(true) as SVGElement;
iconClone.style.flexShrink = '0';
diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
index 67ac0b3f30d..e5f5cc8fdc3 100644
--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
@@ -4,8 +4,8 @@ import {
AGENT_DOCUMENT_SKILL_CATEGORY,
AGENT_SIGNAL_SOURCE_TYPE,
} from '@lobechat/const';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import type { ReactNode } from 'react';
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import type { ComponentProps } from 'react';
import type * as ReactRouterDom from 'react-router';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -25,9 +25,15 @@ const messageError = vi.hoisted(() => vi.fn());
const messageSuccess = vi.hoisted(() => vi.fn());
const navigateMock = vi.hoisted(() => vi.fn());
const openDocumentMock = vi.hoisted(() => vi.fn());
+const editorMock = vi.hoisted(() => ({ dispatchCommand: vi.fn(), focus: vi.fn() }));
const removeDocumentMock = vi.hoisted(() => vi.fn());
const useParamsMock = vi.hoisted(() => vi.fn());
const documentExplorerShouldThrow = vi.hoisted(() => ({ current: false }));
+const userSkillInventory = vi.hoisted(() => ({
+ canManage: true,
+ enabledIds: [] as string[],
+ items: [] as { id: string; name: string }[],
+}));
vi.mock('@lobehub/ui', async (importOriginal) => ({
...(await importOriginal<object>()),
@@ -66,6 +72,7 @@ vi.mock('react-i18next', () => ({
'workingPanel.resources.filter.web': 'Web',
'workingPanel.resources.updatedAt': `Updated ${options?.time}`,
'workingPanel.skills.empty': 'No skills found',
+ 'workingPanel.skills.manage.title': 'Manage user skills',
'workingPanel.skills.section.agent': 'Agent skills',
'workingPanel.skills.section.device': 'Device skills',
'workingPanel.skills.section.project': 'Project skills',
@@ -109,68 +116,47 @@ vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
vi.mock('@/features/SkillsList', async () => {
const { filterSkillItems } = await import('@/features/SkillsList/filterSkillItems');
const { default: SkillsSearchBar } = await import('@/features/SkillsList/SkillsSearchBar');
- type Item = { fileCount?: number; id: string; name: string };
- const SkillsList = ({
- items,
- onOpenFile,
- onOpenSkill,
- }: {
- items: Item[];
- onOpenFile?: (item: Item, relativePath: string) => void;
- onOpenSkill?: (item: Item) => void;
- }) => (
+ const { default: ActualSkillsList } = await import('@/features/SkillsList/SkillsList');
+ const SkillsList = (props: ComponentProps<typeof ActualSkillsList>) => (
<div data-testid="skills-list">
- {items.map((item) => (
- <div data-skill-id={item.id} key={item.id}>
- <button onClick={() => onOpenSkill?.(item)}>{item.name}</button>
- <span data-testid={`skill-${item.id}-count`}>{item.fileCount}</span>
- <button
- data-testid={`skill-${item.id}-open-skill-md`}
- onClick={() => onOpenFile?.(item, 'SKILL.md')}
- >
- open-skill-md
- </button>
- </div>
- ))}
+ <ActualSkillsList {...props} />
</div>
);
- // SkillSection is a thin presentational wrapper — the real one swaps the
- // children for an empty placeholder when `isEmpty` is true. We mirror that
- // here so co-located assertions (e.g. "skills-list does not render when no
- // bundles are present") line up with production behavior.
- const SkillSection = ({
- children,
- emptyText,
- isEmpty,
- sectionHeader,
- }: {
- children?: ReactNode;
- emptyText?: string;
- isEmpty?: boolean;
- sectionHeader?: { count?: number; title: string };
- }) => (
- <div data-testid={sectionHeader ? `skill-section-${sectionHeader.title}` : 'skill-section'}>
- {sectionHeader && (
- <div data-testid="skill-section-header">
- <span>{sectionHeader.title}</span>
- {typeof sectionHeader.count === 'number' && <span>{sectionHeader.count}</span>}
- </div>
- )}
- {isEmpty ? <div data-testid="skill-section-empty">{emptyText}</div> : children}
+ const { default: ActualSkillSection } = await import('@/features/SkillsList/SkillSection');
+ const SkillSection = (props: ComponentProps<typeof ActualSkillSection>) => (
+ <div
+ data-testid={
+ props.sectionHeader ? `skill-section-${props.sectionHeader.title}` : 'skill-section'
+ }
+ >
+ <ActualSkillSection {...props} />
</div>
);
const useProjectSkills = (...args: unknown[]) => useProjectSkillsMock(...args);
return { filterSkillItems, SkillSection, SkillsList, SkillsSearchBar, useProjectSkills };
});
-// UserLevelSkills owns its own store wiring and is exercised separately. We
-// stub it (component + the lifted hook) so AgentDocumentsGroup's render logic
-// can be tested without dragging the tool store into the working-sidebar
-// tests. Default to an empty user-skill list so the empty-state branch is
-// reachable; individual tests can re-mock before render to override.
-vi.mock('./UserLevelSkills', () => ({
- default: () => null,
- useUserSkills: () => [],
+vi.mock('./useCanManageUserSkills', () => ({
+ useCanManageUserSkills: () => userSkillInventory.canManage,
+}));
+// Keep the real user-skill section and accordion so header interactions are covered.
+vi.mock('@/store/tool', () => ({
+ useToolStore: (selector: (state: object) => unknown) =>
+ selector({ useFetchAgentSkills: () => undefined }),
+}));
+vi.mock('@/store/tool/selectors', () => ({
+ agentSkillsSelectors: {
+ getAgentSkills: () =>
+ userSkillInventory.items.map((item) => ({
+ identifier: item.id,
+ name: item.name,
+ })),
+ },
+}));
+vi.mock('./UserSkillsManagement', () => ({
+ UserSkillsManagement: ({ onClose }: { onClose: () => void }) => (
+ <button onClick={onClose}>Cancel skill changes</button>
+ ),
}));
vi.mock('@/features/ChatInput/InputEditor/ActionTag/skillDragData', () => ({
startSkillDrag: () => undefined,
@@ -185,12 +171,19 @@ vi.mock('@/services/agentDocument', () => ({
vi.mock('@/store/agent', () => ({
useAgentStore: (selector: (state: { activeAgentId: string; agentMap: object }) => unknown) =>
- selector({ activeAgentId: 'agent-1', agentMap: {} }),
+ selector({
+ activeAgentId: 'agent-1',
+ agentMap: { 'agent-1': { plugins: userSkillInventory.enabledIds } },
+ }),
}));
vi.mock('@/store/chat', () => ({
- useChatStore: (selector: (state: { openDocument: typeof openDocumentMock }) => unknown) =>
- selector({ openDocument: openDocumentMock }),
+ useChatStore: (
+ selector: (state: {
+ mainInputEditor: { instance: typeof editorMock };
+ openDocument: typeof openDocumentMock;
+ }) => unknown,
+ ) => selector({ mainInputEditor: { instance: editorMock }, openDocument: openDocumentMock }),
}));
vi.mock('react-router', async () => {
@@ -308,11 +301,9 @@ describe('AgentDocumentsGroup', () => {
useProjectSkillsMock.mockReturnValue({
deviceItems: [],
error: undefined,
- getRowActions: () => [],
isLoading: false,
items: [],
mutate: vi.fn(),
- onOpenFile: () => undefined,
onOpenSkill: () => undefined,
projectItems: [],
raw: undefined,
@@ -322,10 +313,56 @@ describe('AgentDocumentsGroup', () => {
messageSuccess.mockReset();
navigateMock.mockReset();
openDocumentMock.mockReset();
+ editorMock.dispatchCommand.mockReset();
+ editorMock.focus.mockReset();
removeDocumentMock.mockReset();
removeDocumentMock.mockResolvedValue({ deleted: true, id: 'doc-1' });
useParamsMock.mockReturnValue({});
documentExplorerShouldThrow.current = false;
+ userSkillInventory.items = [];
+ userSkillInventory.enabledIds = [];
+ userSkillInventory.canManage = true;
+ });
+
+ it('keeps management reachable with every user skill disabled and returns after cancelling', () => {
+ documentListMock.mockReturnValue({ data: [] });
+ userSkillInventory.items = [{ id: 'disabled-skill', name: 'Disabled skill' }];
+ render(<AgentDocumentsGroup />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Manage user skills' }));
+ expect(
+ screen.queryByPlaceholderText('workingPanel.skills.searchPlaceholder'),
+ ).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel skill changes' }));
+ expect(screen.getByRole('button', { name: 'Manage user skills' })).toBeInTheDocument();
+ });
+
+ it('keeps the user skills collapsible with an independently clickable settings action', () => {
+ documentListMock.mockReturnValue({ data: [] });
+ userSkillInventory.items = [{ id: 'writing', name: 'Writing skill' }];
+ userSkillInventory.enabledIds = ['writing'];
+ render(<AgentDocumentsGroup />);
+
+ const header = screen.getByRole('button', { name: /User skills/ });
+ const settings = screen.getByRole('button', { name: 'Manage user skills' });
+ expect(header).toHaveAttribute('aria-expanded', 'true');
+ expect(header.contains(settings)).toBe(false);
+ fireEvent.click(header);
+ expect(header).toHaveAttribute('aria-expanded', 'false');
+ expect(settings).toBeVisible();
+ fireEvent.click(header);
+ expect(header).toHaveAttribute('aria-expanded', 'true');
+ fireEvent.click(header);
+ fireEvent.click(settings);
+ expect(screen.getByRole('button', { name: 'Cancel skill changes' })).toBeInTheDocument();
+ });
+
+ it('does not offer management to a read-only viewer', () => {
+ documentListMock.mockReturnValue({ data: [] });
+ userSkillInventory.items = [{ id: 'disabled-skill', name: 'Disabled skill' }];
+ userSkillInventory.canManage = false;
+ render(<AgentDocumentsGroup />);
+ expect(screen.queryByRole('button', { name: 'Manage user skills' })).not.toBeInTheDocument();
});
it('defaults to the Skills tab and renders skill bundles via SkillsList', () => {
@@ -336,8 +373,7 @@ describe('AgentDocumentsGroup', () => {
const list = screen.getByTestId('skills-list');
expect(list).toBeInTheDocument();
expect(screen.getByText('YouTube Comment Retrieval Workflow')).toBeInTheDocument();
- // bundle's file children count (the SKILL.md row collapsed inside the expand panel)
- expect(screen.getByTestId('skill-skill-bundle-doc-count')).toHaveTextContent('1');
+ expect(within(list).queryByText('1')).not.toBeInTheDocument();
// file / web docs should not leak into the skills tab
expect(screen.queryByText('Brief')).not.toBeInTheDocument();
expect(screen.queryByText('Example')).not.toBeInTheDocument();
@@ -345,13 +381,11 @@ describe('AgentDocumentsGroup', () => {
it('renders project and device filesystem skills as separate sections', () => {
const projectItem = {
- fileCount: 1,
id: 'project-skill',
name: 'project-writer',
scope: 'project' as const,
};
const deviceItem = {
- fileCount: 1,
id: 'device-skill',
name: 'device-writer',
scope: 'device' as const,
@@ -359,11 +393,9 @@ describe('AgentDocumentsGroup', () => {
useProjectSkillsMock.mockReturnValue({
deviceItems: [deviceItem],
error: undefined,
- getRowActions: () => [],
isLoading: false,
items: [projectItem, deviceItem],
mutate: vi.fn(),
- onOpenFile: () => undefined,
onOpenSkill: () => undefined,
projectItems: [projectItem],
raw: undefined,
@@ -381,7 +413,6 @@ describe('AgentDocumentsGroup', () => {
it('keeps the filesystem skill scan inert while the pane is disabled', () => {
const projectItem = {
description: 'writes things',
- fileCount: 2,
files: [],
id: 'project-skill',
name: 'project-writer',
@@ -390,11 +421,9 @@ describe('AgentDocumentsGroup', () => {
useProjectSkillsMock.mockReturnValue({
deviceItems: [],
error: undefined,
- getRowActions: () => [],
isLoading: false,
items: [projectItem],
mutate: vi.fn(),
- onOpenFile: () => undefined,
onOpenSkill: () => undefined,
projectItems: [projectItem],
raw: undefined,
@@ -414,17 +443,43 @@ describe('AgentDocumentsGroup', () => {
expect(screen.queryByText('project-writer')).not.toBeInTheDocument();
});
- it('opens the SKILL.md document in the portal when clicking a skill bundle row', () => {
+ it('inserts a skill tag into the composer when clicking a skill bundle row', () => {
documentListMock.mockReturnValue(skillDocumentListState());
render(<AgentDocumentsGroup />);
fireEvent.click(screen.getByText('YouTube Comment Retrieval Workflow'));
- expect(openDocumentMock).toHaveBeenCalledWith('skill-index-doc', 'skill-index-row');
+ expect(editorMock.focus).toHaveBeenCalledOnce();
+ expect(editorMock.dispatchCommand).toHaveBeenCalledWith(expect.anything(), {
+ category: 'agentSkill',
+ label: 'YouTube Comment Retrieval Workflow',
+ skipIfExists: true,
+ type: 'agent-skills:youtube-comment-retrieval-workflow',
+ });
+ expect(openDocumentMock).not.toHaveBeenCalled();
expect(navigateMock).not.toHaveBeenCalled();
});
- it('falls back to the bundle id when opening an orphan skill bundle', () => {
+ it('shows no management actions or file counts on hover or right-click', () => {
+ documentListMock.mockReturnValue(skillDocumentListState());
+
+ render(<AgentDocumentsGroup />);
+
+ const list = screen.getByTestId('skills-list');
+ const row = within(list).getByRole('button', { name: 'YouTube Comment Retrieval Workflow' });
+ fireEvent.mouseEnter(row);
+ fireEvent.contextMenu(row);
+
+ expect(within(list).getAllByRole('button')).toHaveLength(1);
+ expect(within(list).queryByText('1')).not.toBeInTheDocument();
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument();
+ expect(editorMock.dispatchCommand).not.toHaveBeenCalled();
+ expect(openDocumentMock).not.toHaveBeenCalled();
+ expect(modalConfirm).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the bundle id when opening an orphan skill bundle in document mode', () => {
+ useParamsMock.mockReturnValue({ docId: 'doc-content-1' });
documentListMock.mockReturnValue({
data: [skillBundleRow], // no SKILL.md child
error: undefined,
@@ -432,21 +487,23 @@ describe('AgentDocumentsGroup', () => {
mutate: vi.fn(),
});
- render(<AgentDocumentsGroup />);
+ render(<AgentDocumentsGroup activeFilter="skills" />);
fireEvent.click(screen.getByText('YouTube Comment Retrieval Workflow'));
- expect(openDocumentMock).toHaveBeenCalledWith('skill-bundle-doc', 'skill-bundle-row');
- expect(navigateMock).not.toHaveBeenCalled();
+ expect(navigateMock).toHaveBeenCalledWith('/agent/agent-1/docs/skill-bundle-doc');
+ expect(editorMock.dispatchCommand).not.toHaveBeenCalled();
});
- it('opens a child file by relative path through onOpenFile', () => {
+ it('selects a skill with the keyboard without exposing its file tree', () => {
documentListMock.mockReturnValue(skillDocumentListState());
render(<AgentDocumentsGroup />);
- fireEvent.click(screen.getByTestId('skill-skill-bundle-doc-open-skill-md'));
- expect(openDocumentMock).toHaveBeenCalledWith('skill-index-doc', 'skill-index-row');
- expect(navigateMock).not.toHaveBeenCalled();
+ const row = screen.getByRole('button', { name: 'YouTube Comment Retrieval Workflow' });
+ fireEvent.keyDown(row, { key: 'Enter' });
+ expect(editorMock.dispatchCommand).toHaveBeenCalledOnce();
+ expect(screen.queryByText('SKILL.md')).not.toBeInTheDocument();
+ expect(openDocumentMock).not.toHaveBeenCalled();
});
it('routes directly when opening a skill from document mode', () => {
@@ -457,6 +514,7 @@ describe('AgentDocumentsGroup', () => {
fireEvent.click(screen.getByText('YouTube Comment Retrieval Workflow'));
expect(navigateMock).toHaveBeenCalledWith('/agent/agent-1/docs/skill-index-doc');
+ expect(editorMock.dispatchCommand).not.toHaveBeenCalled();
expect(openDocumentMock).not.toHaveBeenCalled();
});
@@ -644,6 +702,36 @@ describe('AgentDocumentsGroup', () => {
);
});
+ it.each([
+ { canManage: false, documentMode: false },
+ { canManage: false, documentMode: true },
+ { canManage: true, documentMode: true },
+ { canManage: true, documentMode: false },
+ ])('reports no matching user skills exactly once: %j', async ({ canManage, documentMode }) => {
+ documentListMock.mockReturnValue({ data: [] });
+ userSkillInventory.items = [{ id: 'writing', name: 'Writing skill' }];
+ userSkillInventory.enabledIds = ['writing'];
+ userSkillInventory.canManage = canManage;
+ useParamsMock.mockReturnValue(documentMode ? { docId: 'document' } : {});
+ render(<AgentDocumentsGroup activeFilter="skills" />);
+
+ expect(screen.getByText('Writing skill')).toBeInTheDocument();
+ search('no-such-skill');
+ await waitFor(() =>
+ expect(screen.getAllByText('workingPanel.skills.noSearchResults')).toHaveLength(1),
+ );
+ expect(screen.queryByText('Writing skill')).not.toBeInTheDocument();
+ if (!canManage || documentMode) {
+ expect(
+ screen.queryByRole('button', { name: 'Manage user skills' }),
+ ).not.toBeInTheDocument();
+ }
+
+ search('');
+ await waitFor(() => expect(screen.getByText('Writing skill')).toBeInTheDocument());
+ expect(screen.queryByText('workingPanel.skills.noSearchResults')).not.toBeInTheDocument();
+ });
+
it('does not keep filtering after the search bar unmounts with the Skills tab', async () => {
render(<AgentDocumentsGroup />);
diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
index 8c88e93a47a..9cd97c7ee34 100644
--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
@@ -11,7 +11,7 @@ import * as stylex from '@stylexjs/stylex';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import type { LucideIcon } from 'lucide-react';
-import { EyeIcon, FileTextIcon, GlobeIcon, PencilIcon, Trash2Icon } from 'lucide-react';
+import { FileTextIcon, GlobeIcon, Trash2Icon } from 'lucide-react';
import type { CSSProperties, DragEvent, MouseEvent } from 'react';
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -28,9 +28,7 @@ import { startSkillDrag } from '@/features/ChatInput/InputEditor/ActionTag/skill
import { startDocumentDrag } from '@/features/ChatInput/InputEditor/ReferDocument/documentDragData';
import {
filterSkillItems,
- openRenameSkillModal,
type SkillListItem,
- type SkillRowAction,
SkillSection,
SkillsList,
SkillsSearchBar,
@@ -50,7 +48,10 @@ import { standardizeIdentifier } from '@/utils/identifier';
import DeviceLevelSkills from './DeviceLevelSkills';
import ProjectLevelSkills from './ProjectLevelSkills';
+import { useCanManageUserSkills } from './useCanManageUserSkills';
import UserLevelSkills, { useUserSkills } from './UserLevelSkills';
+import { UserSkillsManagement } from './UserSkillsManagement';
+import { useSelectSkill } from './useSelectSkill';
dayjs.extend(relativeTime);
@@ -288,13 +289,14 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
workingDirectory,
}) => {
const { t } = useTranslation('chat');
- const { t: tCommon } = useTranslation('common');
const agentId = useAgentStore((s) => s.activeAgentId);
+ const canManageUserSkills = useCanManageUserSkills(agentId || '');
const { docId } = useParams<{ docId?: string }>();
const navigate = useWorkspaceAwareNavigate();
const openDocument = useChatStore((s) => s.openDocument);
const isDocumentMode = !!docId;
+ const canManageSkills = !isDocumentMode && canManageUserSkills;
const resolvedOpenMode = openMode ?? (isDocumentMode ? 'route' : 'portal');
const isLocalEnabled = useAgentStore((s) =>
agentId ? chatConfigByIdSelectors.isLocalSystemEnabledById(agentId)(s) : false,
@@ -303,6 +305,7 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
isDocumentMode ? 'documents' : 'skills',
);
const [skillSearchQuery, setSkillSearchQuery] = useState('');
+ const [managingSkillsFor, setManagingSkillsFor] = useState<string>();
const activeDocumentIdentifier = docId ? standardizeIdentifier(docId) : undefined;
const filterOptions = isDocumentMode ? DOCUMENT_MODE_FILTER_OPTIONS : FILTER_OPTIONS;
const resolvedFilter = controlledFilter ?? filter;
@@ -325,7 +328,8 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
// Mirror what each child component reads so the parent can decide the
// section layout (flat when a single source has items, sectioned otherwise).
// Both hooks are SWR-deduped against their respective child fetches.
- const userSkillItems = useUserSkills(enabled);
+ // Include disabled inventory so the management entry survives disabling every skill.
+ const userSkillItems = useUserSkills(enabled, canManageSkills);
const {
deviceItems: deviceSkillItems,
error: projectSkillsError,
@@ -365,7 +369,6 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
() =>
skillBundleViews.map(({ bundle, files }) => ({
description: bundle.description ?? undefined,
- fileCount: files.length,
files,
id: bundle.documentId,
name: bundle.title || bundle.filename || '',
@@ -424,105 +427,30 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
[openAgentDocument, skillBundleViews],
);
+ const getAgentSkillIdentifier = useCallback(
+ (item: SkillListItem) => {
+ const filename = skillBundleViews.find((view) => view.bundle.documentId === item.id)?.bundle
+ .filename;
+ return filename ? buildAgentSkillIdentifier(filename) : undefined;
+ },
+ [skillBundleViews],
+ );
+ const selectAgentSkill = useSelectSkill('agentSkill', getAgentSkillIdentifier);
+
// The runtime resolves these via the `agent-skills:<filename>` identifier
// (built from the shared const helper so the prefix stays in lockstep with
// the server-side resolver). Display label keeps the human-readable title.
const handleAgentSkillDragStart = useCallback(
(item: SkillListItem, event: DragEvent) => {
- const view = skillBundleViews.find((v) => v.bundle.documentId === item.id);
- const filename = view?.bundle.filename;
- if (!filename) return;
+ const type = getAgentSkillIdentifier(item);
+ if (!type) return;
startSkillDrag(event, {
category: 'agentSkill',
label: item.name,
- type: buildAgentSkillIdentifier(filename),
+ type,
});
},
- [skillBundleViews],
- );
-
- // Agent skills are document bundles, so view / rename / delete map onto the
- // agent-document service (`item.id` is the bundle's documentId; the service
- // keys off the row id carried on the bundle).
- const getAgentSkillActions = useCallback(
- (item: SkillListItem): SkillRowAction[] => {
- const view = skillBundleViews.find((v) => v.bundle.documentId === item.id);
- const rowId = view?.bundle.id;
- return [
- {
- icon: EyeIcon,
- key: 'view',
- label: t('workingPanel.skills.actions.view'),
- onClick: openAgentSkill,
- sfSymbol: 'eye',
- },
- {
- disabled: !rowId,
- icon: PencilIcon,
- key: 'rename',
- label: t('workingPanel.skills.actions.rename'),
- onClick: () => {
- if (!rowId) return;
- openRenameSkillModal({
- currentName: item.name,
- onSubmit: async (newName) => {
- try {
- await agentDocumentService.renameDocument({
- agentId: agentId!,
- id: rowId,
- newTitle: newName,
- });
- await mutate();
- return undefined;
- } catch (error) {
- return error instanceof Error
- ? error.message
- : t('workingPanel.skills.rename.error');
- }
- },
- });
- },
- sfSymbol: 'pencil',
- },
- {
- danger: true,
- disabled: !rowId,
- icon: Trash2Icon,
- key: 'delete',
- label: t('workingPanel.skills.actions.delete'),
- onClick: () => {
- if (!rowId) return;
- confirmModal({
- cancelText: tCommon('cancel'),
- content: t('workingPanel.skills.delete.agentConfirm', { name: item.name }),
- okButtonProps: { danger: true },
- okText: tCommon('delete'),
- onOk: async () => {
- try {
- // A skill bundle always holds its SKILL.md and resources.
- await agentDocumentService.removeDocument({
- agentId: agentId!,
- id: rowId,
- withChildren: true,
- });
- await mutate();
- toast.success(t('workingPanel.skills.delete.success'));
- } catch (error) {
- toast.error(
- error instanceof Error
- ? error.message
- : t('workingPanel.skills.delete.error'),
- );
- }
- },
- title: t('workingPanel.skills.delete.title'),
- });
- },
- sfSymbol: 'trash',
- },
- ];
- },
- [agentId, mutate, openAgentSkill, skillBundleViews, t, tCommon],
+ [getAgentSkillIdentifier],
);
if (!agentId) return null;
@@ -556,15 +484,31 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
const renderAgentSkillsList = () => (
<SkillsList
- getRowActions={getAgentSkillActions}
items={matchedSkillItems}
onOpenFile={openAgentSkillFile}
onOpenSkill={openAgentSkill}
+ onSelectSkill={isDocumentMode ? undefined : selectAgentSkill}
onSkillDragStart={handleAgentSkillDragStart}
/>
);
const renderSkills = () => {
+ if (agentId && managingSkillsFor === agentId) {
+ return (
+ <UserSkillsManagement
+ agentId={agentId}
+ items={userSkillItems}
+ key={agentId}
+ onClose={() =>
+ setManagingSkillsFor((current) => (current === agentId ? undefined : current))
+ }
+ />
+ );
+ }
+
+ // This is an invocation picker for agent/project/device/user skills, not a
+ // full capability inventory. Builtin bundles intentionally keep their existing
+ // slash/profile entry points instead of being copied into this sidebar.
// Sections render in fixed order — agent → project → device → user — and each one
// hides itself when it has nothing to show. When exactly one source has
// items we drop the group header and render the list flat (no redundant
@@ -616,7 +560,7 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
return (
<Flexbox gap={16} style={{ paddingBottom: 16 }}>
<SkillsSearchBar onSearch={setSkillSearchQuery} />
- {!hasMatch && (
+ {!hasMatch && !(hasUser && canManageSkills) && (
<Center flex={1} gap={8} paddingBlock={24}>
<Empty description={t('workingPanel.skills.noSearchResults')} icon={SkillsIcon} />
</Center>
@@ -650,7 +594,13 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
workingDirectory={workingDirectory!}
/>
)}
- {hasMatchedUser && <UserLevelSkills hideHeader={flat} searchQuery={skillSearchQuery} />}
+ {hasUser && (
+ <UserLevelSkills
+ hideHeader={flat}
+ searchQuery={skillSearchQuery}
+ onManage={canManageSkills ? () => setManagingSkillsFor(agentId) : undefined}
+ />
+ )}
</Flexbox>
);
};
diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/DeviceLevelSkills.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/DeviceLevelSkills.tsx
index eefb093589c..caee862c04e 100644
--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/DeviceLevelSkills.tsx
+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/DeviceLevelSkills.tsx
@@ -11,6 +11,8 @@ import {
useProjectSkills,
} from '@/features/SkillsList';
+import { useSelectSkill } from './useSelectSkill';
+
const handleSkillDragStart = (item: SkillListItem, event: React.DragEvent) => {
startSkillDrag(event, {
category: 'projectSkill',
@@ -35,10 +37,8 @@ interface DeviceLevelSkillsProps {
const DeviceLevelSkills = memo<DeviceLevelSkillsProps>(
({ deviceId, hideHeader, searchQuery = '', workingDirectory }) => {
const { t } = useTranslation('chat');
- const { deviceItems, error, getRowActions, mutate, onOpenFile, onOpenSkill } = useProjectSkills(
- workingDirectory,
- deviceId,
- );
+ const onSelectSkill = useSelectSkill('projectSkill');
+ const { deviceItems, error, mutate } = useProjectSkills(workingDirectory, deviceId);
const items = useMemo(
() => filterSkillItems(deviceItems, searchQuery),
@@ -62,10 +62,8 @@ const DeviceLevelSkills = memo<DeviceLevelSkillsProps>(
const list = (
<SkillsList
- getRowActions={getRowActions}
items={items}
- onOpenFile={onOpenFile}
- onOpenSkill={onOpenSkill}
+ onSelectSkill={onSelectSkill}
onSkillDragStart={handleSkillDragStart}
/>
);
diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/ProjectLevelSkills.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/ProjectLevelSkills.tsx
index f5a5b8f478c..273e7e3f0ea 100644
--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/ProjectLevelSkills.tsx
+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/ProjectLevelSkills.tsx
@@ -11,6 +11,8 @@ import {
useProjectSkills,
} from '@/features/SkillsList';
+import { useSelectSkill } from './useSelectSkill';
+
// Project skills are resolved by the underlying CLI agent itself, so
// we serialize them as a literal `/skill-name` (projectSkill chip).
const handleSkillDragStart = (item: SkillListItem, event: React.DragEvent) => {
@@ -37,8 +39,8 @@ interface ProjectLevelSkillsProps {
const ProjectLevelSkills = memo<ProjectLevelSkillsProps>(
({ deviceId, hideHeader, searchQuery = '', workingDirectory }) => {
const { t } = useTranslation('chat');
- const { error, getRowActions, mutate, onOpenFile, onOpenSkill, projectItems } =
- useProjectSkills(workingDirectory, deviceId);
+ const onSelectSkill = useSelectSkill('projectSkill');
+ const { error, mutate, projectItems } = useProjectSkills(workingDirectory, deviceId);
const items = useMemo(
() => filterSkillItems(projectItems, searchQuery),
@@ -64,10 +66,8 @@ const ProjectLevelSkills = memo<ProjectLevelSkillsProps>(
const list = (
<SkillsList
- getRowActions={getRowActions}
items={items}
- onOpenFile={onOpenFile}
- onOpenSkill={onOpenSkill}
+ onSelectSkill={onSelectSkill}
onSkillDragStart={handleSkillDragStart}
/>
);
diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/SkillsGroup.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/SkillsGroup.tsx
index 22bea3b1870..93ac9c22ddd 100644
--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/SkillsGroup.tsx
+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/SkillsGroup.tsx
@@ -13,6 +13,8 @@ import {
useProjectSkills,
} from '@/features/SkillsList';
+import { useSelectSkill } from './useSelectSkill';
+
// Filesystem skills are resolved by the underlying runtime registry, so
// we serialize them as a literal `/skill-name` (projectSkill chip).
const handleSkillDragStart = (item: SkillListItem, event: React.DragEvent) => {
@@ -31,29 +33,22 @@ interface SkillsGroupProps {
const SkillsGroup = memo<SkillsGroupProps>(({ deviceId, workingDirectory }) => {
const { t } = useTranslation('chat');
+ const onSelectSkill = useSelectSkill('projectSkill');
const [searchQuery, setSearchQuery] = useState('');
// Local desktop reads over IPC; a bound device reads over RPC. Either path
// makes the skills list reachable even when this client isn't the desktop.
const enabled = (isDesktop || !!deviceId) && !!workingDirectory;
- const {
- deviceItems,
- error,
- getRowActions,
- isLoading,
- mutate,
- onOpenFile,
- onOpenSkill,
- projectItems,
- } = useProjectSkills(enabled ? workingDirectory : undefined, deviceId);
+ const { deviceItems, error, isLoading, mutate, projectItems } = useProjectSkills(
+ enabled ? workingDirectory : undefined,
+ deviceId,
+ );
if (!enabled) return null;
const renderList = (items: typeof projectItems) => (
<SkillsList
- getRowActions={getRowActions}
items={items}
- onOpenFile={onOpenFile}
- onOpenSkill={onOpenSkill}
+ onSelectSkill={onSelectSkill}
onSkillDragStart={handleSkillDragStart}
/>
);
diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.test.ts b/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.test.ts
index d65fa5e0e3f..651e246d402 100644
--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.test.ts
+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.test.ts
@@ -1,5 +1,4 @@
import { act, renderHook } from '@testing-library/react';
-import { isValidElement } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { useAgentStore } from '@/store/agent';
@@ -39,8 +38,7 @@ vi.mock('@/features/ChatInput/InputEditor/ActionTag/skillDragData', () => ({
startSkillDrag: vi.fn(),
}));
-// Exercise the sidebar's row data, not a component render. The icon's own
-// market lookup remains shared with the input menu.
+// User skills share the list's default glyph, regardless of their source.
describe('useUserSkills', () => {
const initialState = useAgentStore.getState();
@@ -83,7 +81,15 @@ describe('useUserSkills', () => {
expect(result.current).toEqual([]);
});
- it('provides a market icon for installed market skills without changing their identity', () => {
+ it('keeps the full inventory available for management when every skill is disabled', () => {
+ act(() => useAgentStore.setState({ agentMap: { 'agent-a': { plugins: [] } } }));
+ const { result } = renderHook(() => useUserSkills(true, true));
+ expect(result.current.map((skill) => skill.id)).toEqual(
+ skills.map((skill) => skill.identifier),
+ );
+ });
+
+ it('uses the shared skill glyph for market skills without changing their identity', () => {
const { result } = renderHook(() => useUserSkills());
expect(result.current[0]).toMatchObject({
@@ -91,14 +97,13 @@ describe('useUserSkills', () => {
id: skills[0].identifier,
name: skills[0].name,
});
- expect(result.current[0]).toHaveProperty('icon', expect.anything());
- expect(isValidElement(result.current[0].icon)).toBe(true);
+ expect(result.current[0]).not.toHaveProperty('icon');
});
- it('keeps the generic skill icon fallback for custom skills', () => {
+ it('uses the same shared skill glyph for custom skills', () => {
const { result } = renderHook(() => useUserSkills());
- expect(result.current[1].icon).toBeUndefined();
+ expect(result.current[1]).not.toHaveProperty('icon');
});
it('does not produce rows or icons when the section is disabled', () => {
diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsx
index cc0dcd76b6f..ed6ee6d611e 100644
--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsx
+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsx
@@ -1,29 +1,24 @@
import { getLibrarySkillMode } from '@lobechat/types';
-import { confirmModal, createModal, toast } from '@lobehub/ui';
+import { ActionIcon } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
-import { t as translate } from 'i18next';
-import { EyeIcon, PencilIcon, Trash2Icon } from 'lucide-react';
+import { SettingsIcon } from 'lucide-react';
import type React from 'react';
-import { lazy, memo, Suspense, useCallback, useMemo } from 'react';
+import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import MarketSkillIcon from '@/components/MarketSkillIcon';
import { startSkillDrag } from '@/features/ChatInput/InputEditor/ActionTag/skillDragData';
import {
filterSkillItems,
- openRenameSkillModal,
type SkillListItem,
- type SkillRowAction,
SkillSection,
SkillsList,
} from '@/features/SkillsList';
-import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useToolStore } from '@/store/tool';
import { agentSkillsSelectors } from '@/store/tool/selectors';
-const AgentSkillDetail = lazy(() => import('@/features/AgentSkillDetail'));
+import { useSelectSkill } from './useSelectSkill';
const EMPTY_ITEMS: SkillListItem[] = [];
@@ -35,19 +30,6 @@ const handleSkillDragStart = (item: SkillListItem, event: React.DragEvent) => {
});
};
-const openSkillDetailModal = (skillId: string) =>
- createModal({
- content: (
- <Suspense fallback={<div style={{ height: '100%' }} />}>
- <AgentSkillDetail skillId={skillId} />
- </Suspense>
- ),
- footer: null,
- styles: { content: { height: 'calc(100dvh - 200px)', overflow: 'hidden', padding: 0 } },
- title: translate('workingPanel.skills.detail.title', { ns: 'chat' }),
- width: 960,
- });
-
/**
* Reads user-installed skills (entries in the `agent_skill` table — market
* imports plus user-created customs) enabled for the current agent into the
@@ -58,7 +40,7 @@ const openSkillDetailModal = (skillId: string) =>
* data even when the Tools popover hasn't been opened in this session. The key
* is deduplicated, so co-mounting with `useControls` doesn't double-fetch.
*/
-export const useUserSkills = (enabled = true): SkillListItem[] => {
+export const useUserSkills = (enabled = true, includeDisabled = false): SkillListItem[] => {
useToolStore((s) => s.useFetchAgentSkills)(enabled);
const agentSkills = useToolStore(agentSkillsSelectors.getAgentSkills, isEqual);
const plugins = useAgentStore((s) => agentSelectors.currentAgentConfig(s)?.plugins);
@@ -68,20 +50,19 @@ export const useUserSkills = (enabled = true): SkillListItem[] => {
!enabled
? EMPTY_ITEMS
: agentSkills
- .filter((skill) => getLibrarySkillMode(plugins, skill.identifier) !== 'disabled')
+ .filter(
+ (skill) =>
+ includeDisabled || getLibrarySkillMode(plugins, skill.identifier) !== 'disabled',
+ )
.map((skill) => ({
description: skill.description ?? undefined,
- icon:
- skill.source === 'market' ? (
- <MarketSkillIcon identifier={skill.identifier} name={skill.name} />
- ) : undefined,
// `identifier` is what the runtime resolves through the skill registry,
// and is unique per skill — reuse it as both the React key and the
// drag payload's `type`.
id: skill.identifier,
name: skill.name,
})),
- [agentSkills, enabled, plugins],
+ [agentSkills, enabled, includeDisabled, plugins],
);
};
@@ -92,123 +73,48 @@ interface UserLevelSkillsProps {
* matching the agent-only layout this used to ship with.
*/
hideHeader?: boolean;
+ onManage?: () => void;
/** Only render skills matching this query. */
searchQuery?: string;
}
-const UserLevelSkills = memo<UserLevelSkillsProps>(({ hideHeader, searchQuery = '' }) => {
+const UserLevelSkills = memo<UserLevelSkillsProps>(({ hideHeader, onManage, searchQuery = '' }) => {
const { t } = useTranslation('chat');
- const { t: tCommon } = useTranslation('common');
+ const onSelectSkill = useSelectSkill('skill');
const userItems = useUserSkills();
const items = useMemo(() => filterSkillItems(userItems, searchQuery), [userItems, searchQuery]);
- // The row shape keys off `identifier`, but the store mutations key off the DB
- // id — resolve one from the other through the raw skill list.
- const agentSkills = useToolStore(agentSkillsSelectors.getAgentSkills, isEqual);
- const updateAgentSkill = useToolStore((s) => s.updateAgentSkill);
- const deleteAgentSkill = useToolStore((s) => s.deleteAgentSkill);
- const { allowed: canEdit } = usePermission('edit_own_content');
-
- const getRowActions = useCallback(
- (item: SkillListItem): SkillRowAction[] => {
- const skill = agentSkills.find((s) => s.identifier === item.id);
- if (!skill) return [];
-
- const actions: SkillRowAction[] = [
- {
- icon: EyeIcon,
- key: 'view',
- label: t('workingPanel.skills.actions.view'),
- onClick: () => openSkillDetailModal(skill.id),
- sfSymbol: 'eye',
- },
- ];
-
- // Only user-authored skills carry an editable name; market imports are
- // pinned to their source manifest.
- if (skill.source === 'user') {
- actions.push({
- disabled: !canEdit,
- icon: PencilIcon,
- key: 'rename',
- label: t('workingPanel.skills.actions.rename'),
- onClick: () => {
- openRenameSkillModal({
- currentName: skill.name,
- onSubmit: async (newName) => {
- try {
- await updateAgentSkill({ id: skill.id, name: newName });
- return undefined;
- } catch (error) {
- return error instanceof Error
- ? error.message
- : t('workingPanel.skills.rename.error');
- }
- },
- });
- },
- sfSymbol: 'pencil',
- });
- }
-
- actions.push({
- danger: true,
- disabled: !canEdit,
- icon: Trash2Icon,
- key: 'delete',
- label: t('workingPanel.skills.actions.delete'),
- onClick: () => {
- confirmModal({
- cancelText: tCommon('cancel'),
- content: t('workingPanel.skills.delete.userConfirm', { name: skill.name }),
- okButtonProps: { danger: true },
- okText: tCommon('delete'),
- onOk: async () => {
- try {
- await deleteAgentSkill(skill.id);
- toast.success(t('workingPanel.skills.delete.success'));
- } catch (error) {
- toast.error(
- error instanceof Error ? error.message : t('workingPanel.skills.delete.error'),
- );
- }
- },
- title: t('workingPanel.skills.delete.title'),
- });
- },
- sfSymbol: 'trash',
- });
-
- return actions;
- },
- [agentSkills, canEdit, deleteAgentSkill, t, tCommon, updateAgentSkill],
- );
-
- const onOpenSkill = useCallback(
- (item: SkillListItem) => {
- const skill = agentSkills.find((s) => s.identifier === item.id);
- if (skill) openSkillDetailModal(skill.id);
- },
- [agentSkills],
- );
-
- if (items.length === 0) return null;
+ if (items.length === 0 && !onManage) return null;
const list = (
<SkillsList
- getRowActions={getRowActions}
items={items}
- onOpenSkill={onOpenSkill}
+ onSelectSkill={onSelectSkill}
onSkillDragStart={handleSkillDragStart}
/>
);
- if (hideHeader) return list;
+ if (hideHeader && !onManage) return list;
return (
<SkillSection
+ isEmpty={items.length === 0}
+ emptyText={t(
+ searchQuery
+ ? 'workingPanel.skills.noSearchResults'
+ : 'workingPanel.skills.manage.noneEnabled',
+ )}
sectionHeader={{
- count: items.length,
+ action: onManage && (
+ <ActionIcon
+ aria-label={t('workingPanel.skills.manage.title')}
+ icon={SettingsIcon}
+ size="small"
+ title={t('workingPanel.skills.manage.title')}
+ onClick={onManage}
+ />
+ ),
+ count: onManage ? userItems.length : items.length,
title: t('workingPanel.skills.section.user'),
}}
>
diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/UserSkillsManagement.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/UserSkillsManagement.tsx
new file mode 100644
index 00000000000..c59d15afa28
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/UserSkillsManagement.tsx
@@ -0,0 +1,138 @@
+import { Alert, Button, Checkbox, Flexbox, Icon, Text } from '@lobehub/ui';
+import { SkillsIcon } from '@lobehub/ui/icons';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { useTranslation } from 'react-i18next';
+import { Virtuoso } from 'react-virtuoso';
+
+import AsyncError from '@/components/AsyncError';
+import { type SkillListItem, SkillsSearchBar } from '@/features/SkillsList';
+import { normalizeAsyncError } from '@/libs/swr/normalizeError';
+
+import { useCanManageUserSkills } from './useCanManageUserSkills';
+import { useUserSkillsManagement } from './useUserSkillsManagement';
+
+const SKILL_ROW_HEIGHT = 36;
+
+const styles = stylex.create({
+ row: {
+ display: 'flex',
+ boxSizing: 'border-box',
+ height: SKILL_ROW_HEIGHT,
+ width: '100%',
+ minWidth: 0,
+ paddingBlock: '8px',
+ paddingInline: '4px',
+ borderRadius: '6px',
+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },
+ },
+ rowText: { flex: '1', minWidth: 0 },
+ footer: {
+ paddingBlock: '12px',
+ borderBlockStartWidth: '1px',
+ borderBlockStartStyle: 'solid',
+ borderBlockStartColor: cssVar.colorSplit,
+ },
+});
+
+interface UserSkillsManagementProps {
+ agentId: string;
+ items: SkillListItem[];
+ onClose: () => void;
+}
+
+export const UserSkillsManagement = ({ agentId, items, onClose }: UserSkillsManagementProps) => {
+ const { t } = useTranslation(['chat', 'common']);
+ const canEdit = useCanManageUserSkills(agentId);
+ const selection = useUserSkillsManagement(agentId, items, canEdit);
+ const selectedResults = selection.filteredItems.filter(({ id }) =>
+ selection.isSelected(id),
+ ).length;
+ const disabled = !canEdit || selection.saving;
+
+ return (
+ <Flexbox gap={12}>
+ <Text weight={500}>{t('workingPanel.skills.manage.title')}</Text>
+ <SkillsSearchBar onSearch={selection.setQuery} />
+ <Checkbox
+ disabled={disabled || selection.filteredItems.length === 0}
+ indeterminate={selectedResults > 0 && selectedResults < selection.filteredItems.length}
+ checked={
+ selection.filteredItems.length > 0 && selectedResults === selection.filteredItems.length
+ }
+ onChange={(checked) =>
+ selection.setSelected(
+ selection.filteredItems.map(({ id }) => id),
+ checked,
+ )
+ }
+ >
+ {t('workingPanel.skills.manage.selectResults', { count: selection.filteredItems.length })}
+ </Checkbox>
+ {selection.filteredItems.length === 0 ? (
+ <Text type="secondary">{t('workingPanel.skills.noSearchResults')}</Text>
+ ) : (
+ <Virtuoso
+ computeItemKey={(_, item) => item.id}
+ data={selection.filteredItems}
+ fixedItemHeight={SKILL_ROW_HEIGHT}
+ itemContent={(_, item) => (
+ <Checkbox
+ aria-label={item.name}
+ checked={selection.isSelected(item.id)}
+ disabled={disabled}
+ classNames={{
+ text: stylex.props(styles.rowText).className,
+ wrapper: stylex.props(styles.row).className,
+ }}
+ onChange={(checked) => selection.setSelected([item.id], checked)}
+ >
+ <Flexbox horizontal align="center" gap={8} style={{ minWidth: 0 }}>
+ <Icon icon={SkillsIcon} size={16} />
+ <Text ellipsis fontSize={13} title={item.name}>
+ {item.name}
+ </Text>
+ </Flexbox>
+ </Checkbox>
+ )}
+ style={{
+ height: Math.min(selection.filteredItems.length * SKILL_ROW_HEIGHT, 360),
+ maxHeight: '45vh',
+ }}
+ />
+ )}
+ {!canEdit && <Alert title={t('workingPanel.skills.manage.noPermission')} type="warning" />}
+ {selection.saveFailure && (
+ <AsyncError
+ align="start"
+ details={normalizeAsyncError(selection.saveFailure.error).rawMessage}
+ error={selection.saveFailure.error}
+ title={t('workingPanel.skills.manage.saveFailed')}
+ variant="inline"
+ />
+ )}
+ <Flexbox gap={8} {...stylex.props(styles.footer)}>
+ <Text fontSize={12} type="secondary">
+ {t('workingPanel.skills.manage.selected', { count: selection.selectedCount })}
+ {selection.dirty && ` · ${t('workingPanel.skills.manage.unsaved')}`}
+ </Text>
+ <Flexbox horizontal gap={8} justify="flex-end">
+ <Button disabled={selection.saving} size="small" onClick={onClose}>
+ {t('cancel', { ns: 'common' })}
+ </Button>
+ <Button
+ disabled={disabled || !selection.dirty}
+ loading={selection.saving}
+ size="small"
+ type="primary"
+ onClick={async () => {
+ if (await selection.save()) onClose();
+ }}
+ >
+ {t('workingPanel.skills.manage.save')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ );
+};
diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/useCanManageUserSkills.ts b/src/features/Conversation/WorkingSidebar/ResourcesSection/useCanManageUserSkills.ts
new file mode 100644
index 00000000000..4f20c923fd6
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/useCanManageUserSkills.ts
@@ -0,0 +1,13 @@
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
+import { usePermission } from '@/hooks/usePermission';
+import { useAgentStore } from '@/store/agent';
+
+export const useCanManageUserSkills = (agentId: string) => {
+ const { allowed } = usePermission('edit_own_content');
+ const visibility = useAgentStore((s) => s.agentMap[agentId]?.visibility);
+ const { canEditResource, isAccessResolved } = useResourceAccess(
+ 'agent',
+ visibility === 'private' ? undefined : agentId || undefined,
+ );
+ return Boolean(agentId && allowed && isAccessResolved && canEditResource);
+};
diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/useSelectSkill.test.ts b/src/features/Conversation/WorkingSidebar/ResourcesSection/useSelectSkill.test.ts
new file mode 100644
index 00000000000..4913189dfac
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/useSelectSkill.test.ts
@@ -0,0 +1,75 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { INSERT_ACTION_TAG_COMMAND } from '@/features/ChatInput/InputEditor/ActionTag/command';
+
+import { useSelectSkill } from './useSelectSkill';
+
+const mocks = vi.hoisted(() => ({
+ editor: { dispatchCommand: vi.fn(), focus: vi.fn() },
+ hasEditor: true,
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: unknown) => unknown) =>
+ selector({ mainInputEditor: mocks.hasEditor ? { instance: mocks.editor } : null }),
+}));
+
+const item = { id: 'skill-id', name: 'Display name' };
+
+describe('useSelectSkill', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.hasEditor = true;
+ });
+
+ it.each([
+ ['projectSkill', 'Display name'],
+ ['skill', 'skill-id'],
+ ] as const)('inserts a %s tag and focuses the composer', (category, type) => {
+ const { result } = renderHook(() => useSelectSkill(category));
+
+ act(() => result.current?.(item));
+
+ expect(mocks.editor.focus).toHaveBeenCalledOnce();
+ expect(mocks.editor.dispatchCommand).toHaveBeenCalledExactlyOnceWith(
+ INSERT_ACTION_TAG_COMMAND,
+ { category, label: item.name, skipIfExists: true, type },
+ );
+ });
+
+ it('resolves agent skills by filename, not their display title or document id', () => {
+ const { result } = renderHook(() => useSelectSkill('agentSkill', () => 'agent-skills:writing'));
+
+ act(() => result.current?.(item));
+
+ expect(mocks.editor.dispatchCommand).toHaveBeenCalledWith(INSERT_ACTION_TAG_COMMAND, {
+ category: 'agentSkill',
+ label: item.name,
+ skipIfExists: true,
+ type: 'agent-skills:writing',
+ });
+ });
+
+ it('does not insert an unresolvable agent skill', () => {
+ const { result } = renderHook(() => useSelectSkill('agentSkill', () => undefined));
+ act(() => result.current?.(item));
+ expect(mocks.editor.dispatchCommand).not.toHaveBeenCalled();
+ expect(mocks.editor.focus).not.toHaveBeenCalled();
+ });
+
+ it('preserves browsing without a composer and enables selection when it mounts', () => {
+ mocks.hasEditor = false;
+ const { result, rerender } = renderHook(() => useSelectSkill('skill'));
+ expect(result.current).toBeUndefined();
+
+ mocks.hasEditor = true;
+ rerender();
+ act(() => result.current?.(item));
+ expect(mocks.editor.dispatchCommand).toHaveBeenCalledOnce();
+
+ mocks.hasEditor = false;
+ rerender();
+ expect(result.current).toBeUndefined();
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/useSelectSkill.ts b/src/features/Conversation/WorkingSidebar/ResourcesSection/useSelectSkill.ts
new file mode 100644
index 00000000000..248ba078fda
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/useSelectSkill.ts
@@ -0,0 +1,38 @@
+import { useCallback } from 'react';
+
+import {
+ INSERT_ACTION_TAG_COMMAND,
+ type InsertActionTagPayload,
+} from '@/features/ChatInput/InputEditor/ActionTag/command';
+import type { SkillListItem } from '@/features/SkillsList';
+import { useChatStore } from '@/store/chat';
+
+/** Use the same skill tags as the slash menu and drag-and-drop, without sending a message. */
+export const useSelectSkill = (
+ category: Extract<InsertActionTagPayload['category'], 'skill' | 'projectSkill' | 'agentSkill'>,
+ getIdentifier?: (item: SkillListItem) => string | undefined,
+) => {
+ const editor = useChatStore((s) => s.mainInputEditor?.instance);
+ const selectSkill = useCallback(
+ (item: SkillListItem) => {
+ const type = getIdentifier
+ ? getIdentifier(item)
+ : category === 'projectSkill'
+ ? item.name
+ : item.id;
+ if (!editor || !type) return;
+
+ editor.focus();
+ editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, {
+ category,
+ label: item.name,
+ skipIfExists: true,
+ type,
+ });
+ },
+ [category, editor, getIdentifier],
+ );
+
+ // Document-only surfaces retain their browsing behavior when no composer is mounted.
+ return editor ? selectSkill : undefined;
+};
diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/useUserSkillsManagement.test.ts b/src/features/Conversation/WorkingSidebar/ResourcesSection/useUserSkillsManagement.test.ts
new file mode 100644
index 00000000000..519e9ee94a9
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/useUserSkillsManagement.test.ts
@@ -0,0 +1,228 @@
+import { type AgentPluginEntry } from '@lobechat/types';
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { applyUserSkillChanges, useUserSkillsManagement } from './useUserSkillsManagement';
+
+const mocks = vi.hoisted(() => ({
+ agents: {} as Record<string, { plugins: AgentPluginEntry[] }>,
+ refresh: vi.fn(),
+ update: vi.fn(),
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: {
+ getState: () => ({
+ agentMap: mocks.agents,
+ internal_refreshAgentConfig: mocks.refresh,
+ updateAgentConfigById: mocks.update,
+ }),
+ },
+}));
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgentConfigById: (id: string) => (state: { agentMap: typeof mocks.agents }) =>
+ state.agentMap[id],
+ },
+}));
+
+const items = [
+ { id: 'writing', name: 'Writing' },
+ { id: 'analysis', name: 'Analysis', description: 'Spreadsheets' },
+ { id: 'review', name: 'Review' },
+];
+
+beforeEach(() => {
+ mocks.agents = {
+ 'agent-a': { plugins: ['writing', { identifier: 'analysis', mode: 'auto' }, 'mcp-tool'] },
+ 'agent-b': { plugins: [] },
+ };
+ mocks.update.mockReset().mockResolvedValue(undefined);
+ mocks.refresh.mockReset().mockResolvedValue(undefined);
+});
+
+describe('applyUserSkillChanges', () => {
+ it('preserves untouched legacy entries, auto mode, tools, and builtin skills', () => {
+ const plugins: AgentPluginEntry[] = [
+ 'writing',
+ { identifier: 'analysis', mode: 'auto' },
+ 'mcp-tool',
+ 'lobehub',
+ ];
+ expect(applyUserSkillChanges(plugins, { review: true, writing: false })).toEqual([
+ { identifier: 'analysis', mode: 'auto' },
+ 'mcp-tool',
+ 'lobehub',
+ { identifier: 'review', mode: 'pinned' },
+ ]);
+ expect(plugins[0]).toBe('writing');
+ });
+
+ it('does not turn an already enabled auto skill into pinned', () => {
+ const plugins: AgentPluginEntry[] = [{ identifier: 'analysis', mode: 'auto' }];
+ expect(applyUserSkillChanges(plugins, { analysis: true })).toBe(plugins);
+ });
+
+ it('persists a newly enabled skill explicitly and removes disabled opt-in skills', () => {
+ expect(applyUserSkillChanges(undefined, { review: true })).toEqual([
+ { identifier: 'review', mode: 'pinned' },
+ ]);
+ expect(applyUserSkillChanges(['review'], { review: false })).toEqual([]);
+ });
+});
+
+describe('useUserSkillsManagement', () => {
+ it('keeps edits local and discards them on cancel/unmount', () => {
+ const { result, unmount } = renderHook(() => useUserSkillsManagement('agent-a', items, true));
+ expect(result.current.selectedCount).toBe(2);
+ act(() => result.current.setSelected(['review'], true));
+ expect(result.current.selectedCount).toBe(3);
+ expect(result.current.dirty).toBe(true);
+ unmount();
+ expect(mocks.update).not.toHaveBeenCalled();
+ expect(mocks.agents['agent-a'].plugins).not.toContain('review');
+ });
+
+ it('keeps checked and unchecked skills visible and preserves selections across search', () => {
+ const { result } = renderHook(() => useUserSkillsManagement('agent-a', items, true));
+ expect(result.current.filteredItems).toEqual(items);
+ act(() => result.current.setSelected(['review'], true));
+ act(() => result.current.setSelected(['writing'], false));
+ expect(result.current.filteredItems).toEqual(items);
+ act(() => result.current.setQuery('spreadsheets'));
+ expect(result.current.filteredItems.map(({ id }) => id)).toEqual(['analysis']);
+ act(() => result.current.setQuery(''));
+ expect(result.current.filteredItems).toEqual(items);
+ expect(result.current.isSelected('review')).toBe(true);
+ expect(result.current.isSelected('writing')).toBe(false);
+ });
+
+ it('applies bulk selection only to the matching results', () => {
+ const { result } = renderHook(() => useUserSkillsManagement('agent-a', items, true));
+ act(() => result.current.setQuery('writing'));
+ act(() =>
+ result.current.setSelected(
+ result.current.filteredItems.map(({ id }) => id),
+ false,
+ ),
+ );
+ expect(result.current.isSelected('writing')).toBe(false);
+ expect(result.current.isSelected('analysis')).toBe(true);
+ expect(result.current.isSelected('review')).toBe(false);
+ });
+
+ it('saves one patch to the bound agent, merging only edited skills into the latest config', async () => {
+ const { result } = renderHook(() => useUserSkillsManagement('agent-a', items, true));
+ act(() => result.current.setSelected(['review'], true));
+ mocks.agents['agent-a'].plugins.push('new-connector');
+ await act(async () => {
+ expect(await result.current.save()).toBe(true);
+ });
+ expect(mocks.update).toHaveBeenCalledExactlyOnceWith(
+ 'agent-a',
+ {
+ plugins: [
+ 'writing',
+ { identifier: 'analysis', mode: 'auto' },
+ 'mcp-tool',
+ 'new-connector',
+ { identifier: 'review', mode: 'pinned' },
+ ],
+ },
+ { rethrow: true, showErrorMessage: false },
+ );
+ expect(mocks.agents['agent-b'].plugins).toEqual([]);
+ });
+
+ it('does not change modes when a selection is toggled off and back on', async () => {
+ const { result } = renderHook(() => useUserSkillsManagement('agent-a', items, true));
+ act(() => result.current.setSelected(['analysis'], false));
+ act(() => result.current.setSelected(['analysis'], true));
+ expect(result.current.dirty).toBe(false);
+ await act(async () => {
+ await result.current.save();
+ });
+ expect(mocks.update).not.toHaveBeenCalled();
+ });
+
+ it('prevents edits and writes without permission', async () => {
+ const { result } = renderHook(() => useUserSkillsManagement('agent-a', items, false));
+ act(() => result.current.setSelected(['review'], true));
+ expect(result.current.dirty).toBe(false);
+ await act(async () => {
+ expect(await result.current.save()).toBe(false);
+ });
+ expect(mocks.update).not.toHaveBeenCalled();
+ });
+
+ it('locks edits and duplicate submissions while saving', async () => {
+ const deferred = Promise.withResolvers<void>();
+ mocks.update.mockReturnValueOnce(deferred.promise);
+ const { result } = renderHook(() => useUserSkillsManagement('agent-a', items, true));
+ act(() => result.current.setSelected(['review'], true));
+ let pending = Promise.resolve(false);
+ act(() => {
+ pending = result.current.save();
+ });
+ expect(result.current.saving).toBe(true);
+ act(() => result.current.setSelected(['writing'], false));
+ expect(result.current.isSelected('writing')).toBe(true);
+ expect(await result.current.save()).toBe(false);
+ await act(async () => {
+ deferred.resolve();
+ await pending;
+ });
+ expect(result.current.saving).toBe(false);
+ expect(mocks.update).toHaveBeenCalledOnce();
+ });
+
+ it.each([
+ new Error('Network error'),
+ { message: 'Forbidden', data: { httpStatus: 403 } },
+ undefined,
+ ])('retains the draft and failure details, then permits retry: %j', async (error) => {
+ mocks.update.mockRejectedValueOnce(error);
+ const { result } = renderHook(() => useUserSkillsManagement('agent-a', items, true));
+ act(() => result.current.setSelected(['review'], true));
+ await act(async () => {
+ expect(await result.current.save()).toBe(false);
+ });
+ expect(result.current.saveFailure).toEqual({ error });
+ expect(result.current.saving).toBe(false);
+ expect(result.current.isSelected('review')).toBe(true);
+ expect(result.current.dirty).toBe(true);
+ expect(mocks.refresh).toHaveBeenCalledWith('agent-a');
+ await act(async () => {
+ expect(await result.current.save()).toBe(true);
+ });
+ expect(result.current.saveFailure).toBeUndefined();
+ });
+
+ it('keeps the original save failure when refreshing confirmed config also fails', async () => {
+ const error = new Error('Save failed');
+ mocks.update.mockRejectedValueOnce(error);
+ mocks.refresh.mockRejectedValueOnce(new Error('Refresh failed'));
+ const { result } = renderHook(() => useUserSkillsManagement('agent-a', items, true));
+ act(() => result.current.setSelected(['review'], true));
+ await act(async () => {
+ expect(await result.current.save()).toBe(false);
+ });
+ expect(result.current.saveFailure?.error).toBe(error);
+ expect(result.current.saving).toBe(false);
+ expect(result.current.isSelected('review')).toBe(true);
+ });
+
+ it('does not re-enable a skill uninstalled while the editor is open', async () => {
+ const { result, rerender } = renderHook(
+ ({ inventory }) => useUserSkillsManagement('agent-a', inventory, true),
+ { initialProps: { inventory: items } },
+ );
+ act(() => result.current.setSelected(['review'], true));
+ rerender({ inventory: items.filter(({ id }) => id !== 'review') });
+ expect(result.current.dirty).toBe(false);
+ await act(async () => {
+ await result.current.save();
+ });
+ expect(mocks.update).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/useUserSkillsManagement.ts b/src/features/Conversation/WorkingSidebar/ResourcesSection/useUserSkillsManagement.ts
new file mode 100644
index 00000000000..4a7933bf2bd
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/useUserSkillsManagement.ts
@@ -0,0 +1,108 @@
+import {
+ type AgentPluginEntry,
+ getLibrarySkillMode,
+ LIBRARY_SKILL_IMPLICIT_MODE,
+ upsertPluginMode,
+} from '@lobechat/types';
+import { useRef, useState } from 'react';
+
+import { filterSkillItems, type SkillListItem } from '@/features/SkillsList';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+
+/** Apply only edited skills to the latest config, preserving tools and untouched modes. */
+export const applyUserSkillChanges = (
+ plugins: AgentPluginEntry[] | undefined,
+ changes: Record<string, boolean>,
+): AgentPluginEntry[] => {
+ let next = plugins ?? [];
+ for (const [id, enabled] of Object.entries(changes)) {
+ if ((getLibrarySkillMode(next, id) !== 'disabled') === enabled) continue;
+ next = upsertPluginMode(next, id, enabled ? 'pinned' : 'disabled', LIBRARY_SKILL_IMPLICIT_MODE);
+ }
+ return next;
+};
+
+export const useUserSkillsManagement = (
+ agentId: string,
+ items: SkillListItem[],
+ canEdit: boolean,
+) => {
+ const [baseline] = useState(() => {
+ const plugins = agentByIdSelectors.getAgentConfigById(agentId)(
+ useAgentStore.getState(),
+ )?.plugins;
+ return Object.fromEntries(
+ items.map(({ id }) => [id, getLibrarySkillMode(plugins, id) !== 'disabled']),
+ );
+ });
+ const [changes, setChanges] = useState<Record<string, boolean>>({});
+ const [query, setQuery] = useState('');
+ const [saving, setSaving] = useState(false);
+ const [saveFailure, setSaveFailure] = useState<{ error: unknown }>();
+ const savingRef = useRef(false);
+ const isSelected = (id: string) => changes[id] ?? baseline[id] ?? false;
+ const filteredItems = filterSkillItems(items, query);
+ const installedIds = new Set(items.map(({ id }) => id));
+ const pendingChanges = Object.fromEntries(
+ Object.entries(changes).filter(([id]) => installedIds.has(id)),
+ );
+
+ const setSelected = (ids: string[], selected: boolean) => {
+ if (!canEdit || savingRef.current) return;
+ setChanges((current) => {
+ const next = { ...current };
+ for (const id of ids) {
+ if (!installedIds.has(id)) continue;
+ if (selected === Boolean(baseline[id])) delete next[id];
+ else next[id] = selected;
+ }
+ return next;
+ });
+ };
+
+ const save = async () => {
+ if (!canEdit || !agentId || savingRef.current) return false;
+ if (Object.keys(pendingChanges).length === 0) return true;
+ const state = useAgentStore.getState();
+ const config = agentByIdSelectors.getAgentConfigById(agentId)(state);
+ if (!config) return false;
+ savingRef.current = true;
+ setSaving(true);
+ setSaveFailure(undefined);
+ try {
+ await state.updateAgentConfigById(
+ agentId,
+ { plugins: applyUserSkillChanges(config.plugins, pendingChanges) },
+ { rethrow: true, showErrorMessage: false },
+ );
+ return true;
+ } catch (error) {
+ setSaveFailure({ error });
+ // Config writes are optimistic. Restore the confirmed config after failure,
+ // while keeping this editor's draft intact for Retry or Cancel.
+ try {
+ await useAgentStore.getState().internal_refreshAgentConfig(agentId);
+ } catch {
+ // The inline save error stays visible even if the refresh also fails.
+ }
+ return false;
+ } finally {
+ savingRef.current = false;
+ setSaving(false);
+ }
+ };
+
+ return {
+ dirty: Object.keys(pendingChanges).length > 0,
+ filteredItems,
+ isSelected,
+ query,
+ save,
+ saveFailure,
+ saving,
+ selectedCount: items.filter(({ id }) => isSelected(id)).length,
+ setQuery,
+ setSelected,
+ };
+};
diff --git a/src/features/ProfileEditor/PluginTag.test.tsx b/src/features/ProfileEditor/PluginTag.test.tsx
index fd956c9e6e4..532744d92a7 100644
--- a/src/features/ProfileEditor/PluginTag.test.tsx
+++ b/src/features/ProfileEditor/PluginTag.test.tsx
@@ -24,6 +24,10 @@ const mocks = vi.hoisted(() => ({
identifier: string;
}>,
marketplaceConnectors: [] as Array<Record<string, unknown>>,
+ agentSkills: [] as Array<{ identifier: string; source: 'market' | 'user' }>,
+ builtinList: [] as Array<{ identifier: string; meta: { avatar: string; title: string } }>,
+ marketSkillDetail: undefined as { icon?: string } | undefined,
+ fetchSkillDetail: vi.fn(() => ({ queryKey: 'market-skill' })),
}));
vi.mock('react-i18next', () => ({
@@ -47,7 +51,11 @@ vi.mock('@lobehub/ui', async (importOriginal) => {
}),
async (importOriginal) => ({
...(await importOriginal<object>()),
- Avatar: ({ title }: { title?: string }) => <span data-testid="author-avatar">{title}</span>,
+ Avatar: ({ avatar, title }: { avatar?: string; title?: string }) => (
+ <span data-avatar={avatar} data-testid="author-avatar">
+ {title}
+ </span>
+ ),
Tooltip: ({ children, title }: { children: ReactNode; title?: string }) => (
<div data-testid="author-tooltip" data-title={title}>
{children}
@@ -63,7 +71,10 @@ vi.mock('@lobehub/ui', async (importOriginal) => {
return merged;
});
vi.mock('@lobechat/const', () => ({ resolveConnectorCatalogItem: () => undefined }));
-vi.mock('@lobehub/ui/icons', () => ({ McpIcon: () => null }));
+vi.mock('@lobehub/ui/icons', () => ({
+ McpIcon: () => null,
+ SkillsIcon: () => <svg data-testid="default-skill-icon" />,
+}));
vi.mock('@/components/Plugins/PluginAvatar', () => ({ default: () => null }));
// Run selectors against controlled state (the mocked selectors ignore state).
@@ -79,7 +90,11 @@ vi.mock('@/store/tool/slices/connector/selectors', () => ({
},
}));
vi.mock('@/store/tool/selectors', () => ({
- builtinToolSelectors: { allMetaList: () => [], metaList: () => [] },
+ agentSkillsSelectors: {
+ getAgentSkillByIdentifier: (identifier: string) => () =>
+ mocks.agentSkills.find((skill) => skill.identifier === identifier),
+ },
+ builtinToolSelectors: { allMetaList: () => mocks.builtinList, metaList: () => mocks.builtinList },
composioStoreSelectors: { getServers: () => [] },
lobehubSkillStoreSelectors: { getServers: () => [] },
pluginSelectors: { installedPluginMetaList: () => [], isPluginInstalled: () => () => false },
@@ -90,8 +105,22 @@ vi.mock('@/store/serverConfig', () => ({
}));
vi.mock('@/store/discover', () => ({
useDiscoverStore: (sel: (s: unknown) => unknown) =>
- sel({ useFetchPluginDetail: () => ({ isLoading: false, queryKey: undefined }) }),
+ sel({
+ useFetchPluginDetail: () => ({ isLoading: false, queryKey: undefined }),
+ useFetchSkillDetail: mocks.fetchSkillDetail,
+ }),
}));
+vi.mock('@/store/discover/selectors', () => ({
+ pluginSelectors: { pluginDetail: () => () => undefined },
+ skillSelectors: { skillDetail: () => () => mocks.marketSkillDetail },
+}));
+
+beforeEach(() => {
+ mocks.agentSkills = [];
+ mocks.builtinList = [];
+ mocks.marketSkillDetail = undefined;
+ mocks.fetchSkillDetail.mockClear();
+});
describe('PluginTag author attribution', () => {
beforeEach(() => {
@@ -179,6 +208,42 @@ describe('PluginTag row variant', () => {
);
});
+ it('shows the publisher icon for a community skill on the skill settings page', () => {
+ mocks.agentSkills = [{ identifier: 'writing', source: 'market' }];
+ mocks.builtinList = [{ identifier: 'writing', meta: { avatar: '🧩', title: 'Writing' } }];
+ mocks.marketSkillDetail = { icon: 'https://example.com/writing.png' };
+ render(<PluginTag isSkill pluginId="writing" variant="row" />);
+
+ expect(screen.getByTestId('author-avatar')).toHaveAttribute(
+ 'data-avatar',
+ 'https://example.com/writing.png',
+ );
+ expect(screen.queryByTestId('default-skill-icon')).toBeNull();
+ });
+
+ it.each([undefined, {}])('uses the default skill icon without a publisher icon: %j', (detail) => {
+ mocks.agentSkills = [{ identifier: 'writing', source: 'market' }];
+ mocks.builtinList = [{ identifier: 'writing', meta: { avatar: '🧩', title: 'Writing' } }];
+ mocks.marketSkillDetail = detail;
+ render(<PluginTag isSkill pluginId="writing" variant="row" />);
+
+ expect(screen.getByTestId('default-skill-icon')).toBeInTheDocument();
+ expect(screen.queryByTestId('author-avatar')).toBeNull();
+ });
+
+ it.each([
+ { isSkill: true, source: 'user' as const, variant: 'row' as const },
+ { isSkill: false, source: 'market' as const, variant: 'row' as const },
+ { isSkill: true, source: 'market' as const, variant: 'chip' as const },
+ ])('leaves other row and chip icons unchanged: %j', (props) => {
+ mocks.agentSkills = [{ identifier: 'writing', source: props.source }];
+ mocks.builtinList = [{ identifier: 'writing', meta: { avatar: '🧩', title: 'Writing' } }];
+ render(<PluginTag isSkill={props.isSkill} pluginId="writing" variant={props.variant} />);
+
+ expect(screen.getByTestId('author-avatar')).toHaveAttribute('data-avatar', '🧩');
+ expect(mocks.fetchSkillDetail).not.toHaveBeenCalled();
+ });
+
it('names the kind of tool and shows whose credentials it runs under', () => {
mocks.agentConnectors = [
{ authorizedByAvatar: null, authorizedByName: '张三', identifier: 'gmail' },
diff --git a/src/features/ProfileEditor/PluginTag.tsx b/src/features/ProfileEditor/PluginTag.tsx
index e687dd513da..c73a7ec4b62 100644
--- a/src/features/ProfileEditor/PluginTag.tsx
+++ b/src/features/ProfileEditor/PluginTag.tsx
@@ -14,12 +14,13 @@ import {
Text,
Tooltip,
} from '@lobehub/ui';
-import { McpIcon } from '@lobehub/ui/icons';
+import { McpIcon, SkillsIcon } from '@lobehub/ui/icons';
import isEqual from 'fast-deep-equal';
import { AlertCircle, Loader2, Square, SquareCheckBig, SquareMinus, X } from 'lucide-react';
import React, { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import MarketSkillIcon from '@/components/MarketSkillIcon';
import PluginAvatar from '@/components/Plugins/PluginAvatar';
import { useIsDark } from '@/hooks/useIsDark';
import { useDiscoverStore } from '@/store/discover';
@@ -27,6 +28,7 @@ import { pluginSelectors as discoverPluginSelectors } from '@/store/discover/sel
import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useToolStore } from '@/store/tool';
import {
+ agentSkillsSelectors,
builtinToolSelectors,
composioStoreSelectors,
lobehubSkillStoreSelectors,
@@ -196,6 +198,12 @@ const PluginTag = memo<PluginTagProps>(
// Extract identifier
const identifier = typeof pluginId === 'string' ? pluginId : pluginId?.identifier;
+ const showMarketSkillIcon = useToolStore(
+ (s) =>
+ variant === 'row' &&
+ isSkill &&
+ agentSkillsSelectors.getAgentSkillByIdentifier(identifier)(s)?.source === 'market',
+ );
// Agent-scoped connectors (empty unless agentId is provided).
const agentConnectors = useToolStore(
@@ -411,6 +419,17 @@ const PluginTag = memo<PluginTagProps>(
return <AlertCircle className={styles.warningIcon} size={14} />;
}
+ if (showMarketSkillIcon) {
+ return (
+ <MarketSkillIcon
+ fallback={<Icon icon={SkillsIcon} size={16} />}
+ identifier={identifier}
+ name={displayTitle}
+ size={16}
+ />
+ );
+ }
+
// Composio type has icon property
if (meta.type === 'composio' && 'icon' in meta && 'label' in meta) {
return <ComposioIcon icon={meta.icon} label={meta.label} />;
diff --git a/src/features/SkillsList/RenameSkillModal.tsx b/src/features/SkillsList/RenameSkillModal.tsx
deleted file mode 100644
index 85a7dcb6f5c..00000000000
--- a/src/features/SkillsList/RenameSkillModal.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-'use client';
-
-import {
- Button,
- createModal,
- cssVar,
- Flexbox,
- Input,
- type ModalInstance,
- Text,
- useModalContext,
-} from '@lobehub/ui';
-import { t } from 'i18next';
-import { memo, useCallback, useEffect, useRef, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-interface RenameSkillContentProps {
- /** The skill's current name — prefilled and selected for quick editing. */
- currentName: string;
- /**
- * Rename the skill. Return an error message to show inline and keep the modal
- * open; return undefined on success (the modal closes).
- */
- onSubmit: (name: string) => Promise<string | undefined>;
-}
-
-const RenameSkillContent = memo<RenameSkillContentProps>(({ currentName, onSubmit }) => {
- const { t: tChat } = useTranslation('chat');
- const { t: tCommon } = useTranslation('common');
- const { close } = useModalContext();
- const [value, setValue] = useState(currentName);
- const [loading, setLoading] = useState(false);
- const [error, setError] = useState<string>();
- const inputRef = useRef<HTMLInputElement>(null);
-
- useEffect(() => {
- // Focus + select the whole name so the user can immediately retype.
- queueMicrotask(() => inputRef.current?.select());
- }, []);
-
- const handleSubmit = useCallback(async () => {
- if (loading) return;
- const name = value.trim();
- if (!name || name === currentName) return;
- setLoading(true);
- try {
- const message = await onSubmit(name);
- if (message) {
- setError(message);
- return;
- }
- close();
- } finally {
- setLoading(false);
- }
- }, [close, currentName, loading, onSubmit, value]);
-
- const trimmed = value.trim();
- return (
- <Flexbox gap={16}>
- <Flexbox gap={6}>
- <Input
- placeholder={tChat('workingPanel.skills.rename.placeholder')}
- ref={inputRef}
- value={value}
- onPressEnter={handleSubmit}
- onChange={(e) => {
- setValue(e.target.value);
- setError(undefined);
- }}
- />
- {error ? <Text style={{ color: cssVar.colorError, fontSize: 12 }}>{error}</Text> : null}
- </Flexbox>
- <Flexbox horizontal gap={8} justify={'flex-end'}>
- <Button disabled={loading} onClick={close}>
- {tCommon('cancel')}
- </Button>
- <Button
- disabled={!trimmed || trimmed === currentName}
- loading={loading}
- type={'primary'}
- onClick={handleSubmit}
- >
- {tChat('workingPanel.skills.rename.action')}
- </Button>
- </Flexbox>
- </Flexbox>
- );
-});
-
-RenameSkillContent.displayName = 'RenameSkillContent';
-
-/**
- * Skill-name entry for renaming a skill. Prefills the current name and submits
- * the new one. Shared by the agent-skill and user-skill rows in the working
- * sidebar (both back onto a rename service); mirrors the branch rename modal.
- */
-export const openRenameSkillModal = (options: {
- currentName: string;
- onSubmit: (name: string) => Promise<string | undefined>;
-}): ModalInstance =>
- createModal({
- content: <RenameSkillContent currentName={options.currentName} onSubmit={options.onSubmit} />,
- footer: null,
- maskClosable: true,
- styles: { header: { borderBottom: 'none' } },
- title: t('workingPanel.skills.rename.title', { ns: 'chat' }),
- width: 'min(90vw, 480px)',
- });
diff --git a/src/features/SkillsList/SkillSection.tsx b/src/features/SkillsList/SkillSection.tsx
index 7e7824d3e95..163c04315fe 100644
--- a/src/features/SkillsList/SkillSection.tsx
+++ b/src/features/SkillsList/SkillSection.tsx
@@ -4,6 +4,8 @@ import { memo, type ReactNode, useState } from 'react';
import AsyncError from '@/components/AsyncError';
export interface SkillSectionHeader {
+ /** Independent header action, outside the accordion's collapse trigger. */
+ action?: ReactNode;
/** Wrap the section in a collapsible Accordion. Defaults to true. */
collapsible?: boolean;
count?: number;
@@ -125,14 +127,15 @@ const SkillSection = memo<SkillSectionProps>(
if (!sectionHeader) return body;
- const { collapsible = true, count, title } = sectionHeader;
+ const { action, collapsible = true, count, title } = sectionHeader;
if (!collapsible) {
return (
<Flexbox gap={4}>
- <div className={styles.flatHeader}>
+ <Flexbox horizontal align="center" className={styles.flatHeader} justify="space-between">
<HeaderRow count={count} title={title} />
- </div>
+ {action}
+ </Flexbox>
{body}
</Flexbox>
);
@@ -145,7 +148,13 @@ const SkillSection = memo<SkillSectionProps>(
styles={{ trigger: { paddingBlock: 2, paddingInline: 4 } }}
value={expanded ? [ITEM_KEY] : []}
items={[
- { key: ITEM_KEY, title: <HeaderRow count={count} title={title} />, children: body },
+ {
+ action,
+ alwaysShowAction: true,
+ key: ITEM_KEY,
+ title: <HeaderRow count={count} title={title} />,
+ children: body,
+ },
]}
onValueChange={(keys) => setExpanded(keys.length > 0)}
/>
diff --git a/src/features/SkillsList/SkillsList.tsx b/src/features/SkillsList/SkillsList.tsx
index 3dec7f8c563..33cc2813936 100644
--- a/src/features/SkillsList/SkillsList.tsx
+++ b/src/features/SkillsList/SkillsList.tsx
@@ -1,18 +1,7 @@
import { EMPTY_ARRAY } from '@lobechat/const';
-import type { SFSymbol } from '@lobechat/electron-client-ipc';
-import {
- ContextMenuTrigger,
- createStaticStyles,
- cx,
- type DropdownItem,
- Flexbox,
- Icon,
- Tag,
- Text,
- Tooltip,
-} from '@lobehub/ui';
+import { createStaticStyles, Flexbox, Icon, Tag, Text, Tooltip } from '@lobehub/ui';
import { SkillsIcon } from '@lobehub/ui/icons';
-import { ChevronRightIcon, FileIcon, FolderIcon, type LucideIcon } from 'lucide-react';
+import { ChevronRightIcon, FileIcon, FolderIcon } from 'lucide-react';
import type React from 'react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -21,54 +10,23 @@ export interface SkillListItem {
description?: string;
/** Manual invocation only, as declared by the skill; not a disabled state. */
disableModelInvocation?: boolean;
- /**
- * File count shown next to the name. Omit (or pass 0) for atomic skills with
- * no embedded files — e.g. user-level skills sourced from MCP servers.
- */
- fileCount?: number;
/**
* Optional file tree for skills that bundle markdown/script assets. When
* empty or omitted the row stays atomic (no chevron, no expansion).
*/
files?: string[];
- /** Custom icon; omitted for skills that use the generic skill glyph. */
- icon?: React.ReactNode;
id: string;
name: string;
/** Filesystem skill scope when the row comes from a device scan. */
scope?: 'device' | 'project';
}
-/**
- * A per-row action (view / rename / delete …). The same descriptor drives both
- * the hover-revealed icon button on the right of the row and the right-click
- * context menu, so callers wire each capability once. Disabled actions render
- * greyed (used for not-yet-supported operations, e.g. mutating filesystem
- * project skills).
- */
-export interface SkillRowAction {
- danger?: boolean;
- disabled?: boolean;
- icon: LucideIcon;
- key: string;
- label: string;
- onClick: (item: SkillListItem) => void;
- sfSymbol?: SFSymbol;
- /** Hover-icon tooltip; falls back to `label`. Use for "coming soon" hints. */
- tooltip?: string;
-}
-
interface SkillsListProps {
- /**
- * Per-row actions. When this returns a non-empty array the row gains a
- * hover-revealed action cluster (right side, swaps with the file count) and a
- * right-click context menu sharing the same actions. Return `[]`/omit for
- * read-only rows (no menu, native right-click preserved).
- */
- getRowActions?: (item: SkillListItem) => SkillRowAction[];
items: SkillListItem[];
onOpenFile?: (item: SkillListItem, relativePath: string) => void;
onOpenSkill?: (item: SkillListItem) => void;
+ /** Select into the conversation instead of browsing the skill's files. */
+ onSelectSkill?: (item: SkillListItem) => void;
/**
* When provided, each skill row becomes draggable and this fires on dragstart.
* The handler is expected to write the drag payload onto `event.dataTransfer`
@@ -125,62 +83,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
color: ${cssVar.colorText};
background: ${cssVar.colorFillTertiary};
}
-
- /* Swap the file count for the row actions while hovering the row. */
- &:hover .skill-row-actions {
- display: flex;
- }
-
- &:hover .skill-row-count {
- display: none;
- }
- `,
- itemCount: css`
- flex-shrink: 0;
- font-size: 12px;
- font-variant-numeric: tabular-nums;
- color: ${cssVar.colorTextTertiary};
- `,
- rowAction: css`
- cursor: pointer;
-
- display: flex;
- align-items: center;
- justify-content: center;
-
- width: 20px;
- height: 20px;
- border-radius: 4px;
-
- color: ${cssVar.colorTextTertiary};
-
- transition: all 0.2s;
-
- &:hover {
- color: ${cssVar.colorText};
- background: ${cssVar.colorFillSecondary};
- }
- `,
- rowActionDanger: css`
- &:hover {
- color: ${cssVar.colorError};
- background: ${cssVar.colorErrorBg};
- }
- `,
- rowActionDisabled: css`
- cursor: not-allowed;
- color: ${cssVar.colorTextQuaternary};
-
- &:hover {
- color: ${cssVar.colorTextQuaternary};
- background: transparent;
- }
- `,
- rowActions: css`
- display: none;
- flex: none;
- gap: 2px;
- align-items: center;
`,
itemIcon: css`
flex-shrink: 0;
@@ -314,10 +216,10 @@ TreeRow.displayName = 'SkillsListTreeRow';
interface SkillRowProps {
expanded: boolean;
- getRowActions?: (item: SkillListItem) => SkillRowAction[];
item: SkillListItem;
onOpenFile?: (item: SkillListItem, relativePath: string) => void;
onOpenSkill?: (item: SkillListItem) => void;
+ onSelectSkill?: (item: SkillListItem) => void;
onSkillDragStart?: (item: SkillListItem, event: React.DragEvent) => void;
onToggle: (id: string) => void;
reserveChevronSlot: boolean;
@@ -329,19 +231,18 @@ interface SkillRowProps {
const SkillRow = memo<SkillRowProps>(
({
expanded,
- getRowActions,
item,
onOpenFile,
onOpenSkill,
+ onSelectSkill,
onSkillDragStart,
onToggle,
reserveChevronSlot,
}) => {
const { t } = useTranslation('chat');
- const files = item.files ?? EMPTY_ARRAY;
+ const activateSkill = onSelectSkill ?? onOpenSkill;
+ const files = onSelectSkill ? EMPTY_ARRAY : (item.files ?? EMPTY_ARRAY);
const hasFiles = files.length > 0;
- const actions = useMemo(() => getRowActions?.(item) ?? EMPTY_ARRAY, [getRowActions, item]);
- const hasActions = actions.length > 0;
const tree = useMemo(() => buildSkillTree(files), [files]);
const [expandedFolders, setExpandedFolders] = useState<Set<string>>(() => new Set());
@@ -359,30 +260,8 @@ const SkillRow = memo<SkillRowProps>(
[item, onOpenFile],
);
- const contextMenuItems = useCallback(
- (): (DropdownItem & { sfSymbol?: SFSymbol })[] =>
- actions.map((action) => ({
- danger: action.danger,
- disabled: action.disabled,
- icon: <Icon icon={action.icon} />,
- key: action.key,
- label: action.label,
- onClick: () => action.onClick(item),
- sfSymbol: action.sfSymbol,
- })),
- [actions, item],
- );
-
- // The description Tooltip wraps just the name (a ref-forwarding leaf) and the
- // ContextMenuTrigger wraps just the row Flexbox — both cloning wrappers get
- // a clean DOM-forwarding child. Nesting them (Tooltip around the trigger, or
- // vice versa) would drop `onContextMenu` / the ref on the way through.
const nameNode = (
- <Text
- ellipsis
- style={{ color: 'inherit', flex: 1, minWidth: 0 }}
- onClick={onOpenSkill ? () => onOpenSkill(item) : undefined}
- >
+ <Text ellipsis style={{ color: 'inherit', flex: 1, minWidth: 0 }}>
{item.name}
</Text>
);
@@ -394,7 +273,17 @@ const SkillRow = memo<SkillRowProps>(
className={styles.item}
draggable={!!onSkillDragStart}
gap={6}
+ role={activateSkill ? 'button' : undefined}
+ tabIndex={activateSkill ? 0 : undefined}
+ onClick={activateSkill ? () => activateSkill(item) : undefined}
onDragStart={onSkillDragStart ? (event) => onSkillDragStart(item, event) : undefined}
+ onKeyDown={(event) => {
+ if (!activateSkill || event.target !== event.currentTarget) return;
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ activateSkill(item);
+ }
+ }}
>
{hasFiles ? (
<Flexbox
@@ -412,10 +301,10 @@ const SkillRow = memo<SkillRowProps>(
size={14}
/>
</Flexbox>
- ) : reserveChevronSlot ? (
+ ) : !onSelectSkill && reserveChevronSlot ? (
<span style={{ flexShrink: 0, height: 20, width: 20 }} />
) : null}
- {item.icon ?? <Icon className={styles.itemIcon} icon={SkillsIcon} size={14} />}
+ <Icon className={styles.itemIcon} icon={SkillsIcon} size={14} />
{item.description ? (
<Tooltip
placement={'left'}
@@ -431,38 +320,12 @@ const SkillRow = memo<SkillRowProps>(
{t('workingPanel.skills.manualOnly')}
</Tag>
)}
- {typeof item.fileCount === 'number' && item.fileCount > 0 && (
- <span className={cx('skill-row-count', styles.itemCount)}>{item.fileCount}</span>
- )}
- {hasActions && (
- <div className={cx('skill-row-actions', styles.rowActions)} draggable={false}>
- {actions.map((action) => (
- <Tooltip key={action.key} title={action.tooltip ?? action.label}>
- <div
- role={'button'}
- className={cx(
- styles.rowAction,
- action.danger && !action.disabled && styles.rowActionDanger,
- action.disabled && styles.rowActionDisabled,
- )}
- onClick={(e) => {
- e.stopPropagation();
- if (action.disabled) return;
- action.onClick(item);
- }}
- >
- <Icon icon={action.icon} size={13} />
- </div>
- </Tooltip>
- ))}
- </div>
- )}
</Flexbox>
);
return (
<>
- {hasActions ? <ContextMenuTrigger items={contextMenuItems}>{row}</ContextMenuTrigger> : row}
+ {row}
{expanded &&
hasFiles &&
onOpenFile &&
@@ -484,7 +347,7 @@ const SkillRow = memo<SkillRowProps>(
SkillRow.displayName = 'SkillsListSkillRow';
const SkillsList = memo<SkillsListProps>(
- ({ getRowActions, items, onOpenFile, onOpenSkill, onSkillDragStart }) => {
+ ({ items, onOpenFile, onOpenSkill, onSelectSkill, onSkillDragStart }) => {
const [expanded, setExpanded] = useState<Set<string>>(() => new Set());
const toggle = useCallback((id: string) => {
@@ -506,12 +369,12 @@ const SkillsList = memo<SkillsListProps>(
{items.map((item) => (
<SkillRow
expanded={expanded.has(item.id)}
- getRowActions={getRowActions}
item={item}
key={item.id}
reserveChevronSlot={reserveChevronSlot}
onOpenFile={onOpenFile}
onOpenSkill={onOpenSkill}
+ onSelectSkill={onSelectSkill}
onSkillDragStart={onSkillDragStart}
onToggle={toggle}
/>
diff --git a/src/features/SkillsList/index.ts b/src/features/SkillsList/index.ts
index b166d4b155b..8f6f79e1ca4 100644
--- a/src/features/SkillsList/index.ts
+++ b/src/features/SkillsList/index.ts
@@ -1,8 +1,7 @@
export { filterSkillItems } from './filterSkillItems';
-export { openRenameSkillModal } from './RenameSkillModal';
export type { SkillSectionHeader, SkillSectionProps } from './SkillSection';
export { default as SkillSection } from './SkillSection';
-export type { SkillListItem, SkillRowAction } from './SkillsList';
+export type { SkillListItem } from './SkillsList';
export { default as SkillsList } from './SkillsList';
export { default as SkillsSearchBar } from './SkillsSearchBar';
export { useProjectSkills, type UseProjectSkillsResult } from './useProjectSkills';
diff --git a/src/features/SkillsList/useProjectSkills.ts b/src/features/SkillsList/useProjectSkills.ts
index 5aabae9a337..5a728cadff6 100644
--- a/src/features/SkillsList/useProjectSkills.ts
+++ b/src/features/SkillsList/useProjectSkills.ts
@@ -1,31 +1,21 @@
import type { ListProjectSkillsResult, ProjectSkillItem } from '@lobechat/electron-client-ipc';
-import { EyeIcon, PencilIcon, Trash2Icon } from 'lucide-react';
-import path from 'pathe';
import { useCallback, useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
import { useChatStore } from '@/store/chat';
import { useToolStore } from '@/store/tool';
import { projectSkillsSelectors } from '@/store/tool/selectors';
-import type { SkillListItem, SkillRowAction } from './SkillsList';
+import type { SkillListItem } from './SkillsList';
export interface UseProjectSkillsResult {
deviceItems: SkillListItem[];
/** The thrown error from the latest scan, if it failed. */
error: unknown;
- /**
- * Per-row actions for filesystem skills: "view" opens the SKILL.md (locally
- * via IPC, or on a bound device over RPC — same as the Files tab), while
- * rename / delete are stubbed (disabled) until filesystem-mutation IPC lands.
- */
- getRowActions: (item: SkillListItem) => SkillRowAction[];
/** No scan (persisted or fresh) for this device + directory yet. */
isLoading: boolean;
items: SkillListItem[];
/** Retry the failed scan. */
mutate: () => void;
- onOpenFile: (item: SkillListItem, relativePath: string) => void;
onOpenSkill: (item: SkillListItem) => void;
projectItems: SkillListItem[];
raw: ListProjectSkillsResult | undefined;
@@ -50,7 +40,6 @@ export const useProjectSkills = (
workingDirectory: string | undefined,
deviceId?: string,
): UseProjectSkillsResult => {
- const { t } = useTranslation('chat');
const openLocalFile = useChatStore((s) => s.openLocalFile);
const { error, revalidate } = useToolStore((s) => s.useFetchProjectSkills)(
@@ -72,7 +61,6 @@ export const useProjectSkills = (
(data?.skills ?? []).map((skill) => ({
description: skill.description,
disableModelInvocation: skill.disableModelInvocation,
- fileCount: skill.fileCount,
files: skill.files,
id: skill.skillDir,
name: skill.name,
@@ -115,15 +103,6 @@ export const useProjectSkills = (
[deviceId, openLocalFile, previewRoot],
);
- const onOpenFile = useCallback(
- (item: SkillListItem, relativePath: string) => {
- const skill = skillByDir.get(item.id);
- if (!skill) return;
- openSkillFile(skill, path.join(skill.skillDir, relativePath));
- },
- [openSkillFile, skillByDir],
- );
-
const onOpenSkill = useCallback(
(item: SkillListItem) => {
const skill = skillByDir.get(item.id);
@@ -133,44 +112,6 @@ export const useProjectSkills = (
[openSkillFile, skillByDir],
);
- const getRowActions = useCallback(
- (_item: SkillListItem): SkillRowAction[] => {
- const comingSoon = t('workingPanel.skills.actions.comingSoon');
- return [
- {
- // Preview works in every mode: local via IPC, bound device via RPC
- // (matches the Files tab, which reads remote files over RPC).
- icon: EyeIcon,
- key: 'view',
- label: t('workingPanel.skills.actions.view'),
- onClick: onOpenSkill,
- sfSymbol: 'eye',
- },
- {
- // Renaming a filesystem skill needs an IPC/RPC that doesn't exist yet.
- disabled: true,
- icon: PencilIcon,
- key: 'rename',
- label: t('workingPanel.skills.actions.rename'),
- onClick: () => {},
- sfSymbol: 'pencil',
- tooltip: comingSoon,
- },
- {
- danger: true,
- disabled: true,
- icon: Trash2Icon,
- key: 'delete',
- label: t('workingPanel.skills.actions.delete'),
- onClick: () => {},
- sfSymbol: 'trash',
- tooltip: comingSoon,
- },
- ];
- },
- [onOpenSkill, t],
- );
-
const retry = useCallback(() => {
void revalidate();
}, [revalidate]);
@@ -178,11 +119,9 @@ export const useProjectSkills = (
return {
deviceItems,
error,
- getRowActions,
isLoading,
items,
mutate: retry,
- onOpenFile,
onOpenSkill,
projectItems,
raw: data,