Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Add incremental agent Markdown rendering https://github.com/siyuan-note/siyuan/issues/19517

fengwind20066d1c732644c8
diff --git a/app/src/layout/dock/agent/AgentMarkdownBlocks.test.ts b/app/src/layout/dock/agent/AgentMarkdownBlocks.test.ts
new file mode 100644
index 0000000000..9052ba3d1c
--- /dev/null
+++ b/app/src/layout/dock/agent/AgentMarkdownBlocks.test.ts
@@ -0,0 +1,88 @@
+import * as assert from "node:assert/strict";
+import {test} from "node:test";
+import {AgentMarkdownBlocks} from "./AgentMarkdownBlocks";
+import {getAgentLute} from "../../../protyle/render/setLute";
+
+require("../../../../stage/protyle/js/lute/lute.min.js");
+const lute = getAgentLute({emojiSite: "/emojis", emojis: {}, sanitize: true});
+const normalize = (html: string) => html.replace(/ (?:id|updated)="[^"]*"/g, "");
+const padding = "A completed **paragraph**.\n\n".repeat(82);
+const samples = [
+ "# Heading\n\nParagraph\n\nLast\n",
+ "- one\n - nested\n\n continuation\n- two\n\nAfter\n",
+ "1. first\n\n2. second\n\nAfter\n",
+ "> quote\n>\n> - item\n> continuation\n\nAfter\n",
+ "> [!NOTE]\n> a callout\n\nAfter\n",
+ "````md\n```ts\n\nText\n\n```\n````\n\nAfter\n",
+ "```ts\n\n ```\n\nStill code\n\n```\n\nAfter\n",
+ " ~~~ts\n\nCode\n\n ~~~\n\nAfter\n",
+ "- ```ts\n value\n\n more\n ```\n\nAfter\n",
+ "| A | B |\n| --- | --- |\n| 1 | 2 |\n\nAfter\n",
+ "Header | other\n--- | ---\nvalue | more\n\nAfter\n",
+ "[link](https://example.com/a_(b))\n\nAfter\n",
+ "`multi\nline` **strong**\n\nAfter\n",
+ "中文 **粗体** 😀\r\n\r\n第二段\r\n",
+ "Bare\r\rCR\r\rAfter\r",
+ "$$\n\nx^2\n\n$$\n\nAfter\n",
+ "Text <span\n\nclass=\"foo\">inline</span>\n\nAfter\n",
+ "<!-- comment\n\nText\n\n-->\n\nAfter\n",
+ "<div>\n\n**bold**\n\n</div>\n\nAfter\n",
+ "<pre>\n\n```\n\nRaw\n\n</pre>\n\nAfter\n",
+ "{{{row\n\nLeft\n\n{{{col\n\nNested\n\n}}}\n\n}}}\n\nAfter\n",
+ "{{select * from blocks\n\nwhere type = 'p'\n\n}}\n\nAfter\n",
+ "\\[\n\nx^2\n\n\\]\n\nAfter\n",
+ "=== \"Tab\"\n\nText\n\n=== \"Next\"\n\nOther\n",
+ "Paragraph\n{: id=\"20240101000000-abcdefg\" custom-test=\"value\"}\n\nAfter\n",
+ "[ref]: https://example.com\n\nReference [ref]\n\nAfter\n",
+ ("# Section\n\n**bold** with `code`\n\n- one\n- two\n\n```ts\nconst a = 1;\n```\n\n").repeat(35),
+];
+
+test("streaming block groups match full Lute parsing across append boundaries", () => {
+ for (const sample of samples) {
+ // 将待测结构放在缓存阈值前后,防止仅在未触发分组的小输入上验证。
+ for (const prefix of [padding, padding.slice(0, 1800) + "\n\n"]) {
+ const source = prefix + sample + padding + "Tail\n";
+ const blocks = new AgentMarkdownBlocks();
+ let start = 0;
+ let committed = "";
+ for (let end = 1; end < source.length + 113; end += 113) {
+ const partial = source.slice(0, end);
+ for (const boundary of blocks.scan(partial)) {
+ assert.ok(boundary > start);
+ committed += lute.ProtylePreviewStr("", partial.slice(start, boundary))
+ .replace(/<\/pre>$/, "</pre>\n");
+ start = boundary;
+ }
+ assert.equal(normalize(committed + lute.ProtylePreviewStr("", partial.slice(start))),
+ normalize(lute.ProtylePreviewStr("", partial)), sample + " at " + end);
+ }
+ }
+ }
+});
+
+test("only completed independent lines commit groups, preserving split CRLF and IAL", () => {
+ for (const suffix of ["{: id=\"test\"}\n", " continuation\n", "- item\n", "1. item\n", "> quote\n"]) {
+ const blocks = new AgentMarkdownBlocks();
+ const source = "x".repeat(2200) + "\r\n\r\n";
+ assert.deepEqual(blocks.scan(source), []);
+ for (let i = 1; i <= suffix.length; i++) {
+ assert.deepEqual(blocks.scan(source + suffix.slice(0, i)), []);
+ }
+ }
+ const blocks = new AgentMarkdownBlocks();
+ const source = "x".repeat(2200) + "\r\n\r\nNext\r";
+ assert.deepEqual(blocks.scan(source), []);
+ assert.deepEqual(blocks.scan(source + "\n"), [2204]);
+ assert.deepEqual(blocks.scan(source + "\n"), []);
+});
+
+test("ordinary long replies produce bounded groups without splitting open containers", () => {
+ const blocks = new AgentMarkdownBlocks();
+ const source = padding.repeat(80) + "Tail\n";
+ const boundaries = blocks.scan(source);
+ assert.ok(boundaries.length > 70);
+ assert.ok(boundaries.every((end, i) => end - (boundaries[i - 1] || 0) < 2200));
+ for (const opening of ["```\n", "<!--\n", "$$\n", "{{{row\n", "=== \"Tab\"\n"]) {
+ assert.deepEqual(new AgentMarkdownBlocks().scan(opening + source), []);
+ }
+});
diff --git a/app/src/layout/dock/agent/AgentMarkdownBlocks.ts b/app/src/layout/dock/agent/AgentMarkdownBlocks.ts
new file mode 100644
index 0000000000..a53b5f2438
--- /dev/null
+++ b/app/src/layout/dock/agent/AgentMarkdownBlocks.ts
@@ -0,0 +1,68 @@
+// 缓存以段落组为单位,避免大量小段落分别创建解析任务。
+const groupSize = 2048;
+const listMarker = /^(?:[-+*]|\d+[.)])(?:[ \t]|$)/;
+
+/**
+ * 只扫描新增的完整行。空行不是充分条件:还需要后续完整的顶层普通段落或标题来关闭前块。
+ * 列表、引述和表格不从内部拆开;不确定的 HTML、公式和思源扩展留在同一个可变尾部。
+ * 调用者只传入同一条消息的追加式原文;偏移按原始 UTF-16 计算,不改写 CRLF。
+ */
+export class AgentMarkdownBlocks {
+ private cursor = 0;
+ private lineStart = 0;
+ private groupStart = 0;
+ private blank = false;
+ private opaque = false;
+ private fence = "";
+ private fenceLength = 0;
+
+ public scan(content: string): number[] {
+ const boundaries: number[] = [];
+ while (this.cursor < content.length) {
+ const char = content[this.cursor];
+ if (char !== "\n" && char !== "\r") {
+ this.cursor++;
+ continue;
+ }
+ // 保留分块末尾的 CR,等下一次输入确认它是不是 CRLF。
+ if (char === "\r" && this.cursor + 1 === content.length) {
+ break;
+ }
+ const line = content.slice(this.lineStart, this.cursor);
+ if (this.blank && !this.fence && !this.opaque &&
+ this.lineStart - this.groupStart >= groupSize && this.startsIndependentBlock(line)) {
+ boundaries.push(this.lineStart);
+ this.groupStart = this.lineStart;
+ }
+ this.consumeLine(line);
+ this.cursor += char === "\r" && content[this.cursor + 1] === "\n" ? 2 : 1;
+ this.lineStart = this.cursor;
+ }
+ return boundaries;
+ }
+
+ private startsIndependentBlock(line: string) {
+ // 等待完整的后继行,防止逐字符到达的 IAL、列表标记或容器开头被误认为普通段落。
+ return !!line && !/^[\s><{}`~$=|:+*-]/.test(line) && !listMarker.test(line);
+ }
+
+ private consumeLine(line: string) {
+ if (this.fence) {
+ const closing = /^ {0,3}(`+|~+)[ \t]*$/.exec(line);
+ if (closing && closing[1][0] === this.fence && closing[1].length >= this.fenceLength) {
+ this.fence = "";
+ }
+ this.blank = false;
+ return;
+ }
+ const opening = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
+ if (opening && (opening[1][0] !== "`" || !opening[2].includes("`"))) {
+ this.fence = opening[1][0];
+ this.fenceLength = opening[1].length;
+ } else if (/<|\$\$|\{\{|\{:|^[ \t]*===|`{3}|~{3}/.test(line)) {
+ // 这些语法可能跨空行或影响父容器;宁可减少缓存,也不复制一套不完整的 Lute 语法。
+ this.opaque = true;
+ }
+ this.blank = /^[ \t]*$/.test(line);
+ }
+}
diff --git a/app/src/layout/dock/agent/AgentMarkdownParser.ts b/app/src/layout/dock/agent/AgentMarkdownParser.ts
new file mode 100644
index 0000000000..e9930a6b65
--- /dev/null
+++ b/app/src/layout/dock/agent/AgentMarkdownParser.ts
@@ -0,0 +1,90 @@
+import {getAgentLute} from "../../../protyle/render/setLute";
+import {Constants} from "../../../constants";
+
+export interface AgentMarkdownParseRequest {
+ markdown: string;
+ luteURL: string;
+}
+
+export type AgentMarkdownParseResponse = {html: string; duration: number} | {error: true};
+
+const createWorker = () => {
+ // @ts-ignore -- Webpack 通过 import.meta.url 打包 Worker,主项目使用 CommonJS 类型检查。
+ return new Worker(new URL("./AgentMarkdownWorker.ts", import.meta.url));
+};
+
+/** 同时只允许一个解析请求;按需创建独立 Worker,不支持后台解析时使用相同的主线程 Lute。 */
+export class AgentMarkdownParser {
+ private worker: Worker | undefined;
+ private workerUnavailable = false;
+ private lute: Lute | undefined;
+ private generation = 0;
+
+ constructor(private readonly workerFactory: () => Worker = createWorker) {
+ }
+
+ public parse(markdown: string, done: (html?: string, duration?: number) => void) {
+ const generation = this.generation;
+ const script = document.getElementById("protyleLuteScript") as HTMLScriptElement;
+ // 本地内核通过 XHR 将 Lute 内联到 script,没有 src;此时使用相同的版本化资源地址。
+ const luteURL = script && (script.src || new URL(
+ `${Constants.PROTYLE_CDN}/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}`, document.baseURI).href);
+ if (!this.workerUnavailable && luteURL) {
+ try {
+ if (!this.worker) {
+ this.worker = this.workerFactory();
+ }
+ this.worker.onmessage = (event: MessageEvent<AgentMarkdownParseResponse>) => {
+ if (generation === this.generation) {
+ if ("html" in event.data) {
+ done(event.data.html, event.data.duration);
+ } else {
+ done();
+ }
+ }
+ };
+ const onFailure = (event: Event) => {
+ event.preventDefault();
+ if (generation !== this.generation) {
+ return;
+ }
+ this.cancel();
+ this.workerUnavailable = true;
+ this.parseInline(markdown, done);
+ };
+ this.worker.onerror = onFailure;
+ this.worker.onmessageerror = onFailure;
+ this.worker.postMessage({markdown, luteURL} satisfies AgentMarkdownParseRequest);
+ return;
+ } catch (e) {
+ this.cancel();
+ this.workerUnavailable = true;
+ }
+ }
+ this.parseInline(markdown, done);
+ }
+
+ public cancel() {
+ this.generation++;
+ if (this.worker) {
+ this.worker.onmessage = null;
+ this.worker.onerror = null;
+ this.worker.onmessageerror = null;
+ this.worker.terminate();
+ this.worker = undefined;
+ }
+ }
+
+ private parseInline(markdown: string, done: (html?: string) => void) {
+ let html: string | undefined;
+ try {
+ if (!this.lute) {
+ this.lute = getAgentLute({emojiSite: "/emojis", emojis: {}, sanitize: true});
+ }
+ html = this.lute.ProtylePreviewStr("", markdown);
+ } catch (e) {
+ // 当前预览保留到下一次输入重试;解析错误不应中断 SSE 或覆盖已经格式化的内容。
+ }
+ done(html);
+ }
+}
diff --git a/app/src/layout/dock/agent/AgentMarkdownWorker.ts b/app/src/layout/dock/agent/AgentMarkdownWorker.ts
new file mode 100644
index 0000000000..bf40092946
--- /dev/null
+++ b/app/src/layout/dock/agent/AgentMarkdownWorker.ts
@@ -0,0 +1,24 @@
+import {getAgentLute} from "../../../protyle/render/setLute";
+import type {AgentMarkdownParseRequest, AgentMarkdownParseResponse} from "./AgentMarkdownParser";
+
+const scope = globalThis as unknown as {
+ importScripts: (url: string) => void;
+ onmessage: (event: MessageEvent<AgentMarkdownParseRequest>) => void;
+ postMessage: (response: AgentMarkdownParseResponse) => void;
+};
+let lute: Lute;
+
+scope.onmessage = (event) => {
+ if (!lute) {
+ // 加载失败交给 Worker 的 error 事件处理,使主页面可在不支持 Worker 的环境继续预览。
+ scope.importScripts(event.data.luteURL);
+ lute = getAgentLute({emojiSite: "/emojis", emojis: {}, sanitize: true});
+ }
+ try {
+ const start = performance.now();
+ const html = lute.ProtylePreviewStr("", event.data.markdown);
+ scope.postMessage({html, duration: performance.now() - start});
+ } catch (e) {
+ scope.postMessage({error: true});
+ }
+};
diff --git a/app/src/layout/dock/agent/AgentStreamingMarkdown.ts b/app/src/layout/dock/agent/AgentStreamingMarkdown.ts
new file mode 100644
index 0000000000..2fc018e41c
--- /dev/null
+++ b/app/src/layout/dock/agent/AgentStreamingMarkdown.ts
@@ -0,0 +1,207 @@
+import {escapeHtml} from "../../../util/escape";
+import {AgentMarkdownBlocks} from "./AgentMarkdownBlocks";
+import {AgentMarkdownParser} from "./AgentMarkdownParser";
+
+export const AGENT_MARKDOWN_INTERVAL = 100;
+const maxInterval = 1000;
+
+export interface AgentStreamingMarkdownScheduler {
+ now: () => number;
+ schedule: (callback: () => void, delay: number) => number;
+ cancel: (id: number) => void;
+}
+
+const scheduler: AgentStreamingMarkdownScheduler = {
+ now: () => performance.now(),
+ schedule: (callback, delay) => window.setTimeout(callback, delay),
+ cancel: (id) => window.clearTimeout(id),
+};
+
+export class AgentStreamingMarkdown {
+ private timer: number | undefined;
+ private generation = 0;
+ private parsing = false;
+ private content = "";
+ private renderedLength = 0;
+ private interval = AGENT_MARKDOWN_INTERVAL;
+ private nextUpdate = 0;
+ private readonly blocks = new AgentMarkdownBlocks();
+ private readonly parser = new AgentMarkdownParser();
+ private boundaries: number[] = [];
+ private boundaryIndex = 0;
+ private tailStart = 0;
+ private tailNodes: Node[] | undefined;
+
+ constructor(private readonly body: HTMLElement, private readonly onUpdate: () => void,
+ private readonly clock: AgentStreamingMarkdownScheduler = scheduler) {
+ }
+
+ public update(content: string) {
+ // 一条控制器对应一条追加式消息;替换原文/恢复会话时由 AgentChat 创建新控制器。
+ this.content = content;
+ if (content.length !== this.renderedLength) {
+ this.schedule();
+ }
+ }
+
+ public flush() {
+ // 原文由 AgentChat 保存并负责最终渲染;切换/收尾不重复解析,也不把预览改成源码。
+ this.cancel();
+ }
+
+ public cancel() {
+ this.generation++;
+ if (this.timer !== undefined) {
+ this.clock.cancel(this.timer);
+ this.timer = undefined;
+ }
+ this.parser.cancel();
+ this.parsing = false;
+ }
+
+ private schedule() {
+ if (this.timer !== undefined || this.parsing) {
+ return;
+ }
+ // 已排队的任务不因新 token 重置;后台解析期间只保留最新快照,不积压解析请求。
+ const generation = this.generation;
+ this.timer = this.clock.schedule(() => {
+ if (generation !== this.generation) {
+ return;
+ }
+ this.timer = undefined;
+ this.render();
+ }, Math.max(0, this.nextUpdate - this.clock.now()));
+ }
+
+ private render() {
+ const content = this.content;
+ this.blocks.scan(content).forEach(boundary => this.boundaries.push(boundary));
+ const boundary = this.boundaries[this.boundaryIndex];
+ const end = boundary ?? content.length;
+ const source = content.slice(this.tailStart, end);
+ const start = this.clock.now();
+ const generation = this.generation;
+ this.parsing = true;
+ this.parser.parse(source, (html, parseDuration) => {
+ if (generation !== this.generation) {
+ return;
+ }
+ this.parsing = false;
+ if (html === undefined) {
+ // 不在同一份失败快照上自动重试;下一次输入仍会触发解析,完成时使用完整原文。
+ this.nextUpdate = this.clock.now() + maxInterval;
+ if (content !== this.content) {
+ this.schedule();
+ }
+ return;
+ }
+ const applyStart = this.clock.now();
+ const template = this.body.ownerDocument.createElement("template");
+ template.innerHTML = html || escapeHtml(source);
+ if (boundary !== undefined && template.content.lastChild?.nodeName === "PRE") {
+ // Lute 在文档末尾省略代码块后的换行;已缓存分组在完整消息中并不是文档末尾。
+ template.content.appendChild(this.body.ownerDocument.createTextNode("\n"));
+ }
+ this.preparePreview(template.content);
+ this.patchPreview(template.content, boundary !== undefined);
+ this.body.classList.add("agent-chat__body--streaming-markdown");
+ this.renderedLength = end;
+ if (boundary !== undefined) {
+ // 已完成前缀留在原位,此后既不交给 Lute,也不再遍历其 DOM。
+ this.tailStart = boundary;
+ this.boundaryIndex++;
+ if (this.boundaryIndex === this.boundaries.length) {
+ this.boundaries = [];
+ this.boundaryIndex = 0;
+ }
+ }
+ // 将布局和滚动更新计入节流预算;超预算只降频,不关闭格式化预览。
+ this.onUpdate();
+ void this.body.offsetHeight;
+ // Worker 的首次加载等待不代表解析成本,避免刚开启预览就被长期降频。
+ const duration = (parseDuration ?? (applyStart - start)) + this.clock.now() - applyStart;
+ this.interval = Math.min(maxInterval,
+ Math.max(AGENT_MARKDOWN_INTERVAL, this.interval * 0.75, duration * 8, source.length / 64));
+ // 初次加载或积压的已完成段落组分任务处理,每次让出主线程,再追赶可变尾部。
+ this.nextUpdate = this.clock.now() + (boundary === undefined ? this.interval : 16);
+ if (this.renderedLength !== this.content.length) {
+ this.schedule();
+ }
+ });
+ }
+
+ private preparePreview(fragment: DocumentFragment) {
+ fragment.querySelectorAll("[id], [updated]").forEach((element) => {
+ // Lute 为每次解析生成新的 ID/时间,预览不使用这些临时属性。
+ element.removeAttribute("id");
+ element.removeAttribute("updated");
+ });
+ fragment.querySelectorAll<HTMLElement>("[data-subtype][data-content]").forEach((element) => {
+ // 公式和图表在生成期间显示源码,不启动重型渲染器。
+ const source = this.body.ownerDocument.createElement(element.tagName === "SPAN" ? "code" : "pre");
+ source.textContent = element.getAttribute("data-content");
+ element.replaceWith(source);
+ });
+ fragment.querySelectorAll("table").forEach((table) => {
+ const wrapper = this.body.ownerDocument.createElement("div");
+ wrapper.className = "table";
+ const scroll = this.body.ownerDocument.createElement("div");
+ table.before(wrapper);
+ wrapper.appendChild(scroll);
+ scroll.appendChild(table);
+ });
+ }
+
+ private patchPreview(fragment: DocumentFragment, committed: boolean) {
+ const previous = this.tailNodes ?? Array.from(this.body.childNodes);
+ const incoming = Array.from(fragment.childNodes);
+ // 提交前缀时保留已经可见的尾部,避免分任务追赶时先删除后追加而产生闪烁。
+ const updated = this.patchChildren(this.body,
+ committed ? previous.slice(0, incoming.length) : previous, incoming);
+ this.tailNodes = committed ? previous.slice(incoming.length) : updated;
+ }
+
+ private patchChildren(parent: Node, previous: Node[], incoming: Node[]): Node[] {
+ const result = incoming.map((node, index) => {
+ const old = previous[index];
+ if (!old) {
+ parent.appendChild(node);
+ return node;
+ }
+ if (old.isEqualNode(node)) {
+ return old;
+ }
+ if (old.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
+ const before = (old as Text).data;
+ const after = (node as Text).data;
+ if (after.startsWith(before)) {
+ // 未高亮代码块和正文尾部只追加字符,保留节点及已经选中的文本。
+ (old as Text).appendData(after.slice(before.length));
+ } else {
+ (old as Text).data = after;
+ }
+ return old;
+ }
+ if (old instanceof Element && node instanceof Element && old.tagName === node.tagName &&
+ old.namespaceURI === node.namespaceURI) {
+ Array.from(old.attributes).forEach((attr) => {
+ if (!node.hasAttribute(attr.name)) {
+ old.removeAttribute(attr.name);
+ }
+ });
+ Array.from(node.attributes).forEach((attr) => {
+ if (old.getAttribute(attr.name) !== attr.value) {
+ old.setAttribute(attr.name, attr.value);
+ }
+ });
+ this.patchChildren(old, Array.from(old.childNodes), Array.from(node.childNodes));
+ return old;
+ }
+ parent.replaceChild(node, old);
+ return node;
+ });
+ previous.slice(incoming.length).forEach(node => parent.removeChild(node));
+ return result;
+ }
+}