An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:recycle: Unify local and remote map webviews https://github.com/siyuan-note/siyuan/issues/20129
Daniel3fe405e242ed
diff --git a/app/electron/main.js b/app/electron/main.jsindex 2051f3de30..efdc21d8a5 100644--- a/app/electron/main.js+++ b/app/electron/main.js@@ -21,7 +21,6 @@ const {net,app,BrowserWindow,- WebContentsView,MessageChannelMain,Notification,shell,@@ -131,6 +130,7 @@ const notebookSystemLock = createNotebookSystemLock({});const windowKernelTargets = new Map();const initializedWindowIds = new Set();+let mapHostManager;const pendingWindowIds = new Set();createSettingsTaskBridge({ipcMain,@@ -1385,6 +1385,8 @@ const getKernelTarget = (target = kernelPort) => {const rememberWindowKernelTarget = (window, target) => {const webContentsId = window.webContents.id;windowKernelTargets.set(webContentsId, target);+ // 在首次加载前登记宿主,远程窗口仅允许已授权的内置地图 guest。+ mapHostManager.registerOwner(window.webContents);blockDragWindowFocusOrder.set(webContentsId, ++blockDragWindowFocusSequence);window.on("focus", () => {blockDragWindowFocusOrder.set(webContentsId, ++blockDragWindowFocusSequence);@@ -1396,10 +1398,6 @@ const rememberWindowKernelTarget = (window, target) => {writeLog("blocked subframe navigation in remote kernel mode [url=" + event.url + "]");}});- window.webContents.on("will-attach-webview", (event) => {- event.preventDefault();- writeLog("blocked webview creation in remote kernel mode");- });}window.webContents.on("did-start-navigation", (details) => {if (details.isMainFrame && !details.isSameDocument) {@@ -2189,7 +2187,7 @@ const initMainWindow = (kernel = kernelPort, remoteAuthenticated = true) => {nodeIntegration: true,nodeIntegrationInSubFrames: false,nodeIntegrationInWorker: false,- webviewTag: kernelTarget.mode !== "remote",+ webviewTag: true,webSecurity: kernelTarget.mode === "remote",...(kernelTarget.mode === "remote" ? {session: getRemoteSession(kernelTarget)} : {}),contextIsolation: false,@@ -2928,7 +2926,7 @@ const initRemoteKernel = async (target) => {};app.whenReady().then(() => {- createMapHostManager({app, ipcMain, session, BrowserWindow, WebContentsView, MessageChannelMain, appDir,+ mapHostManager = createMapHostManager({app, ipcMain, session, BrowserWindow, MessageChannelMain, appDir,getTarget: id => getWindowKernelTarget(id), isInitialized: id => initializedWindowIds.has(id)});const startupStartedAt = Date.now();writeLog("app ready, preparing startup window");@@ -3911,7 +3909,7 @@ app.whenReady().then(() => {nodeIntegration: true,nodeIntegrationInSubFrames: false,nodeIntegrationInWorker: false,- webviewTag: kernelTarget.mode !== "remote",+ webviewTag: true,webSecurity: kernelTarget.mode === "remote",...(kernelTarget.mode === "remote" ? {session: getRemoteSession(kernelTarget)} : {}),autoplayPolicy: "user-gesture-required" // 桌面端禁止自动播放多媒体 https://github.com/siyuan-note/siyuan/issues/7587diff --git a/app/electron/mapHostDiagnostics.js b/app/electron/mapHostDiagnostics.jsindex cfe8aed51d..88f68f6acd 100644--- a/app/electron/mapHostDiagnostics.js+++ b/app/electron/mapHostDiagnostics.js@@ -4,8 +4,7 @@ const mapDiagnosticCodes = Object.freeze(["hostSetupFailed", "assetUnavailable", "documentLoadFailed", "bootstrapTimeout", "sdkTimeout","providerRequestDenied", "providerInsecureRequest", "providerHTTPFailure", "providerNetworkFailure","cspScript", "cspWorker", "cspConnect", "cspImage", "cspStyle", "cspEval", "cspWasm",- "storageUnavailable", "webglUnavailable", "geometryInvalid", "geometryLogicalBounds",- "geometryCropBounds", "geometryWindowBounds", "geometryRoundedEmpty",+ "storageUnavailable", "webglUnavailable",]);const mapCSPDiagnosticCodes = Object.freeze(["cspScript", "cspWorker", "cspConnect", "cspImage", "cspStyle", "cspEval", "cspWasm"]);const mapCSPResourceCodes = Object.freeze([diff --git a/app/electron/mapHostManager.js b/app/electron/mapHostManager.jsindex 28087bf02d..2bccf004a2 100644--- a/app/electron/mapHostManager.js+++ b/app/electron/mapHostManager.js@@ -5,13 +5,11 @@const path = require("node:path");const fs = require("node:fs/promises");const {randomBytes} = require("node:crypto");-const {createManager: createUnplacedManager} = require("./mapUnplaced/manager");-const {CHANNEL: UNPLACED_CHANNEL, keys: hasUnplacedKeys} = require("./mapUnplaced/policy");const {hardenMapWebviewPreferences, isMapWebviewAttachment, getMapWebviewPreferenceMismatch} = require("./mapWebviewHost");const {mapDiagnosticCodes, mapCSPDiagnosticCodes, isMapCSPResource, MAX_MAP_DIAGNOSTICS, classifyMapConsoleMessage,classifyMapCSPResources} = require("./mapHostDiagnostics");const {- hasUnsafeMapSwitches, normalizeMapOrigin, parseMapCreate, parseMapCommand, parseMapReply, parseMapGeometry,+ hasUnsafeMapSwitches, normalizeMapOrigin, parseMapCreate, parseMapCommand, parseMapReply,isAllowedMapProviderURL, getMapRequestPolicy, createMapContentSecurityPolicy,} = require("./mapHostPolicy");@@ -182,7 +180,7 @@ const createMapSessionRouter = ({ses, origin, appDir, readFile = fs.readFile, tr};};-const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContentsView, MessageChannelMain,+const createMapHostManager = ({app, ipcMain, session, BrowserWindow, MessageChannelMain,getTarget, isInitialized, appDir, readFile, randomID = () => randomBytes(24).toString("hex")}) => {const hosts = new Map();const attachmentOwners = new WeakSet();@@ -219,58 +217,38 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContentsreturn {reason: "unsupportedDocument"};}} catch (_error) { return {reason: "invalidDocument"}; }- return {owner: {win, origin, mode: target.mode === "local" ? "webview" : "native"}};+ return {owner: {win, origin, mode: "webview", kernelMode: target.mode}};};const trustedOwner = event => inspectOwner(event).owner;const getHost = (event, value) => {- const owner = trustedOwner(event);- if (!owner || value?.version !== 1 || typeof value.instanceID !== "string") return;+ if (!event?.sender || value?.version !== 1 || typeof value.instanceID !== "string") return;const host = hosts.get(event.sender.id + ":" + value.instanceID);- if (host && !host.destroyed && host.owner === event.sender && host.win === owner.win &&- host.origin === owner.origin && host.mode === owner.mode && host.frame === event.senderFrame) return host;+ if (!host || host.destroyed || host.owner !== event.sender || host.frame !== event.senderFrame) return;+ const owner = trustedOwner(event);+ if (owner && host.win === owner.win && host.origin === owner.origin &&+ host.mode === owner.mode && host.kernelMode === owner.kernelMode) return host;+ // 切换内核目标后,即使两者都使用 webview,也不能复用原来的隔离会话和端口。+ destroy(host);};const sendOwner = (host, reply) => {if (!host.destroyed && !host.owner.isDestroyed()) {try { host.owner.send("siyuan-map-reply", reply); } catch (_error) { destroy(host); }}};- const setVisible = (host, visible, updateNative = true) => {- if (host.mode === "webview") {- host.visible = visible && host.ready && host.win.isVisible() && !host.win.isMinimized();- if (!host.visible) host.attributionGestureUntil = 0;- const visibility = host.visible ? host.visibility : {visible: false};- const key = JSON.stringify(visibility);- if (host.ready && key !== host.lastVisibility) {- host.lastVisibility = key;- post(host, {version: 1, instanceID: host.init.instanceID, type: "visibility", ...visibility});- }- return;- }- if (updateNative && !host.view.webContents.isDestroyed()) host.view.setVisible(visible);- if (!visible) host.attributionGestureUntil = 0;- host.visible = visible;- // 原生视口已裁剪并平移 #map,此处不能再次叠加 crop。- const obscured = [...hosts.values()].some(item => item.win === host.win && item.unplaced?.inspect()?.ready);- // 可信菜单独立叠在原生地图之上,保留地图绘制,但遮挡期间不能累计署名可见时间。- if (obscured) host.attributionGestureUntil = 0;- const visibility = visible ? {visible: true, ...(!obscured && {viewport: {x: 0, y: 0,- width: host.geometry.bounds.width / host.geometry.zoom, height: host.geometry.bounds.height / host.geometry.zoom}})} :- {visible: false};+ const setVisible = (host, visible) => {+ host.visible = visible && host.ready && host.win.isVisible() && !host.win.isMinimized();+ if (!host.visible) host.attributionGestureUntil = 0;+ const visibility = host.visible ? host.visibility : {visible: false};const key = JSON.stringify(visibility);if (host.ready && key !== host.lastVisibility) {host.lastVisibility = key;post(host, {version: 1, instanceID: host.init.instanceID, type: "visibility", ...visibility});}};- const hide = host => {- host.unplaced?.dismiss("map-hidden");- host.geometry = undefined;- setVisible(host, false);- };+ const hide = host => setVisible(host, false);const destroy = host => {if (!host || host.destroyed) return;host.destroyed = true;- host.unplaced?.destroy();clearTimeout(host.timer);hosts.delete(host.key);for (const [emitter, name, listener] of host.listeners) emitter.removeListener(name, listener);@@ -280,10 +258,7 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContentsfor (const port of [host.port, host.transferredPort]) {try { port?.close(); } catch (_error) { /* 端口已转移或关闭。 */ }}- try {- if (host.view && !host.win.isDestroyed()) host.win.contentView.removeChildView(host.view);- } catch (_error) { /* 移除失败也必须关闭渲染器。 */ }- // 移除视图不会销毁 WebContents,必须实际关闭 SDK 渲染器。+ // 移除 DOM 不保证销毁 WebContents,必须实际关闭 SDK 渲染器。if (host.contents && !host.contents.isDestroyed()) {try { host.contents.stop(); } catch (_error) { /* 仍尝试关闭。 */ }try { host.contents.close({waitForBeforeUnload: false}); } catch (_error) { /* 渲染器可能已关闭。 */ }@@ -316,94 +291,23 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContentstry { host.port.postMessage(message); } catch (_error) { fail(host, "hostOperationFailed"); }}};- const applyGeometry = host => {- if (host.mode === "webview") {- setVisible(host, host.visibility?.visible === true, false);- return;- }- const geometry = host.geometry;- if (!geometry?.visible || host.destroyed) return;- // SDK 初始化也需要非零尺寸;设置已校验的几何不等于允许显示原生视图。- host.view.webContents.setZoomFactor(geometry.zoom);- host.view.setBounds(geometry.bounds);- if (host.loaded) {- host.view.webContents.send("siyuan-map-viewport", {logicalSize: geometry.logicalSize, crop: geometry.crop});- }- if (!host.ready || !host.win.isVisible() || host.win.isMinimized()) {- setVisible(host, false);- return;- }- setVisible(host, true);- post(host, {version: 1, instanceID: host.init.instanceID, type: "resize"});- };- const dismissUnplaced = (win, reason) => {- for (const host of hosts.values()) if (host.win === win) host.unplaced?.dismiss(reason);- };- const refreshMenuVisibility = win => {- for (const host of hosts.values()) {- if (host.win !== win || host.destroyed) continue;- host.attributionGestureUntil = 0;- if (host.geometry) setVisible(host, host.visible, false);- }- };- const unplacedFor = host => {- if (host.mode !== "native") return;- if (host.unplaced) return host.unplaced;- const send = value => {- if (host.owner.isDestroyed() || host.frame !== host.owner.mainFrame) return;- try { host.owner.send("siyuan-map-unplaced-reply", {version: 1, instanceID: host.init.instanceID, ...value}); }- catch (_error) { host.unplaced?.dismiss("owner-unavailable"); }- };- host.unplaced = createUnplacedManager({ipcMain, session, WebContentsView, owner: host.owner, win: host.win,- ownerURL: host.frame.url, assets: {controlsPath: path.join(appDir, "stage/build/map/unplaced-controls.css")},- randomID, readFile, handleActions: false,- mayUse: () => getHost({sender: host.owner, senderFrame: host.frame}, host.init) === host && host.ready &&- host.visible && !host.view.webContents.isDestroyed() && !hasUnsafeMapSwitches(app.commandLine),- onAction: ({type, ...action}) => send({type: "action", action: type, ...action}),- onClose: value => send({type: "closed", ...value}),- onVisibility: () => refreshMenuVisibility(host.win)});- return host.unplaced;- };- ipcMain.handle("siyuan-map-unplaced-open", (event, value) => {- const host = getHost(event, value);- if (!host || host.mode !== "native" || !host.ready || !host.visible ||- !hasUnplacedKeys(value, ["version", "instanceID", "state", "anchor"])) return;- try {- // 同一窗口最多一个菜单,新菜单不会改变任何地图的相机或原生可见性。- dismissUnplaced(host.win, "replace");- const sessionID = unplacedFor(host).open(event, {state: value.state, anchor: value.anchor});- return sessionID ? {version: 1, instanceID: host.init.instanceID, sessionID} : undefined;- } catch (_error) { host.unplaced?.dismiss("operation-failed"); }- });- for (const [name, method, field] of [["update", "update", "state"], ["anchor", "setAnchor", "anchor"],- ["theme", "setTheme", "theme"], ["close", "close", "reason"]]) {- ipcMain.on("siyuan-map-unplaced-" + name, (event, value) => {- const host = getHost(event, value);- if (!host || !hasUnplacedKeys(value, ["version", "instanceID", "sessionID", field])) return;- try { host.unplaced?.[method](event, {sessionID: value.sessionID, [field]: value[field]}); }- catch (_error) { host.unplaced?.dismiss("operation-failed"); }- });- }- ipcMain.on(UNPLACED_CHANNEL + "-action", (event, value) => {- for (const host of hosts.values()) {- if (host.unplaced?.inspect()?.view.webContents !== event.sender) continue;- try { host.unplaced.action(event, value); }- catch (_error) { host.unplaced.dismiss("operation-failed"); }- return;- }- });+ const applyVisibility = host => setVisible(host, host.visibility?.visible === true);const currentWebviewOwner = host => host.mode === "webview" && !hasUnsafeMapSwitches(app.commandLine) &&getHost({sender: host.owner, senderFrame: host.frame}, host.init) === host;const closeMapGuest = contents => {try { contents.setWindowOpenHandler(() => ({action: "deny"})); } catch (_error) { /* 对象可能已被前序监听器销毁。 */ }try { if (!contents.isDestroyed()) contents.close({waitForBeforeUnload: false}); } catch (_error) { /* 会话路由仍保持拒绝。 */ }};- const installAttachmentOwner = owner => {+ // 由主进程在加载窗口文档前调用,远程窗口自首次执行页面脚本起默认拒绝 webview。+ const registerOwner = owner => {if (attachmentOwners.has(owner)) return;attachmentOwners.add(owner);const beforeAttach = (event, preferences, params) => {- // 仅接管保留的地图分区,其余插件和文档 webview 保留原有行为。- if (typeof params?.partition !== "string" || !params.partition.startsWith("siyuan-map-")) return;+ // 本地普通 webview 保留既有行为;远程或未登记目标只能使用主进程保留的地图分区。+ if (typeof params?.partition !== "string" || !params.partition.startsWith("siyuan-map-")) {+ if (getTarget(owner.id)?.mode !== "local") event.preventDefault();+ return;+ }const host = [...hosts.values()].find(item => item.partition === params.partition);if (!host || host.owner !== owner || event.sender !== owner || !currentWebviewOwner(host) ||host.attachmentAccepted || !isMapWebviewAttachment(params, host)) {@@ -429,7 +333,11 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContentsconst didAttach = (_event, contents) => {let host, mapGuest = false;try {- if (contents.isDestroyed() || !webviewSessions.has(contents.session)) return;+ if (contents.isDestroyed()) return;+ if (!webviewSessions.has(contents.session)) {+ if (getTarget(owner.id)?.mode !== "local") closeMapGuest(contents);+ return;+ }mapGuest = true;host = [...hosts.values()].find(item => item.contents === contents);if (!host || !currentWebviewOwner(host) || host.attachmentVerified || contents.hostWebContents !== owner ||@@ -454,7 +362,12 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContentsapp.on("web-contents-created", (_event, contents) => {let host, mapGuest = false, ownsReservation = false;try {- if (contents.isDestroyed() || contents.getType() !== "webview" || !webviewSessions.has(contents.session)) return;+ if (contents.isDestroyed() || contents.getType() !== "webview") return;+ if (!webviewSessions.has(contents.session)) {+ const owner = contents.hostWebContents;+ if (owner && attachmentOwners.has(owner) && getTarget(owner.id)?.mode !== "local") closeMapGuest(contents);+ return;+ }mapGuest = true;host = [...hosts.values()].find(item => item.session === contents.session);ownsReservation = !!host && !host.contents && contents.hostWebContents === host.owner && host.attachmentAccepted;@@ -482,11 +395,11 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContentsif (!owner || !init) throw new Error("Invalid map host owner or configuration");if (hasUnsafeMapSwitches(app.commandLine)) return {version: 1, instanceID: init.instanceID, error: "unsupportedEnvironment"};const key = event.sender.id + ":" + init.instanceID;+ getHost(event, init);if (hosts.has(key) || hosts.size >= 32 || [...hosts.values()].filter(host => host.owner === event.sender).length >= 8) {return {version: 1, instanceID: init.instanceID, error: "hostLimitReached"};}- let host, router, view, ses;- let creationFailure = "hostSetupFailed";+ let host, router, ses;const report = (code, resource) => {if (!host || host.destroyed || !mapDiagnosticCodes.includes(code) ||resource !== undefined && (!mapCSPDiagnosticCodes.includes(code) || !isMapCSPResource(resource))) return;@@ -501,15 +414,10 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContentsconst partition = "siyuan-map-" + randomID();ses = session.fromPartition(partition, {cache: false});router = createMapSessionRouter({ses, origin: owner.origin, appDir, readFile, trackFetch, report});- if (owner.mode === "native") view = new WebContentsView({webPreferences: {session: ses, sandbox: true, contextIsolation: true,- webSecurity: true, nodeIntegration: false, nodeIntegrationInSubFrames: false,- nodeIntegrationInWorker: false, webviewTag: false, allowRunningInsecureContent: false,- navigateOnDragDrop: false, safeDialogs: true, disableDialogs: true, devTools: false,- spellcheck: false, backgroundThrottling: false, preload: path.join(__dirname, "mapHostPreload.js")}});const nonce = randomID();const entryURL = owner.origin + "/stage/map/index.html?provider=openfreemap#" + init.instanceID + ":" + nonce;host = {key, init, owner: event.sender, frame: event.senderFrame, win: owner.win, origin: owner.origin, diagnostics: new Set(), report,- mode: owner.mode, session: ses, partition, entryURL, view, router, listeners: [], ids: new Set(), revision: -1,+ mode: owner.mode, kernelMode: owner.kernelMode, session: ses, partition, entryURL, router, listeners: [], ids: new Set(), revision: -1,loaded: false, ready: false, bootstrapped: false, destroyed: false,visible: false, attributionGestureUntil: 0};hosts.set(key, host);@@ -520,15 +428,9 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContentsif (details.isMainFrame && !details.isSameDocument) destroy(host);});for (const name of ["hide", "minimize"]) listen(host, owner.win, name, () => hide(host));- if (host.mode === "native") {- for (const name of ["resize", "enter-full-screen", "leave-full-screen"]) {- listen(host, owner.win, name, () => hide(host));- }- listen(host, event.sender, "zoom-changed", () => hide(host));- }- // 失焦仅撤销署名外链手势,DOM 自行处理本地地图的裁剪和叠层。+ // 失焦仅撤销署名外链手势,DOM 处理地图的裁剪和叠层。listen(host, owner.win, "blur", () => { host.attributionGestureUntil = 0; });- for (const name of ["focus", "show", "restore"]) listen(host, owner.win, name, () => applyGeometry(host));+ for (const name of ["focus", "show", "restore"]) listen(host, owner.win, name, () => applyVisibility(host));host.attachContents = contents => {host.contents = contents;// 全局 web-contents-created 会安装外部打开链接处理器,必须在加载前替换为拒绝。@@ -540,8 +442,7 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents};listen(host, contents, "before-mouse-event", (_event, input) => {if (input.type === "mouseDown") {- if (host.mode === "native") dismissUnplaced(host.win, "outside");- else if (currentWebviewOwner(host) && host.ready && host.visible && host.win.isFocused() &&+ if (currentWebviewOwner(host) && host.ready && host.visible && host.win.isFocused() &&host.win.isVisible() && !host.win.isMinimized()) {sendOwner(host, {version: 1, instanceID: host.init.instanceID, type: "dismissMenu"});}@@ -573,23 +474,22 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContentsfail(host, "hostDocumentLoadFailed");});listen(host, contents, "render-process-gone", () => fail(host, "hostRendererGone"));- if (host.mode === "webview") {- listen(host, contents, "did-navigate-in-page", () => fail(host, "hostDocumentMismatch"));- listen(host, contents, "did-navigate", (_event, url) => {- if (url !== entryURL) fail(host, "hostDocumentMismatch");- });- }+ listen(host, contents, "did-navigate-in-page", () => fail(host, "hostDocumentMismatch"));+ listen(host, contents, "did-navigate", (_event, url) => {+ if (url !== entryURL) fail(host, "hostDocumentMismatch");+ });listen(host, contents, "destroyed", () => fail(host, "hostDestroyed"));listen(host, contents, "did-finish-load", () => {if (host.destroyed) return;try {- if (host.mode === "webview" && !host.attachmentVerified) { fail(host, "hostAttachFailed"); return; }+ if (!currentWebviewOwner(host)) { destroy(host); return; }+ if (!host.attachmentVerified) { fail(host, "hostAttachFailed"); return; }if (host.loaded) { fail(host, "hostDocumentReloaded"); return; }if (contents.getURL() !== entryURL) { fail(host, "hostDocumentMismatch"); return; }host.loaded = true;// 初始隐藏的 renderer 必须显式唤醒产帧,否则 SDK 的 load 会等待显示,而显示又等待 ready。contents.setBackgroundThrottling(false);- applyGeometry(host);+ applyVisibility(host);const {port1, port2} = new MessageChannelMain();host.port = port1;host.transferredPort = port2;@@ -613,7 +513,7 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContentsif (host.points) post(host, host.points);post(host, {version: 1, instanceID: init.instanceID, type: "theme", theme: init.theme});if (host.destroyed) return;- applyGeometry(host);+ applyVisibility(host);if (host.destroyed) return;contents.setBackgroundThrottling(true);sendOwner(host, reply);@@ -637,27 +537,15 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents});};setDeadline(host, MAP_HOST_BOOTSTRAP_TIMEOUT);- if (host.mode === "webview") {- webviewSessions.add(ses);- installAttachmentOwner(event.sender);- return {version: 1, instanceID: init.instanceID, mode: "webview", src: entryURL, partition};- }- host.attachContents(view.webContents);- creationFailure = "hostAttachFailed";- view.setVisible(false);- // DOM 暂时不可见时也能完成初始化;此占位视图始终隐藏,不会覆盖编辑器。- view.setBounds({x: 0, y: 0, width: 1, height: 1});- owner.win.contentView.addChildView(view);- // Electron 添加的新地图会位于最上层;只提升菜单,不重排或隐藏其他地图。- for (const other of hosts.values()) if (other.win === owner.win) other.unplaced?.promote();- void host.contents.loadURL(entryURL).catch(() => { report("documentLoadFailed"); fail(host, "hostDocumentLoadFailed"); });+ webviewSessions.add(ses);+ registerOwner(event.sender);+ return {version: 1, instanceID: init.instanceID, mode: "webview", src: entryURL, partition};} catch (_error) {- if (host) fail(host, creationFailure);+ if (host) fail(host, "hostSetupFailed");else if (router) router.destroy();else if (ses) clearMapSession(ses);- return {version: 1, instanceID: init.instanceID, error: creationFailure};+ return {version: 1, instanceID: init.instanceID, error: "hostSetupFailed"};}- return {version: 1, instanceID: init.instanceID, mode: "native"};});ipcMain.on("siyuan-map-command", (event, value) => {const host = getHost(event, value);@@ -665,9 +553,8 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContentsconst command = parseMapCommand(value, host.init.instanceID);if (!command) return;if (command.type === "visibility") {- if (host.mode !== "webview") return;host.visibility = command.visible ? {visible: true, ...(command.viewport && {viewport: command.viewport})} : {visible: false};- applyGeometry(host);+ applyVisibility(host);return;}if (command.type === "destroy") { destroy(host); return; }@@ -679,19 +566,9 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents} else if (command.type === "theme") host.init.theme = command.theme;if (host.ready) post(host, command);});- ipcMain.on("siyuan-map-geometry", (event, value) => {- const host = getHost(event, value);- if (!host || host.mode !== "native") return;- try {- const geometry = parseMapGeometry(value, host.owner.getZoomFactor(), host.win.getContentBounds(), host.report);- if (!geometry?.visible) { hide(host); return; }- host.geometry = geometry;- applyGeometry(host);- } catch (_error) { fail(host, "hostOperationFailed"); }- });ipcMain.on("siyuan-map-destroy", (event, value) => destroy(getHost(event, value)));app.on("before-quit", () => [...hosts.values()].forEach(destroy));- return {destroyAll: () => [...hosts.values()].forEach(destroy)};+ return {registerOwner, destroyAll: () => [...hosts.values()].forEach(destroy)};};module.exports = {createMapSessionRouter, createMapHostManager, MAP_HOST_BOOTSTRAP_TIMEOUT, MAP_HOST_READY_TIMEOUT};diff --git a/app/electron/mapHostManager.test.js b/app/electron/mapHostManager.test.jsindex eedfa752f5..c90b17339d 100644--- a/app/electron/mapHostManager.test.js+++ b/app/electron/mapHostManager.test.js@@ -175,26 +175,23 @@ test("destroy aborts in-flight provider requests, clears session state and leaveassert.equal(ses.cleanup.length, 5);});-const setup = (initialFault, mode = "remote") => {+const setup = (initialFault, mode = "remote", autoAttach = true) => {let sequence = 0;const faults = new Set(initialFault ? [initialFault] : []);const fault = name => {if (faults.has(name)) throw new Error("https://private.invalid/?key=secret " + name);};- const handlers = {}, sessions = [], views = [], channels = [], order = [], switches = new Map();+ const handlers = {}, sessions = [], guests = [], channels = [], order = [], switches = new Map();const app = Object.assign(new EventEmitter(), {commandLine: {hasSwitch: name => switches.has(name), getSwitchValue: name => switches.get(name),}});const contents = id => Object.assign(new EventEmitter(), {id, mainFrame: {url: origin + "/stage/build/app/"}, sent: [], destroyed: false, zoom: 1,isDestroyed() { return this.destroyed; }, getZoomFactor() { return this.zoom; },- focus() { this.focused = true; },send(...args) { this.sent.push(structuredClone(args)); }});const owner = contents(1);- const win = Object.assign(new EventEmitter(), {webContents: owner, destroyed: false, focused: true, visible: true, minimized: false, children: [],+ const win = Object.assign(new EventEmitter(), {webContents: owner, destroyed: false, focused: true, visible: true, minimized: false,isDestroyed() { return this.destroyed; }, isFocused() { return this.focused; },- isVisible() { return this.visible; }, isMinimized() { return this.minimized; }, getContentBounds: () => ({width: 1000, height: 800})});- win.contentView = {addChildView: view => { fault("attach"); win.children = win.children.filter(item => item !== view); win.children.push(view); },- removeChildView: view => { fault("detach"); win.children = win.children.filter(item => item !== view); }};+ isVisible() { return this.visible; }, isMinimized() { return this.minimized; }});const target = {origin, mode};app.on("web-contents-created", (_event, guest) => guest.setWindowOpenHandler(() => ({action: "allow"})));let initialized = true;@@ -209,35 +206,6 @@ const setup = (initialFault, mode = "remote") => {ses.setPermissionRequestHandler = value => { fault("router"); setPermission(value); };return ses;}},- WebContentsView: class {- constructor(options) {- fault("view");- this.options = options;- this.webContents = contents(100 + views.length);- Object.assign(this.webContents, {- setWindowOpenHandler(handler) { fault("openHandler"); this.openHandler = handler; order.push("openHandler"); },- getURL() { return this.url; },- loadURL(url) {- fault("loadSync"); this.url = url; this.mainFrame.url = url; order.push("load");- if (faults.has("earlyConsole")) {- this.emit("console-message", {message: "Creating a worker from 'blob:null/private' violates the following Content Security Policy directive: \"worker-src 'none'\"."});- }- return faults.has("loadAsync") ? Promise.reject(new Error("private load failure")) : Promise.resolve();- },- postMessage(...args) { fault("portTransfer"); this.transferred = args; },- setZoomFactor(zoom) { this.zoom = zoom; },- setBackgroundThrottling(value) { this.throttling = value; order.push("throttling:" + value); },- stop() { fault("stop"); this.stopped = true; },- close(options) { this.closeOptions = options; this.destroyed = true; this.emit("destroyed"); },- });- const on = this.webContents.on;- this.webContents.on = function (...args) { fault("listener"); return on.apply(this, args); };- views.push(this);- }- setVisible(value) { this.visible = value; (this.visibility ||= []).push(value); }- setBackgroundColor(value) { this.background = value; }- setBounds(value) { fault("bounds"); this.bounds = value; }- },MessageChannelMain: class {constructor() {fault("channel");@@ -249,46 +217,64 @@ const setup = (initialFault, mode = "remote") => {}},});+ manager.registerOwner(owner);const event = () => ({sender: owner, senderFrame: owner.mainFrame});- const create = (data = {}) => handlers["siyuan-map-create"](event(), {...envelope, provider: "openfreemap", theme: "light", ...data});- const command = data => handlers["siyuan-map-command"](event(), {...envelope, ...data});- const reply = data => channels.at(-1).port1.emit("message", {data: {...envelope, ...data}});- const load = () => views.at(-1).webContents.emit("did-finish-load");const attach = (descriptor, overrides = {}) => {const params = {src: descriptor.src, partition: descriptor.partition, ...overrides.params};const preferences = {nodeIntegration: true, sandbox: false, preload: "/untrusted.js", ...overrides.preferences};- const attachEvent = {sender: owner, prevented: false, preventDefault() { this.prevented = true; }};+ const attachEvent = {sender: owner, prevented: false, preventDefault() { this.prevented = true; }, ...overrides.event};owner.emit("will-attach-webview", attachEvent, preferences, params);if (attachEvent.prevented) return {attachEvent, preferences};- const guest = Object.assign(contents(500 + sessions.length), {session: preferences.session, hostWebContents: owner,- getType: () => "webview", getLastWebPreferences: () => preferences,- getURL: () => descriptor.src,- setWindowOpenHandler(handler) { this.openHandler = handler; },- setBackgroundThrottling() {}, postMessage(...args) { this.transferred = args; },- stop() {}, close() { this.destroyed = true; this.emit("destroyed"); }, ...overrides.contents});+ const guest = Object.assign(contents(500 + guests.length), {session: preferences.session, hostWebContents: owner,+ url: descriptor.src, getType: () => "webview", getLastWebPreferences: () => preferences,+ getURL() { return this.url; },+ setWindowOpenHandler(handler) { this.openHandler = handler; order.push("openHandler"); },+ setBackgroundThrottling(value) { this.throttling = value; order.push("throttling:" + value); },+ postMessage(...args) { fault("portTransfer"); this.transferred = args; },+ stop() { fault("stop"); this.stopped = true; },+ close(options) { this.closeOptions = options; this.destroyed = true; this.emit("destroyed"); }, ...overrides.contents});+ guest.preferences = preferences;+ const on = guest.on;+ guest.on = function (...args) { fault("listener"); return on.apply(this, args); };+ guests.push(guest);if (overrides.deferCreated) return {attachEvent, preferences, guest};app.emit("web-contents-created", {}, guest);if (!guest.destroyed && !overrides.skipVerified) owner.emit("did-attach-webview", {}, guest);+ if (faults.has("earlyConsole")) {+ guest.emit("console-message", {message: "Creating a worker from 'blob:null/private' violates the following Content Security Policy directive: \"worker-src 'none'\"."});+ }return {attachEvent, preferences, guest};};- return {manager, app, handlers, sessions, views, channels, order, switches, owner, win, target, event, create, command, reply, load, faults, attach,+ const create = (data = {}) => {+ const descriptor = handlers["siyuan-map-create"](event(), {...envelope, provider: "openfreemap", theme: "light", ...data});+ if (autoAttach && !descriptor.error) attach(descriptor);+ return descriptor;+ };+ const command = data => handlers["siyuan-map-command"](event(), {...envelope, ...data});+ const reply = data => channels.at(-1).port1.emit("message", {data: {...envelope, ...data}});+ const load = () => guests.at(-1).emit("did-finish-load");+ return {manager, app, handlers, sessions, guests, channels, order, switches, owner, win, target, event, create, command, reply, load, faults, attach,setInitialized(value) { initialized = value; }};};-test("WCV keeps an isolated memory session, secure preferences, denied external navigation and credential-free bootstrap", () => {- const s = setup();- assert.deepEqual(s.create({credentials: {apiKey: "test-key", securityCode: "test-code"}}), {...envelope, mode: "native"});- const prefs = s.views[0].options.webPreferences;+const managerTest = (name, run) => {+ for (const mode of ["local", "remote"]) test(name + " (" + mode + ")", t => run(t, mode));+};++managerTest("map guest keeps an isolated memory session, secure preferences, denied external navigation and credential-free bootstrap", (_t, mode) => {+ const s = setup(undefined, mode);+ assert.equal(s.create({credentials: {apiKey: "test-key", securityCode: "test-code"}}).mode, "webview");+ const prefs = s.guests[0].preferences;assert.equal(prefs.sandbox, true); assert.equal(prefs.webSecurity, true); assert.equal(prefs.contextIsolation, true);for (const key of ["nodeIntegration", "nodeIntegrationInSubFrames", "nodeIntegrationInWorker", "webviewTag", "allowRunningInsecureContent"]) {assert.equal(prefs[key], false);}assert.equal(s.sessions[0].partition.startsWith("persist:"), false);assert.deepEqual(s.sessions[0].options, {cache: false});- assert.deepEqual(s.order, ["openHandler", "load"]);- assert.deepEqual(s.views[0].webContents.openHandler({url: "file:///etc/passwd"}), {action: "deny"});- assert.equal(s.views[0].visible, false);- assert.equal(s.views[0].webContents.url.includes("test-key"), false);+ assert.deepEqual(s.order, ["openHandler", "openHandler", "openHandler"]);+ assert.deepEqual(s.guests[0].openHandler({url: "file:///etc/passwd"}), {action: "deny"});+ assert.equal(s.channels.length, 0);+ assert.equal(s.guests[0].url.includes("test-key"), false);s.load();assert.equal(s.channels[0].port1.sent.length, 0);s.reply({type: "ready"});@@ -300,8 +286,8 @@ test("WCV keeps an isolated memory session, secure preferences, denied externals.manager.destroyAll();});-test("only initialized registered owner main frame may create, update or destroy a map", () => {- const s = setup();+managerTest("only initialized registered owner main frame may create, update or destroy a map", (_t, mode) => {+ const s = setup(undefined, mode);const create = s.handlers["siyuan-map-create"];const config = {...envelope, provider: "openfreemap", theme: "light"};assert.throws(() => create({...s.event(), senderFrame: {}}, config));@@ -310,15 +296,15 @@ test("only initialized registered owner main frame may create, update or destroys.owner.mainFrame.url = origin + "/stage/build/app/";s.create();s.handlers["siyuan-map-destroy"]({...s.event(), senderFrame: {}}, envelope);- assert.equal(s.views[0].webContents.destroyed, false);+ assert.equal(s.guests[0].destroyed, false);s.target.origin = "http://127.0.0.1:6807";s.handlers["siyuan-map-destroy"](s.event(), envelope);- assert.equal(s.views[0].webContents.destroyed, false);+ assert.equal(s.guests[0].destroyed, true, "a changed kernel origin revokes the guest");s.manager.destroyAll();});-test("points and clicks are bounded by current revision and membership; ready is one-shot", () => {- const s = setup(); s.create(); s.load();+managerTest("points and clicks are bounded by current revision and membership; ready is one-shot", (_t, mode) => {+ const s = setup(undefined, mode); s.create(); s.load();s.command({type: "setPoints", revision: 2, points: [{id: "row", longitude: 10, latitude: 20, secret: "never"}]});s.reply({type: "bootstrapReady"}); s.reply({type: "ready"}); s.reply({type: "ready"});assert.equal(s.owner.sent.filter(entry => entry[1].type === "ready").length, 1);@@ -335,20 +321,19 @@ test("points and clicks are bounded by current revision and membership; ready iss.manager.destroyAll();});-test("attribution links require one recent native input in a ready visible focused map", (t) => {+managerTest("attribution links require one recent trusted guest input in a ready visible focused map", (t, mode) => {let now = 100000;t.mock.method(Date, "now", () => now);- const s = setup(); s.create(); s.load();- const contents = s.views[0].webContents;+ const s = setup(undefined, mode); s.create(); s.load();+ const contents = s.guests[0];const click = () => contents.emit("before-mouse-event", {}, {type: "mouseUp", button: "left"});const links = () => s.owner.sent.filter(entry => entry[1].type === "attributionClick").map(entry => entry[1]);- const geometry = {...envelope, visible: true, bounds: {x: 10, y: 20, width: 400, height: 300},- logicalSize: {width: 400, height: 300}, crop: {x: 0, y: 0}};+ const visibility = {type: "visibility", visible: true, viewport: {x: 0, y: 0, width: 400, height: 300}};click(); s.reply({type: "attributionClick", link: "maplibre"});s.reply({type: "bootstrapReady"}); s.reply({type: "ready"});click(); s.reply({type: "attributionClick", link: "maplibre"});assert.deepEqual(links(), []);- s.handlers["siyuan-map-geometry"](s.event(), geometry);+ s.command(visibility);s.reply({type: "attributionClick", link: "maplibre"});assert.deepEqual(links(), [], "a provider message alone is insufficient");click();@@ -362,7 +347,8 @@ test("attribution links require one recent native input in a ready visible focuss.reply({type: "attributionClick", link: "openstreetmap"});assert.equal(links().length, 2);click(); s.win.focused = false; s.win.emit("blur");- assert.equal(s.views[0].visible, true, "switching applications keeps the visible map painted");+ assert.equal(s.channels[0].port1.sent.filter(value => value.type === "visibility").at(-1).visible, true,+ "switching applications keeps the visible map painted");s.reply({type: "attributionClick", link: "maplibre"});click(); s.reply({type: "attributionClick", link: "maplibre"});contents.emit("before-input-event", {}, {type: "keyDown", key: "Enter", isAutoRepeat: false});@@ -371,90 +357,25 @@ test("attribution links require one recent native input in a ready visible focuss.win.focused = true; s.win.emit("focus");s.reply({type: "attributionClick", link: "maplibre"});assert.equal(links().length, 2, "blur invalidates an outstanding gesture even after focus returns");- click(); s.handlers["siyuan-map-geometry"](s.event(), {...envelope, visible: false});+ click(); s.command({type: "visibility", visible: false});s.reply({type: "attributionClick", link: "maplibre"});- s.handlers["siyuan-map-geometry"](s.event(), geometry);+ s.command(visibility);s.reply({type: "attributionClick", link: "maplibre"});- assert.equal(links().length, 2, "hidden geometry invalidates an outstanding gesture");+ assert.equal(links().length, 2, "hidden visibility invalidates an outstanding gesture");click(); now += 1001; s.reply({type: "attributionClick", link: "maplibre"});- assert.equal(links().length, 2, "expired native input cannot open a link");+ assert.equal(links().length, 2, "expired guest input cannot open a link");s.command({type: "visibility", visible: true, viewport: {x: 0, y: 0, width: 400, height: 300}});const sent = s.channels[0].port1.sent.filter(message => message.type === "visibility");- assert.deepEqual(sent.map(message => message.visible), [true, false, true]);- assert.deepEqual(sent[0].viewport, {x: 0, y: 0, width: 400, height: 300});+ assert.deepEqual(sent.map(message => message.visible), [false, true, false, true]);+ assert.deepEqual(sent[1].viewport, {x: 0, y: 0, width: 400, height: 300});s.manager.destroyAll();assert.equal(contents.listenerCount("before-mouse-event"), 0);assert.equal(contents.listenerCount("before-input-event"), 0);});-test("geometry is invisible before ready, uses owner zoom, and hides on invalid geometry or window transitions", () => {- const s = setup(); s.create(); s.load(); s.owner.zoom = 1.25;- const geometry = {...envelope, visible: true, bounds: {x: 10, y: 20, width: 200, height: 100},- logicalSize: {width: 400, height: 300}, crop: {x: 30, y: 40}};- s.handlers["siyuan-map-geometry"](s.event(), geometry);- assert.equal(s.views[0].visible, false);- assert.deepEqual(s.views[0].bounds, {x: 13, y: 25, width: 249, height: 125});- s.reply({type: "bootstrapReady"}); s.reply({type: "ready"});- assert.equal(s.views[0].visible, true);- assert.deepEqual(s.views[0].bounds, {x: 13, y: 25, width: 249, height: 125});- assert.equal(s.views[0].webContents.zoom, 1.25);- assert.deepEqual(s.channels[0].port1.sent.find(message => message.type === "visibility" && message.visible).viewport,- {x: 0, y: 0, width: 199.2, height: 100}, "native viewport uses cropped DIP bounds divided by zoom without adding crop");- s.win.emit("resize"); assert.equal(s.views[0].visible, false);- s.handlers["siyuan-map-geometry"](s.event(), geometry); assert.equal(s.views[0].visible, true);- s.handlers["siyuan-map-geometry"](s.event(), {...geometry, bounds: {...geometry.bounds, width: 10000}});- assert.equal(s.views[0].visible, false);- assert.deepEqual(s.owner.sent.at(-1)[1], {...envelope, type: "diagnostic", code: "geometryLogicalBounds"});- const count = s.owner.sent.length;- s.handlers["siyuan-map-geometry"](s.event(), {...geometry, bounds: {...geometry.bounds, width: 10000}});- assert.equal(s.owner.sent.length, count);- s.manager.destroyAll();-});--test("hidden bootstrap receives nonzero bounds and rendering frames without becoming visible", () => {- const s = setup(); s.create();- const view = s.views[0];- assert.equal(view.options.webPreferences.backgroundThrottling, false);- assert.deepEqual(view.bounds, {x: 0, y: 0, width: 1, height: 1});- assert.equal(view.visible, false);- const geometry = {...envelope, visible: true, bounds: {x: 10, y: 20, width: 200, height: 100},- logicalSize: {width: 400, height: 300}, crop: {x: 30, y: 40}};- s.handlers["siyuan-map-geometry"](s.event(), geometry);- assert.deepEqual(view.bounds, geometry.bounds);- assert.equal(view.webContents.sent.length, 0, "viewport waits for the preload to exist");- s.load();- assert.equal(view.webContents.throttling, false);- assert.equal(view.visible, false);- assert.deepEqual(view.webContents.sent[0], ["siyuan-map-viewport", {logicalSize: geometry.logicalSize, crop: geometry.crop}]);- s.reply({type: "bootstrapReady"});- s.handlers["siyuan-map-geometry"](s.event(), {...envelope, visible: false});- s.reply({type: "ready"});- assert.equal(view.visible, false, "a menu or hidden DOM during bootstrap must still hide the native view");- assert.equal(view.webContents.throttling, true, "normal throttling resumes after bootstrap");- s.handlers["siyuan-map-geometry"](s.event(), geometry);- assert.equal(view.visible, true);- s.manager.destroyAll();- assert.equal(view.webContents.destroyed, true);-});--test("an initially hidden or zero-size DOM can finish bootstrap without exposing the placeholder", () => {- const s = setup(); s.create(); s.load();- s.handlers["siyuan-map-geometry"](s.event(), {...envelope, visible: true, bounds: {x: 0, y: 0, width: 0, height: 0},- logicalSize: {width: 0, height: 0}, crop: {x: 0, y: 0}});- assert.deepEqual(s.views[0].bounds, {x: 0, y: 0, width: 1, height: 1});- assert.equal(s.views[0].webContents.throttling, false);- s.reply({type: "bootstrapReady"}); s.reply({type: "ready"});- assert.equal(s.views[0].visible, false);- assert.equal(s.views[0].webContents.throttling, true);- s.manager.destroyAll();- s.load();- assert.equal(s.views[0].visible, false);- assert.equal(s.views[0].webContents.destroyed, true);-});--test("known host diagnostics are bounded fixed codes and stop on disposal", () => {- const s = setup(); s.create();- const contents = s.views[0].webContents;+managerTest("known host diagnostics are bounded fixed codes and stop on disposal", (_t, mode) => {+ const s = setup(undefined, mode); s.create();+ const contents = s.guests[0];const message = "Content Security Policy worker-src 'none'; https://secret.invalid/?key=private";contents.emit("console-message", {message});contents.emit("console-message", {message});@@ -465,10 +386,10 @@ test("known host diagnostics are bounded fixed codes and stop on disposal", () =assert.equal(s.owner.sent.length, 1);});-test("CSP resources are captured before load, deduplicated by category and isolated from the map port", () => {- const s = setup("earlyConsole"); s.create();+managerTest("CSP resources are captured before load, deduplicated by category and isolated from the map port", (_t, mode) => {+ const s = setup("earlyConsole", mode); s.create();assert.deepEqual(s.owner.sent.map(entry => entry[1]), [{...envelope, type: "diagnostic", code: "cspWorker", resource: "blob"}]);- const contents = s.views[0].webContents;+ const contents = s.guests[0];const emit = url => contents.emit("console-message", {}, 2,`Connecting to '${url}' violates the following Content Security Policy directive: "connect-src https://tiles.openfreemap.org".`);emit("https://tiles.openfreemap.org/path?key=secret");@@ -487,9 +408,9 @@ test("CSP resources are captured before load, deduplicated by category and isolaassert.equal(s.owner.sent.length, count);});-test("unapproved CSP hostnames redact and deduplicate without entering public diagnostics", () => {- const s = setup(); s.create();- const contents = s.views[0].webContents;+managerTest("unapproved CSP hostnames redact and deduplicate without entering public diagnostics", (_t, mode) => {+ const s = setup(undefined, mode); s.create();+ const contents = s.guests[0];for (let index = 0; index < 100; index++) {contents.emit("console-message", {message: `Connecting to 'https://map${index}.openfreemap.org/private?key=secret' violates the following Content Security Policy directive: "connect-src https://tiles.openfreemap.org".`});}@@ -523,13 +444,13 @@ test("provider routing reports fixed transport failures without logging requestsassert.equal(JSON.stringify(diagnostics).includes("private"), false);});-test("destroy and owner navigation close real contents, ports, requests and session; stale events cannot resurrect", () => {- const s = setup(); s.create(); s.load(); s.reply({type: "bootstrapReady"});+managerTest("destroy and owner navigation close real contents, ports, requests and session; stale events cannot resurrect", (_t, mode) => {+ const s = setup(undefined, mode); s.create(); s.load(); s.reply({type: "bootstrapReady"});s.owner.emit("did-start-navigation", {isMainFrame: true, isSameDocument: false});- assert.equal(s.views[0].webContents.destroyed, true);- assert.deepEqual(s.views[0].webContents.closeOptions, {waitForBeforeUnload: false});+ assert.equal(s.guests[0].destroyed, true);+ assert.deepEqual(s.guests[0].closeOptions, {waitForBeforeUnload: false});assert.equal(s.channels[0].port1.closed, true); assert.equal(s.channels[0].port2.closed, true);- assert.equal(s.win.children.length, 0); assert.equal(s.sessions[0].cleanup.length, 5);+ assert.equal(s.sessions[0].cleanup.length, 5);s.reply({type: "ready"}); assert.equal(s.owner.sent.length, 0);s.manager.destroyAll(); assert.equal(s.sessions[0].cleanup.length, 5);s.create({instanceID: "b".repeat(48)});@@ -537,28 +458,28 @@ test("destroy and owner navigation close real contents, ports, requests and sesss.manager.destroyAll();});-test("unsafe effective switches reject creation and duplicate instance IDs cannot replace a running host", () => {- const s = setup(); s.switches.set("disable-web-security", "");- assert.equal(s.create().error, "unsupportedEnvironment"); assert.equal(s.views.length, 0);- s.switches.clear(); s.create(); assert.equal(s.create().error, "hostLimitReached"); assert.equal(s.views.length, 1);+managerTest("unsafe effective switches reject creation and duplicate instance IDs cannot replace a running host", (_t, mode) => {+ const s = setup(undefined, mode); s.switches.set("disable-web-security", "");+ assert.equal(s.create().error, "unsupportedEnvironment"); assert.equal(s.guests.length, 0);+ s.switches.clear(); s.create(); assert.equal(s.create().error, "hostLimitReached"); assert.equal(s.guests.length, 1);s.manager.destroyAll();});-test("capability is credential-free and only supports trusted owners with safe process switches", () => {- const s = setup();+managerTest("capability is credential-free and only supports trusted owners with safe process switches", (_t, mode) => {+ const s = setup(undefined, mode);const capability = s.handlers["siyuan-map-capability"];assert.deepEqual(capability(s.event()), {version: 1, supported: true});assert.deepEqual(capability({...s.event(), senderFrame: {}}), {version: 1, supported: false, reason: "notMainFrame"});s.switches.set("no-sandbox", "");assert.deepEqual(capability(s.event()), {version: 1, supported: false, reason: "unsafeProcessSwitches"});- assert.equal(s.views.length, 0);+ assert.equal(s.guests.length, 0);});-test("Electron's default file-access switch permits the HTTP map host while file access stays denied", async () => {- const s = setup();+managerTest("Electron's default file-access switch permits the HTTP map host while file access stays denied", async (_t, mode) => {+ const s = setup(undefined, mode);s.switches.set("allow-file-access-from-files", "");assert.deepEqual(s.handlers["siyuan-map-capability"](s.event()), {version: 1, supported: true});- assert.deepEqual(s.create(), {...envelope, mode: "native"});+ assert.equal(s.create().mode, "webview");const ses = s.sessions[0];assert.equal((await ses.protocols.file(new Request("file:///etc/passwd"))).status, 403);assert.equal(ses.before({url: "file:///etc/passwd", resourceType: "mainFrame"}).cancel, true);@@ -568,59 +489,8 @@ test("Electron's default file-access switch permits the HTTP map host while files.manager.destroyAll();});-test("switching applications keeps a visible map painted through blur, geometry updates and focus", () => {- const s = setup(); s.create(); s.load(); s.reply({type: "bootstrapReady"}); s.reply({type: "ready"});- const geometry = {...envelope, visible: true, bounds: {x: 10, y: 20, width: 200, height: 100},- logicalSize: {width: 200, height: 100}, crop: {x: 0, y: 0}};- s.handlers["siyuan-map-geometry"](s.event(), geometry);- assert.equal(s.views[0].visible, true);- for (let i = 0; i < 3; i++) {- s.win.focused = false; s.win.emit("blur");- assert.equal(s.views[0].visible, true);- geometry.bounds.x += 10;- s.handlers["siyuan-map-geometry"](s.event(), geometry);- assert.equal(s.views[0].visible, true);- assert.deepEqual(s.views[0].bounds, geometry.bounds);- s.win.focused = true; s.win.emit("focus");- assert.equal(s.views[0].visible, true);- }- const visibility = s.channels[0].port1.sent.filter(message => message.type === "visibility");- assert.deepEqual(visibility.map(message => message.visible), [true], "focus changes must not hide and restore the provider");- s.manager.destroyAll();-});--test("an unfocused window can finish showing a map but hiding, minimizing and owner overlays still suppress it", () => {- const s = setup(); s.create(); s.load();- const geometry = {...envelope, visible: true, bounds: {x: 10, y: 20, width: 200, height: 100},- logicalSize: {width: 200, height: 100}, crop: {x: 0, y: 0}};- s.win.focused = false; s.win.emit("blur");- s.handlers["siyuan-map-geometry"](s.event(), geometry);- assert.equal(s.views[0].visible, false, "bootstrap must still complete before showing the map");- s.reply({type: "bootstrapReady"}); s.reply({type: "ready"});- assert.equal(s.views[0].visible, true);- for (const [property, hiddenValue, event, restore] of [- ["visible", false, "hide", "show"], ["minimized", true, "minimize", "restore"],- ]) {- s.win[property] = hiddenValue;- s.win.emit(event);- assert.equal(s.views[0].visible, false);- s.handlers["siyuan-map-geometry"](s.event(), geometry);- s.win.emit("focus");- assert.equal(s.views[0].visible, false, "geometry and focus cannot show a hidden or minimized window");- s.win[property] = !hiddenValue;- s.win.emit(restore);- assert.equal(s.views[0].visible, true);- }- s.handlers["siyuan-map-geometry"](s.event(), {...envelope, visible: false});- s.win.focused = true; s.win.emit("focus");- assert.equal(s.views[0].visible, false, "window focus must not revive an owner-occluded map");- s.handlers["siyuan-map-geometry"](s.event(), geometry);- assert.equal(s.views[0].visible, true);- s.manager.destroyAll();-});--test("navigation, redirects, client certificates, login and renderer failure are blocked", () => {- const s = setup(); s.create(); const wc = s.views[0].webContents;+managerTest("navigation, redirects, client certificates, login and renderer failure are blocked", (_t, mode) => {+ const s = setup(undefined, mode); s.create(); const wc = s.guests[0];for (const name of ["will-navigate", "will-frame-navigate", "will-redirect", "will-attach-webview"]) {let prevented = false; wc.emit(name, {preventDefault() { prevented = true; }}); assert.equal(prevented, true, name);}@@ -633,8 +503,8 @@ test("navigation, redirects, client certificates, login and renderer failure areassert.equal(s.owner.sent[0][1].code, "hostRendererGone");});-test("main-process provider fetch cannot select client certificates or authenticate, including null WebContents", async () => {- const s = setup(); s.create();+managerTest("main-process provider fetch cannot select client certificates or authenticate, including null WebContents", async (_t, mode) => {+ const s = setup(undefined, mode); s.create();let finish;s.sessions[0].fetch = () => new Promise(resolve => { finish = resolve; });const url = "https://tiles.openfreemap.org/tile";@@ -654,135 +524,136 @@ test("main-process provider fetch cannot select client certificates or authentics.manager.destroyAll();});-test("a closed runtime port destroys the map instead of retaining a live orphan renderer", () => {- const s = setup(); s.create(); s.load();+managerTest("a closed runtime port destroys the map instead of retaining a live orphan renderer", (_t, mode) => {+ const s = setup(undefined, mode); s.create(); s.load();s.channels[0].port1.emit("close");- assert.equal(s.views[0].webContents.destroyed, true);+ assert.equal(s.guests[0].destroyed, true);assert.equal(s.owner.sent[0][1].code, "hostPortClosed");});-test("bootstrap and SDK receive separate deadlines and duplicate bootstrap cannot extend SDK lifetime", t => {+managerTest("bootstrap and SDK receive separate deadlines and duplicate bootstrap cannot extend SDK lifetime", (t, mode) => {t.mock.timers.enable({apis: ["setTimeout"]});- const s = setup(); s.create(); s.load();+ const s = setup(undefined, mode); s.create(); s.load();t.mock.timers.tick(29000);s.reply({type: "bootstrapReady"});t.mock.timers.tick(39000);- assert.equal(s.views[0].webContents.destroyed, false, "both SDK phases retain their own 20-second budget");+ assert.equal(s.guests[0].destroyed, false, "both SDK phases retain their own 20-second budget");assert.deepEqual(s.owner.sent, []);s.reply({type: "bootstrapReady"});t.mock.timers.tick(5999);- assert.equal(s.views[0].webContents.destroyed, false);+ assert.equal(s.guests[0].destroyed, false);t.mock.timers.tick(1);assert.deepEqual(s.owner.sent.map(entry => entry[1]), [{...envelope, type: "error", code: "hostSDKTimeout"}]);- assert.equal(s.views[0].webContents.destroyed, true);+ assert.equal(s.guests[0].destroyed, true);assert.equal(s.channels[0].port1.closed, true);});-test("document and bootstrap timeouts have distinct final codes and successful ready clears all deadlines", t => {+managerTest("document and bootstrap timeouts have distinct final codes and successful ready clears all deadlines", (t, mode) => {t.mock.timers.enable({apis: ["setTimeout"]});for (const loaded of [false, true]) {- const s = setup(); s.create();+ const s = setup(undefined, mode); s.create();if (loaded) s.load();t.mock.timers.tick(29999);assert.deepEqual(s.owner.sent, []);t.mock.timers.tick(1);assert.deepEqual(s.owner.sent.map(entry => entry[1]), [{...envelope, type: "error",code: loaded ? "hostBootstrapTimeout" : "hostDocumentLoadTimeout"}]);- assert.equal(s.views[0].webContents.destroyed, true);+ assert.equal(s.guests[0].destroyed, true);}- const s = setup(); s.create(); s.load();+ const s = setup(undefined, mode); s.create(); s.load();t.mock.timers.tick(29000); s.reply({type: "bootstrapReady"});t.mock.timers.tick(39999); s.reply({type: "ready"});t.mock.timers.tick(90000);assert.deepEqual(s.owner.sent.map(entry => entry[1]), [{...envelope, type: "ready"}]);- assert.equal(s.views[0].webContents.destroyed, false);+ assert.equal(s.guests[0].destroyed, false);s.manager.destroyAll();});-test("creation failures return fixed stage codes and release every resource already allocated", () => {- for (const [point, code] of [["session", "hostSetupFailed"], ["router", "hostSetupFailed"],- ["view", "hostSetupFailed"], ["openHandler", "hostSetupFailed"], ["listener", "hostSetupFailed"],- ["attach", "hostAttachFailed"], ["bounds", "hostAttachFailed"], ["loadSync", "hostAttachFailed"]]) {- const s = setup(point);- assert.deepEqual(s.create(), {...envelope, error: code}, point);- assert.equal(s.win.children.length, 0, point);+managerTest("creation failures return fixed stage codes and release every resource already allocated", (_t, mode) => {+ for (const point of ["session", "router"]) {+ const s = setup(point, mode);+ assert.deepEqual(s.create(), {...envelope, error: "hostSetupFailed"}, point);for (const ses of s.sessions) assert.equal(ses.cleanup.length, 5, point);- for (const view of s.views) {- assert.equal(view.webContents.destroyed, true, point);- assert.equal(view.webContents.eventNames().length, 0, point);- }+ assert.equal(s.guests.length, 0);assert.equal(JSON.stringify(s.owner.sent).includes("secret"), false, point);s.faults.clear();- assert.deepEqual(s.create(), {...envelope, mode: "native"}, "a failed instance must not occupy its slot: " + point);+ assert.equal(s.create().mode, "webview", "a failed instance must not occupy its slot: " + point);s.manager.destroyAll();}});-test("load rejection and main-frame failure report document failure without waiting for the deadline", async () => {- const s = setup("loadAsync"); s.create();- await Promise.resolve();+managerTest("guest listener setup failure closes the guest and releases the reservation", (_t, mode) => {+ const s = setup("listener", mode);+ assert.equal(s.create().mode, "webview");+ assert.equal(s.guests[0].destroyed, true);+ assert.equal(s.guests[0].eventNames().length, 0);+ assert.equal(s.sessions[0].cleanup.length, 5);+ assert.deepEqual(s.owner.sent.map(entry => entry[1]), [{...envelope, type: "error", code: "hostAttachFailed"}]);+ s.faults.clear();+ assert.equal(s.create().mode, "webview");+ s.manager.destroyAll();+});++managerTest("main-frame load failure reports document failure without waiting for the deadline", (_t, mode) => {+ const s = setup(undefined, mode); s.create();+ s.guests[0].emit("did-fail-load", {}, -2, "secret", "https://private.invalid/?key=secret", false);+ assert.deepEqual(s.owner.sent, []);+ s.guests[0].emit("did-fail-load", {}, -2, "secret", "https://private.invalid/?key=secret", true);assert.equal(s.owner.sent.at(-1)[1].code, "hostDocumentLoadFailed");- assert.equal(s.views[0].webContents.destroyed, true);- const f = setup(); f.create();- f.views[0].webContents.emit("did-fail-load", {}, -2, "secret", "https://private.invalid/?key=secret", false);- assert.deepEqual(f.owner.sent, []);- f.views[0].webContents.emit("did-fail-load", {}, -2, "secret", "https://private.invalid/?key=secret", true);- assert.equal(f.owner.sent.at(-1)[1].code, "hostDocumentLoadFailed");- assert.equal(JSON.stringify(f.owner.sent).includes("secret"), false);- assert.equal(f.views[0].webContents.destroyed, true);+ assert.equal(JSON.stringify(s.owner.sent).includes("secret"), false);+ assert.equal(s.guests[0].destroyed, true);});-test("unexpected document, reload, destruction and bootstrap rejection retain their final failure reason", () => {+managerTest("unexpected document, reload, destruction and bootstrap rejection retain their final failure reason", (_t, mode) => {const cases = [- ["hostDocumentMismatch", s => { s.views[0].webContents.url += "unexpected"; s.load(); }],+ ["hostDocumentMismatch", s => { s.guests[0].url += "unexpected"; s.load(); }],["hostDocumentReloaded", s => { s.load(); s.load(); }],- ["hostDestroyed", s => { s.views[0].webContents.destroyed = true; s.views[0].webContents.emit("destroyed"); }],+ ["hostDestroyed", s => { s.guests[0].destroyed = true; s.guests[0].emit("destroyed"); }],["hostBootstrapFailed", s => { s.load(); s.reply({type: "error", code: "hostUnavailable"}); }],["hostOperationFailed", s => { s.load(); s.reply({type: "bootstrapReady"}); s.reply({type: "error", code: "hostUnavailable"}); }],];for (const [code, trigger] of cases) {- const s = setup(); s.create(); trigger(s);+ const s = setup(undefined, mode); s.create(); trigger(s);assert.deepEqual(s.owner.sent.map(entry => entry[1]), [{...envelope, type: "error", code}]);- assert.equal(s.views[0].webContents.destroyed, true);- assert.equal(s.win.children.length, 0);+ assert.equal(s.guests[0].destroyed, true);s.manager.destroyAll();assert.equal(s.owner.sent.length, 1, "disposal must not manufacture another hostDestroyed failure");}});-test("port setup and message failures close both endpoints and preserve the fixed failure stage", () => {+managerTest("port setup and message failures close both endpoints and preserve the fixed failure stage", (_t, mode) => {for (const point of ["channel", "portListener", "portStart", "portTransfer"]) {- const s = setup(); s.create(); s.faults.add(point); s.load();+ const s = setup(undefined, mode); s.create(); s.faults.add(point); s.load();assert.deepEqual(s.owner.sent.map(entry => entry[1]), [{...envelope, type: "error", code: "hostPortSetupFailed"}], point);- assert.equal(s.views[0].webContents.destroyed, true, point);+ assert.equal(s.guests[0].destroyed, true, point);for (const channel of s.channels) {assert.equal(channel.port1.closed, true, point);assert.equal(channel.port2.closed, true, point);}}for (const ready of [false, true]) {- const s = setup(); s.create(); s.load();+ const s = setup(undefined, mode); s.create(); s.load();if (ready) s.reply({type: "bootstrapReady"});s.faults.add("portPost");s.reply({type: ready ? "ready" : "bootstrapReady"});assert.deepEqual(s.owner.sent.map(entry => entry[1]), [{...envelope, type: "error", code: "hostOperationFailed"}]);- assert.equal(s.views[0].webContents.destroyed, true);- assert.equal(s.views[0].webContents.throttling, false, "a failed post must not continue ready operations");+ assert.equal(s.guests[0].destroyed, true);+ assert.equal(s.guests[0].throttling, false, "a failed post must not continue ready operations");}});-test("renderer closure still runs when detaching the view or stopping it throws", () => {- const s = setup(); s.create(); s.load();- s.faults.add("detach"); s.faults.add("stop");+managerTest("renderer closure still runs when stopping it throws", (_t, mode) => {+ const s = setup(undefined, mode); s.create(); s.load();+ s.faults.add("stop");s.channels[0].port1.emit("close");assert.deepEqual(s.owner.sent.map(entry => entry[1]), [{...envelope, type: "error", code: "hostPortClosed"}]);- assert.equal(s.views[0].webContents.destroyed, true);+ assert.equal(s.guests[0].destroyed, true);assert.equal(s.sessions[0].cleanup.length, 5);assert.equal(s.channels[0].port1.closed, true);assert.equal(s.channels[0].port2.closed, true);});-test("main wiring removes only the process security bypass and never enables remote on map contents", () => {+managerTest("main wiring removes only the process security bypass and never enables remote on map contents", () => {const source = fs.readFileSync(path.join(__dirname, "main.js"), "utf8");assert.ok(!source.includes('appendSwitch("disable-web-security")'));assert.match(source, /createMapHostManager\(/);@@ -794,7 +665,7 @@ test("main wiring removes only the process security bypass and never enables rem});-test("capability reports bounded reasons for every owner rejection without weakening creation", () => {+managerTest("capability reports bounded reasons for every owner rejection without weakening creation", (_t, mode) => {const cases = [["ownerUnavailable", (_s, event) => { event.sender = undefined; }],["ownerUnavailable", s => { s.owner.destroyed = true; }],@@ -809,167 +680,119 @@ test("capability reports bounded reasons for every owner rejection without weake["invalidDocument", s => { s.owner.mainFrame.url = "invalid secret"; }],];for (const [reason, change] of cases) {- const s = setup(), event = s.event();+ const s = setup(undefined, mode), event = s.event();change(s, event);assert.deepEqual(s.handlers["siyuan-map-capability"](event), {version: 1, supported: false, reason});assert.throws(() => s.handlers["siyuan-map-create"](event, {...envelope, provider: "openfreemap", theme: "light"}));- assert.equal(s.views.length, 0);+ assert.equal(s.guests.length, 0);s.manager.destroyAll();}});-const unplacedState = (extra = {}) => ({revision: 0, requestID: 0, query: "", page: 1, total: 1,- rows: [{id: "private-row", title: "Private <img src=x>"}], loading: false, error: false,- theme: {mode: "light", fontSize: 16}, labels: {title: "List", search: "Search", empty: "Empty", loading: "Loading",- more: "Next", previous: "Previous", retry: "Retry", close: "Close"}, ...extra});-const unplacedAnchor = {x: 100, y: 50, width: 160, height: 30};-const readyMap = (s, id = instanceID) => {- s.create({instanceID: id});- const view = s.views.at(-1);- view.webContents.emit("did-finish-load");- const channel = s.channels.at(-1);- for (const type of ["bootstrapReady", "ready"]) channel.port1.emit("message", {data: {version: 1, instanceID: id, type}});- const geometry = {version: 1, instanceID: id, visible: true, bounds: {x: 10, y: 120, width: 600, height: 400},- logicalSize: {width: 600, height: 400}, crop: {x: 0, y: 0}};- s.handlers["siyuan-map-geometry"](s.event(), geometry);- return {view, channel, geometry};-};-const openUnplaced = (s, id = instanceID, extra = {}) => {- const result = s.handlers["siyuan-map-unplaced-open"](s.event(), {version: 1, instanceID: id,- state: unplacedState(extra), anchor: unplacedAnchor});- if (!result) return;- const view = s.views.at(-1);- const action = (type, values = {}, event = {sender: view.webContents, senderFrame: view.webContents.mainFrame}) => {- s.handlers["siyuan-map-unplaced-menu-action"](event, {sessionID: result.sessionID, revision: 0, type, ...values});- };- action("ready");- return {...result, view, action};+const readyWebview = s => {+ const descriptor = s.create();+ const attached = s.attach(descriptor);+ assert.equal(attached.attachEvent.prevented, false);+ assert.equal(attached.guest.destroyed, false);+ attached.guest.emit("did-finish-load");+ s.reply({type: "bootstrapReady"});+ s.reply({type: "ready"});+ s.command({type: "visibility", visible: true, viewport: {x: 0, y: 0, width: 400, height: 300}});+ return {...attached, descriptor};};-const unplacedReplies = s => s.owner.sent.filter(([name]) => name === "siyuan-map-unplaced-reply").map(([, value]) => value);-test("production unplaced IPC requires the captured ready visible map owner and never delivers private text to the map", () => {- const s = setup();- assert.equal(openUnplaced(s), undefined);- s.create();- assert.equal(openUnplaced(s), undefined);- s.load(); s.reply({type: "bootstrapReady"}); s.reply({type: "ready"});- assert.equal(openUnplaced(s), undefined, "ready without visible geometry must reject menus");- s.handlers["siyuan-map-geometry"](s.event(), {...envelope, visible: true, bounds: {x: 0, y: 100, width: 600, height: 400},- logicalSize: {width: 600, height: 400}, crop: {x: 0, y: 0}});- const value = {...envelope, state: unplacedState(), anchor: unplacedAnchor};- for (const event of [{...s.event(), senderFrame: {}}, {sender: s.views[0].webContents, senderFrame: s.views[0].webContents.mainFrame}]) {- assert.equal(s.handlers["siyuan-map-unplaced-open"](event, value), undefined);+managerTest("owner registration guards attachments before map creation and stays idempotent", (_t, mode) => {+ const s = setup(undefined, mode, false);+ s.manager.registerOwner(s.owner);+ assert.equal(s.owner.listenerCount("will-attach-webview"), 1);+ assert.equal(s.owner.listenerCount("did-attach-webview"), 1);+ s.setInitialized(false);+ s.owner.mainFrame.url = "about:blank";+ for (const params of [undefined, {}, {src: origin + "/stage/map/index.html?provider=openfreemap"},+ {src: "https://example.invalid/", partition: "plugin-session"},+ {src: "https://example.invalid/", partition: "persist:siyuan-map-forged"},+ {src: "https://example.invalid/", partition: "siyuan-map-forged"}]) {+ const event = {sender: s.owner, prevented: false, preventDefault() { this.prevented = true; }};+ const preferences = {sandbox: false, preload: "/plugin.js"};+ s.owner.emit("will-attach-webview", event, preferences, params);+ assert.equal(event.prevented, mode === "remote" || params?.partition === "siyuan-map-forged");+ assert.deepEqual(preferences, {sandbox: false, preload: "/plugin.js"});}- assert.equal(s.handlers["siyuan-map-unplaced-open"](s.event(), {...value, instanceID: "foreign"}), undefined);- assert.equal(s.handlers["siyuan-map-unplaced-open"](s.event(), {...value, note: {content: "secret"}}), undefined);- const menu = openUnplaced(s);- assert.ok(menu);- assert.equal(menu.view.visible, true);- assert.match(menu.view.options.webPreferences.preload, /mapUnplaced[/\\]preload\.js$/);- assert.equal(menu.view.options.webPreferences.sandbox, true);- assert.equal(menu.view.options.webPreferences.nodeIntegration, false);- assert.equal(s.sessions.at(-1).fetches.length, 0);- assert.equal(JSON.stringify(s.channels[0].port1.sent).includes("Private"), false);- assert.equal(JSON.stringify(s.views[0].webContents.sent).includes("Private"), false);- s.owner.mainFrame = {url: s.owner.mainFrame.url};- menu.action("select", {id: "private-row"});- assert.equal(menu.view.webContents.isDestroyed(), true, "same URL with a different owner frame cannot reuse the session");- assert.equal(unplacedReplies(s).some(reply => reply.action === "select"), false);+ s.target.mode = "unknown";+ assert.equal(s.attach({src: "https://example.invalid/", partition: "ordinary"}).attachEvent.prevented, true);+ s.owner.emit("destroyed");+ assert.equal(s.owner.listenerCount("will-attach-webview"), 0);+ assert.equal(s.owner.listenerCount("did-attach-webview"), 0);s.manager.destroyAll();});-test("production menu stays above newly created maps, accepts their native outside clicks and never toggles map visibility", () => {- const s = setup(), first = readyMap(s);- const before = first.view.visibility.slice();- const menu = openUnplaced(s);- assert.equal(s.win.children.at(-1), menu.view);- const second = readyMap(s, "b".repeat(48));- assert.equal(s.win.children.at(-1), menu.view);- assert.deepEqual(s.win.children.slice(0, -1), [first.view, second.view]);- let prevented = false;- second.view.webContents.emit("before-mouse-event", {preventDefault() { prevented = true; }}, {type: "mouseDown", button: "left"});- assert.equal(prevented, false);- assert.equal(menu.view.webContents.isDestroyed(), true);- assert.equal(s.owner.focused, undefined, "outside click must keep the clicked map's focus");- assert.equal(unplacedReplies(s).at(-1).reason, "outside");- assert.deepEqual(first.view.visibility, before);- assert.equal(second.view.visible, true);- s.manager.destroyAll();-});--test("production menus pause attribution timing while painting maps, restore viewport on close and revoke old click gestures", () => {- const s = setup(), map = readyMap(s);- map.view.webContents.emit("before-mouse-event", {}, {type: "mouseUp", button: "left"});- const before = map.view.visibility.slice(), menu = openUnplaced(s);- assert.deepEqual(map.channel.port1.sent.filter(value => value.type === "visibility").at(-1), {...envelope, type: "visibility", visible: true});- const count = s.owner.sent.length;- s.reply({type: "attributionClick", attribution: "openfreemap"});- assert.equal(s.owner.sent.length, count);- s.win.focused = false; s.win.emit("blur");- assert.equal(menu.view.webContents.isDestroyed(), true);- assert.equal(map.view.visible, true);- assert.deepEqual(map.view.visibility, before);- assert.deepEqual(map.channel.port1.sent.filter(value => value.type === "visibility").at(-1),- {...envelope, type: "visibility", visible: true, viewport: {x: 0, y: 0, width: 600, height: 400}});- assert.equal(unplacedReplies(s).at(-1).reason, "window-blur");- s.manager.destroyAll();+managerTest("unreserved created or attached guests obey the current owner's default policy", (_t, mode) => {+ for (const phase of ["created", "attached"]) {+ const s = setup(undefined, mode, false);+ const guest = {session: {}, hostWebContents: s.owner, getType: () => "webview",+ isDestroyed() { return !!this.destroyed; },+ setWindowOpenHandler(value) { this.openHandler = value; }, close() { this.destroyed = true; }};+ if (phase === "created") s.app.emit("web-contents-created", {}, guest);+ else s.owner.emit("did-attach-webview", {}, guest);+ assert.equal(!!guest.destroyed, mode === "remote", phase);+ if (mode === "remote") assert.deepEqual(guest.openHandler({url: "https://example.invalid/"}), {action: "deny"});+ s.manager.destroyAll();+ }});-test("one menu per window and a single terminal selection protect owner row lookup", () => {- const s = setup(); readyMap(s);- const otherID = "b".repeat(48); readyMap(s, otherID);- const first = openUnplaced(s), second = openUnplaced(s, otherID);- assert.equal(first.view.webContents.isDestroyed(), true);- assert.equal(unplacedReplies(s).at(-1).reason, "replace");- const count = unplacedReplies(s).length;- second.action("select", {id: "private-row"});- assert.equal(second.view.webContents.isDestroyed(), true);- assert.deepEqual(unplacedReplies(s).slice(count), [{version: 1, instanceID: otherID, type: "action", action: "select",- sessionID: second.sessionID, revision: 0, requestID: 0, id: "private-row"}]);- first.action("select", {id: "private-row"});- second.action("select", {id: "private-row"});- assert.equal(unplacedReplies(s).length, count + 1);+managerTest("a reservation is bound to its owner, exact entry URL and memory partition", (_t, mode) => {+ const s = setup(undefined, mode, false), descriptor = s.create();+ const otherOwner = Object.assign(new EventEmitter(), {id: 2});+ s.manager.registerOwner(otherOwner);+ const foreign = {sender: otherOwner, prevented: false, preventDefault() { this.prevented = true; }};+ otherOwner.emit("will-attach-webview", foreign, {}, {src: descriptor.src, partition: descriptor.partition});+ assert.equal(foreign.prevented, true);+ assert.equal(s.attach(descriptor, {event: {sender: otherOwner}}).attachEvent.prevented, true);+ for (const params of [{src: descriptor.src + "extra"}, {src: descriptor.src.split("#")[0]},+ {src: descriptor.src.replace("provider=openfreemap", "provider=other")},+ {partition: "siyuan-map-forged"}]) {+ assert.equal(s.attach(descriptor, {params}).attachEvent.prevented, true);+ }+ const {guest} = s.attach(descriptor);+ assert.equal(guest.destroyed, false, "foreign attempts cannot consume the owner's reservation");+ assert.equal(s.attach(descriptor).attachEvent.prevented, true);s.manager.destroyAll();});-test("production native menu closes with its map, policy revocation and renderer failure without changing sibling maps", () => {- for (const operation of [- s => s.handlers["siyuan-map-destroy"](s.event(), envelope),- s => s.handlers["siyuan-map-geometry"](s.event(), {...envelope, visible: false}),- (s, menu) => { s.setInitialized(false); menu.action("select", {id: "private-row"}); },- (_s, menu) => menu.view.webContents.emit("render-process-gone"),- ]) {- const s = setup(); readyMap(s);- const sibling = readyMap(s, "b".repeat(48));- const before = sibling.view.visibility.slice(), menu = openUnplaced(s);- operation(s, menu);- assert.equal(menu.view.webContents.isDestroyed(), true);- assert.equal(sibling.view.visible, true);- assert.deepEqual(sibling.view.visibility, before);- assert.equal(unplacedReplies(s).some(reply => reply.action === "select"), false);+managerTest("changing target mode revokes pending and admitted reservations before they can be reused", (_t, mode) => {+ for (const phase of ["reserved", "accepted", "attached", "ready"]) {+ const s = setup(undefined, mode, false), descriptor = s.create();+ let guest;+ if (phase !== "reserved") ({guest} = s.attach(descriptor, {deferCreated: phase === "accepted"}));+ if (phase === "ready") {+ guest.emit("did-finish-load");+ s.reply({type: "bootstrapReady"}); s.reply({type: "ready"});+ }+ s.target.mode = mode === "local" ? "remote" : "local";+ if (phase === "reserved") assert.equal(s.attach(descriptor).attachEvent.prevented, true);+ if (phase === "accepted") s.app.emit("web-contents-created", {}, guest);+ if (phase === "attached") guest.emit("did-finish-load");+ if (phase === "ready") s.command({type: "theme", theme: "dark"});+ if (guest) assert.equal(guest.destroyed, true, phase);+ if (phase !== "ready") assert.equal(s.channels.length, 0, phase);+ else assert.equal(s.channels[0].port1.closed, true);+ assert.equal(s.sessions[0].cleanup.length, 5, phase);+ assert.equal(s.attach(descriptor).attachEvent.prevented, true, "revoked partitions cannot be reused");+ const replacement = s.create();+ assert.equal(replacement.mode, "webview");+ assert.notEqual(replacement.partition, descriptor.partition);+ assert.equal(s.attach(replacement).guest.destroyed, false);s.manager.destroyAll();}});-const readyWebview = s => {- const descriptor = s.create();- const attached = s.attach(descriptor);- assert.equal(attached.attachEvent.prevented, false);- assert.equal(attached.guest.destroyed, false);- attached.guest.emit("did-finish-load");- s.reply({type: "bootstrapReady"});- s.reply({type: "ready"});- s.command({type: "visibility", visible: true, viewport: {x: 0, y: 0, width: 400, height: 300}});- return {...attached, descriptor};-};--test("local map reserves one fixed memory guest and installs its deny policy before first load", () => {- const s = setup(undefined, "local");+managerTest("map reserves one fixed memory guest and installs its deny policy before first load", (_t, mode) => {+ const s = setup(undefined, mode, false);const descriptor = s.create({mode: "native", src: "https://evil.invalid/", partition: "persist:evil"});assert.equal(descriptor.mode, "webview");assert.match(descriptor.partition, /^siyuan-map-[a-f0-9]{48}$/);assert.match(descriptor.src, new RegExp("^" + origin + "/stage/map/index.html\\?provider=openfreemap#" + instanceID + ":[a-f0-9]{48}$"));- assert.equal(s.views.length, 0);+ assert.equal(s.guests.length, 0);assert.equal(s.channels.length, 0);const {guest, preferences} = s.attach(descriptor);assert.equal(guest.session, s.sessions[0]);@@ -994,9 +817,9 @@ test("local map reserves one fixed memory guest and installs its deny policy befassert.equal(s.sessions[0].cleanup.length, 5);});-test("local guest initial zoom uses the verified owner after clearing untrusted preferences", () => {+managerTest("guest initial zoom uses the verified owner after clearing untrusted preferences", (_t, mode) => {for (const zoom of [0.25, 1.25, 5]) {- const s = setup(undefined, "local");+ const s = setup(undefined, mode, false);s.owner.zoom = zoom;const {attachEvent, guest, preferences} = s.attach(s.create(), {preferences: {zoomFactor: 99}});assert.equal(attachEvent.prevented, false);@@ -1007,9 +830,25 @@ test("local guest initial zoom uses the verified owner after clearing untrusted}});-test("local guest rejects invalid or unavailable owner zoom and releases its reservation", () => {+managerTest("every security preference mismatch rejects a guest before bootstrap", (_t, mode) => {+ for (const preference of ["sandbox", "contextIsolation", "webSecurity", "nodeIntegration", "nodeIntegrationInSubFrames",+ "nodeIntegrationInWorker", "webviewTag", "allowRunningInsecureContent", "experimentalFeatures", "disablePopups",+ "safeDialogs", "disableDialogs"]) {+ const s = setup(undefined, mode, false), descriptor = s.create();+ const {guest} = s.attach(descriptor, {contents: {+ getLastWebPreferences: () => ({...MAP_WEBVIEW_PREFERENCES, [preference]: !MAP_WEBVIEW_PREFERENCES[preference]}),+ }});+ assert.equal(guest.destroyed, true, preference);+ assert.equal(s.channels.length, 0, preference);+ assert.equal(s.sessions[0].cleanup.length, 5, preference);+ assert.equal(s.owner.sent.at(-1)[1].code, "hostAttachFailed", preference);+ s.manager.destroyAll();+ }+});++managerTest("guest rejects invalid or unavailable owner zoom and releases its reservation", (_t, mode) => {for (const zoom of [undefined, "1.25", NaN, Infinity, -Infinity, 0, -1, 0.249, 5.001, "throws"]) {- const s = setup(undefined, "local"), descriptor = s.create();+ const s = setup(undefined, mode, false), descriptor = s.create();s.owner.getZoomFactor = () => {if (zoom === "throws") throw new Error("destroyed");return zoom;@@ -1026,8 +865,8 @@ test("local guest rejects invalid or unavailable owner zoom and releases its res}});-test("attachment guards reject map forgeries without taking over ordinary webviews", () => {- const s = setup(undefined, "local"), descriptor = s.create();+managerTest("attachment guards reject map forgeries and preserve the target-specific ordinary webview policy", (_t, mode) => {+ const s = setup(undefined, mode, false), descriptor = s.create();for (const params of [{src: origin + "/api/private"}, {preload: "file:///private.js"}, {nodeintegration: true},{webpreferences: "sandbox=false"}, {disablewebsecurity: true}]) {assert.equal(s.attach(descriptor, {params}).attachEvent.prevented, true);@@ -1035,7 +874,7 @@ test("attachment guards reject map forgeries without taking over ordinary webvieconst ordinary = {sender: s.owner, prevented: false, preventDefault() { this.prevented = true; }};const ordinaryPrefs = {nodeIntegration: true};s.owner.emit("will-attach-webview", ordinary, ordinaryPrefs, {src: "https://example.invalid/", partition: "plugin-session"});- assert.equal(ordinary.prevented, false);+ assert.equal(ordinary.prevented, mode === "remote");assert.deepEqual(ordinaryPrefs, {nodeIntegration: true});const {guest} = s.attach(descriptor);const second = Object.assign(new EventEmitter(), {session: s.sessions[0], hostWebContents: {},@@ -1049,7 +888,7 @@ test("attachment guards reject map forgeries without taking over ordinary webvies.manager.destroyAll();});-test("pending local attachments close immediately on owner loss and cannot be revived by late guest creation", () => {+managerTest("pending attachments close immediately on owner loss and cannot be revived by late guest creation", (_t, mode) => {for (const invalidate of [s => s.owner.emit("did-start-navigation", {isMainFrame: true, isSameDocument: false}),s => s.owner.emit("destroyed"),@@ -1057,7 +896,7 @@ test("pending local attachments close immediately on owner loss and cannot be res => s.win.emit("closed"),s => s.handlers["siyuan-map-destroy"](s.event(), envelope),]) {- const s = setup(undefined, "local"), descriptor = s.create();+ const s = setup(undefined, mode, false), descriptor = s.create();const {guest} = s.attach(descriptor, {deferCreated: true});invalidate(s);assert.equal(s.sessions[0].cleanup.length, 5);@@ -1069,9 +908,9 @@ test("pending local attachments close immediately on owner loss and cannot be re}});-test("unattached map reservation uses the existing fixed bootstrap deadline", t => {+managerTest("unattached map reservation uses the existing fixed bootstrap deadline", (t, mode) => {t.mock.timers.enable({apis: ["setTimeout"]});- const s = setup(undefined, "local"), descriptor = s.create();+ const s = setup(undefined, mode, false), descriptor = s.create();t.mock.timers.tick(29999);assert.equal(s.sessions[0].cleanup.length, 0);t.mock.timers.tick(1);@@ -1081,8 +920,8 @@ test("unattached map reservation uses the existing fixed bootstrap deadline", ts.manager.destroyAll();});-test("local visibility is bounded and survives resize while native geometry and unplaced admission stay separate", () => {- const s = setup(undefined, "local"), {guest} = readyWebview(s);+managerTest("guest visibility is bounded and survives resize without native geometry or menu handlers", (_t, mode) => {+ const s = setup(undefined, mode, false), {guest} = readyWebview(s);const visibility = () => s.channels[0].port1.sent.filter(item => item.type === "visibility");const dismiss = () => s.owner.sent.filter(item => item[1].type === "dismissMenu");const mouse = () => guest.emit("before-mouse-event", {preventDefault() { assert.fail("map input must continue"); }}, {type: "mouseDown"});@@ -1091,26 +930,55 @@ test("local visibility is bounded and survives resize while native geometry ands.owner.emit("zoom-changed");mouse();assert.equal(dismiss().length, 1);- s.handlers["siyuan-map-geometry"](s.event(), {...envelope, visible: false});- mouse();- assert.equal(dismiss().length, 2, "native geometry cannot hide a DOM guest");- assert.equal(s.handlers["siyuan-map-unplaced-open"](s.event(), {...envelope}), undefined);+ assert.equal(s.handlers["siyuan-map-geometry"], undefined);+ assert.equal(s.handlers["siyuan-map-unplaced-open"], undefined);s.win.visible = false; s.win.emit("hide"); mouse();- assert.equal(dismiss().length, 2);+ assert.equal(dismiss().length, 1);assert.equal(visibility().at(-1).visible, false);s.win.visible = true; s.win.emit("show"); mouse();- assert.equal(dismiss().length, 3);+ assert.equal(dismiss().length, 2);assert.equal(visibility().at(-1).visible, true);s.command({type: "visibility", visible: true, viewport: {x: 0, y: 0, width: Infinity, height: 3}});assert.equal(visibility().at(-1).viewport.width, 400);s.command({type: "visibility", visible: false}); mouse();- assert.equal(dismiss().length, 3);- assert.equal(s.views.length, 0);+ assert.equal(dismiss().length, 2);+ assert.equal(s.guests.length, 1);+ s.manager.destroyAll();+});++managerTest("hidden bootstrap gets frames while window and DOM visibility remain authoritative", (_t, mode) => {+ const s = setup(undefined, mode); s.create(); s.load();+ const guest = s.guests[0];+ const visible = {type: "visibility", visible: true, viewport: {x: 0, y: 0, width: 400, height: 300}};+ const visibility = () => s.channels[0].port1.sent.filter(value => value.type === "visibility");+ assert.equal(guest.preferences.backgroundThrottling, false);+ assert.equal(guest.throttling, false);+ s.command(visible);+ assert.equal(visibility().length, 0, "the provider cannot receive a visible state before ready");+ s.command({type: "visibility", visible: false});+ s.reply({type: "bootstrapReady"}); s.reply({type: "ready"});+ assert.equal(guest.throttling, true);+ assert.equal(visibility().at(-1).visible, false);+ s.win.focused = false; s.win.emit("blur"); s.command(visible);+ assert.equal(visibility().at(-1).visible, true, "an unfocused visible window can paint the map");+ for (const [property, hiddenValue, hide, restore] of [+ ["visible", false, "hide", "show"], ["minimized", true, "minimize", "restore"],+ ]) {+ s.win[property] = hiddenValue; s.win.emit(hide);+ assert.equal(visibility().at(-1).visible, false);+ s.command(visible); s.win.emit("focus");+ assert.equal(visibility().at(-1).visible, false, "owner commands cannot expose a hidden window");+ s.win[property] = !hiddenValue; s.win.emit(restore);+ assert.equal(visibility().at(-1).visible, true);+ }+ s.command({type: "visibility", visible: false});+ s.win.focused = true; s.win.emit("focus");+ assert.equal(visibility().at(-1).visible, false, "focus cannot revive an owner-occluded map");s.manager.destroyAll();});-test("only current trusted guest input dismisses DOM menus; guest replies and revoked owners cannot", () => {- const s = setup(undefined, "local"), {guest} = readyWebview(s);+managerTest("only current trusted guest input dismisses DOM menus; guest replies and revoked owners cannot", (_t, mode) => {+ const s = setup(undefined, mode, false), {guest} = readyWebview(s);const dismiss = () => s.owner.sent.filter(item => item[1].type === "dismissMenu");s.reply({type: "dismissMenu"});assert.equal(dismiss().length, 0);@@ -1118,16 +986,16 @@ test("only current trusted guest input dismisses DOM menus; guest replies and reassert.deepEqual(dismiss().map(item => item[1]), [{...envelope, type: "dismissMenu"}]);s.win.focused = false; guest.emit("before-mouse-event", {}, {type: "mouseDown"}); s.win.focused = true;s.setInitialized(false); guest.emit("before-mouse-event", {}, {type: "mouseDown"}); s.setInitialized(true);- s.target.mode = "remote"; guest.emit("before-mouse-event", {}, {type: "mouseDown"});+ s.target.mode = mode === "local" ? "remote" : "local"; guest.emit("before-mouse-event", {}, {type: "mouseDown"});assert.equal(dismiss().length, 1);s.reply({type: "markerClick", id: "row", revision: 1});assert.equal(guest.destroyed, true, "mode changes revoke the old guest before accepting any reply");s.manager.destroyAll();});-test("local load requires verified attachment and exact one-shot document identity", () => {+managerTest("guest load requires verified attachment and exact one-shot document identity", (_t, mode) => {for (const failure of ["unverified", "hash", "other-document", "reload"]) {- const s = setup(undefined, "local"), descriptor = s.create();+ const s = setup(undefined, mode, false), descriptor = s.create();const {guest} = s.attach(descriptor, {skipVerified: failure === "unverified"});guest.emit("did-finish-load");if (failure === "hash") guest.emit("did-navigate-in-page");@@ -1140,18 +1008,18 @@ test("local load requires verified attachment and exact one-shot document identi}});-test("kernel target mode is authoritative and unknown modes are not registered owners", () => {- const s = setup();- assert.equal(s.create({mode: "webview"}).mode, "native");+managerTest("kernel target mode is authoritative and unknown modes are not registered owners", (_t, mode) => {+ const s = setup(undefined, mode);+ assert.equal(s.create({mode: "native"}).mode, "webview");s.manager.destroyAll();delete s.target.mode;assert.equal(s.handlers["siyuan-map-capability"](s.event()).reason, "unregisteredOwner");assert.throws(() => s.create());});-test("guest readback and closure races cannot escape Electron attachment callbacks", () => {+managerTest("guest readback and closure races cannot escape Electron attachment callbacks", (_t, mode) => {for (const phase of ["created", "attached", "close-throws"]) {- const s = setup(undefined, "local"), descriptor = s.create();+ const s = setup(undefined, mode, false), descriptor = s.create();let reads = 0;let attached;assert.doesNotThrow(() => {@@ -1174,7 +1042,7 @@ test("guest readback and closure races cannot escape Electron attachment callbacif (phase !== "close-throws") assert.equal(attached.guest.destroyed, true);s.manager.destroyAll();}- const s = setup(undefined, "local");+ const s = setup(undefined, mode, false);assert.doesNotThrow(() => s.app.emit("web-contents-created", {}, {setWindowOpenHandler() {}, isDestroyed: () => true,getType() { throw new Error("Object has been destroyed"); },diff --git a/app/electron/mapHostPolicy.js b/app/electron/mapHostPolicy.jsindex 917d154887..e85ea80d7d 100644--- a/app/electron/mapHostPolicy.js+++ b/app/electron/mapHostPolicy.js@@ -139,32 +139,6 @@ const createMapContentSecurityPolicy = origin => {"; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";};-// 渲染器传入 CSS 像素,原生视图使用设备无关像素,不能再乘屏幕像素密度。-const parseMapGeometry = (value, zoom, contentBounds, report = () => {}) => {- const reject = code => { report(code); return undefined; };- if (!isRecord(value) || typeof value.visible !== "boolean") return reject("geometryInvalid");- if (!value.visible) return {visible: false};- if (!Number.isFinite(zoom) || zoom < 0.25 || zoom > 5 || !isRecord(value.bounds) ||- !isRecord(value.logicalSize) || !isRecord(value.crop)) return reject("geometryInvalid");- const {x, y, width, height} = value.bounds;- const full = value.logicalSize;- const crop = value.crop;- const numbers = [x, y, width, height, full.width, full.height, crop.x, crop.y];- if (!numbers.every(Number.isFinite) || numbers.some(number => number < 0 || number > 32768)) return reject("geometryInvalid");- if (width < 1 || height < 1 || full.width < width || full.height < height) return reject("geometryLogicalBounds");- if (crop.x + width > full.width + 1 || crop.y + height > full.height + 1) return reject("geometryCropBounds");- if ((x + width) * zoom > contentBounds.width + 1 || (y + height) * zoom > contentBounds.height + 1) {- return reject("geometryWindowBounds");- }- // 向内取整,避免原生视图绘制到可见 DOM 矩形之外。- const left = Math.ceil(x * zoom), top = Math.ceil(y * zoom);- const right = Math.floor((x + width) * zoom), bottom = Math.floor((y + height) * zoom);- if (right <= left || bottom <= top) { report("geometryRoundedEmpty"); return {visible: false}; }- return {visible: true, zoom, bounds: {x: left, y: top, width: right - left, height: bottom - top},- logicalSize: {width: full.width, height: full.height},- crop: {x: crop.x + left / zoom - x, y: crop.y + top / zoom - y}};-};-module.exports = {mapHostFiles, unsafeMapSwitches, hasUnsafeMapSwitches, normalizeMapOrigin,- isMapInstanceID, parseMapCreate, parseMapCommand, parseMapReply, parseMapGeometry,+ isMapInstanceID, parseMapCreate, parseMapCommand, parseMapReply,isAllowedMapProviderURL, getMapRequestPolicy, createMapContentSecurityPolicy};diff --git a/app/electron/mapHostPolicy.test.js b/app/electron/mapHostPolicy.test.jsindex 556a3dbc38..898a529701 100644--- a/app/electron/mapHostPolicy.test.js+++ b/app/electron/mapHostPolicy.test.js@@ -2,7 +2,7 @@ const assert = require("node:assert/strict");const {test} = require("node:test");const {mapHostFiles, unsafeMapSwitches, hasUnsafeMapSwitches, normalizeMapOrigin, parseMapCreate, parseMapCommand,- parseMapReply, parseMapGeometry, isAllowedMapProviderURL, getMapRequestPolicy, createMapContentSecurityPolicy,+ parseMapReply, isAllowedMapProviderURL, getMapRequestPolicy, createMapContentSecurityPolicy,} = require("./mapHostPolicy");const instanceID = "a".repeat(48);@@ -204,40 +204,3 @@ test("OpenFreeMap CSP scopes bundled scripts, worker, styles and tile requests tassert.deepEqual(directives.sandbox, ["allow-scripts"]);assert.equal(getMapRequestPolicy("https://tiles.openfreemap.org/resource", "GET", origin).type, "provider");});--test("native geometry converts CSS to DIP, crops inward, and denies off-window or malformed bounds", () => {- const value = {visible: true, bounds: {x: 10.2, y: 20, width: 200, height: 100},- logicalSize: {width: 400, height: 200}, crop: {x: 40, y: 30}};- const geometry = parseMapGeometry(value, 1.25, {width: 800, height: 600});- assert.deepEqual(geometry.bounds, {x: 13, y: 25, width: 249, height: 125});- assert.equal(geometry.logicalSize.width, 400);- assert.ok(Math.abs(geometry.crop.x - 40.2) < 1e-9);- assert.equal(parseMapGeometry(value, 0, {width: 800, height: 600}), undefined);- assert.equal(parseMapGeometry(value, 1.25, {width: 100, height: 100}), undefined);- assert.equal(parseMapGeometry({...value, crop: {x: 300, y: 0}}, 1, {width: 800, height: 600}), undefined);- assert.equal(parseMapGeometry({...value, bounds: {...value.bounds, x: NaN}}, 1, {width: 800, height: 600}), undefined);- assert.deepEqual(parseMapGeometry({visible: false}, 1, {}), {visible: false});-});--test("geometry rejection reports only fixed reasons without weakening validation", () => {- const value = {visible: true, bounds: {x: 10, y: 20, width: 200, height: 100},- logicalSize: {width: 400, height: 200}, crop: {x: 0, y: 0}};- const viewport = {width: 800, height: 600};- for (const [input, zoom, bounds, reason] of [- [null, 1, viewport, "geometryInvalid"],- [value, 0, viewport, "geometryInvalid"],- [{...value, bounds: {...value.bounds, x: NaN}}, 1, viewport, "geometryInvalid"],- [{...value, logicalSize: {width: 199.99999999999997, height: 200}}, 1, viewport, "geometryLogicalBounds"],- [{...value, crop: {x: 300, y: 0}}, 1, viewport, "geometryCropBounds"],- [value, 1, {width: 100, height: 100}, "geometryWindowBounds"],- [{...value, bounds: {x: 0.1, y: 0.1, width: 1, height: 1}}, 0.25, viewport, "geometryRoundedEmpty"],- ]) {- const reasons = [];- const result = parseMapGeometry(input, zoom, bounds, code => reasons.push(code));- assert.ok(!result?.visible);- assert.deepEqual(reasons, [reason]);- }- const reasons = [];- assert.deepEqual(parseMapGeometry({visible: false}, 1, viewport, code => reasons.push(code)), {visible: false});- assert.deepEqual(reasons, []);-});diff --git a/app/electron/mapHostPreload.js b/app/electron/mapHostPreload.jsindex 048c70f6ad..16b5dcf4a1 100644--- a/app/electron/mapHostPreload.js+++ b/app/electron/mapHostPreload.js@@ -17,14 +17,4 @@ if (process.isMainFrame) {window.postMessage({type: "siyuan-map-desktop-connect", version: 1, instanceID: data.instanceID,nonce: data.nonce, provider: data.provider}, "*", [event.ports[0]]);});- ipcRenderer.on("siyuan-map-viewport", (_event, data) => {- const map = document.getElementById("map");- const size = data?.logicalSize;- const crop = data?.crop;- if (!map || !size || !crop || ![size.width, size.height, crop.x, crop.y]- .every(value => Number.isFinite(value) && value >= 0 && value <= 32768)) return;- map.style.width = size.width + "px";- map.style.height = size.height + "px";- map.style.transform = "translate(" + -crop.x + "px," + -crop.y + "px)";- });}diff --git a/app/electron/mapHostPreload.test.js b/app/electron/mapHostPreload.test.jsindex d31bc6230b..eed02dcd71 100644--- a/app/electron/mapHostPreload.test.js+++ b/app/electron/mapHostPreload.test.js@@ -51,12 +51,3 @@ test("the transferred map port only admits the fixed OpenFreeMap provider", () =assert.equal(s.posted.length, 0);}});--test("viewport accepts only bounded numeric dimensions and crop, without exposing IPC", () => {- const s = setup();- s.listeners["siyuan-map-viewport"]({}, {logicalSize: {width: 500, height: 400}, crop: {x: 20, y: 40}});- assert.equal(s.map.style.width, "500px"); assert.equal(s.map.style.height, "400px");- assert.equal(s.map.style.transform, "translate(-20px,-40px)");- s.listeners["siyuan-map-viewport"]({}, {logicalSize: {width: "url(secret)", height: 400}, crop: {x: 0, y: 0}});- assert.equal(s.map.style.width, "500px");-});diff --git a/app/electron/mapOwnerRegistration.test.js b/app/electron/mapOwnerRegistration.test.jsnew file mode 100644index 0000000000..86e220dfde--- /dev/null+++ b/app/electron/mapOwnerRegistration.test.js@@ -0,0 +1,39 @@+const assert = require("node:assert/strict");+const {EventEmitter} = require("node:events");+const {readFileSync} = require("node:fs");+const {join} = require("node:path");+const {test} = require("node:test");+const {runInNewContext} = require("node:vm");+const {shouldBlockRemoteFrameNavigation} = require("./remoteKernel");++test("window target registration installs the map guard before remote document events and retains subframe denial", () => {+ const source = readFileSync(join(__dirname, "main.js"), "utf8");+ const start = source.indexOf("const rememberWindowKernelTarget =");+ const end = source.indexOf("\nconst getWindowKernelTarget", start);+ const targets = new Map(), initialized = new Set([42]), registered = [];+ const scope = {+ windowKernelTargets: targets, initializedWindowIds: initialized,+ blockDragWindowFocusOrder: new Map(), blockDragWindowFocusSequence: 0,+ mapHostManager: {registerOwner(contents) {+ assert.equal(targets.get(contents.id)?.mode, "remote");+ assert.equal(contents.eventNames().length, 0);+ registered.push(contents);+ }},+ shouldBlockRemoteFrameNavigation, writeLog() {}, cleanupBlockDragSessions() {}, cleanupBlockDragWindow() {},+ };+ const register = runInNewContext(source.slice(start, end) + "\nrememberWindowKernelTarget;", scope);+ const owner = Object.assign(new EventEmitter(), {id: 42});+ const win = Object.assign(new EventEmitter(), {webContents: owner});+ register(win, {mode: "remote", origin: "https://example.invalid"});+ assert.deepEqual(registered, [owner]);+ let blocked = 0;+ owner.emit("will-frame-navigate", {isMainFrame: false, preventDefault() { blocked++; }});+ owner.emit("will-frame-navigate", {isMainFrame: true, preventDefault() { blocked++; }});+ assert.equal(blocked, 1);+ owner.emit("did-start-navigation", {isMainFrame: true, isSameDocument: false});+ assert.equal(initialized.has(42), false);+ owner.emit("destroyed");+ assert.equal(targets.has(42), false);+ assert.match(source, /mapHostManager = createMapHostManager/);+ assert.equal((source.match(/webSecurity: kernelTarget\.mode === "remote"/g) || []).length, 2);+});diff --git a/app/electron/mapUnplaced/manager.js b/app/electron/mapUnplaced/manager.jsdeleted file mode 100644index ebad1f7439..0000000000--- a/app/electron/mapUnplaced/manager.js+++ /dev/null@@ -1,267 +0,0 @@-const path = require("node:path");-const fs = require("node:fs/promises");-const {randomBytes} = require("node:crypto");-const {ORIGIN, CHANNEL, PAGE_SIZE, CSP, keys, parseTheme, parseState, parseAction, parseAnchor, place, resource} = require("./policy");--const deny = () => new Response("Forbidden", {status: 403});-const clearSession = ses => {- for (const method of ["closeAllConnections", "clearStorageData", "clearAuthCache", "clearCache", "clearHostResolverCache"]) {- try { void Promise.resolve(ses[method]()).catch(() => {}); } catch (_error) { /* 继续清理其他状态。 */ }- }-};-const createRouter = (ses, assets, readFile = fs.readFile, onResourceFailure = () => {}) => {- let destroyed = false, documentRequested = false;- ses.setPermissionRequestHandler((_contents, _permission, callback) => callback(false));- ses.setPermissionCheckHandler(() => false);- ses.setDevicePermissionHandler(() => false);- ses.setDisplayMediaRequestHandler((_request, callback) => callback({}));- ses.setCertificateVerifyProc((_request, callback) => callback(-3));- ses.allowNTLMCredentialsForDomains("");- ses.on("will-download", event => event.preventDefault());- ses.webRequest.onBeforeRequest((request, callback) => {- const entry = resource(request.url, request.method);- let allowed = !destroyed && entry && entry[2] === request.resourceType;- if (request.resourceType === "mainFrame") {- allowed = allowed && !documentRequested;- if (allowed) documentRequested = true;- }- callback({cancel: !allowed});- });- ses.webRequest.onBeforeSendHeaders((_details, callback) => callback({cancel: destroyed, requestHeaders: {}}));- const handle = async request => {- const entry = resource(request.url, request.method);- if (destroyed || !entry || request.headers.get("service-worker")) return deny();- try {- const body = entry[0] === "controls.css" ?- assets.controls ?? await readFile(assets.controlsPath) : await readFile(path.join(__dirname, entry[0]));- if (destroyed) return deny();- return new Response(request.method === "HEAD" ? null : body, {headers: {- "Content-Type": entry[1], "Content-Security-Policy": CSP, "Cache-Control": "no-store",- "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer",- "Permissions-Policy": "geolocation=(), camera=(), microphone=(), payment=(), usb=(), serial=(), bluetooth=()",- }});- } catch (_error) {- if (!destroyed) onResourceFailure();- return new Response("Not Found", {status: 404});- }- };- ses.protocol.handle("https", handle);- ses.protocol.handle("http", deny);- ses.protocol.handle("file", deny);- return {destroy() {- if (destroyed) return;- destroyed = true;- clearSession(ses);- }};-};--// 菜单只保留当前页的纯文本;真实查询、权限和最终行对象始终由可信 owner 管理。-const createManager = ({ipcMain, session, WebContentsView, owner, win, ownerURL, outsideContents = [], assets,- onAction, onClose = () => {}, onVisibility = () => {}, mayUse = () => true, readFile,- randomID = () => randomBytes(24).toString("hex"), handleActions = true}) => {- let host, disposed = false;- const ownerFrame = owner.mainFrame;- const listeners = [];- const listen = (emitter, name, fn, list = listeners) => {- const guarded = (...args) => {- try { fn(...args); } catch (_error) { close("operation-failed"); }- };- emitter.on(name, guarded);- list.push([emitter, name, guarded]);- };- const currentOwner = () => !disposed && !owner.isDestroyed() && !win.isDestroyed() &&- owner.mainFrame === ownerFrame && ownerFrame.url === ownerURL;- const trusted = event => currentOwner() && event?.sender === owner && event.senderFrame === owner.mainFrame;- const permitted = () => { try { return mayUse() === true; } catch (_error) { return false; } };- const close = (reason, restore = false, notify = true) => {- const previous = host;- if (!previous) return;- host = undefined;- clearTimeout(previous.timer);- previous.ids.clear();- previous.state.rows = [];- for (const [emitter, name, fn] of previous.listeners) emitter.removeListener(name, fn);- previous.router.destroy();- try { if (!win.isDestroyed()) win.contentView.removeChildView(previous.view); } catch (_error) { /* 继续关闭渲染器。 */ }- const contents = previous.view.webContents;- if (!contents.isDestroyed()) {- try { contents.stop(); } catch (_error) { /* 继续关闭渲染器。 */ }- try { contents.close({waitForBeforeUnload: false}); } catch (_error) { /* 渲染器可能已关闭。 */ }- }- if (previous.ready) onVisibility(false);- if (restore && currentOwner() && win.isFocused()) {- try { owner.focus(); } catch (_error) { /* 关闭仍然完成,不抢其他窗口焦点。 */ }- }- if (notify) onClose({sessionID: previous.sessionID, reason, restore});- };- const geometry = () => {- if (!host) return false;- if (!currentOwner()) { close("owner-unavailable"); return false; }- const zoom = owner.getZoomFactor();- const bounds = place(host.anchor, zoom, win.getContentBounds(), host.preferredHeight);- if (!permitted() || !win.isVisible() || win.isMinimized?.() || !bounds) { close("unavailable"); return false; }- const key = JSON.stringify({bounds, zoom});- if (host.geometryKey !== key) {- host.view.webContents.setZoomFactor(zoom);- host.view.setBounds(bounds);- host.geometryKey = key;- }- return true;- };- const sendState = () => {- if (host?.ready) host.view.webContents.send(CHANNEL + "-state", {sessionID: host.sessionID, state: host.state});- };- const stateIDs = state => new Set(state.loading || state.error ? [] : state.rows.map(row => row.id));- const open = (event, value) => {- if (!trusted(event) || !permitted() || !keys(value, ["state", "anchor"])) return;- const state = parseState(value.state), anchor = parseAnchor(value.anchor);- if (!state || state.requestID !== 0 || !anchor || !place(anchor, owner.getZoomFactor(), win.getContentBounds())) return;- close("replace");- const sessionID = randomID();- let ses, router, view;- try {- ses = session.fromPartition("siyuan-map-unplaced-" + sessionID, {cache: false});- router = createRouter(ses, assets, readFile, () => { if (host?.sessionID === sessionID) close("resource-failed"); });- view = new WebContentsView({webPreferences: {session: ses, preload: path.join(__dirname, "preload.js"),- additionalArguments: ["--unplaced-session=" + sessionID], nodeIntegration: false,- nodeIntegrationInWorker: false, nodeIntegrationInSubFrames: false, contextIsolation: true, sandbox: true,- webSecurity: true, webviewTag: false, allowRunningInsecureContent: false, devTools: false,- navigateOnDragDrop: false, safeDialogs: true, disableDialogs: true, spellcheck: false}});- host = {sessionID, view, router, state, anchor, ids: stateIDs(state), ready: false, listeners: [],- pending: state.loading, query: state.query, page: state.page, requestID: 0};- const active = host;- const contents = view.webContents;- view.setBackgroundColor("#00000000");- contents.setWindowOpenHandler(() => ({action: "deny"}));- for (const name of ["will-navigate", "will-frame-navigate", "will-redirect", "will-attach-webview"]) {- listen(contents, name, event => event.preventDefault(), host.listeners);- }- listen(contents, "login", (event, _details, _info, callback) => { event.preventDefault(); callback(); }, host.listeners);- listen(contents, "select-client-certificate", (event, _url, _certificates, callback) => { event.preventDefault(); callback(); }, host.listeners);- listen(contents, "certificate-error", (_event, _url, _error, _certificate, callback) => callback(false), host.listeners);- listen(contents, "did-finish-load", () => {- if (active.loaded || contents.getURL() !== ORIGIN + "/menu.html") { close("document-mismatch"); return; }- active.loaded = true;- }, host.listeners);- for (const name of ["render-process-gone", "destroyed", "did-fail-load"]) {- listen(contents, name, () => { if (host === active) close("renderer-failed"); }, host.listeners);- }- host.timer = setTimeout(() => { if (host === active) close("ready-timeout"); }, 10000);- host.timer.unref?.();- view.setVisible(false);- win.contentView.addChildView(view);- if (!geometry()) return;- void contents.loadURL(ORIGIN + "/menu.html").catch(() => { if (host === active) close("load-failed"); });- return sessionID;- } catch (_error) {- if (host?.sessionID === sessionID) close("setup-failed");- else {- if (router) router.destroy(); else if (ses) clearSession(ses);- try { if (view && !view.webContents.isDestroyed()) view.webContents.close({waitForBeforeUnload: false}); } catch (_failure) { /* 保留拒绝网络策略。 */ }- }- }- };- const update = (event, value) => {- if (!trusted(event) || !host || !keys(value, ["sessionID", "state"]) || value.sessionID !== host.sessionID) return false;- if (!permitted()) { close("permission-revoked"); return false; }- const state = parseState(value.state);- if (!state || state.revision <= host.state.revision || state.requestID !== host.requestID ||- state.query !== host.query || state.page !== host.page) return false;- host.state = state;- host.ids = stateIDs(state);- host.pending = state.loading;- sendState();- return true;- };- const setAnchor = (event, value) => {- if (!trusted(event) || !host || !keys(value, ["sessionID", "anchor"]) || value.sessionID !== host.sessionID) return false;- const anchor = parseAnchor(value.anchor);- if (!anchor) return false;- host.anchor = anchor;- return geometry();- };- const setTheme = (event, value) => {- if (!trusted(event) || !host || !keys(value, ["sessionID", "theme"]) || value.sessionID !== host.sessionID) return false;- if (!permitted()) { close("permission-revoked"); return false; }- const theme = parseTheme(value.theme);- if (!theme) return false;- // 主题更新不推进数据 revision,避免已发出的编辑、翻页和选择动作变成过期消息。- host.state.theme = theme;- if (host.ready) host.view.webContents.send(CHANNEL + "-theme", {sessionID: host.sessionID, theme});- return true;- };- const message = (event, value) => {- if (host && !currentOwner()) { close("owner-unavailable"); return; }- const action = parseAction(value);- if (!host || !action || event.sender !== host.view.webContents || event.senderFrame !== event.sender.mainFrame ||- event.senderFrame.url !== ORIGIN + "/menu.html" || action.sessionID !== host.sessionID) return;- if (!permitted()) { close("permission-revoked"); return; }- if (action.type === "ready") {- if (host.ready || action.revision !== 0) return;- host.ready = true;- clearTimeout(host.timer);- sendState();- if (geometry()) { host.view.setVisible(true); onVisibility(true); host.view.webContents.focus(); }- return;- }- if (!host.ready || action.revision !== host.state.revision) return;- if (action.type === "resize") {- host.preferredHeight = action.height;- geometry();- return;- }- if (action.type === "close") { close(action.reason, true); return; }- if (action.type === "editing") {- host.ids.clear();- host.pending = true;- host.query = undefined;- onAction({...action, requestID: ++host.requestID});- return;- }- if (action.type === "select") {- if (!host.ids.has(action.id)) return;- const requestID = host.requestID;- // 选择是唯一终止消息;owner 必须先取回私有行对象,再清理自己的会话状态。- close("select", true, false);- onAction({...action, requestID});- return;- }- if (action.type !== "search" && host.pending) return;- if (action.type === "more" && (host.state.error || host.state.page * PAGE_SIZE >= host.state.total)) return;- if (action.type === "previous" && host.state.page <= 1 || action.type === "retry" && !host.state.error) return;- host.ids.clear();- host.pending = true;- host.query = action.type === "search" ? action.query.trim() : host.state.query;- host.page = action.type === "search" ? 1 : host.state.page + (action.type === "more" ? 1 : action.type === "previous" ? -1 : 0);- onAction({...action, query: host.query, page: host.page, requestID: ++host.requestID});- };- if (handleActions) listen(ipcMain, CHANNEL + "-action", message);- const outside = (_event, input) => { if (input.type === "mouseDown") close("outside"); };- for (const contents of outsideContents) listen(contents, "before-mouse-event", outside);- for (const name of ["blur", "hide", "minimize", "closed"]) listen(win, name, () => close("window-" + name));- for (const name of ["resize", "move"]) listen(win, name, geometry);- listen(owner, "zoom-changed", geometry);- for (const name of ["will-navigate", "destroyed", "render-process-gone"]) listen(owner, name, () => close("owner-" + name));- listen(owner, "did-start-navigation", details => { if (details.isMainFrame) close("owner-navigation"); });- return {open, update, setAnchor, setTheme, action: message,- close(event, value) {- if (trusted(event) && host && keys(value, ["sessionID", "reason"]) && value.sessionID === host.sessionID &&- ["outside", "button", "anchor-hidden"].includes(value.reason)) close(value.reason, value.reason === "button");- },- revoke() { close("permission-revoked"); },- dismiss(reason = "outside") { close(reason); },- promote() {- if (!host || !currentOwner() || !permitted()) return;- try { win.contentView.addChildView(host.view); } catch (_error) { close("operation-failed"); }- },- destroy() {- if (disposed) return;- close("destroy");- disposed = true;- for (const [emitter, name, fn] of listeners) emitter.removeListener(name, fn);- },- // 仅供主进程测试读取,不通过 renderer 桥暴露。- inspect: () => host && {sessionID: host.sessionID, view: host.view, ready: host.ready},- };-};-module.exports = {createRouter, createManager};diff --git a/app/electron/mapUnplaced/menu.css b/app/electron/mapUnplaced/menu.cssdeleted file mode 100644index 289bd2410a..0000000000--- a/app/electron/mapUnplaced/menu.css+++ /dev/null@@ -1,29 +0,0 @@-:root[data-font-size="12"] { --b3-font-size: 12px; }-:root[data-font-size="13"] { --b3-font-size: 13px; }-:root[data-font-size="14"] { --b3-font-size: 14px; }-:root[data-font-size="15"] { --b3-font-size: 15px; }-:root[data-font-size="16"] { --b3-font-size: 16px; }-:root[data-font-size="17"] { --b3-font-size: 17px; }-:root[data-font-size="18"] { --b3-font-size: 18px; }-:root[data-font-size="19"] { --b3-font-size: 19px; }-:root[data-font-size="20"] { --b3-font-size: 20px; }-:root[data-font-size="21"] { --b3-font-size: 21px; }-:root[data-font-size="22"] { --b3-font-size: 22px; }-:root[data-font-size="23"] { --b3-font-size: 23px; }-:root[data-font-size="24"] { --b3-font-size: 24px; }-:root[data-font-size="25"] { --b3-font-size: 25px; }-:root[data-font-size="26"] { --b3-font-size: 26px; }-:root[data-font-size="27"] { --b3-font-size: 27px; }-:root[data-font-size="28"] { --b3-font-size: 28px; }-:root[data-font-size="29"] { --b3-font-size: 29px; }-:root[data-font-size="30"] { --b3-font-size: 30px; }-:root[data-font-size="31"] { --b3-font-size: 31px; }-:root[data-font-size="32"] { --b3-font-size: 32px; }-html, body { height: 100%; margin: 0; overflow: hidden; background: transparent; }-.map-unplaced-menu { inset: 24px 24px auto; display: flex; flex-direction: column; max-height: calc(100vh - 48px); overflow: auto; }-.map-unplaced-menu--measure { max-height: none; }-.av-records-panel-head, .av-records-panel-search, .map-unplaced-menu footer { flex-shrink: 0; }-.av-records-panel-item { gap: 4px; }-.map-unplaced-menu footer { display: flex; flex-wrap: wrap; padding: 4px 8px 0; }-.map-unplaced-menu footer .b3-button { flex: 1 1 auto; white-space: normal; overflow-wrap: anywhere; }-.map-unplaced-menu [hidden], body > [hidden] { display: none; }diff --git a/app/electron/mapUnplaced/menu.html b/app/electron/mapUnplaced/menu.htmldeleted file mode 100644index 6d2fb7f441..0000000000--- a/app/electron/mapUnplaced/menu.html+++ /dev/null@@ -1,28 +0,0 @@-<!doctype html>-<html lang="zh-CN" data-theme="light" data-theme-mode="light" data-font-size="14">-<head>- <meta charset="utf-8">- <meta name="viewport" content="width=device-width, initial-scale=1">- <link rel="stylesheet" href="/controls.css">- <link rel="stylesheet" href="/menu.css">- <script defer src="/menu.js"></script>- <title></title>-</head>-<body>- <svg hidden aria-hidden="true" xmlns="http://www.w3.org/2000/svg">- <symbol id="iconOpen" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">- <path d="M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6"/><path d="m21 3-9 9"/><path d="M15 3h6v6"/>- </symbol>- <symbol id="iconFile" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">- <path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"/><path d="M14 2v5a1 1 0 0 0 1 1h5"/>- </symbol>- </svg>- <section id="menu" class="b3-menu av-records-panel map-unplaced-menu" role="dialog" aria-labelledby="title">- <header class="av-records-panel-head"><span id="title" class="b3-menu__label"></span><span id="count" class="counter counter--bg"></span></header>- <div class="av-records-panel-search"><input id="search" class="b3-text-field" type="search" maxlength="256"></div>- <div id="rows" class="b3-menu__items av-records-panel-list" role="group"></div>- <div id="status" class="av-records-panel-empty" role="status" aria-live="polite" hidden></div>- <footer><button id="previous" class="b3-button b3-button--cancel" type="button" hidden></button><button id="more" class="b3-button b3-button--cancel" type="button" hidden></button><button id="close" class="b3-button b3-button--cancel" type="button"></button></footer>- </section>-</body>-</html>diff --git a/app/electron/mapUnplaced/menu.js b/app/electron/mapUnplaced/menu.jsdeleted file mode 100644index 165be4d5d0..0000000000--- a/app/electron/mapUnplaced/menu.js+++ /dev/null@@ -1,155 +0,0 @@-(() => {- const bridge = window.unplacedMenu;- const menu = document.getElementById("menu");- const input = document.getElementById("search");- const rows = document.getElementById("rows");- const status = document.getElementById("status");- const more = document.getElementById("more");- const previous = document.getElementById("previous");- let composing = false, timer, first = true, lastQuery = "", state, pending = false, awaitingSearch = false, searchSent = false;- let reportedHeight = 0, reportedRevision = -1;- const resize = () => {- if (!state) return;- // 临时解除当前原生窗口的高度限制,测量后立即恢复,避免逐次缩小。- menu.classList.add("map-unplaced-menu--measure");- const height = Math.max(50, Math.min(4096, Math.ceil(menu.getBoundingClientRect().height + 48)));- menu.classList.remove("map-unplaced-menu--measure");- if (height !== reportedHeight || state.revision !== reportedRevision) {- reportedHeight = height;- reportedRevision = state.revision;- bridge.resize(height);- }- };- const observer = new ResizeObserver(resize);- observer.observe(menu);- const icon = (name, className) => {- const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");- svg.setAttribute("class", className);- svg.setAttribute("aria-hidden", "true");- const use = document.createElementNS("http://www.w3.org/2000/svg", "use");- use.setAttribute("href", "#" + name);- svg.append(use);- return svg;- };- const disableRows = () => { for (const row of rows.children) row.disabled = true; };- const search = () => {- clearTimeout(timer);- pending = true;- awaitingSearch = true;- searchSent = false;- bridge.editing();- disableRows();- more.disabled = true;- previous.disabled = true;- timer = setTimeout(() => {- lastQuery = input.value.trim();- searchSent = true;- bridge.search(lastQuery);- }, 200);- };- input.addEventListener("compositionstart", () => {- composing = true;- pending = true;- awaitingSearch = true;- searchSent = false;- clearTimeout(timer);- disableRows();- more.disabled = true;- previous.disabled = true;- bridge.editing();- });- input.addEventListener("compositionend", () => { composing = false; search(); });- input.addEventListener("input", event => { if (!composing && !event.isComposing) search(); });- more.addEventListener("click", () => {- if (pending || !state || more.disabled) return;- pending = true;- disableRows();- more.disabled = true;- previous.disabled = true;- if (state.error) bridge.retry(); else bridge.more();- });- previous.addEventListener("click", () => {- if (pending || !state || previous.disabled) return;- pending = true;- disableRows();- more.disabled = true;- previous.disabled = true;- bridge.previous();- });- document.getElementById("close").addEventListener("click", () => bridge.close("button"));- document.addEventListener("pointerdown", event => {- if (!menu.contains(event.target)) bridge.close("button");- });- // 共享 reset 去掉原生 outline;键盘焦点复用菜单已有的 current 状态反馈。- document.addEventListener("focusin", event => {- if (event.target.classList?.contains("b3-menu__item")) event.target.classList.add("b3-menu__item--current");- });- document.addEventListener("focusout", event => {- event.target.classList?.remove("b3-menu__item--current");- });- document.addEventListener("keydown", event => {- if (event.isComposing || composing) return;- if (event.key === "Escape") { event.preventDefault(); bridge.close("escape"); return; }- if (!["ArrowDown", "ArrowUp"].includes(event.key)) return;- const buttons = Array.from(rows.children).filter(row => !row.disabled);- if (!buttons.length) return;- const index = buttons.indexOf(document.activeElement);- const next = event.key === "ArrowDown" ? (index + 1) % buttons.length : (index < 0 ? buttons.length - 1 : (index + buttons.length - 1) % buttons.length);- event.preventDefault();- buttons[next].focus();- });- window.addEventListener("pagehide", () => { clearTimeout(timer); observer.disconnect(); state = undefined; });- const applyTheme = theme => {- document.documentElement.dataset.theme = theme.mode;- document.documentElement.dataset.themeMode = theme.mode;- document.documentElement.dataset.fontSize = String(theme.fontSize);- resize();- };- bridge.subscribe(value => {- applyTheme(value.theme);- if (composing || awaitingSearch && (!searchSent || value.query !== lastQuery)) return;- state = value;- pending = value.loading;- if (!value.loading) awaitingSearch = false;- document.title = value.labels.title;- document.getElementById("title").textContent = value.labels.title;- document.getElementById("count").textContent = value.loading ? "" : String(value.total);- document.getElementById("count").hidden = value.loading;- input.placeholder = value.labels.search;- input.setAttribute("aria-label", value.labels.search);- if (first) { input.value = value.query; lastQuery = value.query; }- const focusedID = document.activeElement?.dataset?.rowId;- rows.replaceChildren();- for (const row of value.rows) {- const button = document.createElement("button");- button.type = "button";- button.className = "b3-menu__item av-records-panel-item";- button.dataset.rowId = row.id;- button.disabled = value.loading || value.error;- const label = document.createElement("span");- label.className = "b3-menu__label";- label.textContent = row.title;- button.append(icon("iconFile", "b3-menu__icon"));- button.append(label);- const open = document.createElement("span");- open.className = "block__icon block__icon--show";- open.setAttribute("aria-hidden", "true");- open.append(icon("iconOpen", ""));- button.append(open);- button.addEventListener("click", () => { if (!pending && !button.disabled) bridge.select(row.id); });- rows.append(button);- if (focusedID === row.id) button.focus();- }- status.textContent = value.loading ? value.labels.loading : value.error ? value.labels.retry : value.rows.length ? "" : value.labels.empty;- status.hidden = !status.textContent;- more.textContent = value.error ? value.labels.retry : value.labels.more;- more.hidden = !value.error && value.page * 50 >= value.total;- more.disabled = value.loading;- previous.textContent = value.labels.previous;- previous.hidden = value.page <= 1;- previous.disabled = value.loading;- document.getElementById("close").textContent = value.labels.close;- if (first) { first = false; input.focus(); }- resize();- }, applyTheme);-})();diff --git a/app/electron/mapUnplaced/policy.js b/app/electron/mapUnplaced/policy.jsdeleted file mode 100644index 32a2ca82c4..0000000000--- a/app/electron/mapUnplaced/policy.js+++ /dev/null@@ -1,74 +0,0 @@-const ORIGIN = "https://siyuan-unplaced.invalid";-const CHANNEL = "siyuan-map-unplaced-menu";-const PAGE_SIZE = 50;-const RESOURCES = Object.freeze({- "/menu.html": ["menu.html", "text/html; charset=utf-8", "mainFrame"],- "/menu.js": ["menu.js", "text/javascript; charset=utf-8", "script"],- "/menu.css": ["menu.css", "text/css; charset=utf-8", "stylesheet"],- "/controls.css": ["controls.css", "text/css; charset=utf-8", "stylesheet"],-});-const CSP = "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'none'; img-src 'none'; " +- "font-src 'none'; media-src 'none'; frame-src 'none'; object-src 'none'; worker-src 'none'; " +- "base-uri 'none'; form-action 'none'; frame-ancestors 'none'";-const keys = (value, names) => !!value && typeof value === "object" && !Array.isArray(value) &&- Object.keys(value).length === names.length && names.every(name => Object.hasOwn(value, name));-const text = (value, max) => typeof value === "string" && value.length <= max && !value.includes("\0");-const integer = (value, max) => Number.isSafeInteger(value) && value >= 0 && value <= max;-const isSession = value => typeof value === "string" && /^[a-f0-9]{48}$/.test(value);-const isRevision = value => integer(value, Number.MAX_SAFE_INTEGER);-const parseTheme = value => keys(value, ["mode", "fontSize"]) && ["light", "dark"].includes(value.mode) &&- integer(value.fontSize, 32) && value.fontSize >= 12 ? {...value} : undefined;-const parseState = value => {- if (!keys(value, ["revision", "requestID", "query", "rows", "total", "page", "loading", "error", "theme", "labels"]) ||- !isRevision(value.revision) || !isRevision(value.requestID) || !text(value.query, 256) || !isRevision(value.total) ||- !integer(value.page, Math.ceil(Number.MAX_SAFE_INTEGER / PAGE_SIZE)) || value.page < 1 ||- typeof value.loading !== "boolean" || typeof value.error !== "boolean" ||- !Array.isArray(value.rows) || value.rows.length > PAGE_SIZE || value.rows.length > value.total ||- !parseTheme(value.theme)) return;- const names = ["title", "search", "empty", "loading", "more", "previous", "retry", "close"];- if (!keys(value.labels, names) || names.some(name => !text(value.labels[name], 120))) return;- const ids = new Set();- const rows = [];- for (const row of value.rows) {- if (!keys(row, ["id", "title"]) || !text(row.id, 128) || !row.id || !text(row.title, 2048) || ids.has(row.id)) return;- ids.add(row.id);- rows.push({id: row.id, title: row.title});- }- return {revision: value.revision, requestID: value.requestID, query: value.query, rows, total: value.total, page: value.page,- loading: value.loading, error: value.error, theme: {...value.theme}, labels: {...value.labels}};-};-const parseAction = value => {- if (!value || !isSession(value.sessionID) || !isRevision(value.revision)) return;- const base = ["sessionID", "revision", "type"];- if (["ready", "editing", "more", "previous", "retry"].includes(value.type) && keys(value, base)) return {...value};- if (value.type === "search" && keys(value, [...base, "query"]) && text(value.query, 256)) return {...value};- if (value.type === "select" && keys(value, [...base, "id"]) && text(value.id, 128) && value.id) return {...value};- if (value.type === "resize" && keys(value, [...base, "height"]) && integer(value.height, 4096) && value.height >= 50) return {...value};- if (value.type === "close" && keys(value, [...base, "reason"]) &&- ["escape", "button"].includes(value.reason)) return {...value};-};-const parseAnchor = value => {- if (!keys(value, ["x", "y", "width", "height"]) ||- Object.values(value).some(n => !Number.isFinite(n) || Math.abs(n) > 100000) ||- value.width <= 0 || value.height <= 0) return;- return {...value};-};-// 缩放取主进程的真实 WebContents 值,锚点以 owner 的 CSS 像素表示。-const place = (anchor, zoom, bounds, preferredHeight = 408) => {- if (!parseAnchor(anchor) || !Number.isFinite(zoom) || zoom < 0.25 || zoom > 5 ||- !integer(preferredHeight, 4096) || preferredHeight < 50 || bounds.width < 240 || bounds.height < 160) return;- const a = {x: anchor.x * zoom, y: anchor.y * zoom, width: anchor.width * zoom, height: anchor.height * zoom};- if (a.x < 0 || a.y < 0 || a.x + a.width > bounds.width || a.y + a.height > bounds.height) return;- const padding = Math.round(24 * zoom);- const width = Math.min(Math.round(368 * zoom), bounds.width);- const height = Math.min(Math.round(preferredHeight * zoom), Math.round(568 * zoom),- Math.floor(bounds.height * 0.65) + 2 * padding, bounds.height);- return {x: Math.max(0, Math.min(Math.round(a.x + a.width - width + padding), bounds.width - width)),- y: Math.max(0, Math.min(Math.round(a.y + a.height - padding), bounds.height - height)), width, height};-};-const resource = (url, method) => {- if (!["GET", "HEAD"].includes(method) || typeof url !== "string") return;- const item = Object.entries(RESOURCES).find(([pathname]) => url === ORIGIN + pathname);- return item?.[1];-};-module.exports = {ORIGIN, CHANNEL, PAGE_SIZE, RESOURCES, CSP, keys, isSession, parseTheme, parseState, parseAction, parseAnchor, place, resource};diff --git a/app/electron/mapUnplaced/preload.js b/app/electron/mapUnplaced/preload.jsdeleted file mode 100644index c6b036bc1a..0000000000--- a/app/electron/mapUnplaced/preload.js+++ /dev/null@@ -1,34 +0,0 @@-const {contextBridge, ipcRenderer} = require("electron");-const CHANNEL = "siyuan-map-unplaced-menu";-const sessionID = process.argv.find(value => value.startsWith("--unplaced-session="))?.slice(19);-let revision = 0, subscribed = false, listener, themeListener;-const send = (type, data = {}) => {- if (/^[a-f0-9]{48}$/.test(sessionID)) ipcRenderer.send(CHANNEL + "-action", {sessionID, revision, type, ...data});-};-ipcRenderer.on(CHANNEL + "-state", (_event, value) => {- if (value?.sessionID !== sessionID || !Number.isSafeInteger(value.state?.revision) || value.state.revision < revision) return;- revision = value.state.revision;- listener?.(value.state);-});-ipcRenderer.on(CHANNEL + "-theme", (_event, value) => {- if (value?.sessionID !== sessionID || !["light", "dark"].includes(value.theme?.mode) ||- !Number.isInteger(value.theme.fontSize) || value.theme.fontSize < 12 || value.theme.fontSize > 32) return;- themeListener?.({mode: value.theme.mode, fontSize: value.theme.fontSize});-});-contextBridge.exposeInMainWorld("unplacedMenu", Object.freeze({- subscribe(callback, onTheme) {- if (subscribed || typeof callback !== "function") return;- subscribed = true;- listener = callback;- if (typeof onTheme === "function") themeListener = onTheme;- send("ready");- },- search(query) { if (typeof query === "string" && query.length <= 256) send("search", {query}); },- editing() { send("editing"); },- more() { send("more"); },- previous() { send("previous"); },- retry() { send("retry"); },- resize(height) { if (Number.isSafeInteger(height) && height >= 50 && height <= 4096) send("resize", {height}); },- select(id) { if (typeof id === "string" && id.length <= 128) send("select", {id}); },- close(reason) { if (["escape", "button"].includes(reason)) send("close", {reason}); },-}));diff --git a/app/electron/settingsWindows.test.js b/app/electron/settingsWindows.test.jsindex 45cb739749..597b54ca7b 100644--- a/app/electron/settingsWindows.test.js+++ b/app/electron/settingsWindows.test.js@@ -138,6 +138,7 @@ test("settings popup authorization requires the registered top-level page and exassert.equal(allowed.overrideBrowserWindowOptions.autoHideMenuBar, true);assert.equal(allowed.overrideBrowserWindowOptions.parent, undefined);assert.equal(allowed.overrideBrowserWindowOptions.webPreferences.webSecurity, true);+ assert.equal(allowed.overrideBrowserWindowOptions.webPreferences.webviewTag, false);assert.equal(allowed.overrideBrowserWindowOptions.webPreferences.backgroundThrottling, false);assert.equal(policy(owner, prepared), undefined);event.senderFrame = {};diff --git a/app/src/assets/scss/component/_record-inbox.scss b/app/src/assets/scss/component/_record-inbox.scssindex 4e47ba04ce..77a1e93d94 100644--- a/app/src/assets/scss/component/_record-inbox.scss+++ b/app/src/assets/scss/component/_record-inbox.scss@@ -25,7 +25,7 @@}}-// 日历无日期列表和可信地图菜单共享同一组内容布局。+// 日历无日期列表内容布局,标题与搜索样式由地图菜单复用。@mixin content($prefix, $list-max-height: min(45vh, 360px)) {@include header-search($prefix);diff --git a/app/src/protyle/render/av/map/desktopGeometry.ts b/app/src/protyle/render/av/map/desktopGeometry.tsdeleted file mode 100644index 456109057f..0000000000--- a/app/src/protyle/render/av/map/desktopGeometry.ts+++ /dev/null@@ -1,63 +0,0 @@-export interface MapRect { x: number; y: number; width: number; height: number; }-export type MapGeometry = {visible: false} | {- visible: true; bounds: MapRect; logicalSize: {width: number; height: number}; crop: {x: number; y: number};-};--export const intersects = (a: MapRect, b: MapRect) => a.x < b.x + b.width && b.x < a.x + a.width &&- a.y < b.y + b.height && b.y < a.y + a.height;--// 菜单打开时不展示难以操作的狭窄残片。-const MIN_MENU_MAP_EDGE = 32;-const MIN_MENU_MAP_AREA = 4096;--// 坐标始终使用主文档 CSS 像素,只由主进程应用文档缩放系数。-export const computeDesktopAVMapGeometry = (rect: MapRect, clips: MapRect[], occluders: MapRect[] = [],- menus: MapRect[] = []): MapGeometry => {- if (![rect, ...clips, ...occluders, ...menus].every((item) => [item.x, item.y, item.width, item.height].every(Number.isFinite) &&- item.width >= 0 && item.height >= 0)) {- return {visible: false};- }- if (rect.width < 1 || rect.height < 1) {- return {visible: false};- }- let left = rect.x, top = rect.y, right = rect.x + rect.width, bottom = rect.y + rect.height;- clips.forEach((clip) => {- left = Math.max(left, clip.x);- top = Math.max(top, clip.y);- right = Math.min(right, clip.x + clip.width);- bottom = Math.min(bottom, clip.y + clip.height);- });- // 裁剪边缘内收一个 CSS 像素,避免半像素命中相邻控件;原生绘制区域与命中检测同步收窄。- if (left > rect.x) left += 1;- if (top > rect.y) top += 1;- if (right < rect.x + rect.width) right -= 1;- if (bottom < rect.y + rect.height) bottom -= 1;- // 裁剪差值的浮点舍入不能使可见尺寸超过原始尺寸。- let bounds = {x: left, y: top, width: Math.min(rect.width, right - left), height: Math.min(rect.height, bottom - top)};- if (left < 0 || top < 0 || bounds.width < 1 || bounds.height < 1) {- return {visible: false};- }- if (occluders.some((item) => item.width > 0 && item.height > 0 && intersects(bounds, item))) {- return {visible: false};- }- const overlapping = menus.filter(item => item.width > 0 && item.height > 0 && intersects(bounds, item));- if (overlapping.length > 1) return {visible: false};- if (overlapping.length) {- const menu = overlapping[0];- const rightEdge = bounds.x + bounds.width, bottomEdge = bounds.y + bounds.height;- // 只处理当前地图唯一的未定位菜单,在四个连续矩形中选择面积最大的安全区域。- const candidates = [- [bounds.x, bounds.y, Math.min(rightEdge, menu.x - 1), bottomEdge],- [Math.max(bounds.x, menu.x + menu.width + 1), bounds.y, rightEdge, bottomEdge],- [bounds.x, bounds.y, rightEdge, Math.min(bottomEdge, menu.y - 1)],- [bounds.x, Math.max(bounds.y, menu.y + menu.height + 1), rightEdge, bottomEdge],- ].map(([x, y, right, bottom]) => ({x: Math.ceil(x), y: Math.ceil(y),- width: Math.floor(right) - Math.ceil(x), height: Math.floor(bottom) - Math.ceil(y)}))- .filter(item => item.width >= MIN_MENU_MAP_EDGE && item.height >= MIN_MENU_MAP_EDGE &&- item.width * item.height >= MIN_MENU_MAP_AREA);- if (!candidates.length) return {visible: false};- bounds = candidates.reduce((largest, item) => item.width * item.height > largest.width * largest.height ? item : largest);- }- return {visible: true, bounds, logicalSize: {width: rect.width, height: rect.height},- crop: {x: bounds.x - rect.x, y: bounds.y - rect.y}};-};diff --git a/app/src/protyle/render/av/map/desktopGeometryDOM.ts b/app/src/protyle/render/av/map/desktopGeometryDOM.tsdeleted file mode 100644index eaf2f3ca8a..0000000000--- a/app/src/protyle/render/av/map/desktopGeometryDOM.ts+++ /dev/null@@ -1,130 +0,0 @@-import {computeDesktopAVMapGeometry, intersects, MapGeometry, MapRect} from "./desktopGeometry";-import {isMapUnplacedMenu} from "./unplacedMenu";--const readMenuRect = (element: HTMLElement, style: CSSStyleDeclaration, scope: Window): MapRect | undefined => {- // 无法用单个矩形可靠界定的主题效果仍走全隐藏路径。- const measurable = (value: CSSStyleDeclaration) => value.transform === "none" && value.filter === "none" &&- ["", "normal", "1"].includes(value.getPropertyValue("zoom")) &&- [value.translate, value.rotate, value.scale].every(item => !item || item === "none");- if (!measurable(style)) return;- for (let parent = element.parentElement; parent; parent = parent.parentElement) {- if (!measurable(scope.getComputedStyle(parent))) return;- }- const rect = element.getBoundingClientRect();- let left = 0, right = 0, top = 0, bottom = 0;- const shadows = style.boxShadow === "none" ? [] : style.boxShadow.split(/,(?![^()]*\))/);- for (const shadow of shadows) {- const parts = shadow.replace(/(?:rgba?|hsla?)\([\d\s.,%/+\-]+\)/, "").trim().split(/\s+/);- const inset = parts[0] === "inset" || parts[parts.length - 1] === "inset";- if (inset) parts.splice(parts[0] === "inset" ? 0 : parts.length - 1, 1);- if (parts.length < 2 || parts.length > 4 || parts.some(value => !/^-?(?:\d+\.?\d*|\.\d+)px$/.test(value))) return;- const [x, y, blur = 0, spread = 0] = parts.map(parseFloat);- if (blur < 0) return;- if (inset) continue;- // 模糊阴影按两倍半径保守外扩,包含多层阴影、负偏移和边框外侧的描边。- const extent = Math.max(0, blur * 2 + spread);- left = Math.max(left, extent - x);- right = Math.max(right, extent + x);- top = Math.max(top, extent - y);- bottom = Math.max(bottom, extent + y);- }- if (style.outlineStyle !== "none") {- if (![style.outlineWidth, style.outlineOffset].every(value => /^-?(?:\d+\.?\d*|\.\d+)px$/.test(value))) return;- const outline = Math.max(0, parseFloat(style.outlineWidth) + parseFloat(style.outlineOffset));- left = Math.max(left, outline);- right = Math.max(right, outline);- top = Math.max(top, outline);- bottom = Math.max(bottom, outline);- }- return {x: rect.x - left, y: rect.y - top, width: rect.width + left + right, height: rect.height + top + bottom};-};--export const readDesktopAVMapGeometry = (container: HTMLElement): MapGeometry => {- const doc = container.ownerDocument;- const scope = doc.defaultView;- if (!scope) {- return {visible: false};- }- if (doc.hidden) {- return {visible: false};- }- if (!container.isConnected) {- return {visible: false};- }- if (!container.getClientRects().length) {- return {visible: false};- }- const rect = container.getBoundingClientRect();- const clips: MapRect[] = [{x: 0, y: 0, width: scope.innerWidth, height: scope.innerHeight}];- for (let element: HTMLElement = container; element; element = element.parentElement) {- const style = scope.getComputedStyle(element);- if (style.display === "none" || style.visibility !== "visible" || Number(style.opacity) === 0 ||- style.getPropertyValue("content-visibility") === "hidden") {- return {visible: false};- }- if (element !== container && /hidden|clip|scroll|auto/.test(style.overflowX + style.overflowY)) {- const bounds = element.getBoundingClientRect();- const clipX = /hidden|clip|scroll|auto/.test(style.overflowX);- const clipY = /hidden|clip|scroll|auto/.test(style.overflowY);- const scaleX = element.offsetWidth ? bounds.width / element.offsetWidth : 1;- const scaleY = element.offsetHeight ? bounds.height / element.offsetHeight : 1;- clips.push({x: clipX ? bounds.x + element.clientLeft * scaleX : 0,- y: clipY ? bounds.y + element.clientTop * scaleY : 0,- width: clipX ? element.clientWidth * scaleX : scope.innerWidth,- height: clipY ? element.clientHeight * scaleY : scope.innerHeight});- }- }- const views = container.closest(".av[data-type='NodeAttributeView']")- ?.querySelector<HTMLElement>(":scope > .av__container > .av__header > .av__views--fixed");- if (views?.getClientRects().length) {- const style = scope.getComputedStyle(views);- const bounds = views.getBoundingClientRect();- if (["fixed", "sticky"].includes(style.position) && style.display !== "none" &&- style.visibility === "visible" && Number(style.opacity) !== 0 && intersects(rect, bounds)) {- // 本数据库的固定页签栏遮住地图顶部时,只展示栏底部以下的区域。- const top = Math.max(0, bounds.y + bounds.height);- clips.push({x: 0, y: top, width: scope.innerWidth, height: Math.max(0, scope.innerHeight - top)});- }- }- const occluders: MapRect[] = [];- const menus: MapRect[] = [];- let unsupportedMenu = false;- // 只检查应用实际浮层根节点,不根据任意 z-index 猜测遮挡。- doc.querySelectorAll<HTMLElement>(".b3-menu, .b3-dialog, .av__panel, .protyle-util, .protyle-toolbar, .block__popover, [popover]")- .forEach((element) => {- if (element.contains(container) || !element.getClientRects().length) {- return;- }- const style = scope.getComputedStyle(element);- if (style.display !== "none" && style.visibility === "visible" && Number(style.opacity) !== 0) {- if (isMapUnplacedMenu(element, container)) {- const bounds = readMenuRect(element, style, scope);- const hasSubmenu = Array.from(element.querySelectorAll<HTMLElement>(".b3-menu__submenu"))- .some(submenu => {- const submenuStyle = scope.getComputedStyle(submenu);- return submenu.getClientRects().length && submenuStyle.display !== "none" &&- submenuStyle.visibility === "visible" && Number(submenuStyle.opacity) !== 0;- });- if (!bounds || hasSubmenu) unsupportedMenu = true;- else menus.push(bounds);- } else {- occluders.push(element.getBoundingClientRect());- }- }- });- if (unsupportedMenu) return {visible: false};- const geometry = computeDesktopAVMapGeometry(rect, clips, occluders, menus);- if (geometry.visible) {- const bounds = geometry.bounds;- // 在主文档中命中检测,包括固定工具栏;原生子视图不属于此 DOM 树。- for (const x of [bounds.x + 0.5, bounds.x + bounds.width / 2, bounds.x + bounds.width - 0.5]) {- for (const y of [bounds.y + 0.5, bounds.y + bounds.height / 2, bounds.y + bounds.height - 0.5]) {- const top = doc.elementFromPoint(x, y);- if (!top || !container.contains(top)) {- return {visible: false};- }- }- }- }- return geometry;-};diff --git a/app/src/protyle/render/av/map/desktopTransport.test.ts b/app/src/protyle/render/av/map/desktopTransport.test.tsindex 01ad4bc3a4..e147365e34 100644--- a/app/src/protyle/render/av/map/desktopTransport.test.ts+++ b/app/src/protyle/render/av/map/desktopTransport.test.ts@@ -4,18 +4,9 @@ import {webcrypto} from "node:crypto";import {describe, it} from "node:test";import * as ts from "typescript";import * as protocol from "./protocol";-import * as unplacedMenu from "./unplacedMenu";-import {computeDesktopAVMapGeometry, MapGeometry} from "./desktopGeometry";-import * as desktopGeometryDOM from "./desktopGeometryDOM";import * as loadingBudget from "./loadingBudget";-import * as desktopUnplaced from "./desktopUnplaced";import {getAVMapVisibility} from "./host";-const visibleGeometry = (geometry: MapGeometry) => {- assert.ok(geometry.visible === true, "the fixture must produce visible geometry");- return geometry;-};-const source = readFileSync(__dirname + "/desktopTransport.ts", "utf8");const load = (ipc: unknown, browser = false, warnings: unknown[][] = []) => {// Exercise the same compile-time branches as webpack without importing Electron into Node.@@ -29,9 +20,7 @@ const load = (ipc: unknown, browser = false, warnings: unknown[][] = []) => {const result: any = {};const requireModule = (name: string) => {if (name === "./protocol") { return protocol; }- if (name === "./desktopGeometryDOM") { return desktopGeometryDOM; }if (name === "./loadingBudget") { return loadingBudget; }- if (name === "./desktopUnplaced") { return desktopUnplaced; }if (name === "./host") { return {getAVMapVisibility}; }assert.equal(name, "electron");assert.equal(browser, false, "browser must not import Electron");@@ -43,7 +32,7 @@ const load = (ipc: unknown, browser = false, warnings: unknown[][] = []) => {return result;};-const fixture = (warnings: unknown[][] = []) => {+const fixture = (warnings: unknown[][] = [], origin = "http://127.0.0.1:6806") => {const calls: Array<[string, any]> = [];const listeners = new Map<string, (...args: any[]) => void>();const domListeners = new Map<string, () => void>();@@ -51,7 +40,7 @@ const fixture = (warnings: unknown[][] = []) => {const timers = new Map<number, {callback: () => void; delay: number}>();let resolveCreate: (value: unknown) => void;let rejectCreate: (value: unknown) => void;- let now = 0, nextFrame = 0, nextTimer = 0;+ let nextFrame = 0, nextTimer = 0;const ipc = {invoke: (name: string, value: unknown) => {calls.push([name, value]);@@ -78,8 +67,8 @@ const fixture = (warnings: unknown[][] = []) => {},addEventListener: (name: string, fn: () => void) => domListeners.set(name, fn),removeEventListener: (name: string) => domListeners.delete(name)};- const scope = {crypto: webcrypto, location: {origin: "http://127.0.0.1:6806"},- innerWidth: 1000, innerHeight: 800, performance: {now: () => now},+ const scope = {crypto: webcrypto, location: {origin},+ innerWidth: 1000, innerHeight: 800,setTimeout: (callback: () => void, delay: number) => {timers.set(++nextTimer, {callback, delay});return nextTimer;@@ -113,11 +102,12 @@ const fixture = (warnings: unknown[][] = []) => {await new Promise<void>((resolve) => setImmediate(resolve));},created: async (overrides: object = {}) => {- resolveCreate({version: 1, instanceID, mode: "native", ...overrides});+ resolveCreate({version: 1, instanceID, mode: "webview",+ src: `${origin}/stage/map/index.html?provider=openfreemap#${instanceID}:${"b".repeat(48)}`,+ partition: `siyuan-map-${"c".repeat(48)}`, ...overrides});await new Promise<void>((resolve) => setImmediate(resolve));},- advance: (milliseconds = 150) => {- now += milliseconds;+ advance: () => {const pending = [...frames.values()];frames.clear();pending.forEach((fn) => fn());@@ -125,7 +115,7 @@ const fixture = (warnings: unknown[][] = []) => {};describe("desktop map transport", () => {- it("accepts only explicit native mode or the fixed owner-origin map document and ephemeral webview partition", () => {+ it("accepts only the fixed owner-origin map document and ephemeral webview partition", () => {const api = load({});const instanceID = "a".repeat(48);const origin = "http://127.0.0.1:6806";@@ -133,7 +123,7 @@ describe("desktop map transport", () => {const partition = `siyuan-map-${"c".repeat(48)}`;const valid = {version: 1, instanceID, mode: "webview", src, partition};assert.deepEqual(api.parseDesktopMapCreation(valid, instanceID, origin), {mode: "webview", src, partition});- assert.deepEqual(api.parseDesktopMapCreation({version: 1, instanceID, mode: "native"}, instanceID, origin), {mode: "native"});+ assert.equal(api.parseDesktopMapCreation({version: 1, instanceID, mode: "native"}, instanceID, origin), undefined);const invalidCreations: unknown[] = [null, [], {version: 1, instanceID}, {...valid, mode: "iframe"},{...valid, src: undefined}, {...valid, partition: undefined}, {...valid, preload: "/private/preload.js"},{...valid, mode: "native"}, {...valid, partition: "persist:" + partition}, {...valid, partition: "siyuan-map-other"},@@ -145,80 +135,79 @@ describe("desktop map transport", () => {}});- it("mounts local maps as ordinary webviews and keeps the same guest through menus, scrolling and resize", async () => {- const oldMutation = globalThis.MutationObserver, oldResize = globalThis.ResizeObserver;- let mutations = 0, resizes = 0, disconnects = 0;- globalThis.MutationObserver = class {- constructor() { mutations++; }- observe() {}- disconnect() {}- } as any;- globalThis.ResizeObserver = class {- constructor() { resizes++; }- observe() {}- disconnect() { disconnects++; }- } as any;- const f = fixture();- const src = `${f.doc.defaultView.location.origin}/stage/map/index.html?provider=openfreemap#${f.instanceID}:${"b".repeat(48)}`;- const partition = `siyuan-map-${"c".repeat(48)}`;- const command = () => f.calls.filter(([name, value]) => name === "siyuan-map-command" && value.type === "visibility").at(-1)?.[1];- try {- f.host.setPoints([{id: "row", longitude: 1, latitude: 2, name: "private"}], 1);- f.host.setTheme("dark");- await f.created({mode: "webview", src, partition});- assert.equal(f.guests.length, 1);- const guest = f.guests[0];- assert.equal(guest.tag, "webview");- assert.deepEqual([...guest.attributes], [["title", ""], ["partition", partition], ["src", src]]);- assert.deepEqual(f.attachments, [guest]);- assert.equal(mutations, 0, "local composition must not install the native stability/occlusion observer");- assert.equal(resizes, 1);- assert.equal(desktopUnplaced.openDesktopMapUnplaced(f.container, f.container,- {} as desktopUnplaced.DesktopMapUnplacedState, () => {}, () => {}, () => true), undefined,- "local maps use the existing DOM unplaced menu");- f.reply({type: "ready"});- assert.equal(f.ready(), 1);- assert.deepEqual(command().viewport, {x: 0, y: 0, width: 400, height: 300});- const pointCommand = f.calls.find(([name, value]) => name === "siyuan-map-command" && value.type === "setPoints")[1];- assert.equal(pointCommand.points[0].name, undefined);- const themeCommand = f.calls.find(([name, value]) => name === "siyuan-map-command" && value.type === "theme")[1];- assert.equal(themeCommand.theme, "dark");- const scrim = {className: "av__panel", contains: () => false, getClientRects: () => [f.rect],- getBoundingClientRect: () => f.rect};- f.doc.querySelectorAll = () => [scrim];- f.doc.elementFromPoint = () => scrim;- f.advance();- assert.equal(command().visible, false, "a full menu scrim suppresses attribution interaction only");- assert.equal(guest.removed, false, "menus cannot detach or hide the guest map");- assert.deepEqual([...guest.attributes], [["title", ""], ["partition", partition], ["src", src]]);- f.doc.querySelectorAll = (): HTMLElement[] => [];- f.doc.elementFromPoint = () => f.container;- f.rect.y = -40;- f.domListeners.get("scroll")();- assert.equal(command().visible, true, "local scrolling has no native settle delay");- assert.deepEqual(command().viewport, {x: 0, y: 40, width: 400, height: 260});- f.host.resize();- assert.ok(f.calls.some(([name, value]) => name === "siyuan-map-command" && value.type === "resize"));- assert.equal(f.calls.some(([name]) => name === "siyuan-map-geometry"), false);- assert.equal(f.guests.length, 1);- f.doc.hidden = true;- f.domListeners.get("visibilitychange")();- assert.equal(command().visible, false);- f.host.destroy();- assert.equal(guest.removed, true);- assert.equal(disconnects, 1);- assert.equal(f.frames.size, 0);- assert.equal(f.listeners.size, 0);- assert.equal(f.domListeners.size, 0);- assert.deepEqual(f.errors, []);- } finally {- f.host.destroy();- globalThis.MutationObserver = oldMutation;- globalThis.ResizeObserver = oldResize;- }- });+ for (const origin of ["http://127.0.0.1:6806", "https://notes.example.test"]) {+ it(`keeps the same webview through menus, scrolling and resize for ${origin}`, async () => {+ const oldMutation = globalThis.MutationObserver, oldResize = globalThis.ResizeObserver;+ let mutations = 0, resizes = 0, disconnects = 0;+ globalThis.MutationObserver = class {+ constructor() { mutations++; }+ observe() {}+ disconnect() {}+ } as any;+ globalThis.ResizeObserver = class {+ constructor() { resizes++; }+ observe() {}+ disconnect() { disconnects++; }+ } as any;+ const f = fixture([], origin);+ const src = `${f.doc.defaultView.location.origin}/stage/map/index.html?provider=openfreemap#${f.instanceID}:${"b".repeat(48)}`;+ const partition = `siyuan-map-${"c".repeat(48)}`;+ const command = () => f.calls.filter(([name, value]) => name === "siyuan-map-command" && value.type === "visibility").at(-1)?.[1];+ try {+ f.host.setPoints([{id: "row", longitude: 1, latitude: 2, name: "private"}], 1);+ f.host.setTheme("dark");+ await f.created({mode: "webview", src, partition});+ assert.equal(f.guests.length, 1);+ const guest = f.guests[0];+ assert.equal(guest.tag, "webview");+ assert.deepEqual([...guest.attributes], [["title", ""], ["partition", partition], ["src", src]]);+ assert.deepEqual(f.attachments, [guest]);+ assert.equal(mutations, 0, "webview composition must not install a stability/occlusion observer");+ assert.equal(resizes, 1);+ f.reply({type: "ready"});+ assert.equal(f.ready(), 1);+ assert.deepEqual(command().viewport, {x: 0, y: 0, width: 400, height: 300});+ const pointCommand = f.calls.find(([name, value]) => name === "siyuan-map-command" && value.type === "setPoints")[1];+ assert.equal(pointCommand.points[0].name, undefined);+ const themeCommand = f.calls.find(([name, value]) => name === "siyuan-map-command" && value.type === "theme")[1];+ assert.equal(themeCommand.theme, "dark");+ const scrim = {className: "av__panel", contains: () => false, getClientRects: () => [f.rect],+ getBoundingClientRect: () => f.rect};+ f.doc.querySelectorAll = () => [scrim];+ f.doc.elementFromPoint = () => scrim;+ f.advance();+ assert.equal(command().visible, false, "a full menu scrim suppresses attribution interaction only");+ assert.equal(guest.removed, false, "menus cannot detach or hide the guest map");+ assert.deepEqual([...guest.attributes], [["title", ""], ["partition", partition], ["src", src]]);+ f.doc.querySelectorAll = (): HTMLElement[] => [];+ f.doc.elementFromPoint = () => f.container;+ f.rect.y = -40;+ f.domListeners.get("scroll")();+ assert.equal(command().visible, true, "scrolling has no native settle delay");+ assert.deepEqual(command().viewport, {x: 0, y: 40, width: 400, height: 260});+ f.host.resize();+ assert.ok(f.calls.some(([name, value]) => name === "siyuan-map-command" && value.type === "resize"));+ assert.equal(f.calls.some(([name]) => name === "siyuan-map-geometry"), false);+ assert.equal(f.guests.length, 1);+ f.doc.hidden = true;+ f.domListeners.get("visibilitychange")();+ assert.equal(command().visible, false);+ f.host.destroy();+ assert.equal(guest.removed, true);+ assert.equal(disconnects, 1);+ assert.equal(f.frames.size, 0);+ assert.equal(f.listeners.size, 0);+ assert.equal(f.domListeners.size, 0);+ assert.deepEqual(f.errors, []);+ } finally {+ f.host.destroy();+ globalThis.MutationObserver = oldMutation;+ globalThis.ResizeObserver = oldResize;+ }+ });+ }- it("dismisses existing menus only for fixed trusted-main signals from the live visible local map", async () => {+ it("dismisses existing menus only for fixed trusted-main signals from the live visible map", async () => {const oldResize = globalThis.ResizeObserver, oldWindow = globalThis.window;globalThis.ResizeObserver = class { observe() {} disconnect() {} } as any;let dismissed = 0;@@ -251,12 +240,15 @@ describe("desktop map transport", () => {});it("fails closed on missing modes and defers early ready callbacks until creation is validated", async () => {- for (const mode of [undefined, "other", "webview"]) {+ const invalidReplies: Array<Record<string, unknown>> = [+ {mode: undefined}, {mode: "other"}, {mode: "native"}, {src: undefined}, {partition: undefined},+ ];+ for (const invalid of invalidReplies) {const f = fixture();f.host.setPoints([{id: "row", longitude: 1, latitude: 2}], 1);f.reply({type: "ready"});assert.equal(f.ready(), 0);- await f.created({mode});+ await f.created(invalid);assert.equal(f.ready(), 0);assert.deepEqual(f.errors, ["hostCreateInvalidResponse"]);assert.equal(f.guests.length, 0);@@ -269,42 +261,6 @@ describe("desktop map transport", () => {assert.equal(disposed.guests.length, 0, "a late response cannot recreate a disposed guest");});- it("registers a menu only for its ready map and closes a late menu creation after map disposal", async () => {- class Observer { observe() {} disconnect() {} }- const oldMutation = globalThis.MutationObserver, oldResize = globalThis.ResizeObserver, oldWindow = globalThis.window;- globalThis.MutationObserver = Observer as any;- globalThis.ResizeObserver = Observer as any;- globalThis.window = {siyuan: {config: {editor: {fontSize: 16}}}} as any;- const f = fixture();- let closed = 0;- const anchor = {...f.container, getBoundingClientRect: () => ({left: 100, right: 130, top: 20, bottom: 44})};- const state: desktopUnplaced.DesktopMapUnplacedState = {requestID: 0, query: "", rows: [], total: 0, page: 1,- loading: true, error: false, labels: {title: "Unplaced", search: "Search", empty: "Empty", loading: "Loading",- more: "Next", previous: "Previous", retry: "Retry", close: "Close"}};- const open = () => desktopUnplaced.openDesktopMapUnplaced(f.container, anchor, state, () => {}, () => closed++, () => true);- try {- assert.equal(open(), undefined);- await f.created();- assert.equal(open(), undefined, "an initializing map cannot own a native menu");- f.reply({type: "ready"});- assert.ok(open());- assert.equal(f.calls.filter(([name]) => name === "siyuan-map-unplaced-open").length, 1);- f.host.destroy();- assert.equal(closed, 1);- await f.created({sessionID: "b".repeat(48)});- assert.ok(f.calls.some(([name, value]) => name === "siyuan-map-unplaced-close" && value.sessionID === "b".repeat(48)),- "a session created after disposal is immediately closed");- assert.equal(open(), undefined);- assert.equal(f.listeners.size, 0);- assert.equal(f.frames.size, 0);- assert.equal(f.timers.size, 0);- } finally {- f.host.destroy();- globalThis.MutationObserver = oldMutation;- globalThis.ResizeObserver = oldResize;- globalThis.window = oldWindow;- }- });it("forwards only ready current fixed attribution replies already verified by main", async () => {class Observer { observe() {} disconnect() {} }const oldMutation = globalThis.MutationObserver, oldResize = globalThis.ResizeObserver;@@ -328,6 +284,122 @@ describe("desktop map transport", () => {globalThis.ResizeObserver = oldResize;}});++ it("releases buffered commands only after validated creation and ready, and rejects stale marker replies", async () => {+ const oldResize = globalThis.ResizeObserver;+ globalThis.ResizeObserver = class { observe() {} disconnect() {} } as any;+ const f = fixture([], "https://notes.example.test");+ try {+ f.host.setPoints([{id: "row", latitude: 2, longitude: 1, name: "private"}], 1);+ f.host.setTheme("dark");+ f.host.resize();+ f.reply({type: "ready", instanceID: "old"});+ f.reply({type: "ready"});+ assert.equal(f.ready(), 0);+ assert.equal(f.calls.some(([name]) => name === "siyuan-map-command"), false);+ await f.created();+ assert.equal(f.ready(), 1);+ f.reply({type: "ready"});+ assert.equal(f.ready(), 1);+ const commands = f.calls.filter(([name]) => name === "siyuan-map-command").map(([, value]) => value);+ assert.deepEqual(commands.map(command => command.type), ["setPoints", "theme", "visibility"]);+ assert.equal(commands[0].points[0].name, undefined);+ assert.equal(commands[1].theme, "dark");+ assert.equal(commands[2].visible, true);+ assert.match(f.instanceID, /^[a-f0-9]{48}$/);+ assert.equal(f.calls[0][1].credentials, undefined);+ for (const mismatch of [{instanceID: "old"}, {revision: 0}, {id: "missing"}]) {+ f.reply({type: "markerClick", id: "row", revision: 1, ...mismatch});+ }+ assert.deepEqual(f.clicks, []);+ f.reply({type: "markerClick", id: "row", revision: 1});+ assert.deepEqual(f.clicks, [["row", 1]]);+ f.host.setPoints([], 2);+ f.host.setPoints([{id: "row", latitude: 2, longitude: 1}], 1);+ f.reply({type: "markerClick", id: "row", revision: 2});+ assert.equal(f.clicks.length, 1);+ f.host.destroy();+ const sent = f.calls.length;+ f.host.resize();+ f.host.setPoints([], 3);+ f.host.setTheme("light");+ f.reply({type: "markerClick", id: "row", revision: 1});+ f.advance();+ assert.equal(f.calls.length, sent);+ assert.equal(f.frames.size, 0);+ assert.equal(f.timers.size, 0);+ assert.equal(f.listeners.size, 0);+ assert.equal(f.domListeners.size, 0);+ assert.equal(f.guests[0].removed, true);+ } finally {+ f.host.destroy();+ globalThis.ResizeObserver = oldResize;+ }+ });++ it("updates attribution visibility through clipping, overlap, focus and hidden owners without changing the guest", async () => {+ const oldResize = globalThis.ResizeObserver;+ globalThis.ResizeObserver = class { observe() {} disconnect() {} } as any;+ const warnings: unknown[][] = [];+ const f = fixture(warnings, "https://notes.example.test");+ const visibility = () => f.calls.filter(([name, value]) => name === "siyuan-map-command" &&+ value.type === "visibility").at(-1)?.[1];+ try {+ await f.created();+ f.reply({type: "ready"});+ const guest = f.guests[0];+ const attributes = [...guest.attributes];+ const scroll = f.domListeners.get("scroll");+ const focus = f.domListeners.get("focus");+ assert.equal(f.domListeners.has("blur"), false);+ focus();+ assert.equal(visibility().visible, true);+ const menu = {contains: () => false, getClientRects: () => [f.rect],+ getBoundingClientRect: () => ({...f.rect, width: 5, height: 5})};+ f.doc.querySelectorAll = () => [menu];+ focus();+ assert.equal(visibility().visible, true, "a small menu leaves ordinary map composition active");+ assert.equal(visibility().viewport, undefined, "overlap suppresses attribution interaction");+ f.doc.querySelectorAll = (): unknown[] => [];+ f.doc.elementFromPoint = (_x: number, y: number) => y < 100 ? menu : f.container;+ scroll();+ assert.equal(visibility().visible, true);+ assert.equal(visibility().viewport, undefined, "partial unknown occlusion cannot authorize attribution");+ f.doc.elementFromPoint = () => menu;+ f.advance();+ assert.equal(visibility().visible, false);+ f.doc.elementFromPoint = () => f.container;+ for (let i = 0; i < 8; i++) {+ f.rect.y = -10 - i * 7;+ scroll();+ assert.equal(visibility().visible, true);+ assert.equal(visibility().viewport.y, -f.rect.y);+ }+ f.doc.hidden = true;+ f.domListeners.get("visibilitychange")();+ assert.equal(visibility().visible, false);+ f.doc.hidden = false;+ f.container.isConnected = false;+ focus();+ assert.equal(visibility().visible, false);+ f.container.isConnected = true;+ f.advance();+ assert.equal(visibility().visible, true);+ assert.deepEqual([...guest.attributes], attributes);+ assert.equal(guest.removed, false);+ assert.equal(f.guests.length, 1);+ assert.deepEqual(warnings, []);+ f.host.destroy();+ const sent = f.calls.length;+ scroll();+ focus();+ f.advance();+ assert.equal(f.calls.length, sent);+ } finally {+ f.host.destroy();+ globalThis.ResizeObserver = oldResize;+ }+ });it("preserves fixed creation failures and never logs rejected IPC details", async () => {for (const code of ["hostLimitReached", "hostSetupFailed", "hostAttachFailed"] as const) {const warnings: unknown[][] = [];@@ -436,668 +508,12 @@ describe("desktop map transport", () => {assert.equal(await load(undefined, true, browserWarnings).isDesktopAVMapHostSupported(), false);assert.deepEqual(browserWarnings, []);});- it("clips CSS rectangles, preserves full logical size and never multiplies by display scale", () => {- const compute = computeDesktopAVMapGeometry;- assert.deepEqual(compute({x: -20.5, y: 30, width: 200, height: 100},- [{x: 0, y: 0, width: 1000, height: 800}, {x: 10, y: 40, width: 100, height: 60}]),- {visible: true, bounds: {x: 11, y: 41, width: 98, height: 58},- logicalSize: {width: 200, height: 100}, crop: {x: 31.5, y: 11}});- const rect = {x: 0, y: 0, width: 100, height: 100};- assert.deepEqual(compute(rect, [{...rect, x: 200}]), {visible: false});- assert.deepEqual(compute(rect, [], [{x: 30, y: 40, width: 5, height: 5}]), {visible: false});- assert.equal(compute(rect, [], [{...rect, x: 100}]).visible, true);- assert.deepEqual(compute({...rect, width: NaN}, []), {visible: false});- });- it("keeps the native map inside the measured editor edge during upward and downward scrolling", async () => {- const oldMutation = globalThis.MutationObserver, oldResize = globalThis.ResizeObserver;- class Observer {- observe() {}- disconnect() {}- }- globalThis.MutationObserver = Observer as any;- globalThis.ResizeObserver = Observer as any;- const f = fixture();- const scope = f.doc.defaultView;- scope.innerWidth = 1920;- scope.innerHeight = 655;- Object.assign(f.rect, {x: 478, y: 375.5, width: 1290, height: 327.5});- const editor = {parentElement: null as HTMLElement | null, offsetWidth: 1500, offsetHeight: 539,- clientLeft: 0, clientTop: 0, clientWidth: 1490, clientHeight: 539,- getBoundingClientRect: () => ({x: 378, y: 84, width: 1500, height: 539})};- f.container.parentElement = editor;- const getStyle = scope.getComputedStyle;- scope.getComputedStyle = (element: unknown) => ({...getStyle(),- overflowX: element === editor ? "auto" : "visible", overflowY: element === editor ? "auto" : "visible"});- // 实测底栏从 y=623 开始,但半像素位置 622.5 已命中底栏。- f.doc.elementFromPoint = (_x: number, y: number) => y >= 622.5 ? editor : f.container;- try {- await f.created();- f.reply({type: "ready"});- f.advance();- const last = () => f.calls.filter(([name]) => name === "siyuan-map-geometry").at(-1)[1];- assert.deepEqual(last().bounds, {x: 478, y: 375.5, width: 1290, height: 246.5});- assert.deepEqual(last().logicalSize, {width: 1290, height: 327.5});- for (const y of [400, 460, 375.5, 290, 375.5]) {- f.rect.y = y;- f.domListeners.get("scroll")();- assert.equal(last().visible, true);- assert.ok(last().bounds.y + last().bounds.height <= 622);- }- f.doc.elementFromPoint = () => editor;- f.domListeners.get("scroll")();- assert.equal(last().visible, false, "real occlusion must still hide the map");- } finally {- f.host.destroy();- globalThis.MutationObserver = oldMutation;- globalThis.ResizeObserver = oldResize;- }- const compute = computeDesktopAVMapGeometry;- const rect = {x: 0, y: 0, width: 100, height: 100};- assert.equal(compute(rect, [{...rect, height: 1.5}]).visible, false);- assert.equal(visibleGeometry(compute(rect, [{...rect, height: 2}])).bounds.height, 1);- assert.equal(compute(rect, [{...rect, y: 20, height: 2.5}]).visible, false);- assert.equal(visibleGeometry(compute(rect, [{...rect, y: 20, height: 3}])).bounds.height, 1);- assert.deepEqual(visibleGeometry(compute(rect, [rect])).bounds, rect, "uncropped maps retain their complete bounds");- assert.deepEqual(visibleGeometry(compute(rect, [{x: -10, y: -10, width: 120, height: 120}])).bounds, rect);- const clip = {...rect, height: 50};- assert.equal(visibleGeometry(compute(rect, [clip, clip, clip])).bounds.height, 49, "nested clips inset only once");- const {parseMapGeometry} = require("../../../../../electron/mapHostPolicy");- assert.equal(parseMapGeometry(compute(rect, [{...rect, height: 2}]), 0.8, {width: 1000, height: 800}).visible, false);- });it("fails closed for missing capability and omits Electron from browser compilation", async () => {assert.equal(await load(undefined, true).isDesktopAVMapHostSupported(), false);assert.equal(await load({invoke: async () => ({version: 1, supported: true})}).isDesktopAVMapHostSupported(), true);assert.equal(await load({invoke: async () => ({version: 2, supported: true})}).isDesktopAVMapHostSupported(), false);assert.equal(await load({invoke: async () => { throw new Error("old main"); }}).isDesktopAVMapHostSupported(), false);});- it("selects the largest safe rectangle around one owned menu and retains the full logical map", () => {- const compute = computeDesktopAVMapGeometry;- const {parseMapGeometry} = require("../../../../../electron/mapHostPolicy");- const rect = {x: 10, y: 20, width: 400, height: 300};- const cases = [- {menu: {...rect, width: 100}, bounds: {x: 111, y: 20, width: 299, height: 300}},- {menu: {...rect, x: 310, width: 100}, bounds: {x: 10, y: 20, width: 299, height: 300}},- {menu: {...rect, height: 100}, bounds: {x: 10, y: 121, width: 400, height: 199}},- {menu: {...rect, y: 220, height: 100}, bounds: {x: 10, y: 20, width: 400, height: 199}},- {menu: {x: 160, y: 120, width: 100, height: 100}, bounds: {x: 10, y: 20, width: 149, height: 300}},- ];- for (const {menu, bounds} of cases) {- const geometry = visibleGeometry(compute(rect, [], [], [menu]));- assert.deepEqual(geometry.bounds, bounds);- assert.deepEqual(geometry.logicalSize, {width: rect.width, height: rect.height});- assert.deepEqual(geometry.crop, {x: bounds.x - rect.x, y: bounds.y - rect.y});- for (const zoom of [0.8, 0.9, 1, 1.25, 1.5, 2]) {- const native = parseMapGeometry(geometry, zoom, {width: 4000, height: 3000});- assert.equal(native?.visible, true);- assert.ok(native.bounds.x >= rect.x * zoom && native.bounds.y >= rect.y * zoom);- assert.ok(native.bounds.x + native.bounds.width <= (rect.x + rect.width) * zoom);- assert.ok(native.bounds.y + native.bounds.height <= (rect.y + rect.height) * zoom);- assert.ok(native.bounds.x + native.bounds.width <= menu.x * zoom ||- native.bounds.x >= (menu.x + menu.width) * zoom ||- native.bounds.y + native.bounds.height <= menu.y * zoom ||- native.bounds.y >= (menu.y + menu.height) * zoom);- }- }- const menu = {...rect, width: 100};- assert.deepEqual(compute(rect, [], [menu]), {visible: false}, "ordinary menus never opt into cropping");- assert.deepEqual(compute(rect, [], [{...rect, width: 2}], [menu]), {visible: false},- "a second overlay hides the map even when it would lie outside the chosen crop");- assert.deepEqual(compute(rect, [], [], [menu, {...menu, x: 300}]), {visible: false});- assert.deepEqual(compute(rect, [], [], [rect]), {visible: false});- assert.deepEqual(compute(rect, [], [], [{...rect, width: 380}]), {visible: false});- assert.deepEqual(compute({...rect, height: 100}, [], [], [{...rect, width: 360}]), {visible: false});- assert.deepEqual(compute(rect, [], [], [{...menu, x: NaN}]), {visible: false});- const fractional = {x: 10.25, y: 20.75, width: 400.5, height: 300.5};- const geometry = visibleGeometry(compute(fractional, [{x: 30.5, y: 50.25, width: 340, height: 220}], [],- [{x: 290.5, y: 30, width: 100, height: 290}]));- assert.deepEqual(geometry.bounds, {x: 32, y: 52, width: 257, height: 217});- assert.deepEqual(geometry.crop, {x: 21.75, y: 31.25});- assert.deepEqual(geometry.logicalSize, {width: 400.5, height: 300.5});- });- it("clips only its own live unplaced menu including shadows and restores without refitting or recreating", async () => {- const oldMutation = globalThis.MutationObserver, oldResize = globalThis.ResizeObserver;- const callbacks: Array<() => void> = [];- class Observer {- constructor(callback: () => void) { callbacks.push(callback); }- observe() {}- disconnect() {}- }- globalThis.MutationObserver = Observer as any;- globalThis.ResizeObserver = Observer as any;- const f = fixture();- const rect = {x: 310, y: 30, width: 100, height: 260};- const submenu = {getClientRects: () => [rect]};- let submenus: unknown[] = [];- const menu: any = {contains: () => false, getClientRects: () => [rect], getBoundingClientRect: () => rect,- querySelectorAll: () => submenus};- const getStyle = f.doc.defaultView.getComputedStyle;- let shadow = "rgba(0, 0, 0, 0.2) 0px 8px 24px 0px";- let extraStyle = {};- f.doc.defaultView.getComputedStyle = (element: unknown) => ({...getStyle(),- ...(element === menu ? {boxShadow: shadow, ...extraStyle} : {})});- const lastGeometry = () => f.calls.filter(([name]) => name === "siyuan-map-geometry").at(-1)[1];- let release = unplacedMenu.registerMapUnplacedMenu(menu, f.container);- try {- await f.created();- f.reply({type: "ready"});- f.advance();- const commands = f.calls.filter(([name]) => name === "siyuan-map-command").length;- f.doc.querySelectorAll = () => [menu];- callbacks[0]();- f.advance();- assert.deepEqual(lastGeometry().bounds, {x: 10, y: 20, width: 251, height: 300});- assert.deepEqual(lastGeometry().logicalSize, {width: 400, height: 300});- const scroll = f.domListeners.get("scroll");- rect.height = 40;- scroll();- assert.deepEqual(lastGeometry().bounds, {x: 10, y: 127, width: 400, height: 193},- "a shorter result list can leave a larger rectangle below the menu");- rect.height = 260;- rect.x = 270;- scroll();- assert.equal(lastGeometry().bounds.width, 211, "moving or growing the menu refreshes its crop");- shadow = "rgba(0, 0, 0, 0.8) -8px -4px 3px 2px, rgb(255, 255, 255) 0px 0px 0px 2px";- scroll();- assert.equal(lastGeometry().bounds.width, 243, "every shadow and negative offset must be covered");- shadow = "rgb(0 0 0 / 0.5) 0px 0px 100px 0px inset";- scroll();- assert.equal(lastGeometry().bounds.width, 259, "inset shadows do not extend the menu");- extraStyle = {outlineStyle: "solid", outlineWidth: "4px", outlineOffset: "2px"};- scroll();- assert.equal(lastGeometry().bounds.width, 253, "outline pixels also remain outside the map");- extraStyle = {};- for (const unsupported of ["color(display-p3 1 0 0) 0px 0px 10px 0px", "rgb(0, 0, 0) 0px 0px invalid",- "rgb(0, 0, 0) 0px 0px -1px 0px"]) {- shadow = unsupported;- scroll();- assert.equal(lastGeometry().visible, false, "unsupported effects fail closed");- }- shadow = "none";- for (const style of [{transform: "matrix(1, 0, 0, 1, 1, 1)"}, {filter: "blur(2px)"},- {scale: "1.1"}, {getPropertyValue: () => "1.5"},- {outlineStyle: "solid", outlineWidth: "invalid", outlineOffset: "0px"}]) {- extraStyle = style;- scroll();- assert.equal(lastGeometry().visible, false);- }- extraStyle = {};- const parent = {};- menu.parentElement = parent;- f.doc.defaultView.getComputedStyle = (element: unknown) => ({...getStyle(),- ...(element === parent ? {getPropertyValue: () => "1.5"} : {})});- scroll();- assert.equal(lastGeometry().visible, false, "ancestor CSS zoom cannot leave underestimated shadow bounds");- menu.parentElement = null;- f.doc.defaultView.getComputedStyle = getStyle;- submenus = [submenu];- scroll();- assert.equal(lastGeometry().visible, false, "a visible submenu is not covered by the root rectangle");- submenus = [];- const otherMenu = {contains: () => false, getClientRects: () => [rect], getBoundingClientRect: () => rect};- f.doc.querySelectorAll = () => [menu, otherMenu];- scroll();- assert.equal(lastGeometry().visible, false, "a second overlapping menu retains full hiding");- f.doc.querySelectorAll = () => [menu];- f.doc.elementFromPoint = () => ({});- scroll();- assert.equal(lastGeometry().visible, false, "unknown overlays still fail the final hit test");- f.doc.elementFromPoint = () => f.container;- release();- scroll();- assert.equal(lastGeometry().visible, false, "a reused common menu loses the crop exception on close");- release = unplacedMenu.registerMapUnplacedMenu(menu, {} as HTMLElement);- scroll();- assert.equal(lastGeometry().visible, false, "another split view cannot claim this map's menu");- release();- release = unplacedMenu.registerMapUnplacedMenu(menu, f.container);- scroll();- assert.equal(lastGeometry().visible, true);- f.doc.querySelectorAll = (): HTMLElement[] => [];- callbacks[0]();- f.advance();- assert.deepEqual(lastGeometry().bounds, {x: f.rect.x, y: f.rect.y, width: f.rect.width, height: f.rect.height});- assert.deepEqual(lastGeometry().crop, {x: 0, y: 0});- assert.equal(f.calls.filter(([name]) => name === "siyuan-map-create").length, 1);- assert.equal(f.calls.filter(([name]) => name === "siyuan-map-command").length, commands,- "menu geometry changes must not send fit or recreate map state");- } finally {- release();- f.host.destroy();- globalThis.MutationObserver = oldMutation;- globalThis.ResizeObserver = oldResize;- }- });- it("keeps replacement menu ownership when an older registration is released", () => {- const menu = {} as HTMLElement, first = {} as HTMLElement, second = {} as HTMLElement;- const releaseFirst = unplacedMenu.registerMapUnplacedMenu(menu, first);- const releaseSecond = unplacedMenu.registerMapUnplacedMenu(menu, second);- releaseFirst();- assert.equal(unplacedMenu.isMapUnplacedMenu(menu, first), false);- assert.equal(unplacedMenu.isMapUnplacedMenu(menu, second), true);- releaseSecond();- assert.equal(unplacedMenu.isMapUnplacedMenu(menu, second), false);- });- it("preserves fractional geometry through native validation at every clipped edge and zoom", () => {- const compute = computeDesktopAVMapGeometry;- const {parseMapGeometry} = require("../../../../../electron/mapHostPolicy");- const rect = {x: 155.55555555555554, y: 555.5555555555555, width: 1433.3333333333333, height: 480};- assert.ok(rect.y + rect.height - rect.y > rect.height, "the fixture must reproduce floating-point expansion");- const cases = [- {clips: [], width: rect.width, height: rect.height, cropX: 0, cropY: 0},- {clips: [{x: rect.x + 40, y: 0, width: 2000, height: 1400}],- width: rect.width - 41, height: rect.height, cropX: 41, cropY: 0},- {clips: [{x: 0, y: 0, width: rect.x + rect.width - 40, height: 1400}],- width: rect.width - 41, height: rect.height, cropX: 0, cropY: 0},- {clips: [{x: 0, y: rect.y + 40, width: 2000, height: 1400}],- width: rect.width, height: rect.height - 41, cropX: 0, cropY: 41},- {clips: [{x: 0, y: 0, width: 2000, height: rect.y + rect.height - 40}],- width: rect.width, height: rect.height - 41, cropX: 0, cropY: 0},- {clips: [{x: rect.x + 10, y: rect.y + 30, width: rect.width - 30, height: rect.height - 70}],- width: rect.width - 32, height: rect.height - 72, cropX: 11, cropY: 31},- ];- for (const entry of cases) {- const geometry = visibleGeometry(compute(rect, entry.clips));- assert.ok(geometry.bounds.width <= rect.width);- assert.ok(geometry.bounds.height <= rect.height);- assert.ok(Math.abs(geometry.bounds.width - entry.width) < 1e-9);- assert.ok(Math.abs(geometry.bounds.height - entry.height) < 1e-9);- assert.ok(Math.abs(geometry.crop.x - entry.cropX) < 1e-9);- assert.ok(Math.abs(geometry.crop.y - entry.cropY) < 1e-9);- for (const zoom of [0.8, 0.9, 1, 1.1, 1.25, 1.5, 2]) {- const native = parseMapGeometry(geometry, zoom, {width: 4000, height: 3000});- assert.equal(native?.visible, true, `native validation must retain the map at zoom ${zoom}`);- assert.ok(native.bounds.x >= geometry.bounds.x * zoom);- assert.ok(native.bounds.y >= geometry.bounds.y * zoom);- assert.ok(native.bounds.x + native.bounds.width <= (geometry.bounds.x + geometry.bounds.width) * zoom);- assert.ok(native.bounds.y + native.bounds.height <= (geometry.bounds.y + geometry.bounds.height) * zoom);- }- }- const widthRect = {...rect, x: rect.y, width: rect.height};- assert.ok(widthRect.x + widthRect.width - widthRect.x > widthRect.width);- const geometry = visibleGeometry(compute(widthRect, []));- assert.equal(geometry.bounds.width, widthRect.width);- assert.equal(parseMapGeometry(geometry, 1.25, {width: 4000, height: 3000})?.visible, true);- });- it("keeps all visibility and hit-test checks without logging normal geometry transitions", async () => {- const oldMutation = globalThis.MutationObserver, oldResize = globalThis.ResizeObserver;- class Observer { observe() {} disconnect() {} }- globalThis.MutationObserver = Observer as any;- globalThis.ResizeObserver = Observer as any;- const warnings: unknown[][] = [];- const f = fixture(warnings);- const getStyle = f.doc.defaultView.getComputedStyle;- const lastGeometry = () => f.calls.filter(([name]) => name === "siyuan-map-geometry").at(-1)[1];- f.container.id = "private-block-id";- f.container.textContent = "private-document-content";- try {- await f.created();- assert.equal(lastGeometry().visible, false);- f.advance();- assert.equal(lastGeometry().visible, true);- const scroll = f.domListeners.get("scroll");- const expectHidden = (reason: string) => {- scroll();- assert.equal(lastGeometry().visible, false, reason);- for (let i = 0; i < 10; i++) f.advance(30);- assert.equal(warnings.length, 0, "normal geometry changes must not log warnings");- };- f.doc.hidden = true;- expectHidden("documentHidden");- f.doc.hidden = false;- f.container.isConnected = false;- expectHidden("disconnected");- f.container.isConnected = true;- f.container.getClientRects = (): DOMRect[] => [];- expectHidden("noClientRects");- f.container.getClientRects = () => [f.rect];- f.doc.defaultView.getComputedStyle = () => ({...getStyle(), visibility: "hidden"});- expectHidden("hiddenStyle");- f.doc.defaultView.getComputedStyle = getStyle;- f.rect.width = 0;- expectHidden("zeroRect");- f.rect.width = 400;- f.rect.x = NaN;- expectHidden("invalidGeometry");- f.rect.x = 10;- f.rect.y = 900;- expectHidden("outsideViewport");- f.rect.y = 20;- const parent = {parentElement: null as HTMLElement | null, getBoundingClientRect: () => ({x: 0, y: 0, width: 1000, height: 800}),- offsetWidth: 1000, offsetHeight: 800, clientWidth: 1000, clientHeight: 0, clientLeft: 0, clientTop: 0};- f.container.parentElement = parent;- f.doc.defaultView.getComputedStyle = (element: unknown) => ({...getStyle(),- overflowY: element === parent ? "hidden" : "visible"});- expectHidden("clipped");- f.container.parentElement = null;- f.doc.defaultView.getComputedStyle = getStyle;- f.doc.querySelectorAll = () => [{contains: () => false, getClientRects: () => [f.rect],- getBoundingClientRect: () => f.rect, textContent: "private-overlay-content"}];- expectHidden("overlay");- f.doc.querySelectorAll = (): HTMLElement[] => [];- for (const [y, reason] of [[f.rect.y + 0.5, "hitTestTop"],- [f.rect.y + f.rect.height / 2, "hitTestMiddle"], [f.rect.y + f.rect.height - 0.5, "hitTestBottom"]] as const) {- f.doc.elementFromPoint = (_x: number, pointY: number) => pointY === y ?- {textContent: "private-hit-content", id: "private-overlay-id"} : f.container;- expectHidden(reason);- }- f.doc.elementFromPoint = () => f.container;- scroll();- assert.equal(lastGeometry().visible, true);- for (let i = 0; i < 100; i++) {- f.doc.hidden = i % 2 === 0;- scroll();- assert.equal(lastGeometry().visible, !f.doc.hidden, "repeated changes must not interrupt geometry updates");- }- assert.equal(warnings.length, 0);- f.host.destroy();- scroll();- f.advance();- assert.equal(warnings.length, 0);- } finally {- f.host.destroy();- globalThis.MutationObserver = oldMutation;- globalThis.ResizeObserver = oldResize;- }- });- it("caches ready commands, validates replies and recovers from scroll, occlusion and visibility changes", async () => {- const oldMutation = globalThis.MutationObserver, oldResize = globalThis.ResizeObserver;- let disconnects = 0;- class Observer { observe() {} disconnect() { disconnects++; } }- globalThis.MutationObserver = Observer as any;- globalThis.ResizeObserver = Observer as any;- const f = fixture();- try {- const point = {id: "row", longitude: 1, latitude: 2, name: "private"};- f.host.setPoints([point], 1);- f.host.setTheme("dark");- assert.equal(f.calls[0][1].credentials, undefined);- assert.match(f.calls[0][1].instanceID, /^[a-f0-9]{48}$/);- await f.created();- f.reply({type: "ready", instanceID: "old"});- assert.equal(f.ready(), 0);- f.reply({type: "ready"});- f.reply({type: "ready"});- assert.equal(f.ready(), 1);- const commands = f.calls.filter(([name]) => name === "siyuan-map-command").map(([, value]) => value);- assert.deepEqual(commands.map((value) => value.type), ["setPoints", "theme"]);- assert.equal(commands[0].points[0].name, undefined);- assert.equal(commands[1].theme, "dark");- f.reply({type: "markerClick", id: "row", revision: 0});- f.reply({type: "markerClick", id: "missing", revision: 1});- f.reply({type: "markerClick", id: "row", revision: 1});- assert.deepEqual(f.clicks, [["row", 1]]);- f.host.setPoints([], 2);- f.reply({type: "markerClick", id: "row", revision: 2});- assert.equal(f.clicks.length, 1);- const lastGeometry = () => {- const entries = f.calls.filter(([name]) => name === "siyuan-map-geometry");- return entries[entries.length - 1][1];- };- f.advance();- assert.equal(lastGeometry().visible, true);- assert.equal(f.domListeners.has("blur"), false, "focusing the native map must not hide it");- f.domListeners.get("focus")();- assert.equal(lastGeometry().visible, true);- f.advance();- assert.equal(lastGeometry().visible, true);- f.domListeners.get("scroll")();- assert.equal(lastGeometry().visible, true);- f.advance();- assert.equal(lastGeometry().visible, true);- f.doc.elementFromPoint = () => ({});- f.advance();- assert.equal(lastGeometry().visible, false);- f.doc.elementFromPoint = () => f.container;- f.advance(); f.advance();- assert.equal(lastGeometry().visible, true);- f.doc.hidden = true;- f.domListeners.get("visibilitychange")();- assert.equal(lastGeometry().visible, false);- f.doc.hidden = false;- f.advance(); f.advance();- assert.equal(lastGeometry().visible, true);- f.container.isConnected = false;- f.advance();- assert.equal(lastGeometry().visible, false);- f.host.destroy();- assert.equal(f.listeners.size, 0);- assert.equal(f.frames.size, 0);- assert.equal(f.domListeners.size, 0);- assert.equal(disconnects, 2);- assert.deepEqual(f.errors, []);- } finally {- f.host.destroy();- globalThis.MutationObserver = oldMutation;- globalThis.ResizeObserver = oldResize;- }- });- it("keeps the map visible when focus returns from attribution while rechecking real occlusion", async () => {- const oldMutation = globalThis.MutationObserver, oldResize = globalThis.ResizeObserver;- class Observer { observe() {} disconnect() {} }- globalThis.MutationObserver = Observer as any;- globalThis.ResizeObserver = Observer as any;- const f = fixture();- const geometryCalls = () => f.calls.filter(([name]) => name === "siyuan-map-geometry");- const lastGeometry = () => geometryCalls().at(-1)[1];- try {- await f.created();- f.reply({type: "ready"});- f.advance();- const count = geometryCalls().length;- assert.equal(f.domListeners.has("blur"), false, "the map receives focus without hiding its native view");- for (let i = 0; i < 3; i++) {- f.domListeners.get("focus")();- assert.equal(lastGeometry().visible, true, "clicking outside attribution must not blank the map");- f.advance(30);- }- assert.equal(geometryCalls().length, count, "unchanged focus returns must not send hidden geometry");- const menu = {contains: () => false, getClientRects: () => [f.rect],- getBoundingClientRect: () => ({...f.rect, width: 5, height: 5})};- f.doc.querySelectorAll = () => [menu];- f.domListeners.get("focus")();- assert.equal(lastGeometry().visible, false, "an overlapping app menu must hide the map immediately on focus");- f.doc.querySelectorAll = (): HTMLElement[] => [];- f.domListeners.get("focus")();- f.advance(119);- assert.equal(lastGeometry().visible, false);- f.advance(1);- assert.equal(lastGeometry().visible, true);- f.rect.x += 10;- f.domListeners.get("focus")();- assert.equal(lastGeometry().visible, false, "changed geometry still waits for layout to settle");- f.advance();- assert.equal(lastGeometry().bounds.x, f.rect.x);- f.doc.hidden = true;- f.domListeners.get("focus")();- assert.equal(lastGeometry().visible, false, "a genuinely hidden document remains hidden");- f.doc.hidden = false;- f.doc.elementFromPoint = () => ({});- f.domListeners.get("focus")();- assert.equal(lastGeometry().visible, false, "unknown owner overlays retain the hit-test safeguard");- f.doc.elementFromPoint = () => f.container;- f.domListeners.get("focus")();- f.advance();- assert.equal(lastGeometry().visible, true);- assert.deepEqual(f.errors, []);- } finally {- f.host.destroy();- globalThis.MutationObserver = oldMutation;- globalThis.ResizeObserver = oldResize;- }- });- it("clips beneath its own fixed database tabs while retaining menu and unknown occlusion checks", async () => {- const oldMutation = globalThis.MutationObserver, oldResize = globalThis.ResizeObserver;- const callbacks: Array<() => void> = [];- class Observer {- constructor(callback: () => void) { callbacks.push(callback); }- observe() {}- disconnect() {}- }- globalThis.MutationObserver = Observer as any;- globalThis.ResizeObserver = Observer as any;- const f = fixture();- const lastGeometry = () => f.calls.filter(([name]) => name === "siyuan-map-geometry").at(-1)[1];- const tabsRect = {x: 10, y: 90, width: 400, height: 33};- const tabs = {getClientRects: () => [tabsRect], getBoundingClientRect: () => tabsRect};- const av = {querySelector: (selector: string) => {- assert.equal(selector, ":scope > .av__container > .av__header > .av__views--fixed");- return tabs;- }};- f.container.closest = (selector: string) => {- assert.equal(selector, ".av[data-type='NodeAttributeView']");- return av;- };- const getStyle = f.doc.defaultView.getComputedStyle;- f.doc.defaultView.getComputedStyle = (element: unknown) => ({...getStyle(element), position: element === tabs ? "fixed" : "static"});- f.rect.y = 60;- f.doc.elementFromPoint = (_x: number, y: number) => y >= tabsRect.y && y < tabsRect.y + tabsRect.height ? tabs : f.container;- try {- await f.created();- f.reply({type: "ready"});- f.advance();- assert.deepEqual(lastGeometry().bounds, {x: 10, y: 124, width: 400, height: 236});- assert.deepEqual(lastGeometry().logicalSize, {width: 400, height: 300});- assert.deepEqual(lastGeometry().crop, {x: 0, y: 64});- f.rect.y = 40;- f.domListeners.get("scroll")();- assert.deepEqual(lastGeometry().bounds, {x: 10, y: 124, width: 400, height: 216});- tabsRect.height += 5;- callbacks[0]();- assert.deepEqual(lastGeometry().bounds, {x: 10, y: 129, width: 400, height: 211});- assert.deepEqual(lastGeometry().crop, {x: 0, y: 89});- const menu = {contains: () => false, getClientRects: () => [f.rect],- getBoundingClientRect: () => ({x: 30, y: 160, width: 40, height: 40})};- f.doc.querySelectorAll = () => [menu];- callbacks[0]();- assert.equal(lastGeometry().visible, false);- f.doc.querySelectorAll = (): HTMLElement[] => [];- f.doc.elementFromPoint = () => ({});- callbacks[0]();- f.advance();- assert.equal(lastGeometry().visible, false, "other database bars and unknown overlays must still hide the map");- f.doc.elementFromPoint = () => f.container;- callbacks[0]();- f.advance();- assert.equal(lastGeometry().visible, true);- } finally {- f.host.destroy();- globalThis.MutationObserver = oldMutation;- globalThis.ResizeObserver = oldResize;- }- });- it("updates throughout continuous scrolling while hiding occlusion and stopping after disposal", async () => {- const oldMutation = globalThis.MutationObserver, oldResize = globalThis.ResizeObserver;- const callbacks: Array<() => void> = [];- class Observer {- constructor(callback: () => void) { callbacks.push(callback); }- observe() {}- disconnect() {}- }- globalThis.MutationObserver = Observer as any;- globalThis.ResizeObserver = Observer as any;- const f = fixture();- const geometryCalls = () => f.calls.filter(([name]) => name === "siyuan-map-geometry");- const lastGeometry = () => geometryCalls().at(-1)[1];- try {- f.rect.y = 180;- await f.created();- f.reply({type: "ready"});- f.advance();- const first = geometryCalls().length;- const scroll = f.domListeners.get("scroll");- for (let i = 0; i < 8; i++) {- f.rect.y -= 7;- scroll();- assert.equal(lastGeometry().bounds.y, f.rect.y);- f.advance(30);- f.rect.y -= 1;- callbacks[0]();- assert.equal(lastGeometry().bounds.y, f.rect.y, "layout mutations during scrolling must not restart hiding");- }- assert.ok(geometryCalls().slice(first).every(([, value]) => value.visible));- const menu = {contains: () => false, getClientRects: () => [f.rect], getBoundingClientRect: () => f.rect};- f.doc.querySelectorAll = () => [menu];- scroll();- assert.equal(lastGeometry().visible, false, "scrolling elsewhere must still hide a newly overlapping menu");- callbacks[0]();- assert.equal(lastGeometry().visible, false);- f.advance(30);- f.doc.querySelectorAll = (): HTMLElement[] => [];- f.doc.elementFromPoint = () => ({});- callbacks[0]();- assert.equal(lastGeometry().visible, false);- f.doc.elementFromPoint = () => f.container;- callbacks[0]();- assert.equal(lastGeometry().visible, true);- f.container.isConnected = false;- scroll();- assert.equal(lastGeometry().visible, false);- f.host.destroy();- const count = f.calls.length;- scroll();- callbacks[0]();- f.advance();- assert.equal(f.calls.length, count);- } finally {- f.host.destroy();- globalThis.MutationObserver = oldMutation;- globalThis.ResizeObserver = oldResize;- }- });- it("keeps unrelated hover mutations visible while geometry and occlusion changes hide immediately", async () => {- const oldMutation = globalThis.MutationObserver, oldResize = globalThis.ResizeObserver;- const callbacks: Array<() => void> = [];- class Observer {- constructor(callback: () => void) { callbacks.push(callback); }- observe() {}- disconnect() {}- }- globalThis.MutationObserver = Observer as any;- globalThis.ResizeObserver = Observer as any;- const f = fixture();- const geometryCalls = () => f.calls.filter(([name]) => name === "siyuan-map-geometry");- const lastGeometry = () => geometryCalls().at(-1)[1];- try {- await f.created();- f.reply({type: "ready"});- f.advance();- assert.equal(lastGeometry().visible, true);- const count = geometryCalls().length;- for (let i = 0; i < 5; i++) {- callbacks[0]();- f.advance(30);- }- assert.equal(geometryCalls().length, count, "unrelated gutter and tooltip mutations must not hide the map");- f.rect.x += 10;- callbacks[0]();- assert.equal(lastGeometry().visible, false, "a real geometry change hides before the next animation frame");- f.advance(119);- assert.equal(lastGeometry().visible, false);- callbacks[0]();- f.advance(1);- assert.equal(lastGeometry().visible, true, "unrelated mutations must not restart the stability delay");- assert.equal(lastGeometry().bounds.x, f.rect.x);- const menu = {contains: () => false, getClientRects: () => [f.rect],- getBoundingClientRect: () => ({...f.rect, width: 5, height: 5})};- f.doc.querySelectorAll = () => [menu];- callbacks[0]();- assert.equal(lastGeometry().visible, false, "an overlapping menu hides immediately even with unchanged bounds");- f.doc.querySelectorAll = (): HTMLElement[] => [];- callbacks[0]();- f.advance(119);- assert.equal(lastGeometry().visible, false);- f.advance(1);- assert.equal(lastGeometry().visible, true);- f.host.destroy();- const destroyedCount = f.calls.length;- callbacks[0]();- assert.equal(f.calls.length, destroyedCount, "queued mutations cannot reactivate a destroyed host");- } finally {- f.host.destroy();- globalThis.MutationObserver = oldMutation;- globalThis.ResizeObserver = oldResize;- }- });it("destroys a create that resolves after disposal and never recreates listeners", async () => {const f = fixture();f.host.destroy();diff --git a/app/src/protyle/render/av/map/desktopTransport.ts b/app/src/protyle/render/av/map/desktopTransport.tsindex 4d8b985a87..6ac4973df6 100644--- a/app/src/protyle/render/av/map/desktopTransport.ts+++ b/app/src/protyle/render/av/map/desktopTransport.ts@@ -3,9 +3,6 @@ import {ipcRenderer} from "electron";/// #endifimport type {AVMapHost, AVMapHostOptions} from "./host";import {getAVMapVisibility} from "./host";-import {MapGeometry} from "./desktopGeometry";-import {readDesktopAVMapGeometry} from "./desktopGeometryDOM";-import {registerDesktopMapUnplacedHost} from "./desktopUnplaced";import {AV_MAP_OWNER_TIMEOUT} from "./loadingBudget";import {AV_MAP_PROTOCOL_VERSION, AVMapCommand, AVMapErrorCode, AVMapPoint, isAVMapHostErrorCode, isAVMapProvider, isAVMapRevision,@@ -29,8 +26,7 @@ const mapDiagnosticCodes = new Set(["hostSetupFailed", "assetUnavailable", "documentLoadFailed", "bootstrapTimeout", "sdkTimeout","providerRequestDenied", "providerInsecureRequest", "providerHTTPFailure", "providerNetworkFailure","cspScript", "cspWorker", "cspConnect", "cspImage", "cspStyle", "cspEval", "cspWasm",- "storageUnavailable", "webglUnavailable", "geometryInvalid", "geometryLogicalBounds",- "geometryCropBounds", "geometryWindowBounds", "geometryRoundedEmpty",+ "storageUnavailable", "webglUnavailable",]);const mapCSPDiagnosticCodes = new Set(["cspScript", "cspWorker", "cspConnect", "cspImage", "cspStyle", "cspEval", "cspWasm"]);const mapCSPResourceCodes = new Set([@@ -52,7 +48,7 @@ const logMapDiagnostic = (code: unknown, resource?: unknown) => {}};-type DesktopMapCreation = {mode: "native"} | {mode: "webview"; src: string; partition: string};+type DesktopMapCreation = {mode: "webview"; src: string; partition: string};// 主进程只可返回固定地图文档和临时分区;不接受通用 webview 属性或其他导航目标。export const parseDesktopMapCreation = (value: unknown, instanceID: string, origin: string): DesktopMapCreation | undefined => {@@ -60,9 +56,6 @@ export const parseDesktopMapCreation = (value: unknown, instanceID: string, origconst reply = value as Record<string, unknown>;if (reply.version !== AV_MAP_PROTOCOL_VERSION || reply.instanceID !== instanceID) return;const keys = Object.keys(reply);- if (reply.mode === "native") {- return keys.length === 3 ? {mode: "native"} : undefined;- }if (reply.mode !== "webview" || keys.length !== 5 || typeof reply.src !== "string" ||typeof reply.partition !== "string" || !/^siyuan-map-[a-f0-9]{48}$/.test(reply.partition)) return;let owner: URL;@@ -97,32 +90,22 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHosconst scope = container.ownerDocument.defaultView;const ipc = getIPC();let destroyed = false, ready = false, created = false, pendingReady = false;- let mode: DesktopMapCreation["mode"];let webview: HTMLElement;let instanceID = "", revision = -1, theme = options.theme;let points: AVMapPoint[] = [];let ids = new Set<string>();- let frame = 0, timeout = 0, stableAfter = 0, scrollingUntil = 0;- let lastGeometry = "", sentGeometry = "", lastVisibility = "";+ let frame = 0, timeout = 0;+ let lastVisibility = "";const diagnostics = new Set<string>();- let observer: MutationObserver;let resizeObserver: ResizeObserver;- let releaseUnplacedHost: () => void;const envelope = () => ({version: AV_MAP_PROTOCOL_VERSION, instanceID} as const);const send = (command: AVMapCommand) => {if (!destroyed && ready) {ipc.send("siyuan-map-command", command);}};- const geometry = (value: MapGeometry) => {- const key = JSON.stringify(value);- if (created && key !== sentGeometry) {- ipc.send("siyuan-map-geometry", {...envelope(), ...value});- sentGeometry = key;- }- };const updateVisibility = () => {- if (destroyed || mode !== "webview") return;+ if (destroyed) return;const next = ready ? getAVMapVisibility(container) : {visible: false};const key = JSON.stringify(next);if (key !== lastVisibility) {@@ -132,67 +115,15 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos};const invalidate = () => {if (!destroyed && scope) {- if (mode === "webview") {- updateVisibility();- send({...envelope(), type: "resize"});- return;- }- stableAfter = scope.performance.now() + 120;- geometry({visible: false});- }- };- const checkGeometry = () => {- const next = readDesktopAVMapGeometry(container);- const key = JSON.stringify(next);- if (key !== lastGeometry) {- lastGeometry = key;- if (scope.performance.now() < scrollingUntil) {- stableAfter = 0;- geometry(next);- } else {- stableAfter = scope.performance.now() + 120;- geometry({visible: false});- }- }- if (!next.visible) {- geometry(next);- }- return next;- };- const onScroll = () => {- if (!destroyed && scope) {- if (mode === "webview") {- updateVisibility();- return;- }- // 滚动和同轮固定栏布局更新都使用完整遮挡检查后的最新裁剪,不等待滚动停止。- scrollingUntil = scope.performance.now() + 120;- stableAfter = 0;- geometry(checkGeometry());- }- };- const onFocus = () => {- if (!destroyed) {- if (mode === "webview") {- updateVisibility();- return;- }- // 从原生地图回到编辑器只复核布局;实际几何或遮挡变化仍会立即隐藏地图。- checkGeometry();+ updateVisibility();+ send({...envelope(), type: "resize"});}};const tick = () => {if (destroyed) {return;}- if (mode === "webview") {- updateVisibility();- } else {- const next = checkGeometry();- if (!next.visible || scope.performance.now() >= stableAfter) {- geometry(next);- }- }+ updateVisibility();frame = scope.requestAnimationFrame(tick);};const destroy = () => {@@ -201,8 +132,6 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos}destroyed = true;ready = false;- releaseUnplacedHost?.();- releaseUnplacedHost = undefined;if (instanceID) {ipc?.send("siyuan-map-destroy", envelope());}@@ -210,11 +139,10 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHosscope?.clearTimeout(timeout);scope?.cancelAnimationFrame(frame);scope?.removeEventListener("pagehide", destroy);- scope?.removeEventListener("scroll", onScroll, true);+ scope?.removeEventListener("scroll", updateVisibility, true);scope?.removeEventListener("resize", invalidate);- scope?.removeEventListener("focus", onFocus);+ scope?.removeEventListener("focus", updateVisibility);container.ownerDocument.removeEventListener("visibilitychange", invalidate);- observer?.disconnect();resizeObserver?.disconnect();webview?.remove();points = [];@@ -237,7 +165,7 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHosreturn;}const diagnostic = value as {version?: unknown; instanceID?: unknown; type?: unknown; code?: unknown; resource?: unknown};- if (mode === "webview" && ready && diagnostic?.version === AV_MAP_PROTOCOL_VERSION &&+ if (ready && diagnostic?.version === AV_MAP_PROTOCOL_VERSION &&diagnostic.instanceID === instanceID && diagnostic.type === "dismissMenu") {if (Object.keys(diagnostic).length === 3 && getAVMapVisibility(container).visible) {// 只消费主进程由真实 guest 鼠标输入产生的固定信号,不合成编辑器事件。@@ -271,7 +199,7 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos} else if (reply?.type === "markerClick" && ready && reply.revision === revision && ids.has(reply.id)) {options.onMarkerClick(reply.id, reply.revision);} else if (reply?.type === "attributionClick" && ready) {- // 主进程已校验原生视图可见性,并消费一次可信用户输入。+ // 主进程已校验 guest 可见区域,并消费一次可信用户输入。options.onAttributionClick?.(reply.link);} else if (reply?.type === "error") {fail(reply.code);@@ -338,36 +266,18 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHosfail("hostCreateInvalidResponse");return;}- mode = creation.mode;created = true;- if (creation.mode === "webview") {- webview = container.ownerDocument.createElement("webview");- webview.setAttribute("title", options.title || "");- webview.style.cssText = "width:100%;height:100%;border:0;display:flex";- // 分区必须在 src 和连接 DOM 之前指定,主进程再次校验并强制安全偏好。- webview.setAttribute("partition", creation.partition);- webview.setAttribute("src", creation.src);- container.append(webview);- } else {- releaseUnplacedHost = registerDesktopMapUnplacedHost(container, {- ipc, envelope, available: () => ready && !destroyed, theme: () => theme,- });- }- scope.addEventListener("scroll", onScroll, true);+ webview = container.ownerDocument.createElement("webview");+ webview.setAttribute("title", options.title || "");+ webview.style.cssText = "width:100%;height:100%;border:0;display:flex";+ // 分区必须在 src 和连接 DOM 之前指定,主进程再次校验并强制安全偏好。+ webview.setAttribute("partition", creation.partition);+ webview.setAttribute("src", creation.src);+ container.append(webview);+ scope.addEventListener("scroll", updateVisibility, true);scope.addEventListener("resize", invalidate);- // DOM 焦点会在编辑器与原生地图间切换,窗口是否隐藏由主进程与文档可见性共同判断。- scope.addEventListener("focus", onFocus);+ scope.addEventListener("focus", updateVisibility);container.ownerDocument.addEventListener("visibilitychange", invalidate);- if (mode === "native") {- observer = new MutationObserver(() => {- // 悬停提示和块标也会改变 DOM;仅地图几何或遮挡变化需要隐藏原生视图。- if (!destroyed) {- checkGeometry();- }- });- observer.observe(container.ownerDocument.documentElement, {childList: true, subtree: true,- attributes: true, attributeFilter: ["class", "style", "hidden", "open"]});- }resizeObserver = new ResizeObserver(invalidate);resizeObserver.observe(container);if (pendingReady) onReply(undefined, {...envelope(), type: "ready"});diff --git a/app/src/protyle/render/av/map/desktopUnplaced.ts b/app/src/protyle/render/av/map/desktopUnplaced.tsdeleted file mode 100644index b0d5340952..0000000000--- a/app/src/protyle/render/av/map/desktopUnplaced.ts+++ /dev/null@@ -1,238 +0,0 @@-import {AV_MAP_PROTOCOL_VERSION, AVMapTheme, isAVMapIdentifier, isAVMapRevision} from "./protocol";--interface DesktopMapUnplacedIPC {- invoke: (channel: string, value: unknown) => Promise<unknown>;- send: (channel: string, value: unknown) => void;- on: (channel: string, callback: (event: unknown, value: unknown) => void) => unknown;- removeListener: (channel: string, callback: (event: unknown, value: unknown) => void) => unknown;-}--export interface DesktopMapUnplacedState {- requestID: number;- query: string;- rows: Array<{id: string; title: string}>;- total: number;- page: number;- loading: boolean;- error: boolean;- labels: {title: string; search: string; empty: string; loading: string; more: string;- previous: string; retry: string; close: string};-}--export interface DesktopMapUnplacedAction {- action: "editing" | "search" | "more" | "previous" | "retry" | "select";- requestID: number;- query?: string;- page?: number;- id?: string;-}--export interface DesktopMapUnplacedHandle {- update: (state: DesktopMapUnplacedState) => void;- close: () => void;-}--interface DesktopMapUnplacedHost {- ipc: DesktopMapUnplacedIPC;- envelope: () => {version: 1; instanceID: string};- available: () => boolean;- theme: () => AVMapTheme;-}--interface Registration extends DesktopMapUnplacedHost { close?: () => void; }-const hosts = new WeakMap<HTMLElement, Registration>();-const CHANNEL = "siyuan-map-unplaced-";-const isSession = (value: unknown): value is string => typeof value === "string" && /^[a-f0-9]{48}$/.test(value);-const failures = new Set(["operation-failed", "document-mismatch", "renderer-failed", "ready-timeout", "load-failed", "setup-failed", "resource-failed"]);--export const registerDesktopMapUnplacedHost = (canvas: HTMLElement, host: DesktopMapUnplacedHost) => {- hosts.get(canvas)?.close?.();- const registration: Registration = {...host};- hosts.set(canvas, registration);- return () => {- registration.close?.();- if (hosts.get(canvas) === registration) hosts.delete(canvas);- };-};--// 完整记录与数据库上下文始终留在 owner;独立菜单只收到当前页的 ID 和纯文本标题。-export const openDesktopMapUnplaced = (canvas: HTMLElement, anchor: HTMLElement,- initial: DesktopMapUnplacedState,- onAction: (action: DesktopMapUnplacedAction) => void,- onClose: (failed: boolean) => void, available: () => boolean): DesktopMapUnplacedHandle | undefined => {- const host = hosts.get(canvas);- const scope = anchor.ownerDocument?.defaultView;- if (!host?.available() || !scope || !available()) return;- host.close?.();- const envelope = host.envelope();- let closed = false, sessionID = "", revision = 0, latestRequestID = initial.requestID;- let frame = 0, timeout = 0, lastAnchor = "", lastTheme = "";- let state = initial;- const pendingClosed = new Map<string, {restore: boolean; failed: boolean}>();- const active = () => !closed && hosts.get(canvas) === host && host.available() && available() &&- canvas.isConnected && anchor.isConnected && !anchor.ownerDocument.hidden;- const theme = () => ({mode: host.theme(),- fontSize: Math.max(12, Math.min(32, Math.round(Number.parseFloat(- scope.getComputedStyle(anchor.ownerDocument.documentElement).getPropertyValue("--b3-font-size")) || 14)))});- const wireState = () => ({...state, revision, theme: theme(),- rows: state.rows.map(row => ({id: row.id, title: row.title})), labels: {...state.labels}});- const position = () => {- if (!active()) return;- const rect = anchor.getBoundingClientRect();- let left = Math.max(0, rect.left), top = Math.max(0, rect.top);- let right = Math.min(scope.innerWidth, rect.right), bottom = Math.min(scope.innerHeight, rect.bottom);- if (right <= left || bottom <= top) return;- // 裁剪祖先变化后,按钮不能在滚动区域外继续成为原生菜单的锚点。- for (let parent = anchor; parent; parent = parent.parentElement) {- const style = scope.getComputedStyle(parent);- if (style.display === "none" || style.visibility !== "visible" || Number.parseFloat(style.opacity) === 0 ||- style.getPropertyValue?.("content-visibility") === "hidden") return;- if (/(auto|scroll|hidden|clip)/.test(style.overflowX + " " + style.overflowY)) {- const bounds = parent.getBoundingClientRect();- if (/(auto|scroll|hidden|clip)/.test(style.overflowX)) {- left = Math.max(left, bounds.left);- right = Math.min(right, bounds.right);- }- if (/(auto|scroll|hidden|clip)/.test(style.overflowY)) {- top = Math.max(top, bounds.top);- bottom = Math.min(bottom, bounds.bottom);- }- }- }- if (right <= left || bottom <= top || left > rect.left || top > rect.top || right < rect.right || bottom < rect.bottom) return;- const hit = anchor.ownerDocument.elementFromPoint((left + right) / 2, (top + bottom) / 2);- if (!hit || !anchor.contains(hit)) return;- return {x: left, y: top, width: right - left, height: bottom - top};- };- const send = (type: string, value: Record<string, unknown> = {}) => {- if (sessionID) host.ipc.send(CHANNEL + type, {...envelope, sessionID, ...value});- };- const finish = (restore = false, failed = false) => {- if (closed) return;- closed = true;- scope.clearTimeout(timeout);- scope.cancelAnimationFrame(frame);- scope.removeEventListener("scroll", geometry, true);- scope.removeEventListener("resize", geometry);- scope.removeEventListener("pagehide", close);- anchor.ownerDocument.removeEventListener("pointerdown", outside, true);- anchor.ownerDocument.removeEventListener("keydown", keydown, true);- anchor.ownerDocument.removeEventListener("visibilitychange", geometry);- host.ipc.removeListener(CHANNEL + "reply", reply);- if (host.close === close) host.close = undefined;- state = {...state, rows: []};- pendingClosed.clear();- onClose(failed);- if (restore && anchor.isConnected && available()) anchor.focus();- };- const close = () => {- send("close", {reason: "anchor-hidden"});- finish();- };- const fail = () => {- send("close", {reason: "anchor-hidden"});- finish(false, true);- };- const geometry = () => {- if (closed) return;- const next = position();- if (!next) { close(); return; }- const key = JSON.stringify(next);- if (key !== lastAnchor) {- lastAnchor = key;- send("anchor", {anchor: next});- }- };- const outside = (event: PointerEvent) => {- if (!anchor.contains(event.target as Node)) {- send("close", {reason: "outside"});- finish();- }- };- const keydown = (event: KeyboardEvent) => {- if (event.key === "Escape") {- event.preventDefault();- send("close", {reason: "button"});- finish(true);- }- };- const reply = (_event: unknown, value: unknown) => {- const input = value as Record<string, unknown>;- if (closed || !input || input.version !== AV_MAP_PROTOCOL_VERSION || input.instanceID !== envelope.instanceID) return;- if (!sessionID && input.type === "closed" && isSession(input.sessionID) && pendingClosed.size < 4) {- pendingClosed.set(input.sessionID, {restore: input.restore === true, failed: failures.has(input.reason as string)});- return;- }- if (input.sessionID !== sessionID || !sessionID) return;- if (input.type === "closed") { finish(input.restore === true, failures.has(input.reason as string)); return; }- if (!active()) { close(); return; }- if (input.type !== "action" || !isAVMapRevision(input.revision) || input.revision > revision || !isAVMapRevision(input.requestID)) return;- if (input.action === "select") {- if (input.revision !== revision || input.requestID !== latestRequestID || state.loading || state.error || !isAVMapIdentifier(input.id) ||- !state.rows.some(row => row.id === input.id)) return;- onAction({action: "select", requestID: input.requestID, id: input.id});- finish();- return;- }- if (!["editing", "search", "more", "previous", "retry"].includes(input.action as string) ||- input.requestID <= latestRequestID) return;- // 主进程已按其接受的版本校验意图;交错到达的 API 回包不能阻止新搜索取消旧请求。- // 只有编辑和翻页可跨越尚未被主进程接受的数据版本,选择始终严格匹配当前版本与成员。- if (input.action !== "editing" && (typeof input.query !== "string" || input.query.length > 256 ||- input.query.includes("\0") || !isAVMapRevision(input.page) || input.page < 1)) return;- latestRequestID = input.requestID;- onAction({action: input.action as DesktopMapUnplacedAction["action"], requestID: input.requestID,- query: input.query as string, page: input.page as number});- };- const tick = () => {- geometry();- if (closed) return;- const nextTheme = JSON.stringify(theme());- if (nextTheme !== lastTheme) {- lastTheme = nextTheme;- send("theme", {theme: theme()});- }- frame = scope.requestAnimationFrame(tick);- };- const firstAnchor = position();- if (!firstAnchor) return;- lastAnchor = JSON.stringify(firstAnchor);- lastTheme = JSON.stringify(theme());- host.close = close;- host.ipc.on(CHANNEL + "reply", reply);- scope.addEventListener("scroll", geometry, true);- scope.addEventListener("resize", geometry);- scope.addEventListener("pagehide", close);- anchor.ownerDocument.addEventListener("pointerdown", outside, true);- anchor.ownerDocument.addEventListener("keydown", keydown, true);- anchor.ownerDocument.addEventListener("visibilitychange", geometry);- timeout = scope.setTimeout(fail, 8000);- frame = scope.requestAnimationFrame(tick);- void host.ipc.invoke(CHANNEL + "open", {...envelope, state: wireState(), anchor: firstAnchor}).then(value => {- const result = value as {version?: unknown; instanceID?: unknown; sessionID?: unknown};- if (result?.version !== AV_MAP_PROTOCOL_VERSION || result.instanceID !== envelope.instanceID || !isSession(result.sessionID)) {- fail();- return;- }- sessionID = result.sessionID;- if (closed || !active()) {- send("close", {reason: "anchor-hidden"});- finish();- return;- }- const ended = pendingClosed.get(sessionID);- if (ended) { finish(ended.restore, ended.failed); return; }- pendingClosed.clear();- scope.clearTimeout(timeout);- if (revision > 0) send("update", {state: wireState()});- send("theme", {theme: theme()});- lastAnchor = "";- geometry();- }).catch(fail);- return {update: next => {- if (!active()) { close(); return; }- state = next;- revision++;- send("update", {state: wireState()});- }, close};-};diff --git a/app/src/protyle/render/av/map/unplaced.test.ts b/app/src/protyle/render/av/map/unplaced.test.tsindex c1429169a9..1772d53c8d 100644--- a/app/src/protyle/render/av/map/unplaced.test.ts+++ b/app/src/protyle/render/av/map/unplaced.test.ts@@ -7,9 +7,6 @@ import type {AVTableRow} from "../../../../types/api";import * as escape from "../../../../util/escape";import * as locationValue from "../locationValue";import {getMapSettings} from "./state";-import * as unplacedMenu from "./unplacedMenu";-import * as desktopUnplaced from "./desktopUnplaced";-import * as protocol from "./protocol";import {requireFixture} from "./testDOM";class ElementStub {@@ -44,11 +41,7 @@ const row = (id: string, location?: IAVCellLocationValue): AVTableRow => ({id, cconst flush = () => new Promise(resolve => setImmediate(resolve));-const bridgeSource = transpileModule(readFileSync("src/protyle/render/av/map/desktopUnplaced.ts", "utf8"), {- compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},-}).outputText;--const setup = (mobile = false, nativeReady = false) => {+const setup = (mobile = false) => {const requests: Array<{payload: any; signal: AbortSignal; resolve: (response: unknown) => void;reject: (reason?: unknown) => void}> = [];const timers = new Map<number, () => void>();@@ -69,7 +62,6 @@ const setup = (mobile = false, nativeReady = false) => {let current = true;let positions = 0;const opens: Array<{row: IAVRow; keyID: string}> = [];- const messages: string[] = [];const menus: MenuStub[] = [];class MenuStub {items: Array<{option: IMenu; element: ElementStub}> = [];@@ -102,44 +94,12 @@ const setup = (mobile = false, nativeReady = false) => {get: (_target, key: string) => key,}), menus: {menu: {resetPosition: () => { positions++; }}}},setTimeout: (callback: () => void) => { timers.set(++nextTimer, callback); return nextTimer; }};- const bridge = {} as typeof desktopUnplaced;- runInNewContext(bridgeSource, {exports: bridge, window: context, require: requireFixture({"./protocol": protocol})});- const nativeOpens: Array<{value: any; resolve: (value: unknown) => void}> = [];- const nativeSent: Array<{channel: string; value: any}> = [];- const nativeListeners = new Map<string, (event: unknown, value: unknown) => void>();- const nativeFrames = new Map<number, () => void>();- const nativeTimers = new Map<number, () => void>();- const scopeEvents = new Map<string, (event?: any) => void>();- const documentEvents = new Map<string, (event?: any) => void>();- const scope = {innerWidth: 1000, innerHeight: 800,- getComputedStyle: () => ({display: "block", visibility: "visible", overflowX: "visible", overflowY: "visible",- getPropertyValue: (name: string) => name === "--b3-font-size" ? "14px" : ""}),- addEventListener: (type: string, callback: () => void) => scopeEvents.set(type, callback),- removeEventListener: (type: string) => scopeEvents.delete(type),- requestAnimationFrame: (callback: () => void) => { nativeFrames.set(++nextTimer, callback); return nextTimer; },- cancelAnimationFrame: (id: number) => nativeFrames.delete(id),- setTimeout: (callback: () => void) => { nativeTimers.set(++nextTimer, callback); return nextTimer; },- clearTimeout: (id: number) => nativeTimers.delete(id)};- const document = {defaultView: scope, hidden: false, elementFromPoint: () => toggle,- addEventListener: (type: string, callback: () => void) => documentEvents.set(type, callback),- removeEventListener: (type: string) => documentEvents.delete(type)};- canvas.ownerDocument = document;- toggle.ownerDocument = document;- let ready = nativeReady;- let theme: "light" | "dark" = "light";- const releaseHost = bridge.registerDesktopMapUnplacedHost(canvas as unknown as HTMLElement, {- ipc: {invoke: (_channel, value) => new Promise(resolve => nativeOpens.push({value, resolve})),- send: (channel, value) => nativeSent.push({channel, value}),- on: (channel, callback) => nativeListeners.set(channel, callback),- removeListener: channel => nativeListeners.delete(channel)},- envelope: () => ({version: 1, instanceID: "map-instance"}), available: () => ready, theme: () => theme});const methods = {} as typeof import("./unplaced");runInNewContext(transpileModule(readFileSync("src/protyle/render/av/map/unplaced.ts", "utf8"), {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},}).outputText, {exports: methods, window: context, AbortController,clearTimeout: (id: number) => timers.delete(id), require: requireFixture({"../../../../constants": {Constants: {TIMEOUT_INPUT: 256, ATTRIBUTE_MENU_KEYMAP: "data-keymap"}},- "../../../../dialog/message": {showMessage: (text: string) => messages.push(text)},"../../../../plugin/Menu": {Menu: MenuStub},"../../../../util/escape": escape,"../../../../util/functions": {isMobile: () => mobile},@@ -150,9 +110,6 @@ const setup = (mobile = false, nativeReady = false) => {}},"../locationValue": locationValue,"./state": {getMapSettings},- "./unplacedMenu": unplacedMenu,- "./desktopUnplaced": bridge,- "./protocol": protocol,"./settings": {canEditMapSettings: () => !protyle.disabled && !context.siyuan.isPublish &&!protyle.options.history?.created && !protyle.options.history?.snapshot},"./openRecord": {openMapRecord: (_protyle: IProtyle, _block: HTMLElement, row: IAVRow, keyID: string) =>@@ -160,24 +117,7 @@ const setup = (mobile = false, nativeReady = false) => {})});const destroy = methods.bindMapUnplaced({root: root as unknown as HTMLElement, blockElement: block as unknown as HTMLElement,protyle, data, current: () => current});- let issuedRequestID = 0;- const nativeState = () => nativeSent.filter(item => item.channel === "siyuan-map-unplaced-update").at(-1)?.value.state ||- nativeOpens.at(-1)?.value.state;- const nativeReply = (value: Record<string, unknown>) => nativeListeners.get("siyuan-map-unplaced-reply")?.({}, {- version: 1, instanceID: "map-instance", sessionID: "a".repeat(48), ...value});- return {methods, requests, menus, toggle, count, input, canvas, data, protyle, context, opens, destroy,- nativeOpens, nativeSent, nativeState, nativeReply, releaseHost, document, scope, documentEvents, scopeEvents, messages,- setTheme: (value: "light" | "dark") => { theme = value; },- setReady: (value: boolean) => { ready = value; },- nativeOpen: async (index = nativeOpens.length - 1) => {- nativeOpens[index].resolve({version: 1, instanceID: "map-instance", sessionID: "a".repeat(48)});- await flush();- },- nativeAction: (action: string, extra: Record<string, unknown> = {}) => nativeReply({type: "action", action,- revision: nativeState().revision, requestID: action === "select" ? nativeState().requestID : ++issuedRequestID,- query: nativeState().query, page: nativeState().page, ...extra}),- runNativeFrames: () => { const pending = [...nativeFrames.values()]; nativeFrames.clear(); pending.forEach(callback => callback()); },- runNativeTimers: () => { const pending = [...nativeTimers.values()]; nativeTimers.clear(); pending.forEach(callback => callback()); },+ return {methods, requests, menus, toggle, count, input, canvas, data, protyle, context, opens, destroy, block, search,positions: () => positions,stale: () => { current = false; },click: () => toggle.events.get("click")({preventDefault() {}}),@@ -309,18 +249,46 @@ test("map unplaced search aborts obsolete requests and resets its own page withoscenario.destroy();});+test("shared unplaced search aborts immediately and rejects ABA responses and detached row actions", async () => {+ const scenario = setup();+ scenario.click();+ await scenario.respond(1, [row("original")]);+ const original = scenario.menus[0].active().find(item => item.option.label === "<Title original>");+ scenario.inputSearch("same");+ original.option.click(original.element as unknown as HTMLElement, {} as MouseEvent);+ assert.equal(scenario.opens.length, 0, "typing detaches old records before the debounce completes");+ scenario.runTimers();+ const first = scenario.requests.length - 1;+ scenario.inputSearch("other");+ assert.equal(scenario.requests[first].signal.aborted, true);+ scenario.runTimers();+ const second = scenario.requests.length - 1;+ scenario.inputSearch("same");+ assert.equal(scenario.requests[second].signal.aborted, true);+ scenario.runTimers();+ const last = scenario.requests.length - 1;+ assert.equal(scenario.requests[last].payload.search, "same");+ assert.equal(scenario.requests[last].payload.query, "main query");+ await scenario.respond(last, [row("latest")]);+ await scenario.respond(first, [row("stale-same")]);+ await scenario.respond(second, [row("stale-other")]);+ const labels = scenario.menus[0].active().map(item => item.option.label);+ assert.equal(labels.includes("<Title latest>"), true);+ assert.equal(labels.includes("<Title stale-same>"), false);+ assert.equal(labels.includes("<Title stale-other>"), false);+ scenario.menus[0].click("<Title latest>");+ assert.equal(scenario.opens[0].row.id, "latest");+ scenario.destroy();+});+test("closing or destroying unplaced menus aborts pending work and rejects late responses", async () => {for (const close of ["toggle", "menu", "destroy"]) {const scenario = setup();scenario.click();- assert.equal(unplacedMenu.isMapUnplacedMenu(scenario.menus[0].element as unknown as HTMLElement,- scenario.canvas as unknown as HTMLElement), true);if (close === "toggle") scenario.click();if (close === "menu") scenario.menus[0].close();if (close === "destroy") scenario.destroy();assert.equal(scenario.requests[1].signal.aborted, true, close);- assert.equal(unplacedMenu.isMapUnplacedMenu(scenario.menus[0].element as unknown as HTMLElement,- scenario.canvas as unknown as HTMLElement), false);assert.equal(scenario.toggle.attributes.get("aria-expanded"), "false");const before = scenario.positions();await scenario.respond(1, [row("late")]);@@ -366,7 +334,7 @@ test("reopening an inbox starts fresh and a replaced menu response cannot overwr});test("stale permissions, field changes and removed maps cannot open rows or revive an inbox", async () => {- for (const mode of ["disabled", "published", "created", "snapshot", "field", "removed"]) {+ for (const mode of ["disabled", "published", "created", "snapshot", "field", "view", "database", "query", "notebook", "removed"]) {const scenario = setup();scenario.click();await scenario.respond(1, [row("entry")]);@@ -374,6 +342,13 @@ test("stale permissions, field changes and removed maps cannot open rows or reviif (mode === "published") scenario.context.siyuan.isPublish = true;if (["created", "snapshot"].includes(mode)) scenario.protyle.options.history = {[mode]: "version"};if (mode === "field") (scenario.data.view as IAVTable).map.locationKeyID = "different";+ if (mode === "view") scenario.data.viewID = "changed";+ if (mode === "database") scenario.block.dataset.avId = "changed";+ if (mode === "query") scenario.search.textContent = "changed query";+ if (mode === "notebook") {+ scenario.protyle.notebookId = "private";+ Object.assign(scenario.context.siyuan, {notebooks: [{id: "private", encrypted: true, closed: true}]});+ }if (mode === "removed") scenario.stale();scenario.menus[0].click("<Title entry>");assert.equal(scenario.opens.length, 0, mode);@@ -384,14 +359,32 @@ test("stale permissions, field changes and removed maps cannot open rows or revi}});+test("pending unplaced responses cannot populate a changed view or locked encrypted notebook", async () => {+ for (const mode of ["view", "notebook", "removed"]) {+ const scenario = setup();+ scenario.click();+ if (mode === "view") scenario.data.viewID = "changed";+ if (mode === "notebook") {+ scenario.protyle.notebookId = "private";+ Object.assign(scenario.context.siyuan, {notebooks: [{id: "private", encrypted: true, closed: true}]});+ }+ if (mode === "removed") scenario.stale();+ const positions = scenario.positions();+ await scenario.respond(1, [row("late")]);+ await scenario.respond(0, [row("late")]);+ assert.equal(scenario.positions(), positions, mode);+ assert.equal(scenario.menus[0].active().some(item => item.option.label === "<Title late>"), false, mode);+ assert.equal(scenario.toggle.classes.has("fn__none"), true, mode);+ scenario.destroy();+ }+});+test("mobile unplaced menu uses shared menu placement without forcing a software keyboard", async () => {const scenario = setup(true);scenario.click();await scenario.respond(1, [row("mobile")]);assert.equal(scenario.menus[0].position.target, scenario.toggle);assert.equal(scenario.input.focused, false);- assert.equal(unplacedMenu.isMapUnplacedMenu(scenario.menus[0].element as unknown as HTMLElement,- scenario.canvas as unknown as HTMLElement), false);scenario.menus[0].click("<Title mobile>");assert.equal(scenario.opens[0].row.id, "mobile");scenario.destroy();@@ -416,264 +409,3 @@ test("DOM inbox layout belongs to the open menu and preserves the flat search anscenario.destroy();}});--test("ready desktop host uses the real unplaced API and sends only the current page of text to the native menu", async () => {- const scenario = setup(false, true);- scenario.click();- assert.equal(scenario.menus.length, 0, "native menus must not create a DOM menu over the map");- assert.equal(scenario.nativeOpens.length, 1);- assert.equal(scenario.nativeOpens[0].value.state.theme.fontSize, 14, "menu uses shared UI font size");- assert.equal(scenario.nativeOpens[0].value.state.labels.search, "searchPlaceholder");- assert.equal(JSON.stringify(scenario.requests[1].payload), JSON.stringify({id: "database", blockID: "carrier",- viewID: "map-view", query: "main query", search: "", page: 1, pageSize: 50}));- await scenario.nativeOpen();- const pageRows = (page: number) => Array.from({length: page === 12 ? 1 : 50}, (_, index) => row(`record-${(page - 1) * 50 + index}`));- await scenario.respond(1, pageRows(1), 551);- assert.equal(scenario.nativeState().rows.length, 50);- assert.equal(JSON.stringify(scenario.nativeState().rows[0]), JSON.stringify({id: "record-0", title: "<Title record-0>"}));- assert.equal(scenario.nativeState().labels.more, "next");- assert.equal(scenario.nativeState().labels.previous, "previous");- for (let page = 2; page <= 12; page++) {- scenario.nativeAction("more", {page});- const index = scenario.requests.length - 1;- assert.equal(scenario.requests[index].payload.page, page);- await scenario.respond(index, pageRows(page), 551);- assert.equal(scenario.nativeState().rows[0].id, `record-${(page - 1) * 50}`);- assert.ok(scenario.nativeState().rows.length <= 50);- }- scenario.nativeAction("previous", {page: 11});- await scenario.respond(scenario.requests.length - 1, pageRows(11), 551);- scenario.nativeAction("select", {id: "record-550"});- assert.equal(scenario.opens.length, 0, "a row from a replaced page is not selectable");- scenario.nativeAction("select", {id: "record-500"});- assert.equal(scenario.opens[0].row.id, "record-500");- assert.equal(scenario.toggle.attributes.get("aria-expanded"), "false");- assert.equal(scenario.toggle.focused, true);- assert.equal((scenario.data.view as IAVTable).rows.length, 0);- scenario.destroy();-});--test("native search aborts immediately while typing and rejects ABA responses with the same query", async () => {- const scenario = setup(false, true);- scenario.click();- await scenario.nativeOpen();- await scenario.respond(1, [row("original")], 1);- scenario.nativeAction("editing");- scenario.nativeAction("select", {id: "original"});- assert.equal(scenario.opens.length, 0);- scenario.setTheme("dark");- const revision = scenario.nativeState().revision;- scenario.runNativeFrames();- assert.equal(scenario.nativeState().revision, revision, "theme updates never advance the data revision during editing");- assert.equal(scenario.nativeSent.at(-1)?.channel, "siyuan-map-unplaced-theme");- assert.equal(scenario.nativeSent.at(-1)?.value.theme.mode, "dark");- scenario.nativeAction("search", {query: "same", page: 1});- const first = scenario.requests.length - 1;- scenario.nativeAction("editing");- assert.equal(scenario.requests[first].signal.aborted, true);- scenario.nativeAction("search", {query: "other", page: 1});- const second = scenario.requests.length - 1;- scenario.nativeAction("editing");- scenario.nativeAction("search", {query: "same", page: 1});- const last = scenario.requests.length - 1;- assert.equal(scenario.requests[last].payload.search, "same");- assert.equal(scenario.requests[last].payload.query, "main query");- await scenario.respond(last, [row("latest")]);- await scenario.respond(first, [row("stale-same")]);- await scenario.respond(second, [row("stale-other")]);- assert.equal(scenario.nativeState().rows[0].id, "latest");- assert.equal(scenario.nativeState().theme.mode, "dark");- scenario.destroy();-});--test("native paging failures retry the exact failed page and preserve the view query", async () => {- const scenario = setup(false, true);- scenario.click();- await scenario.nativeOpen();- await scenario.respond(1, [row("first")], 120);- scenario.nativeAction("more", {page: 2});- scenario.requests[2].reject(new Error("offline"));- await flush();- assert.equal(scenario.nativeState().error, true);- assert.equal(scenario.nativeState().page, 2);- scenario.nativeAction("retry", {page: 2});- assert.equal(scenario.requests[3].payload.page, 2);- await scenario.respond(3, [row("retry-page")], 120);- assert.equal(scenario.nativeState().error, false);- assert.equal(scenario.nativeState().rows[0].id, "retry-page");- scenario.destroy();-});--test("native ownership rejects foreign session, instance, revision and request messages", async () => {- const scenario = setup(false, true);- scenario.click();- await scenario.nativeOpen();- await scenario.respond(1, [row("record")]);- for (const mismatch of [{sessionID: "b".repeat(48)}, {instanceID: "other"}, {revision: 0}, {requestID: 999}]) {- scenario.nativeReply({type: "action", action: "select", revision: scenario.nativeState().revision,- requestID: scenario.nativeState().requestID, id: "record", ...mismatch});- }- assert.equal(scenario.opens.length, 0);- assert.equal(scenario.toggle.attributes.get("aria-expanded"), "true");- scenario.nativeAction("select", {id: "record"});- assert.equal(scenario.opens.length, 1);- scenario.destroy();-});--test("native menus close and abort proactively when their owner, permissions, field, view or encrypted notebook becomes unavailable", async () => {- for (const mode of ["disabled", "published", "history", "field", "view", "removed", "notebook", "host", "canvas"]) {- const scenario = setup(false, true);- scenario.click();- await scenario.nativeOpen();- if (mode === "disabled") scenario.protyle.disabled = true;- if (mode === "published") scenario.context.siyuan.isPublish = true;- if (mode === "history") scenario.protyle.options.history = {created: "old"};- if (mode === "field") (scenario.data.view as IAVTable).map.locationKeyID = "changed";- if (mode === "view") scenario.data.viewID = "changed";- if (mode === "removed") scenario.stale();- if (mode === "notebook") {- scenario.protyle.notebookId = "private";- Object.assign(scenario.context.siyuan, {notebooks: [{id: "private", encrypted: true, closed: true}]});- }- if (mode === "host") scenario.releaseHost();- if (mode === "canvas") scenario.canvas.remove();- scenario.runNativeFrames();- assert.equal(scenario.toggle.attributes.get("aria-expanded"), "false", mode);- assert.equal(scenario.requests[1].signal.aborted, true, mode);- await scenario.respond(1, [row("late")]);- assert.equal(scenario.nativeSent.some(item => item.value.state?.rows.length), false, mode);- scenario.destroy();- }-});--test("closing or timing out a pending native open destroys a late session instead of reviving it", async () => {- for (const close of ["toggle", "destroy", "timeout", "unregister"]) {- const scenario = setup(false, true);- scenario.click();- if (close === "toggle") scenario.click();- if (close === "destroy") scenario.destroy();- if (close === "timeout") scenario.runNativeTimers();- if (close === "unregister") scenario.releaseHost();- assert.equal(scenario.toggle.attributes.get("aria-expanded"), "false", close);- assert.equal(scenario.requests[1].signal.aborted, true, close);- await scenario.nativeOpen();- assert.equal(scenario.nativeSent.at(-1)?.channel, "siyuan-map-unplaced-close", close);- assert.equal(scenario.nativeSent.at(-1)?.value.sessionID, "a".repeat(48), close);- scenario.destroy();- }-});--test("native owner outside click, Escape, scroll, occlusion, theme and visibility follow the live anchor", async () => {- for (const mode of ["outside", "escape", "hidden", "occluded", "scroll", "collapsed", "transparent"]) {- const scenario = setup(false, true);- scenario.click();- await scenario.nativeOpen();- await scenario.respond(1, [row("entry")]);- scenario.setTheme("dark");- scenario.runNativeFrames();- assert.equal(scenario.nativeSent.at(-1)?.channel, "siyuan-map-unplaced-theme");- assert.equal(scenario.nativeSent.at(-1)?.value.theme.mode, "dark");- if (mode === "outside") scenario.documentEvents.get("pointerdown")({target: new ElementStub()});- if (mode === "escape") scenario.documentEvents.get("keydown")({key: "Escape", preventDefault() {}});- if (mode === "hidden") { scenario.document.hidden = true; scenario.documentEvents.get("visibilitychange")(); }- if (mode === "occluded") { scenario.document.elementFromPoint = () => new ElementStub(); scenario.runNativeFrames(); }- if (mode === "scroll") {- scenario.toggle.getBoundingClientRect = () => ({left: 1, top: 900, right: 25, bottom: 924, width: 24, height: 24});- scenario.scopeEvents.get("scroll")();- }- if (mode === "collapsed" || mode === "transparent") {- const previous = scenario.scope.getComputedStyle;- scenario.scope.getComputedStyle = () => ({...previous(),- visibility: mode === "collapsed" ? "collapse" : "visible", opacity: mode === "transparent" ? "0" : "1"});- scenario.runNativeFrames();- }- assert.equal(scenario.toggle.attributes.get("aria-expanded"), "false", mode);- if (mode === "escape") assert.equal(scenario.toggle.focused, true);- scenario.destroy();- }-});--test("mobile preserves its shared DOM menu even when a native host registration exists", () => {- const scenario = setup(true, true);- scenario.click();- assert.equal(scenario.nativeOpens.length, 0);- assert.equal(scenario.menus.length, 1);- scenario.destroy();-});--test("a theme update crossed with a main-accepted typing action keeps the same data revision and resumes search", async () => {- const scenario = setup(false, true);- scenario.click();- await scenario.nativeOpen();- await scenario.respond(1, [row("first")]);- const acceptedRevision = scenario.nativeState().revision;- scenario.setTheme("dark");- scenario.runNativeFrames();- scenario.nativeAction("editing", {revision: acceptedRevision});- scenario.nativeAction("search", {revision: acceptedRevision, query: "after theme", page: 1});- assert.equal(scenario.requests[2].payload.search, "after theme");- await scenario.respond(2, [row("after-theme")]);- scenario.nativeAction("select", {id: "after-theme"});- assert.equal(scenario.opens[0].row.id, "after-theme");- scenario.destroy();-});--test("native open failures expose a fixed retry message and closed-before-open replies cannot revive a dead session", async () => {- for (const mode of ["invalid", "timeout", "early-close", "closed", "resource"]) {- const scenario = setup(false, true);- scenario.click();- if (mode === "invalid") { scenario.nativeOpens[0].resolve(undefined); await flush(); }- if (mode === "timeout") scenario.runNativeTimers();- if (mode === "early-close") {- scenario.nativeReply({type: "closed", reason: "load-failed", restore: false});- await scenario.nativeOpen();- }- if (mode === "closed" || mode === "resource") {- await scenario.nativeOpen();- scenario.nativeReply({type: "closed", reason: mode === "resource" ? "resource-failed" : "setup-failed", restore: false});- }- assert.equal(scenario.toggle.attributes.get("aria-expanded"), "false", mode);- assert.equal(scenario.requests[1].signal.aborted, true, mode);- assert.deepEqual(scenario.messages, ["mapUnplaced: retry"], mode);- scenario.destroy();- }- const ordinary = setup(false, true);- ordinary.click();- await ordinary.nativeOpen();- ordinary.nativeReply({type: "closed", reason: "outside", restore: false});- assert.deepEqual(ordinary.messages, []);- ordinary.destroy();-});--test("an API response crossed with main-accepted editing cannot strand the next search on an obsolete revision", async () => {- const scenario = setup(false, true);- scenario.click();- await scenario.nativeOpen();- const mainRevision = scenario.nativeState().revision;- await scenario.respond(1, [row("arrived-before-editing-reply")]);- assert.ok(scenario.nativeState().revision > mainRevision);- scenario.nativeAction("editing", {revision: mainRevision});- scenario.nativeAction("search", {revision: mainRevision, query: "next query", page: 1});- assert.equal(scenario.requests[2].payload.search, "next query");- await scenario.respond(2, [row("next-query")]);- scenario.nativeReply({type: "action", action: "editing", revision: mainRevision, requestID: 1});- scenario.nativeAction("select", {id: "next-query", revision: mainRevision});- assert.equal(scenario.opens.length, 0, "selection still requires the exact current data revision");- scenario.nativeAction("select", {id: "next-query"});- assert.equal(scenario.opens[0].row.id, "next-query");- scenario.destroy();-});--test("native opening follows anchor movement and theme changes that occur before the open reply", async () => {- const scenario = setup(false, true);- scenario.click();- scenario.toggle.getBoundingClientRect = () => ({left: 600, top: 100, right: 624, bottom: 124, width: 24, height: 24});- scenario.setTheme("dark");- scenario.runNativeFrames();- await scenario.nativeOpen();- const anchor = [...scenario.nativeSent].reverse().find(item => item.channel === "siyuan-map-unplaced-anchor");- assert.equal(JSON.stringify(anchor.value.anchor), JSON.stringify({x: 600, y: 100, width: 24, height: 24}));- const theme = [...scenario.nativeSent].reverse().find(item => item.channel === "siyuan-map-unplaced-theme");- assert.equal(theme.value.theme.mode, "dark");- scenario.destroy();-});diff --git a/app/src/protyle/render/av/map/unplaced.ts b/app/src/protyle/render/av/map/unplaced.tsindex c2b46df59a..5283d2108b 100644--- a/app/src/protyle/render/av/map/unplaced.ts+++ b/app/src/protyle/render/av/map/unplaced.ts@@ -1,6 +1,5 @@import type {AVTableRow} from "../../../../types/api";import {Constants} from "../../../../constants";-import {showMessage} from "../../../../dialog/message";import {Menu} from "../../../../plugin/Menu";import {escapeAttr, escapeHtml} from "../../../../util/escape";import {fetchSyncPost} from "../../../../util/fetch";@@ -9,9 +8,6 @@ import {validateAVLocation} from "../locationValue";import {openMapRecord} from "./openRecord";import {canEditMapSettings} from "./settings";import {getMapSettings} from "./state";-import {registerMapUnplacedMenu} from "./unplacedMenu";-import {DesktopMapUnplacedHandle, DesktopMapUnplacedState, openDesktopMapUnplaced} from "./desktopUnplaced";-import {isAVMapIdentifier} from "./protocol";const PAGE_SIZE = 50;@@ -62,9 +58,6 @@ export const bindMapUnplaced = (options: {let loading = false;let elements: HTMLElement[] = [];let count: HTMLElement;- let releaseMenu: () => void;- let native: DesktopMapUnplacedHandle;- let nativeGeneration = 0;const updateCount = (value: number) => {toggle.classList.toggle("fn__none", value === 0);@@ -168,111 +161,21 @@ export const bindMapUnplaced = (options: {if (request === controller) loading = false;}};- const openNative = (canvas: HTMLElement) => {- const labels = window.siyuan.languages;- let members = new Map<string, IAVRow>();- let state: DesktopMapUnplacedState = {requestID: 0, query: "", rows: [], total: 0, page: 1,- loading: true, error: false, labels: {title: labels.mapUnplaced, search: labels.searchPlaceholder,- empty: labels.empty, loading: labels.loading, more: labels.next, previous: labels.previous,- retry: labels.retry, close: labels.close}};- const loadPage = async (requestID: number, query: string, nextPage: number) => {- request?.abort();- const controller = new AbortController();- request = controller;- const generation = ++nativeGeneration;- members.clear();- state = {...state, requestID, query, page: nextPage, rows: [], loading: true, error: false};- native.update(state);- try {- const response = await fetchSyncPost("/api/av/getAttributeViewMapUnplaced", {- ...context, search: query.trim(), page: nextPage, pageSize: PAGE_SIZE,- }, undefined, false, controller.signal);- if (controller.signal.aborted || generation !== nativeGeneration || !native) return;- if (!available()) { native.close(); return; }- if (response.code !== 0 || !response.data || !Array.isArray(response.data.rows) ||- response.data.rows.length > PAGE_SIZE || !Number.isSafeInteger(response.data.total) || response.data.total < 0) {- throw new Error("Invalid unplaced page");- }- const nextMembers = new Map<string, IAVRow>();- response.data.rows.forEach(source => {- if (!source || !isAVMapIdentifier(source.id) || nextMembers.has(source.id)) return;- const row = toMapUnplacedRow(source, locationKeyID);- if (row) nextMembers.set(row.id, row);- });- members = nextMembers;- state = {...state, rows: Array.from(members.values(), row => ({id: row.id,- title: (row.cells[0].value.block.content || labels.untitled).slice(0, 2048)})),- total: response.data.total, loading: false};- if (!query.trim()) {- countRequest.abort();- updateCount(state.total);- }- native.update(state);- } catch {- if (controller.signal.aborted || generation !== nativeGeneration || !native) return;- if (!available()) { native.close(); return; }- members.clear();- state = {...state, rows: [], loading: false, error: true};- native.update(state);- }- };- native = openDesktopMapUnplaced(canvas, toggle, state, action => {- if (!native) return;- if (!available()) { native.close(); return; }- if (action.action === "select") {- const row = !state.loading && !state.error && action.requestID === state.requestID ? members.get(action.id) : undefined;- native.close();- if (row && available()) {- toggle.focus();- void openMapRecord(protyle, blockElement, row);- }- return;- }- request?.abort();- nativeGeneration++;- members.clear();- if (action.action === "editing") {- state = {...state, rows: [], loading: true};- return;- }- void loadPage(action.requestID, action.query, action.page);- }, failed => {- nativeGeneration++;- request?.abort();- members.clear();- native = undefined;- toggle.setAttribute("aria-expanded", "false");- if (failed && available()) showMessage(escapeHtml(`${labels.mapUnplaced}: ${labels.retry}`), 5000, "error");- }, available);- if (!native) return false;- toggle.setAttribute("aria-expanded", "true");- void loadPage(0, "", 1);- return true;- };toggle.addEventListener("click", event => {event.preventDefault();if (!available()) return;- if (native) {- native.close();- return;- }if (menu) {menu.close();return;}- const canvas = root.querySelector<HTMLElement>(".av__map-canvas");- if (!isMobile() && canvas && openNative(canvas)) return;menu = new Menu(undefined, () => {clearTimeout(searchTimer);request?.abort();- releaseMenu?.();- releaseMenu = undefined;menu.element.classList.remove("av__map-unplaced-menu");menu = undefined;toggle.setAttribute("aria-expanded", "false");});menu.element.classList.add("av__map-unplaced-menu");- if (!isMobile() && canvas) releaseMenu = registerMapUnplacedMenu(menu.element, canvas);rows = [];page = 0;total = 0;@@ -310,6 +213,5 @@ export const bindMapUnplaced = (options: {request?.abort();clearTimeout(searchTimer);menu?.close();- native?.close();};};diff --git a/app/src/protyle/render/av/map/unplacedMenu.ts b/app/src/protyle/render/av/map/unplacedMenu.tsdeleted file mode 100644index 8420762b63..0000000000--- a/app/src/protyle/render/av/map/unplacedMenu.ts+++ /dev/null@@ -1,13 +0,0 @@-const owners = new WeakMap<HTMLElement, {container: HTMLElement}>();--export const registerMapUnplacedMenu = (menu: HTMLElement, container: HTMLElement) => {- const owner = {container};- owners.set(menu, owner);- return () => {- // 共用菜单被新实例接管后,旧实例的清理不能移除新归属。- if (owners.get(menu) === owner) owners.delete(menu);- };-};--export const isMapUnplacedMenu = (menu: HTMLElement, container: HTMLElement) =>- owners.get(menu)?.container === container;diff --git a/app/tests/fixtures/map-unplaced-overlay/README.md b/app/tests/fixtures/map-unplaced-overlay/README.mddeleted file mode 100644index 758c541df8..0000000000--- a/app/tests/fixtures/map-unplaced-overlay/README.md+++ /dev/null@@ -1,44 +0,0 @@-# 未定位菜单可信 overlay 验证入口--本目录提供合成记录和合成地图的独立验证窗口。菜单 manager、policy、preload、HTML、JS 和 CSS 的唯一实现位于 `app/electron/mapUnplaced/`,真实地图与本入口直接复用,不保留两份菜单实现。合成入口不会读取真实笔记、连接内核或加载 OpenFreeMap,不能替代生产 OFM 验收。--## 可运行入口--在 `app/` 目录运行:--```sh-node --import tsx --test tests/mapUnplacedOverlay.test.js tests/mapUnplacedOverlayStartup.test.js tests/mapUnplacedOverlayBoundary.test.js electron/mapHostManager.test.js-node node_modules/electron/cli.js tests/fixtures/map-unplaced-overlay/harness.cjs-```--第一条命令收集 Node 回归和真实 Electron 边界测试。Linux 缺少 DISPLAY/WAYLAND_DISPLAY 时,真实 Electron 测试明确跳过;不能添加 `--no-sandbox` 或安全绕过参数。第二条命令需要桌面,打开可手动操作的独立窗口。两种入口均在 app ready 前设置独立临时 userData,不使用已有用户 profile。手动入口在退出及启动失败时尽力清理自己创建的临时目录;自动测试管理自己显式传入的 profile。--合成入口在内存编译已有 menu/text-field 共享 SCSS,不生成生产构建文件。生产 webpack.map 输出 `stage/build/map/unplaced-controls.css`,主进程只从本地读取该文件;运行已打包应用不依赖 Sass。其余资源随 `electron/mapUnplaced/` 打包。正式接线生效需要开发者更新前端及地图共享样式构建产物,并完整重启 Electron;本改动不要求重新编译内核。--手动入口启动时输出 `Map overlay prototype starting...`,窗口页面加载完成后输出 `Map overlay prototype window ready.`,失败时输出固定提示。`harness.cjs` 是专用启动入口,`harnessSupport.cjs` 可导入且没有启动副作用。启动回归使用 Electron 相同的动态 `import()` 语义;Node 模式会明确提示检查 `ELECTRON_RUN_AS_NODE`,不会自动改写该环境变量。--## 生产安全边界--- `mapHostManager` 的真实 `getHost` 同时验证 owner WebContents、捕获的主 frame、注册窗口、地图 instanceID、初始化状态和内核 origin。只有已 ready 且可见的存活地图允许打开;后续菜单动作继续验证同一 host,owner/frame 导航和地图销毁关闭菜单-- 每个窗口至多一个菜单。新增地图后只把本窗口已有菜单提升到最上层,不重排地图。所有现有和后续地图的原生 mouseDown 都关闭本窗口菜单,不阻止事件或抢回焦点;窗口 blur 关闭菜单但保持地图绘制-- 每次打开建立新的随机内存 session,不复用 owner 或 OFM session。只允许固定 HTTPS origin 上四个精确本地资源的 GET/HEAD;禁止其他网络、file、导航、子 frame、worker、WebSocket、下载、认证、设备和权限。主文档只允许一次-- 菜单启用 sandbox、contextIsolation、webSecurity,禁用 Node、webview、不安全内容和开发者工具。CSP 不含 unsafe-inline/unsafe-eval,不允许图片、字体、媒体、表单或任意连接;退出后保留拒绝路由并清理 session-- owner 只发送 `{id,title}` 文本条目、计数、页码、加载状态、固定语言标签与主题配置。最多保留当前页 50 条,翻页替换;上一页、下一页和原页重试可访问全部结果,没有 500 条或 20 页截断。标题仅通过 textContent 显示,不接受 HTML、URL 或任意 CSS-- 每个状态必须同时匹配主进程签发的 requestID、query、page 和单调递增 revision。编辑及中文组合开始立刻撤销旧选择集合。选择必须是最新页成员;主进程仅发送一次终止 select 消息,owner 校验 session 和权限、取回私有行对象后才清理状态-- 主题经独立受限 IPC 更新,仅更改浅色/深色和 12–32 整数字号,不推进数据 revision、不恢复选择成员。编辑和主题并行时不会使有效用户动作过期;静态 CSS 枚举不允许任意样式-- 查询、AbortController、最终权限复核和真实行对象保留在可信 owner。OFM renderer 不接收标题、查询或菜单数据-- 锚点是 owner CSS viewport 内与可见滚动容器裁剪后的矩形;实际缩放和窗口 contentBounds 由主进程读取。完全裁掉时关闭,更新 bounds 去重。Esc、选择、显式关闭恢复 owner 焦点,外部点击和窗口失焦不抢焦点-- 菜单可见时地图继续绘制;主进程仅撤销旧版权点击手势,并暂时不给该窗口地图报告完整可见 viewport,避免菜单遮挡仍累计版权展示时间。关闭后恢复 viewport,不隐藏地图或重置相机--## 证据范围与实际验收--Node 回归覆盖真实生产 manager 的 owner/frame/instance 绑定、跨页成员校验、超过 500 条和 20 页的遍历、请求乱序、权限撤销、清理、同窗口菜单排序、新地图外部点击、版权可见计时和地图可见性保持。preload/menu 脚本也在受控 IPC/DOM 下验证。合成 DOM 不能证明浏览器布局、真实中文输入法、CSP 执行或原生合成无闪烁。--真实 Electron 测试使用同一生产菜单实现,验证文本渲染、无 Node/网络权限、主题、分页、Esc、焦点、外部点击、缩放和清理。没有显示环境时必须报告跳过。生产环境仍需人工检查:--1. 实际 OFM 上开关、搜索、分页、窗口切换、滚动和缩放,确认地图无闪烁、相机不跳动、菜单不被新地图盖住-2. 真实中文输入法组合、组合期间 Esc、键盘方向键、长标题、较大字号、不同窗口尺寸和跨平台焦点-3. 实际查询分页、只读权限、锁定加密笔记本、位置字段或视图切换、请求中关闭、快速连续开关及迟到回复-4. 多张地图同时存在、新建地图、关闭所属地图和窗口导航,确认没有残留原生视图、点击层或私有条目--浏览器和移动端继续使用现有 DOM Menu;本入口及 Electron 接线不替换这些平台的行为。diff --git a/app/tests/fixtures/map-unplaced-overlay/harness.cjs b/app/tests/fixtures/map-unplaced-overlay/harness.cjsdeleted file mode 100644index 14fc69330a..0000000000--- a/app/tests/fixtures/map-unplaced-overlay/harness.cjs+++ /dev/null@@ -1,33 +0,0 @@-// Electron's default app imports this entry as a module; require.main is not this file.-// Reusable tests import harnessSupport.cjs instead of this explicit manual entry.-const {app, BrowserWindow} = require("electron");-const {createHarness, createTemporaryProfile} = require("./harnessSupport.cjs");--if (!app || !BrowserWindow) {- console.error("Map overlay prototype requires Electron GUI mode; check ELECTRON_RUN_AS_NODE.");- process.exitCode = 1;-} else {- let temporary;- const fail = () => {- console.error("Map overlay prototype startup failed.");- try {- for (const win of BrowserWindow.getAllWindows()) {- if (!win.isDestroyed()) win.destroy();- }- } finally {- temporary?.cleanup();- app.exit(1);- }- };- try {- console.info("Map overlay prototype starting...");- temporary = createTemporaryProfile();- app.once("will-quit", temporary.cleanup);- app.once("quit", temporary.cleanup);- void createHarness({profile: temporary.profile}).then(() => {- console.info("Map overlay prototype window ready.");- }).catch(fail);- } catch (_error) {- fail();- }-}diff --git a/app/tests/fixtures/map-unplaced-overlay/harnessSupport.cjs b/app/tests/fixtures/map-unplaced-overlay/harnessSupport.cjsdeleted file mode 100644index 14014245c4..0000000000--- a/app/tests/fixtures/map-unplaced-overlay/harnessSupport.cjs+++ /dev/null@@ -1,72 +0,0 @@-const path = require("node:path");-const fs = require("node:fs");-const os = require("node:os");-const {pathToFileURL} = require("node:url");-const {createManager} = require("../../../electron/mapUnplaced/manager");-const createTemporaryProfile = () => {- const profile = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-unplaced-manual-"));- return {profile, cleanup() {- // 只清理本次入口自己生成的临时目录,不删除调用者传入的 profile。- if (path.dirname(path.resolve(profile)) !== path.resolve(os.tmpdir()) ||- !path.basename(profile).startsWith("siyuan-unplaced-manual-")) return;- try { fs.rmSync(profile, {recursive: true, force: true, maxRetries: 3, retryDelay: 100}); }- catch (_error) { /* 系统文件锁尚未释放时,在退出事件中再次清理。 */ }- }};-};-const createHarness = async ({profile, automate = false} = {}) => {- if (typeof profile !== "string" || !path.isAbsolute(profile)) throw new Error("An explicit isolated fixture profile is required");- const {app, BrowserWindow, WebContentsView, ipcMain, session} = require("electron");- const {hasUnsafeMapSwitches} = require("../../../electron/mapHostPolicy");- if (hasUnsafeMapSwitches(app.commandLine)) throw new Error("Unsafe process switches are not supported by this fixture");- app.setPath("userData", profile);- await app.whenReady();- // 样式只编译已有本地共享控件;该入口不生成或修改生产构建文件。- const sass = require("sass");- const component = path.resolve(__dirname, "../../../src/assets/scss/component");- const controls = sass.compileString('@use "../util/reset"; @use "menu"; @use "text-field";', {loadPaths: [component], logger: sass.Logger.silent}).css;- const ownerURL = pathToFileURL(path.join(__dirname, "owner.html")).href;- const win = new BrowserWindow({width: 980, height: 760, useContentSize: true, show: true,- webPreferences: {preload: path.join(__dirname, "owner-preload.cjs"), nodeIntegration: false,- contextIsolation: true, sandbox: true, webSecurity: true, webviewTag: false}});- const owner = win.webContents;- const map = new WebContentsView({webPreferences: {nodeIntegration: false, contextIsolation: true, sandbox: true,- webSecurity: true, webviewTag: false, partition: "unplaced-fixture-synthetic-map"}});- const mapVisible = [];- const setVisible = map.setVisible.bind(map);- map.setVisible = value => { mapVisible.push(value); setVisible(value); };- win.contentView.addChildView(map);- map.setBounds({x: 30, y: 380, width: 860, height: 250});- map.setVisible(true);- await map.webContents.loadURL("data:text/html," + encodeURIComponent('<!doctype html><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; style-src \'unsafe-inline\'"><body style="background:#cbd7df;font:24px system-ui;padding:30px">Synthetic map placeholder. No OFM or private data.</body>'));- let allowed = true;- const events = [];- const reply = value => { events.push(value); if (!owner.isDestroyed()) owner.send("unplaced-fixture-owner-event", value); };- const manager = createManager({ipcMain, session, WebContentsView, owner, win, ownerURL,- outsideContents: [map.webContents], assets: {controls}, mayUse: () => allowed,- onAction: reply, onClose: value => reply({type: "closed", ...value})});- const prefix = "unplaced-fixture-owner-";- const handlers = [];- ipcMain.handle(prefix + "open", (event, value) => manager.open(event, value));- for (const [name, fn] of [["update", manager.update], ["anchor", manager.setAnchor], ["theme", manager.setTheme], ["close", manager.close]]) {- ipcMain.on(prefix + name, fn); handlers.push([prefix + name, fn]);- }- const trusted = event => event.sender === owner && event.senderFrame === owner.mainFrame && owner.mainFrame.url === ownerURL;- const zoom = event => { if (trusted(event)) owner.setZoomFactor(owner.getZoomFactor() === 1 ? 1.25 : 1); };- const permission = event => { if (trusted(event)) { allowed = !allowed; if (!allowed) manager.revoke(); } };- ipcMain.on(prefix + "zoom", zoom); handlers.push([prefix + "zoom", zoom]);- ipcMain.on(prefix + "permission", permission); handlers.push([prefix + "permission", permission]);- let cleaned = false;- const destroy = () => {- if (cleaned) return;- cleaned = true;- manager.destroy();- ipcMain.removeHandler(prefix + "open");- handlers.forEach(([channel, fn]) => ipcMain.removeListener(channel, fn));- if (!map.webContents.isDestroyed()) map.webContents.close({waitForBeforeUnload: false});- if (!win.isDestroyed()) win.destroy();- };- win.on("closed", () => { destroy(); if (!automate) app.quit(); });- await win.loadURL(ownerURL);- return {win, owner, manager, map, mapVisible, events, destroy};-};-module.exports = {createHarness, createTemporaryProfile};diff --git a/app/tests/fixtures/map-unplaced-overlay/owner-preload.cjs b/app/tests/fixtures/map-unplaced-overlay/owner-preload.cjsdeleted file mode 100644index 9257e2a749..0000000000--- a/app/tests/fixtures/map-unplaced-overlay/owner-preload.cjs+++ /dev/null@@ -1,14 +0,0 @@-const {contextBridge, ipcRenderer} = require("electron");-const PREFIX = "unplaced-fixture-owner-";-contextBridge.exposeInMainWorld("fixtureOwner", Object.freeze({- open(value) { return ipcRenderer.invoke(PREFIX + "open", value); },- update(value) { ipcRenderer.send(PREFIX + "update", value); },- anchor(value) { ipcRenderer.send(PREFIX + "anchor", value); },- theme(value) { ipcRenderer.send(PREFIX + "theme", value); },- close(value) { ipcRenderer.send(PREFIX + "close", value); },- zoom() { ipcRenderer.send(PREFIX + "zoom"); },- permission() { ipcRenderer.send(PREFIX + "permission"); },- subscribe(callback) {- if (typeof callback === "function") ipcRenderer.on(PREFIX + "event", (_event, value) => callback(value));- },-}));diff --git a/app/tests/fixtures/map-unplaced-overlay/owner.css b/app/tests/fixtures/map-unplaced-overlay/owner.cssdeleted file mode 100644index b1dde1aeda..0000000000--- a/app/tests/fixtures/map-unplaced-overlay/owner.css+++ /dev/null@@ -1,6 +0,0 @@-body { margin: 20px; font: 16px system-ui, sans-serif; }-button { margin: 4px; padding: 8px; }-#scroll { height: 220px; overflow: auto; position: relative; }-#space { height: 600px; }-#open { margin-left: 240px; }-#result { position: fixed; bottom: 12px; }diff --git a/app/tests/fixtures/map-unplaced-overlay/owner.html b/app/tests/fixtures/map-unplaced-overlay/owner.htmldeleted file mode 100644index 557ca851df..0000000000--- a/app/tests/fixtures/map-unplaced-overlay/owner.html+++ /dev/null@@ -1,11 +0,0 @@-<!doctype html>-<html lang="zh-CN"><head><meta charset="utf-8">-<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'">-<link rel="stylesheet" href="owner.css"><script defer src="owner.js"></script>-<title>Unplaced overlay fixture</title></head><body>-<h1>未定位菜单独立原型</h1>-<p>下方仅为 synthetic 地图占位视图。全部记录是合成数据,没有 OFM、内核或真实笔记连接。</p>-<div id="actions"><button id="theme">切换主题</button><button id="zoom">切换缩放</button><button id="permission">切换权限</button></div>-<div id="scroll"><div id="space"><button id="open">未定位记录</button></div></div>-<p id="result" role="status"></p>-</body></html>diff --git a/app/tests/fixtures/map-unplaced-overlay/owner.js b/app/tests/fixtures/map-unplaced-overlay/owner.jsdeleted file mode 100644index 7a119d8c7f..0000000000--- a/app/tests/fixtures/map-unplaced-overlay/owner.js+++ /dev/null@@ -1,87 +0,0 @@-(() => {- const bridge = window.fixtureOwner;- const toggle = document.getElementById("open");- const result = document.getElementById("result");- const records = Array.from({length: 123}, (_, index) => ({id: "row-" + index,- title: index === 0 ? "PRIVATE_FIXTURE <img src=x onerror=alert(1)>" : "合成记录 " + index}));- const labels = {title: "未定位记录", search: "搜索", empty: "没有记录", loading: "加载中...", more: "下一页", previous: "上一页", retry: "重试", close: "关闭"};- let sessionID, revision = 0, requestID = 0, page = 1, query = "", timer, generation = 0, opening = false;- let theme = {mode: "light", fontSize: 16};- const anchor = () => {- const rect = toggle.getBoundingClientRect();- const viewport = document.getElementById("scroll").getBoundingClientRect();- const x = Math.max(0, rect.left, viewport.left), y = Math.max(0, rect.top, viewport.top);- const right = Math.min(window.innerWidth, rect.right, viewport.right);- const bottom = Math.min(window.innerHeight, rect.bottom, viewport.bottom);- if (right <= x || bottom <= y) return;- return {x, y, width: right - x, height: bottom - y};- };- const state = (loading = false) => {- const filtered = records.filter(row => row.title.includes(query));- return {revision: ++revision, requestID, query, page, total: filtered.length,- rows: loading ? [] : filtered.slice((page - 1) * 50, page * 50), loading, error: false, theme, labels};- };- const update = loading => { if (sessionID) bridge.update({sessionID, state: state(loading)}); };- const geometry = () => {- if (!sessionID) return;- const next = anchor();- if (next) bridge.anchor({sessionID, anchor: next});- else bridge.close({sessionID, reason: "anchor-hidden"});- };- toggle.addEventListener("click", async () => {- if (opening) return;- if (sessionID) { bridge.close({sessionID, reason: "button"}); return; }- const position = anchor();- if (!position) return;- opening = true;- requestID = 0;- page = 1;- query = "";- try { sessionID = await bridge.open({state: state(), anchor: position}); }- finally { opening = false; }- toggle.setAttribute("aria-expanded", String(!!sessionID));- });- bridge.subscribe(message => {- if (message.type === "closed") {- if (message.sessionID !== sessionID) return;- sessionID = undefined;- clearTimeout(timer);- generation++;- toggle.setAttribute("aria-expanded", "false");- if (message.restore) toggle.focus();- result.textContent = "关闭:" + message.reason;- return;- }- if (message.type === "select") {- if (message.sessionID !== sessionID) return;- sessionID = undefined;- generation++;- clearTimeout(timer);- toggle.setAttribute("aria-expanded", "false");- toggle.focus();- result.textContent = "已选择合成记录:" + message.id;- return;- }- if (message.sessionID !== sessionID) return;- clearTimeout(timer);- const current = ++generation;- requestID = message.requestID;- if (message.type === "editing") return;- query = message.query;- page = message.page;- update(true);- timer = setTimeout(() => { if (current === generation && sessionID === message.sessionID) update(false); }, 150);- });- document.getElementById("theme").addEventListener("click", () => {- theme = {mode: theme.mode === "light" ? "dark" : "light", fontSize: theme.fontSize === 16 ? 24 : 16};- if (sessionID) bridge.theme({sessionID, theme});- });- document.getElementById("zoom").addEventListener("click", () => { bridge.zoom(); setTimeout(geometry, 50); });- document.getElementById("permission").addEventListener("click", () => bridge.permission());- window.addEventListener("scroll", geometry, true);- document.addEventListener("pointerdown", event => {- if (sessionID && !toggle.contains(event.target)) bridge.close({sessionID, reason: "outside"});- }, true);- window.addEventListener("resize", geometry);- window.addEventListener("pagehide", () => { clearTimeout(timer); generation++; });-})();diff --git a/app/tests/fixtures/map-webview-boundary/README.md b/app/tests/fixtures/map-webview-boundary/README.mdindex 760e00f863..09043b6403 100644--- a/app/tests/fixtures/map-webview-boundary/README.md+++ b/app/tests/fixtures/map-webview-boundary/README.md@@ -17,6 +17,17 @@ node node_modules/electron/cli.js tests/fixtures/map-webview-boundary/harness.cjnode node_modules/electron/cli.js tests/fixtures/map-webview-boundary/harness.cjs --synthetic --verify```+远程内核宿主边界使用本机测试服务器代替真实内核,但保留远程主窗口的 `webSecurity=true`、正式 `createRemoteDocumentContentSecurityPolicy` 和 `shouldBlockRemoteFrameNavigation` 策略,以及独立 owner 会话;不会删除 CSP。地图授权守卫在 owner 首次加载前注册,先验证无分区、普通分区、持久分区的未授权 webview,以及 iframe/object 均被拒绝,再创建合法地图,完成同样的就绪、隔离、圆角像素、菜单覆盖和输入断言。++```sh+node node_modules/electron/cli.js tests/fixtures/map-webview-boundary/harness.cjs --remote --synthetic --verify+node node_modules/electron/cli.js tests/fixtures/map-webview-boundary/harness.cjs --remote --real+```++如果正式远程 CSP 或导航策略拦住合法地图,远程测试必须失败;不要为使测试通过而修改 CSP、关闭 webSecurity 或移除子框架拦截。真实模式仍需已有地图产物与 OpenFreeMap 网络,合成模式不能证明真实瓦片或 WebGL 可用。++终端会在远程宿主安全断言通过后输出固定的 `Remote map owner policy: PASS.`;启动或验证失败会输出 `Remote map webview verification: FAIL.` 及固定失败阶段,不输出原始异常或私有地址。自动验证还会在合法地图就绪后再次检查默认拒绝仍生效。+自动验证覆盖 guest Node/IPC 与 owner DOM 不可访问、独立会话不受默认会话删除 CSP 影响、内核 API/非白名单/worker 请求拒绝、导航及伪造 guest 拒绝、普通 DOM 菜单合成像素及真实输入、Esc、地图内点击关闭菜单且同次点击仍传给地图、滚动、地图实例/视野/visibility 稳定。合成适配器验证不等于真实 OFM/WebGL 出图验证。手动打开普通菜单,输入中文并使用输入法候选,按 Esc,反复开关菜单,滚动地图所在容器。地图应持续可见,不重建、不重置视野;菜单应覆盖地图并正确接受输入。输入法与平台合成仍需在目标桌面实际确认。@@ -27,4 +38,4 @@ node --test tests/mapWebviewStartup.test.js tests/mapWebviewBoundary.test.js没有 DISPLAY/WAYLAND_DISPLAY 的 Linux 环境会明确跳过真实 Electron 验证,单元测试通过不能替代运行验证。禁止使用 `--no-sandbox`、`--disable-web-security` 或其他安全降级参数。开发环境实装 Electron 44.5.1,package.json 声明 44.7.0;两个版本的真实桌面验证结果需要分别记录。-本地 Electron 使用网页内 webview 承载,普通菜单直接覆盖地图;远程内核保持现有独立宿主路径。此入口用于持续验证同一个正式宿主及网络隔离边界。+本地和远程 Electron 均使用网页内的受控地图 webview,普通菜单直接覆盖地图;远程仅放行主进程登记的地图预约,其余 webview 仍默认拒绝。此入口用于持续验证同一个正式宿主及网络隔离边界。diff --git a/app/tests/fixtures/map-webview-boundary/harness.cjs b/app/tests/fixtures/map-webview-boundary/harness.cjsindex d4f2e99336..3f6b9334f7 100644--- a/app/tests/fixtures/map-webview-boundary/harness.cjs+++ b/app/tests/fixtures/map-webview-boundary/harness.cjs@@ -8,11 +8,13 @@ if (!app || !BrowserWindow) {process.exitCode = 1;} else {let temporary;+ let remoteRequested = false;const fail = error => {console.error("Map webview prototype startup failed.");+ if (remoteRequested) console.error("Remote map webview verification: FAIL.");const codes = ["attachPreferenceMismatch", "hostAttachFailed", "hostDocumentLoadFailed", "hostDocumentMismatch","hostRendererGone", "hostDestroyed", "hostBootstrapTimeout", "hostSDKTimeout", "documentCSPBlocked",- "isolationAssertionFailed", "isolationCheckTimeout", "fixtureSetupFailed", "ownerClosed", "sdkUnavailable", "hostUnavailable",+ "isolationAssertionFailed", "isolationCheckTimeout", "fixtureSetupFailed", "remoteOwnerPolicyFailed", "ownerClosed", "sdkUnavailable", "hostUnavailable","sdkScriptLoadFailed", "sdkGlobalMissing", "mapCreationFailed", "mapReadyTimeout", "mapUnavailable"];if (codes.includes(error?.code)) {const prefKeys = ["sandbox", "contextIsolation", "webSecurity", "nodeIntegration", "nodeIntegrationInSubFrames",@@ -34,7 +36,8 @@ if (!app || !BrowserWindow) {try {console.info("Map webview prototype starting...");const flags = new Set(process.argv.slice(2));- if ([...flags].some(flag => !["--real", "--synthetic", "--verify"].includes(flag)) ||+ remoteRequested = flags.has("--remote");+ if ([...flags].some(flag => !["--real", "--synthetic", "--verify", "--remote"].includes(flag)) ||(flags.has("--real") && flags.has("--synthetic")) || (flags.has("--verify") && !flags.has("--synthetic"))) {throw new Error("Invalid fixture mode");}@@ -42,7 +45,7 @@ if (!app || !BrowserWindow) {app.once("will-quit", temporary.cleanup);app.once("quit", temporary.cleanup);void createHarness({profile: temporary.profile, mode: flags.has("--synthetic") ? "synthetic" : "real",- automate: flags.has("--verify")}).then(async harness => {+ automate: flags.has("--verify"), ...(flags.has("--remote") && {kernelMode: "remote"})}).then(async harness => {console.info("Map webview prototype window ready.");if (flags.has("--verify")) {try { await verifyHarness(harness); }diff --git a/app/tests/fixtures/map-webview-boundary/harnessSupport.cjs b/app/tests/fixtures/map-webview-boundary/harnessSupport.cjsindex 44456c3273..fc4b091513 100644--- a/app/tests/fixtures/map-webview-boundary/harnessSupport.cjs+++ b/app/tests/fixtures/map-webview-boundary/harnessSupport.cjs@@ -6,11 +6,13 @@ const path = require("node:path");const {randomBytes} = require("node:crypto");const {createMapHostManager} = require("../../../electron/mapHostManager");const {hasUnsafeMapSwitches, mapHostFiles} = require("../../../electron/mapHostPolicy");+const {createRemoteDocumentContentSecurityPolicy, shouldBlockRemoteFrameNavigation} = require("../../../electron/remoteKernel");const appDir = path.resolve(__dirname, "../../..");const ownerPreferences = Object.freeze({nodeIntegration: true, nodeIntegrationInSubFrames: false,nodeIntegrationInWorker: false, webviewTag: true, webSecurity: false, contextIsolation: false,autoplayPolicy: "user-gesture-required"});+const remoteOwnerPreferences = Object.freeze({...ownerPreferences, webSecurity: true});const {MAP_WEBVIEW_PREFERENCES: guestPreferences, getMapWebviewPreferenceMismatch: getGuestPreferenceMismatch} =require("../../../electron/mapWebviewHost");// Electron 44 的 getLastWebPreferences 只回传此固定子集,不包含 preload 等构造参数。@@ -84,6 +86,63 @@ const waitFor = async (predicate, label, timeout = 5000) => {}};+// 远程夹具复用正式导航策略,并保留响应 CSP,不运行本地夹具的移除响应头逻辑。+const installRemoteOwnerGuards = (owner, ownerSession, evidence) => {+ const record = url => {+ try { evidence.blockedFramePaths.push(new URL(url).pathname); } catch (_error) { /* 只记录可解析的夹具路径。 */ }+ };+ owner.on("will-frame-navigate", event => {+ if (shouldBlockRemoteFrameNavigation({isMainFrame: event.isMainFrame})) {+ record(event.url);+ event.preventDefault();+ }+ });+ ownerSession.webRequest.onBeforeRequest((details, callback) => {+ const cancel = shouldBlockRemoteFrameNavigation({resourceType: details.resourceType});+ if (cancel) record(details.url);+ callback({cancel});+ });+};++const verifyRemoteOwnerRejections = async ({owner, origin, evidence}, expectedAttached = 0) => {+ const evaluate = source => owner.executeJavaScript(source);+ const before = evidence.rejectedAttachments;+ const blockedBefore = evidence.blockedFramePaths.length;+ await evaluate(`(() => {+ if (!window.remoteFixtureViolations) {+ window.remoteFixtureViolations = [];+ document.addEventListener("securitypolicyviolation", event => {+ window.remoteFixtureViolations.push({directive: event.effectiveDirective, uri: event.blockedURI});+ });+ } else window.remoteFixtureViolations.length = 0;+ for (const partition of ["", "unreserved-remote-map", "persist:unreserved-remote-map"]) {+ const view = document.createElement("webview");+ view.className = "remote-boundary-probe";+ view.setAttribute("src", ${JSON.stringify(origin + "/api/fixture-private")});+ if (partition) view.setAttribute("partition", partition);+ document.body.appendChild(view);+ }+ const frame = document.createElement("iframe");+ frame.className = "remote-boundary-probe";+ frame.src = ${JSON.stringify(origin + "/fixture-blocked-frame")};+ document.body.appendChild(frame);+ const object = document.createElement("object");+ object.className = "remote-boundary-probe";+ object.data = ${JSON.stringify(origin + "/fixture-blocked-object")};+ document.body.appendChild(object);+ })()`);+ await waitFor(() => evidence.rejectedAttachments >= before + 3, "remote ordinary and persistent webviews are denied without a matching reservation");+ for (const pathname of ["/fixture-blocked-frame", "/fixture-blocked-object"]) {+ await waitFor(async () => evidence.blockedFramePaths.slice(blockedBefore).includes(pathname) || await evaluate(+ `window.remoteFixtureViolations.some(value => value.uri === ${JSON.stringify(origin + pathname)})`),+ "remote iframe and object policy rejects " + pathname);+ }+ assert.equal(evidence.attached, expectedAttached, "an unreserved guest never attaches");+ assert.equal(evidence.privateRequests, 0);+ assert.equal(evidence.frameRequests, 0, "blocked embedded documents never reach the server");+ await evaluate('document.querySelectorAll(".remote-boundary-probe").forEach(element => element.remove())');+};+// 编译实际业务样式和可见性函数,避免夹具自行重写圆角规则或命中判断。const readMapCornerAssets = () => {const ts = require("typescript");@@ -148,34 +207,41 @@ const verifyMapCorners = async harness => {}};-const createHarness = async ({profile, mode = "real", automate = false} = {}) => {- if (typeof profile !== "string" || !path.isAbsolute(profile) || !["real", "synthetic"].includes(mode)) {+const createHarness = async ({profile, mode = "real", automate = false, kernelMode = "local"} = {}) => {+ if (typeof profile !== "string" || !path.isAbsolute(profile) || !["real", "synthetic"].includes(mode) ||+ !["local", "remote"].includes(kernelMode)) {throw new Error("An isolated profile and fixed fixture mode are required");}- const {app, BrowserWindow, WebContentsView, MessageChannelMain, ipcMain, session} = require("electron");+ const {app, BrowserWindow, MessageChannelMain, ipcMain, session} = require("electron");if (hasUnsafeMapSwitches(app.commandLine)) throw new Error("Unsafe process switches are prohibited");if (mode === "real") checkRealAssets();app.setPath("userData", profile);await app.whenReady();const syntheticFiles = mode === "synthetic" ? createSyntheticFiles() : undefined;const instanceID = randomBytes(24).toString("hex");- let win, owner, guest, manager, src, partition, startupTimer, closed = false, isolating = false;+ let win, owner, ownerSession, origin, guest, manager, src, partition, startupTimer, closed = false, isolating = false;+ let initialized = false;let resolveReady, rejectReady;const readiness = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });void readiness.catch(() => {});const evidence = {privateRequests: 0, guestNetworkRequests: 0, defaultHeaderCalls: 0,- defaultGuestHeaderCalls: 0, rejectedAttachments: 0, attached: 0, replies: [], diagnostics: []};+ defaultGuestHeaderCalls: 0, rejectedAttachments: 0, attached: 0, replies: [], diagnostics: [],+ ownerDocumentCSP: "", frameRequests: 0, blockedFramePaths: []};+ const ownerHTML = fs.readFileSync(path.join(__dirname, "owner.html"), "utf8");const server = http.createServer((request, response) => {const files = {"/stage/build/app/": ["owner.html", "text/html"],- "/fixture-owner.js": ["owner.js", "text/javascript"], "/fixture-owner.css": ["owner.css", "text/css"]};+ "/stage/fixture-owner.js": ["owner.js", "text/javascript"], "/stage/fixture-owner.css": ["owner.css", "text/css"]};const resource = files[request.url];if (!resource) {- if (request.url.startsWith("/api/")) evidence.privateRequests++;+ if (request.url.startsWith("/fixture-blocked-")) evidence.frameRequests++;+ else if (request.url.startsWith("/api/")) evidence.privateRequests++;else evidence.guestNetworkRequests++;response.writeHead(403).end();return;}- response.setHeader("Content-Security-Policy", "default-src 'none'");+ const csp = kernelMode === "remote" ? createRemoteDocumentContentSecurityPolicy(ownerHTML, origin) : "default-src 'none'";+ if (request.url === "/stage/build/app/") evidence.ownerDocumentCSP = csp;+ response.setHeader("Content-Security-Policy", csp);response.setHeader("Content-Type", resource[1]);response.end(fs.readFileSync(path.join(__dirname, resource[0])));});@@ -203,22 +269,24 @@ const createHarness = async ({profile, mode = "real", automate = false} = {}) =>ipcMain.removeListener("map-webview-fixture-state", onState);app.removeListener("web-contents-created", onCreated);if (win && !win.isDestroyed()) win.destroy();- session.defaultSession.webRequest.onHeadersReceived(null);+ if (kernelMode === "local") session.defaultSession.webRequest.onHeadersReceived(null);+ else ownerSession?.webRequest.onBeforeRequest(null);server.closeAllConnections?.();if (server.listening) await new Promise(resolve => server.close(resolve));};try {await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); });- const origin = `http://127.0.0.1:${server.address().port}`;- session.defaultSession.webRequest.onHeadersReceived((details, callback) => {+ origin = `http://127.0.0.1:${server.address().port}`;+ ownerSession = kernelMode === "remote" ? session.fromPartition("siyuan-fixture-owner-" + randomBytes(24).toString("hex"), {cache: false}) : session.defaultSession;+ if (kernelMode === "local") session.defaultSession.webRequest.onHeadersReceived((details, callback) => {evidence.defaultHeaderCalls++;if (details.url.includes("/stage/map/") || details.url.includes("/stage/build/map/")) evidence.defaultGuestHeaderCalls++;callback({responseHeaders: Object.fromEntries(Object.entries(details.responseHeaders || {}).filter(([name]) => !["content-security-policy", "x-frame-options", "access-control-allow-origin"].includes(name.toLowerCase())))});});- manager = createMapHostManager({app, ipcMain, session, BrowserWindow, WebContentsView, MessageChannelMain, appDir,- getTarget: id => owner && id === owner.id ? {mode: "local", origin} : undefined,- isInitialized: id => owner && id === owner.id,+ manager = createMapHostManager({app, ipcMain, session, BrowserWindow, MessageChannelMain, appDir,+ getTarget: id => owner && id === owner.id ? {mode: kernelMode, origin} : undefined,+ isInitialized: id => initialized && owner && id === owner.id,readFile: syntheticFiles ? async filename => {const relative = path.relative(appDir, filename).split(path.sep).join("/");if (!syntheticFiles.has(relative)) throw new Error("Unknown synthetic fixture asset");@@ -226,8 +294,11 @@ const createHarness = async ({profile, mode = "real", automate = false} = {}) =>} : undefined});app.on("web-contents-created", onCreated);ipcMain.on("map-webview-fixture-state", onState);- win = new BrowserWindow({width: 820, height: 620, useContentSize: true, show: true, webPreferences: {...ownerPreferences}});+ win = new BrowserWindow({width: 820, height: 620, useContentSize: true, show: true,+ webPreferences: {...(kernelMode === "remote" ? remoteOwnerPreferences : ownerPreferences), session: ownerSession}});owner = win.webContents;+ manager.registerOwner(owner);+ if (kernelMode === "remote") installRemoteOwnerGuards(owner, ownerSession, evidence);owner.on("will-attach-webview", event => { queueMicrotask(() => { if (event.defaultPrevented) evidence.rejectedAttachments++; }); });owner.on("did-attach-webview", () => { evidence.attached++; });win.on("closed", () => { void destroy().then(() => { if (!automate) app.quit(); }); });@@ -237,13 +308,19 @@ const createHarness = async ({profile, mode = "real", automate = false} = {}) =>rejectReady(error);}, 85000);await Promise.race([win.loadURL(origin + "/stage/build/app/"), readiness]);+ if (kernelMode === "remote") {+ try { await verifyRemoteOwnerRejections({owner, origin, evidence}); }+ catch (error) { error.code = "remoteOwnerPolicyFailed"; throw error; }+ }+ initialized = true;owner.send("map-webview-fixture-start", {instanceID, mode});await readiness;const harness = {win, owner, get guest() { return guest; }, session: guest.session, origin,- get src() { return src; }, get partition() { return partition; }, instanceID, mode, evidence, destroy};+ get src() { return src; }, get partition() { return partition; }, instanceID, mode, kernelMode, evidence, destroy};isolating = true;await verifyIsolation(harness);console.info("Map webview boundary checks passed: isolated session, opaque origin, no Node/IPC or owner DOM access, private network denied.");+ if (kernelMode === "remote") console.info("Remote map owner policy: PASS. Web security and production CSP retained; unreserved guests, iframes and objects denied.");return harness;} catch (error) {await destroy();@@ -257,7 +334,7 @@ const verifyIsolationChecks = async harness => {const {owner, guest, evidence, origin} = harness;const inspect = source => guest.executeJavaScript(source);const ownerPrefs = owner.getLastWebPreferences();- for (const [name, value] of Object.entries(ownerPreferences)) {+ for (const [name, value] of Object.entries(harness.kernelMode === "remote" ? remoteOwnerPreferences : ownerPreferences)) {if (reportedPreferenceKeys.includes(name)) assert.equal(ownerPrefs[name], value, name);}assert.equal(getGuestPreferenceMismatch(guest.getLastWebPreferences()), undefined);@@ -272,7 +349,15 @@ const verifyIsolationChecks = async harness => {openerOwner: ownerVisible(opener), evalBlocked};})()`), {origin: "null", require: "undefined", process: "undefined", ipc: "undefined", bridge: ["version"],parentOwner: false, topOwner: false, openerOwner: false, evalBlocked: true});- assert.ok(evidence.defaultHeaderCalls > 0, "the unsafe owner header-removal fixture is active");+ if (harness.kernelMode === "remote") {+ const html = fs.readFileSync(path.join(__dirname, "owner.html"), "utf8");+ assert.equal(evidence.ownerDocumentCSP, createRemoteDocumentContentSecurityPolicy(html, origin));+ assert.equal(evidence.defaultHeaderCalls, 0, "remote owner never installs the local CSP-removal hook");+ assert.equal(evidence.frameRequests, 0);+ assert.ok(evidence.rejectedAttachments >= 3, "remote default denial is active before the map reservation");+ } else {+ assert.ok(evidence.defaultHeaderCalls > 0, "the unsafe owner header-removal fixture is active");+ }assert.equal(evidence.defaultGuestHeaderCalls, 0, "guest resources bypass the owner's default session entirely");assert.equal(evidence.guestNetworkRequests, 0, "fixed local guest resources never reach the kernel server");for (const target of [origin + "/api/fixture-private", "https://example.invalid/private", "file:///fixture-private"]) {@@ -301,6 +386,7 @@ const verifyHarness = async harness => {const inspect = source => guest.executeJavaScript(source);await verifyIsolation(harness);await waitFor(() => inspect("window.mapFixture?.fits === 1 && window.mapFixture.visible.at(-1) === true"), "runtime receives points and visibility");+ if (harness.kernelMode === "remote") await verifyRemoteOwnerRejections(harness, 1);assert.equal(await inspect("window.mapFixture.locked"), true);const privateURL = origin + "/api/fixture-private";assert.deepEqual(await inspect(`new Promise(resolve => {@@ -350,6 +436,7 @@ const verifyHarness = async harness => {assert.equal(await evaluate("document.getElementById('scroll-area').scrollTop"), 80);assert.equal(guest.id, identity);// 拒绝第二个伪造 guest,不影响已准入的 guest 和独立会话。+ const rejectedBeforeForgery = evidence.rejectedAttachments;await evaluate(`(() => {const bad = document.createElement("webview");bad.setAttribute("src", ${JSON.stringify(privateURL)});@@ -358,7 +445,7 @@ const verifyHarness = async harness => {bad.setAttribute("disablewebsecurity", "");document.body.appendChild(bad);})()`);- await waitFor(() => evidence.rejectedAttachments > 0, "a forged second guest is rejected before creation");+ await waitFor(() => evidence.rejectedAttachments > rejectedBeforeForgery, "a forged second guest is rejected before creation");assert.equal(evidence.attached, 1);assert.equal(evidence.privateRequests, 0);assert.equal(guest.id, identity);@@ -378,4 +465,5 @@ const verifyHarness = async harness => {};module.exports = {createHarness, createTemporaryProfile, verifyHarness, checkRealAssets,- createSyntheticFiles, ownerPreferences, guestPreferences, verifyIsolation, readMapCornerAssets};+ createSyntheticFiles, ownerPreferences, remoteOwnerPreferences, guestPreferences, verifyIsolation, readMapCornerAssets,+ installRemoteOwnerGuards};diff --git a/app/tests/fixtures/map-webview-boundary/owner.html b/app/tests/fixtures/map-webview-boundary/owner.htmlindex ab72b6f515..e6ce2d4d7d 100644--- a/app/tests/fixtures/map-webview-boundary/owner.html+++ b/app/tests/fixtures/map-webview-boundary/owner.html@@ -3,15 +3,15 @@<head><meta charset="utf-8"><title>Map webview boundary prototype</title>- <link rel="stylesheet" href="/fixture-owner.css">- <script defer src="/fixture-owner.js"></script>+ <link rel="stylesheet" href="/stage/fixture-owner.css">+ <script defer src="/stage/fixture-owner.js"></script></head><body><header><button id="toggle-menu" type="button">Open ordinary DOM menu</button><span id="status">Preparing isolated map...</span></header>- <p>Local prototype with synthetic points. Open the menu, enter Chinese text, press Escape, and scroll.</p>+ <p>Isolated map prototype with synthetic points. Open the menu, enter Chinese text, press Escape, and scroll.</p><div id="scroll-area"><div id="map-slot"></div><div class="spacer">Scroll inside this region.</div></div><div id="owner-private-sentinel" hidden>Owner-only fixture data</div><div id="menu" class="b3-menu" hidden>diff --git a/app/tests/mapAssets.test.js b/app/tests/mapAssets.test.jsnew file mode 100644index 0000000000..cf1240df4f--- /dev/null+++ b/app/tests/mapAssets.test.js@@ -0,0 +1,23 @@+const assert = require("node:assert/strict");+const path = require("node:path");+const {test} = require("node:test");+const config = require("../webpack.map");++test("map asset plugin emits only fixed renderer resources and tracks their source dependencies", () => {+ const assets = new Map();+ const compilation = {+ fileDependencies: new Set(),+ emitAsset(name, source) { assets.set(name, source.source()); },+ hooks: {processAssets: {tap(_options, callback) { callback(); }}},+ };+ const compiler = {hooks: {thisCompilation: {tap(_name, callback) { callback(compilation); }}}};+ const options = config({}, {mode: "production"});+ options.plugins.forEach(plugin => plugin.apply(compiler));+ assert.deepEqual([...assets.keys()].sort(), ["maplibre-LICENSE.txt", "maplibre-gl-csp-worker.js", "maplibre-gl.css", "maplibre-gl.js"]);+ for (const name of ["maplibre-gl-csp.js", "maplibre-gl-csp-worker.js", "maplibre-gl.css", "LICENSE.txt"]) {+ assert.ok(compilation.fileDependencies.has(require.resolve("maplibre-gl/dist/" + name)));+ }+ assert.equal(options.target, "web");+ assert.equal(options.output.path, path.resolve(__dirname, "../stage/build/map"));+ assert.equal(options.output.clean, true);+});diff --git a/app/tests/mapHostBoundary.test.js b/app/tests/mapHostBoundary.test.jsdeleted file mode 100644index d390a12fcd..0000000000--- a/app/tests/mapHostBoundary.test.js+++ /dev/null@@ -1,212 +0,0 @@-const assert = require("node:assert/strict");-const fs = require("node:fs");-const os = require("node:os");-const path = require("node:path");--// 真实 owner、主进程、预载与原生子视图;固定 adapter 只隔离 OFM 网络和 WebGL。-const runBoundaryFixture = async (profile) => {- const {app, BrowserWindow, WebContentsView, MessageChannelMain, ipcMain, session} = require("electron");- const {createMapHostManager} = require("../electron/mapHostManager");- const http = require("node:http");- const ts = require("typescript");- app.setPath("userData", profile);- await app.whenReady();- const mapDirectory = path.join(__dirname, "../src/protyle/render/av/map");- const compile = name => ts.transpileModule(fs.readFileSync(path.join(mapDirectory, name + ".ts"), "utf8"), {- compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},- }).outputText;- const bundle = (names, extra, entry, electron = false) => {- const modules = {...Object.fromEntries(names.map(name => ["./" + name, compile(name)])), ...extra};- return `(() => {- const modules = {${Object.entries(modules).map(([name, source]) =>- `${JSON.stringify(name)}: (require, exports) => {${source}\n}`).join(",")}};- const cache = {};- const load = name => {- ${electron ? 'if (name === "electron") return require("electron");' : ""}- if (!modules[name]) throw new Error("Unknown fixture module");- if (!cache[name]) { cache[name] = {}; modules[name](load, cache[name]); }- return cache[name];- };- ${entry}- })();`;- };- let owner, manager, server;- const views = [];- let privateRequests = 0;- try {- server = http.createServer((request, response) => {- if (request.url !== "/stage/build/app/") {- if (request.url.startsWith("/api/")) privateRequests++;- response.writeHead(403).end();- return;- }- response.setHeader("Content-Type", "text/html");- response.end('<!doctype html><html><body style="margin:0"><div id="map" ' +- 'style="position:fixed;left:10px;top:20px;width:400px;height:300px"></div></body></html>');- });- await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));- const origin = `http://127.0.0.1:${server.address().port}`;- const runtime = bundle(["protocol", "loadingBudget", "bootstrap", "hostRuntime"], {- "./providersLoader": `- window.mapFixture = {fits: 0, revisions: [], destroyed: 0};- exports.prepareAVMapAssets = async () => {- await new Promise(resolve => { window.releaseFixtureBootstrap = resolve; });- return {lock() {}, destroy() { window.mapFixture.assetsDestroyed = true; }};- };- exports.loadAVMapAdapter = async (_init, _container, callbacks) => {- if (window.rejectFixtureMap) throw new Error("private-fixture-path?token=secret");- window.mapFixture.callbacks = callbacks;- return {- setPoints(points, revision) { window.mapFixture.revisions.push(revision); },- fit() { window.mapFixture.fits++; },- resize() {}, setTheme() {}, setVisible() {},- destroy() { window.mapFixture.destroyed++; }- };- };`,- }, 'load("./hostRuntime").connectAVMapRuntime(window);');- const fixtureFiles = new Map([- ["stage/map/index.html", Buffer.from("<!doctype html><html><head><script defer " +- 'src="/stage/build/map/host.js"></script></head><body style="margin:0"><div id="map"></div></body></html>')],- ["stage/build/map/host.js", Buffer.from(runtime)],- ]);- owner = new BrowserWindow({width: 800, height: 600, useContentSize: true, show: true,- webPreferences: {nodeIntegration: true, contextIsolation: false, backgroundThrottling: false}});- manager = createMapHostManager({app, ipcMain, session, BrowserWindow, MessageChannelMain,- WebContentsView: function (options) {- const view = new WebContentsView(options);- views.push(view);- return view;- },- getTarget: id => id === owner.webContents.id ? {origin, mode: "remote"} : undefined,- isInitialized: id => id === owner.webContents.id, appDir: path.join(__dirname, ".."),- readFile: async filename => {- const key = path.relative(path.join(__dirname, ".."), filename).split(path.sep).join("/");- if (!fixtureFiles.has(key)) throw new Error("Unknown fixture asset");- return fixtureFiles.get(key);- }});- await owner.loadURL(origin + "/stage/build/app/");- const evaluate = script => owner.webContents.executeJavaScript(script);- const waitFor = async (predicate, label) => {- const deadline = Date.now() + 5000;- while (!await predicate()) {- assert.ok(Date.now() < deadline, label);- await new Promise(resolve => setTimeout(resolve, 25));- }- };- await evaluate(bundle(["protocol", "loadingBudget", "unplacedMenu", "desktopGeometry", "desktopGeometryDOM", "desktopTransport"], {}, `- window.ownerFixture = {ready: 0, errors: [], links: []};- window.mapContainer = document.getElementById("map");- window.startFixtureHost = () => load("./desktopTransport").createDesktopAVMapHost(window.mapContainer, {- provider: "openfreemap", theme: "light", onMarkerClick() {},- onReady() { window.ownerFixture.ready++; },- onError(code) { window.ownerFixture.errors.push(code); },- onAttributionClick(link) { window.ownerFixture.links.push(link); }- });- window.mapHost = window.startFixtureHost();- window.mapHost.setPoints([{id: "row-1", longitude: 0, latitude: 0}], 1);- window.openFixtureMenu = () => {- const menu = document.createElement("div");- menu.className = "b3-menu";- menu.style.cssText = "position:fixed;left:250px;top:20px;width:150px;height:200px;background:white;z-index:10";- document.body.appendChild(menu);- const release = load("./unplacedMenu").registerMapUnplacedMenu(menu, window.mapContainer);- window.closeFixtureMenu = () => { release(); menu.remove(); };- };- `, true));- await waitFor(() => views.length === 1, "one native view is created");- const view = views[0], map = view.webContents;- const inspectMap = script => map.executeJavaScript(script);- await waitFor(() => inspectMap("typeof window.releaseFixtureBootstrap === 'function'"), "the real preload transfers its port");- assert.equal(view.getVisible(), false);- assert.equal(await evaluate("window.ownerFixture.ready"), 0);- assert.deepEqual(await inspectMap("({origin: window.origin, node: typeof require, bridge: window.siyuanMapDesktop.version})"),- {origin: "null", node: "undefined", bridge: 1});- await inspectMap("window.releaseFixtureBootstrap()");- await waitFor(() => evaluate("window.ownerFixture.ready === 1"), "runtime ready crosses the main process");- await waitFor(() => view.getVisible(), "the stable native map becomes visible");- const fullBounds = view.getBounds();- assert.equal(fullBounds.width, 400);- assert.deepEqual(await inspectMap("({fits: window.mapFixture.fits, revisions: window.mapFixture.revisions})"),- {fits: 1, revisions: [1]});- await evaluate("window.openFixtureMenu()");- await waitFor(() => view.getVisible() && view.getBounds().width < fullBounds.width, "an owned menu crops the real native view");- assert.equal(await inspectMap("document.getElementById('map').style.width"), "400px");- await evaluate("window.closeFixtureMenu()");- await waitFor(() => view.getVisible() && view.getBounds().width === fullBounds.width, "menu closure restores the native view");- assert.equal(await inspectMap("window.mapFixture.fits"), 1);- owner.hide();- await waitFor(() => !view.getVisible(), "hiding the actual owner hides its native child view");- owner.show();- await waitFor(() => view.getVisible(), "showing the owner restores verified native geometry");- assert.deepEqual(view.getBounds(), fullBounds);- assert.equal(await inspectMap("window.mapFixture.fits"), 1);- owner.webContents.setZoomFactor(1.25);- await waitFor(() => view.getVisible() && view.getBounds().width > fullBounds.width, "owner zoom is applied once");- assert.equal(map.getZoomFactor(), 1.25);- await evaluate("window.mapContainer.style.top = '-20px'; window.dispatchEvent(new Event('scroll'));");- await waitFor(() => view.getVisible() && view.getBounds().y < 5, "scroll updates native cropping");- assert.ok(view.getBounds().y >= 0);- assert.match(await inspectMap("document.getElementById('map').style.transform"), /translate\(/);- const privateURL = origin + "/api/map-fixture-private";- assert.equal(await inspectMap(`fetch(${JSON.stringify(privateURL)}).then(() => false, () => true)`), true);- assert.equal(await inspectMap(`new Promise(resolve => {- const source = "fetch(" + ${JSON.stringify(JSON.stringify(privateURL))} + ").then(() => postMessage(false), () => postMessage(true))";- const url = URL.createObjectURL(new Blob([source], {type: "text/javascript"}));- const worker = new Worker(url);- worker.onmessage = event => { worker.terminate(); URL.revokeObjectURL(url); resolve(event.data); };- worker.onerror = () => { worker.terminate(); URL.revokeObjectURL(url); resolve(false); };- })`), true, "the locked worker cannot connect to the owner API");- const entryURL = map.getURL();- await inspectMap(`window.location.href = ${JSON.stringify(privateURL)}`);- await new Promise(resolve => setTimeout(resolve, 100));- assert.equal(map.getURL(), entryURL);- assert.equal(privateRequests, 0);- await inspectMap("window.mapFixture.callbacks.onAttributionClick('maplibre')");- await new Promise(resolve => setTimeout(resolve, 50));- assert.deepEqual(await evaluate("window.ownerFixture"), {ready: 1, errors: [], links: []});- await evaluate("window.mapHost.destroy(); window.mapHost.destroy()");- await waitFor(() => map.isDestroyed(), "destroy closes the actual isolated renderer");- assert.equal(owner.contentView.children.includes(view), false);- await evaluate("window.mapHost = window.startFixtureHost()");- await waitFor(() => views.length === 2, "a replacement receives an independent native view");- const failedMap = views[1].webContents;- await waitFor(() => failedMap.executeJavaScript("typeof window.releaseFixtureBootstrap === 'function'"), "replacement bootstrap receives its port");- await failedMap.executeJavaScript("window.rejectFixtureMap = true; window.releaseFixtureBootstrap()");- await waitFor(() => failedMap.isDestroyed(), "a failed adapter closes its real native renderer");- assert.deepEqual(await evaluate("window.ownerFixture.errors"), ["sdkUnavailable"]);- assert.equal((await evaluate("JSON.stringify(window.ownerFixture)")).includes("secret"), false);- } finally {- manager?.destroyAll();- if (owner && !owner.isDestroyed()) owner.destroy();- if (server) {- server.closeAllConnections?.();- await new Promise(resolve => server.close(resolve));- }- }-};--if (process.versions.electron && process.type === "browser") {- const {app} = require("electron");- runBoundaryFixture(process.argv[2]).then(() => app.exit(0), error => {- console.error(error);- app.exit(1);- });-} else {- const {test} = require("node:test");- const {execFile} = require("node:child_process");- const {promisify} = require("node:util");- test("real Electron owner, main, preload and isolated map enforce native geometry, CSP and teardown", {- skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY- ? "Real Electron boundary verification requires DISPLAY or WAYLAND_DISPLAY" : false,- }, async () => {- const profile = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-map-boundary-"));- const env = {...process.env};- delete env.ELECTRON_RUN_AS_NODE;- try {- await promisify(execFile)(require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 30000});- } finally {- assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));- fs.rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});- }- });-}diff --git a/app/tests/mapUnplacedAssets.test.js b/app/tests/mapUnplacedAssets.test.jsdeleted file mode 100644index 2a7ddc88ae..0000000000--- a/app/tests/mapUnplacedAssets.test.js+++ /dev/null@@ -1,100 +0,0 @@-const assert = require("node:assert/strict");-const path = require("node:path");-const {readFileSync} = require("node:fs");-const {test} = require("node:test");-const config = require("../webpack.map");-const sass = require("sass");-const postcss = require("postcss");--const emitAssets = () => {- const assets = new Map();- const compilation = {- fileDependencies: new Set(),- emitAsset(name, source) { assets.set(name, source.source()); },- hooks: {processAssets: {tap(_options, callback) { callback(); }}},- };- const compiler = {hooks: {thisCompilation: {tap(_name, callback) { callback(compilation); }}}};- const options = config({}, {mode: "production"});- options.plugins.forEach(plugin => plugin.apply(compiler));- return {assets, compilation, options};-};--test("map asset plugin emits shared menu controls and watches their Sass and built-in theme dependencies", () => {- const {assets, compilation, options} = emitAssets();- const controls = assets.get("unplaced-controls.css");- assert.equal(typeof controls, "string");- assert.match(controls, /\.b3-menu__item/);- assert.match(controls, /\.b3-text-field/);- assert.match(controls, /button,\s*input,\s*select,\s*textarea\s*\{[^}]*font-size: 100%/);- assert.doesNotMatch(controls, /@import|https?:\/\//);- for (const name of ["_menu.scss", "_text-field.scss", "_button.scss", "_counter.scss", "_record-inbox.scss"]) {- assert.ok(compilation.fileDependencies.has(path.resolve(__dirname, "../src/assets/scss/component", name)), name);- }- assert.ok(compilation.fileDependencies.has(path.resolve(__dirname, "../src/assets/scss/util/_reset.scss")));- for (const name of ["daylight", "midnight"]) {- assert.ok(compilation.fileDependencies.has(path.resolve(__dirname, "../appearance/themes", name, "theme.css")), name);- }- assert.ok(compilation.fileDependencies.has(path.resolve(__dirname, "../electron/mapUnplaced/menu.css")));- assert.equal(options.output.path, path.resolve(__dirname, "../stage/build/map"));- assert.ok(assets.has("maplibre-gl.js"));-});--test("trusted menu shares calendar content geometry and built-in theme values without remote resource styles", () => {- const {assets} = emitAssets();- const controls = postcss.parse(assets.get("unplaced-controls.css"));- const calendar = postcss.parse(sass.compile(path.resolve(__dirname, "../src/assets/scss/business/_av-calendar.scss"),- {logger: sass.Logger.silent}).css);- const declarations = (root, selector) => {- const result = {};- root.walkRules(rule => {- if (rule.selectors.includes(selector)) rule.walkDecls(declaration => { result[declaration.prop] = declaration.value; });- });- return result;- };- for (const suffix of ["-head", "-head .b3-menu__label", "-search", "-search .b3-text-field", "-empty", "-more"]) {- const expected = declarations(calendar, "#commonMenu .av__calendar-undated" + suffix);- assert.ok(Object.keys(expected).length, suffix);- assert.deepEqual(declarations(controls, ".av-records-panel" + suffix), expected, suffix);- }- assert.equal(declarations(controls, ".av-records-panel-list")["min-height"], "36px");- assert.equal(declarations(controls, ".av-records-panel-list")["max-height"], "360px");- assert.equal(declarations(controls, ".b3-menu__item")["line-height"], "28px");- assert.equal(declarations(controls, ".counter")["height"], "22px");- assert.equal(declarations(controls, ".counter--bg")["background-color"], "var(--b3-theme-surface)");- assert.equal(declarations(controls, ".av-records-panel-item .b3-menu__label")["text-overflow"], "ellipsis");- for (const [mode, theme] of [["light", "daylight"], ["dark", "midnight"]]) {- const source = postcss.parse(readFileSync(path.resolve(__dirname, "../appearance/themes", theme, "theme.css"), "utf8"));- const expected = declarations(source, ":root");- const actual = declarations(controls, ':root[data-theme="' + mode + '"]');- for (const name of ["--b3-font-size", "--b3-font-family", "--b3-menu-background", "--b3-menu-icon-color",- "--b3-theme-background", "--b3-theme-surface-lighter", "--b3-border-radius", "--b3-border-radius-b", "--b3-dialog-shadow"]) {- assert.equal(actual[name], expected[name], mode + " " + name);- }- for (const value of Object.values(actual)) {- for (const reference of value.matchAll(/var\((--[\w-]+)/g)) assert.ok(actual[reference[1]], reference[1]);- }- }- assert.doesNotMatch(assets.get("unplaced-controls.css"), /url\s*\(|@import|https?:\/\//i);- assert.doesNotMatch(readFileSync(path.resolve(__dirname, "../electron/mapUnplaced/menu.css"), "utf8"),- /--b3-(?:theme-|menu-|border-|dialog-)|font-family\s*:/);-});--test("trusted menu embeds only the fixed repository file and open symbols", () => {- const template = readFileSync(path.resolve(__dirname, "../electron/mapUnplaced/menu.html"), "utf8");- const source = readFileSync(path.resolve(__dirname, "../appearance/icons/litheness/icon.js"), "utf8");- for (const name of ["iconFile", "iconOpen"]) {- const symbol = new RegExp('<symbol id="' + name + '"[^>]*>[\\s\\S]*?<\\/symbol>');- assert.equal(template.match(symbol)?.[0].replace(/\s+/g, " "), source.match(symbol)?.[0].replace(/\s+/g, " "), name);- }- assert.equal((template.match(/<symbol /g) || []).length, 2);- assert.doesNotMatch(template, /<svg[^>]*(?:on\w+=)|<(?:iframe|image)|href="(?:https?:)?\/\//i);-});--test("all desktop packages include local trusted menu resources and generated controls", () => {- for (const name of ["electron-builder.yml", "electron-builder-arm64.yml", "electron-builder-linux.yml",- "electron-builder-linux-arm64.yml", "electron-builder-darwin.yml", "electron-builder-darwin-arm64.yml"]) {- const source = readFileSync(path.resolve(__dirname, "..", name), "utf8");- assert.match(source, /files:\s*\n\s*- "electron"/, name);- assert.match(source, /from: "stage"\s*\n\s*to: "stage"/, name);- }-});diff --git a/app/tests/mapUnplacedOverlay.test.js b/app/tests/mapUnplacedOverlay.test.jsdeleted file mode 100644index 9a7402b4f6..0000000000--- a/app/tests/mapUnplacedOverlay.test.js+++ /dev/null@@ -1,595 +0,0 @@-const assert = require("node:assert/strict");-const {test} = require("node:test");-const {EventEmitter} = require("node:events");-const fs = require("node:fs");-const path = require("node:path");-const os = require("node:os");-const vm = require("node:vm");-const {ORIGIN, CHANNEL, CSP, parseState, parseAction, resource, place} = require("../electron/mapUnplaced/policy");-const {createRouter, createManager} = require("../electron/mapUnplaced/manager");-const resourceDirectory = path.join(__dirname, "../electron/mapUnplaced");-const fixtureDirectory = path.join(__dirname, "fixtures/map-unplaced-overlay");-const ownerURL = "file:///fixture/owner.html";-const state = (extra = {}) => ({revision: 1, requestID: 0, query: "", rows: [{id: "row-1", title: "Private <img src=x>"}],- total: 123, page: 1, loading: false, error: false, theme: {mode: "light", fontSize: 16},- labels: {title: "List", search: "Search", empty: "Empty", loading: "Loading", more: "More", previous: "Previous", retry: "Retry", close: "Close"}, ...extra});-const anchor = {x: 100, y: 50, width: 160, height: 30};-const createSession = () => {- const ses = Object.assign(new EventEmitter(), {handlers: {}, protocols: {}, cleanup: []});- for (const name of ["setPermissionRequestHandler", "setPermissionCheckHandler", "setDevicePermissionHandler",- "setDisplayMediaRequestHandler", "setCertificateVerifyProc", "allowNTLMCredentialsForDomains"]) {- ses[name] = fn => { ses.handlers[name] = fn; };- }- for (const name of ["closeAllConnections", "clearStorageData", "clearAuthCache", "clearCache", "clearHostResolverCache"]) {- ses[name] = async () => ses.cleanup.push(name);- }- ses.webRequest = {onBeforeRequest: fn => { ses.handlers.before = fn; },- onBeforeSendHeaders: fn => { ses.handlers.headers = fn; }};- ses.protocol = {handle: (scheme, fn) => { ses.protocols[scheme] = fn; }};- return ses;-};-const createContents = url => Object.assign(new EventEmitter(), {- mainFrame: {url}, dead: false, sent: [], focused: 0, zoom: 1,- isDestroyed() { return this.dead; },- getZoomFactor() { return this.zoom; },- setZoomFactor(value) { this.zoom = value; },- setWindowOpenHandler(fn) { this.popup = fn; },- loadURL(value) { this.mainFrame.url = value; return Promise.resolve(); },- focus() { this.focused++; },- stop() {},- close() { this.dead = true; this.emit("destroyed"); },- send(channel, value) { this.sent.push([channel, value]); },-});-const setup = (fail = "") => {- const ipcMain = new EventEmitter(), owner = createContents(ownerURL), map = createContents("data:synthetic");- const sessions = [], views = [], actions = [], closed = [], children = [];- let allowed = true, counter = 0;- const win = Object.assign(new EventEmitter(), {bounds: {width: 800, height: 600}, visible: true,- isDestroyed: () => false, isFocused: () => true, isVisible() { return this.visible; }, getContentBounds() { return this.bounds; },- contentView: {addChildView(view) { if (fail === "attach") throw new Error("attach"); children.push(view); },- removeChildView(view) { const index = children.indexOf(view); if (index >= 0) children.splice(index, 1); }}});- const manager = createManager({ipcMain, owner, win, ownerURL, outsideContents: [map], assets: {controls: ""},- session: {fromPartition(name) { const ses = createSession(); ses.partition = name; sessions.push(ses); return ses; }},- WebContentsView: function (options) {- if (fail === "constructor") throw new Error("constructor");- const webContents = createContents("");- if (fail === "load") webContents.loadURL = () => Promise.reject(new Error("load"));- const view = {options, webContents, bounds: [], visibility: [],- setBackgroundColor(value) { this.background = value; },- setBounds(value) { if (fail === "bounds") throw new Error("bounds"); this.bounds.push(value); },- setVisible(value) { this.visibility.push(value); }};- views.push(view);- return view;- }, mayUse: () => allowed, randomID: () => (++counter).toString(16).padStart(48, "0"),- readFile: fail === "asset" ? async () => { throw new Error("private path"); } : undefined,- onAction: value => actions.push(value), onClose: value => closed.push(value)});- const event = {sender: owner, senderFrame: owner.mainFrame};- const open = value => manager.open(event, {state: state(value), anchor});- const action = (type, extra = {}, eventOverride) => {- const current = manager.inspect();- const contents = current?.view.webContents || views.at(-1).webContents;- ipcMain.emit(CHANNEL + "-action", eventOverride || {sender: contents, senderFrame: contents.mainFrame},- {sessionID: current?.sessionID, revision: type === "ready" ? 0 : 1, type, ...extra});- };- return {manager, event, open, action, owner, map, win, sessions, views, actions, closed, children, ipcMain,- revoke() { allowed = false; }};-};--test("overlay strict schemas copy bounded plain text and reject URLs, HTML fields, duplicate IDs and CSS", () => {- const source = state(), result = parseState(source);- assert.deepEqual(result, source);- assert.notEqual(result.rows, source.rows);- for (const value of [state({url: "https://evil.invalid"}), state({rows: [{id: "a", title: "x", html: "<b>"}]}),- state({rows: [{id: "a", title: "x"}, {id: "a", title: "y"}]}), state({query: "x".repeat(257)}),- state({theme: {mode: "dark", fontSize: 33}}), state({theme: {mode: "dark", fontSize: 16, css: "url(https://evil)"}}),- state({revision: NaN}), state({total: -1}), state({page: 0}), state({rows: [{id: "x", title: "x".repeat(2049)}]})]) {- assert.equal(parseState(value), undefined);- }- const envelope = {sessionID: "a".repeat(48), revision: 1, type: "select", id: "row-1"};- assert.deepEqual(parseAction(envelope), envelope);- for (const value of [{...envelope, url: "https://evil"}, {...envelope, sessionID: "bad"},- {...envelope, revision: -1}, {...envelope, type: "execute"}]) assert.equal(parseAction(value), undefined);- assert.equal(resource(ORIGIN + "/menu.html", "GET")[0], "menu.html");- for (const url of [ORIGIN + "/%6denu.html", ORIGIN + "/x/../menu.html", ORIGIN + "/menu.html?x", ORIGIN + "/menu.html#x",- "https://[email protected]/menu.html", "https://evil.invalid/menu.html"]) assert.equal(resource(url, "GET"), undefined);- assert.equal(resource(ORIGIN + "/menu.html", "POST"), undefined);- assert.doesNotMatch(CSP, /unsafe-inline|unsafe-eval/);-});--test("overlay router denies all networking, permissions, credentials, frames, repeat navigation and destroyed requests", async () => {- const ses = createSession(), files = [];- const router = createRouter(ses, {controls: "shared"}, async filename => { files.push(filename); return "local"; });- const before = (url, resourceType, method = "GET") => {- let answer;- ses.handlers.before({url, resourceType, method}, value => { answer = value; });- return answer.cancel;- };- assert.equal(before(ORIGIN + "/menu.html", "mainFrame"), false);- assert.equal(before(ORIGIN + "/menu.html", "mainFrame"), true);- assert.equal(before(ORIGIN + "/menu.js", "script"), false);- for (const type of ["subFrame", "xhr", "webSocket", "other"]) assert.equal(before(ORIGIN + "/menu.js", type), true);- for (const url of ["https://tiles.openfreemap.org/private", "http://127.0.0.1:6806/api/sql", "file:///etc/passwd", "data:text/html,hi", "blob:x"]) {- assert.equal(before(url, "script"), true);- }- const response = await ses.protocols.https(new Request(ORIGIN + "/menu.html"));- assert.equal(await response.text(), "local");- assert.equal(response.headers.get("content-security-policy"), CSP);- assert.deepEqual(files, [path.join(resourceDirectory, "menu.html")]);- assert.equal((await ses.protocols.https(new Request(ORIGIN + "/menu.js", {headers: {"service-worker": "script"}}))).status, 403);- assert.equal((await ses.protocols.http(new Request("http://127.0.0.1"))).status, 403);- assert.equal((await ses.protocols.file()).status, 403);- let value;- ses.handlers.setPermissionRequestHandler({}, "clipboard-read", answer => { value = answer; });- assert.equal(value, false);- assert.equal(ses.handlers.setPermissionCheckHandler(), false);- assert.equal(ses.handlers.setDevicePermissionHandler(), false);- ses.handlers.headers({requestHeaders: {Cookie: "secret"}}, answer => { value = answer; });- assert.deepEqual(value.requestHeaders, {});- router.destroy();- assert.equal(before(ORIGIN + "/menu.js", "script"), true);- assert.equal((await ses.protocols.https(new Request(ORIGIN + "/menu.js"))).status, 403);- assert.equal(ses.cleanup.length, 5);-});--test("overlay owner/frame/session binding, request invalidation and membership gate reject stale and foreign selections", () => {- const f = setup();- try {- assert.equal(f.manager.open({...f.event, senderFrame: {}}, {state: state(), anchor}), undefined);- const sessionID = f.open();- f.action("ready");- const options = f.views[0].options.webPreferences;- assert.equal(options.sandbox, true);- assert.equal(options.contextIsolation, true);- assert.equal(options.nodeIntegration, false);- assert.equal(options.webSecurity, true);- assert.equal(options.webviewTag, false);- assert.ok(!f.sessions[0].partition.startsWith("persist:"));- assert.deepEqual(f.views[0].visibility, [false, true]);- f.action("select", {id: "row-1"}, {sender: f.map, senderFrame: f.map.mainFrame});- f.action("select", {id: "missing"});- f.action("select", {id: "row-1", sessionID: "f".repeat(48)});- assert.equal(f.actions.length, 0);- f.action("editing");- f.action("select", {id: "row-1"});- assert.equal(f.actions.length, 1);- assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 2})}), false);- f.action("search", {query: "new"});- assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 2, query: "old"})}), false);- assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 2, requestID: 2, query: "new", loading: true})}), true);- f.action("select", {id: "row-1", revision: 2});- assert.equal(f.actions.length, 2);- assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 3, requestID: 2, query: "new", rows: [{id: "new", title: "new"}]})}), true);- f.action("select", {id: "row-1", revision: 3});- f.action("select", {id: "new", revision: 2});- assert.equal(f.actions.length, 2);- f.action("select", {id: "new", revision: 3});- assert.equal(f.actions.at(-1).id, "new");- assert.equal(f.manager.inspect(), undefined);- assert.equal(f.owner.focused, 1);- const replacement = f.open();- assert.notEqual(replacement, sessionID);- assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 99})}), false);- } finally { f.manager.destroy(); }-});--test("initial loading completes and main-issued request generations reject late A-to-B-to-A results", () => {- const f = setup();- try {- const sessionID = f.open({loading: true, rows: []});- f.action("ready");- assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 2, query: "wrong"})}), false);- assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 2})}), true);- f.action("search", {revision: 2, query: "A"});- f.action("search", {revision: 2, query: "B"});- f.action("search", {revision: 2, query: "A"});- assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 3, requestID: 1, query: "A"})}), false);- assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 4, requestID: 3, query: "A"})}), true);- } finally { f.manager.destroy(); }-});--test("page replacement reaches every result beyond 500 rows and 20 pages, and previous/retry keep main-issued page identity", () => {- const f = setup(), total = 1234;- const rows = page => Array.from({length: Math.min(50, total - (page - 1) * 50)}, (_, index) => ({- id: "row-" + ((page - 1) * 50 + index), title: "Record " + ((page - 1) * 50 + index),- }));- try {- const sessionID = f.open({total, rows: rows(1)});- f.action("ready");- let revision = 1, requestID = 0;- const seen = new Set(rows(1).map(row => row.id));- for (let page = 2; page <= Math.ceil(total / 50); page++) {- f.action("more", {revision});- requestID++;- assert.equal(f.actions.at(-1).requestID, requestID);- assert.equal(f.actions.at(-1).page, page);- assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: revision + 1, requestID,- total, page: page - 1, rows: rows(page)})}), false, "same request with the previous page is stale");- assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: ++revision, requestID,- total, page, rows: rows(page)})}), true);- rows(page).forEach(row => seen.add(row.id));- }- assert.equal(seen.size, total);- const count = f.actions.length;- f.action("more", {revision});- assert.equal(f.actions.length, count, "only the actual final page disables Next");- f.action("previous", {revision});- requestID++;- assert.equal(f.actions.at(-1).page, 24);- assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: ++revision, requestID,- total, page: 24, error: true, rows: []})}), true);- f.action("retry", {revision});- requestID++;- assert.equal(f.actions.at(-1).page, 24);- assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: ++revision, requestID,- total, page: 24, rows: rows(24)})}), true);- f.action("select", {revision, id: rows(25)[0].id});- assert.ok(f.manager.inspect(), "members of a previously rendered page cannot be selected");- f.action("select", {revision, id: rows(24)[0].id});- assert.equal(f.manager.inspect(), undefined);- assert.equal(f.closed.length, 0, "select uses one terminal action and no earlier closed notification");- } finally { f.manager.destroy(); }-});--test("bounded DTOs reject oversized pages while preserving large result counts and settled query/page identity", () => {- assert.ok(parseState(state({total: 2000000, page: 20001})));- assert.equal(parseState(state({rows: Array.from({length: 51}, (_, index) => ({id: String(index), title: "Record"}))})), undefined);- for (const fontSize of [12, 13, 17, 31, 32]) assert.ok(parseState(state({theme: {mode: "dark", fontSize}})));- for (const fontSize of [11, 12.5, 33, Infinity]) assert.equal(parseState(state({theme: {mode: "dark", fontSize}})), undefined);- const f = setup();- try {- const sessionID = f.open(); f.action("ready");- for (const extra of [{query: "unexpected"}, {page: 2}, {requestID: 1}]) {- assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 2, ...extra})}), false);- }- assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 2, theme: {mode: "dark", fontSize: 23}})}), true);- } finally { f.manager.destroy(); }-});--test("independent theme updates never expire an in-flight edit or pagination action and cannot restore cleared row membership", () => {- const f = setup();- try {- const sessionID = f.open(); f.action("ready");- const theme = {mode: "dark", fontSize: 23};- for (const value of [{sessionID: "f".repeat(48), theme}, {sessionID, theme: {...theme, css: "private"}},- {sessionID, theme, revision: 2}, {sessionID, theme: {mode: "dark", fontSize: 33}}]) {- assert.equal(f.manager.setTheme(f.event, value), false);- }- assert.equal(f.manager.setTheme({...f.event, senderFrame: {}}, {sessionID, theme}), false);- assert.equal(f.manager.setTheme(f.event, {sessionID, theme}), true);- assert.deepEqual(f.views[0].webContents.sent.at(-1), [CHANNEL + "-theme", {sessionID, theme}]);- assert.equal(f.views[0].webContents.sent.filter(([name]) => name === CHANNEL + "-state").at(-1)[1].state.revision, 1);- f.action("editing", {revision: 1});- assert.equal(f.actions.at(-1).requestID, 1);- assert.equal(f.manager.setTheme(f.event, {sessionID, theme: {mode: "light", fontSize: 32}}), true);- f.action("select", {revision: 1, id: "row-1"});- assert.equal(f.actions.length, 1, "theme must not restore members cleared during editing");- f.action("search", {revision: 1, query: "latest"});- assert.equal(f.actions.at(-1).requestID, 2);- assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 2, requestID: 2, query: "latest"})}), true);- assert.equal(f.manager.setTheme(f.event, {sessionID, theme}), true);- f.action("more", {revision: 2});- assert.equal(f.actions.at(-1).page, 2);- assert.equal(f.actions.at(-1).requestID, 3);- } finally { f.manager.destroy(); }-});--test("shared production resources are read only from their exact package paths including compiled controls", async () => {- const ses = createSession(), files = [];- const controlsPath = "/app/stage/build/map/unplaced-controls.css";- const router = createRouter(ses, {controlsPath}, async filename => { files.push(filename); return "local"; });- try {- for (const resourceName of ["menu.html", "menu.js", "menu.css", "controls.css"]) {- assert.equal((await ses.protocols.https(new Request(ORIGIN + "/" + resourceName))).status, 200);- }- assert.deepEqual(files, [path.join(resourceDirectory, "menu.html"), path.join(resourceDirectory, "menu.js"),- path.join(resourceDirectory, "menu.css"), controlsPath]);- assert.equal((await ses.protocols.https(new Request(ORIGIN + "/controls.css?url=private"))).status, 403);- assert.equal((await ses.protocols.https(new Request(ORIGIN + "/preload.js"))).status, 403);- } finally { router.destroy(); }-});--test("a missing menu stylesheet closes the session instead of showing partially loaded private UI", async () => {- const f = setup("asset");- try {- f.open(); f.action("ready");- assert.equal((await f.sessions[0].protocols.https(new Request(ORIGIN + "/menu.css"))).status, 404);- assert.equal(f.manager.inspect(), undefined);- assert.equal(f.views[0].webContents.isDestroyed(), true);- assert.equal(f.sessions[0].cleanup.length, 5);- assert.equal(f.closed.at(-1).reason, "resource-failed");- assert.equal(JSON.stringify(f.closed).includes("private path"), false);- } finally { f.manager.destroy(); }-});--test("overlay pagination gates, permission revocation and owner navigation destroy private state", () => {- const f = setup();- try {- f.open(); f.action("ready"); f.action("more"); f.action("more");- assert.equal(f.actions.length, 1);- f.revoke(); f.action("select", {id: "row-1"});- assert.equal(f.manager.inspect(), undefined);- assert.equal(f.closed.at(-1).reason, "permission-revoked");- } finally { f.manager.destroy(); }- for (const operation of [f => f.owner.emit("did-start-navigation", {isMainFrame: true}),- f => { f.owner.mainFrame.url = "file:///other.html"; f.action("select", {id: "row-1"}); },- f => f.owner.emit("destroyed"), f => f.win.emit("closed")]) {- const fixture = setup();- fixture.open(); fixture.action("ready"); operation(fixture);- assert.equal(fixture.manager.inspect(), undefined);- assert.equal(fixture.views[0].webContents.dead, true);- assert.equal(fixture.children.length, 0);- assert.equal(fixture.sessions[0].cleanup.length, 5);- fixture.manager.destroy();- assert.equal(fixture.ipcMain.listenerCount(CHANNEL + "-action"), 0);- }-});--test("overlay anchors use actual zoom/content bounds; geometry is deduplicated and focus transitions do not hide", () => {- const f = setup();- try {- const sessionID = f.open(); f.action("ready");- const view = f.views[0];- f.owner.emit("blur");- assert.ok(f.manager.inspect());- const count = view.bounds.length;- f.manager.setAnchor(f.event, {sessionID, anchor});- assert.equal(view.bounds.length, count);- f.owner.zoom = 1.25;- f.manager.setAnchor(f.event, {sessionID, anchor: {...anchor, y: 100}});- assert.deepEqual(view.bounds.at(-1), place({...anchor, y: 100}, 1.25, f.win.bounds));- assert.deepEqual(view.visibility, [false, true]);- f.map.emit("before-mouse-event", {}, {type: "mouseDown"});- assert.equal(f.manager.inspect(), undefined);- assert.equal(f.owner.focused, 0);- f.open(); f.action("ready");- f.win.bounds = {width: 100, height: 100}; f.win.emit("resize");- assert.equal(f.manager.inspect(), undefined);- } finally { f.manager.destroy(); }-});--test("overlay setup failures close sessions, views and listeners transactionally", async () => {- for (const failure of ["constructor", "attach", "bounds", "load"]) {- const f = setup(failure);- f.open();- await Promise.resolve();- assert.equal(f.manager.inspect(), undefined, failure);- assert.equal(f.children.length, 0, failure);- assert.equal(f.sessions[0].cleanup.length, 5, failure);- if (f.views[0]) assert.equal(f.views[0].webContents.dead, true, failure);- f.manager.destroy();- assert.equal(f.ipcMain.listenerCount(CHANNEL + "-action"), 0, failure);- }-});--test("manual harness requires an explicit profile and owns only its fresh temporary directory", async () => {- const {createHarness, createTemporaryProfile} = require("./fixtures/map-unplaced-overlay/harnessSupport.cjs");- await assert.rejects(createHarness(), /explicit isolated fixture profile/);- const temporary = createTemporaryProfile();- try {- assert.equal(path.dirname(temporary.profile), os.tmpdir());- assert.ok(path.basename(temporary.profile).startsWith("siyuan-unplaced-manual-"));- fs.writeFileSync(path.join(temporary.profile, "fixture-only"), "synthetic");- } finally { temporary.cleanup(); }- assert.equal(fs.existsSync(temporary.profile), false);- temporary.cleanup();-});--test("actual preload exposes only fixed operations, binds session/revision and never forwards IPC events", () => {- const ipc = new EventEmitter(), sent = [];- ipc.send = (channel, value) => sent.push({channel, value});- let bridge;- vm.runInNewContext(fs.readFileSync(path.join(resourceDirectory, "preload.js"), "utf8"), {- require: name => { assert.equal(name, "electron"); return {ipcRenderer: ipc,- contextBridge: {exposeInMainWorld(name, value) { assert.equal(name, "unplacedMenu"); bridge = value; }}}; },- process: {argv: ["--unplaced-session=" + "a".repeat(48)]},- });- assert.deepEqual(Object.keys(bridge).sort(), ["close", "editing", "more", "previous", "resize", "retry", "search", "select", "subscribe"]);- const updates = [], themes = [];- bridge.subscribe((...args) => updates.push(args), (...args) => themes.push(args));- assert.equal(sent[0].value.type, "ready");- const privateEvent = {sender: "must-not-pass"};- ipc.emit(CHANNEL + "-state", privateEvent, {sessionID: "b".repeat(48), state: state()});- assert.equal(updates.length, 0);- ipc.emit(CHANNEL + "-state", privateEvent, {sessionID: "a".repeat(48), state: state({revision: 3})});- assert.equal(updates[0].length, 1);- assert.equal(updates[0][0].revision, 3);- ipc.emit(CHANNEL + "-theme", privateEvent, {sessionID: "a".repeat(48), theme: {mode: "dark", fontSize: 32}});- assert.equal(themes.length, 1);- assert.equal(themes[0].length, 1);- assert.deepEqual(JSON.parse(JSON.stringify(themes[0][0])), {mode: "dark", fontSize: 32});- assert.equal(updates.length, 1, "theme must not replay a stale result state");- bridge.select("row-1");- assert.equal(sent.at(-1).value.revision, 3);- assert.equal(sent.at(-1).value.sessionID, "a".repeat(48));- const count = sent.length;- bridge.close("url"); bridge.search("x".repeat(257));- for (const height of [0, 49, 4097, 50.5, NaN, Infinity, "200"]) bridge.resize(height);- assert.equal(sent.length, count);- bridge.resize(220);- assert.equal(sent.at(-1).value.type, "resize");- assert.equal(sent.at(-1).value.height, 220);- assert.equal(sent.at(-1).value.revision, 3);-});--test("actual menu script uses text nodes, preserves pending edits against late states and suppresses composing search (simulated DOM)", () => {- const {DOMFixture} = require("../src/protyle/render/av/map/testDOM.ts");- const document = new DOMFixture();- document.body.innerHTML = fs.readFileSync(path.join(resourceDirectory, "menu.html"), "utf8");- document.getElementById = id => document.body.querySelector('[id="' + id + '"]');- document.addEventListener = (...args) => document.documentElement.addEventListener(...args);- document.createElementNS = (_namespace, name) => document.createElement(name);- const menu = document.getElementById("menu");- let preferredHeight = 180, observed, disconnected = false;- menu.getBoundingClientRect = () => ({height: menu.classList.contains("map-unplaced-menu--measure") ? preferredHeight : 120});- const rows = document.getElementById("rows");- rows.replaceChildren = () => { Array.from(rows.children).forEach(child => child.remove()); };- const actions = [], timers = new Map();- let update, themeUpdate, nextTimer = 0;- const bridge = {subscribe(fn, onTheme) { update = fn; themeUpdate = onTheme; }};- const sizes = [], windowEvents = new Map();- for (const name of ["search", "editing", "more", "previous", "retry", "select", "close"]) bridge[name] = value => actions.push([name, value]);- bridge.resize = value => sizes.push(value);- const window = {unplacedMenu: bridge, addEventListener(name, callback) { windowEvents.set(name, callback); }};- vm.runInNewContext(fs.readFileSync(path.join(resourceDirectory, "menu.js"), "utf8"), {window, document,- ResizeObserver: function (callback) { observed = callback; this.observe = target => assert.equal(target, menu);- this.disconnect = () => { disconnected = true; }; },- setTimeout(fn) { timers.set(++nextTimer, fn); return nextTimer; }, clearTimeout(id) { timers.delete(id); }});- const flush = () => { const callbacks = [...timers.values()]; timers.clear(); callbacks.forEach(fn => fn()); };- const fire = (element, type, event = {}) => (element.events.get(type) || []).forEach(fn => fn({preventDefault() {}, ...event}));- update(state());- assert.equal(rows.children.length, 1);- assert.equal(rows.querySelectorAll("img").length, 0);- assert.equal(rows.children[0].textContent, "Private <img src=x>");- assert.deepEqual(rows.querySelectorAll("use").map(icon => icon.getAttribute("href")), ["#iconFile", "#iconOpen"]);- assert.ok(rows.children[0].classList.contains("av-records-panel-item"));- assert.ok(document.getElementById("count").classList.contains("counter--bg"));- assert.equal(document.getElementById("count").textContent, "123");- assert.equal(document.getElementById("status").hidden, true);- assert.deepEqual(sizes, [228]);- assert.equal(menu.classList.contains("map-unplaced-menu--measure"), false);- observed();- assert.deepEqual(sizes, [228], "viewport resize must not create a shrinking feedback loop");- update(state({revision: 2}));- assert.deepEqual(sizes, [228, 228], "a new state revision retries the same height after a stale resize");- preferredHeight = 240;- observed();- assert.equal(sizes.at(-1), 288);- const input = document.getElementById("search");- fire(document.getElementById("more"), "click");- assert.equal(rows.children[0].disabled, true);- themeUpdate({mode: "dark", fontSize: 32});- assert.equal(document.documentElement.dataset.fontSize, "32");- assert.equal(rows.children[0].disabled, true, "theme during pagination cannot restore previous-page members");- assert.equal(document.getElementById("more").disabled, true);- update(state());- input.value = ""; fire(input, "input"); flush();- assert.deepEqual(actions.at(-1), ["search", ""]);- themeUpdate({mode: "light", fontSize: 16});- assert.equal(rows.children[0].disabled, true, "theme after same-query search cannot replay the preceding result");- update(state());- input.value = "new"; fire(input, "input");- assert.equal(actions.at(-1)[0], "editing");- update(state({revision: 2}));- assert.equal(rows.children[0].disabled, true);- flush();- assert.deepEqual(actions.at(-1), ["search", "new"]);- update(state({revision: 3, query: "old"}));- assert.equal(rows.children[0].disabled, true);- update(state({revision: 4, query: "new"}));- assert.equal(rows.children[0].disabled, false);- fire(input, "compositionstart"); input.value = "中文"; fire(input, "input", {isComposing: true}); flush();- assert.equal(actions.at(-1)[0], "editing");- update(state({revision: 5, query: "new", theme: {mode: "dark", fontSize: 32}}));- assert.equal(rows.children[0].disabled, true);- assert.equal(document.documentElement.dataset.theme, "dark");- assert.equal(document.documentElement.dataset.fontSize, "32");- fire(input, "compositionend"); flush();- assert.deepEqual(actions.at(-1), ["search", "中文"]);- update(state({revision: 6, query: "中文", theme: {mode: "dark", fontSize: 24}}));- assert.equal(document.documentElement.dataset.theme, "dark");- assert.equal(document.documentElement.dataset.fontSize, "24");- fire(document.documentElement, "keydown", {key: "Escape"});- assert.deepEqual(actions.at(-1), ["close", "escape"]);- const actionCount = actions.length;- fire(document.documentElement, "pointerdown", {target: input});- assert.equal(actions.length, actionCount);- fire(document.documentElement, "pointerdown", {target: document.body});- assert.deepEqual(actions.at(-1), ["close", "button"]);- fire(document.getElementById("close"), "click");- assert.deepEqual(actions.at(-1), ["close", "button"]);- windowEvents.get("pagehide")();- assert.equal(disconnected, true);-});--test("actual owner script keeps toggle/outside separate and cancels stale same-query work (simulated DOM)", async () => {- const {DOMFixture} = require("../src/protyle/render/av/map/testDOM.ts");- const document = new DOMFixture();- document.body.innerHTML = fs.readFileSync(path.join(fixtureDirectory, "owner.html"), "utf8");- document.getElementById = id => document.body.querySelector('[id="' + id + '"]');- document.addEventListener = (...args) => document.documentElement.addEventListener(...args);- const toggle = document.getElementById("open");- toggle.getBoundingClientRect = () => ({x: 100, y: 50, left: 100, top: 50, right: 260, bottom: 80, width: 160, height: 30});- const viewport = {left: 0, top: 20, right: 600, bottom: 420};- document.getElementById("scroll").getBoundingClientRect = () => viewport;- const sessionID = "a".repeat(48), updates = [], closes = [], anchors = [], timers = new Map(), listeners = new Map();- let reply, opens = 0, nextTimer = 0;- const bridge = {- async open(value) { opens++; assert.ok(parseState(value.state)); return sessionID; },- update(value) { assert.ok(parseState(value.state)); updates.push(value); },- close(value) { closes.push(value); },- subscribe(fn) { reply = fn; }, anchor(value) { anchors.push(value); }, zoom() {}, permission() {},- };- vm.runInNewContext(fs.readFileSync(path.join(fixtureDirectory, "owner.js"), "utf8"), {- window: {fixtureOwner: bridge, innerWidth: 800, innerHeight: 600,- addEventListener(name, fn) { listeners.set(name, fn); }}, document,- setTimeout(fn) { timers.set(++nextTimer, fn); return nextTimer; }, clearTimeout(id) { timers.delete(id); },- });- const click = () => toggle.events.get("click")[0]();- const pointer = target => document.documentElement.events.get("pointerdown")[0]({target});- await click();- assert.equal(opens, 1);- pointer(toggle);- assert.equal(closes.length, 0);- await click();- assert.equal(opens, 1);- assert.equal(closes.at(-1).reason, "button");- reply({type: "closed", sessionID, reason: "button", restore: true});- await click();- assert.equal(opens, 2);- viewport.top = 60;- listeners.get("scroll")();- assert.deepEqual(JSON.parse(JSON.stringify(anchors.at(-1).anchor)), {x: 100, y: 60, width: 160, height: 20});- viewport.top = 90;- listeners.get("scroll")();- assert.equal(closes.at(-1).reason, "anchor-hidden");- viewport.top = 20;- pointer(document.body);- assert.equal(closes.at(-1).reason, "outside");- const query = "合成记录 1";- reply({type: "search", sessionID, requestID: 1, query, page: 1});- const lateA = [...timers.values()][0];- reply({type: "editing", sessionID, requestID: 2});- reply({type: "search", sessionID, requestID: 3, query: "合成记录 2", page: 1});- reply({type: "editing", sessionID, requestID: 4});- reply({type: "search", sessionID, requestID: 5, query, page: 1});- const count = updates.length;- lateA();- assert.equal(updates.length, count);- [...timers.values()][0]();- assert.equal(updates.at(-1).state.requestID, 5);- assert.equal(updates.at(-1).state.loading, false);- assert.equal(updates.at(-1).state.total, 34);- reply({type: "closed", sessionID, reason: "outside", restore: false});- assert.equal(timers.size, 0);-});--test("trusted menu content sizing stays bounded and rejects stale or foreign renderer requests", () => {- const f = setup();- try {- f.open(); f.action("ready");- const view = f.views[0];- assert.equal(view.background, "#00000000");- f.action("resize", {height: 220});- assert.equal(view.bounds.at(-1).height, 220);- const count = view.bounds.length;- f.action("resize", {height: 220});- assert.equal(view.bounds.length, count, "same content size never moves or flashes the view");- for (const height of [0, 49, 4097, 100.5, NaN, Infinity]) {- f.action("resize", {height});- assert.equal(view.bounds.length, count);- }- f.action("resize", {height: 250, revision: 0});- f.action("resize", {height: 250, sessionID: "f".repeat(48)});- f.action("resize", {height: 250}, {sender: f.owner, senderFrame: f.owner.mainFrame});- assert.equal(view.bounds.length, count);- f.action("resize", {height: 4096});- const bounds = view.bounds.at(-1);- assert.ok(bounds.height <= Math.floor(f.win.bounds.height * 0.65) + 48);- assert.ok(bounds.x >= 0 && bounds.y >= 0 && bounds.x + bounds.width <= f.win.bounds.width &&- bounds.y + bounds.height <= f.win.bounds.height);- assert.deepEqual(view.visibility, [false, true], "resizing content never hides the map/menu");- assert.equal(f.actions.length, 0, "content size does not become an owner data action");- f.manager.revoke();- assert.equal(f.manager.inspect(), undefined);- } finally { f.manager.destroy(); }-});diff --git a/app/tests/mapUnplacedOverlayBoundary.test.js b/app/tests/mapUnplacedOverlayBoundary.test.jsdeleted file mode 100644index 6b628ef572..0000000000--- a/app/tests/mapUnplacedOverlayBoundary.test.js+++ /dev/null@@ -1,112 +0,0 @@-const assert = require("node:assert/strict");-const fs = require("node:fs");-const path = require("node:path");-const os = require("node:os");--// 使用真实 Electron owner、IPC、sandbox preload 和 DOM;底图及记录仍为合成测试资源。-const run = async profile => {- const {createHarness} = require("./fixtures/map-unplaced-overlay/harnessSupport.cjs");- const f = await createHarness({profile, automate: true});- const owner = source => f.owner.executeJavaScript(source);- const waitFor = async (check, label) => {- const deadline = Date.now() + 5000;- while (!await check()) {- assert.ok(Date.now() < deadline, label);- await new Promise(resolve => setTimeout(resolve, 25));- }- };- const open = async () => {- await owner('document.getElementById("open").click()');- await waitFor(() => f.manager.inspect()?.ready, "overlay becomes ready");- const view = f.manager.inspect().view;- await waitFor(() => view.getVisible(), "overlay becomes visible");- return {view, contents: view.webContents, evaluate: source => view.webContents.executeJavaScript(source)};- };- try {- f.win.focus();- let overlay = await open();- assert.equal(f.win.contentView.children.at(-1), overlay.view);- assert.equal(await overlay.evaluate('document.getElementById("rows").children.length'), 50);- assert.equal(await overlay.evaluate('document.querySelectorAll("img").length'), 0);- assert.equal(await overlay.evaluate('document.getElementById("rows").textContent.includes("<img src=x")'), true);- assert.equal(await overlay.evaluate("typeof require"), "undefined");- assert.equal(await f.map.webContents.executeJavaScript('document.body.textContent.includes("PRIVATE_FIXTURE")'), false);- const security = overlay.contents.getLastWebPreferences();- assert.equal(security.sandbox, true);- assert.equal(security.contextIsolation, true);- assert.equal(security.nodeIntegration, false);- assert.equal(security.webSecurity, true);- assert.equal(await overlay.evaluate('fetch("http://127.0.0.1:6806/api/sql").then(() => false, () => true)'), true);- assert.equal(await overlay.evaluate('fetch("https://tiles.openfreemap.org/private").then(() => false, () => true)'), true);- await overlay.evaluate('document.getElementById("more").click()');- await waitFor(() => overlay.evaluate('document.getElementById("rows").children.length === 50 && document.getElementById("rows").firstElementChild.dataset.rowId === "row-50"'), "pagination replaces the current page");- await overlay.evaluate('const input = document.getElementById("search"); input.value = "合成记录 1"; input.dispatchEvent(new Event("input", {bubbles: true}));');- await waitFor(() => overlay.evaluate('document.getElementById("count").textContent === "34"'), "search result replaces rows");- await owner('document.getElementById("theme").click()');- await waitFor(() => overlay.evaluate('document.documentElement.dataset.theme === "dark"'), "theme reaches trusted view");- assert.equal(await overlay.evaluate('getComputedStyle(document.querySelector(".map-unplaced-menu")).fontSize'), "24px");- assert.equal(await overlay.evaluate('getComputedStyle(document.querySelector(".map-unplaced-menu")).backgroundColor'), "rgb(41, 41, 41)");- const before = overlay.view.getBounds();- await owner('document.getElementById("scroll").scrollTop = 30');- await waitFor(() => overlay.view.getBounds().y !== before.y, "anchor follows owner scroll");- await owner('document.getElementById("zoom").click()');- await waitFor(() => overlay.contents.getZoomFactor() === f.owner.getZoomFactor(), "overlay follows actual owner zoom");- assert.equal(overlay.view.getVisible(), true);- assert.deepEqual(f.mapVisible, [true]);- overlay.contents.sendInputEvent({type: "keyDown", keyCode: "Escape"});- await waitFor(() => !f.manager.inspect(), "escape destroys overlay");- await waitFor(() => owner('document.activeElement.id === "open"'), "escape restores owner focus");- assert.equal(overlay.contents.isDestroyed(), true);- overlay = await open();- await owner('document.getElementById("open").click()');- await waitFor(() => !f.manager.inspect(), "toggle closes once without reopening");- overlay = await open();- await owner('document.body.dispatchEvent(new PointerEvent("pointerdown", {bubbles: true}))');- await waitFor(() => !f.manager.inspect(), "owner DOM outside closes overlay");- assert.equal(f.events.at(-1).restore, false);- overlay = await open();- f.map.webContents.sendInputEvent({type: "mouseDown", x: 20, y: 20, button: "left", clickCount: 1});- f.map.webContents.sendInputEvent({type: "mouseUp", x: 20, y: 20, button: "left", clickCount: 1});- await waitFor(() => !f.manager.inspect(), "native map outside closes overlay");- assert.equal(f.events.at(-1).restore, false);- overlay = await open();- await owner('document.getElementById("scroll").scrollTop = 180');- await waitFor(() => !f.manager.inspect(), "fully clipped anchor destroys overlay");- assert.equal(f.events.at(-1).reason, "anchor-hidden");- assert.equal(f.events.at(-1).restore, false);- await owner('document.getElementById("scroll").scrollTop = 0');- overlay = await open();- await owner('document.getElementById("permission").click()');- await waitFor(() => !f.manager.inspect(), "permission revoke destroys overlay");- assert.equal(overlay.contents.isDestroyed(), true);- await owner('document.getElementById("permission").click()');- overlay = await open();- await f.owner.loadURL("about:blank");- await waitFor(() => !f.manager.inspect(), "programmatic owner navigation destroys overlay");- assert.equal(overlay.contents.isDestroyed(), true);- assert.deepEqual(f.mapVisible, [true]);- } finally { f.destroy(); }-};--if (process.versions.electron && process.type === "browser") {- const {app} = require("electron");- run(process.argv[2]).then(() => app.exit(0), error => { console.error(error); app.exit(1); });-} else {- const {test} = require("node:test");- const {execFile} = require("node:child_process");- const {promisify} = require("node:util");- test("real Electron trusted unplaced overlay DOM, IPC, CSP, theme, focus and native outside clicks", {- skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY- ? "Requires a real display; synthetic Node tests do not validate IME, OFM overlap or production flicker" : false,- }, async () => {- const profile = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-unplaced-overlay-"));- const env = {...process.env};- delete env.ELECTRON_RUN_AS_NODE;- try {- await promisify(execFile)(require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 45000});- } finally {- assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));- fs.rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});- }- });-}diff --git a/app/tests/mapUnplacedOverlayStartup.test.js b/app/tests/mapUnplacedOverlayStartup.test.jsdeleted file mode 100644index 38df2c2e40..0000000000--- a/app/tests/mapUnplacedOverlayStartup.test.js+++ /dev/null@@ -1,97 +0,0 @@-const assert = require("node:assert/strict");-const {test} = require("node:test");-const {spawnSync} = require("node:child_process");-const path = require("node:path");-const {pathToFileURL} = require("node:url");--const entry = pathToFileURL(path.join(__dirname, "fixtures/map-unplaced-overlay/harness.cjs")).href;-const support = pathToFileURL(path.join(__dirname, "fixtures/map-unplaced-overlay/harnessSupport.cjs")).href;--// Match Electron default_app's dynamic import in a fresh process. Only Electron-// and the reusable harness are replaced; the actual manual entry is executed.-const runEntry = mode => spawnSync(process.execPath, ["--input-type=module", "--eval", `- import {createRequire} from "node:module";- const require = createRequire(import.meta.url);- const Module = require("node:module");- const load = Module._load;- const calls = [];- const mode = ${JSON.stringify(mode)};- const electron = {app: {- once(name) { calls.push(name); },- exit(code) { calls.push("exit:" + code); process.exitCode = code; }- }, BrowserWindow: {getAllWindows() { return [{isDestroyed: () => false,- destroy() { calls.push("destroy"); }}]; }}};- const helper = {- createTemporaryProfile() {- calls.push("profile");- if (mode === "profile-failure") throw new Error("private fixture error");- return {profile: "isolated-fixture-profile", cleanup() { calls.push("cleanup"); }};- },- createHarness(options) {- if (options.profile !== "isolated-fixture-profile") throw new Error("wrong profile");- calls.push("create");- if (mode === "sync-failure") throw new Error("private fixture error");- return mode === "async-failure" ? Promise.reject(new Error("private fixture error")) : Promise.resolve();- }- };- Module._load = function(name, parent, isMain) {- if (name === "electron") return mode === "node-mode" ? "electron-binary" : electron;- if (name === "./harnessSupport.cjs") return helper;- return load.call(this, name, parent, isMain);- };- await import(${JSON.stringify(entry)});- await import(${JSON.stringify(entry)});- await new Promise(resolve => setImmediate(resolve));- console.log("fixture-calls:" + JSON.stringify(calls));-`], {cwd: path.join(__dirname, ".."), encoding: "utf8", timeout: 10000});--test("manual Electron dynamic-import entry starts exactly once and reports readiness", () => {- const result = runEntry("success");- assert.equal(result.error, undefined);- assert.equal(result.status, 0, result.stderr);- assert.match(result.stdout, /Map overlay prototype starting\.\.\./);- assert.match(result.stdout, /Map overlay prototype window ready\./);- assert.match(result.stdout, /fixture-calls:\["profile","will-quit","quit","create"\]/);- assert.equal(result.stderr, "");-});--test("manual startup reports synchronous and asynchronous failures without exposing exception details", () => {- for (const mode of ["sync-failure", "async-failure", "profile-failure"]) {- const result = runEntry(mode);- assert.equal(result.error, undefined, mode);- assert.equal(result.status, 1, mode);- assert.match(result.stderr, /Map overlay prototype startup failed\./, mode);- assert.doesNotMatch(result.stdout + result.stderr, /private fixture error|window ready/, mode);- assert.match(result.stdout, /"destroy"/, mode);- if (mode !== "profile-failure") assert.match(result.stdout, /"cleanup"/, mode);- assert.match(result.stdout, /"exit:1"/, mode);- }-});--test("Node-mode invocation gives an explicit message without creating a profile or window", () => {- const result = runEntry("node-mode");- assert.equal(result.error, undefined);- assert.equal(result.status, 1);- assert.match(result.stderr, /requires Electron GUI mode; check ELECTRON_RUN_AS_NODE/);- assert.match(result.stdout, /fixture-calls:\[\]/);-});--test("importing reusable harness support does not start Electron or create a profile", () => {- const result = spawnSync(process.execPath, ["--input-type=module", "--eval", `- import {createRequire} from "node:module";- const require = createRequire(import.meta.url);- const Module = require("node:module");- const load = Module._load;- Module._load = function(name, parent, isMain) {- if (name === "electron") throw new Error("support must not initialize Electron");- return load.call(this, name, parent, isMain);- };- require("node:fs").mkdtempSync = () => { throw new Error("support must not create a profile"); };- const imported = await import(${JSON.stringify(support)});- if (typeof imported.default.createHarness !== "function") throw new Error("missing reusable harness");- `], {cwd: path.join(__dirname, ".."), encoding: "utf8", timeout: 10000});- assert.equal(result.error, undefined);- assert.equal(result.status, 0, result.stderr);- assert.equal(result.stdout, "");- assert.equal(result.stderr, "");-});diff --git a/app/tests/mapWebviewBoundary.test.js b/app/tests/mapWebviewBoundary.test.jsindex e656fa0c24..c6ab57d578 100644--- a/app/tests/mapWebviewBoundary.test.js+++ b/app/tests/mapWebviewBoundary.test.js@@ -5,10 +5,59 @@ const {promisify} = require("node:util");const fs = require("node:fs");const os = require("node:os");const path = require("node:path");-const {ownerPreferences, guestPreferences, createSyntheticFiles, checkRealAssets, verifyIsolation, readMapCornerAssets} =+const {EventEmitter} = require("node:events");+const {ownerPreferences, remoteOwnerPreferences, guestPreferences, createSyntheticFiles, checkRealAssets,+ verifyIsolation, readMapCornerAssets, installRemoteOwnerGuards} =require("./fixtures/map-webview-boundary/harnessSupport.cjs");const {createMapSessionRouter} = require("../electron/mapHostManager");const {createMapContentSecurityPolicy} = require("../electron/mapHostPolicy");+const {createRemoteDocumentContentSecurityPolicy} = require("../electron/remoteKernel");++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);+ assert.equal(remoteOwnerPreferences.nodeIntegrationInSubFrames, false);+ const owner = new EventEmitter(), evidence = {blockedFramePaths: []};+ let beforeRequest;+ installRemoteOwnerGuards(owner, {webRequest: {onBeforeRequest(callback) { beforeRequest = callback; }}}, evidence);+ for (const [resourceType, expected] of [["mainFrame", false], ["script", false], ["subFrame", true], ["object", true]]) {+ let result;+ beforeRequest({resourceType, url: "https://fixture.invalid/" + resourceType}, value => { result = value; });+ assert.deepEqual(result, {cancel: expected});+ }+ for (const isMainFrame of [true, false]) {+ let prevented = false;+ owner.emit("will-frame-navigate", {isMainFrame, url: "https://fixture.invalid/frame",+ preventDefault() { prevented = true; }});+ assert.equal(prevented, !isMainFrame);+ }+ assert.deepEqual(evidence.blockedFramePaths, ["/subFrame", "/object", "/frame"]);+});++test("remote isolation verification fails if owner security, CSP or pre-reservation denial is missing", async () => {+ const origin = "http://127.0.0.1:1234";+ const html = fs.readFileSync(path.join(__dirname, "fixtures/map-webview-boundary/owner.html"), "utf8");+ const result = {origin: "null", require: "undefined", process: "undefined", ipc: "undefined", bridge: ["version"],+ parentOwner: false, topOwner: false, openerOwner: false, evalBlocked: true};+ const fixture = () => ({origin, kernelMode: "remote",+ owner: {getLastWebPreferences: () => remoteOwnerPreferences, session: {}, getOSProcessId: () => 1},+ guest: {getLastWebPreferences: () => guestPreferences, session: {isPersistent: () => false},+ getOSProcessId: () => 2, executeJavaScript: source => Promise.resolve(source.startsWith("fetch(") ? true : result)},+ evidence: {defaultHeaderCalls: 0, defaultGuestHeaderCalls: 0, guestNetworkRequests: 0, privateRequests: 0,+ ownerDocumentCSP: createRemoteDocumentContentSecurityPolicy(html, origin), frameRequests: 0, rejectedAttachments: 3}});+ await verifyIsolation(fixture());+ for (const weaken of [+ value => { value.owner.getLastWebPreferences = () => ownerPreferences; },+ value => { value.evidence.ownerDocumentCSP = ""; },+ value => { value.evidence.defaultHeaderCalls = 1; },+ value => { value.evidence.frameRequests = 1; },+ value => { value.evidence.rejectedAttachments = 0; },+ ]) {+ const value = fixture();+ weaken(value);+ await assert.rejects(verifyIsolation(value));+ }+});test("common isolation checks have a fixed deadline and clear their timer on success, failure and timeout", async t => {let fire, delay;@@ -90,13 +139,17 @@ test("corner fixture compiles production styles and visibility logic without a Gassert.doesNotThrow(() => new Function("exports", assets.visibility));});-test("real Electron webview clips rounded corners, retains attribution visibility and isolation, and stays behind DOM menus", {- skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY- ? "Real Electron verification requires DISPLAY or WAYLAND_DISPLAY; no unsafe startup fallback is allowed" : false,-}, async () => {- const env = {...process.env};- delete env.ELECTRON_RUN_AS_NODE;- const result = await promisify(execFile)(require("electron"), [path.join(__dirname, "fixtures/map-webview-boundary/harness.cjs"),- "--synthetic", "--verify"], {env, windowsHide: true, timeout: 90000});- assert.match(result.stdout, /Map webview prototype verification passed\./);-});+for (const kernelMode of ["local", "remote"]) {+ test(`real Electron ${kernelMode} webview retains owner policy, clips rounded corners and stays behind DOM menus`, {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY+ ? "Real Electron verification requires DISPLAY or WAYLAND_DISPLAY; no unsafe startup fallback is allowed" : false,+ }, async () => {+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ const flags = ["--synthetic", "--verify", ...(kernelMode === "remote" ? ["--remote"] : [])];+ const result = await promisify(execFile)(require("electron"), [path.join(__dirname, "fixtures/map-webview-boundary/harness.cjs"),+ ...flags], {env, windowsHide: true, timeout: 90000});+ assert.match(result.stdout, /Map webview prototype verification passed\./);+ if (kernelMode === "remote") assert.match(result.stdout, /Remote map owner policy: PASS\./);+ });+}diff --git a/app/webpack.map.js b/app/webpack.map.jsindex 5899919e9a..f7a95a982e 100644--- a/app/webpack.map.js+++ b/app/webpack.map.js@@ -1,31 +1,7 @@const fs = require("fs");const path = require("path");-const {fileURLToPath} = require("url");const webpack = require("webpack");const {EsbuildPlugin} = require("esbuild-loader");-const postcss = require("postcss");--// 只打包共享控件引用的内置主题变量,不加载用户 CSS、远程资源或可执行内容。-const menuTheme = (mode, controls, compilation) => {- const themePath = path.resolve(__dirname, "appearance/themes", mode === "dark" ? "midnight" : "daylight", "theme.css");- compilation.fileDependencies.add(themePath);- const variables = new Map();- postcss.parse(fs.readFileSync(themePath, "utf8")).walkRules(":root", rule => {- rule.walkDecls(declaration => variables.set(declaration.prop, declaration.value));- });- const names = new Set(Array.from(controls.matchAll(/var\((--[\w-]+)/g), match => match[1]));- const declarations = [];- for (const name of names) {- const value = variables.get(name);- if (!value) continue;- if (!/^[\w\s#.,%()"'/-]+$/.test(value) || /(?:url|expression|image|paint)\s*\(/i.test(value)) {- throw new Error("Unsafe built-in menu theme variable: " + name);- }- for (const dependency of value.matchAll(/var\((--[\w-]+)/g)) names.add(dependency[1]);- declarations.push(name + ": " + value + ";");- }- return ':root[data-theme="' + mode + '"] {\n' + declarations.join("\n") + "\n}\n";-};// 地图代码独立使用 web 目标,不共享 electron-renderer 的运行时或依赖包。class MapLibreAssetsPlugin {@@ -44,23 +20,6 @@ class MapLibreAssetsPlugin {compilation.fileDependencies.add(resolved);compilation.emitAsset(name, new webpack.sources.RawSource(fs.readFileSync(resolved)));}- // 可信菜单复用共享控件,运行时不加载 Sass 或远程样式。- const sass = require("sass");- const controls = sass.compileString('@use "../util/reset"; @use "../util/mixin"; @use "../business/block"; ' +- '@use "menu"; @use "text-field"; @use "button"; @use "counter"; @use "record-inbox"; ' +- '@include record-inbox.content("av-records-panel", 360px); ' +- ".av-records-panel-item .b3-menu__label { @include mixin.text-clamp(1); display: block; }", {- loadPaths: [path.resolve(__dirname, "src/assets/scss/component")],- logger: sass.Logger.silent,- });- for (const url of controls.loadedUrls) {- if (url.protocol === "file:") compilation.fileDependencies.add(fileURLToPath(url));- }- const menuCSSPath = path.resolve(__dirname, "electron/mapUnplaced/menu.css");- compilation.fileDependencies.add(menuCSSPath);- const references = controls.css + fs.readFileSync(menuCSSPath, "utf8");- const themes = ["light", "dark"].map(mode => menuTheme(mode, references, compilation)).join("");- compilation.emitAsset("unplaced-controls.css", new webpack.sources.RawSource(themes + controls.css));});});}