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: Improve pasting content copied from Doubao https://github.com/siyuan-note/siyuan/issues/19820
Daniel9278cfeb25c1
diff --git a/app/src/protyle/util/markdownClipboard.ts b/app/src/protyle/util/markdownClipboard.tsnew file mode 100644index 0000000000..a95dd4b015--- /dev/null+++ b/app/src/protyle/util/markdownClipboard.ts@@ -0,0 +1,70 @@+const DOLLAR_PLACEHOLDER = "\uE000";++// 比较 Markdown 的普通 HTML 渲染结果,仅忽略块间排版空白及默认列表样式。+const normalizeClipboardHTML = (root: DocumentFragment) => {+ root.querySelectorAll("ol[style]").forEach(element => {+ if (/^\s*list-style-type\s*:\s*decimal\s*;?\s*$/i.test(element.getAttribute("style"))) {+ element.removeAttribute("style");+ }+ });+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT);+ const remove: Node[] = [];+ let node: Node;+ while ((node = walker.nextNode())) {+ if (node.nodeType === Node.COMMENT_NODE ||+ (node.nodeType === Node.TEXT_NODE && !node.textContent.trim() &&+ (node.parentNode === root ||+ /^(DIV|UL|OL|BLOCKQUOTE|TABLE|THEAD|TBODY|TFOOT|TR)$/.test(node.parentElement?.tagName)))) {+ remove.push(node);+ }+ }+ remove.forEach(node => node.parentNode.removeChild(node));+ root.normalize();+};++export const shouldPasteMarkdownFromHTML = (html: string, text: string) => {+ if (!html || !text?.trim() || text.includes(DOLLAR_PLACEHOLDER) || html.includes(DOLLAR_PLACEHOLDER)) {+ return false;+ }+ // 使用惰性片段进行比较,避免加载剪贴板中的图片或执行元素事件。+ const sourceTemplate = document.createElement("template");+ sourceTemplate.innerHTML = html;+ const source = sourceTemplate.content;+ const markdown = text.replace(/\r\n?|\u2028|\u2029/g, "\n");+ // 普通网页划选通常提供相同的可见文本,不能仅凭美元符号或 HTML 排版换行将其解释为 Markdown。+ if (source.textContent.trim() === markdown.trim()) {+ return false;+ }+ normalizeClipboardHTML(source);+ if (source.querySelector("[style], [class], math, svg, iframe, video, audio")) {+ return false;+ }+ const walker = document.createTreeWalker(source, NodeFilter.SHOW_TEXT);+ let node: Node;+ let hasUnrenderedContent = false;+ while ((node = walker.nextNode())) {+ if (!node.parentElement?.closest("pre, code") &&+ (/\n/.test(node.textContent) || /\$[^$\n]+\$/.test(node.textContent))) {+ hasUnrenderedContent = true;+ break;+ }+ }+ if (!hasUnrenderedContent) {+ return false;+ }+ const lute = Lute.New();+ lute.SetHeadingID(false);+ lute.SetInlineMath(false);+ // 临时遮蔽美元符号,模拟未解析公式的 Markdown 转换;实际粘贴仍使用完整的原始文本。+ const renderedTemplate = document.createElement("template");+ renderedTemplate.innerHTML = lute.MarkdownStr("", markdown.replaceAll("$", DOLLAR_PLACEHOLDER))+ .replaceAll(DOLLAR_PLACEHOLDER, "$");+ const rendered = renderedTemplate.content;+ rendered.querySelectorAll("br").forEach(element => element.remove());+ normalizeClipboardHTML(rendered);+ if (!source.isEqualNode(rendered)) {+ return false;+ }+ // 原始 HTML 标签可能生成 HTML 块,不能因预览一致就替换富文本;代码中的标签仍按代码保留。+ return !/<[!/?a-z]/i.test(markdown) || !lute.Md2BlockDOM(markdown).includes('data-type="NodeHTMLBlock"');+};diff --git a/app/src/protyle/util/paste.test.ts b/app/src/protyle/util/paste.test.tsindex aca01571db..d2887a01fc 100644--- a/app/src/protyle/util/paste.test.ts+++ b/app/src/protyle/util/paste.test.ts@@ -40,6 +40,7 @@ const createHarness = (disabled = false, richPaste = false) => {"./selection": {getEditorRange: () => position.range},"./hasClosest": {hasClosestBlock: (): undefined => undefined},"./wpsPresentation": {extractWPSPresentationClipboard: (): undefined => undefined},+ "./markdownClipboard": {shouldPasteMarkdownFromHTML: () => false},"./compatibility": {getLocalFiles: async () => localFiles, isInHarmony: () => false,getTextSiyuanFromTextHTML: (html: string) => ({textSiyuan: "", textHtml: html})},"../upload": {diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.tsindex 8c90d24a70..30f9e29062 100644--- a/app/src/protyle/util/paste.ts+++ b/app/src/protyle/util/paste.ts@@ -53,6 +53,7 @@ import {shouldPreservePastedBlockStructure} from "./pasteSource";import {normalizePasteResponse} from "./pasteResponse";+import {shouldPasteMarkdownFromHTML} from "./markdownClipboard";import {applyLuteMarkdownSyntax} from "../render/luteMarkdownSyntax";import {convertOfficeLists} from "./officeList";import {extractOfficeMathHTML} from "./officeMath";@@ -807,7 +808,9 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven(textHTML || /<[a-z][^>]*>/i.test(textPlain))) {// 表格单元格将可解析的富文本转换为块 DOM,再统一检查不支持的块和净化行内标记。const richBlockDOM = textHTML ?- (/^<span\b[^>]*\bdata-type\s*=\s*["']custom_[^>]*>[\s\S]*<\/span>$/i.test(textHTML.trim()) ?+ (!preserveSourceFormat && shouldPasteMarkdownFromHTML(textHTML, textPlain) ?+ protyle.lute.Md2BlockDOM(textPlain) :+ /^<span\b[^>]*\bdata-type\s*=\s*["']custom_[^>]*>[\s\S]*<\/span>$/i.test(textHTML.trim()) ?protyle.lute.Md2BlockDOM(textHTML) : protyle.lute.HTML2BlockDOM(textHTML)) :protyle.lute.Md2BlockDOM(textPlain);const richTemplate = document.createElement("template");@@ -1309,6 +1312,13 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven// 豆包复制粘贴问题 https://github.com/siyuan-note/siyuan/issues/13265 https://github.com/siyuan-note/siyuan/issues/14313isHTML = false;}+ // 豆包同时提供 Markdown 和未解析公式的 HTML,内容与结构一致时使用完整原文。+ // https://github.com/siyuan-note/siyuan/issues/19820+ if (isHTML && !preserveSourceFormat && !officeListConverted && !files?.length &&+ !mathML && !office && !officeMathHTML && !wps && !wpsPresentation &&+ shouldPasteMarkdownFromHTML(textHTML, textPlain)) {+ isHTML = false;+ }} else if (textPlain && textPlain.trimStart().startsWith("<")) {// 剪贴板没有 text/html,但 text/plain 实际是 HTML 表格(如从纯文本编辑器复制的表格 HTML)// Md2BlockDOM 会把标签当字面文本,需走 html2BlockDOM 解析diff --git a/app/tests/fixtures/doubao-clipboard.json b/app/tests/fixtures/doubao-clipboard.jsonnew file mode 100644index 0000000000..5d383f512e--- /dev/null+++ b/app/tests/fixtures/doubao-clipboard.json@@ -0,0 +1,4 @@+{+ "text": "**示例**\r\n名义增长率 $g=4.2\\%$\r\n国民收入恒等式 $S-A=C_A$\r\n\r\n$$\r\n\\(Y=C+I+G\\)\r\n$$\r\n\r\n**现象**:\r\n在思源编辑器手动输入 `$g=4.2\\%$`、`$S-A=C_A$`,预览可以正常渲染。\r\n\r\n**问题**:\r\n1. 点击豆包下方的复制按钮,复制内容粘贴到思源,粘贴后文本变成:\r\n`示例 名义增长率 $\\(g=4.2\\%\\)$ 国民收入恒等式 $$S-A=C_A$$`\r\n块公式粘贴后变成 `$$(\\(Y=C+I+G\\))$$`\r\n2. `$g=4.2\\%$` 里百分号前面的反斜杠 `\\` 丢失",+ "html": "<!--StartFragment--><html><head></head><body><p><strong>示例</strong>\n名义增长率 $g=4.2%$\n国民收入恒等式 $S-A=C_A$</p>\n<p>$$\n(Y=C+I+G)\n$$</p>\n<p><strong>现象</strong>:\n在思源编辑器手动输入 <code>$g=4.2\\%$</code>、<code>$S-A=C_A$</code>,预览可以正常渲染。</p>\n<p><strong>问题</strong>:</p>\n<ol style=\"list-style-type: decimal;\">\n<li>点击豆包下方的复制按钮,复制内容粘贴到思源,粘贴后文本变成:\n<code>示例 名义增长率 $\\(g=4.2\\%\\)$ 国民收入恒等式 $$S-A=C_A$$</code>\n块公式粘贴后变成 <code>$$(\\(Y=C+I+G\\))$$</code></li>\n<li><code>$g=4.2\\%$</code> 里百分号前面的反斜杠 <code>\\</code> 丢失</li>\n</ol>\n</body></html><!--EndFragment-->"+}diff --git a/app/tests/markdownClipboard.test.js b/app/tests/markdownClipboard.test.jsnew file mode 100644index 0000000000..f49ad066b2--- /dev/null+++ b/app/tests/markdownClipboard.test.js@@ -0,0 +1,221 @@+const assert = require("node:assert/strict");+const {readFileSync, mkdtempSync, rmSync} = require("node:fs");+const path = require("node:path");+const os = require("node:os");++const sources = () => {+ const ts = require("typescript");+ const compile = file => ts.transpileModule(readFileSync(path.join(__dirname, "../src", file), "utf8"), {+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022},+ }).outputText;+ return {+ clipboard: compile("protyle/util/markdownClipboard.ts"),+ paste: compile("protyle/util/paste.ts"),+ fixture: JSON.parse(readFileSync(path.join(__dirname, "fixtures/doubao-clipboard.json"), "utf8")),+ };+};++const runCases = async source => {+ const check = require("node:assert/strict");+ const {Lute} = window;+ const load = (code, mocks = {}) => {+ const module = {exports: {}};+ new Function("module", "exports", "require", code)(module, module.exports, id => mocks[id] || {});+ return module.exports;+ };+ const clipboard = load(source.clipboard);+ const {shouldPasteMarkdownFromHTML: preferMarkdown} = clipboard;+ const {html, text} = source.fixture;+ check.equal(preferMarkdown(html, text), true, "captured Doubao clipboard");+ check.equal(preferMarkdown(Lute.Sanitize(html), text), true, "sanitized clipboard");+ check.equal(preferMarkdown("<p><strong>标题</strong>\n第一行\n第二行</p>", "**标题**\n第一行\n第二行"), true);+ check.equal(preferMarkdown("<p>公式 $g=4.2%$</p>", "公式 $g=4.2\\%$"), true);+ check.equal(preferMarkdown("<p>$$\nY=C+I+G\n$$</p>", "$$\nY=C+I+G\n$$"), false);+ check.equal(preferMarkdown("<p><strong>公式</strong> $x$</p>", "**公式** $x$"), true);+ check.equal(preferMarkdown("<p><strong>代码</strong>\n<code><br></code></p>", "**代码**\n`<br>`"), true);++ const richText = "**标题**\n第二行\n\n[链接](https://example.com)\n\n";+ const richHTML = '<p><strong>标题</strong>\n第二行</p><p><a href="https://example.com">链接</a></p>' ++ '<p><img src="https://example.com/image.png" alt="图片"></p>';+ check.equal(preferMarkdown(richHTML, richText), true, "matching links and images");+ check.equal(preferMarkdown(richHTML.replace("image.png", "other.png"), richText), false, "different image source");+ check.equal(preferMarkdown(richHTML.replace('href="https://example.com"', 'href="https://example.com/other"'), richText),+ false, "different link destination");+ check.equal(preferMarkdown(richHTML + "<p>HTML 独有内容</p>", richText), false, "HTML-only content");++ for (const [name, value, plain] of [+ ["empty text", html, ""],+ ["empty HTML", "", text],+ ["ordinary selection", "<p>第一行\n第二行 $x$</p>", "第一行\n第二行 $x$"],+ ["ordinary rich selection", "<p><strong>标题</strong>\n内容 $x$</p>", "标题\n内容 $x$"],+ ["different text", html, text.replace("4.2", "5.0")],+ ["different structure", html.replaceAll("<strong>", "<em>").replaceAll("</strong>", "</em>"), text],+ ["text color", html.replace("<strong>", '<strong style="color: red">'), text],+ ["font size", html.replace("<p>", '<p style="font-size: 24px">'), text],+ ["list style", html.replace("decimal", "upper-roman"), text],+ ["list numbering", html.replace("<ol ", '<ol start="3" '), text],+ ["rendered math", '<p><strong>公式</strong> <span class="katex">x</span></p>', "**公式** $x$"],+ ["inline code", "<p><strong>示例</strong> <code>$g=4.2\\%$</code></p>", "**示例** `$g=4.2\\%$`"],+ ["fenced code", "<pre><code>$g=4.2\\%$\n$x$\n</code></pre>", "```\n$g=4.2\\%$\n$x$\n```"],+ ["explicit line break", "<p><strong>标题</strong><br>第二行</p>", "**标题**\n第二行"],+ ["placeholder collision", html + "\uE000", text + "\uE000"],+ ["raw HTML", "<p><strong>标题</strong>\n第二行</p>", "<p><strong>标题</strong>\n第二行</p>"],+ ["mixed raw HTML", "<p><strong>标题</strong>\n<span>第二行</span></p>", "**标题**\n<span>第二行</span>"],+ ]) {+ check.equal(preferMarkdown(value, plain), false, name);+ }++ // 识别过程处理未经清洗的受限编辑器剪贴板时,图片事件不能触发。+ window.clipboardImageEvents = 0;+ check.equal(preferMarkdown('<p><strong>图片</strong>\n<img src="data:image/png,broken" ' ++ 'onerror="window.clipboardImageEvents++"></p>', "**图片**\n"), false);+ await new Promise(resolve => setTimeout(resolve, 50));+ check.equal(window.clipboardImageEvents, 0);++ const lute = Lute.New();+ lute.SetInlineMath(true);+ lute.SetProtyleWYSIWYG(true);+ lute.SetTextMark(true);+ lute.SetHTMLTag2TextMark(true);+ const validateResult = result => {+ const root = document.createElement("div");+ root.innerHTML = result;+ check.deepEqual(Array.from(root.querySelectorAll('[data-type="inline-math"]'), node => node.dataset.content),+ ["g=4.2\\%", "S-A=C_A"]);+ check.match(root.querySelector('[data-type="NodeParagraph"] [contenteditable]').textContent,+ /示例\n名义增长率 [\s\S]*\n国民收入恒等式/);+ check.equal(root.querySelector('[data-type="NodeMathBlock"]').dataset.content, "\\(Y=C+I+G\\)");+ check.equal(root.querySelectorAll('[data-type="NodeListItem"]').length, 2);+ check.ok(Array.from(root.querySelectorAll('[data-type~="code"]')).some(node => node.textContent.includes("$g=4.2\\%$")));+ };++ // 执行共享入口,覆盖桌面剪贴板事件、移动端读取结果以及保留来源格式选项。+ const paste = async (mobile, preserveSourceFormat = false, restricted = false) => {+ let inserted;+ let htmlConversions = 0;+ let checkedBlockDOM;+ const validated = new Error("validated restricted content");+ const block = document.createElement("div");+ block.setAttribute("data-type", "NodeParagraph");+ const range = document.createRange();+ range.selectNodeContents(block);+ const noop = () => {};+ const mocks = {+ "../../constants": {Constants: {ZWSP: "\u200b"}},+ "./markdownClipboard": clipboard,+ "../runtimeCapabilities": {+ getProtyleBlockDOMSanitizer: () => restricted ? value => value : undefined,+ isProtyleRichHTMLPasteEnabled: () => restricted,+ isProtyleUploadDisabled: () => true,+ areProtylePluginExtensionsEnabled: () => false,+ getProtyleUnsupportedPasteBlocks: () => value => {+ checkedBlockDOM = value;+ throw validated;+ },+ },+ "../upload/insertPosition": {+ createUploadInsertPosition: () => ({range}), captureUploadDocument: () => ({}),+ isUploadInsertPositionAvailable: () => true, getAvailableUploadInsertRange: () => range,+ },+ "./selection": {getEditorRange: () => range},+ "./hasClosest": {hasClosestBlock: () => block},+ "./wpsPresentation": {extractWPSPresentationClipboard: () => undefined},+ "./compatibility": {isInHarmony: () => false,+ getTextSiyuanFromTextHTML: value => ({textSiyuan: "", textHtml: value})},+ "./officeMath": {extractOfficeMathHTML: () => ""},+ "./officeList": {convertOfficeLists: value => ({html: value, convertedCount: 0})},+ "./pasteSource": {extractCrossBlockPasteContext: value => ({html: value})},+ "./processCode": {processPasteCode: () => false, processRender: noop},+ "./inlineElementMarker": {stripSemanticMarkersFromRangeText: () => ""},+ "../upload/htmlLocalAssets": {resolveHTMLAssetURLs: noop, getHTMLAssetSourceURL: () => undefined,+ collectHTMLLocalAssets: () => [], removeHTMLLocalAssetPaths: noop},+ "../upload/htmlEmbeddedAssets": {hasHTMLEmbeddedAssets: () => false, collectHTMLEmbeddedAssets: () => []},+ "../../util/hostCapabilities": {getHostCapabilities: () => ({localFileSystem: false})},+ "../../util/fetch": {fetchSyncPost: async (_url, request) => {+ htmlConversions++;+ return {code: 0, data: lute.HTML2BlockDOM(request.dom)};+ }},+ "./insertHTML": {insertHTML: value => { inserted = value; }},+ "../ui/hideElements": {hideElements: noop},+ "../render/blockRender": {blockRender: noop},+ "../render/highlightRender": {highlightRender: noop},+ "../render/av/render": {avRender: noop},+ "../../util/highlightById": {scrollCenter: noop},+ "electron": {ipcRenderer: {invoke: async () => ""}},+ };+ window.siyuan = {config: {editor: {pasteURLAutoConvert: false}}};+ const protyle = {lute, hint: {}, options: {upload: {max: 1024 * 1024}},+ wysiwyg: {element: block}, toolbar: {getCurrentType: () => []}};+ const event = mobile ? {textHTML: html, textPlain: text, siyuanHTML: "", target: block, preserveSourceFormat} : {+ target: block, stopPropagation: noop, preventDefault: noop, preserveSourceFormat,+ clipboardData: {files: [], types: [], getData: type => ({"text/html": html, "text/plain": text}[type] || "")},+ };+ try {+ await load(source.paste, mocks).paste(protyle, event);+ check.equal(restricted, false);+ } catch (error) {+ if (!restricted || error !== validated) {+ throw error;+ }+ }+ return {inserted, htmlConversions, checkedBlockDOM};+ };+ for (const mobile of [false, true]) {+ const result = await paste(mobile);+ check.equal(result.htmlConversions, 0);+ validateResult(result.inserted);+ const preserved = await paste(mobile, true);+ check.equal(preserved.htmlConversions, 1);+ const restricted = await paste(mobile, false, true);+ validateResult(restricted.checkedBlockDOM);+ const restrictedPreserved = await paste(mobile, true, true);+ check.doesNotMatch(restrictedPreserved.checkedBlockDOM, /data-type="inline-math"/);+ }+ return "Markdown clipboard cases passed";+};++const run = async () => {+ const {app, BrowserWindow} = require("electron");+ app.setPath("userData", process.argv[2]);+ app.commandLine.appendSwitch("disable-gpu");+ await app.whenReady();+ const win = new BrowserWindow({show: false, webPreferences: {+ nodeIntegration: true, contextIsolation: false, offscreen: true,+ }});+ let code = 0;+ try {+ await win.loadURL("data:text/html,<html><body></body></html>");+ await win.webContents.executeJavaScript(readFileSync(path.join(__dirname,+ "../stage/protyle/js/lute/lute.min.js"), "utf8"));+ const result = await win.webContents.executeJavaScript(`(${runCases.toString()})(${JSON.stringify(sources())})`);+ assert.equal(result, "Markdown clipboard cases passed");+ console.log(result);+ } catch (error) {+ console.error(error);+ code = 1;+ } finally {+ win.destroy();+ app.exit(code);+ }+};++if (process.versions.electron && process.type === "browser") {+ run().catch(error => { console.error(error); require("electron").app.exit(1); });+} else {+ require("node:test").test("Markdown clipboard detection and shared paste entry", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 45000,+ }, async () => {+ const profile = mkdtempSync(path.join(os.tmpdir(), "siyuan-markdown-clipboard-test-"));+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ const {stdout} = await require("node:util").promisify(require("node:child_process").execFile)(+ require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 40000});+ assert.match(stdout, /Markdown clipboard cases passed/);+ } finally {+ assert.ok(path.resolve(profile).startsWith(path.resolve(os.tmpdir()) + path.sep));+ rmSync(profile, {recursive: true, force: true});+ }+ });+}