🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🛠️ fix: unify SKILL.md frontmatter parsing and edit validation in agent documents (#14566)
AmAzing-0c659dbe228e
diff --git a/locales/en-US/editor.json b/locales/en-US/editor.jsonindex 23b8b079051..657561a7772 100644--- a/locales/en-US/editor.json+++ b/locales/en-US/editor.json@@ -40,6 +40,18 @@"modifier.acceptAll": "Keep All","modifier.reject": "Revert","modifier.rejectAll": "Revert All",+ "skillFrontmatter.edit": "Edit metadata",+ "skillFrontmatter.empty": "No metadata",+ "skillFrontmatter.invalid.descriptionInvalid": "Description must be single-line text.",+ "skillFrontmatter.invalid.descriptionRequired": "Description is required.",+ "skillFrontmatter.invalid.mapping": "Frontmatter must be a YAML mapping.",+ "skillFrontmatter.invalid.nameInvalid": "Name must use lowercase letters, numbers, and hyphens.",+ "skillFrontmatter.invalid.nameLocked": "Name must remain {{name}}. Rename the skill bundle instead.",+ "skillFrontmatter.invalid.nameRequired": "Name is required.",+ "skillFrontmatter.invalid.required": "Frontmatter is required.",+ "skillFrontmatter.invalid.syntax": "Invalid YAML syntax.",+ "skillFrontmatter.saveFailed": "Metadata was not saved. Retry, or keep editing.",+ "skillFrontmatter.title": "Skill metadata","slash.compact": "Compact context","slash.h1": "Heading 1","slash.h2": "Heading 2",diff --git a/locales/zh-CN/editor.json b/locales/zh-CN/editor.jsonindex 37a211a4a72..3c4d5918237 100644--- a/locales/zh-CN/editor.json+++ b/locales/zh-CN/editor.json@@ -40,6 +40,18 @@"modifier.acceptAll": "全部保留","modifier.reject": "撤销","modifier.rejectAll": "全部撤销",+ "skillFrontmatter.edit": "编辑元信息",+ "skillFrontmatter.empty": "暂无元信息",+ "skillFrontmatter.invalid.descriptionInvalid": "描述必须是单行文本。",+ "skillFrontmatter.invalid.descriptionRequired": "描述不能为空。",+ "skillFrontmatter.invalid.mapping": "YAML 元信息必须是映射。",+ "skillFrontmatter.invalid.nameInvalid": "名称只能使用小写字母、数字和连字符。",+ "skillFrontmatter.invalid.nameLocked": "名称必须保持为 {{name}}。请通过技能重命名入口修改。",+ "skillFrontmatter.invalid.nameRequired": "名称不能为空。",+ "skillFrontmatter.invalid.required": "YAML 元信息不能为空。",+ "skillFrontmatter.invalid.syntax": "YAML 语法无效。",+ "skillFrontmatter.saveFailed": "元信息未保存。请重试,或继续编辑。",+ "skillFrontmatter.title": "技能元信息","slash.compact": "压缩上下文","slash.h1": "一级标题","slash.h2": "二级标题",diff --git a/src/features/Portal/Document/Body.tsx b/src/features/Portal/Document/Body.tsxindex e193f51a89c..e00e41fa772 100644--- a/src/features/Portal/Document/Body.tsx+++ b/src/features/Portal/Document/Body.tsx@@ -1,8 +1,20 @@'use client';-import { Flexbox } from '@lobehub/ui';-import { createStaticStyles } from 'antd-style';-import { memo } from 'react';+import { ActionIcon, Button, Flexbox, Text, TextArea } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { CheckIcon, PencilIcon, XIcon } from 'lucide-react';+import type { ChangeEvent } from 'react';+import { memo, useCallback, useEffect, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';+import { useDocumentStore } from '@/store/document';+import {+ getSkillMarkdownMetadataError,+ parseSkillMarkdownFrontmatterFields,+ parseSkillMarkdownMetadata,+} from '@/utils/skillMarkdown';import EditorCanvas from './EditorCanvas';import TodoList from './TodoList';@@ -13,6 +25,38 @@ const styles = createStaticStyles(({ css }) => ({flex: 1;padding-inline: 16px;`,+ frontmatter: css`+ margin-block: 16px 12px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 8px;+ background: ${cssVar.colorBgContainer};+ `,+ metadataKey: css`+ flex-shrink: 0;+ width: 112px;+ font-family: ${cssVar.fontFamilyCode};+ color: ${cssVar.colorTextSecondary};+ `,+ metadataRow: css`+ padding-block: 10px;+ padding-inline: 12px;++ &:not(:last-child) {+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ }+ `,+ metadataValue: css`+ min-width: 0;+ white-space: pre-wrap;+ `,+ sectionHeader: css`+ padding-block: 10px;+ padding-inline: 12px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ `,+ textArea: css`+ font-family: ${cssVar.fontFamilyCode};+ `,todoContainer: css`flex-shrink: 0;padding-block-end: 12px;@@ -20,10 +64,152 @@ const styles = createStaticStyles(({ css }) => ({`,}));+interface SkillFrontmatterBlockProps {+ documentId: string;+ frontmatter: string;+}++const SkillFrontmatterBlock = memo<SkillFrontmatterBlockProps>(({ documentId, frontmatter }) => {+ const { t } = useTranslation('editor');+ const metadata = useMemo(() => parseSkillMarkdownMetadata(frontmatter), [frontmatter]);+ const currentName = useMemo(+ () => parseSkillMarkdownFrontmatterFields(frontmatter).name,+ [frontmatter],+ );+ const [draft, setDraft] = useState(frontmatter);+ const [error, setError] = useState<string>();+ const [editing, setEditing] = useState(false);+ const [saving, setSaving] = useState(false);++ const [performSave, updateSkillFrontmatter] = useDocumentStore((s) => [+ s.performSave,+ s.updateSkillFrontmatter,+ ]);++ useEffect(() => {+ if (editing) return;+ setDraft(frontmatter);+ }, [editing, frontmatter]);++ const handleEdit = useCallback(() => {+ setDraft(frontmatter);+ setError(undefined);+ setEditing(true);+ }, [frontmatter]);++ const handleCancel = useCallback(() => {+ setDraft(frontmatter);+ setError(undefined);+ setEditing(false);+ }, [frontmatter]);++ const handleSave = useCallback(async () => {+ const nextError = getSkillMarkdownMetadataError(draft, { expectedName: currentName });+ if (nextError) {+ const message =+ nextError.type === 'nameLocked'+ ? t(`skillFrontmatter.invalid.${nextError.type}`, { name: nextError.expectedName })+ : t(`skillFrontmatter.invalid.${nextError.type}`);+ setError(message);+ return;+ }++ setSaving(true);+ try {+ const updated = updateSkillFrontmatter(documentId, draft);+ if (!updated) {+ setError(t('skillFrontmatter.saveFailed'));+ return;+ }++ await performSave(documentId, undefined, { saveSource: 'manual' });+ const latestDocument = useDocumentStore.getState().documents[documentId];+ if (latestDocument?.isDirty) {+ setError(t('skillFrontmatter.saveFailed'));+ return;+ }++ setEditing(false);+ setError(undefined);+ } finally {+ setSaving(false);+ }+ }, [currentName, documentId, draft, performSave, t, updateSkillFrontmatter]);++ return (+ <Flexbox className={styles.frontmatter}>+ <Flexbox horizontal align="center" className={styles.sectionHeader} justify="space-between">+ <Text type="secondary">{t('skillFrontmatter.title')}</Text>+ {editing ? (+ <Flexbox horizontal gap={8}>+ <Button icon={XIcon} size="small" variant="outlined" onClick={handleCancel}>+ {t('cancel')}+ </Button>+ <Button+ icon={CheckIcon}+ loading={saving}+ size="small"+ type="primary"+ onClick={handleSave}+ >+ {t('confirm')}+ </Button>+ </Flexbox>+ ) : (+ <ActionIcon+ icon={PencilIcon}+ size="small"+ title={t('skillFrontmatter.edit')}+ onClick={handleEdit}+ />+ )}+ </Flexbox>+ {editing ? (+ <Flexbox gap={8} padding={12}>+ {/* Raw YAML is only exposed in edit mode so users can keep advanced frontmatter syntax. */}+ <TextArea+ autoSize={{ maxRows: 12, minRows: 4 }}+ className={styles.textArea}+ value={draft}+ variant="borderless"+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) => {+ setDraft(event.target.value);+ setError(undefined);+ }}+ />+ {error && <Text type="danger">{error}</Text>}+ </Flexbox>+ ) : metadata.length > 0 ? (+ metadata.map((item) => (+ <Flexbox horizontal align="flex-start" className={styles.metadataRow} key={item.key}>+ <Text className={styles.metadataKey}>{item.key}</Text>+ <Text className={styles.metadataValue}>{item.value}</Text>+ </Flexbox>+ ))+ ) : (+ <Flexbox className={styles.metadataRow}>+ <Text type="secondary">{t('skillFrontmatter.empty')}</Text>+ </Flexbox>+ )}+ </Flexbox>+ );+});+const DocumentBody = memo(() => {+ const documentId = useChatStore(chatPortalSelectors.portalDocumentId);+ const [skillFrontmatter, contentFormat] = useDocumentStore((s) =>+ documentId+ ? [s.documents[documentId]?.skillFrontmatter ?? '', s.documents[documentId]?.contentFormat]+ : ['', undefined],+ );+ const isSkillMarkdown = contentFormat === 'skillMarkdown';+return (<Flexbox flex={1} height={'100%'} style={{ overflow: 'hidden' }}><div className={styles.content}>+ {documentId && isSkillMarkdown && (+ <SkillFrontmatterBlock documentId={documentId} frontmatter={skillFrontmatter} />+ )}<EditorCanvas /></div><div className={styles.todoContainer}>diff --git a/src/locales/default/editor.ts b/src/locales/default/editor.tsindex 4c906376f4d..09eefdd7514 100644--- a/src/locales/default/editor.ts+++ b/src/locales/default/editor.ts@@ -52,6 +52,19 @@ export default {'slash.table': 'Table','slash.tex': 'TeX Formula','slash.translate': 'Translate',+ 'skillFrontmatter.edit': 'Edit metadata',+ 'skillFrontmatter.empty': 'No metadata',+ 'skillFrontmatter.invalid.descriptionInvalid': 'Description must be single-line text.',+ 'skillFrontmatter.invalid.descriptionRequired': 'Description is required.',+ 'skillFrontmatter.invalid.mapping': 'Frontmatter must be a YAML mapping.',+ 'skillFrontmatter.invalid.nameInvalid': 'Name must use lowercase letters, numbers, and hyphens.',+ 'skillFrontmatter.invalid.nameLocked':+ 'Name must remain {{name}}. Rename the skill bundle instead.',+ 'skillFrontmatter.invalid.nameRequired': 'Name is required.',+ 'skillFrontmatter.invalid.required': 'Frontmatter is required.',+ 'skillFrontmatter.invalid.syntax': 'Invalid YAML syntax.',+ 'skillFrontmatter.saveFailed': 'Metadata was not saved. Retry, or keep editing.',+ 'skillFrontmatter.title': 'Skill metadata','table.delete': 'Delete table','table.deleteColumn': 'Delete column','table.deleteRow': 'Delete row',diff --git a/src/store/document/slices/document/action.ts b/src/store/document/slices/document/action.tsindex 4e76680db37..d3ad857ca55 100644--- a/src/store/document/slices/document/action.ts+++ b/src/store/document/slices/document/action.ts@@ -1,20 +1,21 @@'use client';import { EDITOR_DEBOUNCE_TIME, EDITOR_MAX_WAIT } from '@lobechat/const';-import { type DocumentItem } from '@lobechat/database/schemas';-import { type IEditor } from '@lobehub/editor';+import type { DocumentItem } from '@lobechat/database/schemas';+import type { IEditor } from '@lobehub/editor';import { debounce } from 'es-toolkit/compat';-import { type SWRResponse } from 'swr';+import type { SWRResponse } from 'swr';import { useClientDataSWRWithSync } from '@/libs/swr';import { documentService } from '@/services/document';import { documentSWRKeys } from '@/services/document/swrKeys';import { usePageStore } from '@/store/page';-import { type StoreSetter } from '@/store/types';+import type { StoreSetter } from '@/store/types';+import { isSkillMarkdownDocument, parseSkillMarkdownFrontmatter } from '@/utils/skillMarkdown';import { setNamespace } from '@/utils/storeDebug';-import { type DocumentStore } from '../../store';-import { type DocumentSourceType } from '../editor/initialState';+import type { DocumentStore } from '../../store';+import type { DocumentContentFormat, DocumentSourceType } from '../editor/initialState';const n = setNamespace('document/document');@@ -28,6 +29,7 @@ export interface InitDocumentParams {*/autoSave?: boolean;content?: string | null;+ contentFormat?: DocumentContentFormat;documentId: string;editor: IEditor;editorData?: unknown;@@ -137,9 +139,22 @@ export class DocumentActionImpl {* Content is loaded into editor via onEditorInit when Editor component is ready.*/initDocumentWithEditor = (params: InitDocumentParams): void => {- const { autoSave, content, documentId, editor, editorData, sourceType, topicId } = params;+ const {+ autoSave,+ content,+ contentFormat,+ documentId,+ editor,+ editorData,+ sourceType,+ topicId,+ } = params;const { internal_dispatchDocument } = this.#get();+ const skillFrontmatter =+ contentFormat === 'skillMarkdown'+ ? parseSkillMarkdownFrontmatter(content).frontmatter+ : undefined;// Add or update document via reducerinternal_dispatchDocument({@@ -148,11 +163,13 @@ export class DocumentActionImpl {value: {autoSave,content: content ?? undefined,+ contentFormat,editorData,lastSavedContent: content ?? undefined,lastSavedEditorData: editorData,sourceType,+ skillFrontmatter,topicId,},});@@ -225,6 +242,7 @@ export class DocumentActionImpl {this.#get().initDocumentWithEditor({autoSave,content: document.content,+ contentFormat: isSkillMarkdownDocument(document) ? 'skillMarkdown' : 'markdown',documentId,editor,editorData: document.editorData,diff --git a/src/store/document/slices/editor/action.test.ts b/src/store/document/slices/editor/action.test.tsindex 2f2628e077d..9bf4311bb41 100644--- a/src/store/document/slices/editor/action.test.ts+++ b/src/store/document/slices/editor/action.test.ts@@ -198,6 +198,127 @@ describe('DocumentStore - Editor Actions', () => {expect(mockEditor.setDocument).toHaveBeenCalledWith('markdown', '# Hello World');});+ it('should load only the editable body for SKILL.md frontmatter documents', () => {+ const { result } = renderHook(() => useDocumentStore());+ const mockEditor = createMockEditor() as any;+ const skillContent = `---+description: >-+ Retrieves comments from YouTube videos.+name: youtube-comment-retrieval-workflow+---++# YouTube Comment Retrieval Workflow`;++ act(() => {+ result.current.initDocumentWithEditor({+ content: skillContent,+ contentFormat: 'skillMarkdown',+ documentId: 'doc-1',+ editor: mockEditor,+ sourceType: 'notebook',+ });+ });++ act(() => {+ result.current.onEditorInit(mockEditor);+ });++ expect(mockEditor.setDocument).toHaveBeenCalledWith(+ 'markdown',+ '# YouTube Comment Retrieval Workflow',+ );+ expect(result.current.documents['doc-1'].skillFrontmatter).toContain(+ 'youtube-comment-retrieval-workflow',+ );+ });++ it('should preserve existing editorData for SKILL.md documents', () => {+ const { result } = renderHook(() => useDocumentStore());+ const mockEditor = createMockEditor() as any;+ const editorData = {+ root: {+ children: [+ {+ children: [+ { children: [{ text: 'origin', type: 'text' }], type: 'paragraph' },+ { children: [{ text: 'modified', type: 'text' }], type: 'paragraph' },+ ],+ diffType: 'modify',+ type: 'diff',+ },+ ],+ type: 'root',+ },+ };++ act(() => {+ result.current.initDocumentWithEditor({+ content: `---+description: Skill metadata+name: skill-name+---++# Body`,+ contentFormat: 'skillMarkdown',+ documentId: 'doc-1',+ editor: mockEditor,+ editorData,+ sourceType: 'notebook',+ });+ });++ act(() => {+ result.current.onEditorInit(mockEditor);+ });++ expect(mockEditor.setDocument).toHaveBeenCalledTimes(1);+ expect(mockEditor.setDocument).toHaveBeenCalledWith('json', JSON.stringify(editorData));+ });++ it('should fall back to editable body when SKILL.md editorData cannot be loaded', () => {+ const { result } = renderHook(() => useDocumentStore());+ const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const editorData = {+ root: { children: [{ children: [], type: 'paragraph' }], type: 'root' },+ };+ const mockEditor = {+ getDocument: vi.fn(),+ setDocument: vi.fn((type: string) => {+ if (type === 'json') {+ throw new Error('editorData unavailable');+ }+ }),+ } as any;++ act(() => {+ result.current.initDocumentWithEditor({+ content: `---+description: Skill metadata+name: skill-name+---++# Body`,+ contentFormat: 'skillMarkdown',+ documentId: 'doc-1',+ editor: mockEditor,+ editorData,+ sourceType: 'notebook',+ });+ });++ act(() => {+ result.current.onEditorInit(mockEditor);+ });++ expect(consoleWarn).toHaveBeenCalledWith(+ '[DocumentStore] Failed to load SKILL.md editorData, falling back to markdown',+ );+ expect(mockEditor.setDocument).toHaveBeenNthCalledWith(1, 'json', JSON.stringify(editorData));+ expect(mockEditor.setDocument).toHaveBeenNthCalledWith(2, 'markdown', '# Body');++ consoleWarn.mockRestore();+ });+it('should load editorData as json into editor', () => {const { result } = renderHook(() => useDocumentStore());const mockEditor = createMockEditor() as any;@@ -253,6 +374,43 @@ describe('DocumentStore - Editor Actions', () => {JSON.stringify(EMPTY_EDITOR_STATE),);});++ it('should fail safely when SKILL.md body cannot be loaded into the editor', async () => {+ const { result } = renderHook(() => useDocumentStore());+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const mockEditor = {+ getDocument: vi.fn(),+ setDocument: vi.fn(() => {+ throw new Error('editor unavailable');+ }),+ } as any;++ act(() => {+ result.current.initDocumentWithEditor({+ content: `---+description: Skill metadata+name: skill-name+---++# Body`,+ contentFormat: 'skillMarkdown',+ documentId: 'doc-1',+ editor: mockEditor,+ sourceType: 'notebook',+ });+ });++ await act(async () => {+ await result.current.onEditorInit(mockEditor);+ });++ expect(consoleError).toHaveBeenCalledWith(+ '[DocumentStore] Failed to load SKILL.md content:',+ expect.any(Error),+ );++ consoleError.mockRestore();+ });});describe('closeDocument', () => {@@ -365,6 +523,208 @@ describe('DocumentStore - Editor Actions', () => {isDirty: true,});});++ it('should preserve SKILL.md frontmatter when syncing editor body changes', () => {+ const { result } = renderHook(() => useDocumentStore());+ const editorData = {+ root: { children: [{ children: [], type: 'paragraph' }], type: 'root' },+ };+ const mockEditor = {+ getDocument: vi.fn((type: string) => {+ if (type === 'markdown') return '# Updated Skill';+ if (type === 'json') return editorData;+ return null;+ }),+ setDocument: vi.fn(),+ } as any;++ act(() => {+ result.current.initDocumentWithEditor({+ content: `---+description: Skill metadata+name: skill-name+---++# Original Skill`,+ contentFormat: 'skillMarkdown',+ documentId: 'doc-1',+ editor: mockEditor,+ editorData,+ sourceType: 'notebook',+ });+ });++ act(() => {+ result.current.handleContentChange();+ });++ expect(result.current.documents['doc-1']).toMatchObject({+ content: `---+description: Skill metadata+name: skill-name+---++# Updated Skill`,+ isDirty: true,+ });+ });++ it('should update SKILL.md frontmatter while preserving the editor body', () => {+ const { result } = renderHook(() => useDocumentStore());+ const editorData = {+ root: { children: [{ children: [], type: 'paragraph' }], type: 'root' },+ };+ const mockEditor = {+ getDocument: vi.fn((type: string) => {+ if (type === 'markdown') return '# Current Body';+ if (type === 'json') return editorData;+ return null;+ }),+ setDocument: vi.fn(),+ } as any;++ act(() => {+ result.current.initDocumentWithEditor({+ content: `---+description: Old metadata+name: old-skill+---++# Original Body`,+ contentFormat: 'skillMarkdown',+ documentId: 'doc-1',+ editor: mockEditor,+ editorData,+ sourceType: 'notebook',+ });+ });++ act(() => {+ result.current.updateSkillFrontmatter(+ 'doc-1',+ `description: New metadata+name: new-skill`,+ );+ });++ expect(result.current.documents['doc-1']).toMatchObject({+ content: `---+description: New metadata+name: new-skill+---++# Current Body`,+ isDirty: true,+ skillFrontmatter: `description: New metadata+name: new-skill`,+ });+ });++ it('should update an inactive SKILL.md document from stored content', () => {+ const { result } = renderHook(() => useDocumentStore());+ const mockEditor = createMockEditor() as any;+ const editorData = {+ root: { children: [{ children: [], type: 'paragraph' }], type: 'root' },+ };++ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Active',+ documentId: 'doc-active',+ editor: mockEditor,+ sourceType: 'notebook',+ });+ result.current.initDocumentWithEditor({+ content: `---+description: Old metadata+name: old-skill+---++# Stored Body`,+ contentFormat: 'skillMarkdown',+ documentId: 'doc-inactive',+ editor: mockEditor,+ editorData,+ sourceType: 'notebook',+ });+ result.current.initDocumentWithEditor({+ content: '# Active',+ documentId: 'doc-active',+ editor: mockEditor,+ sourceType: 'notebook',+ });+ });++ act(() => {+ result.current.updateSkillFrontmatter(+ 'doc-inactive',+ `description: New metadata+name: new-skill`,+ );+ });++ expect(result.current.documents['doc-inactive']).toMatchObject({+ content: `---+description: New metadata+name: new-skill+---++# Stored Body`,+ editorData,+ isDirty: true,+ });+ });++ it('should reject frontmatter updates for missing or non-SKILL documents', () => {+ const { result } = renderHook(() => useDocumentStore());+ const mockEditor = createMockEditor() as any;++ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Markdown',+ documentId: 'doc-1',+ editor: mockEditor,+ sourceType: 'notebook',+ });+ });++ expect(result.current.updateSkillFrontmatter('missing', 'name: skill')).toBe(false);+ expect(result.current.updateSkillFrontmatter('doc-1', 'name: skill')).toBe(false);+ });++ it('should fail safely when active SKILL.md frontmatter update cannot read editor content', () => {+ const { result } = renderHook(() => useDocumentStore());+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const mockEditor = {+ getDocument: vi.fn(() => {+ throw new Error('editor unavailable');+ }),+ setDocument: vi.fn(),+ } as any;++ act(() => {+ result.current.initDocumentWithEditor({+ content: `---+description: Skill metadata+name: skill-name+---++# Body`,+ contentFormat: 'skillMarkdown',+ documentId: 'doc-1',+ editor: mockEditor,+ sourceType: 'notebook',+ });+ });++ expect(result.current.updateSkillFrontmatter('doc-1', 'name: skill-name')).toBe(false);+ expect(consoleError).toHaveBeenCalledWith(+ '[DocumentStore] Failed to update SKILL.md frontmatter:',+ expect.any(Error),+ );++ consoleError.mockRestore();+ });});describe('commitEditorMutation', () => {@@ -640,5 +1000,60 @@ describe('DocumentStore - Editor Actions', () => {);expect(result.current.documents['doc-1'].isDirty).toBe(false);});++ it('should save SKILL.md with its original frontmatter restored', async () => {+ const { result } = renderHook(() => useDocumentStore());+ const editorData = {+ root: { children: [{ children: [], type: 'paragraph' }], type: 'root' },+ };+ const mockEditor = {+ getDocument: vi.fn((type: string) => {+ if (type === 'markdown') return '# Updated Skill';+ if (type === 'json') return editorData;+ return null;+ }),+ setDocument: vi.fn(),+ } as any;++ act(() => {+ result.current.initDocumentWithEditor({+ content: `---+description: Skill metadata+name: skill-name+---++# Original Skill`,+ contentFormat: 'skillMarkdown',+ documentId: 'doc-1',+ editor: mockEditor,+ sourceType: 'notebook',+ });+ result.current.markDirty('doc-1');+ });++ await act(async () => {+ await result.current.performSave('doc-1');+ });++ const expectedContent = `---+description: Skill metadata+name: skill-name+---++# Updated Skill`;++ expect(documentService.updateDocument).toHaveBeenCalledWith(+ expect.objectContaining({+ content: expectedContent,+ editorData: JSON.stringify(editorData),+ id: 'doc-1',+ }),+ );+ expect(result.current.documents['doc-1']).toMatchObject({+ content: expectedContent,+ isDirty: false,+ lastSavedContent: expectedContent,+ });+ });});});diff --git a/src/store/document/slices/editor/action.ts b/src/store/document/slices/editor/action.tsindex 656f47020c1..aed3ef92631 100644--- a/src/store/document/slices/editor/action.ts+++ b/src/store/document/slices/editor/action.ts@@ -8,6 +8,7 @@ import { EMPTY_EDITOR_STATE } from '@/libs/editor/constants';import { isValidEditorData } from '@/libs/editor/isValidEditorData';import { documentService } from '@/services/document';import type { StoreSetter } from '@/store/types';+import { composeSkillMarkdown, parseSkillMarkdownFrontmatter } from '@/utils/skillMarkdown';import { setNamespace } from '@/utils/storeDebug';import type { DocumentStore } from '../../store';@@ -43,14 +44,23 @@ export class EditorActionImpl {this.#get = get;}+ private getPersistedMarkdown = (documentId: string | undefined, markdown: string): string => {+ if (!documentId) return markdown;++ const doc = this.#get().documents[documentId];+ if (doc?.contentFormat !== 'skillMarkdown') return markdown;++ return composeSkillMarkdown(doc.skillFrontmatter, markdown);+ };+getEditorContent = (): { editorData: any; markdown: string } | null => {- const { editor } = this.#get();+ const { activeDocumentId, editor } = this.#get();if (!editor) return null;try {const markdown = (editor.getDocument('markdown') as unknown as string) || '';const editorData = editor.getDocument('json');- return { editorData, markdown };+ return { editorData, markdown: this.getPersistedMarkdown(activeDocumentId, markdown) };} catch (error) {console.error('[DocumentStore] Failed to get editor content:', error);return null;@@ -70,7 +80,8 @@ export class EditorActionImpl {if (!doc) return false;try {- const markdown = (editor.getDocument('markdown') as unknown as string) || '';+ const editorMarkdown = (editor.getDocument('markdown') as unknown as string) || '';+ const markdown = this.getPersistedMarkdown(id, editorMarkdown);const editorData = editor.getDocument('json');const markdownChanged = markdown !== doc.lastSavedContent;@@ -113,6 +124,44 @@ export class EditorActionImpl {this.syncEditorContent(undefined, { triggerAutoSave: true });};+ updateSkillFrontmatter = (documentId: string, frontmatter: string): boolean => {+ const { activeDocumentId, documents, editor, internal_dispatchDocument } = this.#get();+ const doc = documents[documentId];++ if (!doc || doc.contentFormat !== 'skillMarkdown') return false;++ try {+ const isActiveDocument = activeDocumentId === documentId;+ const body =+ isActiveDocument && editor+ ? (editor.getDocument('markdown') as unknown as string) || ''+ : parseSkillMarkdownFrontmatter(doc.content).body;+ const editorData = isActiveDocument && editor ? editor.getDocument('json') : doc.editorData;+ const content = composeSkillMarkdown(frontmatter, body);+ const contentChanged = content !== doc.lastSavedContent;+ const editorDataChanged = !isEqual(editorData, doc.lastSavedEditorData);++ internal_dispatchDocument(+ {+ id: documentId,+ type: 'updateDocument',+ value: {+ content,+ editorData,+ isDirty: contentChanged || editorDataChanged,+ skillFrontmatter: frontmatter,+ },+ },+ 'updateSkillFrontmatter',+ );++ return true;+ } catch (error) {+ console.error('[DocumentStore] Failed to update SKILL.md frontmatter:', error);+ return false;+ }+ };+internal_dispatchDocument = (payload: DocumentDispatch, action?: string): void => {const { documents } = this.#get();const nextDocuments = documentReducer(documents, payload);@@ -147,6 +196,31 @@ export class EditorActionImpl {typeof doc.editorData === 'object' &&Object.keys(doc.editorData).length > 0;+ // SKILL.md frontmatter is metadata, not editable document body. Keep it out of the rich+ // Markdown editor because `---` fences are otherwise parsed as Markdown dividers/headings,+ // then stitch the same YAML back into the persisted content during save.+ if (doc.contentFormat === 'skillMarkdown') {+ if (hasValidEditorData) {+ try {+ editor.setDocument('json', JSON.stringify(doc.editorData));+ return;+ } catch {+ console.warn(+ '[DocumentStore] Failed to load SKILL.md editorData, falling back to markdown',+ );+ }+ }++ try {+ editor.setDocument('markdown', parseSkillMarkdownFrontmatter(doc.content).body);+ this.#set({ editor });+ } catch (err) {+ console.error('[DocumentStore] Failed to load SKILL.md content:', err);+ }++ return;+ }+// Set content from document stateif (hasValidEditorData) {try {@@ -193,7 +267,8 @@ export class EditorActionImpl {internal_dispatchDocument({ id, type: 'updateDocument', value: { saveStatus: 'saving' } });try {- const currentContent = (editor.getDocument('markdown') as unknown as string) || '';+ const currentEditorMarkdown = (editor.getDocument('markdown') as unknown as string) || '';+ const currentContent = this.getPersistedMarkdown(id, currentEditorMarkdown);const currentEditorData = editor.getDocument('json');if (!isValidEditorData(currentEditorData)) {@@ -220,6 +295,7 @@ export class EditorActionImpl {id,type: 'updateDocument',value: {+ content: currentContent,editorData: structuredClone(currentEditorData),isDirty: false,diff --git a/src/store/document/slices/editor/initialState.ts b/src/store/document/slices/editor/initialState.tsindex 004b20426ef..0a9fa98dda0 100644--- a/src/store/document/slices/editor/initialState.ts+++ b/src/store/document/slices/editor/initialState.ts@@ -1,12 +1,13 @@'use client';-import { type IEditor } from '@lobehub/editor';-import { type EditorState as LobehubEditorState } from '@lobehub/editor/react';+import type { IEditor } from '@lobehub/editor';+import type { EditorState as LobehubEditorState } from '@lobehub/editor/react';/*** Document source type - determines which service to use for persistence*/export type DocumentSourceType = 'notebook' | 'page';+export type DocumentContentFormat = 'markdown' | 'skillMarkdown';/*** Editor content state for a single document@@ -22,6 +23,10 @@ export interface EditorContentState {* Document content (markdown)*/content: string;+ /**+ * Content format used by the editor persistence pipeline.+ */+ contentFormat?: DocumentContentFormat;/*** Editor JSON data (BlockNote format)*/@@ -47,6 +52,11 @@ export interface EditorContentState {* Current save status*/saveStatus: 'idle' | 'saving' | 'saved';+ /**+ * YAML frontmatter for SKILL.md documents. It is kept outside the rich Markdown editor because+ * the editor parses the closing `---` as a Setext heading underline and renders metadata as a giant heading.+ */+ skillFrontmatter?: string;/*** Document source type - determines which service to call for persistence*/diff --git a/src/utils/skillMarkdown.test.ts b/src/utils/skillMarkdown.test.tsnew file mode 100644index 00000000000..49e32f8dd28--- /dev/null+++ b/src/utils/skillMarkdown.test.ts@@ -0,0 +1,183 @@+import { describe, expect, it, vi } from 'vitest';++import {+ composeSkillMarkdown,+ getSkillMarkdownMetadataError,+ isSkillMarkdownDocument,+ parseSkillMarkdownFrontmatter,+ parseSkillMarkdownFrontmatterFields,+ parseSkillMarkdownMetadata,+} from './skillMarkdown';++describe('skillMarkdown', () => {+ it('extracts SKILL.md frontmatter and body', () => {+ const content = `---+description: >-+ Use when given a YouTube video link.+name: youtube-comment-retrieval-workflow+---++# Workflow`;++ expect(parseSkillMarkdownFrontmatter(content)).toEqual({+ body: '# Workflow',+ frontmatter: `description: >-+ Use when given a YouTube video link.+name: youtube-comment-retrieval-workflow`,+ });+ });++ it('extracts SKILL.md frontmatter after a BOM or leading whitespace', () => {+ const content = `\uFEFF++ ---+description: Skill metadata+name: skill-name+---++# Workflow`;++ expect(parseSkillMarkdownFrontmatter(content)).toEqual({+ body: '# Workflow',+ frontmatter: `description: Skill metadata+name: skill-name`,+ });+ });++ it('keeps ordinary Markdown unchanged when frontmatter is absent', () => {+ const content = `++# Workflow`;++ expect(parseSkillMarkdownFrontmatter(content)).toEqual({ body: content });+ });++ it('parses folded YAML scalars for display without control markers', () => {+ expect(+ parseSkillMarkdownMetadata(`description: >-+ Use when given a YouTube video link+ and retrieve comments.+name: youtube-comment-retrieval-workflow`),+ ).toEqual([+ {+ key: 'description',+ value: 'Use when given a YouTube video link and retrieve comments.',+ },+ {+ key: 'name',+ value: 'youtube-comment-retrieval-workflow',+ },+ ]);+ });++ it('stringifies non-string metadata values for display', () => {+ expect(+ parseSkillMarkdownMetadata(`enabled: true+retries: 2+resources:+ - reference.md+optional:`),+ ).toEqual([+ { key: 'enabled', value: 'true' },+ { key: 'retries', value: '2' },+ { key: 'resources', value: '["reference.md"]' },+ { key: 'optional', value: '' },+ ]);+ });++ it('reads frontmatter fields used by the metadata editor', () => {+ expect(+ parseSkillMarkdownFrontmatterFields(`name: skill-name+description: >-+ Use when given a YouTube video link+ and retrieve comments.`),+ ).toEqual({+ description: 'Use when given a YouTube video link and retrieve comments.',+ name: 'skill-name',+ });+ });++ it('returns empty frontmatter fields for invalid or non-mapping YAML', () => {+ expect(parseSkillMarkdownFrontmatterFields('description: [')).toEqual({});+ expect(parseSkillMarkdownFrontmatterFields('- name')).toEqual({});+ expect(parseSkillMarkdownFrontmatterFields()).toEqual({});+ });++ it('recomposes frontmatter with the edited body', () => {+ expect(composeSkillMarkdown('name: skill-name', '# Updated')).toBe(`---+name: skill-name+---++# Updated`);+ });++ it('recomposes edge cases without duplicating spacing', () => {+ expect(composeSkillMarkdown(undefined, '# Body')).toBe('# Body');+ expect(composeSkillMarkdown('name: skill-name\n', '')).toBe(`---+name: skill-name+---+`);+ expect(composeSkillMarkdown('name: skill-name', '\n# Body')).toBe(`---+name: skill-name+---++# Body`);+ });++ it('detects SKILL.md documents from document metadata', () => {+ expect(isSkillMarkdownDocument({ fileType: 'skills/index' })).toBe(true);+ expect(isSkillMarkdownDocument({ filename: 'SKILL.md' })).toBe(true);+ expect(isSkillMarkdownDocument({ title: 'SKILL.md' })).toBe(true);+ expect(isSkillMarkdownDocument({ filename: 'README.md' })).toBe(false);+ });++ it('returns an empty metadata list for invalid YAML', () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ expect(parseSkillMarkdownMetadata('description: [')).toEqual([]);++ consoleError.mockRestore();+ });++ it('validates editable YAML frontmatter', () => {+ expect(+ getSkillMarkdownMetadataError(`name: skill-name+description: Skill description`),+ ).toBeUndefined();+ expect(getSkillMarkdownMetadataError('')).toEqual({ type: 'required' });+ expect(getSkillMarkdownMetadataError('- name')).toEqual({ type: 'mapping' });+ expect(getSkillMarkdownMetadataError('description: [')).toEqual({ type: 'syntax' });+ expect(getSkillMarkdownMetadataError('description: Skill description')).toEqual({+ type: 'nameRequired',+ });+ expect(+ getSkillMarkdownMetadataError(`name: Skill Name+description: Skill description`),+ ).toEqual({ type: 'nameInvalid' });+ expect(+ getSkillMarkdownMetadataError(`name: 123+description: Skill description`),+ ).toEqual({ type: 'nameInvalid' });+ expect(getSkillMarkdownMetadataError('name: skill-name')).toEqual({+ type: 'descriptionRequired',+ });+ expect(+ getSkillMarkdownMetadataError(`name: skill-name+description:+ - list item`),+ ).toEqual({ type: 'descriptionInvalid' });+ expect(+ getSkillMarkdownMetadataError(`name: skill-name+description: |+ Line 1+ Line 2`),+ ).toEqual({ type: 'descriptionInvalid' });+ expect(+ getSkillMarkdownMetadataError(+ `name: other-name+description: Skill description`,+ { expectedName: 'skill-name' },+ ),+ ).toEqual({ expectedName: 'skill-name', type: 'nameLocked' });+ });+});diff --git a/src/utils/skillMarkdown.ts b/src/utils/skillMarkdown.tsnew file mode 100644index 00000000000..309d3fff10c--- /dev/null+++ b/src/utils/skillMarkdown.ts@@ -0,0 +1,200 @@+import { parse } from 'yaml';++const SKILL_INDEX_FILENAME = 'SKILL.md';+const SKILL_INDEX_FILE_TYPE = 'skills/index';+const SKILL_MARKDOWN_LEADING_WHITESPACE_REGEX = /^\uFEFF?[ \t]*(?:\r?\n[ \t]*)*/;+const SKILL_MARKDOWN_FRONTMATTER_REGEX =+ /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)([\s\S]*)$/;+const SKILL_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;+const MAX_SKILL_NAME_LENGTH = 80;+const UNSAFE_FRONTMATTER_SCALAR_PATTERN = /[\r\n]/;++interface SkillMarkdownDocumentFields {+ filename?: string | null;+ fileType?: string | null;+ title?: string | null;+}++interface SkillMarkdownParts {+ body: string;+ frontmatter?: string;+}++export interface SkillMarkdownMetadataItem {+ key: string;+ value: string;+}++export interface SkillMarkdownFrontmatterFields {+ description?: string;+ name?: string;+}++interface SkillMarkdownMetadataValidationOptions {+ expectedName?: string;+}++export type SkillMarkdownMetadataError =+ | {+ type: 'required';+ }+ | {+ type: 'mapping';+ }+ | {+ type: 'nameRequired';+ }+ | {+ type: 'nameInvalid';+ }+ | {+ expectedName: string;+ type: 'nameLocked';+ }+ | {+ type: 'descriptionRequired';+ }+ | {+ type: 'descriptionInvalid';+ }+ | {+ type: 'syntax';+ };++export const isSkillMarkdownDocument = (document: SkillMarkdownDocumentFields): boolean =>+ document.fileType === SKILL_INDEX_FILE_TYPE ||+ document.filename === SKILL_INDEX_FILENAME ||+ document.title === SKILL_INDEX_FILENAME;++export const parseSkillMarkdownFrontmatter = (content?: string | null): SkillMarkdownParts => {+ if (!content) return { body: '' };++ const normalizedContent = content.replace(SKILL_MARKDOWN_LEADING_WHITESPACE_REGEX, '');+ const match = normalizedContent.match(SKILL_MARKDOWN_FRONTMATTER_REGEX);+ if (!match) return { body: content };++ return {+ body: match[2].replace(/^\r?\n/, ''),+ frontmatter: match[1],+ };+};++export const composeSkillMarkdown = (frontmatter: string | undefined, body: string): string => {+ if (!frontmatter) return body;++ const normalizedFrontmatter = frontmatter.trimEnd();+ if (!body) return `---\n${normalizedFrontmatter}\n---\n`;++ return `---\n${normalizedFrontmatter}\n---\n\n${body.replace(/^\r?\n/, '')}`;+};++const stringifyMetadataValue = (value: unknown): string => {+ if (value === null || value === undefined) return '';+ if (typeof value === 'string') return value;+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);++ return JSON.stringify(value);+};++const isRecord = (value: unknown): value is Record<string, unknown> =>+ !!value && typeof value === 'object' && !Array.isArray(value);++const isValidSkillName = (name: string): boolean =>+ !!name &&+ name.length <= MAX_SKILL_NAME_LENGTH &&+ SKILL_NAME_PATTERN.test(name) &&+ !name.includes('/') &&+ !name.includes('\\') &&+ name !== '.' &&+ name !== '..';++const readFrontmatterStringField = (+ data: Record<string, unknown>,+ field: keyof SkillMarkdownFrontmatterFields,+): string | undefined => {+ const value = data[field];+ return typeof value === 'string' ? value.trim() : undefined;+};++export const parseSkillMarkdownFrontmatterFields = (+ frontmatter?: string,+): SkillMarkdownFrontmatterFields => {+ if (!frontmatter) return {};++ try {+ const parsed = parse(frontmatter) as unknown;+ if (!isRecord(parsed)) return {};++ return {+ description: readFrontmatterStringField(parsed, 'description'),+ name: readFrontmatterStringField(parsed, 'name'),+ };+ } catch {+ return {};+ }+};++export const getSkillMarkdownMetadataError = (+ frontmatter?: string,+ options?: SkillMarkdownMetadataValidationOptions,+): SkillMarkdownMetadataError | undefined => {+ if (!frontmatter?.trim()) return { type: 'required' };++ try {+ const parsed = parse(frontmatter) as unknown;+ if (!isRecord(parsed)) {+ return { type: 'mapping' };+ }++ // Keep this client-side guard aligned with server skillManagement/frontmatter.ts so the+ // metadata editor cannot persist SKILL.md frontmatter that later skill code rejects.+ const nameValue = parsed.name;+ if (nameValue === undefined || (typeof nameValue === 'string' && !nameValue.trim())) {+ return { type: 'nameRequired' };+ }+ if (typeof nameValue !== 'string') return { type: 'nameInvalid' };++ const name = nameValue.trim();+ if (!isValidSkillName(name)) return { type: 'nameInvalid' };++ const expectedName = options?.expectedName?.trim();+ if (expectedName && isValidSkillName(expectedName) && name !== expectedName) {+ return { expectedName, type: 'nameLocked' };+ }++ const descriptionValue = parsed.description;+ if (+ descriptionValue === undefined ||+ (typeof descriptionValue === 'string' && !descriptionValue.trim())+ ) {+ return { type: 'descriptionRequired' };+ }+ if (typeof descriptionValue !== 'string') return { type: 'descriptionInvalid' };++ const description = descriptionValue.trim();+ if (UNSAFE_FRONTMATTER_SCALAR_PATTERN.test(description)) {+ return { type: 'descriptionInvalid' };+ }++ return undefined;+ } catch {+ return { type: 'syntax' };+ }+};++export const parseSkillMarkdownMetadata = (frontmatter?: string): SkillMarkdownMetadataItem[] => {+ if (!frontmatter) return [];++ try {+ const parsed = parse(frontmatter) as unknown;+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return [];++ return Object.entries(parsed as Record<string, unknown>).map(([key, value]) => ({+ key,+ value: stringifyMetadataValue(value),+ }));+ } catch (error) {+ console.error('[SkillMarkdown] Failed to parse SKILL.md frontmatter:', error);+ return [];+ }+};