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(skills): drag skill chips + register agent-document skills (#15095)

Arvin Xua41fd95eb542
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index d0d7ca86a43..52a8e2fee47 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -69,6 +69,11 @@
"cliAuthGuide.errorDetails": "Error details",
"cliAuthGuide.runCommand": "Run this in Terminal",
"cliAuthGuide.title": "Sign in to {{name}}",
+ "cliOverloadedGuide.actions.retry": "Retry",
+ "cliOverloadedGuide.desc": "{{name}}'s upstream model service is temporarily overloaded. This usually clears in a moment.",
+ "cliOverloadedGuide.errorDetails": "Error details",
+ "cliOverloadedGuide.retryHint": "Wait a few seconds and retry. If it keeps failing, the provider may be having a wider incident.",
+ "cliOverloadedGuide.title": "{{name}} is temporarily overloaded",
"cliRateLimitGuide.actions.openSystemTools": "Open System Tools",
"cliRateLimitGuide.actions.retry": "Retry",
"cliRateLimitGuide.afterReset": "Wait until the reset time, then retry your message. If you are using API authorization, you can also check your provider quota and billing status.",
@@ -274,6 +279,11 @@
"memory.on.desc": "Allow AI to actively search and manage your memories during conversation.",
"memory.on.title": "Enable Memory Tool",
"memory.title": "Memory",
+ "mention.category.agents": "Agents",
+ "mention.category.members": "Members",
+ "mention.category.skills": "Skills",
+ "mention.category.tools": "Tools",
+ "mention.category.topics": "Topics",
"mention.title": "Mention Members",
"messageAction.collapse": "Collapse Message",
"messageAction.continueGeneration": "Continue Generating",
diff --git a/locales/en-US/editor.json b/locales/en-US/editor.json
index d5464989555..789f9c032b3 100644
--- a/locales/en-US/editor.json
+++ b/locales/en-US/editor.json
@@ -1,8 +1,10 @@
{
+ "actionTag.category.agentSkill": "Agent skill",
"actionTag.category.command": "Command",
"actionTag.category.projectSkill": "Project skill",
"actionTag.category.skill": "Skill",
"actionTag.category.tool": "Tool",
+ "actionTag.tooltip.agentSkill": "Loads a skill bundle from this agent's documents for the request.",
"actionTag.tooltip.command": "Runs a client-side slash command before sending.",
"actionTag.tooltip.projectSkill": "Sent as a slash invocation so the agent's CLI runs the matching project skill.",
"actionTag.tooltip.skill": "Loads a reusable skill package for this request.",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 9580ddfcc31..eb835b1f0a6 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -69,6 +69,11 @@
"cliAuthGuide.errorDetails": "错误详情",
"cliAuthGuide.runCommand": "在终端执行",
"cliAuthGuide.title": "登录 {{name}}",
+ "cliOverloadedGuide.actions.retry": "重试",
+ "cliOverloadedGuide.desc": "{{name}} 当前依赖的上游模型服务暂时过载,通常很快就能自动恢复。",
+ "cliOverloadedGuide.errorDetails": "错误详情",
+ "cliOverloadedGuide.retryHint": "稍等几秒重试即可。如果一直失败,可能是模型服务商出现了更大范围的故障。",
+ "cliOverloadedGuide.title": "{{name}} 服务暂时繁忙",
"cliRateLimitGuide.actions.openSystemTools": "打开系统工具",
"cliRateLimitGuide.actions.retry": "重试",
"cliRateLimitGuide.afterReset": "请等到重置时间后再重试这条消息。如果你当前使用的是 API 授权,也可以检查对应提供商的额度和计费状态。",
@@ -274,6 +279,11 @@
"memory.on.desc": "允许 AI 在对话中主动搜索和管理你的记忆。",
"memory.on.title": "启用记忆工具",
"memory.title": "记忆",
+ "mention.category.agents": "助理",
+ "mention.category.members": "成员",
+ "mention.category.skills": "技能",
+ "mention.category.tools": "工具",
+ "mention.category.topics": "话题",
"mention.title": "提及成员",
"messageAction.collapse": "收起消息",
"messageAction.continueGeneration": "继续生成",
@@ -949,7 +959,7 @@
"workingPanel.resources.empty": "暂无文档。与此智能体关联的文档将显示在这里。",
"workingPanel.resources.error": "资源加载失败",
"workingPanel.resources.filter.documents": "文档",
- "workingPanel.resources.filter.skills": "Skills",
+ "workingPanel.resources.filter.skills": "技能",
"workingPanel.resources.filter.web": "网页",
"workingPanel.resources.loading": "资源加载中…",
"workingPanel.resources.previewError": "预览加载失败",
@@ -1003,11 +1013,11 @@
"workingPanel.review.viewMode.unified": "切换到合并视图",
"workingPanel.review.wordWrap.disable": "关闭自动换行",
"workingPanel.review.wordWrap.enable": "启用自动换行",
- "workingPanel.skills.empty": "当前项目未发现 Skills",
- "workingPanel.skills.emptyAgent": "该智能体未附加 Skills",
- "workingPanel.skills.section.agent": "智能体 Skills",
- "workingPanel.skills.section.project": "项目 Skills",
- "workingPanel.skills.title": "Skills",
+ "workingPanel.skills.empty": "当前项目未发现技能",
+ "workingPanel.skills.emptyAgent": "该智能体未附加技能",
+ "workingPanel.skills.section.agent": "智能体技能",
+ "workingPanel.skills.section.project": "项目技能",
+ "workingPanel.skills.title": "技能",
"workingPanel.space": "空间",
"workingPanel.title": "工作面板",
"you": "你",
diff --git a/locales/zh-CN/editor.json b/locales/zh-CN/editor.json
index d561d93afa4..44c6ce4bd23 100644
--- a/locales/zh-CN/editor.json
+++ b/locales/zh-CN/editor.json
@@ -1,8 +1,10 @@
{
+ "actionTag.category.agentSkill": "助理技能",
"actionTag.category.command": "指令",
"actionTag.category.projectSkill": "项目技能",
"actionTag.category.skill": "技能",
"actionTag.category.tool": "工具",
+ "actionTag.tooltip.agentSkill": "为本次请求加载该助理文档库中的技能包。",
"actionTag.tooltip.command": "发送前会先在客户端执行这条 slash 指令。",
"actionTag.tooltip.projectSkill": "以 slash 形式发送,由 Agent CLI 自行识别并执行项目内的对应技能。",
"actionTag.tooltip.skill": "表示这是一条可为本次请求加载的技能包。",
diff --git a/packages/const/src/index.ts b/packages/const/src/index.ts
index 821d8412696..a18e9fefbf7 100644
--- a/packages/const/src/index.ts
+++ b/packages/const/src/index.ts
@@ -17,6 +17,7 @@ export * from './protocol';
export * from './recommendedSkill';
export * from './session';
export * from './settings';
+export * from './skill';
export * from './taskTemplate';
export * from './theme';
export * from './trace';
diff --git a/packages/const/src/plugin.ts b/packages/const/src/plugin.ts
index 6485284311f..ff44ce5e00b 100644
--- a/packages/const/src/plugin.ts
+++ b/packages/const/src/plugin.ts
@@ -6,7 +6,9 @@ export const ARTIFACT_THINKING_TAG = 'lobeThinking';
export const MENTION_TAG = 'mention';
export const THINKING_TAG = 'think';
export const LOCAL_FILE_TAG = 'localFile';
+export const SKILL_TAG = 'skill';
export const TASK_TAG = 'task';
+export const TOOL_TAG = 'tool';
export const USER_FEEDBACK_TAG = 'user_feedback';
// https://regex101.com/r/TwzTkf/2
export const ARTIFACT_TAG_REGEX = /<lobeArtifact\b[^>]*>(?<content>[\S\s]*?)(?:<\/lobeArtifact>|$)/;
diff --git a/packages/const/src/skill.ts b/packages/const/src/skill.ts
new file mode 100644
index 00000000000..43176b1c8e0
--- /dev/null
+++ b/packages/const/src/skill.ts
@@ -0,0 +1,27 @@
+/**
+ * DataTransfer MIME type used when dragging a skill chip from the working
+ * sidebar into the chat input. A custom (non-`Files`) type so the file-upload
+ * drop zone ignores it — it only reacts to `Files`.
+ */
+export const SKILL_DRAG_MIME = 'application/x-lobe-skill';
+
+/**
+ * Identifier prefix for agent-document skill bundles ("智能体 Skills" —
+ * `agent_document` rows with `isSkillBundle=true`). Mirrors the unified VFS
+ * skill namespace `./lobe/skills/agent/skills/<name>` flattened to a single
+ * token, so we can tell these apart from builtin / DB skill names anywhere an
+ * identifier travels (SkillEngine meta, `<skill name="…">` tag, activateSkill
+ * runtime resolution).
+ *
+ * The trailing `:` is part of the prefix so the runtime can `startsWith` /
+ * `slice` cheaply without re-introducing the separator.
+ */
+export const AGENT_SKILLS_IDENTIFIER_PREFIX = 'agent-skills:';
+
+export const buildAgentSkillIdentifier = (filename: string): string =>
+ `${AGENT_SKILLS_IDENTIFIER_PREFIX}${filename}`;
+
+export const parseAgentSkillIdentifier = (identifier: string): string | undefined =>
+ identifier.startsWith(AGENT_SKILLS_IDENTIFIER_PREFIX)
+ ? identifier.slice(AGENT_SKILLS_IDENTIFIER_PREFIX.length)
+ : undefined;
diff --git a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
index f1512f9fdc1..bb0ee920d21 100644
--- a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
+++ b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
@@ -17,6 +17,7 @@ export const CODEX_CLI_INSTALL_COMMANDS = [
export const HeterogeneousAgentSessionErrorCode = {
AuthRequired: 'auth_required',
CliNotFound: 'cli_not_found',
+ Overloaded: 'overloaded',
RateLimit: 'rate_limit',
ResumeCwdMismatch: 'resume_cwd_mismatch',
ResumeThreadNotFound: 'resume_thread_not_found',
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
index efecc426826..94f581e4dcf 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
@@ -54,6 +54,48 @@ describe('ClaudeCodeAdapter', () => {
);
});
+ it('classifies overloaded failures from api_error_status 529 result events', () => {
+ const adapter = new ClaudeCodeAdapter();
+ const rawError =
+ 'API Error: 529 {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}';
+
+ adapter.adapt({ subtype: 'init', type: 'system' });
+ const events = adapter.adapt({
+ api_error_status: 529,
+ is_error: true,
+ result: rawError,
+ type: 'result',
+ });
+
+ expect(events.map((e) => e.type)).toEqual(['stream_end', 'error']);
+ expect(events[1].data).toMatchObject({
+ agentType: 'claude-code',
+ clearEchoedContent: true,
+ code: 'overloaded',
+ message: rawError,
+ stderr: rawError,
+ });
+ });
+
+ it('classifies overloaded failures from result text alone', () => {
+ const adapter = new ClaudeCodeAdapter();
+ const rawError = 'Overloaded';
+
+ adapter.adapt({ subtype: 'init', type: 'system' });
+ const events = adapter.adapt({
+ is_error: true,
+ result: rawError,
+ type: 'result',
+ });
+
+ expect(events.map((e) => e.type)).toEqual(['stream_end', 'error']);
+ expect(events[1].data).toMatchObject({
+ agentType: 'claude-code',
+ code: 'overloaded',
+ message: rawError,
+ });
+ });
+
it('classifies rate-limit failures from paired rate_limit_event + result events', () => {
const adapter = new ClaudeCodeAdapter();
const rawError = "You've hit your limit · resets 9am (Asia/Shanghai)";
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
index 4056f05ca72..6584f486ab5 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
@@ -185,6 +185,12 @@ const CLI_AUTH_REQUIRED_PATTERNS = [
const CLI_RATE_LIMIT_PATTERNS = [/you'?ve hit your limit/i, /rate limit/i] as const;
+const CLI_OVERLOADED_PATTERNS = [
+ /overloaded_error/i,
+ /\boverloaded\b/i,
+ /api error:\s*529\b/i,
+] as const;
+
const getCliResultMessage = (result: unknown): string | undefined => {
if (typeof result === 'string') return result;
if (
@@ -239,6 +245,27 @@ const toRateLimitInfo = (value: unknown): HeterogeneousRateLimitInfo | undefined
};
};
+const getOverloadedTerminalError = (
+ result: unknown,
+ apiErrorStatus?: unknown,
+): HeterogeneousTerminalErrorData | undefined => {
+ const rawMessage = getCliResultMessage(result);
+ const looksOverloaded =
+ apiErrorStatus === 529 ||
+ (!!rawMessage && CLI_OVERLOADED_PATTERNS.some((pattern) => pattern.test(rawMessage)));
+
+ if (!looksOverloaded || !rawMessage) return;
+
+ return {
+ agentType: 'claude-code',
+ clearEchoedContent: true,
+ code: 'overloaded',
+ error: rawMessage,
+ message: rawMessage,
+ stderr: rawMessage,
+ };
+};
+
const getRateLimitTerminalError = (
result: unknown,
rateLimitInfo?: HeterogeneousRateLimitInfo,
@@ -1160,6 +1187,7 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
? this.makeEvent(
'error',
rateLimitError ||
+ getOverloadedTerminalError(raw.result, raw.api_error_status) ||
getAuthRequiredTerminalError(raw.result) || {
error: resultMessage,
message: resultMessage,
diff --git a/src/features/ChatInput/Desktop/index.tsx b/src/features/ChatInput/Desktop/index.tsx
index 51a5f8a160e..c1589efca31 100644
--- a/src/features/ChatInput/Desktop/index.tsx
+++ b/src/features/ChatInput/Desktop/index.tsx
@@ -20,6 +20,7 @@ import { systemStatusSelectors } from '@/store/global/selectors';
import { type ActionToolbarProps } from '../ActionBar';
import ActionBar from '../ActionBar';
import InputEditor from '../InputEditor';
+import { useSkillDrop } from '../InputEditor/ActionTag/useSkillDrop';
import { type PlaceholderVariant } from '../InputEditor/Placeholder';
import RuntimeConfig from '../RuntimeConfig';
import SendArea from '../SendArea';
@@ -119,6 +120,7 @@ const DesktopChatInput = memo<DesktopChatInputProps>(
const chatKey = useChatStore(chatSelectors.currentChatKey);
const setExpand = useChatInputStore((s) => s.setExpand);
+ const skillDrop = useSkillDrop();
useEffect(() => {
if (editor) editor.focus();
@@ -149,6 +151,8 @@ const DesktopChatInput = memo<DesktopChatInputProps>(
className={cx(styles.container, expand && styles.fullscreen)}
gap={8}
paddingBlock={expand ? 0 : showFootnote ? '0 12px' : '0 8px'}
+ onDragOver={skillDrop.onDragOver}
+ onDrop={skillDrop.onDrop}
>
<ChatInput
data-testid="chat-input"
diff --git a/src/features/ChatInput/InputEditor/ActionTag/ActionMention.tsx b/src/features/ChatInput/InputEditor/ActionTag/ActionMention.tsx
index 310d8a0b335..f01af21d0e5 100644
--- a/src/features/ChatInput/InputEditor/ActionTag/ActionMention.tsx
+++ b/src/features/ChatInput/InputEditor/ActionTag/ActionMention.tsx
@@ -15,6 +15,7 @@ export interface ActionMentionProps {
}
const CATEGORY_ICON: Record<ActionTagCategory, FC<any>> = {
+ agentSkill: SkillsIcon,
command: TerminalIcon,
projectSkill: SkillsIcon,
skill: SkillsIcon,
@@ -22,6 +23,7 @@ const CATEGORY_ICON: Record<ActionTagCategory, FC<any>> = {
};
const CATEGORY_I18N_KEY: Record<ActionTagCategory, string> = {
+ agentSkill: 'actionTag.category.agentSkill',
command: 'actionTag.category.command',
projectSkill: 'actionTag.category.projectSkill',
skill: 'actionTag.category.skill',
@@ -29,6 +31,7 @@ const CATEGORY_I18N_KEY: Record<ActionTagCategory, string> = {
};
const CATEGORY_TOOLTIP_I18N_KEY: Record<ActionTagCategory, string> = {
+ agentSkill: 'actionTag.tooltip.agentSkill',
command: 'actionTag.tooltip.command',
projectSkill: 'actionTag.tooltip.projectSkill',
skill: 'actionTag.tooltip.skill',
@@ -37,8 +40,9 @@ const CATEGORY_TOOLTIP_I18N_KEY: Record<ActionTagCategory, string> = {
const CATEGORY_STYLE_KEY: Record<
ActionTagCategory,
- 'commandTag' | 'projectSkillTag' | 'skillTag' | 'toolTag'
+ 'agentSkillTag' | 'commandTag' | 'projectSkillTag' | 'skillTag' | 'toolTag'
> = {
+ agentSkill: 'agentSkillTag',
command: 'commandTag',
projectSkill: 'projectSkillTag',
skill: 'skillTag',
diff --git a/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.ts b/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.ts
index e7f4da66879..593c68eafa8 100644
--- a/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.ts
+++ b/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.ts
@@ -1,3 +1,4 @@
+import { AGENT_SKILLS_IDENTIFIER_PREFIX } from '@lobechat/const';
import {
type getKernelFromEditor,
ILitexmlService,
@@ -54,6 +55,10 @@ export class ActionTagPlugin {
// Writer: ActionTagNode → markdown
// Skills → <skill name="..." label="..." />
+ // AgentSkill → <skill name="agent-skills:<filename>" label="..." />
+ // Wire format collapses to <skill>; the `agent-skills:`
+ // prefix in the identifier is what the runtime keys off to
+ // route the activation through agentDocumentsService.
// Tools → <tool name="..." label="..." />
// ProjectSkill → bare label text (e.g. `/local-testing`) so the downstream
// CLI agent recognizes its own slash-style skill invocation
@@ -61,7 +66,7 @@ export class ActionTagPlugin {
mdService?.registerMarkdownWriter(ActionTagNode.getType(), (ctx: any, node: any) => {
if ($isActionTagNode(node)) {
const cat = node.actionCategory;
- if (cat === 'skill') {
+ if (cat === 'skill' || cat === 'agentSkill') {
ctx.appendLine(`<skill name="${node.actionType}" label="${node.actionLabel}" />`);
} else if (cat === 'tool') {
ctx.appendLine(`<tool name="${node.actionType}" label="${node.actionLabel}" />`);
@@ -84,7 +89,7 @@ export class ActionTagPlugin {
xmlService?.registerXMLWriter(ActionTagNode.getType(), (node: any, ctx: any) => {
if ($isActionTagNode(node)) {
const cat = node.actionCategory;
- if (cat === 'skill') {
+ if (cat === 'skill' || cat === 'agentSkill') {
return ctx.createXmlNode('skill', { label: node.actionLabel, name: node.actionType });
}
if (cat === 'tool') {
@@ -105,14 +110,20 @@ export class ActionTagPlugin {
return false;
});
- // Read <skill>, <tool>, <projectSkill>, and legacy <action> tags
- const readSkill = (xmlElement: any): SerializedActionTagNode => ({
- actionCategory: 'skill',
- actionLabel: xmlElement.getAttribute('label') || '',
- actionType: (xmlElement.getAttribute('name') || '') as ActionTagType,
- type: ActionTagNode.getType(),
- version: 1,
- });
+ // Read <skill>, <tool>, <projectSkill>, and legacy <action> tags.
+ // Agent-document skills share the <skill> wire format; we recover the
+ // 'agentSkill' UI category from the identifier prefix so reload preserves
+ // the chip's color / icon / tooltip.
+ const readSkill = (xmlElement: any): SerializedActionTagNode => {
+ const name = xmlElement.getAttribute('name') || '';
+ return {
+ actionCategory: name.startsWith(AGENT_SKILLS_IDENTIFIER_PREFIX) ? 'agentSkill' : 'skill',
+ actionLabel: xmlElement.getAttribute('label') || '',
+ actionType: name as ActionTagType,
+ type: ActionTagNode.getType(),
+ version: 1,
+ };
+ };
const readTool = (xmlElement: any): SerializedActionTagNode => ({
actionCategory: 'tool',
actionLabel: xmlElement.getAttribute('label') || '',
diff --git a/src/features/ChatInput/InputEditor/ActionTag/skillDragData.ts b/src/features/ChatInput/InputEditor/ActionTag/skillDragData.ts
new file mode 100644
index 00000000000..3e4b4f03815
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ActionTag/skillDragData.ts
@@ -0,0 +1,159 @@
+import { SKILL_DRAG_MIME } from '@lobechat/const';
+import { cssVar } from 'antd-style';
+import type React from 'react';
+
+import type { ActionTagCategory, ActionTagType } from './types';
+
+/**
+ * Payload serialized into the drag `dataTransfer`. Mirrors the action-tag node
+ * fields so the drop handler can dispatch `INSERT_ACTION_TAG_COMMAND` directly.
+ */
+export interface SkillDragPayload {
+ category: ActionTagCategory;
+ label: string;
+ type: ActionTagType;
+}
+
+/**
+ * Write only our custom MIME — no `text/plain` fallback. The Lexical chat
+ * input reacts to `text/plain` drops and would race with `useSkillDrop`,
+ * breaking every skill drag. Drops on non-editor targets silently do nothing.
+ */
+export const writeSkillDragData = (dataTransfer: DataTransfer, payload: SkillDragPayload): void => {
+ dataTransfer.setData(SKILL_DRAG_MIME, JSON.stringify(payload));
+ dataTransfer.effectAllowed = 'copy';
+};
+
+/**
+ * Resolve a `var(--x)` reference (e.g. from antd-style `cssVar.*`) to its
+ * concrete computed value in the context of `ctx`. Lets the drag preview live
+ * on `document.body` (free of transformed ancestors that would break
+ * fixed-position cursor tracking) while still picking up the themed token.
+ */
+const resolveCssVar = (ref: string, ctx: Element): string => {
+ const name = /var\((--[^\s),]+)/.exec(ref)?.[1];
+ if (!name) return ref;
+ return getComputedStyle(ctx).getPropertyValue(name).trim() || ref;
+};
+
+/** Vertical gap between the cursor and the bottom of the floating chip. */
+const DRAG_GAP = 0;
+
+/**
+ * Position the chip centered horizontally on the cursor and floating just above
+ * it. The trailing `translate(-50%, -100%)` shifts the element by its own size,
+ * so it works regardless of the chip's width/height.
+ */
+const dragTransform = (x: number, y: number) =>
+ `translate(${x}px, ${y}px) translate(-50%, calc(-100% - ${DRAG_GAP}px))`;
+
+/**
+ * Render a custom "icon + name" chip that follows the cursor during the drag.
+ *
+ * We suppress the browser's native drag image (a bitmap snapshot the OS draws
+ * with its own drop shadow / rounding that no CSS can remove) by handing
+ * `setDragImage` an invisible 1×1 element, then position our own element under
+ * the cursor via the document-level `dragover` event — the `drag` event reports
+ * 0,0 coordinates in Chrome, so it can't be used for tracking.
+ *
+ * The skill icon is cloned from the dragged row so the chip stays faithful to
+ * whichever group rendered it.
+ */
+const setSkillDragImage = (event: React.DragEvent, label: string): void => {
+ if (typeof document === 'undefined') return;
+
+ const host = event.currentTarget;
+
+ // Suppress the native drag image with an invisible ghost.
+ const ghost = document.createElement('div');
+ Object.assign(ghost.style, {
+ height: '1px',
+ left: '-9999px',
+ opacity: '0',
+ position: 'fixed',
+ top: '-9999px',
+ width: '1px',
+ });
+ document.body.append(ghost);
+ event.dataTransfer.setDragImage(ghost, 0, 0);
+
+ const preview = document.createElement('div');
+ Object.assign(preview.style, {
+ alignItems: 'center',
+ background: resolveCssVar(cssVar.colorBgElevated, host),
+ border: `1px solid ${resolveCssVar(cssVar.colorBorderSecondary, host)}`,
+ borderRadius: '10px',
+ color: resolveCssVar(cssVar.colorText, host),
+ display: 'inline-flex',
+ fontSize: '13px',
+ gap: '8px',
+ left: '0',
+ lineHeight: '1',
+ maxWidth: '280px',
+ padding: '8px 14px',
+ pointerEvents: 'none',
+ position: 'fixed',
+ top: '0',
+ transform: dragTransform(event.clientX, event.clientY),
+ whiteSpace: 'nowrap',
+ zIndex: '9999',
+ });
+
+ // Row layout is: [chevron svg] [skill icon svg] [name] [count]. Take the last
+ // svg so we always grab the skill icon, never the chevron.
+ const svgs = Array.from(host.querySelectorAll('svg'));
+ const iconSvg = svgs.at(-1);
+ if (iconSvg) {
+ const iconClone = iconSvg.cloneNode(true) as SVGElement;
+ iconClone.style.flexShrink = '0';
+ iconClone.style.color = resolveCssVar(cssVar.colorTextTertiary, host);
+ preview.append(iconClone);
+ }
+
+ const text = document.createElement('span');
+ text.textContent = label;
+ text.style.overflow = 'hidden';
+ text.style.textOverflow = 'ellipsis';
+ preview.append(text);
+
+ document.body.append(preview);
+
+ const move = (e: DragEvent) => {
+ preview.style.transform = dragTransform(e.clientX, e.clientY);
+ };
+ const cleanup = () => {
+ document.removeEventListener('dragover', move);
+ preview.remove();
+ ghost.remove();
+ };
+
+ document.addEventListener('dragover', move);
+ host.addEventListener('dragend', cleanup, { once: true });
+};
+
+/**
+ * Start a skill drag: write the payload and swap in the custom drag image.
+ */
+export const startSkillDrag = (event: React.DragEvent, payload: SkillDragPayload): void => {
+ writeSkillDragData(event.dataTransfer, payload);
+ setSkillDragImage(event, payload.label);
+};
+
+export const readSkillDragData = (dataTransfer: DataTransfer): SkillDragPayload | undefined => {
+ const raw = dataTransfer.getData(SKILL_DRAG_MIME);
+ if (!raw) return undefined;
+
+ try {
+ const parsed = JSON.parse(raw) as Partial<SkillDragPayload>;
+ if (!parsed || typeof parsed.type !== 'string' || typeof parsed.category !== 'string') {
+ return undefined;
+ }
+ return {
+ category: parsed.category,
+ label: typeof parsed.label === 'string' ? parsed.label : parsed.type,
+ type: parsed.type,
+ };
+ } catch {
+ return undefined;
+ }
+};
diff --git a/src/features/ChatInput/InputEditor/ActionTag/style.ts b/src/features/ChatInput/InputEditor/ActionTag/style.ts
index ed48677c8bc..7d1133175dc 100644
--- a/src/features/ChatInput/InputEditor/ActionTag/style.ts
+++ b/src/features/ChatInput/InputEditor/ActionTag/style.ts
@@ -27,6 +27,9 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
actionTagLabel: css`
font-weight: 500;
`,
+ agentSkillTag: css`
+ ${colored(cssVar.colorSuccess, cssVar.borderRadius)}
+ `,
commandTag: css`
${colored(cssVar.purple, cssVar.borderRadius)}
`,
diff --git a/src/features/ChatInput/InputEditor/ActionTag/types.ts b/src/features/ChatInput/InputEditor/ActionTag/types.ts
index 4f311d6b5a7..98265c6ac1a 100644
--- a/src/features/ChatInput/InputEditor/ActionTag/types.ts
+++ b/src/features/ChatInput/InputEditor/ActionTag/types.ts
@@ -7,8 +7,11 @@
* 4. ProjectSkill — Hetero-agent project skill (e.g. `.agents/skills/<name>/SKILL.md`),
* inserted via slash menu, serialized as literal `/skill-name` so the
* underlying CLI agent resolves and runs the skill itself.
+ * 5. AgentSkill — Agent-document skill bundle from `agentDocumentService`; the runtime
+ * resolves the chip's identifier (`agent-document:<filename>`) against
+ * the agent's document store at preload time.
*/
-export type ActionTagCategory = 'command' | 'skill' | 'tool' | 'projectSkill';
+export type ActionTagCategory = 'command' | 'skill' | 'tool' | 'projectSkill' | 'agentSkill';
// Built-in commands: client-side intercepted, never sent to AI
export type CommandType = 'compact' | 'newTopic';
diff --git a/src/features/ChatInput/InputEditor/ActionTag/useSkillDrop.ts b/src/features/ChatInput/InputEditor/ActionTag/useSkillDrop.ts
new file mode 100644
index 00000000000..f3224544907
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ActionTag/useSkillDrop.ts
@@ -0,0 +1,55 @@
+import { SKILL_DRAG_MIME } from '@lobechat/const';
+import type React from 'react';
+import { useCallback } from 'react';
+
+import { useChatInputStore } from '../../store';
+import { INSERT_ACTION_TAG_COMMAND, type InsertActionTagPayload } from './command';
+import { readSkillDragData } from './skillDragData';
+
+interface UseSkillDropResult {
+ onDragOver: (event: React.DragEvent) => void;
+ onDrop: (event: React.DragEvent) => void;
+}
+
+/**
+ * Handles skill chips dragged from the working sidebar into the chat input.
+ *
+ * Reacts only to the custom {@link SKILL_DRAG_MIME} payload, so it never
+ * interferes with the file-upload drop zone (which keys off the `Files` type).
+ * On drop it inserts the matching action tag — identical to picking the skill
+ * from the `/` menu.
+ */
+export const useSkillDrop = (): UseSkillDropResult => {
+ const editor = useChatInputStore((s) => s.editor);
+
+ const onDragOver = useCallback((event: React.DragEvent) => {
+ if (!event.dataTransfer.types.includes(SKILL_DRAG_MIME)) return;
+ // preventDefault marks this element as a valid drop target.
+ event.preventDefault();
+ event.dataTransfer.dropEffect = 'copy';
+ }, []);
+
+ const onDrop = useCallback(
+ (event: React.DragEvent) => {
+ if (!event.dataTransfer.types.includes(SKILL_DRAG_MIME)) return;
+ const payload = readSkillDragData(event.dataTransfer);
+ if (!payload) return;
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ if (!editor) return;
+
+ editor.focus();
+ const command: InsertActionTagPayload = {
+ category: payload.category,
+ label: payload.label,
+ type: payload.type,
+ };
+ editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, command);
+ },
+ [editor],
+ );
+
+ return { onDragOver, onDrop };
+};
diff --git a/src/features/ChatInput/InputEditor/useMentionCategories.tsx b/src/features/ChatInput/InputEditor/useMentionCategories.tsx
index f22541a8ecd..06a6dfadbac 100644
--- a/src/features/ChatInput/InputEditor/useMentionCategories.tsx
+++ b/src/features/ChatInput/InputEditor/useMentionCategories.tsx
@@ -2,6 +2,7 @@ import { Avatar, Icon } from '@lobehub/ui';
import { SkillsIcon } from '@lobehub/ui/icons';
import { Bot, MessageSquareText, Users, Wrench } from 'lucide-react';
import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
@@ -21,6 +22,7 @@ const MAX_TOPIC_LABEL = 50;
type MenuOptionWithMetadata = { key: string; metadata?: Record<string, unknown> };
export const useMentionCategories = (): MentionCategory[] => {
+ const { t } = useTranslation('chat');
const currentAgentId = useAgentId();
const allAgents = useHomeStore(homeAgentListSelectors.allAgents);
@@ -67,7 +69,7 @@ export const useMentionCategories = (): MentionCategory[] => {
id: 'agent',
icon: <Icon icon={Bot} size={16} />,
items,
- label: 'Agents',
+ label: t('mention.category.agents'),
});
}
}
@@ -86,7 +88,7 @@ export const useMentionCategories = (): MentionCategory[] => {
id: 'member',
icon: <Icon icon={Users} size={16} />,
items,
- label: 'Members',
+ label: t('mention.category.members'),
});
}
}
@@ -117,7 +119,7 @@ export const useMentionCategories = (): MentionCategory[] => {
id: 'topic',
icon: <Icon icon={MessageSquareText} size={16} />,
items,
- label: 'Topics',
+ label: t('mention.category.topics'),
});
}
}
@@ -139,7 +141,7 @@ export const useMentionCategories = (): MentionCategory[] => {
type: 'skill' as const,
},
})),
- label: 'Skills',
+ label: t('mention.category.skills'),
});
}
@@ -160,7 +162,7 @@ export const useMentionCategories = (): MentionCategory[] => {
type: 'tool' as const,
},
})),
- label: 'Tools',
+ label: t('mention.category.tools'),
});
}
@@ -173,5 +175,6 @@ export const useMentionCategories = (): MentionCategory[] => {
isGroupChat,
externalMentionItems,
enabledSkills,
+ t,
]);
};
diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsx
index b43f30aa861..cff6bc4de8e 100644
--- a/src/features/Conversation/Error/index.tsx
+++ b/src/features/Conversation/Error/index.tsx
@@ -77,6 +77,7 @@ const OllamaSetupGuide = dynamic(() => import('./OllamaSetupGuide'), {
const HETEROGENEOUS_AGENT_STATUS_GUIDE_ERROR_CODES = new Set<string>([
HeterogeneousAgentSessionErrorCode.AuthRequired,
HeterogeneousAgentSessionErrorCode.CliNotFound,
+ HeterogeneousAgentSessionErrorCode.Overloaded,
HeterogeneousAgentSessionErrorCode.RateLimit,
]);
diff --git a/src/features/Conversation/Markdown/plugins/Skill/Render.tsx b/src/features/Conversation/Markdown/plugins/Skill/Render.tsx
new file mode 100644
index 00000000000..30d2eed3ce1
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/Skill/Render.tsx
@@ -0,0 +1,34 @@
+'use client';
+
+import isEqual from 'fast-deep-equal';
+import { memo } from 'react';
+
+import { ActionMention } from '@/features/ChatInput/InputEditor/ActionTag/ActionMention';
+
+import { type MarkdownElementProps } from '../type';
+
+interface SkillNodeProps {
+ label?: string;
+ name?: string;
+}
+
+/**
+ * Render `<skill name="…" label="…" />` tags that survive in persisted user
+ * messages back into the same chip the editor shows during composition. Without
+ * this plugin react-markdown leaves the literal tag text in the bubble, which
+ * is what users were seeing before.
+ *
+ * We don't look up the identifier in any registry — the tag already carries
+ * both the `name` (runtime identifier) and the human-readable `label`, so the
+ * chip just mirrors what was inserted.
+ */
+const Render = memo<MarkdownElementProps<SkillNodeProps>>(({ node, children }) => {
+ const { label, name } = node?.properties || {};
+ const displayLabel = label || name || (typeof children === 'string' ? children : undefined);
+ if (!displayLabel) return null;
+ return <ActionMention category="skill" label={displayLabel} />;
+}, isEqual);
+
+Render.displayName = 'SkillRender';
+
+export default Render;
diff --git a/src/features/Conversation/Markdown/plugins/Skill/index.ts b/src/features/Conversation/Markdown/plugins/Skill/index.ts
new file mode 100644
index 00000000000..7401b8e5118
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/Skill/index.ts
@@ -0,0 +1,14 @@
+import { SKILL_TAG } from '@lobechat/const';
+
+import { createRemarkSelfClosingTagPlugin } from '../remarkPlugins/createRemarkSelfClosingTagPlugin';
+import { type MarkdownElement } from '../type';
+import Render from './Render';
+
+const Skill: MarkdownElement = {
+ Component: Render,
+ remarkPlugin: createRemarkSelfClosingTagPlugin(SKILL_TAG),
+ scope: 'user',
+ tag: SKILL_TAG,
+};
+
+export default Skill;
diff --git a/src/features/Conversation/Markdown/plugins/Tool/Render.tsx b/src/features/Conversation/Markdown/plugins/Tool/Render.tsx
new file mode 100644
index 00000000000..496b6b480ac
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/Tool/Render.tsx
@@ -0,0 +1,28 @@
+'use client';
+
+import isEqual from 'fast-deep-equal';
+import { memo } from 'react';
+
+import { ActionMention } from '@/features/ChatInput/InputEditor/ActionTag/ActionMention';
+
+import { type MarkdownElementProps } from '../type';
+
+interface ToolNodeProps {
+ label?: string;
+ name?: string;
+}
+
+/**
+ * Counterpart to the Skill plugin for `<tool name="…" label="…" />` tags —
+ * see `../Skill/Render.tsx` for the rationale.
+ */
+const Render = memo<MarkdownElementProps<ToolNodeProps>>(({ node, children }) => {
+ const { label, name } = node?.properties || {};
+ const displayLabel = label || name || (typeof children === 'string' ? children : undefined);
+ if (!displayLabel) return null;
+ return <ActionMention category="tool" label={displayLabel} />;
+}, isEqual);
+
+Render.displayName = 'ToolRender';
+
+export default Render;
diff --git a/src/features/Conversation/Markdown/plugins/Tool/index.ts b/src/features/Conversation/Markdown/plugins/Tool/index.ts
new file mode 100644
index 00000000000..562da77605e
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/Tool/index.ts
@@ -0,0 +1,14 @@
+import { TOOL_TAG } from '@lobechat/const';
+
+import { createRemarkSelfClosingTagPlugin } from '../remarkPlugins/createRemarkSelfClosingTagPlugin';
+import { type MarkdownElement } from '../type';
+import Render from './Render';
+
+const Tool: MarkdownElement = {
+ Component: Render,
+ remarkPlugin: createRemarkSelfClosingTagPlugin(TOOL_TAG),
+ scope: 'user',
+ tag: TOOL_TAG,
+};
+
+export default Tool;
diff --git a/src/features/Conversation/Markdown/plugins/index.ts b/src/features/Conversation/Markdown/plugins/index.ts
index e91458d00a3..17a21e47fdd 100644
--- a/src/features/Conversation/Markdown/plugins/index.ts
+++ b/src/features/Conversation/Markdown/plugins/index.ts
@@ -4,8 +4,10 @@ import LobeArtifact from './LobeArtifact';
import LobeThinking from './LobeThinking';
import LocalFile from './LocalFile';
import Mention from './Mention';
+import Skill from './Skill';
import Task from './Task';
import Thinking from './Thinking';
+import Tool from './Tool';
import { type MarkdownElement } from './type';
import UserFeedback from './UserFeedback';
@@ -17,6 +19,8 @@ export const markdownElements: MarkdownElement[] = [
LobeThinking,
LocalFile,
Mention,
+ Skill,
+ Tool,
Task,
UserFeedback,
ImageSearchRef,
diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.test.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.test.tsx
index 308bef7819f..095e4efa919 100644
--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.test.tsx
+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.test.tsx
@@ -41,6 +41,7 @@ vi.mock('antd-style', () => ({
vi.mock('lucide-react', () => ({
ExternalLink: () => <span>ExternalLink Icon</span>,
+ RotateCcw: () => <span>Retry Icon</span>,
Settings2: () => <span>Settings Icon</span>,
}));
@@ -81,6 +82,12 @@ vi.mock('react-i18next', () => ({
'cliAuthGuide.errorDetails': 'Error details',
'cliAuthGuide.runCommand': 'Run this in Terminal',
'cliAuthGuide.title': `Sign in to ${options?.name ?? ''}`,
+ 'cliOverloadedGuide.actions.retry': 'Retry',
+ 'cliOverloadedGuide.desc': `${options?.name ?? ''}'s upstream model service is temporarily overloaded. This usually clears in a moment.`,
+ 'cliOverloadedGuide.errorDetails': 'Error details',
+ 'cliOverloadedGuide.retryHint':
+ 'Wait a few seconds and retry. If it keeps failing, the provider may be having a wider incident.',
+ 'cliOverloadedGuide.title': `${options?.name ?? ''} is temporarily overloaded`,
'cliRateLimitGuide.actions.openSystemTools': 'Open System Tools',
'cliRateLimitGuide.afterReset':
'Wait until the reset time, then retry your message. If you are using API authorization, you can also check your provider quota and billing status.',
@@ -257,6 +264,41 @@ describe('HeterogeneousAgentStatusGuide', () => {
}
});
+ it('renders overloaded guidance with retry action', () => {
+ const onRetry = vi.fn();
+ render(
+ <HeterogeneousAgentStatusGuide
+ agentType={'claude-code'}
+ error={{
+ agentType: 'claude-code',
+ code: HeterogeneousAgentSessionErrorCode.Overloaded,
+ message:
+ 'API Error: 529 {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}',
+ stderr:
+ 'API Error: 529 {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}',
+ }}
+ onRetry={onRetry}
+ />,
+ );
+
+ expect(screen.getByText('Claude Code is temporarily overloaded')).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ "Claude Code's upstream model service is temporarily overloaded. This usually clears in a moment.",
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ 'Wait a few seconds and retry. If it keeps failing, the provider may be having a wider incident.',
+ ),
+ ).toBeInTheDocument();
+ expect(screen.getByText('Error details')).toBeInTheDocument();
+
+ const retryButton = screen.getByRole('button', { name: 'Retry' });
+ retryButton.click();
+ expect(onRetry).toHaveBeenCalledTimes(1);
+ });
+
it('formats reset time with the active i18n locale instead of the system locale', () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-04-23T13:27:00+08:00'));
diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx
index 6b784c44d0d..8bd59d60ead 100644
--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx
+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx
@@ -6,6 +6,7 @@ import { memo } from 'react';
import { resolveHeterogeneousAgentGuideConfig } from './config';
import AuthRequiredState from './states/AuthRequiredState';
import CliInstallState from './states/CliInstallState';
+import OverloadedState from './states/OverloadedState';
import RateLimitState from './states/RateLimitState';
import type { HeterogeneousAgentStatusGuideProps } from './types';
@@ -32,6 +33,10 @@ const HeterogeneousAgentStatusGuide = memo<HeterogeneousAgentStatusGuideProps>(
return <RateLimitState {...stateProps} />;
}
+ case HeterogeneousAgentSessionErrorCode.Overloaded: {
+ return <OverloadedState {...stateProps} />;
+ }
+
default: {
return <CliInstallState {...stateProps} />;
}
diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/states/OverloadedState.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/OverloadedState.tsx
new file mode 100644
index 00000000000..1f3bb039147
--- /dev/null
+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/OverloadedState.tsx
@@ -0,0 +1,57 @@
+import { Flexbox, Highlighter, Text } from '@lobehub/ui';
+import { useTranslation } from 'react-i18next';
+
+import GuideActions from '../GuideActions';
+import GuideShell from '../GuideShell';
+import type { HeterogeneousAgentGuideStateProps } from '../types';
+
+const OverloadedState = ({
+ config,
+ error,
+ onRetry,
+ variant,
+}: HeterogeneousAgentGuideStateProps) => {
+ const { t } = useTranslation('chat');
+ const rawErrorDetails = error?.stderr || error?.message;
+
+ return (
+ <GuideShell
+ icon={<config.icon size={24} />}
+ title={t('cliOverloadedGuide.title', { name: config.title })}
+ variant={variant}
+ actions={
+ <GuideActions retryLabel={t('cliOverloadedGuide.actions.retry')} onRetry={onRetry} />
+ }
+ headerDescription={
+ <Text type="secondary">{t('cliOverloadedGuide.desc', { name: config.title })}</Text>
+ }
+ >
+ <Text style={{ fontSize: 12 }} type="secondary">
+ {t('cliOverloadedGuide.retryHint')}
+ </Text>
+
+ {rawErrorDetails && (
+ <Flexbox gap={6}>
+ <Text strong style={{ fontSize: 12 }}>
+ {t('cliOverloadedGuide.errorDetails')}
+ </Text>
+ <Highlighter
+ wrap
+ actionIconSize={'small'}
+ language={'log'}
+ padding={12}
+ variant={'outlined'}
+ style={{
+ maxHeight: 200,
+ overflow: 'auto',
+ }}
+ >
+ {rawErrorDetails}
+ </Highlighter>
+ </Flexbox>
+ )}
+ </GuideShell>
+ );
+};
+
+export default OverloadedState;
diff --git a/src/features/SkillStore/SkillStoreContent.tsx b/src/features/SkillStore/SkillStoreContent.tsx
index 76715f04c76..dd1c11dd503 100644
--- a/src/features/SkillStore/SkillStoreContent.tsx
+++ b/src/features/SkillStore/SkillStoreContent.tsx
@@ -27,7 +27,7 @@ export const SkillStoreContent = () => {
const options: SegmentedOptions = [
{ label: t('skillStore.tabs.lobehub'), value: SkillStoreTab.LobeHub },
- { label: 'Skills', value: SkillStoreTab.Skills },
+ { label: t('skillStore.tabs.skills'), value: SkillStoreTab.Skills },
{ label: t('skillStore.tabs.mcp'), value: SkillStoreTab.MCP },
{ label: t('skillStore.tabs.custom'), value: SkillStoreTab.Custom },
];
diff --git a/src/features/SkillsList/SkillSection.tsx b/src/features/SkillsList/SkillSection.tsx
new file mode 100644
index 00000000000..a2c9b4e5787
--- /dev/null
+++ b/src/features/SkillsList/SkillSection.tsx
@@ -0,0 +1,139 @@
+import { Accordion, AccordionItem, Center, Flexbox, Text } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { memo, type ReactNode, useState } from 'react';
+
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+
+export interface SkillSectionHeader {
+ /** Wrap the section in a collapsible Accordion. Defaults to true. */
+ collapsible?: boolean;
+ count?: number;
+ /** Initial expansion state when collapsible. Defaults to true. */
+ defaultExpanded?: boolean;
+ title: string;
+}
+
+export interface SkillSectionProps {
+ children?: ReactNode;
+ emptyText?: string;
+ isEmpty?: boolean;
+ isLoading?: boolean;
+ /**
+ * When provided, wraps content in a header + optional Accordion. Omit to
+ * render `children` flat (the caller controls layout entirely).
+ */
+ sectionHeader?: SkillSectionHeader;
+}
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ count: css`
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ empty: css`
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ flatHeader: css`
+ padding-inline: 4px;
+ `,
+ label: css`
+ font-size: 12px;
+ font-weight: 500;
+ `,
+}));
+
+const ITEM_KEY = 'skill-section';
+
+interface HeaderRowProps {
+ count?: number;
+ title: string;
+}
+
+const HeaderRow = memo<HeaderRowProps>(({ count, title }) => (
+ <Flexbox horizontal align={'center'} gap={6}>
+ <Text className={styles.label} type={'secondary'}>
+ {title}
+ </Text>
+ {typeof count === 'number' && count > 0 && <span className={styles.count}>{count}</span>}
+ </Flexbox>
+));
+
+HeaderRow.displayName = 'SkillSectionHeaderRow';
+
+interface BodyProps {
+ children?: ReactNode;
+ emptyText?: string;
+ isEmpty?: boolean;
+ isLoading?: boolean;
+}
+
+const Body = memo<BodyProps>(({ children, emptyText, isEmpty, isLoading }) => {
+ if (isLoading) {
+ return (
+ <Center paddingBlock={12}>
+ <NeuralNetworkLoading size={24} />
+ </Center>
+ );
+ }
+ if (isEmpty) {
+ return (
+ <Center paddingBlock={8}>
+ <Text className={styles.empty}>{emptyText}</Text>
+ </Center>
+ );
+ }
+ return <>{children}</>;
+});
+
+Body.displayName = 'SkillSectionBody';
+
+const SkillSection = memo<SkillSectionProps>(
+ ({ children, emptyText, isEmpty, isLoading, sectionHeader }) => {
+ // Hook always runs regardless of whether sectionHeader is provided.
+ const [expanded, setExpanded] = useState(sectionHeader?.defaultExpanded ?? true);
+
+ const body = (
+ <Body emptyText={emptyText} isEmpty={isEmpty} isLoading={isLoading}>
+ {children}
+ </Body>
+ );
+
+ if (!sectionHeader) return body;
+
+ const { collapsible = true, count, title } = sectionHeader;
+
+ if (!collapsible) {
+ return (
+ <Flexbox gap={4}>
+ <div className={styles.flatHeader}>
+ <HeaderRow count={count} title={title} />
+ </div>
+ {body}
+ </Flexbox>
+ );
+ }
+
+ return (
+ <Accordion
+ expandedKeys={expanded ? [ITEM_KEY] : []}
+ gap={4}
+ onExpandedChange={(keys) => setExpanded(keys.length > 0)}
+ >
+ <AccordionItem
+ itemKey={ITEM_KEY}
+ paddingBlock={2}
+ paddingInline={4}
+ title={<HeaderRow count={count} title={title} />}
+ >
+ {body}
+ </AccordionItem>
+ </Accordion>
+ );
+ },
+);
+
+SkillSection.displayName = 'SkillSection';
+
+export default SkillSection;
diff --git a/src/features/AgentDocumentsExplorer/SkillsList.tsx b/src/features/SkillsList/SkillsList.tsx
similarity index 70%
rename from src/features/AgentDocumentsExplorer/SkillsList.tsx
rename to src/features/SkillsList/SkillsList.tsx
index 592aa0b1a36..81b474412c4 100644
--- a/src/features/AgentDocumentsExplorer/SkillsList.tsx
+++ b/src/features/SkillsList/SkillsList.tsx
@@ -2,6 +2,7 @@ import { Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';
import { SkillsIcon } from '@lobehub/ui/icons';
import { createStaticStyles } from 'antd-style';
import { ChevronRightIcon, FileIcon, FolderIcon } from 'lucide-react';
+import type React from 'react';
import { memo, useCallback, useMemo, useState } from 'react';
export interface SkillListItem {
@@ -16,6 +17,12 @@ interface SkillsListProps {
items: SkillListItem[];
onOpenFile?: (item: SkillListItem, relativePath: string) => void;
onOpenSkill?: (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`
+ * (see `writeSkillDragData`), letting the chat input resolve it on drop.
+ */
+ onSkillDragStart?: (item: SkillListItem, event: React.DragEvent) => void;
}
const styles = createStaticStyles(({ css, cssVar }) => ({
@@ -206,76 +213,86 @@ TreeRow.displayName = 'SkillsListTreeRow';
interface SkillRowProps {
expanded: boolean;
item: SkillListItem;
+ onDragStart?: (event: React.DragEvent) => void;
onOpenFile?: (relativePath: string) => void;
onOpenSkill?: () => void;
onToggle: () => void;
}
-const SkillRow = memo<SkillRowProps>(({ expanded, item, onOpenFile, onOpenSkill, onToggle }) => {
- const tree = useMemo(() => buildSkillTree(item.files), [item.files]);
- const [expandedFolders, setExpandedFolders] = useState<Set<string>>(() => new Set());
+const SkillRow = memo<SkillRowProps>(
+ ({ expanded, item, onDragStart, onOpenFile, onOpenSkill, onToggle }) => {
+ const tree = useMemo(() => buildSkillTree(item.files), [item.files]);
+ const [expandedFolders, setExpandedFolders] = useState<Set<string>>(() => new Set());
- const toggleFolder = useCallback((folderPath: string) => {
- setExpandedFolders((prev) => {
- const next = new Set(prev);
- if (next.has(folderPath)) next.delete(folderPath);
- else next.add(folderPath);
- return next;
- });
- }, []);
+ const toggleFolder = useCallback((folderPath: string) => {
+ setExpandedFolders((prev) => {
+ const next = new Set(prev);
+ if (next.has(folderPath)) next.delete(folderPath);
+ else next.add(folderPath);
+ return next;
+ });
+ }, []);
- return (
- <>
- <Tooltip
- placement={'left'}
- title={
- item.description ? (
- <span className={styles.description}>{item.description}</span>
- ) : undefined
- }
- >
- <Flexbox horizontal align={'center'} className={styles.item} gap={6}>
+ return (
+ <>
+ <Tooltip
+ placement={'left'}
+ title={
+ item.description ? (
+ <span className={styles.description}>{item.description}</span>
+ ) : undefined
+ }
+ >
<Flexbox
+ horizontal
align={'center'}
- justify={'center'}
- style={{ cursor: 'pointer', flexShrink: 0, height: 20, width: 20 }}
- onClick={(e) => {
- e.stopPropagation();
- onToggle();
- }}
+ className={styles.item}
+ draggable={!!onDragStart}
+ gap={6}
+ onDragStart={onDragStart}
>
- <Icon
- className={`${styles.chevron} ${expanded ? styles.chevronExpanded : ''}`}
- icon={ChevronRightIcon}
- size={14}
- />
+ <Flexbox
+ align={'center'}
+ justify={'center'}
+ style={{ cursor: 'pointer', flexShrink: 0, height: 20, width: 20 }}
+ onClick={(e) => {
+ e.stopPropagation();
+ onToggle();
+ }}
+ >
+ <Icon
+ className={`${styles.chevron} ${expanded ? styles.chevronExpanded : ''}`}
+ icon={ChevronRightIcon}
+ size={14}
+ />
+ </Flexbox>
+ <Icon className={styles.itemIcon} icon={SkillsIcon} size={14} />
+ <Text ellipsis style={{ color: 'inherit', flex: 1, minWidth: 0 }} onClick={onOpenSkill}>
+ {item.name}
+ </Text>
+ <span className={styles.itemCount}>{item.fileCount}</span>
</Flexbox>
- <Icon className={styles.itemIcon} icon={SkillsIcon} size={14} />
- <Text ellipsis style={{ color: 'inherit', flex: 1, minWidth: 0 }} onClick={onOpenSkill}>
- {item.name}
- </Text>
- <span className={styles.itemCount}>{item.fileCount}</span>
- </Flexbox>
- </Tooltip>
- {expanded &&
- onOpenFile &&
- tree.map((node) => (
- <TreeRow
- depth={0}
- expanded={expandedFolders}
- key={node.path}
- node={node}
- onOpenFile={onOpenFile}
- onToggleFolder={toggleFolder}
- />
- ))}
- </>
- );
-});
+ </Tooltip>
+ {expanded &&
+ onOpenFile &&
+ tree.map((node) => (
+ <TreeRow
+ depth={0}
+ expanded={expandedFolders}
+ key={node.path}
+ node={node}
+ onOpenFile={onOpenFile}
+ onToggleFolder={toggleFolder}
+ />
+ ))}
+ </>
+ );
+ },
+);
SkillRow.displayName = 'SkillsListSkillRow';
-const SkillsList = memo<SkillsListProps>(({ items, onOpenFile, onOpenSkill }) => {
+const SkillsList = memo<SkillsListProps>(({ items, onOpenFile, onOpenSkill, onSkillDragStart }) => {
const [expanded, setExpanded] = useState<Set<string>>(() => new Set());
const toggle = useCallback((id: string) => {
@@ -294,6 +311,7 @@ const SkillsList = memo<SkillsListProps>(({ items, onOpenFile, onOpenSkill }) =>
expanded={expanded.has(item.id)}
item={item}
key={item.id}
+ onDragStart={onSkillDragStart ? (event) => onSkillDragStart(item, event) : undefined}
onOpenFile={onOpenFile ? (relativePath) => onOpenFile(item, relativePath) : undefined}
onOpenSkill={onOpenSkill ? () => onOpenSkill(item) : undefined}
onToggle={() => toggle(item.id)}
diff --git a/src/features/SkillsList/index.ts b/src/features/SkillsList/index.ts
new file mode 100644
index 00000000000..7c167e56e2c
--- /dev/null
+++ b/src/features/SkillsList/index.ts
@@ -0,0 +1,5 @@
+export type { SkillSectionHeader, SkillSectionProps } from './SkillSection';
+export { default as SkillSection } from './SkillSection';
+export type { SkillListItem } from './SkillsList';
+export { default as SkillsList } from './SkillsList';
+export { useProjectSkills, type UseProjectSkillsResult } from './useProjectSkills';
diff --git a/src/features/SkillsList/useProjectSkills.ts b/src/features/SkillsList/useProjectSkills.ts
new file mode 100644
index 00000000000..9191c9ae998
--- /dev/null
+++ b/src/features/SkillsList/useProjectSkills.ts
@@ -0,0 +1,76 @@
+import { type ListProjectSkillsResult, type ProjectSkillItem } from '@lobechat/electron-client-ipc';
+import path from 'pathe';
+import { useMemo } from 'react';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { localFileService } from '@/services/electron/localFileService';
+import { useChatStore } from '@/store/chat';
+
+import type { SkillListItem } from './SkillsList';
+
+export interface UseProjectSkillsResult {
+ isLoading: boolean;
+ items: SkillListItem[];
+ onOpenFile: (item: SkillListItem, relativePath: string) => void;
+ onOpenSkill: (item: SkillListItem) => void;
+ raw: ListProjectSkillsResult | undefined;
+}
+
+/**
+ * Shared SWR + handlers for filesystem-backed project skills under
+ * `.agents/skills/` / `.claude/skills/` in `workingDirectory`. Powers both
+ * the hetero `SkillsGroup` and the homogeneous `ProjectLevelSkills` section.
+ *
+ * Pass `undefined` to keep the hook inert (no fetch fires) — useful when the
+ * caller hasn't decided whether to render the section yet.
+ */
+export const useProjectSkills = (workingDirectory: string | undefined): UseProjectSkillsResult => {
+ const openLocalFile = useChatStore((s) => s.openLocalFile);
+
+ const { data, isLoading } = useClientDataSWR<ListProjectSkillsResult>(
+ workingDirectory ? ['project-skills', workingDirectory] : null,
+ () => localFileService.listProjectSkills({ scope: workingDirectory! }),
+ { revalidateOnFocus: false, shouldRetryOnError: false },
+ );
+
+ // listProjectSkills approves `data.root` for preview. Hand that exact value
+ // back to openLocalFile so LocalFileProtocolManager.createPreviewUrl's
+ // approved-root check matches; fall back to the requested workingDirectory
+ // while the SWR fetch is in flight.
+ const previewRoot = data?.root || workingDirectory || '';
+
+ const items = useMemo<SkillListItem[]>(
+ () =>
+ (data?.skills ?? []).map((skill) => ({
+ description: skill.description,
+ fileCount: skill.fileCount,
+ files: skill.files,
+ id: skill.skillDir,
+ name: skill.name,
+ })),
+ [data?.skills],
+ );
+
+ const skillByDir = useMemo(() => {
+ const map = new Map<string, ProjectSkillItem>();
+ for (const skill of data?.skills ?? []) map.set(skill.skillDir, skill);
+ return map;
+ }, [data?.skills]);
+
+ const onOpenFile = (item: SkillListItem, relativePath: string) => {
+ const skill = skillByDir.get(item.id);
+ if (!skill) return;
+ openLocalFile({
+ filePath: path.join(skill.skillDir, relativePath),
+ workingDirectory: previewRoot,
+ });
+ };
+
+ const onOpenSkill = (item: SkillListItem) => {
+ const skill = skillByDir.get(item.id);
+ if (!skill) return;
+ openLocalFile({ filePath: skill.path, workingDirectory: previewRoot });
+ };
+
+ return { isLoading, items, onOpenFile, onOpenSkill, raw: data };
+};
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index 783ebf216f0..91098e54721 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -231,6 +231,11 @@ export default {
'memberSelection.selectedAgents': 'Selected ({{count}})',
'memberSelection.setInitialMembers': 'Select Group members',
'members': 'Members',
+ 'mention.category.agents': 'Agents',
+ 'mention.category.members': 'Members',
+ 'mention.category.skills': 'Skills',
+ 'mention.category.tools': 'Tools',
+ 'mention.category.topics': 'Topics',
'mention.title': 'Mention Members',
'messageAction.collapse': 'Collapse Message',
'messageAction.continueGeneration': 'Continue Generating',
@@ -311,6 +316,13 @@ export default {
'cliAuthGuide.errorDetails': 'Error details',
'cliAuthGuide.runCommand': 'Run this in Terminal',
'cliAuthGuide.title': 'Sign in to {{name}}',
+ 'cliOverloadedGuide.actions.retry': 'Retry',
+ 'cliOverloadedGuide.desc':
+ "{{name}}'s upstream model service is temporarily overloaded. This usually clears in a moment.",
+ 'cliOverloadedGuide.errorDetails': 'Error details',
+ 'cliOverloadedGuide.retryHint':
+ 'Wait a few seconds and retry. If it keeps failing, the provider may be having a wider incident.',
+ 'cliOverloadedGuide.title': '{{name}} is temporarily overloaded',
'cliRateLimitGuide.actions.openSystemTools': 'Open System Tools',
'cliRateLimitGuide.actions.retry': 'Retry',
'cliRateLimitGuide.afterReset':
diff --git a/src/locales/default/editor.ts b/src/locales/default/editor.ts
index ffb04c58782..143074e2cfb 100644
--- a/src/locales/default/editor.ts
+++ b/src/locales/default/editor.ts
@@ -35,10 +35,13 @@ export default {
'modifier.acceptAll': 'Keep All',
'modifier.reject': 'Revert',
'modifier.rejectAll': 'Revert All',
+ 'actionTag.category.agentSkill': 'Agent skill',
'actionTag.category.command': 'Command',
'actionTag.category.projectSkill': 'Project skill',
'actionTag.category.skill': 'Skill',
'actionTag.category.tool': 'Tool',
+ 'actionTag.tooltip.agentSkill':
+ "Loads a skill bundle from this agent's documents for the request.",
'actionTag.tooltip.command': 'Runs a client-side slash command before sending.',
'actionTag.tooltip.projectSkill':
"Sent as a slash invocation so the agent's CLI runs the matching project skill.",
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
index 52f2751f560..5bf928c4040 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
@@ -88,7 +88,7 @@ vi.mock('@/features/AgentDocumentsExplorer', () => ({
),
}));
-vi.mock('@/features/AgentDocumentsExplorer/SkillsList', () => {
+vi.mock('@/features/SkillsList', () => {
type Item = { fileCount: number; id: string; name: string };
const SkillsList = ({
items,
@@ -114,7 +114,35 @@ vi.mock('@/features/AgentDocumentsExplorer/SkillsList', () => {
))}
</div>
);
- return { default: SkillsList };
+ // SkillSection is a thin presentational wrapper — the real one only adds
+ // an Accordion / header. For these tests we pass children through and
+ // surface the count so assertions that key off the section header still
+ // work.
+ const SkillSection = ({
+ children,
+ sectionHeader,
+ }: {
+ children?: ReactNode;
+ 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>
+ )}
+ {children}
+ </div>
+ );
+ const useProjectSkills = () => ({
+ isLoading: false,
+ items: [],
+ onOpenFile: () => undefined,
+ onOpenSkill: () => undefined,
+ raw: undefined,
+ });
+ return { SkillSection, SkillsList, useProjectSkills };
});
vi.mock('@/services/agentDocument', () => ({
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
index 5213dce6194..8d6db4d1bbf 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
@@ -1,4 +1,5 @@
-import { Accordion, AccordionItem, ActionIcon, Center, Empty, Flexbox, Text } from '@lobehub/ui';
+import { buildAgentSkillIdentifier } from '@lobechat/const';
+import { ActionIcon, Center, Empty, Flexbox, Text } from '@lobehub/ui';
import { SkillsIcon } from '@lobehub/ui/icons';
import { App } from 'antd';
import { createStaticStyles, cx } from 'antd-style';
@@ -13,7 +14,8 @@ import { useMatch, useNavigate } from 'react-router-dom';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import { DocumentExplorerTree } from '@/features/AgentDocumentsExplorer';
-import SkillsList, { type SkillListItem } from '@/features/AgentDocumentsExplorer/SkillsList';
+import { startSkillDrag } from '@/features/ChatInput/InputEditor/ActionTag/skillDragData';
+import { type SkillListItem, SkillSection, SkillsList } from '@/features/SkillsList';
import { useClientDataSWR } from '@/libs/swr';
import { agentDocumentService, agentDocumentSWRKeys } from '@/services/agentDocument';
import { useAgentStore } from '@/store/agent';
@@ -23,8 +25,6 @@ import { chatPortalSelectors } from '@/store/chat/selectors';
import ProjectLevelSkills from './ProjectLevelSkills';
-const AGENT_SKILLS_ITEM_KEY = 'agent-skills';
-
const PAGE_ROUTE_PATTERN = '/agent/:aid/:topicId/page/:docId?';
dayjs.extend(relativeTime);
@@ -86,19 +86,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
background: ${cssVar.colorFillTertiary};
}
`,
- sectionCount: css`
- font-size: 12px;
- font-variant-numeric: tabular-nums;
- color: ${cssVar.colorTextTertiary};
- `,
- sectionEmpty: css`
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- sectionLabel: css`
- font-size: 12px;
- font-weight: 500;
- `,
title: css`
font-weight: 500;
`,
@@ -282,7 +269,6 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ style, workingDire
const navigate = useNavigate();
const pageMatch = useMatch(PAGE_ROUTE_PATTERN);
const [filter, setFilter] = useState<ResourceFilter>('skills');
- const [agentSkillsExpanded, setAgentSkillsExpanded] = useState(true);
const showProjectSkills = isLocalEnabled && !!workingDirectory;
@@ -339,53 +325,36 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ style, workingDire
);
}
- const renderAgentSkillsList = () =>
- skillItems.length === 0 ? (
- <Center paddingBlock={8}>
- <Text className={styles.sectionEmpty}>{t('workingPanel.skills.emptyAgent')}</Text>
- </Center>
- ) : (
- <SkillsList
- items={skillItems}
- onOpenFile={(item, relativePath) => {
- const view = skillBundleViews.find((v) => v.bundle.documentId === item.id);
- const docId = view?.pathToDocumentId.get(relativePath);
- if (docId) openDocumentByRoute(docId);
- }}
- onOpenSkill={(item) => {
- // Open the SKILL.md (skills/index child) when present; fall back to
- // the bundle itself (orphan bundles surface for recovery).
- const view = skillBundleViews.find((v) => v.bundle.documentId === item.id);
- const indexChild = data.find((doc) => doc.parentId === item.id && doc.isSkillIndex);
- openDocumentByRoute(indexChild?.documentId ?? view?.bundle.documentId ?? item.id);
- }}
- />
- );
-
- const renderAgentSkillsSection = () => (
- <Accordion
- expandedKeys={agentSkillsExpanded ? [AGENT_SKILLS_ITEM_KEY] : []}
- gap={4}
- onExpandedChange={(keys) => setAgentSkillsExpanded(keys.length > 0)}
- >
- <AccordionItem
- itemKey={AGENT_SKILLS_ITEM_KEY}
- paddingBlock={2}
- paddingInline={4}
- title={
- <Flexbox horizontal align={'center'} gap={6}>
- <Text className={styles.sectionLabel} type={'secondary'}>
- {t('workingPanel.skills.section.agent')}
- </Text>
- {skillItems.length > 0 && (
- <span className={styles.sectionCount}>{skillItems.length}</span>
- )}
- </Flexbox>
- }
- >
- {renderAgentSkillsList()}
- </AccordionItem>
- </Accordion>
+ const renderAgentSkillsList = () => (
+ <SkillsList
+ items={skillItems}
+ onOpenFile={(item, relativePath) => {
+ const view = skillBundleViews.find((v) => v.bundle.documentId === item.id);
+ const docId = view?.pathToDocumentId.get(relativePath);
+ if (docId) openDocumentByRoute(docId);
+ }}
+ onOpenSkill={(item) => {
+ // Open the SKILL.md (skills/index child) when present; fall back to
+ // the bundle itself (orphan bundles surface for recovery).
+ const view = skillBundleViews.find((v) => v.bundle.documentId === item.id);
+ const indexChild = data.find((doc) => doc.parentId === item.id && doc.isSkillIndex);
+ openDocumentByRoute(indexChild?.documentId ?? view?.bundle.documentId ?? item.id);
+ }}
+ onSkillDragStart={(item, event) => {
+ // 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 view = skillBundleViews.find((v) => v.bundle.documentId === item.id);
+ const filename = view?.bundle.filename;
+ if (!filename) return;
+ startSkillDrag(event, {
+ category: 'agentSkill',
+ label: item.name,
+ type: buildAgentSkillIdentifier(filename),
+ });
+ }}
+ />
);
const renderSkills = () => {
@@ -405,7 +374,16 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ style, workingDire
// Both sections coexist — label each so the source is clear.
return (
<Flexbox gap={16}>
- {renderAgentSkillsSection()}
+ <SkillSection
+ emptyText={t('workingPanel.skills.emptyAgent')}
+ isEmpty={skillItems.length === 0}
+ sectionHeader={{
+ count: skillItems.length,
+ title: t('workingPanel.skills.section.agent'),
+ }}
+ >
+ {renderAgentSkillsList()}
+ </SkillSection>
<ProjectLevelSkills workingDirectory={workingDirectory!} />
</Flexbox>
);
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/ProjectLevelSkills.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/ProjectLevelSkills.tsx
index f0c00d38551..23e5f685bf7 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/ProjectLevelSkills.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/ProjectLevelSkills.tsx
@@ -1,33 +1,8 @@
-import { type ListProjectSkillsResult, type ProjectSkillItem } from '@lobechat/electron-client-ipc';
-import { Accordion, AccordionItem, Center, Flexbox, Text } from '@lobehub/ui';
-import { createStaticStyles } from 'antd-style';
-import path from 'pathe';
-import { memo, useMemo, useState } from 'react';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
-import SkillsList, { type SkillListItem } from '@/features/AgentDocumentsExplorer/SkillsList';
-import { useClientDataSWR } from '@/libs/swr';
-import { localFileService } from '@/services/electron/localFileService';
-import { useChatStore } from '@/store/chat';
-
-const ITEM_KEY = 'project-skills';
-
-const styles = createStaticStyles(({ css, cssVar }) => ({
- count: css`
- font-size: 12px;
- font-variant-numeric: tabular-nums;
- color: ${cssVar.colorTextTertiary};
- `,
- empty: css`
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- label: css`
- font-size: 12px;
- font-weight: 500;
- `,
-}));
+import { startSkillDrag } from '@/features/ChatInput/InputEditor/ActionTag/skillDragData';
+import { SkillSection, SkillsList, useProjectSkills } from '@/features/SkillsList';
interface ProjectLevelSkillsProps {
workingDirectory: string;
@@ -35,88 +10,33 @@ interface ProjectLevelSkillsProps {
const ProjectLevelSkills = memo<ProjectLevelSkillsProps>(({ workingDirectory }) => {
const { t } = useTranslation('chat');
- const openLocalFile = useChatStore((s) => s.openLocalFile);
- const [expanded, setExpanded] = useState(true);
-
- const { data, isLoading } = useClientDataSWR<ListProjectSkillsResult>(
- ['project-skills', workingDirectory],
- () => localFileService.listProjectSkills({ scope: workingDirectory }),
- { revalidateOnFocus: false, shouldRetryOnError: false },
- );
-
- // listProjectSkills approves `data.root` for preview. Hand that exact value
- // back to openLocalFile so LocalFileProtocolManager.createPreviewUrl's
- // approved-root check matches; fall back to the requested workingDirectory
- // while the SWR fetch is in flight.
- const previewRoot = data?.root || workingDirectory;
-
- const items = useMemo<SkillListItem[]>(
- () =>
- (data?.skills ?? []).map((skill) => ({
- description: skill.description,
- fileCount: skill.fileCount,
- files: skill.files,
- id: skill.skillDir,
- name: skill.name,
- })),
- [data?.skills],
- );
-
- const skillByDir = useMemo(() => {
- const map = new Map<string, ProjectSkillItem>();
- for (const skill of data?.skills ?? []) map.set(skill.skillDir, skill);
- return map;
- }, [data?.skills]);
-
- const count = items.length;
+ const { isLoading, items, onOpenFile, onOpenSkill } = useProjectSkills(workingDirectory);
return (
- <Accordion
- expandedKeys={expanded ? [ITEM_KEY] : []}
- gap={4}
- onExpandedChange={(keys) => setExpanded(keys.length > 0)}
+ <SkillSection
+ emptyText={t('workingPanel.skills.empty')}
+ isEmpty={items.length === 0}
+ isLoading={isLoading}
+ sectionHeader={{
+ count: items.length,
+ title: t('workingPanel.skills.section.project'),
+ }}
>
- <AccordionItem
- itemKey={ITEM_KEY}
- paddingBlock={2}
- paddingInline={4}
- title={
- <Flexbox horizontal align={'center'} gap={6}>
- <Text className={styles.label} type={'secondary'}>
- {t('workingPanel.skills.section.project')}
- </Text>
- {count > 0 && <span className={styles.count}>{count}</span>}
- </Flexbox>
- }
- >
- {isLoading ? (
- <Center paddingBlock={12}>
- <NeuralNetworkLoading size={24} />
- </Center>
- ) : count === 0 ? (
- <Center paddingBlock={8}>
- <Text className={styles.empty}>{t('workingPanel.skills.empty')}</Text>
- </Center>
- ) : (
- <SkillsList
- items={items}
- onOpenFile={(item, relativePath) => {
- const skill = skillByDir.get(item.id);
- if (!skill) return;
- openLocalFile({
- filePath: path.join(skill.skillDir, relativePath),
- workingDirectory: previewRoot,
- });
- }}
- onOpenSkill={(item) => {
- const skill = skillByDir.get(item.id);
- if (!skill) return;
- openLocalFile({ filePath: skill.path, workingDirectory: previewRoot });
- }}
- />
- )}
- </AccordionItem>
- </Accordion>
+ <SkillsList
+ items={items}
+ onOpenFile={onOpenFile}
+ onOpenSkill={onOpenSkill}
+ onSkillDragStart={(item, event) => {
+ // Project skills are resolved by the underlying CLI agent itself, so
+ // we serialize them as a literal `/skill-name` (projectSkill chip).
+ startSkillDrag(event, {
+ category: 'projectSkill',
+ label: item.name,
+ type: item.name,
+ });
+ }}
+ />
+ </SkillSection>
);
});
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/SkillsGroup.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/SkillsGroup.tsx
index c079eda3ecb..903fc9433ad 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/SkillsGroup.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/SkillsGroup.tsx
@@ -1,29 +1,9 @@
import { isDesktop } from '@lobechat/const';
-import { type ListProjectSkillsResult, type ProjectSkillItem } from '@lobechat/electron-client-ipc';
-import { Center, Empty, Flexbox, Text } from '@lobehub/ui';
-import { SkillsIcon } from '@lobehub/ui/icons';
-import { createStaticStyles } from 'antd-style';
-import path from 'pathe';
-import { memo, useMemo } from 'react';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
-import SkillsList, { type SkillListItem } from '@/features/AgentDocumentsExplorer/SkillsList';
-import { useClientDataSWR } from '@/libs/swr';
-import { localFileService } from '@/services/electron/localFileService';
-import { useChatStore } from '@/store/chat';
-
-const styles = createStaticStyles(({ css, cssVar }) => ({
- groupCount: css`
- font-size: 12px;
- font-variant-numeric: tabular-nums;
- color: ${cssVar.colorTextTertiary};
- `,
- groupLabel: css`
- font-size: 12px;
- font-weight: 500;
- `,
-}));
+import { startSkillDrag } from '@/features/ChatInput/InputEditor/ActionTag/skillDragData';
+import { SkillSection, SkillsList, useProjectSkills } from '@/features/SkillsList';
interface SkillsGroupProps {
workingDirectory: string;
@@ -31,78 +11,39 @@ interface SkillsGroupProps {
const SkillsGroup = memo<SkillsGroupProps>(({ workingDirectory }) => {
const { t } = useTranslation('chat');
- const openLocalFile = useChatStore((s) => s.openLocalFile);
-
const enabled = isDesktop && !!workingDirectory;
- const { data, error, isLoading } = useClientDataSWR<ListProjectSkillsResult>(
- enabled ? ['project-skills', workingDirectory] : null,
- () => localFileService.listProjectSkills({ scope: workingDirectory }),
- { revalidateOnFocus: false, shouldRetryOnError: false },
+ const { isLoading, items, onOpenFile, onOpenSkill } = useProjectSkills(
+ enabled ? workingDirectory : undefined,
);
- // listProjectSkills approves `data.root` for preview. Hand that exact value
- // back to openLocalFile so LocalFileProtocolManager.createPreviewUrl's
- // approved-root check matches; fall back to the requested workingDirectory
- // while the SWR fetch is in flight.
- const previewWorkspaceRoot = data?.root || workingDirectory;
-
- const items = useMemo<SkillListItem[]>(
- () =>
- (data?.skills ?? []).map((skill) => ({
- description: skill.description,
- fileCount: skill.fileCount,
- files: skill.files,
- id: skill.skillDir,
- name: skill.name,
- })),
- [data?.skills],
- );
-
- const skillByDir = useMemo(() => {
- const map = new Map<string, ProjectSkillItem>();
- for (const skill of data?.skills ?? []) map.set(skill.skillDir, skill);
- return map;
- }, [data?.skills]);
-
if (!enabled) return null;
- const totalCount = data?.skills.length ?? 0;
-
return (
- <Flexbox gap={4}>
- <Flexbox horizontal align={'center'} gap={6} paddingInline={4}>
- <Text className={styles.groupLabel} type={'secondary'}>
- {t('workingPanel.skills.title')}
- </Text>
- {totalCount > 0 && <span className={styles.groupCount}>{totalCount}</span>}
- </Flexbox>
- {isLoading ? (
- <Center paddingBlock={12}>
- <NeuralNetworkLoading size={24} />
- </Center>
- ) : error || !data || data.skills.length === 0 ? (
- <Center gap={8} paddingBlock={16}>
- <Empty description={t('workingPanel.skills.empty')} icon={SkillsIcon} />
- </Center>
- ) : (
- <SkillsList
- items={items}
- onOpenFile={(item, relativePath) => {
- const skill = skillByDir.get(item.id);
- if (!skill) return;
- openLocalFile({
- filePath: path.join(skill.skillDir, relativePath),
- workingDirectory: previewWorkspaceRoot,
- });
- }}
- onOpenSkill={(item) => {
- const skill = skillByDir.get(item.id);
- if (!skill) return;
- openLocalFile({ filePath: skill.path, workingDirectory: previewWorkspaceRoot });
- }}
- />
- )}
- </Flexbox>
+ <SkillSection
+ emptyText={t('workingPanel.skills.empty')}
+ isEmpty={items.length === 0}
+ isLoading={isLoading}
+ sectionHeader={{
+ collapsible: false,
+ count: items.length,
+ title: t('workingPanel.skills.title'),
+ }}
+ >
+ <SkillsList
+ items={items}
+ onOpenFile={onOpenFile}
+ onOpenSkill={onOpenSkill}
+ onSkillDragStart={(item, event) => {
+ // Project skills are resolved by the underlying CLI agent itself, so
+ // we serialize them as a literal `/skill-name` (projectSkill chip).
+ startSkillDrag(event, {
+ category: 'projectSkill',
+ label: item.name,
+ type: item.name,
+ });
+ }}
+ />
+ </SkillSection>
);
});
diff --git a/src/server/services/agentDocuments/index.ts b/src/server/services/agentDocuments/index.ts
index c741315cbb4..8cfc7f8a53c 100644
--- a/src/server/services/agentDocuments/index.ts
+++ b/src/server/services/agentDocuments/index.ts
@@ -6,6 +6,7 @@ import type {
PolicyLoad,
} from '@lobechat/agent-templates';
import { DocumentLoadPosition, getDocumentTemplate } from '@lobechat/agent-templates';
+import { buildAgentSkillIdentifier } from '@lobechat/const';
import type { LobeChatDatabase } from '@lobechat/database';
import { DOCUMENT_FOLDER_TYPE } from '@lobechat/database/schemas';
@@ -236,6 +237,55 @@ export class AgentDocumentsService {
return this.projectDocuments(docs);
}
+ /**
+ * Return this agent's skill-bundle documents in a shape ready for the
+ * homogeneous skill runtime: identifier is prefixed
+ * (`agent-skills:<filename>`) and the body is resolved from the bundle's
+ * `SKILL.md` index child (falling back to the bundle row for orphans).
+ *
+ * Single source of truth for the agent-document skill registry: both the
+ * SkillEngine assembly (`<available_skills>` for the model) and the skills
+ * `activateSkill` runtime call this; neither re-implements the prefix or the
+ * bundle → index child mapping.
+ */
+ async getAgentSkills(agentId: string): Promise<
+ Array<{
+ content: string;
+ description: string;
+ filename: string;
+ identifier: string;
+ name: string;
+ title: string | null;
+ }>
+ > {
+ const docs = await this.getAgentDocuments(agentId);
+
+ const childrenByParent = new Map<string, AgentDocumentWithRules[]>();
+ for (const doc of docs) {
+ if (!doc.parentId) continue;
+ const list = childrenByParent.get(doc.parentId) ?? [];
+ list.push(doc);
+ childrenByParent.set(doc.parentId, list);
+ }
+
+ return docs
+ .filter((doc) => doc.isSkillBundle)
+ .map((bundle) => {
+ const indexChild = (childrenByParent.get(bundle.documentId) ?? []).find(
+ (child) => child.isSkillIndex,
+ );
+ const identifier = buildAgentSkillIdentifier(bundle.filename);
+ return {
+ content: indexChild?.content ?? bundle.content ?? '',
+ description: bundle.description ?? '',
+ filename: bundle.filename,
+ identifier,
+ name: identifier,
+ title: bundle.title,
+ };
+ });
+ }
+
async getDocumentsByTemplate(
agentId: string,
templateId: string,
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index da0bb4026fd..3dce1ab0194 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -2006,8 +2006,9 @@ export class AiAgentService {
);
// 18. Build OperationSkillSet via SkillEngine
- // Combines builtin skills + user DB skills, filters by platform via enableChecker,
- // and pairs with agent's enabled plugin IDs for downstream SkillResolver consumption.
+ // Combines builtin skills + user DB skills + agent-document skill bundles,
+ // filters by platform via enableChecker, and pairs with agent's enabled
+ // plugin IDs for downstream SkillResolver consumption.
let operationSkillSet;
try {
const builtinMetas = builtinSkills.map((s) => ({
@@ -2024,9 +2025,23 @@ export class AiAgentService {
name: s.name,
}));
+ // Agent-document skill bundles surfaced as runtime skills via the shared
+ // `getAgentSkills` source of truth (prefix + index-child resolution lives
+ // there; see `AgentDocumentsService.getAgentSkills`). Identifier is
+ // prefixed (`agent-skills:<filename>`) so it can't collide with builtin
+ // / DB skill names, and we re-use it as `name` so the prompt's
+ // `<skill name="...">` line and the model's `activateSkill(name)` call
+ // carry the same value.
+ const agentSkills = await this.agentDocumentsService.getAgentSkills(resolvedAgentId);
+ const agentSkillMetas = agentSkills.map((skill) => ({
+ description: skill.description,
+ identifier: skill.identifier,
+ name: skill.name,
+ }));
+
const skillEngine = new SkillEngine({
enableChecker: (skill) => shouldEnableBuiltinSkill(skill.identifier),
- skills: [...builtinMetas, ...dbMetas],
+ skills: [...builtinMetas, ...dbMetas, ...agentSkillMetas],
});
operationSkillSet = skillEngine.generate(agentPlugins ?? []);
} catch (error) {
diff --git a/src/server/services/toolExecution/serverRuntimes/skills.ts b/src/server/services/toolExecution/serverRuntimes/skills.ts
index 6aa4896884b..434fcabf9c5 100644
--- a/src/server/services/toolExecution/serverRuntimes/skills.ts
+++ b/src/server/services/toolExecution/serverRuntimes/skills.ts
@@ -5,7 +5,7 @@ import {
type SkillRuntimeService,
SkillsExecutionRuntime,
} from '@lobechat/builtin-tool-skills/executionRuntime';
-import type { SkillItem, SkillListItem, SkillResourceContent } from '@lobechat/types';
+import type { BuiltinSkill, SkillItem, SkillListItem, SkillResourceContent } from '@lobechat/types';
import type { CodeInterpreterToolName } from '@lobehub/market-sdk';
import debug from 'debug';
import { sha256 } from 'js-sha256';
@@ -15,6 +15,7 @@ import { FileModel } from '@/database/models/file';
import { UserModel } from '@/database/models/user';
import { filterBuiltinSkills } from '@/helpers/skillFilters';
import { FileS3 } from '@/server/modules/S3';
+import { AgentDocumentsService } from '@/server/services/agentDocuments';
import { FileService } from '@/server/services/file';
import { MarketService } from '@/server/services/market';
import { SkillResourceService } from '@/server/services/skill/resource';
@@ -342,8 +343,34 @@ export const skillsRuntime: ServerRuntimeRegistration = {
userId: context.userId,
});
+ // Surface this agent's skill-bundle documents as `BuiltinSkill`-shaped
+ // entries so `activateSkill('agent-skills:<filename>')` resolves on the
+ // existing no-DB-lookup path — no `SkillRuntimeService` extension needed.
+ // `AgentDocumentsService.getAgentSkills` is the single source of truth for
+ // the identifier prefix and the bundle → index-child content resolution
+ // (also used by `aiAgent/index.ts` when building `<available_skills>`).
+ // `source: 'builtin'` is the type-system carrier shape required by
+ // `BuiltinSkill`; the runtime never reads `source`.
+ const agentSkillBuiltins: BuiltinSkill[] = context.agentId
+ ? await new AgentDocumentsService(context.serverDB, context.userId)
+ .getAgentSkills(context.agentId)
+ .then((skills) =>
+ skills.map((skill) => ({
+ content: skill.content,
+ description: skill.description,
+ identifier: skill.identifier,
+ name: skill.name,
+ source: 'builtin' as const,
+ })),
+ )
+ .catch((error) => {
+ log('failed to load agent skills for agent %s: %O', context.agentId, error);
+ return [];
+ })
+ : [];
+
return new SkillsExecutionRuntime({
- builtinSkills: filterBuiltinSkills(builtinSkills),
+ builtinSkills: [...filterBuiltinSkills(builtinSkills), ...agentSkillBuiltins],
service,
});
},
diff --git a/src/store/tool/initialState.ts b/src/store/tool/initialState.ts
index 97c8cca3427..6f8581fdcc8 100644
--- a/src/store/tool/initialState.ts
+++ b/src/store/tool/initialState.ts
@@ -1,3 +1,7 @@
+import {
+ type AgentDocumentSkillsState,
+ initialAgentDocumentSkillsState,
+} from './slices/agentDocumentSkills/initialState';
import { type AgentSkillsState, initialAgentSkillsState } from './slices/agentSkills/initialState';
import { type BuiltinToolState, initialBuiltinToolState } from './slices/builtin/initialState';
import {
@@ -18,7 +22,8 @@ export type ToolStoreState = PluginState &
MCPStoreState &
KlavisStoreState &
LobehubSkillStoreState &
- AgentSkillsState;
+ AgentSkillsState &
+ AgentDocumentSkillsState;
export const initialState: ToolStoreState = {
...initialPluginState,
@@ -28,4 +33,5 @@ export const initialState: ToolStoreState = {
...initialKlavisStoreState,
...initialLobehubSkillStoreState,
...initialAgentSkillsState,
+ ...initialAgentDocumentSkillsState,
};
diff --git a/src/store/tool/selectors/index.ts b/src/store/tool/selectors/index.ts
index 720649d526b..e2f82432428 100644
--- a/src/store/tool/selectors/index.ts
+++ b/src/store/tool/selectors/index.ts
@@ -1,3 +1,4 @@
+export { agentDocumentSkillsSelectors } from '../slices/agentDocumentSkills/selectors';
export { agentSkillsSelectors } from '../slices/agentSkills/selectors';
export {
builtinToolSelectors,
diff --git a/src/store/tool/slices/agentDocumentSkills/action.ts b/src/store/tool/slices/agentDocumentSkills/action.ts
new file mode 100644
index 00000000000..bfdc920028d
--- /dev/null
+++ b/src/store/tool/slices/agentDocumentSkills/action.ts
@@ -0,0 +1,119 @@
+import { buildAgentSkillIdentifier } from '@lobechat/const';
+import useSWR, { type SWRResponse } from 'swr';
+
+import { agentDocumentService, agentDocumentSWRKeys } from '@/services/agentDocument';
+import { type StoreSetter } from '@/store/types';
+import { setNamespace } from '@/utils/storeDebug';
+
+import { type ToolStore } from '../../store';
+import { type AgentDocumentSkillItem, type AgentDocumentSkillsState } from './initialState';
+
+const n = setNamespace('agentDocumentSkills');
+
+type Setter = StoreSetter<ToolStore>;
+
+const mapDocsToSkills = (
+ docs: Awaited<ReturnType<typeof agentDocumentService.getDocuments>>,
+): AgentDocumentSkillItem[] =>
+ docs
+ .filter((doc) => doc.isSkillBundle)
+ .map((doc) => ({
+ description: doc.description ?? undefined,
+ documentId: doc.documentId,
+ identifier: buildAgentSkillIdentifier(doc.filename),
+ name: doc.filename,
+ title: doc.title || undefined,
+ }));
+
+export const createAgentDocumentSkillsSlice = (set: Setter, get: () => ToolStore, _api?: unknown) =>
+ new AgentDocumentSkillsActionImpl(set, get, _api);
+
+export class AgentDocumentSkillsActionImpl {
+ readonly #get: () => ToolStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ToolStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ /**
+ * Load (or refresh) the agent-document skill bundles for the given agent and
+ * publish them to the tool store registry. Cleared first when switching
+ * agents so consumers never see stale items from the previous agent.
+ */
+ refreshAgentDocumentSkills = async (agentId: string): Promise<void> => {
+ const previousAgentId = this.#get().agentDocumentSkillsAgentId;
+ if (previousAgentId && previousAgentId !== agentId) {
+ this.#set(
+ { agentDocumentSkills: [], agentDocumentSkillsAgentId: agentId },
+ false,
+ n('switchAgent'),
+ );
+ } else if (!previousAgentId) {
+ this.#set({ agentDocumentSkillsAgentId: agentId }, false, n('initAgent'));
+ }
+
+ try {
+ const docs = await agentDocumentService.getDocuments({ agentId });
+ const items = mapDocsToSkills(docs);
+ this.#set(
+ { agentDocumentSkills: items, agentDocumentSkillsAgentId: agentId },
+ false,
+ n('refreshAgentDocumentSkills'),
+ );
+ } catch (error) {
+ // Surface registry as empty on failure rather than throwing — slash menu
+ // and drag chips degrade gracefully (just nothing to drag) instead of
+ // crashing the working sidebar.
+
+ console.warn('[agentDocumentSkills] failed to refresh:', error);
+ this.#set(
+ { agentDocumentSkills: [] } satisfies Partial<AgentDocumentSkillsState>,
+ false,
+ n('refreshAgentDocumentSkillsError'),
+ );
+ }
+ };
+
+ clearAgentDocumentSkills = (): void => {
+ this.#set(
+ { agentDocumentSkills: [], agentDocumentSkillsAgentId: undefined },
+ false,
+ n('clearAgentDocumentSkills'),
+ );
+ };
+
+ /**
+ * SWR-backed hook that fetches the agent's skill bundles and keeps the store
+ * in sync. Shares the same SWR key as the working-sidebar panel so the panel
+ * fetch and the registry sync collapse into one network request.
+ */
+ useFetchAgentDocumentSkills = (
+ agentId: string | undefined,
+ ): SWRResponse<Awaited<ReturnType<typeof agentDocumentService.getDocuments>>> =>
+ useSWR<Awaited<ReturnType<typeof agentDocumentService.getDocuments>>>(
+ agentId ? agentDocumentSWRKeys.documentsList(agentId) : null,
+ async () => agentDocumentService.getDocuments({ agentId: agentId! }),
+ {
+ onSuccess: (docs) => {
+ if (!agentId) return;
+ this.#set(
+ {
+ agentDocumentSkills: mapDocsToSkills(docs),
+ agentDocumentSkillsAgentId: agentId,
+ },
+ false,
+ n('useFetchAgentDocumentSkills'),
+ );
+ },
+ revalidateOnFocus: false,
+ },
+ );
+}
+
+export type AgentDocumentSkillsAction = Pick<
+ AgentDocumentSkillsActionImpl,
+ keyof AgentDocumentSkillsActionImpl
+>;
diff --git a/src/store/tool/slices/agentDocumentSkills/index.ts b/src/store/tool/slices/agentDocumentSkills/index.ts
new file mode 100644
index 00000000000..55b4d68b202
--- /dev/null
+++ b/src/store/tool/slices/agentDocumentSkills/index.ts
@@ -0,0 +1,7 @@
+export { type AgentDocumentSkillsAction, createAgentDocumentSkillsSlice } from './action';
+export {
+ type AgentDocumentSkillItem,
+ type AgentDocumentSkillsState,
+ initialAgentDocumentSkillsState,
+} from './initialState';
+export { agentDocumentSkillsSelectors } from './selectors';
diff --git a/src/store/tool/slices/agentDocumentSkills/initialState.ts b/src/store/tool/slices/agentDocumentSkills/initialState.ts
new file mode 100644
index 00000000000..a0661a5701e
--- /dev/null
+++ b/src/store/tool/slices/agentDocumentSkills/initialState.ts
@@ -0,0 +1,31 @@
+/**
+ * Lightweight registry entry for an agent-document skill bundle (the "智能体
+ * Skills" group, sourced from the `agent_document` table).
+ *
+ * Distinct from the user/market `SkillListItem` shape because these skills are
+ * per-agent and don't carry a full `SkillManifest`. The slash menu, drag chip,
+ * and runtime activation all key off `identifier` — the prefix lets the server
+ * resolver tell them apart from builtin/DB skills.
+ */
+export interface AgentDocumentSkillItem {
+ description?: string;
+ documentId: string;
+ /** `agent-document:<filename>` — matches the server-side runtime identifier. */
+ identifier: string;
+ /** Bundle filename (slug). */
+ name: string;
+ /** Human-readable display title; falls back to `name`. */
+ title?: string;
+}
+
+export interface AgentDocumentSkillsState {
+ /** Skills belonging to the currently-active agent; cleared on agent switch. */
+ agentDocumentSkills: AgentDocumentSkillItem[];
+ /** The agent id the current `agentDocumentSkills` snapshot belongs to. */
+ agentDocumentSkillsAgentId: string | undefined;
+}
+
+export const initialAgentDocumentSkillsState: AgentDocumentSkillsState = {
+ agentDocumentSkills: [],
+ agentDocumentSkillsAgentId: undefined,
+};
diff --git a/src/store/tool/slices/agentDocumentSkills/selectors.ts b/src/store/tool/slices/agentDocumentSkills/selectors.ts
new file mode 100644
index 00000000000..2c58faecc7c
--- /dev/null
+++ b/src/store/tool/slices/agentDocumentSkills/selectors.ts
@@ -0,0 +1,15 @@
+import type { ToolStoreState } from '../../initialState';
+import type { AgentDocumentSkillItem } from './initialState';
+
+const getAgentDocumentSkills = (s: ToolStoreState): AgentDocumentSkillItem[] =>
+ s.agentDocumentSkills || [];
+
+const getAgentDocumentSkillByIdentifier =
+ (identifier: string) =>
+ (s: ToolStoreState): AgentDocumentSkillItem | undefined =>
+ (s.agentDocumentSkills || []).find((skill) => skill.identifier === identifier);
+
+export const agentDocumentSkillsSelectors = {
+ getAgentDocumentSkillByIdentifier,
+ getAgentDocumentSkills,
+};
diff --git a/src/store/tool/store.ts b/src/store/tool/store.ts
index 5d0647794d0..303c8387b1a 100644
--- a/src/store/tool/store.ts
+++ b/src/store/tool/store.ts
@@ -7,6 +7,10 @@ import { expose } from '../middleware/expose';
import { flattenActions } from '../utils/flattenActions';
import { type ResetableStore, ResetableStoreAction } from '../utils/resetableStore';
import { initialState, type ToolStoreState } from './initialState';
+import {
+ type AgentDocumentSkillsAction,
+ createAgentDocumentSkillsSlice,
+} from './slices/agentDocumentSkills';
import { type AgentSkillsAction, createAgentSkillsSlice } from './slices/agentSkills';
import { type BuiltinToolAction, createBuiltinToolSlice } from './slices/builtin';
import { createCustomPluginSlice, type CustomPluginAction } from './slices/customPlugin';
@@ -28,6 +32,7 @@ export type ToolStore = ToolStoreState &
KlavisStoreAction &
LobehubSkillStoreAction &
AgentSkillsAction &
+ AgentDocumentSkillsAction &
ResetableStore;
type ToolStoreAction = CustomPluginAction &
@@ -37,6 +42,7 @@ type ToolStoreAction = CustomPluginAction &
KlavisStoreAction &
LobehubSkillStoreAction &
AgentSkillsAction &
+ AgentDocumentSkillsAction &
ResetableStore;
class ToolStoreResetAction extends ResetableStoreAction<ToolStore> {
@@ -55,6 +61,7 @@ const createStore: StateCreator<ToolStore, [['zustand/devtools', never]]> = (
createKlavisStoreSlice(...parameters),
createLobehubSkillStoreSlice(...parameters),
createAgentSkillsSlice(...parameters),
+ createAgentDocumentSkillsSlice(...parameters),
new ToolStoreResetAction(...parameters),
]),
});