Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(chat): render typed skill/tool tags as chips & stop assistant chip leak (#16645)

Arvin Xu897fd452023b
diff --git a/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.test.ts b/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.test.ts
new file mode 100644
index 00000000000..50ea6e9f7c4
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.test.ts
@@ -0,0 +1,119 @@
+import { AGENT_SKILLS_IDENTIFIER_PREFIX } from '@lobechat/const';
+import { describe, expect, it } from 'vitest';
+
+import {
+ INLINE_ACTION_TAG_REGEX,
+ isInCodeContext,
+ resolveActionTagFromMatch,
+} from './ActionTagPlugin';
+
+// Minimal Lexical-node stand-in for isInCodeContext, which only reads
+// hasFormat / getType / getParent.
+const makeNode = (opts: { format?: boolean; parent?: any; type?: string }): any => ({
+ getParent: () => opts.parent ?? null,
+ getType: () => opts.type ?? 'text',
+ hasFormat: (f: string) => f === 'code' && !!opts.format,
+});
+
+describe('INLINE_ACTION_TAG_REGEX', () => {
+ it('matches the tag a user typed, with trailing text (the regression case)', () => {
+ const text = '<skill name="ux-audit" label="ux-audit" /> 搞 LOBE-11218';
+ const match = INLINE_ACTION_TAG_REGEX.exec(text);
+
+ expect(match).not.toBeNull();
+ expect(match!.index).toBe(0);
+ expect(match![0]).toBe('<skill name="ux-audit" label="ux-audit" />');
+ expect(match![1]).toBe('skill');
+ });
+
+ it('matches a tag sitting after leading text', () => {
+ const match = INLINE_ACTION_TAG_REGEX.exec('run <tool name="search" label="Search" /> now');
+ expect(match!.index).toBe(4);
+ expect(match![1]).toBe('tool');
+ });
+
+ it('tolerates no space before the self-close and mixed casing', () => {
+ expect(INLINE_ACTION_TAG_REGEX.exec('<Skill name="a" label="a"/>')?.[1]).toBe('Skill');
+ });
+
+ it('does not match an unterminated / partial tag while still typing', () => {
+ expect(INLINE_ACTION_TAG_REGEX.exec('<skill name="ux-audit"')).toBeNull();
+ });
+
+ it('ignores unrelated tags', () => {
+ expect(INLINE_ACTION_TAG_REGEX.exec('<div name="x" />')).toBeNull();
+ });
+});
+
+describe('resolveActionTagFromMatch', () => {
+ it('resolves a plain skill tag', () => {
+ expect(resolveActionTagFromMatch('skill', ' name="ux-audit" label="ux-audit" ')).toMatchObject({
+ actionCategory: 'skill',
+ actionLabel: 'ux-audit',
+ actionType: 'ux-audit',
+ });
+ });
+
+ it('recovers the agentSkill category from the identifier prefix', () => {
+ const attrs = ` name="${AGENT_SKILLS_IDENTIFIER_PREFIX}my-doc" label="My Doc" `;
+ expect(resolveActionTagFromMatch('skill', attrs)).toMatchObject({
+ actionCategory: 'agentSkill',
+ actionLabel: 'My Doc',
+ });
+ });
+
+ it('resolves tool and projectSkill tags', () => {
+ expect(resolveActionTagFromMatch('tool', ' name="search" label="Search" ')).toMatchObject({
+ actionCategory: 'tool',
+ actionType: 'search',
+ });
+ expect(
+ resolveActionTagFromMatch('projectSkill', ' name="ux-audit" label="UX Audit" '),
+ ).toMatchObject({ actionCategory: 'projectSkill', actionType: 'ux-audit' });
+ });
+
+ it('resolves a legacy <action> tag with an explicit category', () => {
+ expect(
+ resolveActionTagFromMatch('action', ' type="newTopic" category="command" label="New Topic" '),
+ ).toMatchObject({
+ actionCategory: 'command',
+ actionLabel: 'New Topic',
+ actionType: 'newTopic',
+ });
+ });
+
+ it('returns null for an unknown tag name', () => {
+ expect(resolveActionTagFromMatch('div', ' name="x" ')).toBeNull();
+ });
+
+ it('handles single-quoted attribute values', () => {
+ expect(resolveActionTagFromMatch('skill', " name='a' label='B' ")).toMatchObject({
+ actionType: 'a',
+ actionLabel: 'B',
+ });
+ });
+});
+
+describe('isInCodeContext', () => {
+ it('is false for a plain text node in a paragraph', () => {
+ expect(isInCodeContext(makeNode({ parent: makeNode({ type: 'paragraph' }) }))).toBe(false);
+ });
+
+ it('is true for an inline-code formatted text node', () => {
+ expect(isInCodeContext(makeNode({ format: true }))).toBe(true);
+ });
+
+ it('is true for a highlighted code token node', () => {
+ expect(isInCodeContext(makeNode({ type: 'code-highlight' }))).toBe(true);
+ });
+
+ it('is true for text wrapped in an inline-code (codeInline) element', () => {
+ expect(isInCodeContext(makeNode({ parent: makeNode({ type: 'codeInline' }) }))).toBe(true);
+ });
+
+ it('is true for text nested inside a code block', () => {
+ const codeBlock = makeNode({ type: 'code' });
+ const inner = makeNode({ parent: codeBlock, type: 'paragraph' });
+ expect(isInCodeContext(makeNode({ parent: inner }))).toBe(true);
+ });
+});
diff --git a/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.ts b/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.ts
index 39cd1021769..e761544a5fc 100644
--- a/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.ts
+++ b/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.ts
@@ -4,15 +4,122 @@ import {
ILitexmlService,
IMarkdownShortCutService,
} from '@lobehub/editor';
-import type { LexicalEditor, LexicalNode } from 'lexical';
+import { type LexicalEditor, type LexicalNode, TextNode } from 'lexical';
-import { $isActionTagNode, ActionTagNode, type SerializedActionTagNode } from './ActionTagNode';
+import {
+ $createActionTagNode,
+ $isActionTagNode,
+ ActionTagNode,
+ type SerializedActionTagNode,
+} from './ActionTagNode';
import { registerActionTagCommand } from './command';
import { registerActionTagSelectionObserver } from './selectionObserver';
import type { ActionTagCategory, ActionTagType } from './types';
type IEditorKernel = ReturnType<typeof getKernelFromEditor>;
+/**
+ * Minimal shape shared by the LiteXML element and the ad-hoc parser below, so
+ * one set of readers recovers the chip from both a round-tripped XML node and a
+ * raw `<skill … />` string a user typed or pasted.
+ */
+interface XmlAttributeSource {
+ getAttribute: (name: string) => string | null;
+}
+
+// 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 = (el: XmlAttributeSource): SerializedActionTagNode => {
+ const name = el.getAttribute('name') || '';
+ return {
+ actionCategory: name.startsWith(AGENT_SKILLS_IDENTIFIER_PREFIX) ? 'agentSkill' : 'skill',
+ actionLabel: el.getAttribute('label') || '',
+ actionType: name as ActionTagType,
+ type: ActionTagNode.getType(),
+ version: 1,
+ };
+};
+const readTool = (el: XmlAttributeSource): SerializedActionTagNode => ({
+ actionCategory: 'tool',
+ actionLabel: el.getAttribute('label') || '',
+ actionType: (el.getAttribute('name') || '') as ActionTagType,
+ type: ActionTagNode.getType(),
+ version: 1,
+});
+const readProjectSkill = (el: XmlAttributeSource): SerializedActionTagNode => ({
+ actionCategory: 'projectSkill',
+ actionLabel: el.getAttribute('label') || '',
+ actionType: (el.getAttribute('name') || '') as ActionTagType,
+ type: ActionTagNode.getType(),
+ version: 1,
+});
+const readLegacyAction = (el: XmlAttributeSource): SerializedActionTagNode => ({
+ actionCategory: (el.getAttribute('category') || 'skill') as ActionTagCategory,
+ actionLabel: el.getAttribute('label') || '',
+ actionType: (el.getAttribute('type') || 'translate') as ActionTagType,
+ type: ActionTagNode.getType(),
+ version: 1,
+});
+
+const TAG_READERS: Record<string, (el: XmlAttributeSource) => SerializedActionTagNode> = {
+ action: readLegacyAction,
+ projectskill: readProjectSkill,
+ skill: readSkill,
+ tool: readTool,
+};
+
+// A single self-closing action tag: <skill … />, <tool … />, <projectSkill … />
+// or the legacy <action … />. Non-global so `.exec` reports the first match's
+// index; the transform re-runs on the trailing text to pick up later tags.
+export const INLINE_ACTION_TAG_REGEX = /<(skill|projectskill|tool|action)(\s[^>]*?)?\/>/i;
+const ATTRIBUTE_REGEX = /([\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
+
+const parseAttributeSource = (attributeString: string): XmlAttributeSource => {
+ const attributes: Record<string, string> = {};
+ let match: RegExpExecArray | null;
+ ATTRIBUTE_REGEX.lastIndex = 0;
+ while ((match = ATTRIBUTE_REGEX.exec(attributeString)) !== null) {
+ attributes[match[1]] = match[2] ?? match[3] ?? '';
+ }
+ return { getAttribute: (name) => (name in attributes ? attributes[name] : null) };
+};
+
+/**
+ * Resolve a raw action-tag name + attribute string into the serialized chip
+ * node, or `null` for an unknown tag. Exported for unit testing the parsing /
+ * category resolution independently of the Lexical editor.
+ */
+export const resolveActionTagFromMatch = (
+ tagName: string,
+ attributeString: string,
+): SerializedActionTagNode | null => {
+ const reader = TAG_READERS[tagName.toLowerCase()];
+ if (!reader) return null;
+ return reader(parseAttributeSource(attributeString));
+};
+
+// @lobehub/editor code node types: 'code' (CodeMirror block), 'codeInline'
+// (inline-code element wrapping text), 'code-highlight' (highlighted token
+// text nodes inside a fenced block).
+const CODE_CONTEXT_NODE_TYPES = new Set(['code', 'codeInline', 'code-highlight', 'codemirror']);
+
+/**
+ * True when a text node is part of a code snippet β€” inline code (a `code`
+ * format flag or a `codeInline` wrapper), a highlighted token, or inside a code
+ * block. A literal `<skill … />` a user writes/pastes in code is content, not a
+ * chip, so the tag transform must leave it alone.
+ */
+export const isInCodeContext = (node: TextNode): boolean => {
+ if (node.hasFormat('code')) return true;
+ let current: LexicalNode | null = node;
+ while (current) {
+ if (CODE_CONTEXT_NODE_TYPES.has(current.getType())) return true;
+ current = current.getParent();
+ }
+ return false;
+};
+
export interface ActionTagPluginOptions {
decorator: (node: ActionTagNode, editor: LexicalEditor) => any;
theme?: { actionTag?: string };
@@ -46,10 +153,50 @@ export class ActionTagPlugin {
onInit(editor: LexicalEditor): void {
this.clears.push(registerActionTagCommand(editor));
this.clears.push(registerActionTagSelectionObserver(editor));
+ this.clears.push(this.registerTextTagTransform(editor));
this.registerMarkdown();
this.registerLiteXml();
}
+ /**
+ * Turn a raw `<skill … />` / `<tool … />` / `<action … />` tag that a user
+ * typed or pasted into the editor into the matching chip node. Without this,
+ * only the slash / mention menu could produce a chip; a hand-written or
+ * copy-pasted tag would send as literal XML and β€” because sent user messages
+ * render their persisted editor state, not markdown β€” show up raw in the
+ * bubble. Reuses the same readers as the LiteXML round-trip so category
+ * resolution (e.g. the `agent-skills:` prefix β†’ agentSkill) lives in one place.
+ */
+ private registerTextTagTransform(editor: LexicalEditor): () => void {
+ return editor.registerNodeTransform(TextNode, (node) => {
+ // A literal tag written/pasted inside code is content, not a chip.
+ if (isInCodeContext(node)) return;
+
+ const text = node.getTextContent();
+ const match = INLINE_ACTION_TAG_REGEX.exec(text);
+ if (!match) return;
+
+ const [fullMatch, tagName, attributeString] = match;
+ const serialized = resolveActionTagFromMatch(tagName, attributeString ?? '');
+ if (!serialized) return;
+
+ const actionNode = $createActionTagNode(
+ serialized.actionType,
+ serialized.actionCategory,
+ serialized.actionLabel,
+ );
+
+ const startIndex = match.index;
+ const endIndex = startIndex + fullMatch.length;
+
+ // Split the raw tag out of the text node and swap it for the chip; the
+ // trailing text node re-enters this transform to catch any further tags.
+ const targetNode =
+ startIndex === 0 ? node.splitText(endIndex)[0] : node.splitText(startIndex, endIndex)[1];
+ targetNode.replace(actionNode);
+ });
+ }
+
private registerMarkdown(): void {
const mdService = this.kernel.requireService(IMarkdownShortCutService);
@@ -112,42 +259,10 @@ export class ActionTagPlugin {
return false;
});
- // 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') || '',
- actionType: (xmlElement.getAttribute('name') || '') as ActionTagType,
- type: ActionTagNode.getType(),
- version: 1,
- });
- const readProjectSkill = (xmlElement: any): SerializedActionTagNode => ({
- actionCategory: 'projectSkill',
- actionLabel: xmlElement.getAttribute('label') || '',
- actionType: (xmlElement.getAttribute('name') || '') as ActionTagType,
- type: ActionTagNode.getType(),
- version: 1,
- });
- const readLegacyAction = (xmlElement: any): SerializedActionTagNode => ({
- actionCategory: (xmlElement.getAttribute('category') || 'skill') as ActionTagCategory,
- actionLabel: xmlElement.getAttribute('label') || '',
- actionType: (xmlElement.getAttribute('type') || 'translate') as ActionTagType,
- type: ActionTagNode.getType(),
- version: 1,
- });
-
+ // Read <skill>, <tool>, <projectSkill>, and legacy <action> tags. The
+ // readers are shared with the typed/pasted-tag transform (see module top),
+ // so `<skill>`'s `agent-skills:` prefix β†’ agentSkill mapping stays in one
+ // place. LiteXML elements already satisfy the `getAttribute` contract.
xmlService?.registerXMLReader('skill', readSkill);
xmlService?.registerXMLReader('tool', readTool);
xmlService?.registerXMLReader('projectSkill', readProjectSkill);
diff --git a/src/features/Conversation/Messages/useChatMarkdown.test.tsx b/src/features/Conversation/Messages/useChatMarkdown.test.tsx
new file mode 100644
index 00000000000..6aa1e0e9dbe
--- /dev/null
+++ b/src/features/Conversation/Messages/useChatMarkdown.test.tsx
@@ -0,0 +1,48 @@
+import { renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { markdownElements } from '../Markdown/plugins';
+import { useChatMarkdown } from './useChatMarkdown';
+
+// The hook reads a general-settings slice for the fade-in transition; stub it so
+// the hook renders without a full store. We only assert plugin wiring here.
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: any) => selector({ settings: {} }),
+}));
+vi.mock('@/store/user/selectors', () => ({
+ userGeneralSettingsSelectors: { config: () => ({ transitionMode: 'none' }) },
+}));
+
+const remarkPluginFor = (tag: string) =>
+ markdownElements.find((el) => el.tag === tag)?.remarkPlugin;
+
+describe('useChatMarkdown (assistant / grouped message pipeline)', () => {
+ it('excludes user-scoped plugins so echoed <skill>/<tool> tags never become chips', () => {
+ const { result } = renderHook(() => useChatMarkdown({ id: 'a1', isGenerating: false }));
+
+ const remarkPlugins = result.current.markdownProps.remarkPlugins ?? [];
+
+ const skillPlugin = remarkPluginFor('skill');
+ const toolPlugin = remarkPluginFor('tool');
+ expect(skillPlugin).toBeTruthy();
+ expect(toolPlugin).toBeTruthy();
+
+ // The Skill / Tool plugins are `scope: 'user'` β€” they must not run on the
+ // assistant path (the #2 fix). Before the fix, this hook included them.
+ expect(remarkPlugins).not.toContain(skillPlugin);
+ expect(remarkPlugins).not.toContain(toolPlugin);
+ });
+
+ it('still includes assistant-scoped plugins', () => {
+ const { result } = renderHook(() => useChatMarkdown({ id: 'a2', isGenerating: false }));
+ const remarkPlugins = result.current.markdownProps.remarkPlugins ?? [];
+
+ // Sanity: an assistant-scoped plugin (e.g. LocalFile) is still wired in, so
+ // the filter narrowed the set rather than emptying it.
+ const assistantScoped = markdownElements.find(
+ (el) => el.scope === 'assistant' && el.remarkPlugin,
+ );
+ expect(assistantScoped).toBeTruthy();
+ expect(remarkPlugins).toContain(assistantScoped!.remarkPlugin);
+ });
+});
diff --git a/src/features/Conversation/Messages/useChatMarkdown.tsx b/src/features/Conversation/Messages/useChatMarkdown.tsx
index 3e238d5bbcc..de4c0409de5 100644
--- a/src/features/Conversation/Messages/useChatMarkdown.tsx
+++ b/src/features/Conversation/Messages/useChatMarkdown.tsx
@@ -9,10 +9,17 @@ import { userGeneralSettingsSelectors } from '@/store/user/selectors';
import { type MarkdownElement, markdownElements } from '../Markdown/plugins';
-const rehypePlugins = markdownElements
+// Honor each plugin's declared `scope`: this hook renders assistant / grouped
+// messages, so user-only constructs (skill, tool, action, mention, …) must not
+// be parsed here β€” otherwise a `<skill … />` the model happens to echo back
+// would render as an interactive chip. Mirrors the `scope !== 'assistant'`
+// filter on the user-message hook.
+const assistantMarkdownElements = markdownElements.filter((s) => s.scope !== 'user');
+
+const rehypePlugins = assistantMarkdownElements
.map((element: MarkdownElement) => element.rehypePlugin)
.filter(Boolean);
-const remarkPlugins = markdownElements
+const remarkPlugins = assistantMarkdownElements
.map((element: MarkdownElement) => element.remarkPlugin)
.filter(Boolean);