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: Fix beta regression fixtures and keymap filter refresh
Danielba6552daa4b6
diff --git a/app/src/business/openRecentDocs.test.ts b/app/src/business/openRecentDocs.test.tsindex e1ff78d0e2..452d8f550e 100644--- a/app/src/business/openRecentDocs.test.ts+++ b/app/src/business/openRecentDocs.test.ts@@ -3,12 +3,13 @@ import {readFileSync} from "node:fs";import {test} from "node:test";import {runInNewContext} from "node:vm";import {createSourceFile, isArrowFunction, isBlock, isIfStatement, isVariableStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";+const {createMockRequire} = require("../../tests/fixtures/mockModules.cjs");const loadModule = (filename: string, globals: Record<string, unknown>, dependencies: Record<string, unknown> = {}, tail = "") => {const exports: any = {};runInNewContext(transpileModule(readFileSync(filename, "utf8") + tail, {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},- }).outputText, {exports, require: (name: string) => dependencies[name] || {}, ...globals});+ }).outputText, {exports, require: createMockRequire(dependencies), ...globals});return exports;};@@ -49,11 +50,12 @@ const createHarness = () => {const pathRequests: Array<{id: string, resolve: (response: unknown) => void}> = [];const requests: Array<{url: string, data: any, receive: (response: unknown) => void}> = [];const cleanups: string[] = [];+ const patches: unknown[][] = [];let dialogOptions: any;- const constants = {LOCAL_IMAGES: "images", LOCAL_RECENT_DOCS: "recent", DIALOG_RECENTDOCS: "recent-dialog"};+ const constants = {LOCAL_IMAGES: "images", DIALOG_RECENTDOCS: "recent-dialog"};const siyuan = {- config: {fileTree: {useSVGDefaultIcon: true}, keymap: {general: {riffCard: {custom: ""}}}},- storage: {images: {file: "1f4c4"}, recent: {type: "viewedAt"}},+ config: {fileTree: {useSVGDefaultIcon: true, recentDocsSort: "viewedAt"}, keymap: {general: {riffCard: {custom: ""}}}},+ storage: {images: {file: "1f4c4"}},languages: {riffCard: "Cards", recentDocs: "Recent documents"},dialogs: [] as Array<{element: typeof root}>,};@@ -64,6 +66,7 @@ const createHarness = () => {"../constants": {Constants: constants}, "../util/escape": escape, "./iconValue": iconValue,});const api = loadModule("src/business/openRecentDocs.ts", globals, {+ "../config/tabs/fileRuntime": {fileConfigApi: {patch: async (...args: unknown[]) => { patches.push(args); }}},"../util/fetch": {fetchSyncPost: (_url: string, data: {id: string}) => new Promise(resolve => pathRequests.push({id: data.id, resolve})),fetchPost: (url: string, data: unknown, receive: (response: unknown) => void) => requests.push({url, data, receive}),@@ -72,7 +75,9 @@ const createHarness = () => {"../constants": {Constants: constants},"../util/escape": escape,"../util/functions": {isWindow: () => false},- "../protyle/util/compatibility": {updateHotkeyTip: (value: string) => value, setStorageVal() {}},+ "../protyle/util/compatibility": {updateHotkeyTip: (value: string) => value},+ "../protyle/util/hasClosest": {},+ "../protyle/ui/hideElements": {},"../layout/getAll": {getAllDocks: () => [{title: "Documents", type: "files", icon: "iconFiles"}]},"../layout/dock/hotkey": {getDockHotkey: () => ""},"../block/panelOwnership": {destroyDialogBlockPanels: (element: typeof root) => {@@ -88,7 +93,7 @@ const createHarness = () => {}},}, "\nexports.render = renderRecentDocsContent;");const settle = async () => { await new Promise(resolve => setImmediate(resolve)); };- return {api, root, host, path, input, select, siyuan, pathRequests, requests, callbacks, cleanups, settle,+ return {api, root, host, path, input, select, siyuan, pathRequests, requests, callbacks, cleanups, patches, settle,icons: () => icons, dialogOptions: () => dialogOptions};};@@ -157,12 +162,14 @@ test("sort responses cannot restore older preview anchors or update a closing diconst h = createHarness();h.api.openRecentDocs();assert.equal(h.requests[0].url, "/api/storage/getRecentDocs");+ assert.equal(h.requests[0].data.sortBy, "viewedAt");h.requests[0].receive({data: []});assert.equal(h.dialogOptions().destroyCallback, undefined, "Dialog owns guarded focus restoration");h.select.value = "created";h.callbacks.get("select:change")();h.select.value = "closedAt";h.callbacks.get("select:change")();+ assert.deepEqual(h.patches, [["recentDocsSort", "created"], ["recentDocsSort", "closedAt"]]);h.requests[2].receive({data: [{rootID: "latest", title: "Latest"}]});h.requests[1].receive({data: [{rootID: "old", title: "Old"}]});assert.deepEqual(h.pathRequests.map(item => item.id), ["latest"]);diff --git a/app/src/config/tabs/ai/aiRuntime.test.ts b/app/src/config/tabs/ai/aiRuntime.test.tsindex abd4c27e29..1fdf3f4c5c 100644--- a/app/src/config/tabs/ai/aiRuntime.test.ts+++ b/app/src/config/tabs/ai/aiRuntime.test.ts@@ -21,6 +21,9 @@ test("decision connection testing waits for queued AI saves and detects save faiwindow: {siyuan, dispatchEvent: () => true},CustomEvent: class {},require: (name: string) => {+ if (name === "./agentStreamingMarkdown") {+ return {AGENT_STREAMING_MARKDOWN_CHANGED_EVENT: "siyuan-agent-streaming-markdown-changed"};+ }assert.equal(name, "../../util/namespaceApi");return {createConfigNamespaceApi: (options: {namespace: string;diff --git a/app/src/config/tabs/keymapUi.test.ts b/app/src/config/tabs/keymapUi.test.tsindex c5df6f9d8f..4b742382fa 100644--- a/app/src/config/tabs/keymapUi.test.ts+++ b/app/src/config/tabs/keymapUi.test.ts@@ -2,10 +2,10 @@ import * as assert from "node:assert/strict";import {readFileSync} from "node:fs";import {test} from "node:test";import {runInNewContext} from "node:vm";-import {createSourceFile, isClassDeclaration, isMethodDeclaration, isVariableStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";+import {createSourceFile, forEachChild, isClassDeclaration, isMethodDeclaration, isVariableStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";import {CALLOUT_PRESETS} from "../../protyle/wysiwyg/calloutType";-test("editing bindings keeps search results and the active conflict filter until another search", () => {+test("binding refresh hides an empty conflict filter and returns to all bindings", () => {const source = createSourceFile("keymapUi.ts", readFileSync("src/config/tabs/keymapUi.ts", "utf8"), ScriptTarget.ES2021, true);const declaration = source.statements.find(statement => isVariableStatement(statement) &&statement.declarationList.declarations.some(item => item.name.getText(source) === "refreshKeymapBindings"));@@ -20,7 +20,9 @@ test("editing bindings keeps search results and the active conflict filter untilconst filter = {dataset: {keymapFilterValue: "conflict"}, classList: {toggle: (name: string, value: boolean) => hidden.set(name, value),}, setAttribute: () => {}};- const list = {dataset: {keymapFilter: "conflict"}, querySelector: (): undefined => undefined, querySelectorAll: () => [filter]};+ let hasConflict = false;+ const list = {dataset: {keymapFilter: "conflict"}, querySelector: () => hasConflict ? row : undefined,+ querySelectorAll: () => [filter]};const root = {querySelectorAll: () => [row], querySelector: () => list};let searches = 0;const exports = {} as {refresh: (root: unknown) => void};@@ -29,14 +31,70 @@ test("editing bindings keeps search results and the active conflict filter untilgetKeymapItem: () => ({}), searchKeymapList: () => { searches++; },});for (const updated of [[], ["F10"], ["F9"]]) {+ list.dataset.keymapFilter = "conflict";keys = updated;exports.refresh(root);- assert.equal(list.dataset.keymapFilter, "conflict");- assert.equal(hidden.get("fn__none"), false);+ assert.equal(list.dataset.keymapFilter, "all");+ assert.equal(hidden.get("fn__none"), true);assert.equal(row.dataset.conflict, "false");}assert.equal(searches, 0);assert.equal(row.dataset.customized, "false");+ hasConflict = true;+ list.dataset.keymapFilter = "conflict";+ exports.refresh(root);+ assert.equal(list.dataset.keymapFilter, "conflict");+ assert.equal(hidden.get("fn__none"), false);+ hasConflict = false;+ list.dataset.keymapFilter = "customized";+ exports.refresh(root);+ assert.equal(list.dataset.keymapFilter, "customized");+ assert.equal(hidden.get("fn__none"), true);+});++test("editing, deleting and resetting a binding immediately reapplies the current text and shortcut filters", () => {+ const source = createSourceFile("keymapUi.ts", readFileSync("src/config/tabs/keymapUi.ts", "utf8"), ScriptTarget.ES2021, true);+ let declaration: string;+ const visit = (node: import("typescript").Node) => {+ if (isVariableStatement(node) && node.declarationList.declarations.some(item => item.name.getText(source) === "saveRow")) {+ declaration = node.getText(source);+ }+ forEachChild(node, visit);+ };+ visit(source);+ assert.ok(declaration);+ const code = transpileModule(declaration + "\nexports.save = saveRow;", {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText;+ const root = {};+ const list = {dataset: {keymapFilter: "customized"}};+ const search = {value: "Go to tab #5"};+ const shortcut = {dataset: {keymap: "⌘5"}};+ const row = {dataset: {key: "general|test"}};+ const calls: unknown[][] = [];+ const item = {bindings: {priority: 3}};+ const exports = {} as {save: (row: unknown, keys: string[], reset?: boolean) => void};+ runInNewContext(code, {exports, root, keymapListElement: list, searchElement: search, searchKeymapElement: shortcut,+ Constants: {ZWSP: "|"}, getKeymapItem: () => item,+ renderRowBindings: (...args: unknown[]) => calls.push(["render", ...args]),+ saveKeymapRow: (_root: unknown, _row: unknown, keys: string[], change?: (data: unknown) => void) => {+ calls.push(["save", keys]);+ change?.({});+ },+ refreshBindings: () => calls.push(["refresh"]),+ searchKeymapList: (...args: unknown[]) => calls.push(["search", ...args]),+ });+ for (const [keys, reset] of [[["F10"], false], [[], false], [["⌘5"], true]] as [string[], boolean][]) {+ calls.length = 0;+ exports.save(row, keys, reset);+ assert.deepEqual(calls, [["render", row, keys], ["save", keys], ["refresh"],+ ["search", list, "Go to tab #5", "⌘5"]]);+ assert.equal(list.dataset.keymapFilter, "customized");+ }+ assert.equal(item.bindings.priority, undefined);+ delete shortcut.dataset.keymap;+ exports.save(row, ["F11"]);+ assert.deepEqual(calls.at(-1), ["search", list, "Go to tab #5", ""]);});test("callout shortcut rows use localized labels without requiring separate translation keys", () => {@@ -55,6 +113,42 @@ test("callout shortcut rows use localized labels without requiring separate tranassert.equal(exports.label("quote"), "引述块");});+test("a failed binding save reapplies filters after restoring saved bindings", async () => {+ const source = createSourceFile("keymapUi.ts", readFileSync("src/config/tabs/keymapUi.ts", "utf8"), ScriptTarget.ES2021, true);+ const declaration = source.statements.find(statement => isVariableStatement(statement) &&+ statement.declarationList.declarations.some(item => item.name.getText(source) === "saveKeymapRow"));+ assert.ok(declaration);+ const code = transpileModule(declaration.getText(source) + "\nexports.save = saveKeymapRow;", {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText;+ const row = {dataset: {key: "general|test"}, keys: ["F10"]};+ const list = {dataset: {keymapFilter: "customized"}};+ const root = {querySelectorAll: () => [row], querySelector: (selector: string) =>+ selector === "#keymapList" ? list : selector === "#keymapInput" ? {value: "tab"} : {dataset: {keymap: "F9"}}};+ const calls: unknown[][] = [];+ const exports = {} as {save: (root: unknown, row: unknown, keys: string[]) => void};+ const config = {keymap: {test: {keys: ["F9"]}}};+ const context = {exports, Constants: {ZWSP: "|"}, window: {siyuan: {config, languages: {keymapSaveFailed: "failed"}}},+ savedKeymap: undefined as typeof config.keymap | undefined, keymapRevision: 0, keymapSaveQueue: Promise.resolve(),+ getKeymapItem: (data: typeof config.keymap) => data.test,+ getKeymapBindings: (item: {keys: string[]}) => item.keys,+ setKeymapBindings: (item: {keys: string[]}, keys: string[]) => { item.keys = keys; },+ applyKeymap: (data: typeof config.keymap) => { config.keymap = data; },+ keymapRowPatch: () => ({}),+ configApi: {set: async () => { throw new Error("save rejected"); }},+ trackSettingSave: (promise: Promise<void>) => promise,+ renderRowBindings: (element: typeof row, keys: string[]) => { element.keys = keys; },+ refreshKeymapBindings: () => calls.push(["refresh", [...row.keys]]),+ searchKeymapList: (...args: unknown[]) => calls.push(["search", ...args]),+ showMessage: (message: string) => calls.push(["message", message]), console: {error() {}},+ };+ runInNewContext(code, context);+ exports.save(root, row, ["F10"]);+ await context.keymapSaveQueue;+ assert.deepEqual([...row.keys], ["F9"]);+ assert.deepEqual(calls, [["refresh", ["F9"]], ["search", list, "tab", "F9"], ["message", "failed"]]);+});+test("settings keymap search keeps undeclared owner plugins visible", () => {const source = createSourceFile("keymapUi.ts", readFileSync("src/config/tabs/keymapUi.ts", "utf8"), ScriptTarget.ES2021, true);const declarations = source.statements.filter(statement => isVariableStatement(statement) &&@@ -113,6 +207,7 @@ test("keymap refresh retains local search and untouched controls while synchroni};let refreshed = 0;let resets = 0;+ const searches: unknown[][] = [];const exports = {} as {mountKeymapTab: (root: unknown, keywords: undefined, app: undefined, rebuild: boolean) => Promise<void>};runInNewContext(code, {exports, Constants: {ZWSP: "|"},window: {siyuan: {config: {keymap: {first: ["F9"], second: ["F11"]}}}},@@ -122,7 +217,11 @@ test("keymap refresh retains local search and untouched controls while synchronirow.dataset.keys = JSON.stringify(keys);row.controls = {};},- refreshKeymapBindings: () => { refreshed++; },+ refreshKeymapBindings: () => {+ refreshed++;+ if (list.dataset.keymapFilter === "conflict") list.dataset.keymapFilter = "all";+ },+ searchKeymapList: (...args: unknown[]) => searches.push([list.dataset.keymapFilter, ...args]),resetKeymapList: () => { resets++; },});for (let i = 0; i < 2; i++) {@@ -136,6 +235,14 @@ test("keymap refresh retains local search and untouched controls while synchroni}assert.equal(refreshed, 2);assert.equal(resets, 0);+ assert.deepEqual(searches, [+ ["customized", list, "Go to tab #5", "F9"],+ ["customized", list, "Go to tab #5", "F9"],+ ]);+ list.dataset.keymapFilter = "conflict";+ await exports.mountKeymapTab(root, undefined, undefined, true);+ assert.equal(list.dataset.keymapFilter, "all");+ assert.deepEqual(searches.at(-1), ["all", list, "Go to tab #5", "F9"]);await exports.mountKeymapTab(root, undefined, undefined, false);assert.equal(search.value, "");assert.equal(hotkey.value, "");diff --git a/app/src/config/tabs/keymapUi.ts b/app/src/config/tabs/keymapUi.tsindex e36e691613..9ebf0d7897 100644--- a/app/src/config/tabs/keymapUi.ts+++ b/app/src/config/tabs/keymapUi.ts@@ -94,6 +94,9 @@ export const mountKeymapTab = async (root: HTMLElement, keywords?: string, _app?}});refreshKeymapBindings(root);+ searchKeymapList(root.querySelector<HTMLElement>("#keymapList"),+ root.querySelector<HTMLInputElement>("#keymapInput").value,+ root.querySelector<HTMLElement>("#searchByKey").dataset.keymap || "");return;}if (root.innerHTML === "") {@@ -414,6 +417,7 @@ const bindKeymapList = (root: HTMLElement) => {delete getKeymapItem(data, row.dataset.key.split(Constants.ZWSP)).bindings.priority;} : undefined);refreshBindings();+ searchKeymapList(keymapListElement, searchElement.value, searchKeymapElement.dataset.keymap || "");};keymapListElement.addEventListener("pointerdown", (event) => {if (recording && (event.target as HTMLElement).closest(".config-keymap__controls") &&@@ -711,12 +715,15 @@ const refreshKeymapBindings = (root: HTMLElement) => {});const list = root.querySelector<HTMLElement>("#keymapList");const hasConflict = Boolean(list.querySelector('[data-conflict="true"]'));+ if (!hasConflict && list.dataset.keymapFilter === "conflict") {+ list.dataset.keymapFilter = "all";+ }list.querySelectorAll<HTMLElement>("[data-keymap-filter-value]").forEach(button => {const active = button.dataset.keymapFilterValue === list.dataset.keymapFilter;button.classList.toggle("b3-chip--current", active);button.setAttribute("aria-pressed", String(active));if (button.dataset.keymapFilterValue === "conflict") {- button.classList.toggle("fn__none", !hasConflict && !active);+ button.classList.toggle("fn__none", !hasConflict);}});};@@ -754,6 +761,9 @@ const saveKeymapRow = (root: HTMLElement, row: HTMLElement, keys: string[], chanrenderRowBindings(element, getKeymapBindings(getKeymapItem(savedKeymap, element.dataset.key.split(Constants.ZWSP))));});refreshKeymapBindings(root);+ searchKeymapList(root.querySelector<HTMLElement>("#keymapList"),+ root.querySelector<HTMLInputElement>("#keymapInput").value,+ root.querySelector<HTMLElement>("#searchByKey").dataset.keymap || "");showMessage(window.siyuan.languages.keymapSaveFailed);}}));diff --git a/app/src/mobile/util/frequentSlashMenu.test.ts b/app/src/mobile/util/frequentSlashMenu.test.tsindex 730a9dd0ef..859b09718e 100644--- a/app/src/mobile/util/frequentSlashMenu.test.ts+++ b/app/src/mobile/util/frequentSlashMenu.test.ts@@ -85,75 +85,79 @@ test("mobile frequent group clones supported buttons and preserves the original}});-test("full mobile slash panel keeps original hidden items and only prefixes eligible rendered commands", () => {- const filename = path.join(__dirname, "keyboardToolbar.ts");- const file = createSourceFile(filename, readFileSync(filename, "utf8"), ScriptTarget.Latest, true);- const source = file.statements.filter(statement => isVariableStatement(statement) &&- statement.declarationList.declarations.some(declaration =>- ["getSlashItem", "renderSlashMenu"].includes(declaration.name.getText(file))))- .map(statement => statement.getText(file)).join("\n");- let mounted = 0;- let boundUploads = 0;- let eligibilityCalls = 0;- let frequentButtons: HTMLButtonElement[] = [];- const util = {- innerHTML: "",- querySelectorAll: () => Array.from(util.innerHTML.matchAll(/<button[^>]+data-slash-entry-key="([^"]+)"[^>]*>/g),- match => new Button(match[1])),- };- const root = {querySelector: () => util};- const protyle = {- lite: false,- app: {plugins: [] as unknown[]},- hint: {splitChar: "", lastIndex: 0, bindUploadEvent: () => boundUploads++},- options: {upload: {}},- };- const environment = {- Constants: {ZWSP: "\u200b", CUSTOM_SY_LIST_MINDMAP: "custom-sy-list-mindmap"},- Lute: {Caret: "caret"},- window: {siyuan: {languages: {}}},- SLASH_MENU_ROOT_PATH: "editor.slash.menu",- getHostCapabilities: () => ({widgets: false, remoteKernel: true}),- isDisabledFeature: () => true,- isInAndroid: () => false,- isBuiltinInlineStyleVisible: () => false,- getSuperBlockCommand: (layout: string) => layout,- escapeHtml: (value: string) => value,- getFrequentSlashButtons,- getFrequentSlashItems: (buttons: HTMLButtonElement[], getKey: (button: HTMLButtonElement) => string) =>- rankFrequentSlashItems(buttons, getKey, {heading1: 100, code: 1, insertHTMLFile: 99}),- hintSlash: (key: string, editor: unknown, hideConfiguredCreate: boolean, options: {visibilityRoot: string}) => {- eligibilityCalls++;- assert.equal(key, "");- assert.equal(editor, protyle);- assert.equal(hideConfiguredCreate, false);- assert.equal(options.visibilityRoot, "editor.slash.menu");- return [{entryKey: "code", html: "Code"}, {entryKey: "insertHTMLFile", html: "HTML upload"},- {entryKey: "separator_1", html: "separator"}];- },- prependFrequentSlashButtons: (_container: unknown, buttons: HTMLButtonElement[]) => frequentButtons = buttons,- mountLiteSlashMenu: () => { mounted++; },- };- const render = new Function("environment", "const {" + Object.keys(environment).join(",") +- "} = environment; let unmountLiteSlashMenu; " + transpileModule(source,- {compilerOptions: {target: ScriptTarget.ES2021}}).outputText + "\nreturn renderSlashMenu;")(environment) as- (editor: unknown, toolbar: unknown) => void;- render(protyle, root);- assert.equal(eligibilityCalls, 1);- assert.deepEqual(frequentButtons.map(button => button.dataset.slashEntryKey), ["code"]);- assert.equal((util.innerHTML.match(/data-slash-entry-key="heading1"/g) || []).length, 1);- assert.equal((util.innerHTML.match(/data-slash-entry-key="code"/g) || []).length, 1);- assert.equal((util.innerHTML.match(/data-slash-entry-key="insertAsset"/g) || []).length, 1);- assert.equal((util.innerHTML.match(/data-slash-entry-key="insertHTMLFile"/g) || []).length, 0);- assert.equal(boundUploads, 1);- assert.equal(protyle.hint.splitChar, "/");- assert.equal(protyle.hint.lastIndex, -1);- protyle.lite = true;- render(protyle, root);- assert.equal(mounted, 1);- assert.equal(eligibilityCalls, 1);- assert.equal(boundUploads, 1);-});+for (const iosPhotos of [false, true]) {+ test(`full mobile slash panel preserves eligible commands with iOS photos ${iosPhotos}`, () => {+ const filename = path.join(__dirname, "keyboardToolbar.ts");+ const file = createSourceFile(filename, readFileSync(filename, "utf8"), ScriptTarget.Latest, true);+ const source = file.statements.filter(statement => isVariableStatement(statement) &&+ statement.declarationList.declarations.some(declaration =>+ ["getSlashItem", "renderSlashMenu"].includes(declaration.name.getText(file))))+ .map(statement => statement.getText(file)).join("\n");+ let mounted = 0;+ let boundUploads = 0;+ let eligibilityCalls = 0;+ let frequentButtons: HTMLButtonElement[] = [];+ const util = {+ innerHTML: "",+ querySelectorAll: () => Array.from(util.innerHTML.matchAll(/<button[^>]+data-slash-entry-key="([^"]+)"[^>]*>/g),+ match => new Button(match[1])),+ };+ const root = {querySelector: () => util};+ const protyle = {+ lite: false,+ app: {plugins: [] as unknown[]},+ hint: {splitChar: "", lastIndex: 0, bindUploadEvent: () => boundUploads++},+ options: {upload: {}},+ };+ const environment = {+ Constants: {ZWSP: "\u200b", CUSTOM_SY_LIST_MINDMAP: "custom-sy-list-mindmap"},+ Lute: {Caret: "caret"},+ window: {siyuan: {languages: {}}},+ SLASH_MENU_ROOT_PATH: "editor.slash.menu",+ getHostCapabilities: () => ({widgets: false, remoteKernel: true}),+ isDisabledFeature: () => true,+ isInAndroid: () => false,+ canPickIOSPhotos: () => iosPhotos,+ isBuiltinInlineStyleVisible: () => false,+ getSuperBlockCommand: (layout: string) => layout,+ escapeHtml: (value: string) => value,+ getFrequentSlashButtons,+ getFrequentSlashItems: (buttons: HTMLButtonElement[], getKey: (button: HTMLButtonElement) => string) =>+ rankFrequentSlashItems(buttons, getKey, {heading1: 100, code: 1, insertHTMLFile: 99}),+ hintSlash: (key: string, editor: unknown, hideConfiguredCreate: boolean, options: {visibilityRoot: string}) => {+ eligibilityCalls++;+ assert.equal(key, "");+ assert.equal(editor, protyle);+ assert.equal(hideConfiguredCreate, false);+ assert.equal(options.visibilityRoot, "editor.slash.menu");+ return [{entryKey: "code", html: "Code"}, {entryKey: "insertHTMLFile", html: "HTML upload"},+ {entryKey: "separator_1", html: "separator"}];+ },+ prependFrequentSlashButtons: (_container: unknown, buttons: HTMLButtonElement[]) => frequentButtons = buttons,+ mountLiteSlashMenu: () => { mounted++; },+ };+ const render = new Function("environment", "const {" + Object.keys(environment).join(",") ++ "} = environment; let unmountLiteSlashMenu; " + transpileModule(source,+ {compilerOptions: {target: ScriptTarget.ES2021}}).outputText + "\nreturn renderSlashMenu;")(environment) as+ (editor: unknown, toolbar: unknown) => void;+ render(protyle, root);+ assert.equal(eligibilityCalls, 1);+ assert.deepEqual(frequentButtons.map(button => button.dataset.slashEntryKey), ["code"]);+ assert.equal((util.innerHTML.match(/data-slash-entry-key="heading1"/g) || []).length, 1);+ assert.equal((util.innerHTML.match(/data-slash-entry-key="code"/g) || []).length, 1);+ assert.equal((util.innerHTML.match(/data-slash-entry-key="insertAsset"/g) || []).length, iosPhotos ? 2 : 1);+ assert.equal(util.innerHTML.includes('data-native-photos="true"'), iosPhotos);+ assert.equal((util.innerHTML.match(/data-slash-entry-key="insertHTMLFile"/g) || []).length, 0);+ assert.equal(boundUploads, 1);+ assert.equal(protyle.hint.splitChar, "/");+ assert.equal(protyle.hint.lastIndex, -1);+ protyle.lite = true;+ render(protyle, root);+ assert.equal(mounted, 1);+ assert.equal(eligibilityCalls, 1);+ assert.equal(boundUploads, 1);+ });+}const chromium = process.env.CHROMIUM_PATH;diff --git a/app/src/mobile/util/sidebarSwipe.test.ts b/app/src/mobile/util/sidebarSwipe.test.tsindex b542f69249..15cba084c2 100644--- a/app/src/mobile/util/sidebarSwipe.test.ts+++ b/app/src/mobile/util/sidebarSwipe.test.ts@@ -6,6 +6,7 @@ import {runInNewContext} from "node:vm";import {ModuleKind, transpileModule} from "typescript";import * as gestures from "./touchPanelGesture";import {getTouchAxis} from "./touchGesture";+const {createMockRequire} = require("../../../tests/fixtures/mockModules.cjs");const loadModule = (name: string, globals: Record<string, unknown>) => {const exports: Record<string, (...args: unknown[]) => void> = {};@@ -46,7 +47,8 @@ test("sidebar cycling follows visible tab order and dispatches plugin activation},};const sidebar = loadModule("sidebar", {- require: () => ({}),+ require: createMockRequire({"./keyboardToolbar": {}, "./closePanel": {},+ "../../protyle/render/av/cellEditor": {}}),document: {getElementById: () => ({querySelector: () => toolbar})},CustomEvent: class {detail: string;@@ -69,7 +71,7 @@ test("sidebar cycling follows visible tab order and dispatches plugin activation});const createTouchHarness = (side: "left" | "right", options: {- scrollable?: boolean, disabled?: boolean, closed?: boolean,+ scrollable?: boolean, disabled?: boolean, closed?: boolean, iosDevice?: boolean,editorSelection?: "editor" | "outside",} = {}) => {const actions: string[] = [];@@ -124,14 +126,21 @@ const createTouchHarness = (side: "left" | "right", options: {},"./closePanel": {closePanel: () => actions.push("close"), showPanelMask: () => {}},"./keyboardToolbar": {activeBlur: (force: boolean) => { forcedBlur = force; }, resetAndroidBoundedSelectionGesture: () => {}},- "../../protyle/util/compatibility": {isInHarmony: () => false, isInAndroid: () => false, isIPhone: () => false},+ "../../protyle/util/compatibility": {isInHarmony: () => false, isInAndroid: () => false,+ isIPhone: () => false, isIOSDevice: () => options.iosDevice === true},+ "../../protyle/wysiwyg/nativeTextMenu": {usesNativeTextMenu: () => false},+ "../../protyle/util/selection": {},+ "../../protyle/wysiwyg/getBlock": {},+ "../menu/model": {},+ "./blockSelection": {},+ "./multiSelectToolbar": {},"../editor": {getCurrentEditor: () => options.editorSelection ? editor : undefined},"./touchSelection": {hasVisibleSelectionText: () => false},"../../protyle/util/inlineElementMarker": {stripSemanticMarkersFromRangeText: () => ""},"../../constants": {Constants: {SIZE_DRAG_THRESHOLD: 5, TIMEOUT_LONGPRESS: 500, TIMEOUT_MULTIPLE_SELECT: 500}},};const touch = loadModule("touch", {- require: (name: string) => modules[name] || {},+ require: createMockRequire(modules),document: {activeElement,querySelector: (selector: string) => selector === ".side-mask" ? mask : {classList: classList("fn__none")},@@ -166,36 +175,38 @@ const createTouchHarness = (side: "left" | "right", options: {for (const side of ["left", "right"] as const) {const nextX = side === "left" ? 240 : 120;const closeX = side === "left" ? 120 : 240;- test(`${side} sidebar clears the native editor caret at gesture takeover and saves its position`, () => {- const harness = createTouchHarness(side, {closed: true, editorSelection: "editor"});- harness.start();- assert.equal(harness.move(185).defaultPrevented, false);- assert.equal(harness.selection.rangeCount, 1);- assert.equal(harness.move(nextX).defaultPrevented, true);- assert.equal(harness.selection.rangeCount, 0);- assert.equal(harness.blurred(), 1);- assert.equal(harness.forcedBlur(), true);- assert.deepEqual(harness.mobile.touchRange, harness.range);- assert.notEqual(harness.mobile.touchRange, harness.range);- harness.move(nextX);- assert.equal(harness.blurred(), 1);- harness.end(nextX);- assert.deepEqual(harness.actions, [`open:${side}`]);- assert.equal(harness.selection.rangeCount, 0);- });+ for (const iosDevice of [false, true]) {+ test(`${side} sidebar saves and clears the native editor caret with iOS ${iosDevice}`, () => {+ const harness = createTouchHarness(side, {closed: true, editorSelection: "editor", iosDevice});+ harness.start();+ assert.equal(harness.move(185).defaultPrevented, false);+ assert.equal(harness.selection.rangeCount, 1);+ assert.equal(harness.move(nextX).defaultPrevented, true);+ assert.equal(harness.selection.rangeCount, 0);+ assert.equal(harness.blurred(), 1);+ assert.equal(harness.forcedBlur(), true);+ assert.deepEqual(harness.mobile.touchRange, harness.range);+ assert.notEqual(harness.mobile.touchRange, harness.range);+ harness.move(nextX);+ assert.equal(harness.blurred(), 1);+ harness.end(nextX);+ assert.deepEqual(harness.actions, [`open:${side}`]);+ assert.equal(harness.selection.rangeCount, 0);+ });- test(`${side} sidebar preserves unrelated selections and ordinary vertical gestures`, () => {- const outside = createTouchHarness(side, {closed: true, editorSelection: "outside"});- outside.start();- outside.move(nextX);- assert.equal(outside.selection.rangeCount, 1);- assert.equal(outside.mobile.touchRange, undefined);- const vertical = createTouchHarness(side, {closed: true, editorSelection: "editor"});- vertical.start();- assert.equal(vertical.move(185, 240).defaultPrevented, false);- assert.equal(vertical.selection.rangeCount, 1);- assert.equal(vertical.blurred(), 0);- });+ test(`${side} sidebar preserves unrelated selections and vertical gestures with iOS ${iosDevice}`, () => {+ const outside = createTouchHarness(side, {closed: true, editorSelection: "outside", iosDevice});+ outside.start();+ outside.move(nextX);+ assert.equal(outside.selection.rangeCount, 1);+ assert.equal(outside.mobile.touchRange, undefined);+ const vertical = createTouchHarness(side, {closed: true, editorSelection: "editor", iosDevice});+ vertical.start();+ assert.equal(vertical.move(185, 240).defaultPrevented, false);+ assert.equal(vertical.selection.rangeCount, 1);+ assert.equal(vertical.blurred(), 0);+ });+ }test(`${side} sidebar does not reuse a gesture consumed by editor block selection`, () => {const harness = createTouchHarness(side, {closed: true});diff --git a/app/src/protyle/preview/plantumlInteraction.test.ts b/app/src/protyle/preview/plantumlInteraction.test.tsindex 3af388a6d2..b1c620cd15 100644--- a/app/src/protyle/preview/plantumlInteraction.test.ts+++ b/app/src/protyle/preview/plantumlInteraction.test.ts@@ -3,6 +3,7 @@ import {readFileSync} from "node:fs";import {test} from "node:test";import {runInNewContext} from "node:vm";import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+const {createMockRequire} = require("../../../tests/fixtures/mockModules.cjs");test("reading mode opens PlantUML only on double click and keeps ordinary image clicks", () => {const compiled = transpileModule(readFileSync("src/protyle/preview/index.ts", "utf8"), {@@ -10,16 +11,25 @@ test("reading mode opens PlantUML only on double click and keeps ordinary image}).outputText;const elements: Array<{listeners: Record<string, (event: unknown) => void>}> = [];let diagramPreviews = 0;- let imagePreviews = 0;+ const imagePreviews: unknown[][] = [];const diagram = {getAttribute: () => "plantuml"};const exports = {} as {Preview: new (protyle: unknown) => unknown};runInNewContext(compiled, {exports,- require: () => ({- getDiagramBlock: (element: unknown) => element,- previewDiagram: (element: unknown) => { assert.equal(element, diagram); diagramPreviews++; },- previewDocImage: () => { imagePreviews++; },- hasTopClosestByAttribute: (): false => false,+ require: createMockRequire({+ ...Object.fromEntries(["../util/compatibility", "../util/selectionOffsets", "../../editor/openLink",+ "../../dialog/message", "../../util/needSubscribe", "../util/richClipboard", "../../layout/getAll",+ "../../util/fetch", "../util/processCode", "../render/tabsRender", "../render/highlightRender",+ "../render/speechRender", "../render/av/render", "../ui/initUI", "./platformCopy", "./wechatMath",+ "../../util/hostCapabilities", "../render/autoDirection"].map(name => [name, {}])),+ "./diagram": {+ getDiagramBlock: (element: unknown) => element,+ previewDiagram: (element: unknown) => { assert.equal(element, diagram); diagramPreviews++; },+ },+ "./image": {previewDocImage: (...args: unknown[]) => { imagePreviews.push(args); }},+ "../util/hasClosest": {hasTopClosestByAttribute: (): false => false},+ "../../constants": {Constants: {CUSTOM_SY_LIVE_PHOTO: "custom-sy-live-photo",+ CUSTOM_SY_LIVE_PHOTO_VIDEO: "custom-sy-live-photo-video"}},}),document: {addEventListener: () => {},@@ -36,19 +46,25 @@ test("reading mode opens PlantUML only on double click and keeps ordinary image});new exports.Preview({options: {classes: {}, preview: {actions: []}}, block: {rootID: "doc"}});const event = {- target: {tagName: "IMG", closest: () => diagram, isEqualNode: () => false, getAttribute: () => "diagram.svg"},+ target: {tagName: "IMG", closest: () => diagram, isEqualNode: () => false,+ getAttribute: (name: string) => name === "src" ? "diagram.svg" : null},preventDefault: () => {},stopPropagation: () => {},};elements[0].listeners.click(event);elements[0].listeners.click(event);assert.equal(diagramPreviews, 0);- assert.equal(imagePreviews, 0);+ assert.equal(imagePreviews.length, 0);elements[0].listeners.dblclick(event);assert.equal(diagramPreviews, 1);const ordinaryImage = {...event, target: {...event.target, closest: (): null => null}};elements[0].listeners.click(ordinaryImage);- assert.equal(imagePreviews, 1);+ assert.deepEqual(imagePreviews, [["diagram.svg", "doc", ""]]);elements[0].listeners.dblclick(ordinaryImage);assert.equal(diagramPreviews, 1);+ const livePhoto = {...ordinaryImage, target: {...ordinaryImage.target, getAttribute: (name: string) => ({+ src: "photo.heic", "custom-sy-live-photo": "1", "custom-sy-live-photo-video": "photo.mov",+ })[name] || null}};+ elements[0].listeners.click(livePhoto);+ assert.deepEqual(imagePreviews.at(-1), ["photo.heic", "doc", "photo.mov"]);});diff --git a/app/src/protyle/wysiwyg/tabsList.test.ts b/app/src/protyle/wysiwyg/tabsList.test.tsindex 974777fd12..c9aeae1c74 100644--- a/app/src/protyle/wysiwyg/tabsList.test.ts+++ b/app/src/protyle/wysiwyg/tabsList.test.ts@@ -1,18 +1,22 @@import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+const {createMockRequire} = require("../../../tests/fixtures/mockModules.cjs");-const buildGlobals = ["SIYUAN_VERSION", "NODE_ENV"].map(name => ({- name, descriptor: Object.getOwnPropertyDescriptor(globalThis, name),-}));-buildGlobals.forEach(({name}) => Object.defineProperty(globalThis, name, {configurable: true, value: "test"}));-const {isEmptyTabPlaceholder}: typeof import("./tabsList") = require("./tabsList");-buildGlobals.forEach(({name, descriptor}) => {- if (descriptor) {- Object.defineProperty(globalThis, name, descriptor);- } else {- Reflect.deleteProperty(globalThis, name);- }+const api = {} as typeof import("./tabsList");+runInNewContext(transpileModule(readFileSync("src/protyle/wysiwyg/tabsList.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText, {+ exports: api,+ require: createMockRequire({+ "../render/tabsRender": {},+ "../render/listMindmap/model": {},+ "../render/listMindmap/preferences": {},+ }),});+const {isEmptyTabPlaceholder} = api;const paragraph = (attrs: Record<string, string>, text = "", rich = false) => ({attributes: Object.entries(attrs).map(([name, value]) => ({name, value})),diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex b1843465d8..0d90da95fa 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -680,7 +680,7 @@ export type BatchUpdateBlockRequestInput = { "blocks": Array<UpdateBlockRequestIexport type BatchUpdatePackageRequestInput = { "frontend": string; };-export type BazaarAppearance = { "bodyGradient": BazaarBodyGradient | null; "closeButtonBehavior": number; "codeBlockThemeDark": string; "codeBlockThemeLight": string; "darkThemes": Array<BazaarAppearanceTheme | null> | null; "entryVisibility": BazaarEntryVisibility | null; "globalFontFamilies": Array<BazaarEditorFont | null> | null; "hideStatusBar": boolean; "hideToolbar": boolean; "icon": string; "iconVer": string; "icons": Array<BazaarAppearanceIcon | null> | null; "lang": string; "lightThemes": Array<BazaarAppearanceTheme | null> | null; "mode": number; "modeOS": boolean; "notifications": BazaarNotifications | null; "statusBar": BazaarStatusBar | null; "themeDark": string; "themeJS": boolean; "themeLight": string; "themeVer": string; };+export type BazaarAppearance = { "bodyGradient": BazaarBodyGradient | null; "closeButtonBehavior": number; "codeBlockThemeDark": string; "codeBlockThemeLight": string; "compactMode": boolean; "darkThemes": Array<BazaarAppearanceTheme | null> | null; "entryVisibility": BazaarEntryVisibility | null; "globalFontFamilies": Array<BazaarEditorFont | null> | null; "hideStatusBar": boolean; "hideToolbar": boolean; "icon": string; "iconVer": string; "icons": Array<BazaarAppearanceIcon | null> | null; "lang": string; "lightThemes": Array<BazaarAppearanceTheme | null> | null; "menuMouseScroll": boolean; "mobileBars": BazaarMobileBars | null; "mode": number; "modeOS": boolean; "notifications": BazaarNotifications | null; "outlineKeepCurrentExpand": boolean; "pdfTheme": BazaarPDFTheme | null; "statusBar": BazaarStatusBar | null; "themeDark": string; "themeJS": boolean; "themeLight": string; "themeVer": string; };export type BazaarAppearanceIcon = { "label": string; "name": string; };@@ -708,8 +708,12 @@ export type BazaarLocalInstallError = { "minAppVersion": string; "packageName":export type BazaarLocalInstallResult = (BazaarLocalInstallData & { "reason"?: never; }) | (BazaarLocalInstallError & { "updated"?: never; });+export type BazaarMobileBars = { "autoHide": boolean | null; "sidebarButtons": boolean | null; "sidebarSwipe": boolean | null; };+export type BazaarNotifications = { "browserCompatibility": boolean; "docTreeMaxList": boolean; "formatPainterTip"?: boolean; "selectAllIncompleteTip"?: boolean; "selectAllTip"?: boolean; "tagMaxList": boolean; "workspaceNotSSD": boolean; };+export type BazaarPDFTheme = { "annoColor": string; "dark": string; "light": string; };+export type BazaarPackage = { "author": string; "backends": Array<string> | null; "bazaarIncompatible"?: boolean; "bootAppearances"?: Array<string>; "choices"?: Array<BazaarPackageChoice>; "current": boolean; "deprecated"?: boolean; "deprecatedReason"?: Record<string, string>; "description": Record<string, string> | null; "disabledInPublish": boolean; "disallowInstall": boolean; "disallowUpdate": boolean; "displayName": Record<string, string> | null; "downloads": number; "enabled"?: boolean; "frontends": Array<string> | null; "funding": BazaarFunding | null; "hInstallDate": string; "hInstallSize": string; "hSize": string; "hUpdated": string; "hasStorageData"?: boolean; "icon"?: string; "iconURL": string; "installSize": number; "installTime": number; "installed": boolean; "installedIncompatible"?: boolean; "invalidReason"?: "missing-manifest" | "invalid-manifest" | "name-mismatch"; "kernels": Array<string> | null; "keywords": Array<string> | null; "minAppVersion": string; "modes"?: Array<string> | null; "name": string; "openIssues": number; "outdated": boolean; "preferredDeprecatedReason"?: string; "preferredDesc": string; "preferredFunding": string; "preferredName": string; "preferredReadme": string; "preview"?: string; "previewURL": string; "rating"?: BazaarPackageRating; "ratingAvailable": boolean; "readme": Record<string, string> | null; "repoHash": string; "repoRef"?: string; "repoURL": string; "settingsWindow"?: boolean; "size": number; "stars": number; "updateRequiredMinAppVer"?: string; "updateTime": number; "updated": string; "url": string; "userDisabledInPublish"?: boolean; "version": string; };export type BazaarPackageChoice = { "name": string; "packageType": string; };diff --git a/app/tests/api-contract.types.ts b/app/tests/api-contract.types.tsindex b375bf9a50..2b9b5ad338 100644--- a/app/tests/api-contract.types.ts+++ b/app/tests/api-contract.types.ts@@ -205,6 +205,28 @@ fetchPost("/api/bazaar/setBazaarPackageRating", {packageType: "plugin", packageNfetchPost("/api/bazaar/getBazaarPackageRatings", {packageType: "plugin", packageNames: [1]});fetchPost("/api/bazaar/installLocalBazaarPackage", new ContractFormData({file: new Blob(), overwrite: "true"}));+declare const bazaarAppearanceResponse: APIPOSTRoutes[+ "/api/bazaar/installBazaarIcon" | "/api/bazaar/uninstallBazaarIcon" |+ "/api/bazaar/installBazaarTheme" | "/api/bazaar/uninstallBazaarTheme"+]["response"];+if (bazaarAppearanceResponse.code === 0 && bazaarAppearanceResponse.data.appearance) {+ const appearance = bazaarAppearanceResponse.data.appearance;+ const compactMode: boolean = appearance.compactMode;+ const menuMouseScroll: boolean = appearance.menuMouseScroll;+ const outlineKeepCurrentExpand: boolean = appearance.outlineKeepCurrentExpand;+ const pdfTheme: {light: string; dark: string; annoColor: string} | null = appearance.pdfTheme;+ const mobileBars: {autoHide: boolean | null; sidebarSwipe: boolean | null; sidebarButtons: boolean | null} | null = appearance.mobileBars;+ void [compactMode, menuMouseScroll, outlineKeepCurrentExpand, pdfTheme, mobileBars];+ // @ts-expect-error Appearance preferences retain boolean response types.+ const numericCompactMode: number = appearance.compactMode;+ void numericCompactMode;+ if (appearance.mobileBars) {+ // @ts-expect-error Unset mobile preferences remain nullable in responses.+ const autoHide: boolean = appearance.mobileBars.autoHide;+ void autoHide;+ }+}+type RPCWebSocket = APIGETRoutes["/ws/plugin/rpc"]["websocket"];const rpcCall: RPCWebSocket["incoming"] = {jsonrpc: "2.0", method: "call", id: 1};const rpcNotice: RPCWebSocket["outgoing"] = {jsonrpc: "2.0", method: "event", params: null};diff --git a/app/tests/assetPreview.test.js b/app/tests/assetPreview.test.jsindex 9c512c67ba..83aaef978b 100644--- a/app/tests/assetPreview.test.js+++ b/app/tests/assetPreview.test.js@@ -34,7 +34,10 @@ const runCases = async source => {const check = require("node:assert/strict");const load = (code, modules = {}) => {const exports = {};- new Function("require", "exports", code)(name => modules[name] || {}, exports);+ new Function("require", "exports", code)(name => {+ check.ok(Object.hasOwn(modules, name), "Unexpected asset preview fixture module: " + name);+ return modules[name];+ }, exports);return exports;};const settle = () => new Promise(resolve => setTimeout(resolve, 10));@@ -43,27 +46,33 @@ const runCases = async source => {const promise = new Promise(done => { resolve = done; });return {promise, resolve};};- const Constants = {SIYUAN_ASSETS_IMAGE: [".png"], SIYUAN_ASSETS_AUDIO: [".mp3"], SIYUAN_ASSETS_VIDEO: [".mp4"],- LOCAL_PDFTHEME: "pdfTheme"};+ const Constants = {SIYUAN_ASSETS_IMAGE: [".png"], SIYUAN_ASSETS_AUDIO: [".mp3"], SIYUAN_ASSETS_VIDEO: [".mp4"]};let mobile = false;- window.siyuan = {languages: source.languages, config: {appearance: {mode: 0}, editor: {}},- storage: {pdfTheme: {light: "light", dark: "dark"}}};+ window.siyuan = {languages: source.languages, config: {+ appearance: {mode: 0, pdfTheme: {light: "light", dark: "dark"}}, editor: {}, readonly: false,+ }, storage: {}};+ const themePatches = [];const viewerTemplate = load(source.viewerTemplate, {"../../protyle/util/compatibility": {updateHotkeyTip: value => value},});const pdfTheme = load(source.pdfTheme, {- "../constants": {Constants}, "../protyle/util/compatibility": {setStorageVal: () => {}},+ "../constants": {Constants},+ "../config/tabs/appearancePreferences": {patchAppearancePreference: async (key, value) => {+ themePatches.push([key, value]);+ }},});const highlight = load(source.highlight, {"../util/addScript": {addScript: () => Promise.resolve()},"../../constants": {Constants}, "./util": {setCodeTheme() {}},"./foldedContent": {isFoldedRenderContent: () => false},+ "../util/selectionOffsets": {}, "../wysiwyg/getBlock": {}, "../../util/escape": {},});const pathName = {getAssetExtension: value => require("node:path").extname(value.split(/[?#]/)[0])};const previewPath = load(source.previewPath);const escape = load(source.escape);const media = load(source.media, {"../constants": {Constants}, "../util/pathName": pathName,- "../util/escape": escape, "./previewPath": previewPath});+ "../util/escape": escape, "./previewPath": previewPath,+ "../layout/getAll": {}, dayjs: {}, "./html": {}, "../util/imageURL": {}});const pdfCalls = [];let destroyed = 0;let loaded = 0;@@ -171,15 +180,27 @@ const runCases = async source => {}check.equal(destroyed, 2);const themed = document.createElement("div");- themed.innerHTML = viewerTemplate.getPdfViewerHTML();for (const mode of [0, 1]) {+ themed.innerHTML = viewerTemplate.getPdfViewerHTML();window.siyuan.config.appearance.mode = mode;pdfTheme.bindPdfTheme(themed);check.equal(themed.firstElementChild.classList.contains("pdf__outer--dark"), mode === 1);+ themed.querySelector(mode === 0 ? "#pdfDark" : "#pdfLight").click();+ check.equal(themed.firstElementChild.classList.contains("pdf__outer--dark"), mode === 0);}- themed.querySelector("#pdfLight").click();- check.equal(window.siyuan.storage.pdfTheme.dark, "light");+ check.deepEqual(themePatches, [["pdfTheme.light", "dark"], ["pdfTheme.dark", "light"]]);+ check.equal(window.siyuan.config.appearance.pdfTheme.light, "light");+ check.equal(window.siyuan.config.appearance.pdfTheme.dark, "dark", "theme changes await confirmed configuration");check.equal(themed.firstElementChild.classList.contains("pdf__outer--dark"), false);+ for (const protectedMode of ["readonly", "publish"]) {+ window.siyuan.config.readonly = protectedMode === "readonly";+ window.siyuan.isPublish = protectedMode === "publish";+ themed.querySelector("#pdfDark").click();+ check.equal(themePatches.length, 2);+ check.equal(themed.firstElementChild.classList.contains("pdf__outer--dark"), false);+ }+ window.siyuan.config.readonly = false;+ window.siyuan.isPublish = false;const read = async response => {window.fetch = async (_url, options) => {@@ -211,6 +232,7 @@ const runCases = async source => {let model;const mobileAPI = load(source.mobilePDF, {+ "../dialog/message": {}, "../util/fetch": {},"../util/escape": escape,"../asset/pdf/viewerTemplate": viewerTemplate,"../util/pathName": {getDisplayName: value => value, getAssetPathWithoutQuery: value => value.split("?")[0]},@@ -242,7 +264,9 @@ const runCases = async source => {"../util/functions": {isMobile: () => mobile, isBrowser: () => true},"../util/hostCapabilities": {getHostCapabilities: () => ({localFileSystem: false})},"../protyle/util/hasClosest": {hasClosestByClassName: (element, name) => element.closest("." + name)},- "./ocr": {mountOCRSettings: () => () => {}},+ ...Object.fromEntries(["./setting/maintenance", "../dialog/confirmDialog", "../util/fetchAppId",+ "../layout/getAll", "path", "../editor/util", "../protyle/util/compatibility", "../dialog/message",+ "../protyle/util/lute", "./setting/mount", "../mobile/editor", "../block/Panel"].map(name => [name, {}])),"../protyle": {Protyle: class {constructor(_app, element) { this.protyle = {element}; }destroy() {}@@ -347,6 +371,7 @@ const runCases = async source => {};const viewerAPI = load(source.viewer, {"./ui_utils.js": {RenderingStates: {}, ScrollMode: {}, SpreadMode: {}, TextLayerMode: {}},+ "./renderable_view.js": {},"./app_options.js": {AppOptions: {set() {}}},"./pdf_link_service.js": {LinkTarget: {}},"./app.js": {PDFViewerApplication: application},@@ -373,11 +398,18 @@ const runCases = async source => {const runtime = load(source.annotationRuntime);const annotationRequests = [];const anno = load(source.annotations, {+ ...Object.fromEntries(["../util/setPosition", "../protyle/util/hasClosest", "../protyle/util/compatibility",+ "../config/tabs/appearancePreferences", "../protyle/util/selectionOffsets", "../constants", "../dialog",+ "../dialog/message", "../util/functions", "../dialog/confirmDialog", "../util/escape", "filesize",+ "blueimp-md5", "./rectAnnotationResize", "./pdfRectCapture", "../protyle/upload",+ "../protyle/upload/uploadResult", "../editor/pdfAssetLink", "./pdfTextAnnotation", "./pdfCoordinates",+ "./pdfSelectionText"].map(name => [name, {}])),"./annoRuntime": runtime,"../layout/getAll": {getAllModels: () => ({asset: []})},"../util/fetch": {fetchPost: (...args) => annotationRequests.push(args)},});const {TextLayerBuilder} = load(source.textLayer, {+ "./ui_utils.js": {},"../anno": anno,"./pdfjs": {TextLayer: class {textDivs = [];diff --git a/app/tests/automationPanel.test.js b/app/tests/automationPanel.test.jsindex ef80a31d66..65fdf3daa3 100644--- a/app/tests/automationPanel.test.js+++ b/app/tests/automationPanel.test.js@@ -7,6 +7,15 @@ const runCases = async (sources, css, mobile) => {const assert = require("node:assert/strict");const path = require("node:path").posix;const tick = () => new Promise(resolve => setTimeout(resolve, 30));+ const waitForDialogLayout = async dialog => {+ const container = dialog.element.querySelector(".b3-dialog__container");+ for (let attempt = 0; !dialog.element.classList.contains("b3-dialog--open") && attempt < 100; attempt++) {+ await tick();+ }+ assert.equal(dialog.element.classList.contains("b3-dialog--open"), true, "the dialog has opened before measuring its layout");+ await Promise.all(container.getAnimations().map(animation => animation.finished));+ assert.equal(getComputedStyle(container).transform, "none", "the dialog opening animation has finished");+ };document.head.innerHTML = "";document.body.innerHTML = '<div class="av__panel"><div class="b3-menu"></div></div>';document.body.className = "body--windows";@@ -190,7 +199,8 @@ const runCases = async (sources, css, mobile) => {const nameRect = get('[data-action="rules"]').getBoundingClientRect();const enabledRect = get("[data-enabled]").getBoundingClientRect();assert.ok(Math.abs((nameRect.top + nameRect.bottom) / 2 - (enabledRect.top + enabledRect.bottom) / 2) <= 1,- "the enable switch aligns with the rule name");+ `the enable switch aligns with the rule name: ${JSON.stringify({mobile, width: window.innerWidth,+ nameRect, enabledRect, font: getComputedStyle(menu).font, rowGap: getComputedStyle(get("[data-enabled]").parentElement).rowGap})}`);const ruleRect = nameRect;for (const action of ["add-rule"]) {const button = get(`[data-action="${action}"]`).getBoundingClientRect();@@ -703,6 +713,7 @@ const runCases = async (sources, css, mobile) => {await click('[data-action="manage-collection"]');assert.equal(window.siyuan.dialogs.length, 1, "collection review uses the shared dialog on desktop and mobile");const reviewDialog = window.siyuan.dialogs[0];+ await waitForDialogLayout(reviewDialog);assert.equal(reviewDialog.element.querySelectorAll("[data-results] img").length, 0, "source text is escaped");assert.equal(transactions.length, writesBeforeReview, "reviewing entries does not mutate the database");const reviewTheme = document.createElement("style");@@ -724,11 +735,16 @@ const runCases = async (sources, css, mobile) => {const previous = reviewDialog.element.querySelector("[data-prev]").getBoundingClientRect();const cleanup = reviewDialog.element.querySelector("[data-cleanup]").getBoundingClientRect();if (cleanup.top > previous.bottom) {- assert.ok(cleanup.top - previous.bottom >= 8, "wrapped review actions preserve their spacing");+ assert.ok(cleanup.top - previous.bottom >= 8,+ `wrapped review actions preserve their spacing: ${JSON.stringify({mobile, width, fontSize, theme: name,+ previous, cleanup, gap: cleanup.top - previous.bottom,+ transform: getComputedStyle(reviewDialog.element.querySelector(".b3-dialog__container")).transform,+ rowGap: getComputedStyle(reviewDialog.element.querySelector(".b3-dialog__action")).rowGap})}`);}reviewDialog.element.querySelector("[data-cleanup]").click();await tick();const confirmation = window.siyuan.dialogs[1];+ await waitForDialogLayout(confirmation);for (const element of confirmation.element.querySelectorAll(".b3-dialog__body, button")) {assert.ok(element.scrollWidth <= element.clientWidth + 1, "confirmation wraps at narrow widths and large fonts");}@@ -855,7 +871,9 @@ if (process.versions.electron && process.type === "browser") {for (const mobile of [false, true]) {await win.loadURL("data:text/html,<html><body></body></html>");if (!win.webContents.debugger.isAttached()) win.webContents.debugger.attach("1.3");- await win.webContents.debugger.sendCommand("Emulation.setTouchEmulationEnabled", {enabled: mobile});+ if (mobile) {+ await win.webContents.debugger.sendCommand("Emulation.setTouchEmulationEnabled", {enabled: true});+ }const css = sources.daylight + sass.compile(path.join(__dirname, `../src/assets/scss/${mobile ? "mobile" : "base"}.scss`), {logger: sass.Logger.silent}).css;await win.webContents.executeJavaScript(`(${runCases.toString()})(${JSON.stringify(sources)}, ${JSON.stringify(css)}, ${mobile})`);}diff --git a/app/tests/databaseRowNavigation.test.js b/app/tests/databaseRowNavigation.test.jsindex 264887b7ba..8fe4b095ce 100644--- a/app/tests/databaseRowNavigation.test.js+++ b/app/tests/databaseRowNavigation.test.js@@ -36,6 +36,7 @@ const runCases = async (sources, css, touch) => {"../../../util/escape": {escapeAttr: String},"./renderData": {isAVRenderData: value => !!value?.view},"./virtualScroll": {getAVData: () => undefined},+ "./readonlyState": {getReadonlyAVSort: () => undefined},});const commands = load(sources.commands);let context;diff --git a/app/tests/fixtures/mockModules.cjs b/app/tests/fixtures/mockModules.cjsnew file mode 100644index 0000000000..4a062f75e3--- /dev/null+++ b/app/tests/fixtures/mockModules.cjs@@ -0,0 +1,8 @@+const createMockRequire = modules => name => {+ if (!Object.hasOwn(modules, name)) {+ throw new Error("Unexpected fixture module: " + name);+ }+ return modules[name];+};++module.exports = {createMockRequire};diff --git a/app/tests/mobileContentToolbar.test.js b/app/tests/mobileContentToolbar.test.jsindex 38b8d0af85..08aa5f756b 100644--- a/app/tests/mobileContentToolbar.test.js+++ b/app/tests/mobileContentToolbar.test.js@@ -5,6 +5,8 @@ const os = require("node:os");const runCases = async () => {const assert = require("node:assert/strict");+ const errors = [];+ window.addEventListener("error", event => errors.push(event.message));window.siyuan = {zIndex: 0, languages: {}, menus: {menu: {element: document.createElement("div"), remove() { this.data = undefined; }, fullscreen() {},}}};@@ -225,6 +227,14 @@ const runCases = async () => {assert.deepEqual(documentEditor.menus, [documentEditor.block]);documentEditor.toolbar.subElement.querySelector('[data-type="exitMultiSelectMode"]').click();assert.equal(documentEditor.element.querySelector(".protyle-wysiwyg--select"), null);++ // iOS 正文双击保留原生文字菜单,不显示自定义内容工具栏。+ window.contentToolbarIOS = true;+ const nativeMenu = createEditor(false);+ nativeMenu.editable.dispatchEvent(new MouseEvent("dblclick", {bubbles: true}));+ assert.equal(nativeMenu.toolbar.subElement.classList.contains("fn__none"), true);+ assert.equal(getSelection().toString(), "lph");+ assert.deepEqual(errors, []);};const runElectron = async () => {@@ -266,6 +276,8 @@ const runElectron = async () => {"const stripSemanticMarkersFromRangeText = range => range.toString();","const getAVTemplateInteractiveElement = () => undefined; const getDiagramBlock = () => undefined;","const isNotEditBlock = () => false;",+ "const isIOSDevice = () => window.contentToolbarIOS === true;",+ extract("protyle/wysiwyg/nativeTextMenu", ["usesNativeTextMenu"]),"const contentMenu = (protyle, node) => protyle.toolbar.showContent(protyle, getSelection().getRangeAt(0), node);",read("protyle/util/hasClosest"),read("protyle/wysiwyg/blockSelection"),diff --git a/app/tests/mockModules.test.js b/app/tests/mockModules.test.jsnew file mode 100644index 0000000000..0a85b8a1f4--- /dev/null+++ b/app/tests/mockModules.test.js@@ -0,0 +1,13 @@+const assert = require("node:assert/strict");+const {test} = require("node:test");+const {createMockRequire} = require("./fixtures/mockModules.cjs");++test("mock module loading accepts only explicitly registered dependencies", () => {+ const empty = {};+ const api = {patch() {}};+ const load = createMockRequire({"./empty": empty, "./api": api});+ assert.equal(load("./empty"), empty);+ assert.equal(load("./api"), api);+ assert.throws(() => load("./missing"), /Unexpected fixture module: \.\/missing/);+ assert.throws(() => load("toString"), /Unexpected fixture module: toString/);+});diff --git a/app/tests/pdfAnnotationInteractions.test.js b/app/tests/pdfAnnotationInteractions.test.jsindex 5a6031dc0e..7c5b7e1033 100644--- a/app/tests/pdfAnnotationInteractions.test.js+++ b/app/tests/pdfAnnotationInteractions.test.js@@ -25,7 +25,8 @@ async function runElectron() {const result = await win.webContents.executeJavaScript(`(async () => {window.pdfjsLib = await import(${JSON.stringify(runtime)});globalThis.pdfjsWorker = await import(${JSON.stringify(worker)});- window.siyuan = {languages: new Proxy({}, {get: (_, key) => key}), storage: {pdf: {}}};+ window.siyuan = {languages: new Proxy({}, {get: (_, key) => key}), storage: {},+ config: {appearance: {pdfTheme: {}}}};let nextID = 0;window.Lute = {NewNodeID: () => "20261010120000-" + String(++nextID).padStart(7, "0")};const {getPdfViewerHTML, webViewerLoad, getPdfSelectionText, PDFViewer, PDFThumbnailViewer, TextLayerBuilder} = await import(${JSON.stringify(bundle)});diff --git a/app/tests/pdfViewerBundle.cjs b/app/tests/pdfViewerBundle.cjsindex c7934b7088..c2e8cace86 100644--- a/app/tests/pdfViewerBundle.cjs+++ b/app/tests/pdfViewerBundle.cjs@@ -8,7 +8,7 @@ module.exports = async ({annotations = false} = {}) => {export const initAnno = () => {}; export const destroyAnno = () => {};export const getPdfInstance = () => null; export const hlPDFRect = () => {};`,"../annoRuntime": "export const registerPdfInstance = () => {};",- "../../constants": "export const Constants = {PROTYLE_CDN: '/stage/protyle', SIZE_UNDO: 100, LOCAL_PDFTHEME: 'pdf', LOCAL_MENU_MOUSE_SCROLL: 'local-menu-mouse-scroll'};",+ "../../constants": "export const Constants = {PROTYLE_CDN: '/stage/protyle', SIZE_UNDO: 100};","../../protyle/util/compatibility": "export const setStorageVal = async () => {}; export const updateHotkeyTip = x => x; export const isInMobileApp = () => false;","../../util/functions": "export const isMobile = () => window.pdfTestMobile === true;","../../protyle/util/hasClosest": "export const hasClosestByClassName = (el, name) => el.closest?.('.' + name);",@@ -23,7 +23,8 @@ module.exports = async ({annotations = false} = {}) => {callback?.({code: 0, data: {data: JSON.stringify(window.pdfSavedAnnotations || {})}});};`,"../layout/getAll": "export const getAllModels = () => ({asset: []});",- "../protyle/util/compatibility": "export const setStorageVal = () => {}; export const readText = async () => ''; export const writeText = text => {window.pdfCopiedText = text;};",+ "../protyle/util/compatibility": "export const readText = async () => ''; export const writeText = text => {window.pdfCopiedText = text;};",+ "../config/tabs/appearancePreferences": "export const patchAppearancePreference = async () => {};","../constants": mocks["../../constants"],"../dialog": "export class Dialog {}","../dialog/message": "export const showMessage = () => {};",diff --git a/app/tests/settingsWindow.test.js b/app/tests/settingsWindow.test.jsindex e2a078bacf..5f00b51014 100644--- a/app/tests/settingsWindow.test.js+++ b/app/tests/settingsWindow.test.js@@ -237,6 +237,7 @@ const runCases = async (sources) => {"../../constants": {Constants: {DIALOG_SETTING: "settings"}},"./tabs": {getSettingTab: () => ({mount: async root => { remounted++; root.innerHTML = markup(); }})},"./windowContext": {getSettingsOwnerApp: () => window.siyuan.ws.app},+ "./collapse": loadRendererModule(sources.collapse, {}),});const saving = loadRendererModule(sources.save, {"./mount": mounting,@@ -459,7 +460,8 @@ if (process.versions.electron && process.type === "browser") {native: "config/setting/nativeWindow.ts", fit: "config/setting/windowDialog.ts", controls: "boot/windowControls.ts",settingInterface: "config/setting/interface.ts",paint: "util/windowPaint.ts", frontend: "util/functions.ts", titles: "util/processTitle.ts",- mount: "config/setting/mount.ts", save: "config/setting/save.ts", fragments: "config/render/fragments.ts",+ mount: "config/setting/mount.ts", collapse: "config/setting/collapse.ts",+ save: "config/setting/save.ts", fragments: "config/render/fragments.ts",bazaarPath: "config/bazaar/openPath.ts", tooltip: "dialog/tooltip.ts", hoverInput: "util/hoverInput.ts"})) {let source = fs.readFileSync(path.join(__dirname, "../src", file), "utf8");if (key === "frontend") {diff --git a/app/tests/superBlockCreation.test.js b/app/tests/superBlockCreation.test.jsindex cbde2261ce..7e2f5631f4 100644--- a/app/tests/superBlockCreation.test.js+++ b/app/tests/superBlockCreation.test.js@@ -94,6 +94,7 @@ const cases = async source => {getHostCapabilities: () => ({widgets: false, remoteKernel: true}),isDisabledFeature: () => true,isInAndroid: () => false,+ canPickIOSPhotos: () => false,isBuiltinInlineStyleVisible: () => false,normalizeHTMLAssetIFrameBlockDOM: value => value,fetchSyncPost: async (url, data) => {diff --git a/app/tests/taskStatus.test.js b/app/tests/taskStatus.test.jsindex f3b006f299..ee4d33f882 100644--- a/app/tests/taskStatus.test.js+++ b/app/tests/taskStatus.test.js@@ -301,11 +301,11 @@ const cases = async source => {isMultiSelectMode: () => false}, gutter: {renderMenu: (_protyle, block) => { blockMenuTarget = block; }}};window.siyuan.menus = {menu: {popup() {}, fullscreen() {}, remove() {}}};const contextMenu = new Function("protyle", "getBlockSelectionModeElement", "isInEmbedBlock", "hasClosestBlock",- "hasClosestByClassName", "getEditorRange", "isNotEditBlock", "hasClosestByAttribute", "hideElements",+ "hasClosestByClassName", "getEditorRange", "isNotEditBlock", "hasClosestByAttribute", "hideElements", "isIOSDevice",source.contextMenu + "; return handleContextMenu;")(contextProtyle, () => null, () => null, target => target.closest("[data-node-id]"),(target, name) => target.closest(`.${name}`), () => selectionRange, () => false,- (target, name, value) => target.closest(`[${name}~="${value}"]`), () => {});+ (target, name, value) => target.closest(`[${name}~="${value}"]`), () => {}, () => false);for (const readonly of [false, true]) {contextProtyle.disabled = readonly;for (const target of taskItem.querySelectorAll(".protyle-action, svg, use")) {diff --git a/app/tests/textSelectionContextMenu.test.js b/app/tests/textSelectionContextMenu.test.jsindex c66f810228..1355574f95 100644--- a/app/tests/textSelectionContextMenu.test.js+++ b/app/tests/textSelectionContextMenu.test.js@@ -44,9 +44,15 @@ const sources = () => {};const touchSelection = readFileSync(path.join(__dirname, "../src/protyle/wysiwyg/touchBlockSelection.ts"), "utf8").replace(/^import .*;\r?\n/gm, "").replaceAll("export const ", "const ");+ const nativeMenu = ts.createSourceFile("nativeTextMenu.ts", readFileSync(path.join(__dirname,+ "../src/protyle/wysiwyg/nativeTextMenu.ts"), "utf8"), ts.ScriptTarget.Latest, true);+ const usesNativeTextMenu = nativeMenu.statements.find(node => ts.isVariableStatement(node) &&+ node.declarationList.declarations.some(item => item.name.getText(nativeMenu) === "usesNativeTextMenu"));+ assert.ok(usesNativeTextMenu);return [false, true].map(mobile => ts.transpileModule(preprocess(`const bind = function(protyle) {let beforeContextmenuRange; ${bindings.join(";\n")};};\n` +- range.getText(selection).replace("export ", "") + "\n" + wordSelection + "\n" + touchSelection, mobile), {+ range.getText(selection).replace("export ", "") + "\n" + wordSelection + "\n" + touchSelection + "\n" ++ usesNativeTextMenu.getText(nativeMenu).replace("export ", ""), mobile), {compilerOptions: {target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS},}).outputText);};@@ -63,13 +69,15 @@ const cases = async compiled => {const selection = getSelection();const menus = [];const callbacks = {};+ let iosDevice = false;const protyle = {element: root, wysiwyg: {element: root}, toolbar: {- isMultiSelectMode: () => false, element: document.createElement("div"),+ isMultiSelectMode: () => false, element: document.createElement("div"), subElement: document.createElement("div"),}, gutter: {renderMenu: () => menus.push({blockMenu: true})}};protyle.toolbar.element.classList.add("fn__none");const closest = node => (node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement).closest("[data-node-id]");const dependencies = {isMobile: () => mobile,+ isIOSDevice: () => iosDevice,getBlockSelectionModeElement: () => undefined,isInEmbedBlock: () => undefined,hasClosestBlock: closest,@@ -93,7 +101,7 @@ const cases = async compiled => {const eventErrors = [];const recordEventError = event => { eventErrors.push(event.error); event.preventDefault(); };window.addEventListener("error", recordEventError);- bind.call({element: {addEventListener: (name, callback) => {+ bind.call({element: {contains: node => root.contains(node), addEventListener: (name, callback) => {callbacks[name] = callback;if (name === "pointerdown") root.addEventListener(name, callback);}}}, protyle);@@ -154,6 +162,18 @@ const cases = async compiled => {check.equal(menus[0].copy(), "为什么");check.equal(selection.toString(), "为什么");delete dependencies.window.JSAndroid;+ if (mobile) {+ iosDevice = true;+ const selectedText = selection.toString();+ menus.length = 0;+ prevented = false;+ await callbacks.contextmenu({shiftKey: false, target: blocks[1].firstElementChild, detail: {},+ clientX: 20, clientY: 20, stopPropagation() {}, preventDefault() { prevented = true; }});+ check.equal(prevented, false, "iOS keeps the native text menu");+ check.equal(menus.length, 0, "iOS does not overlay the application text menu");+ check.equal(selection.toString(), selectedText);+ check.equal(protyle.toolbar.subElement.classList.contains("fn__none"), true);+ }window.removeEventListener("error", recordEventError);}return "Text selection context menu cases passed";diff --git a/kernel/api/bazaar.go b/kernel/api/bazaar.goindex e98e033be6..3e8cde603b 100644--- a/kernel/api/bazaar.go+++ b/kernel/api/bazaar.go@@ -570,6 +570,15 @@ func bazaarAppearance(value *conf.Appearance) *apicontract.BazaarAppearance {return nil}ret := &apicontract.BazaarAppearance{}+ ret.CompactMode = value.CompactMode+ ret.MenuMouseScroll = value.MenuMouseScroll+ ret.OutlineKeepCurrentExpand = value.OutlineKeepCurrentExpand+ if value.PDFTheme != nil {+ ret.PDFTheme = &apicontract.BazaarPDFTheme{Light: value.PDFTheme.Light, Dark: value.PDFTheme.Dark, AnnoColor: value.PDFTheme.AnnoColor}+ }+ if value.MobileBars != nil {+ ret.MobileBars = &apicontract.BazaarMobileBars{AutoHide: value.MobileBars.AutoHide, SidebarSwipe: value.MobileBars.SidebarSwipe, SidebarButtons: value.MobileBars.SidebarButtons}+ }ret.BodyGradient = bazaarBodyGradient(value.BodyGradient)if value.GlobalFontFamilies != nil {ret.GlobalFontFamilies = make([]*apicontract.BazaarEditorFont, len(value.GlobalFontFamilies))diff --git a/kernel/api/contract_bazaar_test.go b/kernel/api/contract_bazaar_test.goindex 1b1c688ab3..f73dacc914 100644--- a/kernel/api/contract_bazaar_test.go+++ b/kernel/api/contract_bazaar_test.go@@ -1694,6 +1694,57 @@ func TestBazaarContractTransportCompatibility(t *testing.T) {}}}++func TestBazaarContractAppearanceTransportCompatibility(t *testing.T) {+ bundle, err := apicontract.BuildBundle()+ if err != nil {+ t.Fatal(err)+ }+ for _, test := range []struct {+ name string+ appearance *conf.Appearance+ }{+ {"nil", nil},+ {"zero", &conf.Appearance{}},+ {"defaults", conf.NewAppearance()},+ {"configured", &conf.Appearance{+ CompactMode: true,+ MenuMouseScroll: true,+ PDFTheme: &conf.PDFTheme{Light: "dark", Dark: "light", AnnoColor: "#abcdef"},+ OutlineKeepCurrentExpand: true,+ MobileBars: &conf.MobileBars{AutoHide: new(false), SidebarSwipe: new(true)},+ }},+ {"disabled", &conf.Appearance{+ PDFTheme: &conf.PDFTheme{},+ MobileBars: &conf.MobileBars{AutoHide: new(false), SidebarSwipe: new(false), SidebarButtons: new(false)},+ }},+ } {+ t.Run(test.name, func(t *testing.T) {+ payload := bazaarAppearance(test.appearance)+ expected, err := json.Marshal(test.appearance)+ if err != nil {+ t.Fatal(err)+ }+ actual, err := json.Marshal(payload)+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(actual, expected) {+ t.Fatalf("appearance transport mismatch:\ngot %s\nwant %s", actual, expected)+ }+ response, err := json.Marshal(apicontract.Success(apicontract.BazaarAppearancePackagesData{Appearance: payload}))+ if err != nil {+ t.Fatal(err)+ }+ for _, endpoint := range []string{"installBazaarIcon", "uninstallBazaarIcon", "installBazaarTheme", "uninstallBazaarTheme"} {+ if err := bundle.ValidateResponse(http.MethodPost, "/api/bazaar/"+endpoint, response); err != nil {+ t.Errorf("%s: %v", endpoint, err)+ }+ }+ })+ }+}+func TestBazaarContractHTTPFailures(t *testing.T) {document, err := apicontract.BuildBundle()if err != nil {diff --git a/kernel/api/contract_native_container_test.go b/kernel/api/contract_native_container_test.goindex 0e7be319cd..b8cf3129fe 100644--- a/kernel/api/contract_native_container_test.go+++ b/kernel/api/contract_native_container_test.go@@ -217,10 +217,8 @@ func testAPIContractNativeContainers(t *testing.T, boxID string) {t.Fatal(err)}if invalid {- if !bytes.Equal(before, readFile(t)) ||- (endpoint != "prependBlock" && (response.Code != -1 || response.Data != nil)) ||- (endpoint == "prependBlock" && response.Code != 0) {- t.Fatalf("invalid API insert changed document: %s", recorder.Body.String())+ if response.Code != -1 || response.Data != nil || !bytes.Equal(before, readFile(t)) {+ t.Fatalf("invalid API insert was not rejected without persistence: %s", recorder.Body.String())}} else {if response.Code != 0 || len(response.Data) != 1 || len(response.Data[0].DoOperations) != 1 {diff --git a/kernel/apicontract/bazaar.go b/kernel/apicontract/bazaar.goindex 8f40234517..541f119d6b 100644--- a/kernel/apicontract/bazaar.go+++ b/kernel/apicontract/bazaar.go@@ -297,28 +297,47 @@ type BazaarPackage struct {Modes *[]string `json:"modes,omitempty"` // 主题:支持的模式列表}type BazaarAppearance struct {- BodyGradient *BazaarBodyGradient `json:"bodyGradient"` // 背景渐变,空值表示自动配色- GlobalFontFamilies []*BazaarEditorFont `json:"globalFontFamilies"` // 按优先级排列的全局默认字体- Mode int `json:"mode"` // 模式:0:明亮,1:暗黑- ModeOS bool `json:"modeOS"` // 模式是否跟随系统- DarkThemes []*BazaarAppearanceTheme `json:"darkThemes"` // 暗黑模式外观主题列表- LightThemes []*BazaarAppearanceTheme `json:"lightThemes"` // 明亮模式外观主题列表- ThemeDark string `json:"themeDark"` // 选择的暗黑模式外观主题- ThemeLight string `json:"themeLight"` // 选择的明亮模式外观主题- ThemeVer string `json:"themeVer"` // 选择的主题版本- Icons []*BazaarAppearanceIcon `json:"icons"` // 图标列表- Icon string `json:"icon"` // 选择的图标- IconVer string `json:"iconVer"` // 选择的图标版本- CodeBlockThemeLight string `json:"codeBlockThemeLight"` // 明亮模式下代码块主题- CodeBlockThemeDark string `json:"codeBlockThemeDark"` // 暗黑模式下代码块主题- Lang string `json:"lang"` // 选择的界面语言,同 AppConf.Lang- ThemeJS bool `json:"themeJS"` // 是否启用了主题 JavaScript- CloseButtonBehavior int `json:"closeButtonBehavior"` // 关闭按钮行为,0:退出,1:最小化到托盘- HideToolbar bool `json:"hideToolbar"` // 是否隐藏顶栏工具栏- HideStatusBar bool `json:"hideStatusBar"` // 是否隐藏底部状态栏- StatusBar *BazaarStatusBar `json:"statusBar"` // 底部状态栏配置- Notifications *BazaarNotifications `json:"notifications"` // 外观通知开关配置- EntryVisibility *BazaarEntryVisibility `json:"entryVisibility"` // 桌面端入口可见性配置+ CompactMode bool `json:"compactMode"` // 桌面端紧凑模式,默认关闭+ MenuMouseScroll bool `json:"menuMouseScroll"` // 桌面端菜单鼠标滚动,新工作空间默认启用+ PDFTheme *BazaarPDFTheme `json:"pdfTheme"` // PDF 阅读主题与标注颜色,响应保留空值+ OutlineKeepCurrentExpand bool `json:"outlineKeepCurrentExpand"` // 大纲保持当前标题展开,默认关闭+ MobileBars *BazaarMobileBars `json:"mobileBars"` // 移动端工具栏与侧栏访问偏好,响应保留空值+ BodyGradient *BazaarBodyGradient `json:"bodyGradient"` // 背景渐变,空值表示自动配色+ GlobalFontFamilies []*BazaarEditorFont `json:"globalFontFamilies"` // 按优先级排列的全局默认字体+ Mode int `json:"mode"` // 模式:0:明亮,1:暗黑+ ModeOS bool `json:"modeOS"` // 模式是否跟随系统+ DarkThemes []*BazaarAppearanceTheme `json:"darkThemes"` // 暗黑模式外观主题列表+ LightThemes []*BazaarAppearanceTheme `json:"lightThemes"` // 明亮模式外观主题列表+ ThemeDark string `json:"themeDark"` // 选择的暗黑模式外观主题+ ThemeLight string `json:"themeLight"` // 选择的明亮模式外观主题+ ThemeVer string `json:"themeVer"` // 选择的主题版本+ Icons []*BazaarAppearanceIcon `json:"icons"` // 图标列表+ Icon string `json:"icon"` // 选择的图标+ IconVer string `json:"iconVer"` // 选择的图标版本+ CodeBlockThemeLight string `json:"codeBlockThemeLight"` // 明亮模式下代码块主题+ CodeBlockThemeDark string `json:"codeBlockThemeDark"` // 暗黑模式下代码块主题+ Lang string `json:"lang"` // 选择的界面语言,同 AppConf.Lang+ ThemeJS bool `json:"themeJS"` // 是否启用了主题 JavaScript+ CloseButtonBehavior int `json:"closeButtonBehavior"` // 关闭按钮行为,0:退出,1:最小化到托盘+ HideToolbar bool `json:"hideToolbar"` // 是否隐藏顶栏工具栏+ HideStatusBar bool `json:"hideStatusBar"` // 是否隐藏底部状态栏+ StatusBar *BazaarStatusBar `json:"statusBar"` // 底部状态栏配置+ Notifications *BazaarNotifications `json:"notifications"` // 外观通知开关配置+ EntryVisibility *BazaarEntryVisibility `json:"entryVisibility"` // 桌面端入口可见性配置+}++// BazaarPDFTheme 明亮界面默认 light,暗黑界面默认 dark;标注颜色默认为 var(--b3-pdf-background1)。+type BazaarPDFTheme struct {+ Light string `json:"light"`+ Dark string `json:"dark"`+ AnnoColor string `json:"annoColor"`+}++// BazaarMobileBars 三项默认开启;响应保留未设置的 null,不将其转换为 false。+type BazaarMobileBars struct {+ AutoHide *bool `json:"autoHide"`+ SidebarSwipe *bool `json:"sidebarSwipe"`+ SidebarButtons *bool `json:"sidebarButtons"`}type BazaarBodyGradient struct {Mode string `json:"mode"` // auto:自动,custom:自定义,off:关闭diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex ac43b5ab1b..944e46f380 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -16458,6 +16458,9 @@"codeBlockThemeLight": {"type": "string"},+ "compactMode": {+ "type": "boolean"+ },"darkThemes": {"anyOf": [{@@ -16563,6 +16566,19 @@}]},+ "menuMouseScroll": {+ "type": "boolean"+ },+ "mobileBars": {+ "anyOf": [+ {+ "$ref": "#/$defs/BazaarMobileBars"+ },+ {+ "type": "null"+ }+ ]+ },"mode": {"type": "integer"},@@ -16579,6 +16595,19 @@}]},+ "outlineKeepCurrentExpand": {+ "type": "boolean"+ },+ "pdfTheme": {+ "anyOf": [+ {+ "$ref": "#/$defs/BazaarPDFTheme"+ },+ {+ "type": "null"+ }+ ]+ },"statusBar": {"anyOf": [{@@ -16607,6 +16636,7 @@"closeButtonBehavior","codeBlockThemeDark","codeBlockThemeLight",+ "compactMode","darkThemes","entryVisibility","globalFontFamilies",@@ -16617,9 +16647,13 @@"icons","lang","lightThemes",+ "menuMouseScroll",+ "mobileBars","mode","modeOS","notifications",+ "outlineKeepCurrentExpand",+ "pdfTheme","statusBar","themeDark","themeJS",@@ -16971,6 +17005,47 @@}]},+ "BazaarMobileBars": {+ "type": "object",+ "properties": {+ "autoHide": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "sidebarButtons": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "sidebarSwipe": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": [+ "autoHide",+ "sidebarButtons",+ "sidebarSwipe"+ ],+ "additionalProperties": false+ },"BazaarNotifications": {"type": "object","properties": {@@ -17004,6 +17079,26 @@],"additionalProperties": false},+ "BazaarPDFTheme": {+ "type": "object",+ "properties": {+ "annoColor": {+ "type": "string"+ },+ "dark": {+ "type": "string"+ },+ "light": {+ "type": "string"+ }+ },+ "required": [+ "annoColor",+ "dark",+ "light"+ ],+ "additionalProperties": false+ },"BazaarPackage": {"type": "object","properties": {diff --git a/kernel/model/attribute_view_automation_fts5_test.go b/kernel/model/attribute_view_automation_fts5_test.goindex ffe20bf1f0..21010298b2 100644--- a/kernel/model/attribute_view_automation_fts5_test.go+++ b/kernel/model/attribute_view_automation_fts5_test.go@@ -214,7 +214,7 @@ func TestAutomationEncryptedUnavailableReferencePause(t *testing.T) {_, source, target, statusID, _ := setupAutomationTest(t)boxID := ast.NewNodeID()markRuntimeEncryptedBox(boxID)- setDEKForTest(boxID, bytes.Repeat([]byte{0x72}, 32))+ prepareUnlockedEncryptedBoxTest(t, boxID, bytes.Repeat([]byte{0x72}, 32))t.Cleanup(func() {for _, view := range []*av.AttributeView{source, target} {av.SetAVBoxID(view.ID, "")@@ -407,7 +407,7 @@ func TestAutomationRelationKeywordsKeepCryptoBoundary(t *testing.T) {_, source, target, _, logsID := setupAutomationTest(t)boxID := ast.NewNodeID()markRuntimeEncryptedBox(boxID)- setDEKForTest(boxID, bytes.Repeat([]byte{0x62}, 32))+ prepareUnlockedEncryptedBoxTest(t, boxID, bytes.Repeat([]byte{0x62}, 32))t.Cleanup(func() {av.SetAVBoxID(target.ID, "")forgetRuntimeEncryptedBox(boxID)@@ -731,7 +731,7 @@ func TestAutomationEncryptedExecutionAndFailures(t *testing.T) {boxID := ast.NewNodeID()markRuntimeEncryptedBox(boxID)key := bytes.Repeat([]byte{0x71}, 32)- setDEKForTest(boxID, key)+ prepareUnlockedEncryptedBoxTest(t, boxID, key)t.Cleanup(func() {for _, view := range []*av.AttributeView{source, target} {av.SetAVBoxID(view.ID, "")diff --git a/kernel/model/attribute_view_binding_test.go b/kernel/model/attribute_view_binding_test.goindex a6ff8e79a0..e9f4f3668b 100644--- a/kernel/model/attribute_view_binding_test.go+++ b/kernel/model/attribute_view_binding_test.go@@ -137,7 +137,7 @@ func TestUpdateBoundBlockAvsAttributeDoesNotWriteOutsideBox(t *testing.T) {util.Langs["en"][382] = "Cannot export database [%s]. Check database bindings and notebook location"const encryptedBoxID = "20260909101000-encbox0"markRuntimeEncryptedBox(encryptedBoxID)- setDEKForTest(encryptedBoxID, bytes.Repeat([]byte{0x73}, 32))+ prepareUnlockedEncryptedBoxTest(t, encryptedBoxID, bytes.Repeat([]byte{0x73}, 32))av.SetAVBoxID(fixture.attrView.ID, encryptedBoxID)t.Cleanup(func() {av.SetAVBoxID(fixture.attrView.ID, "")diff --git a/kernel/model/attribute_view_binding_undo_sqlcipher_test.go b/kernel/model/attribute_view_binding_undo_sqlcipher_test.goindex 70aa9bb968..ab186d37db 100644--- a/kernel/model/attribute_view_binding_undo_sqlcipher_test.go+++ b/kernel/model/attribute_view_binding_undo_sqlcipher_test.go@@ -32,7 +32,7 @@ func TestAttributeViewBindingEncryptedReplay(t *testing.T) {}markRuntimeEncryptedBox(boxID)dek := bytes.Repeat([]byte{0x63}, 32)- setDEKForTest(boxID, dek)+ prepareUnlockedEncryptedBoxTest(t, boxID, dek)boxConf := conf.NewBoxConf()boxConf.Encrypted = trueboxConf.BoxCrypt = &conf.BoxEncryption{Spec: boxEncryptionSpec}diff --git a/kernel/model/attribute_view_block_history_fts5_test.go b/kernel/model/attribute_view_block_history_fts5_test.goindex 0a7a2427e5..ecde524572 100644--- a/kernel/model/attribute_view_block_history_fts5_test.go+++ b/kernel/model/attribute_view_block_history_fts5_test.go@@ -263,7 +263,7 @@ func TestAttributeViewBoundHistoryRestore(t *testing.T) {if encrypted {boxID = ast.NewNodeID()markRuntimeEncryptedBox(boxID)- setDEKForTest(boxID, bytes.Repeat([]byte{0x67}, 32))+ prepareUnlockedEncryptedBoxTest(t, boxID, bytes.Repeat([]byte{0x67}, 32))av.SetAVBoxID(before.ID, boxID)tree.Box = boxIDt.Cleanup(func() {diff --git a/kernel/model/attribute_view_block_undo_sqlcipher_test.go b/kernel/model/attribute_view_block_undo_sqlcipher_test.goindex b1a3c04006..0f51ce54db 100644--- a/kernel/model/attribute_view_block_undo_sqlcipher_test.go+++ b/kernel/model/attribute_view_block_undo_sqlcipher_test.go@@ -31,7 +31,7 @@ func TestAttributeViewDeletedBlockEncryptedReplay(t *testing.T) {}markRuntimeEncryptedBox(boxID)dek := bytes.Repeat([]byte{0x63}, 32)- setDEKForTest(boxID, dek)+ prepareUnlockedEncryptedBoxTest(t, boxID, dek)boxConf := conf.NewBoxConf()boxConf.Encrypted = trueboxConf.BoxCrypt = &conf.BoxEncryption{Spec: boxEncryptionSpec}diff --git a/kernel/model/attribute_view_calendar_fts5_test.go b/kernel/model/attribute_view_calendar_fts5_test.goindex 20d10d62c8..cff32664f9 100644--- a/kernel/model/attribute_view_calendar_fts5_test.go+++ b/kernel/model/attribute_view_calendar_fts5_test.go@@ -36,7 +36,7 @@ func TestAttributeViewCalendarDateUndoAndEncryptedReplay(t *testing.T) {if encrypted {boxID = ast.NewNodeID()markRuntimeEncryptedBox(boxID)- setDEKForTest(boxID, bytes.Repeat([]byte{0x63}, 32))+ prepareUnlockedEncryptedBoxTest(t, boxID, bytes.Repeat([]byte{0x63}, 32))av.SetAVBoxID(original.ID, boxID)t.Cleanup(func() {av.SetAVBoxID(original.ID, "")diff --git a/kernel/model/attribute_view_collection_sqlcipher_test.go b/kernel/model/attribute_view_collection_sqlcipher_test.goindex 3e643f0831..458c336038 100644--- a/kernel/model/attribute_view_collection_sqlcipher_test.go+++ b/kernel/model/attribute_view_collection_sqlcipher_test.go@@ -37,7 +37,7 @@ func testBlockCollectionEncryptedSourceAndRecovery(t *testing.T, target string)}markRuntimeEncryptedBox(boxID)key := bytes.Repeat([]byte{0x58}, 32)- setDEKForTest(boxID, key)+ prepareUnlockedEncryptedBoxTest(t, boxID, key)boxConf := conf.NewBoxConf()boxConf.Encrypted, boxConf.BoxCrypt = true, &conf.BoxEncryption{Spec: boxEncryptionSpec}if err = encryptBoxMetadata(boxID, boxConf, key); err != nil {diff --git a/kernel/model/attribute_view_conditional_color_fts5_test.go b/kernel/model/attribute_view_conditional_color_fts5_test.goindex c60b961c80..a23b0f5cbc 100644--- a/kernel/model/attribute_view_conditional_color_fts5_test.go+++ b/kernel/model/attribute_view_conditional_color_fts5_test.go@@ -36,7 +36,7 @@ func TestAttributeViewConditionalColorsUndoAndEncryptedReplay(t *testing.T) {if encrypted {boxID = ast.NewNodeID()markRuntimeEncryptedBox(boxID)- setDEKForTest(boxID, bytes.Repeat([]byte{0x63}, 32))+ prepareUnlockedEncryptedBoxTest(t, boxID, bytes.Repeat([]byte{0x63}, 32))av.SetAVBoxID(original.ID, boxID)t.Cleanup(func() {av.SetAVBoxID(original.ID, "")diff --git a/kernel/model/attribute_view_fields_fts5_test.go b/kernel/model/attribute_view_fields_fts5_test.goindex 6afc96b2ab..13dbe5012c 100644--- a/kernel/model/attribute_view_fields_fts5_test.go+++ b/kernel/model/attribute_view_fields_fts5_test.go@@ -298,7 +298,7 @@ func TestAttributeViewFieldsEncryptedReplay(t *testing.T) {_, before, tx := setupAttributeViewFieldsTest(t, av.KeyTypeText)boxID := ast.NewNodeID()markRuntimeEncryptedBox(boxID)- setDEKForTest(boxID, bytes.Repeat([]byte{0x62}, 32))+ prepareUnlockedEncryptedBoxTest(t, boxID, bytes.Repeat([]byte{0x62}, 32))av.SetAVBoxID(before.ID, boxID)t.Cleanup(func() {av.SetAVBoxID(before.ID, "")diff --git a/kernel/model/attribute_view_group_undo_fts5_test.go b/kernel/model/attribute_view_group_undo_fts5_test.goindex 7e8e79d7b6..d666498d43 100644--- a/kernel/model/attribute_view_group_undo_fts5_test.go+++ b/kernel/model/attribute_view_group_undo_fts5_test.go@@ -108,7 +108,7 @@ func TestAttributeViewGroupMoveEncrypted(t *testing.T) {_, before, tx := setupAttributeViewGroupMoveTest(t, av.LayoutTypeKanban, "C")boxID := ast.NewNodeID()markRuntimeEncryptedBox(boxID)- setDEKForTest(boxID, bytes.Repeat([]byte{0x65}, 32))+ prepareUnlockedEncryptedBoxTest(t, boxID, bytes.Repeat([]byte{0x65}, 32))av.SetAVBoxID(before.ID, boxID)t.Cleanup(func() {av.SetAVBoxID(before.ID, "")diff --git a/kernel/model/attribute_view_option_undo_fts5_test.go b/kernel/model/attribute_view_option_undo_fts5_test.goindex 04d11c29e0..4bb0846096 100644--- a/kernel/model/attribute_view_option_undo_fts5_test.go+++ b/kernel/model/attribute_view_option_undo_fts5_test.go@@ -213,7 +213,7 @@ func TestAttributeViewOptionEncryptedReplay(t *testing.T) {boxID := ast.NewNodeID()dek := bytes.Repeat([]byte{0x64}, 32)markRuntimeEncryptedBox(boxID)- setDEKForTest(boxID, dek)+ prepareUnlockedEncryptedBoxTest(t, boxID, dek)t.Cleanup(func() {for _, view := range []*av.AttributeView{source, peer} {av.SetAVBoxID(view.ID, "")diff --git a/kernel/model/attribute_view_recovery_fts5_test.go b/kernel/model/attribute_view_recovery_fts5_test.goindex 5cb0a3aa57..a60d38dbb7 100644--- a/kernel/model/attribute_view_recovery_fts5_test.go+++ b/kernel/model/attribute_view_recovery_fts5_test.go@@ -94,7 +94,7 @@ func TestAttributeViewMissingDatabaseHistoryRecovery(t *testing.T) {if encrypted {boxID = ast.NewNodeID()markRuntimeEncryptedBox(boxID)- setDEKForTest(boxID, bytes.Repeat([]byte{0x73}, 32))+ prepareUnlockedEncryptedBoxTest(t, boxID, bytes.Repeat([]byte{0x73}, 32))av.SetAVBoxID(before.ID, boxID)t.Cleanup(func() {av.SetAVBoxID(before.ID, "")@@ -433,7 +433,7 @@ func TestAttributeViewBoundHistoryOneWayEncrypted(t *testing.T) {dest, keyID, itemID := addDeletedBlockOneWayTestRelation(t, source)boxID := ast.NewNodeID()markRuntimeEncryptedBox(boxID)- setDEKForTest(boxID, bytes.Repeat([]byte{0x79}, 32))+ prepareUnlockedEncryptedBoxTest(t, boxID, bytes.Repeat([]byte{0x79}, 32))t.Cleanup(func() {for _, view := range []*av.AttributeView{source, dest} {av.SetAVBoxID(view.ID, "")diff --git a/kernel/model/attribute_view_relation_item_sqlcipher_test.go b/kernel/model/attribute_view_relation_item_sqlcipher_test.goindex 9b414db8e6..cb3a9919ec 100644--- a/kernel/model/attribute_view_relation_item_sqlcipher_test.go+++ b/kernel/model/attribute_view_relation_item_sqlcipher_test.go@@ -33,7 +33,7 @@ func TestAttributeViewRelationItemEncrypted(t *testing.T) {}markRuntimeEncryptedBox(boxID)key := bytes.Repeat([]byte{0x64}, 32)- setDEKForTest(boxID, key)+ prepareUnlockedEncryptedBoxTest(t, boxID, key)boxConf := conf.NewBoxConf()boxConf.Encrypted = trueboxConf.BoxCrypt = &conf.BoxEncryption{Spec: boxEncryptionSpec}diff --git a/kernel/model/backlink_sort_fts5_test.go b/kernel/model/backlink_sort_fts5_test.goindex 47e07391d6..0183da343d 100644--- a/kernel/model/backlink_sort_fts5_test.go+++ b/kernel/model/backlink_sort_fts5_test.go@@ -76,6 +76,14 @@ func TestBacklinkAnchorSortContext(t *testing.T) {}const childID = "20260917000000-child01"ids := []string{"20260917000001-ref0010", "20260917000002-ref0002", "20260917000003-ref0001", "20260917000004-ref002b"}+ assertIndexedReference := func(parentID string) {+ t.Helper()+ // 直接读取索引,避免缓存掩盖重复插入留下的旧父级和内容。+ rows, err := sql.QueryNoLimitArgsInBox("SELECT parent_id, content FROM blocks WHERE id = ?", boxID, ids[2])+ if err != nil || len(rows) != 1 || rows[0]["parent_id"] != parentID || rows[0]["content"] != "A1" {+ t.Fatalf("indexed reference in %s notebook: got %+v, want one row under %s with content A1: %v", name, rows, parentID, err)+ }+ }for i, tree := range trees {for tree.Root.FirstChild != nil {tree.Root.FirstChild.Unlink()@@ -149,9 +157,10 @@ func TestBacklinkAnchorSortContext(t *testing.T) {t.Fatal(err)}treenode.UpsertBlockTree(tree)- sql.IndexTreeQueue(tree)+ sql.UpsertTreeQueue(tree)sql.UpdateRefsTreeQueue(tree)sql.FlushQueue()+ assertIndexedReference(fixture.targetID)for _, mode := range []int{0, 1, 2, 0} {want := []string{fixture.targetID}switch mode {@@ -204,9 +213,10 @@ func TestBacklinkAnchorSortContext(t *testing.T) {t.Fatal(err)}treenode.UpsertBlockTree(tree)- sql.IndexTreeQueue(tree)+ sql.UpsertTreeQueue(tree)sql.UpdateRefsTreeQueue(tree)sql.FlushQueue()+ assertIndexedReference(item.ID)newToken, _, _, _, expired, err := GetGlobalBacklinks(globalQuery, "", 0, "", allow)if err != nil || expired {t.Fatalf("refreshed global sorting in %s notebook: %v %v", name, expired, err)diff --git a/kernel/model/crypto_test.go b/kernel/model/crypto_test.goindex d8bd28f2fb..9a11b0f293 100644--- a/kernel/model/crypto_test.go+++ b/kernel/model/crypto_test.go@@ -38,6 +38,63 @@ func setDEKForTest(boxID string, dek []byte) {cachedDEKs[boxID] = dek}+// prepareUnlockedEncryptedBoxTest 为数据读写测试设置加密身份、密钥和已完成初始化的生命周期。+func prepareUnlockedEncryptedBoxTest(t *testing.T, boxID string, dek []byte) {+ t.Helper()+ dataDir := filepath.Clean(util.DataDir)+ key := bytes.Clone(dek)+ markRuntimeEncryptedBox(boxID)+ setDEKForTest(boxID, key)+ setEncryptedBoxState(boxID, EncryptedBoxStateUnlocked)+ t.Cleanup(func() {+ cachedDEKsLock.Lock()+ zeroAndClear(cachedDEKs[boxID])+ delete(cachedDEKs, boxID)+ cachedDEKsLock.Unlock()+ zeroAndClear(key)+ removeEncryptedBoxLifecycle(boxID)+ runtimeEncryptedBoxes.CompareAndDelete(boxID, dataDir)+ runtimeNormalBoxes.CompareAndDelete(boxID, dataDir)+ })+}++func TestUnlockedEncryptedBoxFixtureLifecycle(t *testing.T) {+ oldDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() { util.DataDir = oldDataDir })+ const boxID = "20261019000000-fixture"+ key := bytes.Repeat([]byte{0x69}, 32)+ t.Run("unlocked", func(t *testing.T) {+ prepareUnlockedEncryptedBoxTest(t, boxID, key)+ if !IsEncryptedBox(boxID) || !isBoxUnlockedForAccess(boxID) {+ t.Fatal("fixture did not initialize an accessible encrypted notebook")+ }+ if err := AcquireEncryptedBoxOperation(boxID); err != nil {+ t.Fatal(err)+ }+ ReleaseEncryptedBoxOperation(boxID)+ setEncryptedBoxStateWithAdmission(boxID, EncryptedBoxStateUnlocked, false)+ if err := AcquireEncryptedBoxOperation(boxID); err == nil {+ ReleaseEncryptedBoxOperation(boxID)+ t.Fatal("fixture bypassed operation admission")+ }+ setEncryptedBoxState(boxID, EncryptedBoxStateError)+ setDEKForTest(boxID, bytes.Clone(key))+ if _, err := GetDEKIfUnlocked(boxID); err == nil {+ t.Fatal("fixture bypassed an unavailable notebook state")+ }+ })+ if IsBoxUnlocked(boxID) || isRuntimeEncryptedBox(boxID) {+ t.Fatal("fixture retained its key or notebook identity")+ }+ if _, exists := encryptedBoxLifecycles.Load(boxID); exists {+ t.Fatal("fixture retained its lifecycle")+ }+ if !bytes.Equal(key, bytes.Repeat([]byte{0x69}, 32)) {+ t.Fatal("fixture changed its caller's key")+ }+}+func TestEncryptedBoxIdentityRejectsInvalidIDs(t *testing.T) {oldDataDir := util.DataDirutil.DataDir = t.TempDir()diff --git a/kernel/model/export_attribute_view_test.go b/kernel/model/export_attribute_view_test.goindex cc2f741da6..28a81ba8ea 100644--- a/kernel/model/export_attribute_view_test.go+++ b/kernel/model/export_attribute_view_test.go@@ -202,7 +202,7 @@ func TestAttributeViewExportDoesNotCrossEncryptedBoundary(t *testing.T) {"en": {"key": "Key", "select": "Select", "table": "Table", "gallery": "Gallery"},}markRuntimeEncryptedBox(encryptedBoxID)- setDEKForTest(encryptedBoxID, bytes.Repeat([]byte{0x42}, 32))+ prepareUnlockedEncryptedBoxTest(t, encryptedBoxID, bytes.Repeat([]byte{0x42}, 32))t.Cleanup(func() {util.Lang, util.AttrViewLangs = oldLang, oldAttrViewLangsav.SetAVBoxID(encryptedAvID, "")diff --git a/kernel/model/ocr_status_test.go b/kernel/model/ocr_status_test.goindex c10459ea91..9448e022ff 100644--- a/kernel/model/ocr_status_test.go+++ b/kernel/model/ocr_status_test.go@@ -59,9 +59,19 @@ func TestOCRFailureStatusBounded(t *testing.T) {ocrFailures.paths = previousocrFailures.Unlock()})- for i := range ocrFailureLimit + 1 {- recordOCRFailure(fmt.Sprintf("assets/ocr-status-%04d.png", i), errors.New("inference failed"))+ oldest := time.Unix(0, 0)+ for i := range ocrFailureLimit {+ path := fmt.Sprintf("assets/ocr-status-%04d.png", i)+ recordOCRFailure(path, errors.New("inference failed"))+ if !HasOCRFailure(path) {+ t.Fatalf("failure was not recorded: %s", path)+ }+ // 固定严格递增的更新时间,避免时钟精度和 map 遍历顺序影响最旧项选择。+ ocrFailures.Lock()+ ocrFailures.paths[path] = oldest.Add(time.Duration(i) * time.Second)+ ocrFailures.Unlock()}+ recordOCRFailure(fmt.Sprintf("assets/ocr-status-%04d.png", ocrFailureLimit), errors.New("inference failed"))ocrFailures.Lock()count := len(ocrFailures.paths)ocrFailures.Unlock()@@ -69,4 +79,9 @@ func TestOCRFailureStatusBounded(t *testing.T) {!HasOCRFailure(fmt.Sprintf("assets/ocr-status-%04d.png", ocrFailureLimit)) {t.Fatalf("failure cache limit: %d", count)}+ for i := 1; i <= ocrFailureLimit; i++ {+ if !HasOCRFailure(fmt.Sprintf("assets/ocr-status-%04d.png", i)) {+ t.Fatalf("failure cache evicted a newer entry: %d", i)+ }+ }}diff --git a/kernel/model/sync_auto_pause_test.go b/kernel/model/sync_auto_pause_test.goindex 4d5dec5e60..70c0dc5912 100644--- a/kernel/model/sync_auto_pause_test.go+++ b/kernel/model/sync_auto_pause_test.go@@ -1,6 +1,7 @@package modelimport (+ "encoding/json""net/http""net/http/httptest""net/url"@@ -79,18 +80,32 @@ func TestAutoSyncPauseNotificationAndStatus(t *testing.T) {_ = connection.SetReadDeadline(time.Now().Add(5 * time.Second))var events []eventfor {- var item event- if err := connection.ReadJSON(&item); err != nil {+ var envelope struct {+ Cmd string+ Msg string+ Data json.RawMessage+ }+ if err := connection.ReadJSON(&envelope); err != nil {t.Fatal(err)}- if item.Cmd == "barrier" {+ if envelope.Cmd == "barrier" {return events}- if item.Cmd == "msg" || item.Cmd == "statusbar" || item.Cmd == "cmsg" {+ if envelope.Cmd == "msg" || envelope.Cmd == "statusbar" || envelope.Cmd == "cmsg" {+ item := event{Cmd: envelope.Cmd, Msg: envelope.Msg}+ if err := json.Unmarshal(envelope.Data, &item.Data); err != nil {+ t.Fatalf("decode %s notification: %v", envelope.Cmd, err)+ }events = append(events, item)}}}+ // 非通知事件可以携带标量或数组,过滤命令后才解析通知的对象载荷。+ for _, frame := range []string{`{"cmd":"syncing","data":true}`, `{"cmd":"progress","data":"waiting"}`, `{"cmd":"transactions","data":[]}`} {+ if err := push.Broadcast([]byte(frame)); err != nil {+ t.Fatal(err)+ }+ }autoSyncErrCount.Store(7)if !checkSync(false, false, false) || len(readEvents()) != 0 {t.Fatal("backoff began before the existing threshold")