Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Keep maps visible during scrolling and preserve host startup budgets https://github.com/siyuan-note/siyuan/issues/20129

Daniel562cb2ac67d2
diff --git a/app/electron/mapHostManager.js b/app/electron/mapHostManager.js
index 1e925174cf..d994ff237b 100644
--- a/app/electron/mapHostManager.js
+++ b/app/electron/mapHostManager.js
@@ -15,6 +15,11 @@ const deniedResponse = () => new Response("Forbidden", {status: 403,
headers: {"Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store"}});
const withoutCredentials = (headers) => Object.fromEntries(Object.entries(headers || {})
.filter(([name]) => !["cookie", "authorization", "proxy-authorization"].includes(name.toLowerCase())));
+const clearMapSession = ses => {
+ for (const method of ["closeAllConnections", "clearStorageData", "clearAuthCache", "clearCache", "clearHostResolverCache"]) {
+ try { void Promise.resolve(ses[method]()).catch(() => {}); } catch (_error) { /* 继续清理其他会话状态。 */ }
+ }
+};
// 此会话从不向任何内核发送网络请求,包括未设置密码的本机内核。
const createMapSessionRouter = ({ses, origin, provider, appDir, readFile = fs.readFile, trackFetch = () => {}, report = () => {}}) => {
@@ -164,8 +169,7 @@ const createMapSessionRouter = ({ses, origin, provider, appDir, readFile = fs.re
for (const request of requests) request.abort();
requests.clear();
// Electron 没有 Session.destroy;清理状态后仍保留拒绝处理器,阻止残留请求恢复访问。
- void Promise.allSettled([ses.closeAllConnections(), ses.clearStorageData(), ses.clearAuthCache(),
- ses.clearCache(), ses.clearHostResolverCache()]);
+ clearMapSession(ses);
},
};
};
@@ -215,7 +219,9 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents
if (host && host.origin === owner.origin && host.frame === event.senderFrame) return host;
};
const sendOwner = (host, reply) => {
- if (!host.destroyed && !host.owner.isDestroyed()) host.owner.send("siyuan-map-reply", reply);
+ if (!host.destroyed && !host.owner.isDestroyed()) {
+ try { host.owner.send("siyuan-map-reply", reply); } catch (_error) { destroy(host); }
+ }
};
const hide = host => {
host.geometry = undefined;
@@ -234,24 +240,41 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents
for (const port of [host.port, host.transferredPort]) {
try { port?.close(); } catch (_error) { /* 端口已转移或关闭。 */ }
}
- if (!host.win.isDestroyed()) host.win.contentView.removeChildView(host.view);
+ try {
+ if (!host.win.isDestroyed()) host.win.contentView.removeChildView(host.view);
+ } catch (_error) { /* 移除失败也必须关闭渲染器。 */ }
// 移除视图不会销毁 WebContents,必须实际关闭 SDK 渲染器。
if (!host.view.webContents.isDestroyed()) {
- host.view.webContents.stop();
- host.view.webContents.close({waitForBeforeUnload: false});
+ try { host.view.webContents.stop(); } catch (_error) { /* 仍尝试关闭。 */ }
+ try { host.view.webContents.close({waitForBeforeUnload: false}); } catch (_error) { /* 渲染器可能已关闭。 */ }
}
mapContents.delete(host.view.webContents.id);
};
const fail = (host, code) => {
+ if (!host || host.destroyed) return;
sendOwner(host, {version: 1, instanceID: host.init.instanceID, type: "error", code});
destroy(host);
};
+ const setDeadline = (host, milliseconds) => {
+ clearTimeout(host.timer);
+ host.timer = setTimeout(() => {
+ const code = !host.loaded ? "hostDocumentLoadTimeout" : host.bootstrapped ? "hostSDKTimeout" : "hostBootstrapTimeout";
+ fail(host, code);
+ }, milliseconds);
+ host.timer.unref?.();
+ };
const listen = (host, emitter, name, listener) => {
- emitter.on(name, listener);
- host.listeners.push([emitter, name, listener]);
+ const guarded = (...args) => {
+ if (host.destroyed) return;
+ try { listener(...args); } catch (_error) { fail(host, "hostOperationFailed"); }
+ };
+ host.listeners.push([emitter, name, guarded]);
+ emitter.on(name, guarded);
};
const post = (host, message) => {
- if (!host.destroyed && host.port) host.port.postMessage(message);
+ if (!host.destroyed && host.port) {
+ try { host.port.postMessage(message); } catch (_error) { fail(host, "hostOperationFailed"); }
+ }
};
const applyGeometry = host => {
const geometry = host.geometry;
@@ -281,106 +304,121 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents
if (hasUnsafeMapSwitches(app.commandLine)) return {version: 1, instanceID: init.instanceID, error: "unsupportedEnvironment"};
const key = event.sender.id + ":" + init.instanceID;
if (hosts.has(key) || hosts.size >= 32 || [...hosts.values()].filter(host => host.owner === event.sender).length >= 8) {
- return {version: 1, instanceID: init.instanceID, error: "hostUnavailable"};
+ return {version: 1, instanceID: init.instanceID, error: "hostLimitReached"};
}
- const ses = session.fromPartition("siyuan-map-" + randomID(), {cache: false});
- let host, router, view;
+ let host, router, view, ses;
+ let creationFailure = "hostSetupFailed";
const report = code => {
if (!host || host.destroyed || !mapDiagnosticCodes.includes(code) || host.diagnostics.has(code)) return;
host.diagnostics.add(code);
sendOwner(host, {version: 1, instanceID: init.instanceID, type: "diagnostic", code});
};
try {
+ ses = session.fromPartition("siyuan-map-" + randomID(), {cache: false});
router = createMapSessionRouter({ses, origin: owner.origin, provider: init.provider, appDir, readFile, trackFetch, report});
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")}});
- } catch (_error) {
- router?.destroy();
- return {version: 1, instanceID: init.instanceID, error: "hostUnavailable", diagnostic: "hostSetupFailed"};
- }
- const contents = view.webContents;
- // 全局 web-contents-created 会安装外部打开链接处理器,必须在加载前替换为拒绝。
- contents.setWindowOpenHandler(() => ({action: "deny"}));
- mapContents.add(contents.id);
- host = {key, init, owner: event.sender, frame: event.senderFrame, win: owner.win, origin: owner.origin, diagnostics: new Set(),
- view, router, listeners: [], ids: new Set(), revision: -1, loaded: false, ready: false, bootstrapped: false, destroyed: false};
- hosts.set(key, host);
- const denyNavigation = event => event.preventDefault();
- for (const name of ["will-navigate", "will-frame-navigate", "will-redirect", "will-attach-webview"]) {
- listen(host, contents, name, denyNavigation);
- }
- listen(host, contents, "select-client-certificate", (event, _url, _certificates, callback) => { event.preventDefault(); callback(); });
- listen(host, contents, "login", (event, _details, _auth, callback) => { event.preventDefault(); callback(); });
- listen(host, contents, "certificate-error", (_event, _url, _error, _certificate, callback) => callback(false));
- listen(host, contents, "console-message", (event, _level, legacyMessage) => {
- for (const code of classifyMapConsoleMessage(event?.message ?? legacyMessage)) report(code);
- });
- listen(host, contents, "did-fail-load", () => report("documentLoadFailed"));
- listen(host, contents, "render-process-gone", () => fail(host, "hostUnavailable"));
- listen(host, contents, "destroyed", () => destroy(host));
- listen(host, event.sender, "destroyed", () => destroy(host));
- listen(host, event.sender, "render-process-gone", () => destroy(host));
- listen(host, event.sender, "did-start-navigation", details => {
- if (details.isMainFrame && !details.isSameDocument) destroy(host);
- });
- for (const name of ["resize", "hide", "minimize", "enter-full-screen", "leave-full-screen"]) {
- listen(host, owner.win, name, () => hide(host));
- }
- listen(host, owner.win, "blur", () => view.setVisible(false));
- for (const name of ["focus", "show", "restore"]) listen(host, owner.win, name, () => applyGeometry(host));
- listen(host, event.sender, "zoom-changed", () => hide(host));
- const nonce = randomID();
- const entryURL = owner.origin + "/stage/map/index.html?provider=" + init.provider + "#" + init.instanceID + ":" + nonce;
- listen(host, contents, "did-finish-load", () => {
- if (host.destroyed) return;
- if (host.loaded || contents.getURL() !== entryURL) { fail(host, "hostUnavailable"); return; }
- host.loaded = true;
- // 初始隐藏的 renderer 必须显式唤醒产帧,否则 SDK 的 load 会等待显示,而显示又等待 ready。
- contents.setBackgroundThrottling(false);
- applyGeometry(host);
- const {port1, port2} = new MessageChannelMain();
- host.port = port1;
- host.transferredPort = port2;
- port1.on("message", ({data}) => {
+ const contents = view.webContents;
+ host = {key, init, owner: event.sender, frame: event.senderFrame, win: owner.win, origin: owner.origin, diagnostics: new Set(),
+ view, router, listeners: [], ids: new Set(), revision: -1, loaded: false, ready: false, bootstrapped: false, destroyed: false};
+ hosts.set(key, host);
+ // 全局 web-contents-created 会安装外部打开链接处理器,必须在加载前替换为拒绝。
+ contents.setWindowOpenHandler(() => ({action: "deny"}));
+ mapContents.add(contents.id);
+ const denyNavigation = event => event.preventDefault();
+ for (const name of ["will-navigate", "will-frame-navigate", "will-redirect", "will-attach-webview"]) {
+ listen(host, contents, name, denyNavigation);
+ }
+ listen(host, contents, "select-client-certificate", (event, _url, _certificates, callback) => { event.preventDefault(); callback(); });
+ listen(host, contents, "login", (event, _details, _auth, callback) => { event.preventDefault(); callback(); });
+ listen(host, contents, "certificate-error", (_event, _url, _error, _certificate, callback) => callback(false));
+ listen(host, contents, "console-message", (event, _level, legacyMessage) => {
+ for (const code of classifyMapConsoleMessage(event?.message ?? legacyMessage)) report(code);
+ });
+ listen(host, contents, "did-fail-load", (_event, _code, _description, _url, isMainFrame) => {
+ if (isMainFrame === false) return;
+ report("documentLoadFailed");
+ fail(host, "hostDocumentLoadFailed");
+ });
+ listen(host, contents, "render-process-gone", () => fail(host, "hostRendererGone"));
+ listen(host, contents, "destroyed", () => fail(host, "hostDestroyed"));
+ listen(host, event.sender, "destroyed", () => destroy(host));
+ listen(host, event.sender, "render-process-gone", () => destroy(host));
+ listen(host, event.sender, "did-start-navigation", details => {
+ if (details.isMainFrame && !details.isSameDocument) destroy(host);
+ });
+ for (const name of ["resize", "hide", "minimize", "enter-full-screen", "leave-full-screen"]) {
+ listen(host, owner.win, name, () => hide(host));
+ }
+ listen(host, owner.win, "blur", () => view.setVisible(false));
+ for (const name of ["focus", "show", "restore"]) listen(host, owner.win, name, () => applyGeometry(host));
+ listen(host, event.sender, "zoom-changed", () => hide(host));
+ const nonce = randomID();
+ const entryURL = owner.origin + "/stage/map/index.html?provider=" + init.provider + "#" + init.instanceID + ":" + nonce;
+ listen(host, contents, "did-finish-load", () => {
if (host.destroyed) return;
- const reply = parseMapReply(data, init.instanceID);
- if (!reply) return;
- if (reply.type === "bootstrapReady" && !host.bootstrapped) {
- host.bootstrapped = true;
- post(host, init);
- init.credentials = {};
- } else if (reply.type === "ready" && host.bootstrapped && !host.ready) {
- host.ready = true;
- clearTimeout(host.timer);
- if (host.points) post(host, host.points);
- post(host, {version: 1, instanceID: init.instanceID, type: "theme", theme: init.theme});
- if (host.pendingFit) post(host, {version: 1, instanceID: init.instanceID, type: "fit"});
+ try {
+ 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);
- contents.setBackgroundThrottling(true);
- sendOwner(host, reply);
- } else if (reply.type === "markerClick" && host.ready && reply.revision === host.revision && host.ids.has(reply.id)) {
- sendOwner(host, reply);
- } else if (reply.type === "error") fail(host, reply.code);
+ const {port1, port2} = new MessageChannelMain();
+ host.port = port1;
+ host.transferredPort = port2;
+ port1.on("message", ({data}) => {
+ if (host.destroyed) return;
+ const reply = parseMapReply(data, init.instanceID);
+ if (!reply) return;
+ try {
+ if (reply.type === "bootstrapReady" && !host.bootstrapped) {
+ host.bootstrapped = true;
+ // SDK 脚本和地图完成分别最多等待 20 秒,启动耗时不占用这两个阶段的预算。
+ setDeadline(host, 45000);
+ post(host, init);
+ init.credentials = {};
+ } else if (reply.type === "ready" && host.bootstrapped && !host.ready) {
+ host.ready = true;
+ clearTimeout(host.timer);
+ if (host.points) post(host, host.points);
+ post(host, {version: 1, instanceID: init.instanceID, type: "theme", theme: init.theme});
+ if (host.pendingFit) post(host, {version: 1, instanceID: init.instanceID, type: "fit"});
+ if (host.destroyed) return;
+ applyGeometry(host);
+ if (host.destroyed) return;
+ contents.setBackgroundThrottling(true);
+ sendOwner(host, reply);
+ } else if (reply.type === "markerClick" && host.ready && reply.revision === host.revision && host.ids.has(reply.id)) {
+ sendOwner(host, reply);
+ } else if (reply.type === "error") {
+ fail(host, reply.code === "hostUnavailable" ?
+ host.bootstrapped ? "hostOperationFailed" : "hostBootstrapFailed" : reply.code);
+ }
+ } catch (_error) { fail(host, "hostOperationFailed"); }
+ });
+ port1.on("close", () => fail(host, "hostPortClosed"));
+ port1.start();
+ contents.postMessage("siyuan-map-port", {version: 1, instanceID: init.instanceID, nonce, provider: init.provider}, [port2]);
+ } catch (_error) { fail(host, "hostPortSetupFailed"); }
});
- port1.on("close", () => fail(host, "hostUnavailable"));
- port1.start();
- contents.postMessage("siyuan-map-port", {version: 1, instanceID: init.instanceID, nonce, provider: init.provider}, [port2]);
- });
- host.timer = setTimeout(() => {
- report(host.bootstrapped ? "sdkTimeout" : "bootstrapTimeout");
- fail(host, "hostUnavailable");
- }, 30000);
- host.timer.unref?.();
- try {
+ setDeadline(host, 30000);
+ creationFailure = "hostAttachFailed";
view.setVisible(false);
// DOM 暂时不可见时也能完成初始化;此占位视图始终隐藏,不会覆盖编辑器。
view.setBounds({x: 0, y: 0, width: 1, height: 1});
owner.win.contentView.addChildView(view);
- void contents.loadURL(entryURL).catch(() => { report("documentLoadFailed"); fail(host, "hostUnavailable"); });
- } catch (_error) { fail(host, "hostUnavailable"); }
+ void contents.loadURL(entryURL).catch(() => { report("documentLoadFailed"); fail(host, "hostDocumentLoadFailed"); });
+ } catch (_error) {
+ init.credentials = {};
+ if (host) fail(host, creationFailure);
+ else if (router) router.destroy();
+ else if (ses) clearMapSession(ses);
+ return {version: 1, instanceID: init.instanceID, error: creationFailure};
+ }
return {version: 1, instanceID: init.instanceID};
});
ipcMain.on("siyuan-map-command", (event, value) => {
@@ -401,10 +439,12 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents
ipcMain.on("siyuan-map-geometry", (event, value) => {
const host = getHost(event, value);
if (!host) return;
- const geometry = parseMapGeometry(value, host.owner.getZoomFactor(), host.win.getContentBounds());
- if (!geometry?.visible) { hide(host); return; }
- host.geometry = geometry;
- applyGeometry(host);
+ try {
+ const geometry = parseMapGeometry(value, host.owner.getZoomFactor(), host.win.getContentBounds());
+ 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));
diff --git a/app/electron/mapHostManager.test.js b/app/electron/mapHostManager.test.js
index fb7cce32a3..1d62004936 100644
--- a/app/electron/mapHostManager.test.js
+++ b/app/electron/mapHostManager.test.js
@@ -138,8 +138,12 @@ test("destroy aborts in-flight provider requests, clears session state and leave
assert.equal(ses.cleanup.length, 5);
});
-const setup = () => {
+const setup = (initialFault) => {
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 app = Object.assign(new EventEmitter(), {commandLine: {
hasSwitch: name => switches.has(name), getSwitchValue: name => switches.get(name),
@@ -151,37 +155,53 @@ const setup = () => {
const win = Object.assign(new EventEmitter(), {webContents: owner, destroyed: false, focused: true, children: [],
isDestroyed() { return this.destroyed; }, isFocused() { return this.focused; },
isVisible: () => true, isMinimized: () => false, getContentBounds: () => ({width: 1000, height: 800})});
- win.contentView = {addChildView: view => win.children.push(view), removeChildView: view => { win.children = win.children.filter(item => item !== view); }};
+ win.contentView = {addChildView: view => { fault("attach"); win.children.push(view); },
+ removeChildView: view => { fault("detach"); win.children = win.children.filter(item => item !== view); }};
const target = {origin};
let initialized = true;
const manager = createMapHostManager({app, appDir: "/app", getTarget: id => id === 1 ? target : undefined,
isInitialized: () => initialized, readFile: async () => Buffer.from("asset"), randomID: () => (++sequence).toString(16).padStart(48, "0"),
ipcMain: {handle: (name, handler) => { handlers[name] = handler; }, on: (name, handler) => { handlers[name] = handler; }},
BrowserWindow: {fromWebContents: value => value === owner ? win : undefined},
- session: {fromPartition(partition, options) { const ses = createSession(); Object.assign(ses, {partition, options}); sessions.push(ses); return ses; }},
+ session: {fromPartition(partition, options) {
+ fault("session");
+ const ses = createSession(); Object.assign(ses, {partition, options}); sessions.push(ses);
+ const setPermission = ses.setPermissionRequestHandler;
+ 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) { this.openHandler = handler; order.push("openHandler"); },
+ setWindowOpenHandler(handler) { fault("openHandler"); this.openHandler = handler; order.push("openHandler"); },
getURL() { return this.url; },
- async loadURL(url) { this.url = url; order.push("load"); },
- postMessage(...args) { this.transferred = args; },
+ loadURL(url) {
+ fault("loadSync"); this.url = url; order.push("load");
+ 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() { this.stopped = true; },
+ 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; }
- setBounds(value) { this.bounds = value; }
+ setBounds(value) { fault("bounds"); this.bounds = value; }
},
MessageChannelMain: class {
constructor() {
- const port = () => Object.assign(new EventEmitter(), {sent: [], postMessage(value) { this.sent.push(structuredClone(value)); },
- start() { this.started = true; }, close() { this.closed = true; }});
+ fault("channel");
+ const port = () => Object.assign(new EventEmitter(), {sent: [],
+ on(...args) { fault("portListener"); return EventEmitter.prototype.on.apply(this, args); },
+ postMessage(value) { fault("portPost"); this.sent.push(structuredClone(value)); },
+ start() { fault("portStart"); this.started = true; }, close() { this.closed = true; }});
this.port1 = port(); this.port2 = port(); channels.push(this);
}
},
@@ -191,7 +211,7 @@ const setup = () => {
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");
- return {manager, app, handlers, sessions, views, channels, order, switches, owner, win, target, event, create, command, reply, load,
+ return {manager, app, handlers, sessions, views, channels, order, switches, owner, win, target, event, create, command, reply, load, faults,
setInitialized(value) { initialized = value; }};
};
@@ -368,7 +388,7 @@ test("destroy and owner navigation close real contents, ports, requests and sess
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, "hostUnavailable"); assert.equal(s.views.length, 1);
+ s.switches.clear(); s.create(); assert.equal(s.create().error, "hostLimitReached"); assert.equal(s.views.length, 1);
s.manager.destroyAll();
});
@@ -422,7 +442,7 @@ test("navigation, redirects, client certificates, login and renderer failure are
assert.equal(prevented, true); assert.equal(answered, true);
}
wc.emit("render-process-gone"); assert.equal(wc.destroyed, true);
- assert.equal(s.owner.sent[0][1].code, "hostUnavailable");
+ assert.equal(s.owner.sent[0][1].code, "hostRendererGone");
});
test("main-process provider fetch cannot select client certificates or authenticate, including null WebContents", async () => {
@@ -450,7 +470,128 @@ test("a closed runtime port destroys the map instead of retaining a live orphan
const s = setup(); s.create(); s.load();
s.channels[0].port1.emit("close");
assert.equal(s.views[0].webContents.destroyed, true);
- assert.equal(s.owner.sent[0][1].code, "hostUnavailable");
+ assert.equal(s.owner.sent[0][1].code, "hostPortClosed");
+});
+
+test("bootstrap and SDK receive separate deadlines and duplicate bootstrap cannot extend SDK lifetime", t => {
+ t.mock.timers.enable({apis: ["setTimeout"]});
+ const s = setup(); 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.deepEqual(s.owner.sent, []);
+ s.reply({type: "bootstrapReady"});
+ t.mock.timers.tick(5999);
+ assert.equal(s.views[0].webContents.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.channels[0].port1.closed, true);
+});
+
+test("document and bootstrap timeouts have distinct final codes and successful ready clears all deadlines", t => {
+ t.mock.timers.enable({apis: ["setTimeout"]});
+ for (const loaded of [false, true]) {
+ const s = setup(); 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);
+ }
+ const s = setup(); 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);
+ 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);
+ 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(JSON.stringify(s.owner.sent).includes("secret"), false, point);
+ s.faults.clear();
+ assert.deepEqual(s.create(), envelope, "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();
+ 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);
+});
+
+test("unexpected document, reload, destruction and bootstrap rejection retain their final failure reason", () => {
+ const cases = [
+ ["hostDocumentMismatch", s => { s.views[0].webContents.url += "unexpected"; s.load(); }],
+ ["hostDocumentReloaded", s => { s.load(); s.load(); }],
+ ["hostDestroyed", s => { s.views[0].webContents.destroyed = true; s.views[0].webContents.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);
+ 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);
+ 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", () => {
+ for (const point of ["channel", "portListener", "portStart", "portTransfer"]) {
+ const s = setup(); 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);
+ 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();
+ 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");
+ }
+});
+
+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");
+ 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.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", () => {
diff --git a/app/electron/mapHostPolicy.js b/app/electron/mapHostPolicy.js
index a75316018a..0b8f59d3e2 100644
--- a/app/electron/mapHostPolicy.js
+++ b/app/electron/mapHostPolicy.js
@@ -97,7 +97,11 @@ const parseMapReply = (value, instanceID) => {
}
if (value.type === "error" && ["unsupportedEnvironment", "missingCredentials", "invalidConfiguration",
"hostUnavailable", "sdkUnavailable", "mapUnavailable", "sdkScriptLoadFailed", "sdkCallbackTimeout",
- "sdkGlobalMissing", "mapCreationFailed", "mapReadyTimeout"].includes(value.code)) {
+ "sdkGlobalMissing", "mapCreationFailed", "mapReadyTimeout", "hostLimitReached", "hostSetupFailed",
+ "hostAttachFailed", "hostDocumentLoadFailed", "hostDocumentLoadTimeout", "hostDocumentReloaded",
+ "hostDocumentMismatch", "hostRendererGone", "hostDestroyed", "hostPortSetupFailed", "hostPortClosed",
+ "hostBootstrapFailed", "hostBootstrapTimeout", "hostSDKTimeout", "hostOperationFailed", "hostCreateRejected",
+ "hostCreateInvalidResponse", "hostReadyTimeout", "hostOwnerSetupFailed"].includes(value.code)) {
return {...base, type: "error", code: value.code};
}
};
diff --git a/app/electron/mapHostPolicy.test.js b/app/electron/mapHostPolicy.test.js
index 17e0c26e98..73cf978e2e 100644
--- a/app/electron/mapHostPolicy.test.js
+++ b/app/electron/mapHostPolicy.test.js
@@ -76,6 +76,21 @@ test("map loading failures retain only fixed stage codes across the desktop boun
assert.equal(parseMapReply({...envelope, type: "error", code: "https://private.invalid/?key=secret"}, instanceID), undefined);
});
+test("host failure replies preserve fixed reasons and reject invented or foreign failure codes", () => {
+ for (const code of ["hostLimitReached", "hostSetupFailed", "hostAttachFailed", "hostDocumentLoadFailed",
+ "hostDocumentLoadTimeout", "hostDocumentReloaded", "hostDocumentMismatch", "hostRendererGone", "hostDestroyed",
+ "hostPortSetupFailed", "hostPortClosed", "hostBootstrapFailed", "hostBootstrapTimeout", "hostSDKTimeout",
+ "hostOperationFailed", "hostCreateRejected", "hostCreateInvalidResponse", "hostReadyTimeout", "hostOwnerSetupFailed"]) {
+ const reply = {...envelope, type: "error", code};
+ assert.deepEqual(parseMapReply({...reply, error: "private", url: "https://private.invalid/?key=secret"}, instanceID), reply);
+ assert.equal(parseMapReply(reply, "other"), undefined);
+ assert.equal(parseMapReply({...reply, version: 2}, instanceID), undefined);
+ }
+ for (const code of ["hostSecret", "hostLimitReached\nprivate", "https://private.invalid/?key=secret", null, {}]) {
+ assert.equal(parseMapReply({...envelope, type: "error", code}, instanceID), undefined);
+ }
+});
+
test("map creation fails closed for effective process security bypasses", () => {
const commandLine = switches => ({hasSwitch: name => switches.has(name), getSwitchValue: name => switches.get(name)});
assert.equal(hasUnsafeMapSwitches(commandLine(new Map())), false);
diff --git a/app/src/protyle/render/av/map/desktopTransport.test.ts b/app/src/protyle/render/av/map/desktopTransport.test.ts
index 3d51bd3450..01f1ae9c02 100644
--- a/app/src/protyle/render/av/map/desktopTransport.test.ts
+++ b/app/src/protyle/render/av/map/desktopTransport.test.ts
@@ -33,12 +33,14 @@ const fixture = (warnings: unknown[][] = []) => {
const listeners = new Map<string, (...args: any[]) => void>();
const domListeners = new Map<string, () => void>();
const frames = new Map<number, () => void>();
+ const timers = new Map<number, {callback: () => void; delay: number}>();
let resolveCreate: (value: unknown) => void;
- let now = 0, nextFrame = 0;
+ let rejectCreate: (value: unknown) => void;
+ let now = 0, nextFrame = 0, nextTimer = 0;
const ipc = {
invoke: (name: string, value: unknown) => {
calls.push([name, value]);
- return new Promise((resolve) => { resolveCreate = resolve; });
+ return new Promise((resolve, reject) => { resolveCreate = resolve; rejectCreate = reject; });
},
send: (name: string, value: unknown) => calls.push([name, value]),
on: (name: string, fn: (...args: any[]) => void) => listeners.set(name, fn),
@@ -50,7 +52,11 @@ const fixture = (warnings: unknown[][] = []) => {
addEventListener: (name: string, fn: () => void) => domListeners.set(name, fn),
removeEventListener: (name: string) => domListeners.delete(name)};
const scope = {crypto: webcrypto, innerWidth: 1000, innerHeight: 800, performance: {now: () => now},
- setTimeout: () => 1, clearTimeout() {},
+ setTimeout: (callback: () => void, delay: number) => {
+ timers.set(++nextTimer, {callback, delay});
+ return nextTimer;
+ },
+ clearTimeout: (id: number) => timers.delete(id),
requestAnimationFrame: (fn: () => void) => { frames.set(++nextFrame, fn); return nextFrame; },
cancelAnimationFrame: (id: number) => frames.delete(id),
addEventListener: (name: string, fn: () => void) => domListeners.set(name, fn),
@@ -58,7 +64,7 @@ const fixture = (warnings: unknown[][] = []) => {
getComputedStyle: () => ({display: "block", visibility: "visible", opacity: "1", overflowX: "visible", overflowY: "visible",
getPropertyValue: () => ""})};
doc.defaultView = scope;
- const container: any = {ownerDocument: doc, isConnected: true, parentElement: null,
+ const container: any = {ownerDocument: doc, isConnected: true, parentElement: null, closest: (): HTMLElement | null => null,
getClientRects: () => [rect], getBoundingClientRect: () => rect, contains: (target: unknown) => target === container};
const errors: string[] = [], clicks: unknown[] = [];
let ready = 0;
@@ -67,11 +73,15 @@ const fixture = (warnings: unknown[][] = []) => {
credentials: {apiKey: "do-not-send", extra: "private"}, onError: (value: string) => errors.push(value),
onMarkerClick: (...args: unknown[]) => clicks.push(args), onReady: () => ready++});
const instanceID = calls[0][1].instanceID;
- return {host, calls, listeners, domListeners, frames, errors, clicks, doc, container, rect,
+ return {host, calls, listeners, domListeners, frames, timers, errors, clicks, doc, container, rect,
ready: () => ready,
reply: (value: object) => listeners.get("siyuan-map-reply")?.({}, {version: 1, instanceID, ...value}),
- created: async () => {
- resolveCreate({version: 1, instanceID});
+ rejected: async () => {
+ rejectCreate(new Error("https://private.invalid/?key=secret"));
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ },
+ created: async (overrides: object = {}) => {
+ resolveCreate({version: 1, instanceID, ...overrides});
await new Promise<void>((resolve) => setImmediate(resolve));
},
advance: (milliseconds = 150) => {
@@ -83,6 +93,49 @@ const fixture = (warnings: unknown[][] = []) => {
};
describe("desktop map transport", () => {
+ it("preserves fixed creation failures and never logs rejected IPC details", async () => {
+ for (const code of ["hostLimitReached", "hostSetupFailed", "hostAttachFailed"] as const) {
+ const warnings: unknown[][] = [];
+ const f = fixture(warnings);
+ await f.created({error: code, details: "https://private.invalid/?key=secret"});
+ assert.deepEqual(f.errors, [code]);
+ assert.deepEqual(warnings, [["Database map failed:", code]]);
+ assert.equal(f.timers.size, 0);
+ }
+ for (const response of [{version: 2}, {instanceID: "other"}, {error: "secret"}]) {
+ const f = fixture();
+ await f.created(response);
+ assert.deepEqual(f.errors, ["hostCreateInvalidResponse"]);
+ }
+ const warnings: unknown[][] = [];
+ const f = fixture(warnings);
+ await f.rejected();
+ assert.deepEqual(f.errors, ["hostCreateRejected"]);
+ assert.deepEqual(warnings, [["Database map failed:", "hostCreateRejected"]]);
+ assert.equal(f.listeners.size, 0);
+ });
+ it("lets main report a late SDK failure before the owner fallback and cleans the fallback", async () => {
+ const f = fixture();
+ assert.deepEqual([...f.timers.values()].map((timer) => timer.delay), [90000]);
+ f.reply({type: "error", code: "hostSDKTimeout"});
+ assert.deepEqual(f.errors, ["hostSDKTimeout"]);
+ assert.equal(f.timers.size, 0);
+ await f.created();
+ assert.equal(f.frames.size, 0, "late create must not revive a failed host");
+ const stalled = fixture();
+ const callback = [...stalled.timers.values()][0].callback;
+ callback();
+ assert.deepEqual(stalled.errors, ["hostReadyTimeout"]);
+ assert.equal(stalled.listeners.size, 0);
+ assert.equal(stalled.timers.size, 0);
+ await stalled.created();
+ assert.equal(stalled.frames.size, 0);
+ const disposed = fixture();
+ const late = [...disposed.timers.values()][0].callback;
+ disposed.host.destroy();
+ late();
+ assert.deepEqual(disposed.errors, []);
+ });
it("logs only allowlisted diagnostics for the current instance and ignores provider text", () => {
const warnings: unknown[][] = [];
const f = fixture(warnings);
@@ -178,7 +231,7 @@ describe("desktop map transport", () => {
f.advance();
assert.equal(lastGeometry().visible, true);
f.domListeners.get("scroll")();
- assert.equal(lastGeometry().visible, false);
+ assert.equal(lastGeometry().visible, true);
f.advance();
assert.equal(lastGeometry().visible, true);
f.doc.elementFromPoint = () => ({});
@@ -208,6 +261,125 @@ describe("desktop map transport", () => {
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: 123, width: 400, height: 237});
+ assert.deepEqual(lastGeometry().logicalSize, {width: 400, height: 300});
+ assert.deepEqual(lastGeometry().crop, {x: 0, y: 63});
+ f.rect.y = 40;
+ f.domListeners.get("scroll")();
+ assert.deepEqual(lastGeometry().bounds, {x: 10, y: 123, width: 400, height: 217});
+ tabsRect.height += 5;
+ callbacks[0]();
+ assert.deepEqual(lastGeometry().bounds, {x: 10, y: 128, width: 400, height: 212});
+ assert.deepEqual(lastGeometry().crop, {x: 0, y: 88});
+ 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> = [];
diff --git a/app/src/protyle/render/av/map/desktopTransport.ts b/app/src/protyle/render/av/map/desktopTransport.ts
index 863b7bf111..8e85ba910b 100644
--- a/app/src/protyle/render/av/map/desktopTransport.ts
+++ b/app/src/protyle/render/av/map/desktopTransport.ts
@@ -3,7 +3,7 @@ import {ipcRenderer} from "electron";
/// #endif
import type {AVMapHost, AVMapHostOptions} from "./host";
import {
- AV_MAP_PROTOCOL_VERSION, AVMapCommand, AVMapErrorCode, AVMapPoint, isAVMapProvider, isAVMapRevision,
+ AV_MAP_PROTOCOL_VERSION, AVMapCommand, AVMapErrorCode, AVMapPoint, isAVMapHostErrorCode, isAVMapProvider, isAVMapRevision,
isAVMapTheme, parseAVMapReply, sanitizeAVMapCredentials, sanitizeAVMapPoints,
} from "./protocol";
@@ -109,6 +109,18 @@ const readGeometry = (container: HTMLElement): MapGeometry => {
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[] = [];
// These are actual application overlay roots, not guesses based on arbitrary z-index values.
doc.querySelectorAll<HTMLElement>(".b3-menu, .b3-dialog, .av__panel, .protyle-util, .protyle-toolbar, .block__popover, [popover]")
@@ -144,7 +156,7 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
let instanceID = "", revision = -1, theme = options.theme;
let points: AVMapPoint[] = [];
let ids = new Set<string>();
- let frame = 0, timeout = 0, stableAfter = 0;
+ let frame = 0, timeout = 0, stableAfter = 0, scrollingUntil = 0;
let lastGeometry = "", sentGeometry = "";
let observer: MutationObserver;
let resizeObserver: ResizeObserver;
@@ -172,10 +184,23 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
const key = JSON.stringify(next);
if (key !== lastGeometry) {
lastGeometry = key;
- invalidate();
+ if (scope.performance.now() < scrollingUntil) {
+ stableAfter = 0;
+ geometry(next);
+ } else {
+ invalidate();
+ }
}
return next;
};
+ const onScroll = () => {
+ if (!destroyed && scope) {
+ // 滚动和同轮固定栏布局更新都使用完整遮挡检查后的最新裁剪,不等待滚动停止。
+ scrollingUntil = scope.performance.now() + 120;
+ stableAfter = 0;
+ geometry(checkGeometry());
+ }
+ };
const tick = () => {
if (destroyed) {
return;
@@ -199,7 +224,7 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
scope?.clearTimeout(timeout);
scope?.cancelAnimationFrame(frame);
scope?.removeEventListener("pagehide", destroy);
- scope?.removeEventListener("scroll", invalidate, true);
+ scope?.removeEventListener("scroll", onScroll, true);
scope?.removeEventListener("resize", invalidate);
scope?.removeEventListener("focus", invalidate);
container.ownerDocument.removeEventListener("visibilitychange", invalidate);
@@ -283,21 +308,33 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
instanceID = Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("");
ipc.on("siyuan-map-reply", onReply);
scope.addEventListener("pagehide", destroy, {once: true});
- timeout = scope.setTimeout(() => fail("hostUnavailable"), 30000);
- const reply = await ipc.invoke("siyuan-map-create", {...envelope(), provider: options.provider,
- credentials: sanitizeAVMapCredentials(options.credentials, options.provider), theme});
+ // 主进程先等待引导 30 秒,再为 SDK 两个 20 秒阶段保留 45 秒;这里只做更晚的失联兜底。
+ timeout = scope.setTimeout(() => fail("hostReadyTimeout"), 90000);
+ let reply: {version?: number; instanceID?: string; error?: unknown; diagnostic?: unknown};
+ try {
+ reply = await ipc.invoke("siyuan-map-create", {...envelope(), provider: options.provider,
+ credentials: sanitizeAVMapCredentials(options.credentials, options.provider), theme});
+ } catch (_error) {
+ fail("hostCreateRejected");
+ return;
+ }
// Creation can finish after disposal. Tell main again, even if the first destroy arrived too early.
if (destroyed) {
ipc.send("siyuan-map-destroy", envelope());
return;
}
- if (reply?.version !== AV_MAP_PROTOCOL_VERSION || reply.instanceID !== instanceID || reply.error) {
+ if (reply?.version !== AV_MAP_PROTOCOL_VERSION || reply.instanceID !== instanceID) {
+ fail("hostCreateInvalidResponse");
+ return;
+ }
+ if (reply.error) {
logMapDiagnostic(reply?.diagnostic);
- fail(reply?.error === "unsupportedEnvironment" ? "unsupportedEnvironment" : "hostUnavailable");
+ fail(reply.error === "unsupportedEnvironment" ? "unsupportedEnvironment" :
+ isAVMapHostErrorCode(reply.error) ? reply.error : "hostCreateInvalidResponse");
return;
}
created = true;
- scope.addEventListener("scroll", invalidate, true);
+ scope.addEventListener("scroll", onScroll, true);
scope.addEventListener("resize", invalidate);
// BrowserWindow focus is enforced in main. DOM blur also fires when the map view gains focus.
scope.addEventListener("focus", invalidate);
@@ -314,6 +351,6 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
resizeObserver.observe(container);
tick();
};
- void start().catch(() => fail("hostUnavailable"));
+ void start().catch(() => fail("hostOwnerSetupFailed"));
return host;
};
diff --git a/app/src/protyle/render/av/map/host.test.ts b/app/src/protyle/render/av/map/host.test.ts
index 9ca5b8c359..089f37aee0 100644
--- a/app/src/protyle/render/av/map/host.test.ts
+++ b/app/src/protyle/render/av/map/host.test.ts
@@ -51,6 +51,8 @@ describe("map host boundary", () => {
const attributes: Record<string, string> = {};
const listeners = new Map<string, (event?: unknown) => void>();
const transfers: any[] = [];
+ const timers = new Map<number, {callback: () => void; delay: number}>();
+ let nextTimer = 0;
const iframe = {
src: "", style: {}, removed: false, credentialless: false,
contentWindow: {postMessage: (...args: any[]) => transfers.push(args)},
@@ -60,7 +62,11 @@ describe("map host boundary", () => {
const scope = {
location: {protocol: "https:", origin: "https://fixture.invalid"}, navigator: {userAgent: "Chromium"}, crypto: webcrypto,
HTMLIFrameElement: {prototype: {credentialless: false}},
- clearTimeout() {}, setTimeout() { return 1; },
+ clearTimeout(id: number) { timers.delete(id); },
+ setTimeout(callback: () => void, delay: number) {
+ timers.set(++nextTimer, {callback, delay});
+ return nextTimer;
+ },
addEventListener: (name: string, listener: (event?: unknown) => void) => listeners.set(name, listener),
removeEventListener: (name: string) => listeners.delete(name),
};
@@ -73,6 +79,7 @@ describe("map host boundary", () => {
});
cleanups.push(host.destroy);
await new Promise<void>((resolve) => setImmediate(resolve));
+ assert.deepEqual([...timers.values()].map((timer) => timer.delay), [30000]);
assert.equal(attributes.sandbox, "allow-scripts allow-same-origin");
assert.equal(iframe.credentialless, true);
assert.equal(iframe.src.split("#")[0], "/stage/map/wrapper.html?provider=openfreemap");
@@ -94,6 +101,8 @@ describe("map host boundary", () => {
assert.deepEqual(transfers[0][0], {version: 1, instanceID, nonce, type: "prepare", nativeBoundary: false});
onMessage({...handshake, data: {...handshake.data, type: "bootstrapReady"}});
assert.equal(channels.length, 1);
+ assert.deepEqual([...timers.values()].map((timer) => timer.delay), [45000],
+ "bootstrap completion starts a fresh budget covering both 20-second SDK phases");
assert.equal(listeners.has("message"), false);
onMessage(handshake);
assert.equal(channels.length, 1);
@@ -106,6 +115,7 @@ describe("map host boundary", () => {
assert.equal(ready, 0);
reply({type: "ready"});
reply({type: "ready"});
+ assert.equal(timers.size, 0, "ready clears the SDK deadline");
assert.equal(ready, 1);
assert.deepEqual(port.messages.find((message) => message.type === "setPoints").points, [point]);
assert.equal(port.messages.filter((message) => message.type === "fit").length, 1);
diff --git a/app/src/protyle/render/av/map/host.ts b/app/src/protyle/render/av/map/host.ts
index 8b5d7cdc50..c1faa0d859 100644
--- a/app/src/protyle/render/av/map/host.ts
+++ b/app/src/protyle/render/av/map/host.ts
@@ -98,13 +98,16 @@ export const createAVMapHost = (container: HTMLElement, options: AVMapHostOption
return;
}
if (preparing && isAVMapBootstrapMessage(event.data, "bootstrapError", instanceID, nonce)) {
- fail("hostUnavailable");
+ fail("hostBootstrapFailed");
return;
}
if (!preparing || !isAVMapBootstrapMessage(event.data, "bootstrapReady", instanceID, nonce)) {
return;
}
scope.removeEventListener("message", onMessage);
+ // SDK 脚本和地图初始化各有 20 秒预算,不能被之前的引导计时提前截断。
+ scope.clearTimeout(timeout);
+ timeout = scope.setTimeout(() => fail("hostSDKTimeout"), 45000);
const channel = new MessageChannel();
port = channel.port1;
port.onmessage = (replyEvent) => {
@@ -199,10 +202,10 @@ export const createAVMapHost = (container: HTMLElement, options: AVMapHostOption
iframe.title = options.title || "";
iframe.style.cssText = "width:100%;height:100%;border:0;display:block";
iframe.src = `/stage/map/wrapper.html?provider=${options.provider}#${instanceID}:${nonce}`;
- iframe.addEventListener("error", () => fail("hostUnavailable"), {once: true});
+ iframe.addEventListener("error", () => fail("hostDocumentLoadFailed"), {once: true});
scope.addEventListener("message", onMessage);
scope.addEventListener("pagehide", destroy, {once: true});
- timeout = scope.setTimeout(() => fail("hostUnavailable"), 30000);
+ timeout = scope.setTimeout(() => fail("hostBootstrapTimeout"), 30000);
container.appendChild(iframe);
if (typeof ResizeObserver !== "undefined") {
observer = new ResizeObserver(host.resize);
diff --git a/app/src/protyle/render/av/map/protocol.test.ts b/app/src/protyle/render/av/map/protocol.test.ts
index bdba8dd40b..6f92951e15 100644
--- a/app/src/protyle/render/av/map/protocol.test.ts
+++ b/app/src/protyle/render/av/map/protocol.test.ts
@@ -2,7 +2,7 @@ import * as assert from "node:assert/strict";
import {describe, it} from "node:test";
import {
AV_MAP_ATTRIBUTION_LINKS, AV_MAP_MERCATOR_MAX_LATITUDE, AVMapLoadError, AVMapProvider, getAVMapLoadErrorCode,
- isAVMapHandshake, isAVMapProjectionSupported,
+ isAVMapHandshake, isAVMapHostErrorCode, isAVMapProjectionSupported,
parseAVMapCommand, parseAVMapReply, sanitizeAVMapCredentials, sanitizeAVMapPoints,
} from "./protocol";
@@ -104,4 +104,22 @@ describe("isolated map protocol", () => {
assert.equal(getAVMapLoadErrorCode({code: "mapCreationFailed"}), undefined);
assert.equal(getAVMapLoadErrorCode(Object.assign(new AVMapLoadError("mapCreationFailed"), {code: "secret"})), undefined);
});
+ it("preserves only fixed host failures across the owner and main process boundaries", () => {
+ const {parseMapReply} = require("../../../../../electron/mapHostPolicy");
+ for (const code of ["hostLimitReached", "hostSetupFailed", "hostAttachFailed", "hostDocumentLoadFailed",
+ "hostDocumentLoadTimeout", "hostDocumentReloaded", "hostDocumentMismatch", "hostRendererGone", "hostDestroyed",
+ "hostPortSetupFailed", "hostPortClosed", "hostBootstrapFailed", "hostBootstrapTimeout", "hostSDKTimeout",
+ "hostOperationFailed", "hostCreateRejected", "hostCreateInvalidResponse", "hostReadyTimeout", "hostOwnerSetupFailed"]) {
+ const reply = {version: 1, instanceID: "one", type: "error", code};
+ const input = {...reply, message: "https://private.invalid/?key=secret", stack: "secret"};
+ assert.equal(isAVMapHostErrorCode(code), true);
+ assert.deepEqual(parseAVMapReply(input, "one"), reply);
+ assert.deepEqual(parseMapReply(input, "one"), reply);
+ assert.equal(parseAVMapReply(input, "other"), undefined);
+ }
+ for (const code of ["hostSecret", "https://private.invalid/?key=secret", {}, null]) {
+ assert.equal(isAVMapHostErrorCode(code), false);
+ assert.equal(parseAVMapReply({version: 1, instanceID: "one", type: "error", code}, "one"), undefined);
+ }
+ });
});
diff --git a/app/src/protyle/render/av/map/protocol.ts b/app/src/protyle/render/av/map/protocol.ts
index 1983b1db1d..22197452ce 100644
--- a/app/src/protyle/render/av/map/protocol.ts
+++ b/app/src/protyle/render/av/map/protocol.ts
@@ -7,8 +7,22 @@ export type AVMapTheme = "light" | "dark";
export type AVMapCoordinateSystem = "wgs84" | "gcj02" | "bd09";
export type AVMapLoadErrorCode = "sdkScriptLoadFailed" | "sdkCallbackTimeout" | "sdkGlobalMissing" |
"mapCreationFailed" | "mapReadyTimeout";
+export type AVMapHostErrorCode = "hostLimitReached" | "hostSetupFailed" | "hostAttachFailed" |
+ "hostDocumentLoadFailed" | "hostDocumentLoadTimeout" | "hostDocumentReloaded" | "hostDocumentMismatch" |
+ "hostRendererGone" | "hostDestroyed" | "hostPortSetupFailed" | "hostPortClosed" | "hostBootstrapFailed" |
+ "hostBootstrapTimeout" | "hostSDKTimeout" | "hostOperationFailed" | "hostCreateRejected" |
+ "hostCreateInvalidResponse" | "hostReadyTimeout" | "hostOwnerSetupFailed";
export type AVMapErrorCode = "unsupportedEnvironment" | "missingCredentials" | "invalidConfiguration" |
- "hostUnavailable" | "sdkUnavailable" | "mapUnavailable" | AVMapLoadErrorCode;
+ "hostUnavailable" | "sdkUnavailable" | "mapUnavailable" | AVMapLoadErrorCode | AVMapHostErrorCode;
+
+const mapHostErrorCodes = new Set<AVMapHostErrorCode>([
+ "hostLimitReached", "hostSetupFailed", "hostAttachFailed", "hostDocumentLoadFailed", "hostDocumentLoadTimeout",
+ "hostDocumentReloaded", "hostDocumentMismatch", "hostRendererGone", "hostDestroyed", "hostPortSetupFailed",
+ "hostPortClosed", "hostBootstrapFailed", "hostBootstrapTimeout", "hostSDKTimeout", "hostOperationFailed",
+ "hostCreateRejected", "hostCreateInvalidResponse", "hostReadyTimeout", "hostOwnerSetupFailed",
+]);
+export const isAVMapHostErrorCode = (value: unknown): value is AVMapHostErrorCode =>
+ typeof value === "string" && mapHostErrorCodes.has(value as AVMapHostErrorCode);
const mapLoadErrorCodes = new Set<AVMapLoadErrorCode>([
"sdkScriptLoadFailed", "sdkCallbackTimeout", "sdkGlobalMissing", "mapCreationFailed", "mapReadyTimeout",
@@ -182,7 +196,8 @@ export const parseAVMapReply = (value: unknown, instanceID: string): AVMapReply
return {...envelope, type: "markerClick", id: input.id, revision: input.revision};
}
if (input.type === "error" && (["unsupportedEnvironment", "missingCredentials", "invalidConfiguration",
- "hostUnavailable", "sdkUnavailable", "mapUnavailable"].includes(input.code as string) || isAVMapLoadErrorCode(input.code))) {
+ "hostUnavailable", "sdkUnavailable", "mapUnavailable"].includes(input.code as string) ||
+ isAVMapLoadErrorCode(input.code) || isAVMapHostErrorCode(input.code))) {
return {...envelope, type: "error", code: input.code as AVMapErrorCode};
}
};