An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:white_check_mark: Repair alpha CI fixtures and preserve failure diagnostics
Daniel4e670ba8ea7b
diff --git a/app/electron/mapHostManager.test.js b/app/electron/mapHostManager.test.jsindex c90b17339d..66a6571222 100644--- a/app/electron/mapHostManager.test.js+++ b/app/electron/mapHostManager.test.js@@ -61,7 +61,7 @@ test("anonymous map session blocks permissions, downloads, credentials and all nconst response = await ses.protocols.http(new Request(origin + "/stage/map/index.html?provider=openfreemap"));assert.equal(await response.text(), "asset");assert.equal(files.length, 1);- assert.equal(files[0], "/app/stage/map/index.html");+ assert.equal(files[0], path.join("/app", "stage/map/index.html"));assert.match(response.headers.get("content-security-policy"), /sandbox allow-scripts/);assert.equal(ses.fetches.length, 0);let headers;diff --git a/app/src/boot/globalEvent/gutterMargin.test.ts b/app/src/boot/globalEvent/gutterMargin.test.tsindex cfeeb98d3a..c09c4f94f7 100644--- a/app/src/boot/globalEvent/gutterMargin.test.ts+++ b/app/src/boot/globalEvent/gutterMargin.test.ts@@ -2,6 +2,7 @@ import * as assert from "node:assert/strict";import {readFileSync} from "node:fs";import {test} from "node:test";import {runInNewContext} from "node:vm";+import {isContainerGutterBridge} from "../../protyle/gutter/container";import {ModuleKind, ScriptTarget, transpileModule} from "typescript";const compiled = transpileModule(readFileSync(__dirname + "/mousemove.ts", "utf8"), {@@ -17,7 +18,7 @@ const fixture = (paddingLeft: string, hasBlock = true) => {const block = {classList: {contains: () => false}, getBoundingClientRect: () => ({left: 196})};const hits: number[][] = [];const rendered: unknown[] = [];- const protyle = {wysiwyg: {element: root}, gutter: {render: (_owner: unknown, target: unknown) => rendered.push(target)}};+ const protyle = {wysiwyg: {element: root}, gutter: {element: {classList: {contains: () => true}}, render: (_owner: unknown, target: unknown) => rendered.push(target)}};const exports = {} as typeof import("./mousemove");runInNewContext(compiled, {exports,@@ -29,6 +30,7 @@ const fixture = (paddingLeft: string, hasBlock = true) => {},getComputedStyle: () => ({paddingLeft}),require: () => ({+ isContainerGutterBridge,hasClosestBlock: (target: unknown) => target,getAllModels: () => ({editor: [{editor: {protyle}}], backlink: [] as unknown[]}),}),diff --git a/app/src/boot/globalEvent/mousemove.test.ts b/app/src/boot/globalEvent/mousemove.test.tsindex 1533f5a045..4bc199fe17 100644--- a/app/src/boot/globalEvent/mousemove.test.ts+++ b/app/src/boot/globalEvent/mousemove.test.ts@@ -54,6 +54,7 @@ const fixture = (location: "editor" | "popover" | "backlink") => {const api: {windowMouseMove: (event: MouseEvent) => void} = {windowMouseMove: () => {}};runInNewContext(source, {exports: api,+ getComputedStyle: () => ({paddingLeft: root.style.paddingLeft}),require: (name: string) => modules[name] || {},window: {siyuan: {layout: {}, blockPanels: location === "popover" ? [{editors: [{protyle}]}] : []}},document: {diff --git a/app/src/config/tabs/ai/aiBuiltinSkillView.test.ts b/app/src/config/tabs/ai/aiBuiltinSkillView.test.tsindex 1d3892b2c6..181201fecc 100644--- a/app/src/config/tabs/ai/aiBuiltinSkillView.test.ts+++ b/app/src/config/tabs/ai/aiBuiltinSkillView.test.ts@@ -24,6 +24,7 @@ class ElementStub {remove: (value: string) => this.classes.delete(value),contains: (value: string) => this.classes.has(value) || this.className.split(" ").includes(value),};+ dispatchEvent(event: Event) { this.events[event.type]?.(event); return true; }append(element: ElementStub) { this.children.push(element); }closest() { return this; }addEventListener(name: string, callback: (event: unknown) => void) { this.events[name] = callback; }@@ -50,6 +51,7 @@ const loadView = (languages: Record<string, string> = new Proxy({}, {get: (_objerunInNewContext(code, {exports,HTMLElement: ElementStub,+ CustomEvent,document: {createElement: () => view},window: {siyuan: {config, languages}},require: (name: string) => {diff --git a/app/src/dialog/tooltipInput.test.ts b/app/src/dialog/tooltipInput.test.tsindex 3902010430..37f1aa928f 100644--- a/app/src/dialog/tooltipInput.test.ts+++ b/app/src/dialog/tooltipInput.test.ts@@ -5,7 +5,7 @@ import {tmpdir} from "node:os";import * as path from "node:path";import {test} from "node:test";import {promisify} from "node:util";-import {compileString} from "sass";+import {compile} from "sass";import {ModuleKind, ScriptTarget, transpileModule} from "typescript";const browserCases = async (sources: string[], css: string) => {@@ -126,7 +126,7 @@ test("touch hover suppression preserves mouse, validation feedback and toolbar lcompilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},}).outputText);const css = ["business/_block.scss", "component/_tooltips.scss", "main/_main.scss"]- .map(file => compileString(readFileSync("src/assets/scss/" + file, "utf8")).css).join("\n");+ .map(file => compile("src/assets/scss/" + file).css).join("\n");const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-touch-hover-test-"));const script = path.join(temporary, "run.cjs");writeFileSync(script, `const {app, BrowserWindow, ipcMain} = require("electron");diff --git a/app/src/protyle/render/av/lunarDate.test.ts b/app/src/protyle/render/av/lunarDate.test.tsindex 7d63e57670..8bebf8ffd6 100644--- a/app/src/protyle/render/av/lunarDate.test.ts+++ b/app/src/protyle/render/av/lunarDate.test.ts@@ -6,7 +6,7 @@ import * as path from "node:path";import {test} from "node:test";import {promisify} from "node:util";import {ModuleKind, ScriptTarget, transpileModule} from "typescript";-import {compileString} from "sass";+import {compile} from "sass";const browserCases = (sources: Record<string, string>, language: Record<string, unknown>, data: unknown, css: string) => {const check: typeof assert = require("node:assert/strict");@@ -234,7 +234,7 @@ test("lunar date controls preserve dates, validate selections, and fit narrow la}const language = JSON.parse(readFileSync("appearance/langs/zh-CN.json", "utf8"));const data = JSON.parse(readFileSync("../kernel/av/lunar_calendar_data.json", "utf8"));- const css = compileString(readFileSync("src/assets/scss/business/_av.scss", "utf8")).css;+ const css = compile("src/assets/scss/business/_av.scss").css;const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-lunar-date-test-"));const script = path.join(temporary, "run.cjs");const args = [sources, language, data, css].map(value => JSON.stringify(value)).join(",");diff --git a/app/src/protyle/util/tableCellRichLute.test.ts b/app/src/protyle/util/tableCellRichLute.test.tsindex 2a3a052484..3c28a6bb94 100644--- a/app/src/protyle/util/tableCellRichLute.test.ts+++ b/app/src/protyle/util/tableCellRichLute.test.ts@@ -502,7 +502,8 @@ const browserCases = async (source: string, enterSource: string, hintSource: strlet oldCode: ReturnType<typeof api.serializeTableCellRich>;const settingCell = document.createElement("td");Object.assign(window.siyuan, {menus: {menu: {- remove: () => { menuItems = []; }, append: () => {}, popup: () => { menuShown++; },+ element: document.createElement("div"),+ remove() { menuItems = []; this.data = undefined; }, append: () => {}, popup: () => { menuShown++; },fullscreen: () => { mobileMenuShown++; },}}});const copyDependencies = {@@ -797,7 +798,7 @@ test("table cells insert code through slash and Enter without losing soft breaksconst start = editor.indexOf('host.addEventListener("keydown", event => {');const end = editor.indexOf("}, {capture: true, signal});", start) + "}, {capture: true, signal});".length;const keydownSource = compile(editor.substring(start, end));- const copySource = ["normalizeText.ts", "../wysiwyg/codeBlockUtil.ts", "../wysiwyg/codeBlock.ts", "../lite/codeActions.ts"]+ const copySource = ["../../menus/menuToggle.ts", "normalizeText.ts", "../wysiwyg/codeBlockUtil.ts", "../wysiwyg/codeBlock.ts", "../lite/codeActions.ts"].map(file => compile(read(file))).join("\n") +"\nbindLiteCodeActions(host, fragment.protyle, {signal, canEdit, beforeChange, onChange: commit});";const selectionSource = compile(read("selectionOffsets.ts")) + "\n" + compile(read("selection.ts")) + "\n" + compile(read("tableCellRichSelection.ts"));diff --git a/app/tests/agentStreamingMarkdown.test.js b/app/tests/agentStreamingMarkdown.test.jsindex 44908a2f24..ee03a139cf 100644--- a/app/tests/agentStreamingMarkdown.test.js+++ b/app/tests/agentStreamingMarkdown.test.js@@ -422,18 +422,20 @@ const runCases = async (sources, css, luteScript) => {check.equal(longBody.querySelector("strong").textContent, "Last");const switching = chatFixture(true);- const run = {};switching.appendToken("# First\n\n**partial**");- switching.prepareSessionRunForDetach(run);- switching.captureSessionRunView(run);- const firstBody = run.viewState.currentAIElement.querySelector(".agent-chat__body");+ switching.prepareRunViewForDetach();+ const state = switching.captureRunViewState();+ switching.captureRunView(state);+ const firstBody = state.currentAIElement.querySelector(".agent-chat__body");switching.currentAIElement = null;switching.currentContent = "";switching.appendToken("# Second");await tick();check.match(switching.messagesContainer.textContent, /Second/);check.doesNotMatch(firstBody.textContent, /Second/);- switching.restoreSessionRunState(run);+ let consumed = false;+ check.equal(switching.restoreRunView(state, () => { consumed = true; }), true);+ check.equal(consumed, true);switching.appendToken(" more");await tick();check.match(switching.messagesContainer.textContent, /partial more/);diff --git a/app/tests/avAttributeCarrier.test.js b/app/tests/avAttributeCarrier.test.jsindex a618d9d171..975fa8c6fb 100644--- a/app/tests/avAttributeCarrier.test.js+++ b/app/tests/avAttributeCarrier.test.js@@ -227,7 +227,7 @@ const runElectron = async () => {extract("openMenuPanel", ["openMenuPanel"]), extract("cell", ["updateCellsValue"]),extract("primaryFocus", ["focusDatabasePrimary"]),extract("rowReadonly", ["inheritDatabaseRowReadonly"]),- extract("../../../editor/databaseRow", ["newDatabaseRowModel"]),+ extract("../../../editor/databaseRow", ["rowReady", "rowSwitchers", "newDatabaseRowModel"]),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/avRichTextEditor.test.js b/app/tests/avRichTextEditor.test.jsindex 8ea75d34b3..7469a3f28c 100644--- a/app/tests/avRichTextEditor.test.js+++ b/app/tests/avRichTextEditor.test.js@@ -40,6 +40,7 @@ const runCases = async (sources) => {"../../../mobile/util/mobileAppUtil": {callMobileAppShowKeyboard: () => {}},"../../hint/extend": {hintRef, hintSlash: () => []},"../../hint/builtinSlash": {registerBuiltinSlashHint: value => value},+ "../../util/selection": {focusBlock: element => element.focus()},"../../toolbar/defaults": {getDefaultToolbar: () => []},"../highlightRender": {highlightRender: () => {}},"../mathRender": {mathRender: () => {}},diff --git a/app/tests/dialogFocus.test.js b/app/tests/dialogFocus.test.jsindex 63ffce45a1..ca41586817 100644--- a/app/tests/dialogFocus.test.js+++ b/app/tests/dialogFocus.test.js@@ -336,7 +336,7 @@ const runFlashcardCases = async (dialogSource, cardSource, mobile) => {}};-const runSearchCases = async (dialogSource, focusSource, searchSource, mobileSource) => {+const runSearchCases = async (dialogSource, focusSource, searchSource, mobileSource, openOptionsSource) => {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",@@ -397,6 +397,7 @@ const runSearchCases = async (dialogSource, focusSource, searchSource, mobileSou};modules["../dialog"] = load(dialogSource);modules["./focus"] = modules["../search/focus"] = load(focusSource);+ modules["./openOptions"] = load(openOptionsSource);const {openSearch} = load(searchSource);const mobile = load(mobileSource);const search = () => openSearch({app: {}, hotkey: "search", notebookId: "box", searchPath: "/doc.sy"});@@ -553,7 +554,8 @@ if (process.versions.electron && process.type === "browser") {await win.webContents.executeJavaScript(`(${runSearchCases.toString()})(${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("command/nativeRuntime.ts", true))},+ ${JSON.stringify(compileSearch("search/openOptions.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 3f6b9334f7..38ecb8242d 100644--- a/app/tests/fixtures/map-webview-boundary/harness.cjs+++ b/app/tests/fixtures/map-webview-boundary/harness.cjs@@ -11,6 +11,18 @@ if (!app || !BrowserWindow) {let remoteRequested = false;const fail = error => {console.error("Map webview prototype startup failed.");+ 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]);+ if (failure.code === "ERR_ASSERTION") {+ const operators = ["strictEqual", "notStrictEqual", "deepStrictEqual", "notDeepStrictEqual", "==", "!=", "fail"];+ console.error("Verification assertion: ERR_ASSERTION" ++ (operators.includes(failure.operator) ? "; operator: " + failure.operator : ""));+ }+ }if (remoteRequested) console.error("Remote map webview verification: FAIL.");const codes = ["attachPreferenceMismatch", "hostAttachFailed", "hostDocumentLoadFailed", "hostDocumentMismatch","hostRendererGone", "hostDestroyed", "hostBootstrapTimeout", "hostSDKTimeout", "documentCSPBlocked",@@ -50,7 +62,7 @@ if (!app || !BrowserWindow) {if (flags.has("--verify")) {try { await verifyHarness(harness); }catch (failure) {- const error = new Error("Fixture verification failed");+ const error = new Error("Fixture verification failed", {cause: failure});error.code = failure?.code === "isolationCheckTimeout" ? "isolationCheckTimeout" : "isolationAssertionFailed";throw error;}diff --git a/app/tests/inlineMathSelection.test.js b/app/tests/inlineMathSelection.test.jsindex 2c4c133ef6..ea911a4b21 100644--- a/app/tests/inlineMathSelection.test.js+++ b/app/tests/inlineMathSelection.test.js@@ -74,7 +74,11 @@ const setupEdge = async (mode) => {}, {once: true});return {before, after, left: {x: rect.left + 0.5, y: after.y},mathEnd: {x: rect.right + 1, y: after.y}, right: {x: rect.right + 1, y: before.y},- width: editable.clientWidth, mathLeft: rect.left, prefixLeft: prefix.getBoundingClientRect().left};+ width: editable.clientWidth, mathLeft: rect.left, prefixLeft: prefix.getBoundingClientRect().left,+ geometry: {mode, requestedWidth: editable.style.width, measuredPrefixWidth: width,+ editable: editable.getBoundingClientRect().toJSON(), math: rect.toJSON(),+ prefixLines: Array.from(prefix.getClientRects(), item => item.toJSON()),+ fontsStatus: document.fonts.status, devicePixelRatio: window.devicePixelRatio}};};const runElectron = async () => {@@ -170,14 +174,14 @@ const runElectron = async () => {for (const direction of mode === "left" ? ["forward", "backward", "cross-line"] : ["forward", "cross-line"]) {const points = await win.webContents.executeJavaScript(`(${setupEdge.toString()})(${JSON.stringify(mode)})`);if (mode === "left") {- assert.ok(Math.abs(points.mathLeft - points.prefixLeft) < 1);+ assert.ok(Math.abs(points.mathLeft - points.prefixLeft) < 1, JSON.stringify(points));await drag(direction === "forward" ? points.left : direction === "backward" ? points.after : points.before,direction === "backward" ? points.left : direction === "forward" ? points.mathEnd : points.after, true);if (direction === "backward") {assert.equal(await win.webContents.executeJavaScript("getSelection().direction"), "backward");}} else {- assert.ok(points.mathLeft > points.prefixLeft + points.width - 30);+ assert.ok(points.mathLeft > points.prefixLeft + points.width - 30, JSON.stringify(points));await drag(direction === "cross-line" ? points.after : points.before,direction === "forward" ? points.right : points.before, true);}diff --git a/app/tests/mapAttribution.test.js b/app/tests/mapAttribution.test.jsindex e165435954..4979d7a40d 100644--- a/app/tests/mapAttribution.test.js+++ b/app/tests/mapAttribution.test.js@@ -3,6 +3,12 @@ const fs = require("node:fs");const os = require("node:os");const path = require("node:path");+const closeTileServer = server => new Promise(resolve => {+ server.close(resolve);+ // 断言可能在刻意挂起的瓦片响应释放之前失败,清理时必须关闭这些连接。+ server.closeAllConnections();+});+const install = (sources, css, controlledClock) => {document.head.innerHTML = "";document.body.innerHTML = '<div id="map" class="maplibregl-map"></div>';@@ -204,8 +210,8 @@ const verifyTileHTTP = async (win, sources, css, sdk) => {assert.deepEqual(state.errors, ["mapUnavailable"]);assert.equal(state.removed, 1, "unclassified SDK errors retain the fatal cleanup path");} finally {- await win.webContents.executeJavaScript("window.tileAdapter?.destroy()");- await new Promise(resolve => server.close(resolve));+ try { await win.webContents.executeJavaScript("window.tileAdapter?.destroy()"); }+ finally { await closeTileServer(server); }}};@@ -324,6 +330,30 @@ 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 fixture cleanup completes even when a failed assertion leaves responses held", async () => {+ const http = require("node:http");+ let response;+ let requestReceived;+ const received = new Promise(resolve => { requestReceived = resolve; });+ const server = http.createServer((_request, incomingResponse) => {+ response = incomingResponse;+ requestReceived();+ });+ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));+ const request = http.get(`http://127.0.0.1:${server.address().port}/tile/0/0/0.png`);+ request.on("error", () => {});+ await received;+ let rescued = false;+ const rescue = setTimeout(() => { rescued = true; response.destroy(); }, 1000);+ try {+ await closeTileServer(server);+ assert.equal(rescued, false, "teardown must close held responses before waiting for the server");+ } finally {+ clearTimeout(rescue);+ request.destroy();+ server.closeAllConnections();+ }+ });test("MapLibre attribution uses its real rounded DOM and supports trusted disclosure and visible display time", {skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY? "Real Electron DOM verification requires DISPLAY or WAYLAND_DISPLAY" : false,diff --git a/app/tests/mapWebviewBoundary.test.js b/app/tests/mapWebviewBoundary.test.jsindex c6ab57d578..8dd5d018d4 100644--- a/app/tests/mapWebviewBoundary.test.js+++ b/app/tests/mapWebviewBoundary.test.js@@ -13,6 +13,35 @@ const {createMapSessionRouter} = require("../electron/mapHostManager");const {createMapContentSecurityPolicy} = require("../electron/mapHostPolicy");const {createRemoteDocumentContentSecurityPolicy} = require("../electron/remoteKernel");+test("verification failures identify the assertion location without exposing probe secrets", async () => {+ const vm = require("node:vm");+ const source = fs.readFileSync(path.join(__dirname, "fixtures/map-webview-boundary/harness.cjs"), "utf8");+ for (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",+ });+ const messages = [];+ let resolveExit;+ const exited = new Promise(resolve => { resolveExit = resolve; });+ vm.runInNewContext(source, {+ process: {argv: ["electron", "harness.cjs", "--synthetic", "--verify"]},+ console: {info() {}, error: value => messages.push(String(value))},+ require: name => name === "electron" ? {+ app: {once() {}, exit: resolveExit}, BrowserWindow: {getAllWindows: () => []},+ } : {+ createTemporaryProfile: () => ({profile: "fixture", cleanup() {}}),+ createHarness: async () => { if (duringSetup) throw failure; return {}; },+ verifyHarness: async () => { throw failure; },+ },+ });+ assert.equal(await exited, 1);+ assert.match(messages.join("\n"), /Verification location: harnessSupport\.cjs:401:12/);+ assert.match(messages.join("\n"), /Verification assertion: ERR_ASSERTION; operator: deepStrictEqual/);+ assert.doesNotMatch(messages.join("\n"), /private|secret-token|https:/);+ }+});+test("remote fixture retains web security and rejects subframes and objects with the production navigation policy", () => {assert.equal(remoteOwnerPreferences.webviewTag, true);assert.equal(remoteOwnerPreferences.webSecurity, true);diff --git a/app/tests/pdfAnnotationCompatibility.test.js b/app/tests/pdfAnnotationCompatibility.test.jsindex 1c9bfbd272..c624c03bb2 100644--- a/app/tests/pdfAnnotationCompatibility.test.js+++ b/app/tests/pdfAnnotationCompatibility.test.js@@ -154,9 +154,29 @@ async function runElectron() {const viewerResults = await win.webContents.executeJavaScript(`(async () => {const {webViewerLoad, getPdfViewerHTML} = await import(${JSON.stringify(treeUrl)});const errors = [];+ const errorDiagnostics = [];+ let phase = "initialize viewers";+ const recordError = message => {+ errors.push(message);+ if (errorDiagnostics.length >= 16) return;+ // 仅在错误发生时记录测试查看器的几何信息,不改变渲染时序。+ errorDiagnostics.push({phase, message, time: performance.now(),+ viewers: Array.from(document.querySelectorAll(".testViewer"), element => {+ const container = element.querySelector("#viewerContainer");+ return {hidden: getComputedStyle(element).display === "none",+ rect: element.getBoundingClientRect().toJSON(),+ container: container?.getBoundingClientRect().toJSON(),+ scroll: container ? [container.scrollLeft, container.scrollTop,+ container.scrollWidth, container.scrollHeight] : null,+ pages: Array.from(element.querySelectorAll(".page"), page => ({+ number: page.dataset.pageNumber, rect: page.getBoundingClientRect().toJSON(),+ scale: getComputedStyle(page).getPropertyValue("--scale-factor"),+ }))};+ })});+ };const originalConsoleError = console.error;- console.error = (...args) => errors.push(args.map(String).join(" "));- const onError = event => errors.push(String(event.error || event.reason || event.message));+ console.error = (...args) => recordError(args.map(String).join(" "));+ const onError = event => recordError(String(event.error || event.reason || event.message));window.addEventListener("error", onError);window.addEventListener("unhandledrejection", onError);const waitFor = (bus, name, predicate = () => true) => new Promise((resolve, reject) => {@@ -192,6 +212,7 @@ async function runElectron() {const viewers = [];try {for (let i = 0; i < 2; i++) {+ phase = "initialize viewer " + i;const element = document.createElement("div");element.className = "testViewer fn__flex-1";if (i === 0) element.classList.add("fn__none");@@ -223,6 +244,7 @@ async function runElectron() {if (page.div.querySelector('input[type="text"]').value !== "form text") throw new Error("Missing text field value");}const {pdf, element} = viewers[1];+ phase = "zoom and rotate";const firstScale = viewers[0].pdf.pdfViewer.currentScale;let rendered = waitFor(pdf.eventBus, "pagerendered");pdf.zoomIn();@@ -232,6 +254,7 @@ async function runElectron() {pdf.rotatePages(90);await rendered;const found = waitFor(pdf.eventBus, "updatefindmatchescount", data => data.matchesCount.total === 2);+ phase = "search and sidebar";pdf.eventBus.dispatch("find", {source: null, type: "", query: "Hello", caseSensitive: false,entireWord: true, highlightAll: true, findPrevious: false, matchDiacritics: false});await found;@@ -242,6 +265,7 @@ async function runElectron() {if (!thumbnail.image.src.startsWith("blob:")) throw new Error("Missing thumbnail image");if (parseFloat(getComputedStyle(thumbnail.image).width) !== thumbnail.canvasWidth) throw new Error("Invalid thumbnail width");await pdf.pdfDocumentProperties.open();+ phase = "document properties and page navigation";if (element.querySelector("#pageCountField").textContent !== "2") throw new Error("Missing document properties");await pdf.pdfDocumentProperties.close();const secondPage = pdf.pdfViewer.getPageView(1);@@ -253,6 +277,7 @@ async function runElectron() {throw new Error("Missing PDF UserUnit scale");}element.style.width = "375px";+ phase = "resize and pinch";pdf.pdfViewer.currentScaleValue = "page-width";const scaleBeforePinch = pdf.pdfViewer.currentScale;pdf.touchPinchCallback([180, 200], 100, 150, 0, 0);@@ -266,12 +291,14 @@ async function runElectron() {throw new Error("Deferred PDF navigation timed out");};pdf.pdfSidebar.close();+ phase = "hide and queue navigation";pdf.rotatePages(-90);pdf.pdfLinkService.goToPage(1);element.classList.add("fn__none");pdf.pdfLinkService.setHash("page=1&zoom=150,0,50");pdf.pdfLinkService.setHash("page=2&zoom=150,0,100");await new Promise(resolve => setTimeout(resolve, 50));+ phase = "show and resolve deferred navigation";element.classList.remove("fn__none");await waitUntil(() => pdf.pdfViewer.currentPageNumber === 2 &&pdf.pdfViewer.currentScale === 1.5 && pdf.pdfViewer.container.scrollTop > 0);@@ -281,11 +308,12 @@ async function runElectron() {throw new Error("Deferred PDF destination differs from visible navigation");}element.classList.add("fn__none");+ phase = "destroy with deferred navigation";pdf.pdfLinkService.setHash("page=1&zoom=200,0,50");await pdf.destroy();element.classList.remove("fn__none");await new Promise(resolve => setTimeout(resolve, 100));- return {count: viewers.length, pages: viewers[0].pdf.pagesCount, errors};+ return {count: viewers.length, pages: viewers[0].pdf.pagesCount, errors, errorDiagnostics};} finally {for (const {pdf, element} of viewers) { await pdf.destroy(); element.remove(); }URL.revokeObjectURL(url);@@ -294,7 +322,8 @@ async function runElectron() {console.error = originalConsoleError;}})()`);- assert.deepEqual(viewerResults, {count: 2, pages: 2, errors: []});+ const {errorDiagnostics, ...viewerState} = viewerResults;+ assert.deepEqual(viewerState, {count: 2, pages: 2, errors: []}, JSON.stringify(errorDiagnostics));} catch (error) {console.error(error);exitCode = 1;diff --git a/app/tests/pdfViewerBundle.cjs b/app/tests/pdfViewerBundle.cjsindex 4086c6dcf2..f903918e6e 100644--- a/app/tests/pdfViewerBundle.cjs+++ b/app/tests/pdfViewerBundle.cjs@@ -43,7 +43,7 @@ module.exports = async ({annotations = false} = {}) => {},bundle: true, write: false, format: "esm", platform: "browser",plugins: [{name: "siyuan-test-boundaries", setup(build) {- build.onResolve({filter: /.*/}, args => annotations && args.importer.endsWith("/asset/anno.ts") && Object.hasOwn(annotationMocks, args.path)+ build.onResolve({filter: /.*/}, args => annotations && args.importer.replaceAll("\\", "/").endsWith("/asset/anno.ts") && Object.hasOwn(annotationMocks, args.path)? {path: args.path, namespace: "siyuan-annotation-mock"} : undefined);build.onLoad({filter: /.*/, namespace: "siyuan-annotation-mock"}, args => ({contents: annotationMocks[args.path], loader: "js"}));build.onResolve({filter: /.*/}, args => Object.hasOwn(mocks, args.path)diff --git a/app/tests/settingsNotifications.test.js b/app/tests/settingsNotifications.test.jsindex eea12d2fb5..2e07d2b8cd 100644--- a/app/tests/settingsNotifications.test.js+++ b/app/tests/settingsNotifications.test.js@@ -54,6 +54,7 @@ for (const file of ["src/index.ts", "src/window/index.ts", "src/mobile/util/onMerunInNewContext(compile(`let zoomRevision = 0; const applyZoom = () => {}; ${storageChanged}export const receive = data => {switch(data.cmd){${clauses.join("\n")}}};`), {exports: receiver, window, ...preference,+ onPageScrollButtonsStorageChanged() {},onWindowWorkspaceStorageChanged: key => platformCalls.push(key),MOBILE_BARS_CONFIG_KEY: "mobile-bars", Constants: {LOCAL_MOBILE_BOTTOM_BAR: "mobile-bottom", LOCAL_MOBILE_SIDE_PANEL: "mobile-side"},showMobileBars: () => platformCalls.push("bars"), renderMobileBottomBar: () => platformCalls.push("bottom"),diff --git a/app/tests/settingsWindow.test.js b/app/tests/settingsWindow.test.jsindex 5b6e5e4a59..c9efa51a04 100644--- a/app/tests/settingsWindow.test.js+++ b/app/tests/settingsWindow.test.js@@ -124,7 +124,12 @@ const bootChild = async (sources) => {});check.equal(typeof window.Lute, "undefined");const pluginEvents = [];+ const hoverInput = loadRendererModule(sources.hoverInput, {+ "../protyle/util/compatibility": {isInIOS: () => false},+ "./touchActivation": {},+ });const {initTooltips} = loadRendererModule(sources.tooltip, {+ "../util/hoverInput": hoverInput,"../util/functions": {isMobile: () => false},"../plugin/EventBusCore": {emitToPlugins: name => pluginEvents.push(name),forEachPluginSubscriber: (name, callback) => callback({emit: () => pluginEvents.push(name)})},@@ -445,7 +450,7 @@ if (process.versions.electron && process.type === "browser") {native: "config/setting/nativeWindow.ts", fit: "config/setting/windowDialog.ts", controls: "boot/windowControls.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",- bazaarPath: "config/bazaar/openPath.ts", tooltip: "dialog/tooltip.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") {source = require("ifdef-loader/preprocessor").parse(source, {MOBILE: false, BROWSER: false}, false, true);diff --git a/app/tests/taskStatus.test.js b/app/tests/taskStatus.test.jsindex 0b386b6366..f3b006f299 100644--- a/app/tests/taskStatus.test.js+++ b/app/tests/taskStatus.test.js@@ -191,7 +191,7 @@ const cases = async source => {openedMenu.items.find(item => item.id === "taskStatusInProgress").click();check.equal(api.getTabTask(menuFixture.item), "/");protyle.disabled = true;- openTabMenu(protyle, menuFixture.from, menuFixture.item, menuFixture.item);+ openTabMenu(protyle, menuFixture.from, menuFixture.item, menuFixture.item, false);check.deepEqual(openedMenu.items.map(item => item.icon), ["iconCopy", "iconEnter"]);openedMenu.items.find(item => item.icon === "iconEnter").click();check.equal(focusedTab.protyle, protyle);diff --git a/app/tests/textSelectionContextMenu.test.js b/app/tests/textSelectionContextMenu.test.jsindex 3ceea529be..cb2c566bca 100644--- a/app/tests/textSelectionContextMenu.test.js+++ b/app/tests/textSelectionContextMenu.test.js@@ -42,9 +42,11 @@ const sources = () => {return false;}).join("\n");};+ const touchSelection = readFileSync(path.join(__dirname, "../src/protyle/wysiwyg/touchBlockSelection.ts"), "utf8")+ .replace(/^import .*;\r?\n/gm, "").replaceAll("export const ", "const ");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, mobile), {+ range.getText(selection).replace("export ", "") + "\n" + wordSelection + "\n" + touchSelection, mobile), {compilerOptions: {target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS},}).outputText);};diff --git a/kernel/model/file_corrupted_windows_test.go b/kernel/model/file_corrupted_windows_test.goindex e3f8c5745f..2505b7b3c4 100644--- a/kernel/model/file_corrupted_windows_test.go+++ b/kernel/model/file_corrupted_windows_test.go@@ -1,13 +1,16 @@package modelimport (+ "errors""os""path/filepath""syscall""testing"+ "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) {@@ -15,8 +18,15 @@ func TestDocIALSharingViolationRecovers(t *testing.T) {originalWorkspace := util.WorkspaceDirutil.WorkspaceDir = t.TempDir()t.Cleanup(func() { util.WorkspaceDir = originalWorkspace })- filePath := filepath.Join(util.DataDir, fixture.box.ID, fixture.sourcePath)- cache.RemoveDocIAL(fixture.sourcePath)+ // 直接写入独立文档,避免建树时的异步缓存写入覆盖测试前的清理。+ id := ast.NewNodeID()+ document := "/" + id + ".sy"+ filePath := filepath.Join(util.DataDir, fixture.box.ID, document)+ raw := []byte(`{"Type":"NodeDocument","Properties":{"id":"` + id + `","title":"Source"}}`)+ if err := os.WriteFile(filePath, raw, 0644); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { cache.RemoveDocIALInBox(document, fixture.box.ID) })ptr, err := syscall.UTF16PtrFromString(filePath)if err != nil {t.Fatal(err)@@ -35,7 +45,13 @@ func TestDocIALSharingViolationRecovers(t *testing.T) {if _, err = os.Stat(filePath); err != nil {t.Fatal(err)}- if attrs := fixture.box.docIAL(fixture.sourcePath); attrs != nil {+ 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)+ }+ if attrs := cache.GetDocIALInBox(document, fixture.box.ID); attrs != nil {+ t.Fatalf("sharing-violation fixture unexpectedly has cached attributes: %v", attrs)+ }+ if attrs := fixture.box.docIAL(document); attrs != nil {t.Fatalf("unreadable file returned attributes: %v", attrs)}if _, err = os.Stat(filepath.Join(util.WorkspaceDir, "corrupted")); !os.IsNotExist(err) {@@ -45,7 +61,7 @@ func TestDocIALSharingViolationRecovers(t *testing.T) {t.Fatal(err)}closed = true- if attrs := fixture.box.docIAL(fixture.sourcePath); attrs["title"] != "Source" {+ if attrs := fixture.box.docIAL(document); attrs["title"] != "Source" {t.Fatalf("document did not recover after sharing violation: %v", attrs)}}diff --git a/kernel/model/sync_ignore_windows_test.go b/kernel/model/sync_ignore_windows_test.goindex 54457a95e7..f8f656b2e5 100644--- a/kernel/model/sync_ignore_windows_test.go+++ b/kernel/model/sync_ignore_windows_test.go@@ -1,12 +1,14 @@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) {@@ -18,6 +20,8 @@ func TestSyncIgnoreReadFailureRecovers(t *testing.T) {if err := os.WriteFile(p, []byte("/private/**/*"), 0644); err != nil {t.Fatal(err)}+ invalidateSyncIgnoreRules(p)+ t.Cleanup(func() { invalidateSyncIgnoreRules(p) })ptr, err := syscall.UTF16PtrFromString(p)if err != nil {t.Fatal(err)@@ -36,8 +40,11 @@ func TestSyncIgnoreReadFailureRecovers(t *testing.T) {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)+ }if _, matcher, loadErr := getSyncIgnoreRules(); loadErr == nil || matcher != nil {- t.Fatal("unreadable rules must return an error without a matcher")+ t.Fatalf("unreadable rules must return an error without a matcher: error=%v, matcher=%v", loadErr, matcher)}if !PathsAffectSync(filepath.Join(util.DataDir, "private", "secret.txt")) {t.Fatal("read failure must conservatively schedule sync")diff --git a/kernel/util/path_namespace_test.go b/kernel/util/path_namespace_test.goindex 85d1f0c24c..b996d4459a 100644--- a/kernel/util/path_namespace_test.go+++ b/kernel/util/path_namespace_test.go@@ -37,20 +37,29 @@ func TestIsSensitivePathNamespaceAlias(t *testing.T) {tempDir := filepath.Join(WorkspaceDir, "temp")dataDir := filepath.Join(WorkspaceDir, "data")- for _, test := range []struct {+ type pathCase struct {name stringpath stringsensitive bool- }{+ }+ tests := []pathCase{{"普通路径的 conf 目录", confDir, true},- {"扩展长度前缀的 conf 目录", `\\?\` + confDir, true},- {"反斜杠前缀的家目录凭据", `\\?\` + filepath.Join(HomeDir, ".ssh", "id_rsa"), true},+ {"普通路径的家目录凭据", filepath.Join(HomeDir, ".ssh", "id_rsa"), true},{"普通路径的 temp 目录", filepath.Join(tempDir, "private.txt"), true},- {"扩展长度前缀的 temp 目录", `\\?\` + filepath.Join(tempDir, "private.txt"), true},{"temp/export 仍允许导出", filepath.Join(tempDir, "export", "document.pdf"), false},- {"扩展长度前缀的 temp/export 仍允许导出", `\\?\` + filepath.Join(tempDir, "export", "document.pdf"), false},- {"扩展长度前缀的工作空间资源", `\\?\` + filepath.Join(dataDir, "assets", "image.png"), false},- } {+ {"普通路径的工作空间资源", filepath.Join(dataDir, "assets", "image.png"), false},+ }+ // Windows 命名空间前缀不能拼接到 POSIX 路径作为同位置别名。+ if runtime.GOOS == "windows" {+ tests = append(tests, []pathCase{+ {"扩展长度前缀的 conf 目录", `\\?\` + confDir, true},+ {"反斜杠前缀的家目录凭据", `\\?\` + filepath.Join(HomeDir, ".ssh", "id_rsa"), true},+ {"扩展长度前缀的 temp 目录", `\\?\` + filepath.Join(tempDir, "private.txt"), true},+ {"扩展长度前缀的 temp/export 仍允许导出", `\\?\` + filepath.Join(tempDir, "export", "document.pdf"), false},+ {"扩展长度前缀的工作空间资源", `\\?\` + filepath.Join(dataDir, "assets", "image.png"), false},+ }...)+ }+ for _, test := range tests {t.Run(test.name, func(t *testing.T) {if got := IsSensitivePath(test.path); got != test.sensitive {t.Errorf("IsSensitivePath(%q) = %v, want %v", test.path, got, test.sensitive)