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: Repair alpha test fixtures and deferred PDF navigation
Daniel164fa844c332
diff --git a/app/src/asset/pdf/pdf_viewer.js b/app/src/asset/pdf/pdf_viewer.jsindex ac63806b63..10fa6f62ba 100644--- a/app/src/asset/pdf/pdf_viewer.js+++ b/app/src/asset/pdf/pdf_viewer.js@@ -286,6 +286,8 @@ class PDFViewer {#pendingScroll = null;+ #pendingScrollFrame = null;+#resizeObserver = new ResizeObserver(this.#resizeObserverCallback.bind(this));#scrollModePageState = null;@@ -403,7 +405,7 @@ class PDFViewer {abortSignal?.addEventListener("abort",() => {- this.#pendingScroll = null;+ this.#cancelPendingScroll();this.#resizeObserver.disconnect();this.#resizeObserver = null;},@@ -1359,7 +1361,7 @@ class PDFViewer {}_resetView() {- this.#pendingScroll = null;+ this.#cancelPendingScroll();this._pages = [];this._currentPageNumber = 1;this._currentScale = UNKNOWN_SCALE;@@ -2674,21 +2676,43 @@ class PDFViewer {Math.floor(entry.borderBoxSize[0].blockSize));this.#containerTopLeft = null;- const pending = this.#pendingScroll;- if (pending && this.pdfDocument && this.container.clientWidth && this.container.clientHeight) {- this.#pendingScroll = null;- if (pending.pageView) {- this.#scrollIntoView(pending.pageView, pending.pageSpot);- } else {- this.scrollPageIntoView(pending);- }- this.update();- }+ this.#schedulePendingScroll();break;}}}+ #cancelPendingScroll() {+ this.#pendingScroll = null;+ if (this.#pendingScrollFrame !== null) {+ cancelAnimationFrame(this.#pendingScrollFrame);+ this.#pendingScrollFrame = null;+ }+ }++ #schedulePendingScroll() {+ if (this.#pendingScrollFrame !== null || !this.#pendingScroll || !this.pdfDocument ||+ !this.container.isConnected || !this.container.clientWidth || !this.container.clientHeight) {+ return;+ }+ // 导航可能改变缩放和滚动条,不能在 ResizeObserver 的同一轮投递中修改布局。+ this.#pendingScrollFrame = requestAnimationFrame(() => {+ this.#pendingScrollFrame = null;+ const pending = this.#pendingScroll;+ if (this.#abortSignal?.aborted || !pending || !this.pdfDocument ||+ !this.container.isConnected || !this.container.clientWidth || !this.container.clientHeight) {+ return;+ }+ this.#pendingScroll = null;+ if (pending.pageView) {+ this.#scrollIntoView(pending.pageView, pending.pageSpot);+ } else {+ this.scrollPageIntoView(pending);+ }+ this.update();+ });+ }+get containerTopLeft() {return (this.#containerTopLeft ||= [this.container.offsetTop,diff --git a/app/src/protyle/util/onGetMobileTopBar.test.ts b/app/src/protyle/util/onGetMobileTopBar.test.tsindex 7e6f32d573..cb63582a55 100644--- a/app/src/protyle/util/onGetMobileTopBar.test.ts+++ b/app/src/protyle/util/onGetMobileTopBar.test.ts@@ -25,6 +25,7 @@ const sources = {editor: compile(sliceSource("../../mobile/util/setEmpty.ts", "export const setEditor = ")),render: compile(sliceSource("onGet.ts", "export const onGet = ", "export const disabledForeverProtyle = ")),loading: compile(sliceSource("../ui/initUI.ts", "export const addLoading = ", "export const setPadding = ")),+ navigation: compile(sliceSource("../render/av/databaseRowNavigation.ts", "export const clearDatabaseRowNavigation = ", "export const mountDatabaseRowNavigation = ")),completion: compile(sliceSource("../../mobile/editor.ts", " let completed = false;", " if (!isValid()) {")),};@@ -86,7 +87,7 @@ const browserCases = (code: typeof sources) => {dependencies[name] = noop;}const runtime = new Function(...Object.keys(dependencies), code.orientation + code.layout + code.editor + code.loading +- code.render + code.completion + "\nreturn {onGet, addLoading, complete, fail, updateMobileTopBarLayout};")(+ code.render + code.navigation + code.completion + "\nreturn {onGet, addLoading, complete, fail, updateMobileTopBarLayout};")(...Object.values(dependencies));if (mode !== "desktop") {runtime.updateMobileTopBarLayout();@@ -122,6 +123,33 @@ const browserCases = (code: typeof sources) => {return "Mobile top bar loading cases passed";};+test("mobile loading completion clears row navigation before settling once", () => {+ const calls: string[] = [];+ const container = {+ querySelector: (selector: string) => {+ assert.match(selector, /data-database-row-navigation/);+ return {remove: () => calls.push("remove navigation")};+ },+ classList: {remove: (name: string) => calls.push(name)},+ };+ const dependencies = {+ window: {siyuan: {config: {fileTree: {}}}},+ document: {getElementById: (): HTMLElement | null => null},+ setEditor: () => calls.push("show editor"),+ bindMobileBarsScroll: () => calls.push("bind scroll"),+ isValid: () => true,+ action: [] as string[], Constants: {CB_GET_OPENNEW: "open-new"},+ afterOpen: () => calls.push("opened"),+ onFailure: () => assert.fail("completion must not fail"),+ };+ const complete = new Function(...Object.keys(dependencies), sources.navigation + sources.completion + "\nreturn complete;")(+ ...Object.values(dependencies));+ const protyle = {element: container, contentElement: {}};+ complete(protyle);+ complete(protyle);+ assert.deepEqual(calls, ["remove navigation", "protyle--database-row-navigation", "show editor", "bind scroll", "opened"]);+});+test("document rendering preserves landscape title controls and finishes loading", {skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,timeout: 30000,@@ -135,8 +163,10 @@ app.whenReady().then(async () => {const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});try {await win.loadURL("data:text/html,<html><body></body></html>");- console.log(await win.webContents.executeJavaScript(${JSON.stringify("const __name = value => value; (" +- browserCases.toString() + ")(" + JSON.stringify(sources) + ")")}));+ const result = await win.webContents.executeJavaScript(${JSON.stringify("(() => { try { const __name = value => value; return {value: (" ++ browserCases.toString() + ")(" + JSON.stringify(sources) + ")}; } catch (error) { return {error: error.stack || String(error)}; } })()")});+ if (result.error) throw new Error(result.error);+ console.log(result.value);win.destroy();app.exit(0);} catch (error) {diff --git a/app/tests/avAttributeCarrier.test.js b/app/tests/avAttributeCarrier.test.jsindex 975fa8c6fb..df00df95b4 100644--- a/app/tests/avAttributeCarrier.test.js+++ b/app/tests/avAttributeCarrier.test.js@@ -228,6 +228,7 @@ const runElectron = async () => {extract("primaryFocus", ["focusDatabasePrimary"]),extract("rowReadonly", ["inheritDatabaseRowReadonly"]),extract("../../../editor/databaseRow", ["rowReady", "rowSwitchers", "newDatabaseRowModel"]),+ extract("databaseRowNavigation", ["clearDatabaseRowNavigation", "mountDatabaseRowNavigation"]),extract("openDatabaseRow", ["closeMobileDatabaseRow", "openMobileDatabaseRow"])].map(source =>ts.transpileModule(source, {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020}}).outputText);await win.loadURL("data:text/html,<html><body></body></html>");diff --git a/app/tests/dialogFocus.test.js b/app/tests/dialogFocus.test.jsindex ca41586817..88c5a736bb 100644--- a/app/tests/dialogFocus.test.js+++ b/app/tests/dialogFocus.test.js@@ -196,10 +196,14 @@ const runPositionCases = async (dialogSource, positionSource, dialogCSS) => {"../constants": {Constants: {TIMEOUT_OPENDIALOG: 0, TIMEOUT_DBLCLICK: 0}},"../block/panelOwnership": {getDialogBlockPanel() {}, destroyDialogBlockPanels() {}},"../layout/getTopBarHeight": {getTopBarHeight: () => 0},+ "../protyle/util/compatibility": {isNotCtrl: () => true},};const load = source => {const exports = {};- new Function("require", "exports", source)(name => modules[name] || {}, exports);+ new Function("require", "exports", source)(name => {+ assert.ok(Object.hasOwn(modules, name), `Unexpected fixture module: ${name}`);+ return modules[name];+ }, exports);return exports;};const {Dialog} = load(dialogSource);@@ -254,6 +258,17 @@ const runFlashcardCases = async (dialogSource, cardSource, mobile) => {"../util/zIndex": {isAbove: () => false},"./moveResize": {moveResize() {}},"../util/functions": {isMobile: () => mobile},+ "../protyle/util/compatibility": {isNotCtrl: () => true},+ // 复习正文由 bindCardEvent 夹具隔离,意外访问这些依赖时立即失败。+ ...Object.fromEntries([+ "../menus/menuToggle", "../dialog/inputDialog", "../util/fetch", "./fetchDueCards", "../protyle",+ "../protyle/util/onGet", "../protyle/util/hasClosest", "../protyle/ui/hideElements",+ "../protyle/breadcrumb/action", "../menus/Menu", "../util/escape", "../editor/util", "dayjs",+ "../util/pathName", "../protyle/util/resize", "../dialog/message", "../plugin/Menu",+ "../protyle/wysiwyg/transaction", "./flashcardMode", "../protyle/util/blockFold", "../plugin/EventBusCore",+ ].map(name => [name, new Proxy({}, {get: (_target, key) => {+ throw new Error(`Unexpected flashcard fixture dependency: ${name}.${String(key)}`);+ }})])),"../constants": {Constants: constants},"../block/panelOwnership": {getDialogBlockPanel() {}, destroyDialogBlockPanels() {}},"../protyle/util/selectionOffsets": {focusByRange: range => {@@ -264,7 +279,10 @@ const runFlashcardCases = async (dialogSource, cardSource, mobile) => {};const load = source => {const exports = {};- new Function("require", "exports", source)(name => modules[name] || {}, exports);+ new Function("require", "exports", source)(name => {+ assert.ok(Object.hasOwn(modules, name), `Unexpected fixture module: ${name}`);+ return modules[name];+ }, exports);return exports;};modules["../dialog"] = load(dialogSource);@@ -336,7 +354,7 @@ const runFlashcardCases = async (dialogSource, cardSource, mobile) => {}};-const runSearchCases = async (dialogSource, focusSource, searchSource, mobileSource, openOptionsSource) => {+const runSearchCases = async (dialogSource, focusSource, searchSource, mobileSource, openOptionsSource, navigationSource) => {const assert = require("node:assert/strict");const tick = () => new Promise(resolve => setTimeout(resolve, 20));const constants = {TIMEOUT_OPENDIALOG: 0, TIMEOUT_DBLCLICK: 0, DIALOG_SEARCH: "search",@@ -377,6 +395,11 @@ const runSearchCases = async (dialogSource, focusSource, searchSource, mobileSou"../util/pathName": {getNotebookName: () => "Notebook", pathPosix: () => ({join: (...parts) => parts.join("/")})},"./config": {hasExplicitSearchScope: () => true, setSearchConfigTemporaryPath() {}},"./request": {cancelSearchRequest() {}},+ // 当前用例只覆盖搜索入口,不应访问其他命令或复用窗口的路径更新。+ ...Object.fromEntries(["./path", "../protyle/render/av/addToDatabase", "../protyle/util/hasClosest",+ "../protyle/hint/extend"].map(name => [name, new Proxy({}, {get: (_target, key) => {+ throw new Error(`Unexpected search fixture dependency: ${name}.${String(key)}`);+ }})])),"./util": {genSearch: (_app, _config, element) => {element.innerHTML = '<input id="searchInput" value="previous query"><div id="searchList"></div>';return {edit: {destroy() {}}, unRefEdit: {destroy() {}}};@@ -392,12 +415,16 @@ const runSearchCases = async (dialogSource, focusSource, searchSource, mobileSou};const load = source => {const exports = {};- new Function("require", "exports", source)(name => modules[name] || {}, exports);+ new Function("require", "exports", source)(name => {+ assert.ok(Object.hasOwn(modules, name), `Unexpected fixture module: ${name}`);+ return modules[name];+ }, exports);return exports;};modules["../dialog"] = load(dialogSource);modules["./focus"] = modules["../search/focus"] = load(focusSource);modules["./openOptions"] = load(openOptionsSource);+ modules["./databaseRowNavigation"] = load(navigationSource);const {openSearch} = load(searchSource);const mobile = load(mobileSource);const search = () => openSearch({app: {}, hotkey: "search", notebookId: "box", searchPath: "/doc.sy"});@@ -555,7 +582,8 @@ if (process.versions.electron && process.type === "browser") {${JSON.stringify(source)}, ${JSON.stringify(compileSearch("search/focus.ts"))},${JSON.stringify(compileSearch("search/spread.ts"))},${JSON.stringify(compileSearch("command/nativeRuntime.ts", true))},- ${JSON.stringify(compileSearch("search/openOptions.ts"))})`);+ ${JSON.stringify(compileSearch("search/openOptions.ts"))},+ ${JSON.stringify(compileSearch("command/databaseRowNavigation.ts"))})`);const cardSource = fs.readFileSync(path.join(__dirname, "../src/card/openCard.ts"), "utf8");for (const mobile of [false, true]) {const compiled = ts.transpileModule(parse(cardSource, {MOBILE: mobile, BROWSER: true}, false, true), {diff --git a/app/tests/fixtures/map-webview-boundary/harness.cjs b/app/tests/fixtures/map-webview-boundary/harness.cjsindex 38ecb8242d..047939e5a6 100644--- a/app/tests/fixtures/map-webview-boundary/harness.cjs+++ b/app/tests/fixtures/map-webview-boundary/harness.cjs@@ -14,9 +14,11 @@ if (!app || !BrowserWindow) {if (process.argv.includes("--verify")) {// 只输出安全的断言位置和操作符,不泄露探测地址、令牌或断言值。const failure = error.cause || error;- const location = typeof failure.stack === "string" &&- failure.stack.match(/\bharnessSupport\.cjs:(\d+):(\d+)\)?(?:\r?\n|$)/);- if (location) console.error("Verification location: harnessSupport.cjs:" + location[1] + ":" + location[2]);+ const locations = typeof failure.stack === "string" ?+ failure.stack.matchAll(/\bharnessSupport\.cjs:(\d+):(\d+)\)?(?:\r?\n|$)/g) : [];+ for (const location of locations) {+ console.error("Verification location: harnessSupport.cjs:" + location[1] + ":" + location[2]);+ }if (failure.code === "ERR_ASSERTION") {const operators = ["strictEqual", "notStrictEqual", "deepStrictEqual", "notDeepStrictEqual", "==", "!=", "fail"];console.error("Verification assertion: ERR_ASSERTION" +diff --git a/app/tests/inlineMathSelection.test.js b/app/tests/inlineMathSelection.test.jsindex ea911a4b21..356bad82ad 100644--- a/app/tests/inlineMathSelection.test.js+++ b/app/tests/inlineMathSelection.test.js@@ -52,7 +52,13 @@ const setupEdge = async (mode) => {await document.fonts.ready;const range = document.createRange();range.selectNodeContents(prefix);- const width = range.getBoundingClientRect().width;+ // 先测量整段文字,不能把已换行文本的外接矩形当作单行宽度。+ editable.style.width = "max-content";+ editable.style.whiteSpace = "nowrap";+ const measuredLines = Array.from(range.getClientRects());+ if (measuredLines.length !== 1) throw new Error("Prefix measurement must occupy one line");+ const width = measuredLines[0].width;+ editable.style.removeProperty("white-space");editable.style.width = (width + math.getBoundingClientRect().width * (mode === "left" ? 0.5 : 1) + 2) + "px";const point = (node, offset) => {range.setStart(node, offset);diff --git a/app/tests/mapAttribution.test.js b/app/tests/mapAttribution.test.jsindex 4979d7a40d..f86972a39a 100644--- a/app/tests/mapAttribution.test.js+++ b/app/tests/mapAttribution.test.js@@ -9,6 +9,28 @@ const closeTileServer = server => new Promise(resolve => {server.closeAllConnections();});+const sampleTilePixel = (tileMap, timeout) => new Promise((resolve, reject) => {+ if (timeout <= 0) { resolve([0, 0, 0, 0]); return; }+ const canvas = tileMap.getCanvas();+ const gl = canvas.getContext("webgl2");+ const pixel = new Uint8Array(4);+ const finish = error => {+ clearTimeout(timer);+ tileMap.off("render", sample);+ if (error) reject(error);+ else resolve(Array.from(pixel));+ };+ const sample = () => {+ try {+ gl.readPixels(Math.floor(canvas.width / 2), Math.floor(canvas.height / 2), 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);+ if (pixel[3] > 0) finish();+ } catch (error) { finish(error); }+ };+ const timer = setTimeout(() => finish(), timeout);+ tileMap.on("render", sample);+ tileMap.triggerRepaint();+});+const install = (sources, css, controlledClock) => {document.head.innerHTML = "";document.body.innerHTML = '<div id="map" class="maplibregl-map"></div>';@@ -137,7 +159,8 @@ const verifyTileHTTP = async (win, sources, css, sdk) => {window.tileHTTP = {errors: [], removed: 0, tileError: null, ready: false, loaded: false};class FixtureMap extends sdk.Map {constructor(options) {- super({...options, preserveDrawingBuffer: true, style: {version: 8, sources: {fixture: {type: "raster", tileSize: 256,+ super({...options, canvasContextAttributes: {...options.canvasContextAttributes, preserveDrawingBuffer: true},+ style: {version: 8, sources: {fixture: {type: "raster", tileSize: 256,tiles: [origin + "/tile/{z}/{x}/{y}.png"], minzoom: 0, maxzoom: 6, attribution: "Fixture data"}},layers: [{id: "fixture", type: "raster", source: "fixture"}]}});window.tileMap = this;@@ -165,6 +188,9 @@ const verifyTileHTTP = async (win, sources, css, sdk) => {await win.webContents.executeJavaScript(`(${installRealMap.toString()})(${JSON.stringify(sources)},${JSON.stringify(css)}, ${JSON.stringify(origin)})`);assert.equal(await win.webContents.executeJavaScript("tileHTTP.ready"), true);+ assert.equal(await win.webContents.executeJavaScript(+ "tileMap.getCanvas().getContext('webgl2').getContextAttributes().preserveDrawingBuffer"), true,+ "the fixture requests a retained WebGL buffer through the installed SDK API");assert.equal(await win.webContents.executeJavaScript("tileHTTP.loaded"), false);await win.webContents.executeJavaScript("tileAdapter.setPoints([{id:'fixture', longitude:121, latitude:31}],1); tileAdapter.fit(); void 0");assert.equal(await win.webContents.executeJavaScript("document.querySelectorAll('.maplibregl-marker').length"), 1);@@ -180,13 +206,8 @@ const verifyTileHTTP = async (win, sources, css, sdk) => {await new Promise(resolve => setTimeout(resolve, 50));}assert.equal(await win.webContents.executeJavaScript("tileHTTP.loaded"), true, "delayed tiles eventually finish rendering");- const pixel = await win.webContents.executeJavaScript(`(() => {- const canvas = tileMap.getCanvas();- const gl = canvas.getContext("webgl2");- const pixel = new Uint8Array(4);- gl.readPixels(Math.floor(canvas.width / 2), Math.floor(canvas.height / 2), 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);- return Array.from(pixel);- })()`);+ const pixel = await win.webContents.executeJavaScript(`(${sampleTilePixel.toString()})(tileMap,+ ${Math.max(0, loadDeadline - Date.now())})`);assert.ok(pixel[3] > 0, "the real WebGL canvas paints the delayed raster tile");failNextTile = true;await win.webContents.executeJavaScript("tileMap.setZoom(3); void 0");@@ -330,6 +351,46 @@ if (process.versions.electron && process.type === "browser") {const {test} = require("node:test");const {execFile} = require("node:child_process");const {promisify} = require("node:util");+ test("tile pixel checks sample render frames and release their listener on paint or deadline", async t => {+ assert.deepEqual(await sampleTilePixel({}, 0), [0, 0, 0, 0], "an expired load budget never waits for another frame");+ for (const outcome of ["painted", "transparent", "error"]) {+ const painted = outcome === "painted";+ let deadline, render, reads = 0, repaints = 0;+ const timer = {}, cleared = [];+ t.mock.method(global, "setTimeout", (callback, delay) => {+ assert.equal(delay, 123);+ deadline = callback;+ return timer;+ });+ t.mock.method(global, "clearTimeout", value => cleared.push(value));+ const map = {+ getCanvas: () => ({width: 800, height: 600, getContext: () => ({+ RGBA: 1, UNSIGNED_BYTE: 2,+ readPixels(x, y, width, height, format, type, pixel) {+ assert.deepEqual([x, y, width, height, format, type], [400, 300, 1, 1, 1, 2]);+ reads++;+ if (outcome === "error") throw new Error("fixture readPixels failure");+ pixel[3] = painted ? 255 : 0;+ },+ })}),+ on(name, callback) { assert.equal(name, "render"); render = callback; },+ off(name, callback) { assert.equal(name, "render"); assert.equal(callback, render); render = null; },+ triggerRepaint() { repaints++; },+ };+ const pending = sampleTilePixel(map, 123);+ assert.equal(reads, 0, "sampling waits for a completed render");+ assert.equal(repaints, 1);+ const rejected = outcome === "error" ? assert.rejects(pending, /fixture readPixels failure/) : null;+ assert.doesNotThrow(() => render(), "render callbacks report failures through the awaited promise");+ if (outcome === "transparent") deadline();+ if (rejected) await rejected;+ else assert.deepEqual(await pending, [0, 0, 0, painted ? 255 : 0]);+ assert.equal(reads, 1);+ assert.equal(render, null);+ assert.deepEqual(cleared, [timer]);+ t.mock.restoreAll();+ }+ });test("tile fixture cleanup completes even when a failed assertion leaves responses held", async () => {const http = require("node:http");let response;diff --git a/app/tests/mapWebviewBoundary.test.js b/app/tests/mapWebviewBoundary.test.jsindex 8dd5d018d4..67f37f8373 100644--- a/app/tests/mapWebviewBoundary.test.js+++ b/app/tests/mapWebviewBoundary.test.js@@ -19,7 +19,10 @@ test("verification failures identify the assertion location without exposing profor (const duringSetup of [false, true]) {const failure = Object.assign(new Error("https://private.invalid/?token=secret-token"), {code: "ERR_ASSERTION", operator: "deepStrictEqual", actual: "secret-token",- stack: "Error: https://private.invalid/?token=secret-token\n at verifyHarness (C:\\private\\harnessSupport.cjs:401:12)\n",+ stack: "Error: https://private.invalid/?token=secret-token\n" ++ " at waitFor (C:\\private\\harnessSupport.cjs:84:16)\n" ++ " at async verifyMapCorners (/private/harnessSupport.cjs:196:17)\n" ++ " at async verifyHarness (C:\\private\\harnessSupport.cjs:404:5)\n",});const messages = [];let resolveExit;@@ -36,7 +39,9 @@ test("verification failures identify the assertion location without exposing pro},});assert.equal(await exited, 1);- assert.match(messages.join("\n"), /Verification location: harnessSupport\.cjs:401:12/);+ assert.match(messages.join("\n"), /Verification location: harnessSupport\.cjs:84:16/);+ assert.match(messages.join("\n"), /Verification location: harnessSupport\.cjs:196:17/);+ assert.match(messages.join("\n"), /Verification location: harnessSupport\.cjs:404:5/);assert.match(messages.join("\n"), /Verification assertion: ERR_ASSERTION; operator: deepStrictEqual/);assert.doesNotMatch(messages.join("\n"), /private|secret-token|https:/);}diff --git a/app/tests/pdfDeferredNavigation.test.js b/app/tests/pdfDeferredNavigation.test.jsnew file mode 100644index 0000000000..a42520e0d5--- /dev/null+++ b/app/tests/pdfDeferredNavigation.test.js@@ -0,0 +1,121 @@+const assert = require("node:assert/strict");+const {readFileSync} = require("node:fs");+const path = require("node:path");+const {test} = require("node:test");+const ts = require("typescript");++const source = readFileSync(path.join(__dirname, "../src/asset/pdf/pdf_viewer.js"), "utf8");+const parsed = ts.createSourceFile("pdf_viewer.js", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);+const viewer = parsed.statements.find(node => ts.isClassDeclaration(node) && node.name?.text === "PDFViewer");+assert.ok(viewer);+const member = name => {+ const node = viewer.members.find(item => name === "constructor" ? ts.isConstructorDeclaration(item) :+ item.name?.getText(parsed) === name);+ assert.ok(node, `Missing production member ${name}`);+ return node.getText(parsed);+};+const methods = ["#resizeObserverCallback", "#schedulePendingScroll", "#cancelPendingScroll",+ "#updateContainerHeightCss"].map(member).join("\n");++const fixture = () => {+ const frames = new Map();+ let sequence = 0;+ const Harness = new Function("requestAnimationFrame", "cancelAnimationFrame", "docStyle", `+ return class {+ #pendingScroll = null;+ #pendingScrollFrame = null;+ #abortSignal = {aborted: false};+ #containerTopLeft = null;+ #previousContainerHeight = 0;+ container = {isConnected: true, clientWidth: 780, clientHeight: 518};+ pdfDocument = {};+ calls = [];+ ${methods}+ #scrollIntoView(pageView, pageSpot) { this.calls.push({pageView, pageSpot}); }+ scrollPageIntoView(destination) { this.calls.push(destination); }+ update() { this.calls.push("update"); }+ queue(destination) { this.#pendingScroll = destination; }+ pending() { return this.#pendingScroll; }+ notify() { this.#resizeObserverCallback([{target: this.container,+ borderBoxSize: [{blockSize: this.container.clientHeight}]}]); }+ reset() { this.#cancelPendingScroll(); this.pdfDocument = {}; }+ abort() { this.#abortSignal.aborted = true; this.#cancelPendingScroll(); }+ };+ `)(callback => { const id = ++sequence; frames.set(id, callback); return id; },+ id => frames.delete(id), {setProperty() {}});+ return {viewer: new Harness(), frames, flush() {+ const queued = [...frames.values()];+ frames.clear();+ queued.forEach(callback => callback());+ }};+};++test("PDF resize delivery defers navigation and coalesces the latest destination", () => {+ const {viewer, frames, flush} = fixture();+ viewer.queue({pageNumber: 1});+ viewer.notify();+ assert.deepEqual(viewer.calls, [], "ResizeObserver must not navigate or update synchronously");+ viewer.queue({pageNumber: 2});+ viewer.notify();+ assert.equal(frames.size, 1);+ flush();+ assert.deepEqual(viewer.calls, [{pageNumber: 2}, "update"]);+ assert.equal(viewer.pending(), null);+});++test("PDF deferred page-view navigation preserves its exact page spot", () => {+ const {viewer, flush} = fixture();+ const destination = {pageView: {id: 2}, pageSpot: {left: 13, top: 29}};+ viewer.queue(destination);+ viewer.notify();+ flush();+ assert.deepEqual(viewer.calls, [destination, "update"]);+});++for (const field of ["clientWidth", "clientHeight", "isConnected"]) {+ test(`PDF navigation keeps its target when ${field} becomes unavailable before the frame`, () => {+ const {viewer, frames, flush} = fixture();+ const destination = {pageNumber: 2};+ viewer.queue(destination);+ viewer.notify();+ const previous = viewer.container[field];+ viewer.container[field] = 0;+ flush();+ assert.deepEqual(viewer.calls, []);+ assert.equal(viewer.pending(), destination);+ viewer.notify();+ assert.equal(frames.size, 0);+ viewer.container[field] = previous;+ viewer.notify();+ flush();+ assert.deepEqual(viewer.calls, [destination, "update"]);+ });+}++for (const action of ["reset", "abort"]) {+ test(`PDF ${action} cancels queued navigation and rejects a stale frame`, () => {+ const {viewer, frames} = fixture();+ viewer.queue({pageNumber: 1});+ viewer.notify();+ const staleFrame = [...frames.values()][0];+ viewer[action]();+ assert.equal(frames.size, 0);+ assert.equal(viewer.pending(), null);+ staleFrame();+ assert.deepEqual(viewer.calls, []);+ });+}++test("PDF document removal before the queued frame does not navigate", () => {+ const {viewer, flush} = fixture();+ viewer.queue({pageNumber: 2});+ viewer.notify();+ viewer.pdfDocument = null;+ flush();+ assert.deepEqual(viewer.calls, []);+});++test("PDF reset and abort production paths cancel deferred navigation", () => {+ assert.match(member("_resetView"), /this\.#cancelPendingScroll\(\)/);+ assert.match(member("constructor"), /"abort",\s*\(\) => \{\s*this\.#cancelPendingScroll\(\)/);+});diff --git a/app/tests/textSelectionContextMenu.test.js b/app/tests/textSelectionContextMenu.test.jsindex cb2c566bca..c66f810228 100644--- a/app/tests/textSelectionContextMenu.test.js+++ b/app/tests/textSelectionContextMenu.test.js@@ -90,7 +90,17 @@ const cases = async compiled => {};const bind = Function(...Object.keys(dependencies), `${compiled[Number(mobile)]}\nreturn bind;`)(...Object.values(dependencies));- bind.call({element: {addEventListener: (name, callback) => {callbacks[name] = callback;}}}, protyle);+ const eventErrors = [];+ const recordEventError = event => { eventErrors.push(event.error); event.preventDefault(); };+ window.addEventListener("error", recordEventError);+ bind.call({element: {addEventListener: (name, callback) => {+ callbacks[name] = callback;+ if (name === "pointerdown") root.addEventListener(name, callback);+ }}}, protyle);+ const pointerdown = (target, pointerType = "mouse") => {+ target.dispatchEvent(new PointerEvent("pointerdown", {bubbles: true, pointerType, button: 0}));+ check.deepEqual(eventErrors, [], "pointerdown completes without renderer exceptions");+ };// 使用真实 DOM Range 覆盖正反向跨块选区,菜单操作仍应读取完整选区。for (const reversed of [false, true]) {for (const target of blocks.slice(0, 3)) {@@ -99,7 +109,7 @@ const cases = async compiled => {const expected = selection.getRangeAt(0).toString();const visibleText = selection.toString();menus.length = 0;- callbacks.pointerdown();+ pointerdown(target.firstElementChild, mobile ? "touch" : "mouse");await callbacks.contextmenu({shiftKey: false, target: target.firstElementChild, detail: {},clientX: 20, clientY: 20, stopPropagation() {}, preventDefault() {}});check.equal(menus.length, 1, `menu on ${target.dataset.nodeId}, mobile=${mobile}, reversed=${reversed}`);@@ -112,14 +122,14 @@ const cases = async compiled => {// 桌面端在未选中的块中右键,不应误用另一处的非空选区。if (!mobile) {menus.length = 0;- callbacks.pointerdown();+ pointerdown(blocks[3].firstElementChild);await callbacks.contextmenu({shiftKey: false, target: blocks[3].firstElementChild, detail: {},clientX: 20, clientY: 20, stopPropagation() {}, preventDefault() {}});check.equal(menus.length, 0);}selection.collapse(texts[1], 3);menus.length = 0;- callbacks.pointerdown();+ pointerdown(blocks[1].firstElementChild, mobile ? "touch" : "mouse");await callbacks.contextmenu({shiftKey: false, target: blocks[1].firstElementChild, detail: {},clientX: 20, clientY: 20, stopPropagation() {}, preventDefault() {}});check.equal(menus.length, 1);@@ -134,7 +144,7 @@ const cases = async compiled => {}};selection.setBaseAndExtent(texts[1], 8, texts[1], 9);menus.length = 0;- callbacks.pointerdown();+ pointerdown(blocks[1].firstElementChild, mobile ? "touch" : "mouse");let prevented = false;await callbacks.contextmenu({shiftKey: false, target: blocks[1].firstElementChild, detail: {},clientX: 20, clientY: 20, stopPropagation() {}, preventDefault() { prevented = true; }});@@ -144,6 +154,7 @@ const cases = async compiled => {check.equal(menus[0].copy(), "为什么");check.equal(selection.toString(), "为什么");delete dependencies.window.JSAndroid;+ window.removeEventListener("error", recordEventError);}return "Text selection context menu cases passed";};diff --git a/kernel/conf/task_status_menu_test.go b/kernel/conf/task_status_menu_test.goindex 45ec219954..9805f97d60 100644--- a/kernel/conf/task_status_menu_test.go+++ b/kernel/conf/task_status_menu_test.go@@ -25,9 +25,9 @@ func TestTaskStatusMenuMigration(t *testing.T) {config := &EntryVisibility{Version: 5, Active: "custom", Profiles: []*EntryVisibilityProfile{&fixture.Input}}for i := 0; i < 2; i++ {NormalizeEntryVisibility(config, EntryVisibilityProfileFull)- if config.Version != 6 || !reflect.DeepEqual(fixture.Input.Entries, fixture.Expected.Entries) ||+ if config.Version != EntryVisibilityVersion || !reflect.DeepEqual(fixture.Input.Entries, fixture.Expected.Entries) ||!reflect.DeepEqual(fixture.Input.Orders, fixture.Expected.Orders) {- t.Fatalf("unexpected migration: %+v", fixture.Input)+ t.Fatalf("unexpected migration: version=%d, expected=%d, profile=%+v", config.Version, EntryVisibilityVersion, fixture.Input)}}})diff --git a/kernel/model/file_corrupted_windows_test.go b/kernel/model/file_corrupted_windows_test.goindex 2505b7b3c4..12806438d3 100644--- a/kernel/model/file_corrupted_windows_test.go+++ b/kernel/model/file_corrupted_windows_test.go@@ -1,7 +1,6 @@package modelimport (- "errors""os""path/filepath""syscall"@@ -10,7 +9,6 @@ import ("github.com/88250/lute/ast""github.com/siyuan-note/siyuan/kernel/cache""github.com/siyuan-note/siyuan/kernel/util"- "golang.org/x/sys/windows")func TestDocIALSharingViolationRecovers(t *testing.T) {@@ -42,12 +40,7 @@ func TestDocIALSharingViolationRecovers(t *testing.T) {syscall.CloseHandle(handle)}}()- if _, err = os.Stat(filePath); err != nil {- t.Fatal(err)- }- if _, readErr := os.ReadFile(filePath); !errors.Is(readErr, windows.ERROR_SHARING_VIOLATION) {- t.Fatalf("read-denying handle did not produce a sharing violation: %v", readErr)- }+ requireReadSharingViolation(t, filePath, handle)if attrs := cache.GetDocIALInBox(document, fixture.box.ID); attrs != nil {t.Fatalf("sharing-violation fixture unexpectedly has cached attributes: %v", attrs)}diff --git a/kernel/model/file_sharing_windows_test.go b/kernel/model/file_sharing_windows_test.gonew file mode 100644index 0000000000..a628bdf6f0--- /dev/null+++ b/kernel/model/file_sharing_windows_test.go@@ -0,0 +1,43 @@+package model++import (+ "errors"+ "os"+ "runtime"+ "syscall"+ "testing"++ "golang.org/x/sys/windows"+)++func requireReadSharingViolation(t *testing.T, path string, held syscall.Handle) {+ t.Helper()+ _, beforeStatErr := os.ReadFile(path)+ if _, err := os.Stat(path); err != nil {+ t.Fatal(err)+ }+ _, afterStatErr := os.ReadFile(path)+ if errors.Is(beforeStatErr, windows.ERROR_SHARING_VIOLATION) && errors.Is(afterStatErr, windows.ERROR_SHARING_VIOLATION) {+ return+ }++ // 前置条件不成立时对比原生打开结果与文件身份,区分句柄、路径和读取实现问题。+ var heldInfo, probeInfo windows.ByHandleFileInformation+ heldInfoErr := windows.GetFileInformationByHandle(windows.Handle(held), &heldInfo)+ ptr, err := windows.UTF16PtrFromString(path)+ if err != nil {+ t.Fatal(err)+ }+ probe, openErr := windows.CreateFile(ptr, windows.GENERIC_READ,+ windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE,+ nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, 0)+ var probeInfoErr error+ if openErr == nil {+ defer windows.CloseHandle(probe)+ probeInfoErr = windows.GetFileInformationByHandle(probe, &probeInfo)+ }+ t.Fatalf("read-denying fixture failed: path=%q, go=%s, read before Stat=%v, read after Stat=%v, native open=%v, held identity=%x:%x:%x (error=%v), probe identity=%x:%x:%x (error=%v)",+ path, runtime.Version(), beforeStatErr, afterStatErr, openErr,+ heldInfo.VolumeSerialNumber, heldInfo.FileIndexHigh, heldInfo.FileIndexLow, heldInfoErr,+ probeInfo.VolumeSerialNumber, probeInfo.FileIndexHigh, probeInfo.FileIndexLow, probeInfoErr)+}diff --git a/kernel/model/sync_ignore.go b/kernel/model/sync_ignore.goindex 86c912e308..a5a72b8125 100644--- a/kernel/model/sync_ignore.go+++ b/kernel/model/sync_ignore.go@@ -29,6 +29,7 @@ type syncIgnoreStamp struct {size int64modified time.Timemode os.FileMode+ entries string}var syncIgnoreCache struct {@@ -39,13 +40,21 @@ var syncIgnoreCache struct {}func syncIgnoreStamps() (ret []syncIgnoreStamp, valid bool) {- paths := []string{filepath.Join(util.DataDir, syncIgnoreRulePath), filepath.Join(util.WorkingDir, "guide")}+ guidePath := filepath.Join(util.WorkingDir, "guide")+ paths := []string{filepath.Join(util.DataDir, syncIgnoreRulePath), guidePath}for _, id := range userGuideIDs {paths = append(paths, filepath.Join(util.WorkingDir, "guide", id, "storage", "av"))}- valid = true+ // 目录时间戳与大小可能保持不变,另外比较实际生成忽略规则的文件名集合。+ avNames, readErr := getAllUserGuideAVJSONFiles()+ valid = readErr == nil+ slices.Sort(avNames)+ avNames = slices.Compact(avNames)for _, path := range paths {stamp := syncIgnoreStamp{path: path}+ if path == guidePath {+ stamp.entries = strings.Join(avNames, "\x00")+ }info, err := os.Stat(path)if err == nil {stamp.size, stamp.modified, stamp.mode = info.Size(), info.ModTime(), info.Mode()diff --git a/kernel/model/sync_ignore_test.go b/kernel/model/sync_ignore_test.goindex 117ffdfea3..09f44eb458 100644--- a/kernel/model/sync_ignore_test.go+++ b/kernel/model/sync_ignore_test.go@@ -9,6 +9,7 @@ import ("testing""time"+ "github.com/88250/lute/ast"ignore "github.com/sabhiram/go-gitignore""github.com/siyuan-note/dejavu""github.com/siyuan-note/siyuan/kernel/util"@@ -242,26 +243,176 @@ func TestSyncIgnoreCache(t *testing.T) {}}-func BenchmarkSyncIgnoreRules(b *testing.B) {+func TestSyncIgnoreCacheDetectsGuideEntriesWithUnchangedMetadata(t *testing.T) {+ for _, operation := range []string{"remove", "rename", "add"} {+ t.Run(operation, func(t *testing.T) {+ oldData, oldWorking := util.DataDir, util.WorkingDir+ util.DataDir, util.WorkingDir = t.TempDir(), t.TempDir()+ t.Cleanup(func() { util.DataDir, util.WorkingDir = oldData, oldWorking })+ const oldName = "20260913123456-abcdefg.json"+ const newName = "20260913123457-abcdefg.json"+ avDir := filepath.Join(util.WorkingDir, "guide", userGuideIDs[0], "storage", "av")+ oldPath, newPath := filepath.Join(avDir, oldName), filepath.Join(avDir, newName)+ writeSyncPathTestFile(t, oldPath)+ mustSyncIgnoreRules(t)+ _, before := mustSyncIgnoreRules(t)+ if !before.MatchesPath("/storage/av/" + oldName) {+ t.Fatal("guide fixture was not ignored")+ }+ switch operation {+ case "remove":+ if err := os.Remove(oldPath); err != nil {+ t.Fatal(err)+ }+ case "rename":+ if err := os.Rename(oldPath, newPath); err != nil {+ t.Fatal(err)+ }+ case "add":+ writeSyncPathTestFile(t, newPath)+ }+ // 模拟目录变更后大小和时间戳没有变化,保留缓存中的旧文件列表与规则。+ current, valid := syncIgnoreStamps()+ if !valid {+ t.Fatal("guide fixture metadata could not be read")+ }+ syncIgnoreCache.Lock()+ for i := range syncIgnoreCache.stamps {+ syncIgnoreCache.stamps[i].size = current[i].size+ syncIgnoreCache.stamps[i].modified = current[i].modified+ }+ syncIgnoreCache.Unlock()+ _, after := mustSyncIgnoreRules(t)+ if after == before {+ t.Fatal("guide entry change reused stale rules when directory metadata matched")+ }+ if got, want := after.MatchesPath("/storage/av/"+oldName), operation == "add"; got != want {+ t.Fatalf("old guide file ignored = %v, want %v", got, want)+ }+ if got, want := after.MatchesPath("/storage/av/"+newName), operation != "remove"; got != want {+ t.Fatalf("new guide file ignored = %v, want %v", got, want)+ }+ _, reused := mustSyncIgnoreRules(t)+ if reused != after {+ t.Fatal("unchanged guide entries did not reuse the refreshed rules")+ }+ })+ }+}++func TestSyncIgnoreGuideFingerprintUsesRuleNames(t *testing.T) {oldData, oldWorking := util.DataDir, util.WorkingDir- util.DataDir, util.WorkingDir = b.TempDir(), b.TempDir()- b.Cleanup(func() { util.DataDir, util.WorkingDir = oldData, oldWorking })- getSyncIgnoreRules()- getSyncIgnoreRules()- b.Run("cached", func(b *testing.B) {- for b.Loop() {- getSyncIgnoreRules()+ util.DataDir, util.WorkingDir = t.TempDir(), t.TempDir()+ t.Cleanup(func() { util.DataDir, util.WorkingDir = oldData, oldWorking })+ const first = "20260913123456-abcdefg.json"+ const second = "20260913123457-abcdefg.json"+ for _, id := range userGuideIDs[:2] {+ avDir := filepath.Join(util.WorkingDir, "guide", id, "storage", "av")+ for _, name := range []string{second, "unrelated.txt", "invalid.json", first} {+ writeSyncPathTestFile(t, filepath.Join(avDir, name))}- })- b.Run("uncached", func(b *testing.B) {- for b.Loop() {- lines, err := loadSyncIgnoreLines()- if err != nil {- b.Fatal(err)+ }+ stamps, valid := syncIgnoreStamps()+ if !valid {+ t.Fatal("guide fixture could not be read")+ }+ for _, stamp := range stamps {+ if stamp.path == filepath.Join(util.WorkingDir, "guide") {+ if want := first + "\x00" + second; stamp.entries != want {+ t.Fatalf("guide fingerprint = %q, want sorted unique rule names %q", stamp.entries, want)}- ignore.CompileIgnoreLines(lines...)+ return}- })+ }+ t.Fatal("guide fingerprint missing")+}++func TestSyncIgnoreCachedGuideReadFailureRecovers(t *testing.T) {+ oldData, oldWorking := util.DataDir, util.WorkingDir+ util.DataDir, util.WorkingDir = t.TempDir(), t.TempDir()+ t.Cleanup(func() { util.DataDir, util.WorkingDir = oldData, oldWorking })+ avDir := filepath.Join(util.WorkingDir, "guide", userGuideIDs[0], "storage", "av")+ if err := os.MkdirAll(avDir, 0755); err != nil {+ t.Fatal(err)+ }+ mustSyncIgnoreRules(t)+ _, cached := mustSyncIgnoreRules(t)+ _, reused := mustSyncIgnoreRules(t)+ if cached != reused {+ t.Fatal("guide fixture did not cache its rules")+ }+ if err := os.Remove(avDir); err != nil {+ t.Fatal(err)+ }+ writeSyncPathTestFile(t, avDir)+ if _, matcher, err := getSyncIgnoreRules(); err == nil || matcher != nil {+ t.Fatalf("unreadable guide returned cached rules: error=%v, matcher=%v", err, matcher)+ }+ if err := os.Remove(avDir); err != nil {+ t.Fatal(err)+ }+ if err := os.MkdirAll(avDir, 0755); err != nil {+ t.Fatal(err)+ }+ mustSyncIgnoreRules(t)+}++func BenchmarkSyncIgnoreRules(b *testing.B) {+ for _, fixture := range []string{"empty", "bundled-guides"} {+ b.Run(fixture, func(b *testing.B) {+ oldData, oldWorking := util.DataDir, util.WorkingDir+ util.DataDir, util.WorkingDir = b.TempDir(), b.TempDir()+ b.Cleanup(func() { util.DataDir, util.WorkingDir = oldData, oldWorking })+ guideFiles := 0+ if fixture == "bundled-guides" {+ for _, id := range userGuideIDs {+ source := filepath.Join("..", "..", "app", "guide", id, "storage", "av")+ entries, err := os.ReadDir(source)+ if err != nil {+ b.Fatal(err)+ }+ destination := filepath.Join(util.WorkingDir, "guide", id, "storage", "av")+ if err = os.MkdirAll(destination, 0755); err != nil {+ b.Fatal(err)+ }+ for _, entry := range entries {+ name := entry.Name()+ if entry.IsDir() || !strings.HasSuffix(name, ".json") || !ast.IsNodeIDPattern(strings.TrimSuffix(name, ".json")) {+ continue+ }+ // 只复用随包指南的文件名与目录规模,不读取或复制文档内容。+ if err = os.WriteFile(filepath.Join(destination, name), nil, 0644); err != nil {+ b.Fatal(err)+ }+ guideFiles+++ }+ }+ }+ mustSyncIgnoreRules(b)+ _, cached := mustSyncIgnoreRules(b)+ b.Run("cached", func(b *testing.B) {+ b.ReportAllocs()+ for b.Loop() {+ _, matcher := mustSyncIgnoreRules(b)+ if matcher != cached {+ b.Fatal("unchanged benchmark fixture did not hit the cache")+ }+ }+ b.ReportMetric(float64(guideFiles), "guide-files")+ })+ b.Run("uncached", func(b *testing.B) {+ b.ReportAllocs()+ for b.Loop() {+ lines, err := loadSyncIgnoreLines()+ if err != nil {+ b.Fatal(err)+ }+ ignore.CompileIgnoreLines(lines...)+ }+ b.ReportMetric(float64(guideFiles), "guide-files")+ })+ })+ }}func TestSyncIgnoreRepoCompatibility(t *testing.T) {diff --git a/kernel/model/sync_ignore_windows_test.go b/kernel/model/sync_ignore_windows_test.goindex f8f656b2e5..f8c59b0451 100644--- a/kernel/model/sync_ignore_windows_test.go+++ b/kernel/model/sync_ignore_windows_test.go@@ -1,14 +1,12 @@package modelimport (- "errors""os""path/filepath""syscall""testing""github.com/siyuan-note/siyuan/kernel/util"- "golang.org/x/sys/windows")func TestSyncIgnoreReadFailureRecovers(t *testing.T) {@@ -37,12 +35,7 @@ func TestSyncIgnoreReadFailureRecovers(t *testing.T) {syscall.CloseHandle(h)}}()- if _, err = os.Stat(p); err != nil {- t.Fatal(err)- }- if _, readErr := os.ReadFile(p); !errors.Is(readErr, windows.ERROR_SHARING_VIOLATION) {- t.Fatalf("read-denying handle did not produce a sharing violation: %v", readErr)- }+ requireReadSharingViolation(t, p, h)if _, matcher, loadErr := getSyncIgnoreRules(); loadErr == nil || matcher != nil {t.Fatalf("unreadable rules must return an error without a matcher: error=%v, matcher=%v", loadErr, matcher)}