An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: https://github.com/siyuan-note/siyuan/issues/18256
Vanessa6a25f1158acf
diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.tsindex 3f6570420a..bafbab17e4 100644--- a/app/src/layout/dock/agent/AgentChat.ts+++ b/app/src/layout/dock/agent/AgentChat.ts@@ -4,6 +4,7 @@ import {App} from "../../../index";import {AgentHttpError, fetchAgentSSE, IEditorContext, ISSEResult, IToolEffects} from "./agentSSE";import {genUUID} from "../../../util/genID";import {mountComposer} from "./AgentComposer";+import {disabledWYSIWYG} from "../../../protyle/util/onGet";import {getAllEditor} from "../../getAll";import "./frontendActions";import {listActions, lookupAction} from "./frontendActions";@@ -37,8 +38,10 @@ const maxVisibleBlockIDs = 50;type EntryBase = { id?: string };+type UserEntry = EntryBase & { type: "user"; content: string; blockHTML?: string; timestamp?: number };+type SessionEntry =- | (EntryBase & { type: "user"; content: string; timestamp?: number })+ | UserEntry| (EntryBase & {type: "thinking";steps: Array<{@@ -561,12 +564,7 @@ export class AgentChat extends Model {private rebuildNavMarkers() {this.navRail.innerHTML = "";- const userEntries = this.entries.filter((e): e is {- id?: string;- type: "user";- content: string;- timestamp?: number- } => e.type === "user");+ const userEntries = this.entries.filter((entry): entry is UserEntry => entry.type === "user");if (userEntries.length === 0) {return;}@@ -1260,9 +1258,8 @@ export class AgentChat extends Model {const entryId = (entry as { id?: string }).id;switch (entry.type) {case "user":- this.appendUserMessage((entry as { content: string }).content, (entry as {- timestamp?: number- }).timestamp, entryId);+ this.appendUserMessage((entry as UserEntry).content, (entry as UserEntry).timestamp, entryId,+ (entry as UserEntry).blockHTML);break;case "thinking":if (entry.steps && entry.steps.length > 0) {@@ -1467,6 +1464,7 @@ export class AgentChat extends Model {}const sendData = this.composer.getSendData();const text = sendData.text;+ const blockHTML = sendData.blockHTML;const refs = sendData.references;const editorContext = this.captureEditorContext();const pluginActions = listActions()@@ -1485,11 +1483,11 @@ export class AgentChat extends Model {this.composer.clear();const userEntryId = SessionStore.newSessionId();- this.entries.push({id: userEntryId, type: "user", content: text, timestamp: Date.now()});+ this.entries.push({id: userEntryId, type: "user", content: text, blockHTML, timestamp: Date.now()});if (this.entries.length === 1) {this.messagesContainer.innerHTML = "";}- this.appendUserMessage(text, Date.now(), userEntryId);+ this.appendUserMessage(text, Date.now(), userEntryId, blockHTML);this.rebuildNavMarkers();this.tryGenerateTitle();if (this.composer) {@@ -1904,21 +1902,26 @@ export class AgentChat extends Model {this.flushThinkingStep();}- private appendUserMessage(text: string, timestamp?: number, entryId?: string) {+ private appendUserMessage(text: string, timestamp?: number, entryId?: string, blockHTML?: string) {const el = document.createElement("div");el.className = "agent-chat__msg agent-chat__msg--user";if (entryId) {el.setAttribute("data-message-id", entryId);}- let html = '<div class="agent-chat__body b3-typography">' + escapeHtml(text) + "</div>";- html += '<div class="agent-chat__msg-actions">';+ const bodyElement = document.createElement("div");+ bodyElement.className = "agent-chat__body protyle-wysiwyg";+ bodyElement.setAttribute("contenteditable", "false");+ bodyElement.setAttribute("data-readonly", "true");+ bodyElement.innerHTML = blockHTML || this.lute.Md2BlockDOM(text);+ el.appendChild(bodyElement);+ let actionsHTML = '<div class="agent-chat__msg-actions">';if (timestamp) {- html += '<span class="agent-chat__msg-meta agent-chat__msg-time">' + this.formatMessageTime(timestamp) + "</span>";+ actionsHTML += '<span class="agent-chat__msg-meta agent-chat__msg-time">' + this.formatMessageTime(timestamp) + "</span>";}- html += '<span class="block__icon block__icon--show ariaLabel" data-position="north" aria-label="' + window.siyuan.languages.copy + '"><svg><use xlink:href="#iconCopy"></use></svg></span>' ++ actionsHTML += '<span class="block__icon block__icon--show ariaLabel" data-position="north" aria-label="' + window.siyuan.languages.copy + '"><svg><use xlink:href="#iconCopy"></use></svg></span>' +"</div>";- el.innerHTML = html;- el.querySelector(".block__icon")?.addEventListener("click", (e) => {+ el.insertAdjacentHTML("beforeend", actionsHTML);+ el.querySelector(".agent-chat__msg-actions .block__icon")?.addEventListener("click", (e) => {e.stopPropagation();navigator.clipboard.writeText(text).then(() => {showMessage(window.siyuan.languages.copied, 2000);@@ -1927,6 +1930,11 @@ export class AgentChat extends Model {});});this.messagesContainer.appendChild(el);+ postRender(el, this.app);+ this.composer?.renderBlockHTML(bodyElement, () => {+ disabledWYSIWYG(bodyElement);+ });+ disabledWYSIWYG(bodyElement);this.scrollToBottom(true);}@@ -2520,7 +2528,7 @@ export class AgentChat extends Model {}this.hasTitled = true;const requestSessionID = this.sessionId;- const userEntry = this.entries.find((e): e is { type: "user"; content: string } => e.type === "user");+ const userEntry = this.entries.find((entry): entry is UserEntry => entry.type === "user");const userMsg = userEntry?.content?.slice(0, 500) || "";fetch("/api/ai/agent/title", {method: "POST",diff --git a/app/src/layout/dock/agent/AgentComposer.ts b/app/src/layout/dock/agent/AgentComposer.tsindex d3d7d57269..5b00bed442 100644--- a/app/src/layout/dock/agent/AgentComposer.ts+++ b/app/src/layout/dock/agent/AgentComposer.ts@@ -5,11 +5,12 @@ import {escapeHtml} from "../../../util/escape";import {fetchPost} from "../../../util/fetch";import {hintRef} from "../../../protyle/hint/extend";import {genEmptyElement} from "../../../block/util";+import {blockRender} from "../../../protyle/render/blockRender";interface ComposerHandle {focus: () => void;destroy: () => void;- getSendData: () => { text: string; references: { id: string; title: string }[] };+ getSendData: () => { text: string; blockHTML: string; references: { id: string; title: string }[] };clear: () => void;pushHistory: (text: string) => void;getHistory: () => string[];@@ -17,10 +18,23 @@ interface ComposerHandle {restoreHistory: (h: string[]) => void;insertMention: (id: string, label: string) => void;insertMentions: (mentions: Array<{ id: string; label: string }>) => void;+ renderBlockHTML: (element: HTMLElement, onEmbedRender: () => void) => void;}type OnChangeCallback = () => void;+const resetEmbedBlocks = (element: HTMLElement) => {+ element.querySelectorAll<HTMLElement>('[data-type="NodeBlockQueryEmbed"]').forEach((embedElement) => {+ embedElement.removeAttribute("data-render");+ embedElement.style.height = "";+ Array.from(embedElement.children).forEach((child) => {+ if (child.classList.contains("protyle-wysiwyg__embed")) {+ child.remove();+ }+ });+ });+};+// / 技能菜单:异步拉取 lsSkills,选中后把技能名作为纯文本插入(value 即技能名)。// 返回 [] 占位,数据在 fetch 回调里通过 protyle.hint.genHTML 填充(与 hintRef 异步模式一致)。const hintSkill = (key: string, protyle: IProtyle): IHintData[] => {@@ -207,7 +221,7 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:event.stopPropagation();const target = history.isBrowsing() ?history.navigateUp() : history.beginBrowsing(wysiwyg.element.innerHTML);- wysiwyg.element.innerHTML = p.lute.SpinBlockDOM(target);+ wysiwyg.element.innerHTML = p.lute.Md2BlockDOM(target);return;}}@@ -217,7 +231,7 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:event.stopPropagation();const target = history.navigateDown();if (history.isBrowsing()) {- p.wysiwyg.element.innerHTML = p.lute.SpinBlockDOM(target);+ p.wysiwyg.element.innerHTML = p.lute.Md2BlockDOM(target);} else {wysiwyg.element.innerHTML = target;}@@ -230,8 +244,14 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:}}, true);- const getPlainText = (): string => {- return (wysiwyg.element.textContent || "").replace(new RegExp(Constants.ZWSP, "g"), "").trim();+ const getMarkdown = (): string => {+ return p.lute.BlockDOM2StdMd(wysiwyg.element.innerHTML).trim();+ };++ const getBlockHTML = (): string => {+ const clone = wysiwyg.element.cloneNode(true) as HTMLElement;+ resetEmbedBlocks(clone);+ return clone.innerHTML;};return {@@ -248,7 +268,7 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:title: ref.textContent || "",});});- return {text: getPlainText(), references};+ return {text: getMarkdown(), blockHTML: getBlockHTML(), references};},clear: () => {wysiwyg.element.innerHTML = "";@@ -277,5 +297,9 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:protyle.insert(html);}},+ renderBlockHTML: (element, onEmbedRender) => {+ resetEmbedBlocks(element);+ blockRender(p, element, undefined, onEmbedRender);+ },};}diff --git a/app/src/layout/dock/agent/AgentMessageRenderer.ts b/app/src/layout/dock/agent/AgentMessageRenderer.tsindex 3f6c06260f..5dbbd067d3 100644--- a/app/src/layout/dock/agent/AgentMessageRenderer.ts+++ b/app/src/layout/dock/agent/AgentMessageRenderer.ts@@ -11,6 +11,15 @@ import {abcRender} from "../../../protyle/render/abcRender";import {plantumlRender} from "../../../protyle/render/plantumlRender";import {htmlRender} from "../../../protyle/render/htmlRender";import {showMessage} from "../../../dialog/message";+import {openLink} from "../../../editor/openLink";+import {previewImages} from "../../../protyle/preview/image";+import {getDiagramBlock, previewDiagram} from "../../../protyle/preview/diagram";+import {removeCompressURL} from "../../../util/image";+/// #if !MOBILE+import {openGlobalSearch} from "../../../search/util";+/// #else+import {popSearch} from "../../../mobile/menu/search";+/// #endifimport type {App} from "../../../index";@@ -269,12 +278,12 @@ export const postRender = (container: HTMLElement, app?: App): void => {code.parentElement?.setAttribute("data-language", match[1]);}});- // Agent 内容由 ProtylePreview 生成,结构与官方 preview 一致,复用 highlightRender 渲染高亮。- // 容器自身可能是 b3-typography(流式更新),也可能外层包裹含 b3-typography 的后代,两种情况都需覆盖。- const typographyElements = container.classList.contains("b3-typography")+ // Assistant 使用 b3-typography,用户消息使用只读 protyle-wysiwyg,两种结构都复用 highlightRender。+ const contentSelector = ".b3-typography, .protyle-wysiwyg";+ const contentElements = container.matches(contentSelector)? [container as HTMLElement]- : Array.from(container.querySelectorAll<HTMLElement>(".b3-typography"));- typographyElements.forEach((item) => highlightRender(item));+ : Array.from(container.querySelectorAll<HTMLElement>(contentSelector));+ contentElements.forEach((item) => highlightRender(item));mathRender(container);mermaidRender(container);flowchartRender(container);@@ -285,19 +294,94 @@ export const postRender = (container: HTMLElement, app?: App): void => {plantumlRender(container);htmlRender(container);addCopyButtons(container);+ if (container.dataset.agentPreviewBound !== "true") {+ container.dataset.agentPreviewBound = "true";+ container.addEventListener("dblclick", (event: MouseEvent) => {+ const target = event.target as HTMLElement;+ const img = target.closest("img:not(.emoji)") as HTMLImageElement;+ if (!img || !container.contains(img)) {+ const diagramElement = getDiagramBlock(target.closest("[data-subtype]") as HTMLElement);+ if (diagramElement && container.contains(diagramElement)) {+ previewDiagram(diagramElement);+ event.preventDefault();+ event.stopPropagation();+ }+ return;+ }+ const srcList = Array.from(container.querySelectorAll<HTMLImageElement>("img:not(.emoji)"))+ .map((item) => removeCompressURL(item.dataset.src || item.getAttribute("src") || ""));+ const currentSrc = removeCompressURL(img.dataset.src || img.getAttribute("src") || "");+ if (currentSrc) {+ previewImages(srcList, currentSrc);+ event.preventDefault();+ event.stopPropagation();+ }+ });+ }if (!app) {return;}- // MarkdownStr 渲染出的 siyuan:// 块链接只是普通 <a href>,需补全 data-type/data-href- // 才能接入全局 popover 浮窗系统;dock 内无 protyle 点击链路,需自行绑定点击打开块。- container.querySelectorAll<HTMLAnchorElement>('a[href^="siyuan://"]').forEach((a) => {- const href = a.getAttribute("href") || "";- a.setAttribute("data-type", "a");- a.setAttribute("data-href", href);- a.addEventListener("click", (event: MouseEvent) => {+ container.querySelectorAll<HTMLAnchorElement>('a[href^="siyuan://"]').forEach((link) => {+ const href = link.getAttribute("href") || "";+ link.setAttribute("data-type", "a");+ link.setAttribute("data-href", href);+ });+ if (container.dataset.agentLinkBound === "true") {+ return;+ }+ container.dataset.agentLinkBound = "true";+ // dock 内没有 Protyle WYSIWYG 的点击分派,使用事件委托覆盖流式及嵌入块异步插入的内容。+ container.addEventListener("click", (event: MouseEvent) => {+ if (event.defaultPrevented) {+ return;+ }+ const target = event.target as HTMLElement;+ const ref = target.closest('[data-type~="block-ref"]') as HTMLElement;+ const refID = ref?.dataset.id;+ if (refID && container.contains(ref)) {event.preventDefault();event.stopPropagation();- void processSiYuanUri(app, href);- });+ void processSiYuanUri(app, "siyuan://blocks/" + refID);+ return;+ }+ const fileRef = target.closest('[data-type~="file-annotation-ref"][data-id]') as HTMLElement;+ const fileID = fileRef?.dataset.id;+ if (fileID && container.contains(fileRef)) {+ event.preventDefault();+ event.stopPropagation();+ openLink(app, fileID, event, event.ctrlKey || event.metaKey);+ return;+ }+ const tag = target.closest('[data-type~="tag"]') as HTMLElement;+ if (tag && container.contains(tag)) {+ event.preventDefault();+ event.stopPropagation();+ /// #if !MOBILE+ openGlobalSearch(app, `#${tag.textContent}#`, true, {method: 0});+ /// #else+ popSearch(app, {+ hasReplace: false,+ method: 0,+ hPath: "",+ idPath: [],+ k: `#${tag.textContent}#`,+ r: "",+ page: 1,+ });+ /// #endif+ return;+ }+ const link = target.closest('[data-type~="a"][data-href], a[href]') as HTMLElement;+ if (!link || !container.contains(link)) {+ return;+ }+ const href = link.getAttribute("data-href") || link.getAttribute("href") || "";+ if (href) {+ event.preventDefault();+ event.stopPropagation();+ if (!processSiYuanUri(app, href)) {+ openLink(app, href, event, event.ctrlKey || event.metaKey);+ }+ }});};