Skip to content

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

:bug: Start the map menu prototype through Electron imports https://github.com/siyuan-note/siyuan/issues/20129

Daniel622e32f5719b
diff --git a/app/tests/fixtures/map-unplaced-overlay/README.md b/app/tests/fixtures/map-unplaced-overlay/README.md
index 3bd5ca8a5e..e54e030e82 100644
--- a/app/tests/fixtures/map-unplaced-overlay/README.md
+++ b/app/tests/fixtures/map-unplaced-overlay/README.md
@@ -7,14 +7,16 @@
在 `app/` 目录运行:
```sh
-node --import tsx --test tests/mapUnplacedOverlay.test.js tests/mapUnplacedOverlayBoundary.test.js
-pnpm exec electron tests/fixtures/map-unplaced-overlay/harness.cjs
+node --import tsx --test tests/mapUnplacedOverlay.test.js tests/mapUnplacedOverlayStartup.test.js tests/mapUnplacedOverlayBoundary.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,不生成生产构建文件。
当前环境无法运行真实 GUI。已执行的 Node 测试验证严格 schema、资源路由、owner/frame/session/revision/requestID、选择成员集合、权限撤销、导航和销毁、失败清理、几何去重,以及实际 preload/menu 脚本在模拟 IPC/DOM 下的行为。模拟 DOM 使用项目现有 parse5 fixture,不证明浏览器排版、真实键盘输入、中文输入法候选窗、CSP 的浏览器执行、原生层合成或真实 OFM 覆盖正确。真实 Electron 入口已经编写,但只有它实际通过后才可报告相应浏览器证据。
+手动入口启动时输出 `Map overlay prototype starting...`,窗口页面加载完成后输出 `Map overlay prototype window ready.`,失败时输出固定提示。`harness.cjs` 是专用启动入口,`harnessSupport.cjs` 是测试可导入的无启动副作用模块;入口回归使用 Electron 相同的动态 `import()` 语义,不能依赖 `require.main === module`。若进程处于 Node 模式,会提示检查 `ELECTRON_RUN_AS_NODE`,不会自动改变该环境变量。此入口回归使用受控替身验证启动分发,不替代真实 GUI 验收。
+
## 最小安全边界
- owner 是构造 manager 时固定登记的 WebContents、当前主 frame 和精确文档 URL。程序导航、销毁、窗口隐藏或失焦都会销毁旧 overlay;owner WebContents 失焦进入同一窗口 overlay 不会误关
diff --git a/app/tests/fixtures/map-unplaced-overlay/harness.cjs b/app/tests/fixtures/map-unplaced-overlay/harness.cjs
index 1392a4d4c4..14fc69330a 100644
--- a/app/tests/fixtures/map-unplaced-overlay/harness.cjs
+++ b/app/tests/fixtures/map-unplaced-overlay/harness.cjs
@@ -1,84 +1,33 @@
-const path = require("node:path");
-const fs = require("node:fs");
-const os = require("node:os");
-const {pathToFileURL} = require("node:url");
-const {createManager} = require("./manager.cjs");
-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 "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], ["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();
+// 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);
+ }
};
- win.on("closed", () => { destroy(); if (!automate) app.quit(); });
- await win.loadURL(ownerURL);
- return {win, owner, manager, map, mapVisible, events, destroy};
-};
-module.exports = {createHarness, createTemporaryProfile};
-if (require.main === module) {
- const {app, BrowserWindow} = require("electron");
- const temporary = createTemporaryProfile();
- app.once("will-quit", temporary.cleanup);
- app.once("quit", temporary.cleanup);
- createHarness({profile: temporary.profile}).catch(error => {
- for (const win of BrowserWindow.getAllWindows()) { if (!win.isDestroyed()) win.destroy(); }
- temporary.cleanup();
- console.error(error);
- 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.cjs
new file mode 100644
index 0000000000..8cae3fd016
--- /dev/null
+++ b/app/tests/fixtures/map-unplaced-overlay/harnessSupport.cjs
@@ -0,0 +1,72 @@
+const path = require("node:path");
+const fs = require("node:fs");
+const os = require("node:os");
+const {pathToFileURL} = require("node:url");
+const {createManager} = require("./manager.cjs");
+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 "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], ["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/mapUnplacedOverlay.test.js b/app/tests/mapUnplacedOverlay.test.js
index 1e7ab5decd..9bbf8aa069 100644
--- a/app/tests/mapUnplacedOverlay.test.js
+++ b/app/tests/mapUnplacedOverlay.test.js
@@ -245,7 +245,7 @@ test("overlay setup failures close sessions, views and listeners transactionally
});
test("manual harness requires an explicit profile and owns only its fresh temporary directory", async () => {
- const {createHarness, createTemporaryProfile} = require("./fixtures/map-unplaced-overlay/harness.cjs");
+ const {createHarness, createTemporaryProfile} = require("./fixtures/map-unplaced-overlay/harnessSupport.cjs");
await assert.rejects(createHarness(), /explicit isolated fixture profile/);
const temporary = createTemporaryProfile();
try {
diff --git a/app/tests/mapUnplacedOverlayBoundary.test.js b/app/tests/mapUnplacedOverlayBoundary.test.js
index 30aa184d0e..e9f09a1e05 100644
--- a/app/tests/mapUnplacedOverlayBoundary.test.js
+++ b/app/tests/mapUnplacedOverlayBoundary.test.js
@@ -5,7 +5,7 @@ const os = require("node:os");
// 使用真实 Electron owner、IPC、sandbox preload 和 DOM;底图及记录仍为合成测试资源。
const run = async profile => {
- const {createHarness} = require("./fixtures/map-unplaced-overlay/harness.cjs");
+ 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) => {
diff --git a/app/tests/mapUnplacedOverlayStartup.test.js b/app/tests/mapUnplacedOverlayStartup.test.js
new file mode 100644
index 0000000000..38df2c2e40
--- /dev/null
+++ b/app/tests/mapUnplacedOverlayStartup.test.js
@@ -0,0 +1,97 @@
+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, "");
+});