An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Restore agent insert commands and atomic skills https://github.com/siyuan-note/siyuan/issues/19696
Danielf14e71f46d11
diff --git a/app/src/layout/dock/agent/AgentComposer.ts b/app/src/layout/dock/agent/AgentComposer.tsindex 7d3258766f..83a6c48fe0 100644--- a/app/src/layout/dock/agent/AgentComposer.ts+++ b/app/src/layout/dock/agent/AgentComposer.ts@@ -1,7 +1,8 @@import {Constants} from "../../../constants";import {escapeHtml} from "../../../util/escape";import {fetchPost} from "../../../util/fetch";-import {hintRef} from "../../../protyle/hint/extend";+import {hintRef, hintSlash} from "../../../protyle/hint/extend";+import {registerBuiltinSlashHint} from "../../../protyle/hint/builtinSlash";import {blockRender} from "../../../protyle/render/blockRender";import {matchHotKey} from "../../../protyle/util/hotKey";import {isSkillHintRequestActive, shouldYieldSkillHint} from "./agentHintState";@@ -9,6 +10,7 @@ import {uploadFiles} from "../../../protyle/upload";import {previewImages} from "../../../protyle/preview/image";import {removeCompressURL} from "../../../util/image";import {mountProtyleLiteFragment} from "../../../protyle/lite/fragmentEditor";+import {AGENT_SKILL_SELECTOR, expandAgentSkillSelection, normalizeAgentSkills} from "./agentSkill";export interface AgentComposerData {text: string;@@ -35,8 +37,8 @@ interface ComposerHandle {type OnChangeCallback = () => void;const AGENT_HINT_OVERLAY_CLASS = "protyle-hint--agent-overlay";-const AGENT_SKILL_SELECTOR = '[data-type~="text"][custom-agent-skill="true"]';const skillHintRequestIDs = new WeakMap<IProtyle, number>();+const skillSlashCommands = new WeakMap<IProtyle, Set<string>>();interface ComposerOptions {initialContent?: string;@@ -71,7 +73,7 @@ const hintAgentRef = (key: string, protyle: IProtyle, source: THintSource): IHin// / 技能菜单:异步拉取 lsSkills,选中后把技能名作为带持久标识的智能体行级元素插入。// 返回 [] 占位,数据在 fetch 回调里通过 protyle.hint.genHTML 填充(与 hintRef 异步模式一致)。-const hintSkill = (key: string, protyle: IProtyle): IHintData[] => {+const hintSkill = registerBuiltinSlashHint((key: string, protyle: IProtyle): IHintData[] => {const requestID = (skillHintRequestIDs.get(protyle) || 0) + 1;skillHintRequestIDs.set(protyle, requestID);if (shouldYieldSkillHint(key, protyle.options.hint.extend.map((item) => item.key))) {@@ -80,9 +82,15 @@ const hintSkill = (key: string, protyle: IProtyle): IHintData[] => {return [];}prepareAgentHint(protyle);- // 每次查询都切换到加载状态,避免已有候选项让异步占位结果关闭菜单。- protyle.hint.genHTML([], protyle, true, "hint");- protyle.hint.genLoading(protyle);+ // 加号面板保留精简编辑器支持的插入项,直接输入斜杠时仍只查询技能。+ const insertItems = protyle.hint.element.closest("#keyboardToolbar") ? hintSlash("", protyle, "hint") : [];+ skillSlashCommands.set(protyle, new Set(insertItems.filter(item => item.html !== "separator").map(item => item.value)));+ if (insertItems.length > 0) {+ protyle.hint.genHTML(insertItems, protyle, false, "hint");+ } else {+ protyle.hint.genHTML([], protyle, true, "hint");+ protyle.hint.genLoading(protyle);+ }fetchPost("/api/ai/agent/lsSkills", {}, (response) => {// 异步响应返回时输入状态可能已变化,避免 Esc 或其他提示触发后重新打开旧菜单。if (!isSkillHintRequestActive({@@ -102,20 +110,26 @@ const hintSkill = (key: string, protyle: IProtyle): IHintData[] => {.filter((s: Record<string, string>) => !q ||(s.name || "").toLowerCase().includes(q) || (s.description || "").toLowerCase().includes(q)).map((s: Record<string, string>) => ({- value: '<span data-type="text" custom-agent-skill="true">' ++ value: '<span data-type="text" custom-agent-skill="true" contenteditable="false">' +escapeHtml(s.name) + "</span> ",html: '<div class="b3-list-item__first"><svg class="b3-list-item__graphic">' +'<use xlink:href="#iconSparkles"></use></svg><span class="b3-list-item__text">' +escapeHtml(s.name) + "</span></div>" +(s.description ? '<div class="b3-list-item__meta b3-list-item__showall">' + escapeHtml(s.description) + "</div>" : ""),}));+ if (insertItems.length > 0) {+ if (dataList.length > 0) {+ dataList.unshift({value: "", html: "separator"});+ }+ dataList.unshift(...insertItems);+ }if (dataList.length === 0) {dataList.push({value: "", html: window.siyuan.languages.emptyContent});}protyle.hint.genHTML(dataList, protyle, false, "hint");});return [];-};+}, (value, protyle) => skillSlashCommands.get(protyle)?.has(value) ?? false);// 已发送消息历史(↑↓ 翻阅),独立于 protyle 的 undo/redo。class ComposerHistory {@@ -196,7 +210,10 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:placeholder: options.placeholder || L.agentInputPlaceholder,emptyClass: "agent-composer--empty",hintOverlayClass: AGENT_HINT_OVERLAY_CLASS,- onChange,+ onChange: () => {+ normalizeAgentSkills(host);+ onChange?.();+ },protyleOptions: {hint: {// / 技能菜单(覆盖默认的块插入菜单 hintSlash);[[ 块引用由 protyle 默认 extend 提供@@ -225,6 +242,7 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:websocket: false,},afterSetContent: (protyle, element) => {+ normalizeAgentSkills(element);resetEmbedBlocks(element);blockRender(protyle, element);},@@ -233,6 +251,19 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:const p = fragment.protyle;const wysiwyg = p.wysiwyg!;+ const prepareSkillSelection = () => {+ const selection = getSelection();+ if (selection.rangeCount > 0) {+ const range = selection.getRangeAt(0);+ if (wysiwyg.element.contains(range.commonAncestorContainer)) {+ expandAgentSkillSelection(range);+ }+ }+ };+ ["beforeinput", "cut", "paste"].forEach(type => {+ wysiwyg.element.addEventListener(type, prepareSkillSelection, true);+ });+// 智能体输入框没有文档 ID,直接预览输入框中的图片,避免走依赖文档资源列表的默认逻辑。wysiwyg.element.addEventListener("dblclick", (event: MouseEvent) => {const image = (event.target as HTMLElement).closest("img:not(.emoji)") as HTMLImageElement | null;@@ -256,6 +287,7 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:if (event.isComposing) {return;}+ prepareSkillSelection();// hint 面板可见时,Enter/方向键主动调 hint.select 完成选择,避免 capture 与冒泡的时序问题。const hintEl = p.hint?.element;if (hintEl && !hintEl.classList.contains("fn__none")) {diff --git a/app/src/layout/dock/agent/agentSkill.test.ts b/app/src/layout/dock/agent/agentSkill.test.tsnew file mode 100644index 0000000000..bb1d89a18b--- /dev/null+++ b/app/src/layout/dock/agent/agentSkill.test.ts@@ -0,0 +1,200 @@+import * as assert from "node:assert/strict";+import {execFile} from "node:child_process";+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";+import {tmpdir} from "node:os";+import * as path from "node:path";+import {test} from "node:test";+import {promisify} from "node:util";+import {createSourceFile, isClassDeclaration, isMethodDeclaration, isVariableStatement, ScriptTarget, transpileModule} from "typescript";++const browserCases = async (source: string) => {+ const check: typeof assert = require("node:assert/strict");+ window.siyuan = {languages: {emptyContent: "Empty"}, zIndex: 1} as unknown as typeof window.siyuan;+ const requests: Array<(response: {data: Array<{name: string; description: string}>}) => void> = [];+ const insertItems: IHintData[] = [{id: "bold", value: "strong", html: "Bold"}];+ let inserted = "";+ let marked = "";+ const dependencies = {+ hintSlash: () => insertItems,+ fetchPost: (_url: string, _data: unknown, callback: typeof requests[number]) => requests.push(callback),+ escapeHtml: (text: string) => {+ const element = document.createElement("div");+ element.textContent = text;+ return element.innerHTML;+ },+ Constants: {BLOCK_HINT_KEYS: ["((", "[["], INLINE_TYPE: ["strong"], ZWSP: "\u200b"},+ hideElements: () => {}, getUndoFocusContext: (): undefined => undefined, focusByRange: () => {},+ hasClosestBlock: (node: Node) => (node instanceof Element ? node : node.parentElement).closest("[data-node-id]"),+ insertHTML: (html: string) => { inserted = html; },+ };+ const api = new Function(...Object.keys(dependencies), source ++ "\nreturn {hintSkill, mountLiteSlashMenu, normalizeAgentSkills, expandAgentSkillSelection, " ++ "AGENT_SKILL_SELECTOR, Hint, isBuiltinSlashHint};")(...Object.values(dependencies));+ const element = document.createElement("div");+ element.className = "protyle-hint fn__none";+ document.body.appendChild(element);+ const panel = document.createElement("div");+ panel.id = "keyboardToolbar";+ document.body.appendChild(panel);+ const hint = {+ element, source: "hint", enableExtend: true, enableSlash: true, splitChar: "/",+ genHTML: (items: IHintData[], _protyle?: IProtyle, reset = false) => {+ if (reset && items.length === 0) {+ element.classList.add("fn__none");+ return;+ }+ element.innerHTML = api.Hint.prototype.getHTMLByData.call(hint, items);+ element.classList.remove("fn__none");+ },+ genLoading: () => {+ element.textContent = "Loading";+ element.classList.remove("fn__none");+ },+ };+ const editor = document.createElement("div");+ editor.innerHTML = '<div data-node-id="paragraph" data-type="NodeParagraph"><div contenteditable="true">text</div></div>';+ document.body.appendChild(editor);+ const range = document.createRange();+ range.selectNodeContents(editor.querySelector("[contenteditable]"));+ const protyle = {lite: true, hint, wysiwyg: {element: editor},+ toolbar: {range, setInlineMark: (_p: IProtyle, value: string) => { marked = value; }},+ options: {hint: {extend: [{key: "/", hint: api.hintSkill}]}}} as unknown as IProtyle;+ const skills = {data: [{name: "test111", description: "test skill"}]};+ let unmount = api.mountLiteSlashMenu(protyle, panel);+ check.ok(panel.querySelector('[data-id="bold"]'), "insert commands are usable before skills arrive");+ requests.shift()(skills);+ check.equal(panel.querySelectorAll(".keyboard__slash-item").length, 2);+ check.ok(panel.querySelector('[data-id="bold"]'), "skills do not replace insert commands");+ check.equal(panel.querySelector(".keyboard__slash-item").getAttribute("data-id"), "bold");+ const skillValue = decodeURIComponent(panel.querySelector<HTMLElement>('[data-id=""][data-value]').dataset.value);+ check.match(skillValue, /contenteditable="false"/);+ check.equal(api.isBuiltinSlashHint(api.hintSkill, skillValue, protyle), false);+ check.equal(api.isBuiltinSlashHint(api.hintSkill, "strong", protyle), true);+ unmount();+ // 面板先卸载,候选填充随后发生,命令来源仍须保留。+ api.Hint.prototype.fill.call(hint, "strong", protyle, false);+ check.equal(marked, "strong");+ check.equal(inserted, "");+ api.Hint.prototype.fill.call(hint, skillValue, protyle, false);+ check.equal(inserted, skillValue);+ unmount = api.mountLiteSlashMenu(protyle, panel);+ requests.shift()({data: []});+ check.equal(panel.querySelectorAll(".keyboard__slash-item").length, 1);+ unmount();+ unmount = api.mountLiteSlashMenu(protyle, panel);+ unmount();+ requests.shift()(skills);+ check.equal(element.classList.contains("fn__none"), true);+ hint.enableExtend = true;+ api.hintSkill("", protyle);+ requests.shift()(skills);+ check.equal(element.querySelectorAll(".b3-list-item").length, 1);+ check.equal(element.textContent.includes("Bold"), false, "typed slash remains a skill query");+ check.equal(api.isBuiltinSlashHint(api.hintSkill, "strong", protyle), false);++ const lute = Lute.New();+ lute.SetTextMark(true);+ lute.SetHTMLTag2TextMark(true);+ lute.SetKramdownIAL(true);+ lute.SetProtyleWYSIWYG(true);+ const prepare = (content = skillValue) => {+ editor.innerHTML = lute.SpinBlockDOM('<div data-node-id="20260921000000-skill01" data-type="NodeParagraph">' ++ '<div contenteditable="true">before ' + content + " after</div></div>");+ api.normalizeAgentSkills(editor);+ const skill = editor.querySelector<HTMLElement>(api.AGENT_SKILL_SELECTOR);+ check.ok(skill, "Lute retains skill identity: " + editor.innerHTML);+ check.equal(skill.contentEditable, "false");+ editor.querySelector<HTMLElement>('[contenteditable="true"]').focus();+ return skill;+ };+ const select = (start: Node, offset: number, end = start, endOffset = offset) => {+ const selection = getSelection();+ const selected = document.createRange();+ selected.setStart(start, offset);+ selected.setEnd(end, endOffset);+ selection.removeAllRanges();+ selection.addRange(selected);+ return selected;+ };+ for (const command of ["delete", "forwardDelete"]) {+ const skill = prepare();+ const index = Array.from(skill.parentNode.childNodes).indexOf(skill);+ select(skill.parentNode, command === "delete" ? index + 1 : index);+ document.execCommand(command);+ check.equal(editor.querySelector(api.AGENT_SKILL_SELECTOR), null, command + " removes the whole skill");+ check.ok(editor.textContent.includes("before"));+ check.ok(editor.textContent.includes("after"));+ document.execCommand("undo");+ api.normalizeAgentSkills(editor);+ check.equal(editor.querySelector(api.AGENT_SKILL_SELECTOR)?.textContent, "test111");+ document.execCommand("redo");+ check.equal(editor.querySelector(api.AGENT_SKILL_SELECTOR), null);+ }+ let skill = prepare(skillValue.replace(' contenteditable="false"', ""));+ const partial = select(skill.firstChild, 2, skill.firstChild, 5);+ api.expandAgentSkillSelection(partial);+ check.equal(partial.toString(), "test111");+ document.execCommand("insertText", false, "replacement");+ check.equal(editor.querySelector(api.AGENT_SKILL_SELECTOR), null);+ check.ok(editor.textContent.includes("replacement"));+ skill = prepare();+ api.expandAgentSkillSelection(select(skill.firstChild, 2));+ document.execCommand("insertText", false, "suffix");+ check.equal(skill.textContent, "test111");+ check.ok(editor.textContent.includes("test111suffix"));+ return "Agent skill cases passed";+};++test("agent mobile commands coexist with skills and skill names remain atomic", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 45000,+}, async () => {+ const read = (file: string) => readFileSync(path.resolve(__dirname, file), "utf8");+ const composer = createSourceFile("composer.ts", read("AgentComposer.ts"), ScriptTarget.Latest, true);+ const selected = new Set(["skillHintRequestIDs", "skillSlashCommands", "prepareAgentHint", "hintSkill"]);+ const composerSource = composer.statements.filter(statement => isVariableStatement(statement) &&+ statement.declarationList.declarations.some(declaration => selected.has(declaration.name.getText(composer))))+ .map(statement => statement.getText(composer)).join("\n");+ const hint = createSourceFile("hint.ts", read("../../../protyle/hint/index.ts"), ScriptTarget.Latest, true);+ const hintSource = hint.statements.find(isClassDeclaration).members.filter(member => isMethodDeclaration(member) &&+ ["fill", "getHTMLByData"].includes(member.name.getText(hint))).map(member => member.getText(hint)).join("\n");+ const source = transpileModule([read("../../../protyle/hint/builtinSlash.ts"),+ read("../../../protyle/hint/blockHintRange.ts"), read("agentHintState.ts"),+ read("agentSkill.ts"), read("../../../mobile/util/liteSlashMenu.ts"), composerSource,+ "class Hint {" + hintSource + "}"].join("\n").replace(/^import .*;\r?\n/gm, "").replace(/^export /gm, ""), {+ compilerOptions: {target: ScriptTarget.ES2021},+ }).outputText;+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-agent-skill-test-"));+ const script = path.join(temporary, "run.cjs");+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});+app.commandLine.appendSwitch("disable-gpu");+app.whenReady().then(async () => {+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false}});+ try {+ await win.loadURL("data:text/html,<html><body></body></html>");+ await win.webContents.executeJavaScript(require("node:fs").readFileSync(+ ${JSON.stringify(path.resolve(__dirname, "../../../../stage/protyle/js/lute/lute.min.js"))}, "utf8"));+ console.log(await win.webContents.executeJavaScript(${JSON.stringify("const __name = value => value; (" ++ browserCases.toString() + ")(" + JSON.stringify(source) + ")")}));+ win.destroy();+ app.exit(0);+ } catch (error) {+ console.error(error);+ win.destroy();+ app.exit(1);+ }+});`, "utf8");+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ const result = await promisify(execFile)(require("electron") as unknown as string, [script],+ {env, timeout: 40000, windowsHide: true});+ assert.match(result.stdout, /Agent skill cases passed/);+ } finally {+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) &&+ path.basename(temporary).startsWith("siyuan-agent-skill-test-")) {+ rmSync(temporary, {recursive: true, force: true});+ }+ }+});diff --git a/app/src/layout/dock/agent/agentSkill.ts b/app/src/layout/dock/agent/agentSkill.tsnew file mode 100644index 0000000000..201d4ba333--- /dev/null+++ b/app/src/layout/dock/agent/agentSkill.ts@@ -0,0 +1,29 @@+export const AGENT_SKILL_SELECTOR = '[data-type~="text"][custom-agent-skill="true"]';++export const normalizeAgentSkills = (element: ParentNode) => {+ // 渲染、撤销和草稿恢复后继续将技能视为整体,兼容已有的技能标记。+ element.querySelectorAll<HTMLElement>(AGENT_SKILL_SELECTOR).forEach(skill => {+ skill.contentEditable = "false";+ });+};++export const expandAgentSkillSelection = (range: Range) => {+ const getSkill = (node: Node) => (node.nodeType === Node.ELEMENT_NODE ? node as Element : node.parentElement)+ ?.closest(AGENT_SKILL_SELECTOR);+ const start = getSkill(range.startContainer);+ const end = getSkill(range.endContainer);+ if (range.collapsed) {+ if (start) {+ range.setStartAfter(start);+ range.collapse(true);+ }+ return;+ }+ // 触摸选区或全选可能落在不可编辑元素内部,替换、剪切时将边界扩展至整个技能。+ if (start) {+ range.setStartBefore(start);+ }+ if (end) {+ range.setEndAfter(end);+ }+};diff --git a/app/src/protyle/hint/builtinSlash.ts b/app/src/protyle/hint/builtinSlash.tsindex 32d1e1c1ff..1659b1e4a9 100644--- a/app/src/protyle/hint/builtinSlash.ts+++ b/app/src/protyle/hint/builtinSlash.ts@@ -1,11 +1,15 @@type TSlashHint = (key: string, protyle: IProtyle, source: THintSource) => IHintData[];-const builtinSlashHints = new WeakSet<TSlashHint>();+type TBuiltinSlashValue = (value: string, protyle: IProtyle) => boolean;++const builtinSlashHints = new WeakMap<TSlashHint, TBuiltinSlashValue>();// 标记内置斜杠菜单及其过滤包装,保留候选项的命令语义。-export const registerBuiltinSlashHint = <T extends TSlashHint>(hint: T): T => {- builtinSlashHints.add(hint);+export const registerBuiltinSlashHint = <T extends TSlashHint>(hint: T,+ isBuiltinValue: TBuiltinSlashValue = () => true): T => {+ builtinSlashHints.set(hint, isBuiltinValue);return hint;};-export const isBuiltinSlashHint = (hint: TSlashHint) => builtinSlashHints.has(hint);+export const isBuiltinSlashHint = (hint: TSlashHint, value: string, protyle: IProtyle) =>+ builtinSlashHints.get(hint)?.(value, protyle) ?? false;diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.tsindex 6d2c99cee3..ba8bf271ba 100644--- a/app/src/protyle/hint/index.ts+++ b/app/src/protyle/hint/index.ts@@ -936,7 +936,8 @@ ${genHintItemHTML(item)}} else if (this.splitChar === "/" || this.splitChar === "、") {// 精简模式的自定义候选按文本插入,内置候选执行命令;块引用保留本地事务和后续提示。if (protyle.lite && (Constants.BLOCK_HINT_KEYS.includes(value) ||- !isBuiltinSlashHint(protyle.options.hint.extend.find((item) => item.key === "/" && item.hint)?.hint))) {+ !isBuiltinSlashHint(protyle.options.hint.extend.find((item) => item.key === "/" && item.hint)?.hint,+ value, protyle))) {insertHTML(value, protyle, false, false, false, undefined, undoContext);if (Constants.BLOCK_HINT_KEYS.includes(value)) {this.enableExtend = true;