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: Align HTML asset uploads with paste conversion https://github.com/siyuan-note/siyuan/issues/18878
Danielcfade91da230
diff --git a/app/src/protyle/upload/base64.ts b/app/src/protyle/upload/base64.tsindex ac1c0b52d1..962817c9ee 100644--- a/app/src/protyle/upload/base64.ts+++ b/app/src/protyle/upload/base64.ts@@ -7,7 +7,7 @@ export const base64ToURL = async (base64SrcList: string[], protyle: IProtyle,const files: File[] = [];const fileSourceIndices: number[] = [];base64SrcList.forEach((item, sourceIndex) => {- const file = createBase64ImageFile(item, `base64image-${Lute.NewNodeID()}`);+ const file = createBase64ImageFile(item, `base64image-${Lute.NewNodeID()}`, protyle.options.upload.max);if (!file) {return;}diff --git a/app/src/protyle/upload/base64File.ts b/app/src/protyle/upload/base64File.tsindex ac64332454..91614993e7 100644--- a/app/src/protyle/upload/base64File.ts+++ b/app/src/protyle/upload/base64File.ts@@ -1,12 +1,41 @@-const getBase64ImageExtension = (mime: string) => ({- "image/png": "png",- "image/jpeg": "jpg",- "image/webp": "webp",- "image/gif": "gif",- "image/svg+xml": "svg",-}[mime] || "png");+interface IBase64ImageFormat {+ extension: string;+ mime: string;+}-export const createBase64ImageFile = (source: string, name: string) => {+const startsWith = (bytes: Uint8Array, signature: number[]) =>+ signature.every((value, index) => bytes[index] === value);++const detectBase64ImageFormat = (bytes: Uint8Array): IBase64ImageFormat | undefined => {+ if (startsWith(bytes, [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) {+ return {extension: "png", mime: "image/png"};+ }+ if (startsWith(bytes, [0xFF, 0xD8, 0xFF])) {+ return {extension: "jpg", mime: "image/jpeg"};+ }+ if (startsWith(bytes, [0x47, 0x49, 0x46, 0x38, 0x37, 0x61]) ||+ startsWith(bytes, [0x47, 0x49, 0x46, 0x38, 0x39, 0x61])) {+ return {extension: "gif", mime: "image/gif"};+ }+ if (startsWith(bytes, [0x42, 0x4D])) {+ return {extension: "bmp", mime: "image/bmp"};+ }+ if (startsWith(bytes, [0x52, 0x49, 0x46, 0x46]) &&+ startsWith(bytes.subarray(8), [0x57, 0x45, 0x42, 0x50])) {+ return {extension: "webp", mime: "image/webp"};+ }+ const text = new TextDecoder().decode(bytes.subarray(0, 4096)).replace(/^\uFEFF/, "").trimStart();+ if (/^(?:<\?xml[^>]*>\s*)?<svg(?:\s|>)/i.test(text)) {+ return {extension: "svg", mime: "image/svg+xml"};+ }+};++const getBase64DecodedSize = (base64: string) => {+ const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;+ return Math.floor(base64.length * 3 / 4) - padding;+};++export const createBase64ImageFile = (source: string, name: string, maxBytes?: number) => {const separator = source.indexOf(",");if (separator < 0) {return;@@ -16,13 +45,20 @@ export const createBase64ImageFile = (source: string, name: string) => {return;}try {- const mime = mimeMatch[1].toLowerCase();- const binary = atob(source.substring(separator + 1));+ const base64 = source.substring(separator + 1).replace(/%0A/gi, "\n").replace(/\s/g, "");+ if (maxBytes !== undefined && getBase64DecodedSize(base64) > maxBytes) {+ return;+ }+ const binary = atob(base64);const bytes = new Uint8Array(binary.length);for (let index = 0; index < binary.length; index++) {bytes[index] = binary.charCodeAt(index);}- return new File([bytes], `${name}.${getBase64ImageExtension(mime)}`, {type: mime});+ const format = detectBase64ImageFormat(bytes);+ if (!format) {+ return;+ }+ return new File([bytes], `${name}.${format.extension}`, {type: format.mime});} catch (error) {console.error(error);}diff --git a/app/src/protyle/upload/htmlEmbeddedAssets.test.ts b/app/src/protyle/upload/htmlEmbeddedAssets.test.tsindex 26a5cf3f52..74f3e30237 100644--- a/app/src/protyle/upload/htmlEmbeddedAssets.test.ts+++ b/app/src/protyle/upload/htmlEmbeddedAssets.test.ts@@ -4,6 +4,7 @@ import {createBase64ImageFile} from "./base64File";import {applyHTMLEmbeddedAssetPaths,collectHTMLEmbeddedAssets,+ hasHTMLEmbeddedAssets,type IHTMLEmbeddedAsset,isHTMLBase64Image,} from "./htmlEmbeddedAssets";@@ -16,16 +17,48 @@ describe("HTML embedded assets", () => {assert.equal(isHTMLBase64Image("https://example.com/image.png"), false);});- it("creates image files using the declared content type", () => {- const file = createBase64ImageFile("data:image/jpeg;base64,YQ==", "image");+ it("creates image files using the detected content type", () => {+ const file = createBase64ImageFile("data:image/png;base64,/9j/2Q==", "image");assert.equal(file.name, "image.jpg");assert.equal(file.type, "image/jpeg");- assert.equal(file.size, 1);+ assert.equal(file.size, 4);+ });++ it("supports raster signatures and encoded Base64 line breaks", () => {+ const gif = createBase64ImageFile("data:image/png;base64,R0lGODlh", "gif");+ const bmp = createBase64ImageFile("data:image/png;base64,Qk0=", "bmp");+ const png = createBase64ImageFile("data:image/png;base64,iVBORw0K%0AGgo=", "png");++ assert.equal(gif.name, "gif.gif");+ assert.equal(gif.type, "image/gif");+ assert.equal(bmp.name, "bmp.bmp");+ assert.equal(bmp.type, "image/bmp");+ assert.equal(png.name, "png.png");+ assert.equal(png.type, "image/png");+ assert.equal(createBase64ImageFile("data:image/png;base64,UklGRgAAAABXRUJQ", "webp")?.type, "image/webp");+ assert.equal(createBase64ImageFile("data:image/png;base64,PHN2Zz48L3N2Zz4=", "svg")?.type, "image/svg+xml");+ });++ it("rejects unsupported and oversized Base64 images before decoding", () => {+ assert.equal(createBase64ImageFile("data:image/png;base64,YQ==", "invalid"), undefined);+ const originalAtob = globalThis.atob;+ let decoded = false;+ globalThis.atob = (value: string) => {+ decoded = true;+ return originalAtob(value);+ };+ try {+ assert.equal(createBase64ImageFile("data:image/png;base64,iVBORw0KGgo=", "large", 7), undefined);+ } finally {+ globalThis.atob = originalAtob;+ }+ assert.equal(decoded, false);+ assert.equal(createBase64ImageFile("data:image/png;base64,iVBORw0KGgo=", "image", 8)?.size, 8);});it("collects Base64 attributes and rewrites them after upload", () => {- const attributes = new Map([["src", "data:image/png;base64,YQ=="]]);+ const attributes = new Map([["src", "data:image/png;base64,iVBORw0KGgo="]]);const element = {getAttribute(name: string) {return attributes.get(name) || null;@@ -47,6 +80,23 @@ describe("HTML embedded assets", () => {assert.equal(attributes.get("src"), "assets/image.png");});+ it("detects embedded assets without decoding them", () => {+ const root = {+ querySelectorAll(selector: string) {+ if (selector === "pre") {+ return [];+ }+ return [{+ getAttribute(attribute: string) {+ return attribute === "src" ? "data:image/png;base64,not-decoded" : null;+ },+ }];+ },+ } as unknown as ParentNode;++ assert.equal(hasHTMLEmbeddedAssets(root), true);+ });+it("collects inline SVG blocks and replaces them with uploaded images", () => {const attributes = new Map<string, string>();const image = {diff --git a/app/src/protyle/upload/htmlEmbeddedAssets.ts b/app/src/protyle/upload/htmlEmbeddedAssets.tsindex cbc5e8f264..f6c9c0db29 100644--- a/app/src/protyle/upload/htmlEmbeddedAssets.ts+++ b/app/src/protyle/upload/htmlEmbeddedAssets.ts@@ -7,7 +7,18 @@ export interface IHTMLEmbeddedAsset {export const isHTMLBase64Image = (value: string) => /^data:image\/[^,]+;base64,/i.test(value.trim());-export const collectHTMLEmbeddedAssets = (root: ParentNode) => {+export const hasHTMLEmbeddedAssets = (root: ParentNode) => {+ if (Array.from(root.querySelectorAll("pre")).some(element => element.hasAttributes() && element.querySelector("svg"))) {+ return true;+ }+ return Array.from(root.querySelectorAll("[href], [src]")).some(element =>+ ["href", "src"].some(attribute => {+ const source = element.getAttribute(attribute);+ return source ? isHTMLBase64Image(source) : false;+ }));+};++export const collectHTMLEmbeddedAssets = (root: ParentNode, maxBytes?: number) => {const assets: IHTMLEmbeddedAsset[] = [];const svgBlocks = new Set<Element>();root.querySelectorAll("pre").forEach(element => {@@ -39,7 +50,7 @@ export const collectHTMLEmbeddedAssets = (root: ParentNode) => {if (!source || !isHTMLBase64Image(source)) {return;}- const file = createBase64ImageFile(source.trim(), `html-image-${assets.length}`);+ const file = createBase64ImageFile(source.trim(), `html-image-${assets.length}`, maxBytes);if (!file) {return;}diff --git a/app/src/protyle/upload/index.ts b/app/src/protyle/upload/index.tsindex b8561aeff5..38b7ccefaa 100644--- a/app/src/protyle/upload/index.ts+++ b/app/src/protyle/upload/index.ts@@ -663,7 +663,7 @@ const startPreparedAssetUpload = (prepared: Awaited<ReturnType<typeof prepareAssreturn;}try {- prepared.task.startUpload();+ prepared.task.startUpload(prepared.task.input.kind === "files" && Boolean(protyle.options.upload.handler));if (prepared.task.input.files.length === 0) {finishUpload(prepared.task, callbacks, {status: "canceled"});return;diff --git a/app/src/protyle/upload/pluginEvent.test.ts b/app/src/protyle/upload/pluginEvent.test.tsindex 0a715df521..16087d4a62 100644--- a/app/src/protyle/upload/pluginEvent.test.ts+++ b/app/src/protyle/upload/pluginEvent.test.ts@@ -411,7 +411,7 @@ describe("asset upload plugin event", () => {assert.equal(signal.aborted, true);});- it("aborts the upload phase when the editor is destroyed", async () => {+ it("does not abort a standard upload after its transport starts", async () => {const currentProtyle = {} as IProtyle;const prepared = await prepareAssetUpload({plugins: [],@@ -424,6 +424,23 @@ describe("asset upload plugin event", () => {cancelAssetUploads(currentProtyle);+ assert.equal(prepared.task.signal.aborted, false);+ prepared.task.complete({status: "canceled"});+ });++ it("aborts a custom upload handler when the editor is destroyed", async () => {+ const currentProtyle = {} as IProtyle;+ const prepared = await prepareAssetUpload({+ plugins: [],+ protyle: currentProtyle,+ input: {kind: "files", files: [createFile("a.png")]},+ context,+ });+ assert.equal(prepared.state, "ready");+ prepared.task.startUpload(true);++ cancelAssetUploads(currentProtyle);+assert.equal(prepared.task.signal.aborted, true);prepared.task.complete({status: "canceled"});});diff --git a/app/src/protyle/upload/pluginEvent.ts b/app/src/protyle/upload/pluginEvent.tsindex 81d4000cc8..0a6e981f1e 100644--- a/app/src/protyle/upload/pluginEvent.ts+++ b/app/src/protyle/upload/pluginEvent.ts@@ -14,7 +14,7 @@ export interface IAssetUploadTask {readonly signal: AbortSignal;input: IAssetUploadInput;abort(reason: Error): void;- startUpload(): void;+ startUpload(cancelOnEditorDestroy?: boolean): void;complete(result: Omit<IAssetUploadResult, "requestId" | "input">): boolean;}@@ -209,11 +209,14 @@ class AssetUploadTask implements IAssetUploadTask {this.waitingPlugins = [];}- public startUpload() {+ public startUpload(cancelOnEditorDestroy = false) {if (this.uploadStarted || !this.protyle) {return;}this.uploadStarted = true;+ if (!cancelOnEditorDestroy) {+ return;+ }let tasks = activeTasksByProtyle.get(this.protyle);if (!tasks) {tasks = new Set();diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.tsindex 9db330d841..c68a0f0ca6 100644--- a/app/src/protyle/util/paste.ts+++ b/app/src/protyle/util/paste.ts@@ -20,7 +20,11 @@ import {clearBlockElement} from "./clear";import {removeZWJ} from "./normalizeText";import {base64ToURL} from "../upload/base64";import {applyHTMLLocalAssetPaths, collectHTMLLocalAssets} from "../upload/htmlLocalAssets";-import {applyHTMLEmbeddedAssetPaths, collectHTMLEmbeddedAssets} from "../upload/htmlEmbeddedAssets";+import {+ applyHTMLEmbeddedAssetPaths,+ collectHTMLEmbeddedAssets,+ hasHTMLEmbeddedAssets,+} from "../upload/htmlEmbeddedAssets";import {getAssetUploadPathsByInput} from "../upload/uploadResult";import {resolveLinkDest} from "../toolbar/util";import {updateTransaction} from "../wysiwyg/transaction";@@ -1052,6 +1056,34 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvenreturn;}const localAssets = collectHTMLLocalAssets(tempElement);+ const conversionContext = {+ text: textPlain,+ mathML,+ office,+ officeMathHTML,+ wps,+ };+ if (localAssets.length > 0 || hasHTMLEmbeddedAssets(tempElement)) {+ let preflightResponse: IWebSocketData;+ try {+ preflightResponse = await fetchSyncPost("/api/lute/html2BlockDOM", {+ ...conversionContext,+ dom: tempElement.innerHTML,+ preflight: true,+ });+ } catch (error) {+ return;+ }+ const preflight = preflightResponse?.data as {converted?: unknown, dom?: unknown, useHTML?: unknown};+ if (preflightResponse?.code !== 0 || preflight?.converted !== true ||+ typeof preflight.useHTML !== "boolean" || typeof preflight.dom !== "string") {+ return;+ }+ if (!preflight.useHTML) {+ insertConvertedBlockDOM(protyle, preflight.dom);+ return;+ }+ }if (localAssets.length > 0) {await new Promise<void>(resolve => {uploadLocalFiles(localAssets.map(item => ({path: item.path, size: null})), protyle, true, {@@ -1064,7 +1096,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven}, () => resolve());});}- const embeddedAssets = collectHTMLEmbeddedAssets(tempElement);+ const embeddedAssets = collectHTMLEmbeddedAssets(tempElement, protyle.options.upload.max);if (embeddedAssets.length > 0) {await new Promise<void>(resolve => {uploadFiles(protyle, embeddedAssets.map(item => item.file), undefined, (_response, result) => {@@ -1077,12 +1109,8 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven});}fetchPost("/api/lute/html2BlockDOM", {+ ...conversionContext,dom: tempElement.innerHTML,- text: textPlain,- mathML,- office,- officeMathHTML,- wps,skipLocalAssets: localAssets.length > 0,skipBase64Assets: true,skipInlineSVGAssets: true,diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex 054b5c0e1a..d0dbf06569 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -406,6 +406,7 @@ type IAssetUploadInput = {type IAssetUploadDecision = {action: "replace",+ /** 必须保持各项的逻辑顺序;需要逐项回填的上传会按下标关联原资源。 */input: IAssetUploadInput} | {action: "cancel"@@ -455,14 +456,17 @@ interface IBeforeUploadAssetsDetail {source: TAssetUploadSource,target: TAssetUploadTarget,position?: IAssetUploadPosition,- /** 替换输入必须保持的精确文件数量。 */+ /** 替换输入必须保持的精确文件数量;各项还须与原输入按下标一一对应。 */requiredFileCount?: number,/** 当前目标支持的输入类型;未提供时支持 files 和 local-files。 */allowedInputKinds?: Array<IAssetUploadInput["kind"]>,input: IAssetUploadInput,- /** 插件处理的取消信号,编辑器销毁、插件卸载或处理超时时触发。 */+ /**+ * 插件处理阶段的取消信号;自定义 upload.handler 执行期间也会在编辑器销毁或超时时触发。+ * 标准传输开始后不再因编辑器销毁触发。+ */signal: AbortSignal,- /** 必须同步调用且每次事件只允许调用一次,异步处理应将 Promise 作为参数传入,每个插件默认 120 秒超时。 */+ /** 必须同步调用且每次事件只允许调用一次;替换项须保持逻辑顺序,异步处理应传入 Promise,每个插件默认 120 秒超时。 */respondWith(response: IAssetUploadDecision | PromiseLike<IAssetUploadDecision>): void,/*** 必须同步注册,经思源前端上传协调层发起的资源写入成功、失败或取消时执行一次。diff --git a/app/src/types/protyle.d.ts b/app/src/types/protyle.d.tsindex 852ca1fd06..a8fddd8e85 100644--- a/app/src/types/protyle.d.ts+++ b/app/src/types/protyle.d.ts@@ -363,7 +363,7 @@ interface IUpload {/** 对服务端返回的数据进行转换,以满足内置的数据结构 */format?(files: File[], responseText: string): string;- /** 将上传的文件处理后再返回 */+ /** 将上传的文件逐项处理后再返回;返回项必须保持原有逻辑顺序 */file?(files: File[]): File[];/** 图片地址上传后的回调 */diff --git a/kernel/api/lute.go b/kernel/api/lute.goindex 10285a023e..f41579d758 100644--- a/kernel/api/lute.go+++ b/kernel/api/lute.go@@ -113,19 +113,24 @@ func html2BlockDOM(c *gin.Context) {skipLocalAssets, _ := arg["skipLocalAssets"].(bool)skipBase64Assets, _ := arg["skipBase64Assets"].(bool)skipInlineSVGAssets, _ := arg["skipInlineSVGAssets"].(bool)+ preflight, _ := arg["preflight"].(bool)luteEngine := util.NewLute()luteEngine.SetHTMLTag2TextMark(true)luteEngine.SetHTML2MarkdownAttrs([]string{"alias", "memo", "bookmark", "custom-*"})- // 将 Word 和 WPS 公式转换为可编辑公式 https://github.com/siyuan-note/siyuan/issues/18747- if markdown, converted := convertClipboardMath(mathML, office, wps); converted {- luteEngine.SetInlineMath(true)- ret.Data = luteEngine.Md2BlockDOM(markdown, false)+ dom, useHTML := resolveHTMLClipboardContent(luteEngine, dom, mathML, office, officeMathHTML, wps,+ convertClipboardMath, convertOfficeHTMLClipboardMath)+ if !useHTML {+ if preflight {+ ret.Data = map[string]any{"converted": true, "dom": dom, "useHTML": false}+ } else {+ ret.Data = dom+ }return}- if markdown, converted := convertOfficeHTMLClipboardMath(officeMathHTML); converted {- luteEngine.SetInlineMath(true)- ret.Data = luteEngine.Md2BlockDOM(markdown, false)- return+ if preflight {+ skipLocalAssets = true+ skipBase64Assets = true+ skipInlineSVGAssets = true}// 将 Word 和 WPS 批注转换为行级备注 https://github.com/siyuan-note/siyuan/issues/18748dom = normalizeWPSComments(dom, text, wps)@@ -135,7 +140,11 @@ func html2BlockDOM(c *gin.Context) {SkipInlineSVGAssets: skipInlineSVGAssets,})if nil == tree {- ret.Data = "Failed to convert"+ if preflight {+ ret.Data = map[string]any{"converted": false, "dom": "Failed to convert", "useHTML": true}+ } else {+ ret.Data = "Failed to convert"+ }return}@@ -251,14 +260,40 @@ func html2BlockDOM(c *gin.Context) {md, err := lute.FormatNodeSync(tree.Root, luteEngine.ParseOptions, luteEngine.RenderOptions)if nil != err {- ret.Data = "Failed to convert"+ if preflight {+ ret.Data = map[string]any{"converted": false, "dom": "Failed to convert", "useHTML": true}+ } else {+ ret.Data = "Failed to convert"+ }return}tree = parse.Parse("", []byte(md), luteEngine.ParseOptions)renderer := render.NewProtyleRenderer(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)output := renderer.Render()- ret.Data = gulu.Str.FromBytes(output)+ convertedDOM := gulu.Str.FromBytes(output)+ if preflight {+ ret.Data = map[string]any{"converted": true, "dom": convertedDOM, "useHTML": true}+ } else {+ ret.Data = convertedDOM+ }+}++type clipboardMathConverter func(mathML, office, wps string) (markdown string, converted bool)+type officeHTMLClipboardMathConverter func(officeMathHTML string) (markdown string, converted bool)++func resolveHTMLClipboardContent(luteEngine *lute.Lute, dom, mathML, office, officeMathHTML, wps string,+ mathConverter clipboardMathConverter, officeHTMLMathConverter officeHTMLClipboardMathConverter) (resolvedDOM string, useHTML bool) {+ // 将 Word 和 WPS 公式转换为可编辑公式 https://github.com/siyuan-note/siyuan/issues/18747+ if markdown, converted := mathConverter(mathML, office, wps); converted {+ luteEngine.SetInlineMath(true)+ return luteEngine.Md2BlockDOM(markdown, false), false+ }+ if markdown, converted := officeHTMLMathConverter(officeMathHTML); converted {+ luteEngine.SetInlineMath(true)+ return luteEngine.Md2BlockDOM(markdown, false), false+ }+ return dom, true}func normalizeMSWordComments(dom string) string {diff --git a/kernel/api/lute_clipboard_math_test.go b/kernel/api/lute_clipboard_math_test.goindex d49da8ed02..96fb779019 100644--- a/kernel/api/lute_clipboard_math_test.go+++ b/kernel/api/lute_clipboard_math_test.go@@ -56,6 +56,39 @@ func TestConvertClipboardMathWithRunner(t *testing.T) {}}+func TestResolveHTMLClipboardContentBeforeAssetProcessing(t *testing.T) {+ mathML := `<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>x</mi></math>`+ htmlWithImage := `<p>fallback</p><img src="data:image/png;base64,iVBORw0KGgo=">`+ mathConverter := func(actualMathML, office, wps string) (string, bool) {+ markdown, converted, err := convertClipboardMathWithRunner(actualMathML, office, wps,+ func(from, to string, input []byte) ([]byte, error) {+ if from != "html" || to != "json" || string(input) != mathML {+ t.Fatalf("unexpected MathML input: from=%q to=%q input=%q", from, to, input)+ }+ return []byte(inlineMathPandocJSON), nil+ })+ if err != nil {+ t.Fatal(err)+ }+ return markdown, converted+ }+ resolvedDOM, useHTML := resolveHTMLClipboardContent(util.NewLute(), htmlWithImage, mathML, "", "", "",+ mathConverter, func(string) (string, bool) {+ t.Fatal("Office HTML converter should not be called after MathML conversion")+ return "", false+ })+ if useHTML || strings.Contains(resolvedDOM, "data:image") || !strings.Contains(resolvedDOM, "x+y") {+ t.Fatalf("unexpected resolved DOM: useHTML=%v dom=%q", useHTML, resolvedDOM)+ }++ resolvedDOM, useHTML = resolveHTMLClipboardContent(util.NewLute(), htmlWithImage, "", "", "", "",+ func(string, string, string) (string, bool) { return "", false },+ func(string) (string, bool) { return "", false })+ if !useHTML || resolvedDOM != htmlWithImage {+ t.Fatalf("HTML fallback was not preserved: useHTML=%v dom=%q", useHTML, resolvedDOM)+ }+}+func TestConvertClipboardMathMixedWPS(t *testing.T) {wps := buildWPSClipboard(t, `<w:document xmlns:w="urn:w" xmlns:m="urn:m"><w:body><m:oMath/></w:body></w:document>`, "")pandocJSON := `{"pandoc-api-version":[1,23,1,2],"meta":{},"blocks":[{"t":"Para","c":[{"t":"Str","c":"123"}]},{"t":"Para","c":[{"t":"Math","c":[{"t":"DisplayMath"},"\\frac{S}{N}"]}]},{"t":"Para","c":[{"t":"Str","c":"456"}]}]}`diff --git a/kernel/model/import.go b/kernel/model/import.goindex 99b8c24c16..e5ca4bf0dc 100644--- a/kernel/model/import.go+++ b/kernel/model/import.go@@ -99,8 +99,11 @@ func HTML2Tree(htmlStr string, luteEngine *lute.Lute, boxID string) (tree *parsefunc HTML2TreeWithOptions(htmlStr string, luteEngine *lute.Lute, boxID string,options HTML2TreeOptions) (tree *parse.Tree, withMath bool) {htmlStr = gulu.Str.RemovePUA(htmlStr)- assetDirPath := GetImportAssetsDir(boxID, "")- _ = os.MkdirAll(assetDirPath, 0755)+ assetDirPath := ""+ if !options.SkipBase64Assets || !options.SkipInlineSVGAssets {+ assetDirPath = GetImportAssetsDir(boxID, "")+ _ = os.MkdirAll(assetDirPath, 0755)+ }tree = luteEngine.HTML2Tree(htmlStr)ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering {diff --git a/kernel/model/import_test.go b/kernel/model/import_test.goindex 784f263fb1..534b19168d 100644--- a/kernel/model/import_test.go+++ b/kernel/model/import_test.go@@ -174,21 +174,16 @@ func TestHTML2TreeCanSkipEmbeddedAssetWrites(t *testing.T) {boxID := "20260826000000-htmlimg"boxAssetsDir := filepath.Join(util.DataDir, boxID, "assets")- if err := os.MkdirAll(boxAssetsDir, 0755); err != nil {- t.Fatal(err)- }options := HTML2TreeOptions{SkipBase64Assets: true, SkipInlineSVGAssets: true}HTML2TreeWithOptions(`<img alt="diagram" src="data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=">`,util.NewLute(), boxID, options)HTML2TreeWithOptions(`<pre class="language-html"><svg><rect width="1" height="1"></rect></svg></pre>`,util.NewLute(), boxID, options)- entries, err := os.ReadDir(boxAssetsDir)- if err != nil {- t.Fatal(err)- }- if len(entries) != 0 {- t.Fatalf("notebook assets count = %d, want 0", len(entries))+ for _, assetsDir := range []string{boxAssetsDir, filepath.Join(util.DataDir, "assets")} {+ if _, err := os.Stat(assetsDir); !os.IsNotExist(err) {+ t.Fatalf("asset directory was created during non-writing conversion: path=%q err=%v", assetsDir, err)+ }}}