Skip to content

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

:bug: Coordinate settings interfaces across workspace windows https://github.com/siyuan-note/siyuan/issues/20513

Daniel569ab0de9496
diff --git a/app/electron/main.js b/app/electron/main.js
index 2bcc65c36f..ec11f7fbd4 100644
--- a/app/electron/main.js
+++ b/app/electron/main.js
@@ -142,6 +142,8 @@ const settingsWindowPolicy = createSettingsWindows({
screen,
icon: path.join(appDir, "stage", "icon-large.png"),
getTarget: id => getWindowKernelTarget(id),
+ getWindows: origin => BrowserWindow.getAllWindows().filter(win =>
+ initializedWindowIds.has(win.webContents.id) && windowKernelTargets.get(win.webContents.id)?.origin === origin),
show: win => showWindow(win),
log: message => writeLog(message),
initialize: (win, target) => {
diff --git a/app/electron/settingsWindows.js b/app/electron/settingsWindows.js
index 2333fc7963..c19c4193ed 100644
--- a/app/electron/settingsWindows.js
+++ b/app/electron/settingsWindows.js
@@ -3,12 +3,40 @@ const {normalizeWindowGeometry, captureWindowGeometry} = require("./windowGeomet
const settingsPath = "/stage/build/app/settings.html";
// 只允许已登记的内核页面打开预先授权的设置页,不改变普通链接的打开规则。
-const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, log, icon, platform = process.platform}) => {
+const createSettingsWindows = ({ipcMain, screen, getTarget, getWindows, initialize, show, log, icon,
+ platform = process.platform}) => {
const pending = new Map();
const reservations = new Map();
const windows = new Map();
const windowStates = new WeakMap();
const owners = new WeakMap();
+ let interfaceRevision = 0;
+ const getSettingTarget = event => {
+ const target = getTarget(event.sender.id);
+ if (!target || event.senderFrame !== event.sender.mainFrame) return;
+ try {
+ const url = new URL(event.sender.getURL());
+ if (url.origin === target.origin &&
+ ["/stage/build/app/", "/stage/build/app/index.html", "/stage/build/app/window.html"].includes(url.pathname)) {
+ return target;
+ }
+ } catch {
+ return;
+ }
+ };
+ const notifySettingDialogs = (target, revision = ++interfaceRevision) => {
+ for (const win of getWindows(target.origin)) {
+ if (win.isDestroyed()) continue;
+ const contents = win.webContents;
+ if (getSettingTarget({sender: contents, senderFrame: contents.mainFrame})?.origin !== target.origin) continue;
+ try {
+ contents.send("siyuan-settings-interface", revision);
+ } catch (error) {
+ log("settings dialog failed to receive switch notification: " + error);
+ }
+ }
+ return revision;
+ };
const release = approved => {
clearTimeout(approved.timer);
const key = approved.owner.id + ":" + approved.frameName;
@@ -94,53 +122,62 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, lo
const approved = win && windowStates.get(win).approved;
if (approved?.owner === event.sender && approved.data.token === data.token) cancel(approved);
});
+ ipcMain.on("siyuan-settings-open-dialog", event => {
+ let revision = false;
+ try {
+ const target = getSettingTarget(event);
+ if (!target) return;
+ // 内置设置按工作区互斥,插件专属窗口仍通过所属宿主及令牌关闭。
+ const key = `${target.origin}:builtin`;
+ const reserved = reservations.get(key);
+ if (reserved) cancel(reserved);
+ const win = windows.get(key);
+ if (win && !win.isDestroyed()) cancel(windowStates.get(win).approved);
+ revision = notifySettingDialogs(target);
+ } finally {
+ event.returnValue = revision;
+ }
+ });
ipcMain.handle("siyuan-settings-prepare", (event, data) => {
const requestedAt = Date.now();
- const target = getTarget(event.sender.id);
- if (!target || event.senderFrame !== event.sender.mainFrame || !data ||
+ const target = getSettingTarget(event);
+ if (!target || !data ||
!/^[a-zA-Z0-9-]{1,100}$/.test(data.token) ||
!/^(builtin|plugin-[a-zA-Z0-9-]+)$/.test(data.key)) {
return {create: false};
}
- let ownerURL;
- try {
- ownerURL = new URL(event.sender.getURL());
- } catch {
- return {create: false};
- }
- if (ownerURL.origin !== target.origin ||
- !["/stage/build/app/", "/stage/build/app/index.html", "/stage/build/app/window.html"].includes(ownerURL.pathname)) {
- return {create: false};
- }
const key = `${target.origin}:${data.key === "builtin" ? "builtin" : event.sender.id + ":" + data.key}`;
const existing = windows.get(key);
if (existing && !existing.isDestroyed()) {
const state = windowStates.get(existing);
+ if (data.key === "builtin") notifySettingDialogs(target, state.approved.revision);
state.data.command = data.command;
existing.webContents.send("siyuan-settings-command", data.command);
if (state.shown) show(existing);
- return {create: false};
+ return {create: false, revision: state.approved.revision};
}
const reserved = reservations.get(key);
if (reserved && reserved.expires >= Date.now() && !reserved.owner.isDestroyed()) {
+ if (data.key === "builtin") notifySettingDialogs(target, reserved.revision);
reserved.data.command = data.command;
- return {create: false};
+ return {create: false, revision: reserved.revision};
}
if (reserved) cancel(reserved);
+ const revision = data.key === "builtin" ? notifySettingDialogs(target) : undefined;
const url = new URL(settingsPath, target.origin);
url.searchParams.set("settingsWindowToken", data.token);
if (target.mode === "remote") {
url.searchParams.set("remote", "1");
}
const frameName = "siyuan-settings-" + data.token;
- const approved = {key, target, owner: event.sender, url: url.href, frameName, data, requestedAt,
+ const approved = {key, target, owner: event.sender, url: url.href, frameName, data, requestedAt, revision,
active: true, expires: Date.now() + 60000};
watchOwner(event.sender).records.add(approved);
approved.timer = setTimeout(() => cancel(approved), 60000);
approved.timer.unref();
pending.set(event.sender.id + ":" + frameName, approved);
reservations.set(key, approved);
- return {create: true, token: data.token, url: approved.url, frameName};
+ return {create: true, token: data.token, url: approved.url, frameName, revision};
});
return (contents, details) => {
const pendingKey = contents.id + ":" + details.frameName;
diff --git a/app/electron/settingsWindows.test.js b/app/electron/settingsWindows.test.js
index 597b54ca7b..00d263f1c6 100644
--- a/app/electron/settingsWindows.test.js
+++ b/app/electron/settingsWindows.test.js
@@ -23,6 +23,7 @@ const setup = (platform = "win32") => {
if (name === "siyuan-settings-ready") ready = callback;
}},
screen: {}, getTarget: id => [1, 2].includes(id) ? target : undefined,
+ getWindows: () => [{webContents: owner, isDestroyed: () => false}],
initialize: (...args) => initialized.push(args), show: win => shown.push(win), log() {},
});
const event = {sender: owner, senderFrame: owner.mainFrame};
diff --git a/app/src/config/index.ts b/app/src/config/index.ts
index 4100761cee..001f746b73 100644
--- a/app/src/config/index.ts
+++ b/app/src/config/index.ts
@@ -25,20 +25,17 @@ import {unmountOCRTab} from "./ocr";
import {getHostCapabilities} from "../util/hostCapabilities";
import {unmountWorkspaceStorage} from "./tabs/workspaceStorage";
/// #if !MOBILE
-import {closeNativeSettings, openNativeSettings} from "./setting/nativeWindow";
+import {openNativeSettings} from "./setting/nativeWindow";
+import {closeSettingDialog, prepareSettingDialog} from "./setting/interface";
import {isSettingsWindow} from "./setting/windowContext";
import {fitSettingsWindowDialog} from "./setting/windowDialog";
/// #endif
/// #if !MOBILE
-const closeSettingDialog = () => {
- window.siyuan.dialogs.find((item) => item.element.querySelector(".config__tab-container"))?.destroy();
-};
-
export const openSettingDialog = (app: App, initialTab: TSettingTab = "editor") => {
/// #if !BROWSER
if (!isSettingsWindow()) {
- closeNativeSettings("builtin");
+ prepareSettingDialog();
}
/// #endif
closeSettingDialog();
diff --git a/app/src/config/openSetting.test.ts b/app/src/config/openSetting.test.ts
index 3a69ce32e5..dec67b9651 100644
--- a/app/src/config/openSetting.test.ts
+++ b/app/src/config/openSetting.test.ts
@@ -26,6 +26,7 @@ const fixture = (browser = false, mobile = false) => {
exports: entry, isSettingsWindow: () => native,
isBazaarAvailable: () => true, getHostCapabilities: () => ({documentImportExport: true}),
openNativeSettings: (...args: unknown[]) => calls.push(["native", ...args]),
+ closeSettingDialog() {},
openSettingDialog: (...args: unknown[]) => { calls.push(["dialog", ...args]); return dialog; },
openMobileSetting: (...args: unknown[]) => calls.push(["mobile", ...args]),
openChatGPTProvider: () => calls.push(["chatgpt"]),
diff --git a/app/src/config/setting/interface.ts b/app/src/config/setting/interface.ts
new file mode 100644
index 0000000000..fab868e489
--- /dev/null
+++ b/app/src/config/setting/interface.ts
@@ -0,0 +1,36 @@
+/// #if !BROWSER
+import {ipcRenderer} from "electron";
+/// #endif
+
+let revision = 0;
+let listening = false;
+
+export const closeSettingDialog = () => {
+ window.siyuan.dialogs.find(item => item.element.querySelector(".config__tab-container"))?.destroy();
+};
+
+export const acceptSettingInterfaceRevision = (next: number) => {
+ if (!Number.isSafeInteger(next) || next < revision) return false;
+ revision = next;
+ return true;
+};
+
+export const watchSettingInterface = () => {
+ /// #if !BROWSER
+ if (listening) return;
+ listening = true;
+ ipcRenderer.on("siyuan-settings-interface", (_event, next: number) => {
+ if (next > revision && acceptSettingInterfaceRevision(next)) closeSettingDialog();
+ });
+ /// #endif
+};
+
+export const prepareSettingDialog = () => {
+ /// #if !BROWSER
+ watchSettingInterface();
+ // 同步取得工作区的打开次序,保留插件 API 的同步返回,并忽略迟到的关闭通知。
+ if (!acceptSettingInterfaceRevision(ipcRenderer.sendSync("siyuan-settings-open-dialog"))) {
+ throw new Error("Could not coordinate the settings dialog");
+ }
+ /// #endif
+};
diff --git a/app/src/config/setting/nativeWindow.ts b/app/src/config/setting/nativeWindow.ts
index 822df3fc57..1476ce04c5 100644
--- a/app/src/config/setting/nativeWindow.ts
+++ b/app/src/config/setting/nativeWindow.ts
@@ -15,6 +15,7 @@ import {getDockEntryOrderSnapshot} from "../entryVisibility/dockOrder";
import {getEditorToolbarCatalogSnapshot} from "../../protyle/toolbar/catalogSnapshot";
import {hasNativeSettingTasks} from "./taskBlocker";
import {openBazaarPath} from "../bazaar/openPath";
+import {acceptSettingInterfaceRevision, watchSettingInterface} from "./interface";
import type {App} from "../../index";
import type {ISettingsWindowHost} from "./windowContext";
import type {TSettingTab} from "./tabs";
@@ -57,6 +58,7 @@ export const openNativeSettings = async (app: App, command: ISettingsCommand = {
plugin?: ISettingsWindowHost["plugin"], key = "builtin") => {
/// #if !BROWSER
if (!ownerActive) return;
+ if (key === "builtin") watchSettingInterface();
openSequence++;
if (!listening) {
listening = true;
@@ -179,7 +181,8 @@ export const openNativeSettings = async (app: App, command: ISettingsCommand = {
dispose(false, false);
return;
}
- if (!isActive() || (plugin && !plugin.isOpen())) {
+ if (!isActive() || (plugin && !plugin.isOpen()) ||
+ (key === "builtin" && !acceptSettingInterfaceRevision(prepared.revision))) {
try {
ipcRenderer.send("siyuan-settings-close", {key, token});
} finally {
diff --git a/app/tests/nativeSettingsOwner.test.js b/app/tests/nativeSettingsOwner.test.js
index c57e40b78f..c93fb798cf 100644
--- a/app/tests/nativeSettingsOwner.test.js
+++ b/app/tests/nativeSettingsOwner.test.js
@@ -59,6 +59,7 @@ const setup = () => {
"../../protyle/toolbar/catalogSnapshot": {getEditorToolbarCatalogSnapshot: () => []},
"./taskBlocker": {hasNativeSettingTasks: () => nativeTask},
"../bazaar/openPath": {openBazaarPath: record("openBazaarPath")},
+ "./interface": {watchSettingInterface() {}, acceptSettingInterfaceRevision: () => true},
};
const context = {exports: {}, window, console: {error: record("error")}, require: name => {
assert.ok(modules[name], name);
diff --git a/app/tests/settingsInterface.test.js b/app/tests/settingsInterface.test.js
index bccf727e93..cadda6a873 100644
--- a/app/tests/settingsInterface.test.js
+++ b/app/tests/settingsInterface.test.js
@@ -55,8 +55,10 @@ const setup = ({mobile = false, browser = false, settingsWindow = false, native
"./tabs/workspaceStorage": {unmountWorkspaceStorage() {}},
"./setting/nativeWindow": {
openNativeSettings: async (...args) => calls.push(["native", ...args]),
- closeNativeSettings: key => calls.push(["closeNative", key]),
},
+ "./setting/interface": {prepareSettingDialog: () => calls.push(["prepareDialog"]),
+ closeSettingDialog: () => window.siyuan.dialogs.find(item =>
+ item.element.querySelector(".config__tab-container"))?.destroy()},
"./setting/windowContext": {isSettingsWindow: () => settingsWindow},
"./setting/windowDialog": {fitSettingsWindowDialog: () => calls.push(["fit"])},
};
@@ -76,13 +78,13 @@ const setup = ({mobile = false, browser = false, settingsWindow = false, native
test("opening a settings dialog closes the builtin native window before mounting", () => {
const {api, app, calls} = setup();
api.openSetting(app, "app");
- assert.deepEqual(calls.slice(0, 2), [["closeNative", "builtin"], ["dialog"]]);
+ assert.deepEqual(calls.slice(0, 2), [["prepareDialog"], ["dialog"]]);
});
test("the plugin settings API also closes the builtin native window", () => {
const {api, app, calls} = setup({native: true});
api.openPluginSetting(app);
- assert.deepEqual(calls.slice(0, 2), [["closeNative", "builtin"], ["dialog"]]);
+ assert.deepEqual(calls.slice(0, 2), [["prepareDialog"], ["dialog"]]);
assert.equal(calls.some(call => call[0] === "native"), false);
});
@@ -112,7 +114,7 @@ test("settings window boot and tab reuse do not close the current native window"
const {api, app, calls} = setup({settingsWindow: true, native: true});
const dialog = api.openSettingDialog(app);
assert.equal(api.openSetting(app, "ai", {aiProvider: "chatgpt"}), dialog);
- assert.equal(calls.some(call => ["closeNative", "destroy", "closeSelf", "native"].includes(call[0])), false);
+ assert.equal(calls.some(call => ["prepareDialog", "destroy", "closeSelf", "native"].includes(call[0])), false);
assert.equal(calls.filter(call => call[0] === "dialog").length, 1);
assert.equal(calls.filter(call => call[0] === "fit").length, 1);
assert.deepEqual(calls.slice(-2), [["tab", "ai"], ["chatgpt"]]);
@@ -132,7 +134,7 @@ for (const mobile of [false, true]) {
test(`browser and mobile settings retain their opening paths (mobile=${mobile})`, () => {
const {api, app, calls} = setup({mobile, browser: true, native: true});
api.openSetting(app, "app");
- assert.equal(calls.some(call => call[0] === "native" || call[0] === "closeNative"), false);
+ assert.equal(calls.some(call => call[0] === "native" || call[0] === "prepareDialog"), false);
assert.equal(calls[0][0], mobile ? "mobile" : "dialog");
});
}
diff --git a/app/tests/settingsInterfaceCoordinator.test.js b/app/tests/settingsInterfaceCoordinator.test.js
new file mode 100644
index 0000000000..cdc6436190
--- /dev/null
+++ b/app/tests/settingsInterfaceCoordinator.test.js
@@ -0,0 +1,215 @@
+const assert = require("node:assert/strict");
+const {EventEmitter} = require("node:events");
+const {readFileSync} = require("node:fs");
+const {test} = require("node:test");
+const {runInNewContext} = require("node:vm");
+const ts = require("typescript");
+const {createSettingsWindows} = require("../electron/settingsWindows");
+
+const compile = file => ts.transpileModule(readFileSync(file, "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},
+}).outputText;
+const interfaceCode = compile("src/config/setting/interface.ts");
+const nativeCode = compile("src/config/setting/nativeWindow.ts");
+
+const setup = () => {
+ const handlers = new Map();
+ const messages = [];
+ const targets = new Map();
+ const windows = [];
+ const children = [];
+ const renderers = [];
+ let sequence = 0;
+ const policy = createSettingsWindows({
+ ipcMain: {on: (name, callback) => handlers.set(name, callback), handle: (name, callback) => handlers.set(name, callback)},
+ getTarget: id => targets.get(id), getWindows: () => windows,
+ initialize: (win, target) => { targets.set(win.webContents.id, target); windows.push(win); },
+ screen: {}, show() {}, log() {},
+ });
+ const renderer = (origin = "https://example.com") => {
+ const id = ++sequence;
+ let held = false;
+ const replies = [];
+ const ipcRenderer = new EventEmitter();
+ const owner = Object.assign(new EventEmitter(), {id, mainFrame: {}, isDestroyed: () => false,
+ getURL: () => origin + "/stage/build/app/window.html",
+ send: (name, ...args) => messages.push({id, name, args})});
+ targets.set(id, {origin, mode: "remote"});
+ windows.push({webContents: owner, isDestroyed: () => false});
+ const event = () => ({sender: owner, senderFrame: owner.mainFrame});
+ Object.assign(ipcRenderer, {
+ sendSync: name => {
+ const request = event();
+ let replied = false;
+ let response;
+ Object.defineProperty(request, "returnValue", {set: value => {
+ assert.equal(replied, false, "synchronous IPC must reply exactly once");
+ replied = true;
+ response = value;
+ }});
+ handlers.get(name)(request);
+ assert.equal(replied, true);
+ return response;
+ },
+ send: (name, ...args) => handlers.get(name)(event(), ...args),
+ invoke: (name, data) => {
+ const prepared = handlers.get(name)(event(), data);
+ return held ? new Promise(resolve => replies.push(() => resolve(prepared))) : Promise.resolve(prepared);
+ },
+ });
+ const events = new EventEmitter();
+ const window = {siyuan: {dialogs: [], storage: {}, languages: {config: "Settings"}},
+ addEventListener: (...args) => events.on(...args), removeEventListener: (...args) => events.removeListener(...args),
+ open: (url, frameName) => {
+ assert.equal(policy(owner, {url, frameName}).action, "allow");
+ let destroyed = false;
+ const contents = Object.assign(new EventEmitter(), {id: ++sequence, mainFrame: {},
+ getURL: () => url, send() {}});
+ const win = Object.assign(new EventEmitter(), {webContents: contents, setMenu() {}, isDestroyed: () => destroyed,
+ destroy() { destroyed = true; this.emit("closed"); }});
+ owner.emit("did-create-window", win, {url});
+ children.push(win);
+ return {};
+ },
+ };
+ const load = (code, modules) => {
+ const exports = {};
+ runInNewContext(code, {exports, window, console, require: name => {
+ assert.ok(modules[name], name);
+ return modules[name];
+ }});
+ return exports;
+ };
+ const settingInterface = load(interfaceCode, {electron: {ipcRenderer}});
+ const native = load(nativeCode, {
+ electron: {ipcRenderer}, "../../util/genID": {genUUID: () => "token-" + (++sequence)},
+ "../../protyle/util/compatibility": {}, "../../layout/util": {}, "../../dialog/processSystem": {},
+ "../../plugin/globalState": {}, "../../plugin/loader": {},
+ "../../boot/globalEvent/globalShortcut": {}, "../../constants": {Constants: {}}, "../../plugin": {},
+ "../../util/processTitle": {getWorkspaceName: () => "Workspace"}, "../entryVisibility/dockOrder": {},
+ "../../protyle/toolbar/catalogSnapshot": {}, "./taskBlocker": {}, "../bazaar/openPath": {},
+ "./interface": settingInterface,
+ });
+ const app = {plugins: []};
+ const dialog = (builtin = true) => {
+ let destroyed = false;
+ const item = {element: {querySelector: () => builtin ? {} : null}, isDestroyed: () => destroyed,
+ destroy() { destroyed = true; window.siyuan.dialogs.splice(window.siyuan.dialogs.indexOf(this), 1); }};
+ window.siyuan.dialogs.push(item);
+ return item;
+ };
+ const result = {id, owner, ipcRenderer, window, native, settingInterface, dialog,
+ openDialog: () => { settingInterface.prepareSettingDialog(); settingInterface.closeSettingDialog(); return dialog(); },
+ openNative: () => { settingInterface.closeSettingDialog(); return native.openNativeSettings(app); },
+ hold: () => { held = true; }, reply: () => replies.shift()(), event};
+ renderers.push(result);
+ return result;
+ };
+ const flush = () => {
+ while (messages.length) {
+ const {id, name, args} = messages.shift();
+ renderers.find(item => item.id === id)?.ipcRenderer.emit(name, {}, ...args);
+ }
+ };
+ return {renderer, flush, handlers, children};
+};
+
+for (const reuse of [false, true]) {
+ test(`a different renderer closes workspace builtin settings before opening its dialog (reuse=${reuse})`, async () => {
+ const {renderer, flush, children} = setup();
+ const a = renderer();
+ const b = renderer();
+ await a.openNative();
+ if (reuse) await b.openNative();
+ const dialog = b.openDialog();
+ assert.equal(children[0].isDestroyed(), true);
+ flush();
+ assert.equal(dialog.isDestroyed(), false);
+ });
+}
+
+test("native settings close sibling builtin dialogs and preserve plugin dialogs and other workspaces", async () => {
+ const {renderer, flush} = setup();
+ const a = renderer();
+ const b = renderer();
+ const other = renderer("https://other.example.com");
+ const dialog = a.openDialog();
+ const plugin = a.dialog(false);
+ const otherDialog = other.openDialog();
+ await b.openNative();
+ flush();
+ assert.equal(dialog.isDestroyed(), true);
+ assert.equal(plugin.isDestroyed(), false);
+ assert.equal(otherDialog.isDestroyed(), false);
+});
+
+test("late switch notifications preserve the latest dialog across alternating renderers", () => {
+ const {renderer, flush} = setup();
+ const a = renderer();
+ const b = renderer();
+ const first = a.openDialog();
+ const second = b.openDialog();
+ const latest = a.openDialog();
+ flush();
+ assert.equal(first.isDestroyed(), true);
+ assert.equal(second.isDestroyed(), true);
+ assert.equal(latest.isDestroyed(), false);
+});
+
+test("a canceled native prepare reply cannot replace a newer dialog", async () => {
+ const {renderer, flush, children} = setup();
+ const a = renderer();
+ a.hold();
+ const opening = a.openNative();
+ const latest = a.openDialog();
+ a.reply();
+ await opening;
+ flush();
+ assert.equal(children.length, 0);
+ assert.equal(latest.isDestroyed(), false);
+});
+
+test("concurrent native reuse preserves the creator's pending reservation", async () => {
+ const {renderer, flush, children} = setup();
+ const a = renderer();
+ const b = renderer();
+ a.hold();
+ const opening = a.openNative();
+ await b.openNative();
+ flush();
+ a.reply();
+ await opening;
+ assert.equal(children.length, 1);
+ assert.equal(children[0].isDestroyed(), false);
+});
+
+test("switching to dialogs leaves plugin native windows and other workspace native settings open", async () => {
+ const {renderer, flush, children} = setup();
+ const a = renderer();
+ const b = renderer();
+ const other = renderer("https://other.example.com");
+ await a.native.openNativeSettings({plugins: []}, {}, undefined, "plugin-example");
+ await other.openNative();
+ await a.openNative();
+ b.openDialog();
+ flush();
+ assert.deepEqual(children.map(win => win.isDestroyed()), [false, false, true]);
+});
+
+test("dialog switching rejects subframes, unregistered senders and non-app pages", async () => {
+ const {renderer, handlers, children} = setup();
+ const a = renderer();
+ const b = renderer();
+ await a.openNative();
+ const subframe = {...b.event(), senderFrame: {}};
+ handlers.get("siyuan-settings-open-dialog")(subframe);
+ assert.equal(subframe.returnValue, false);
+ b.owner.getURL = () => "https://example.com/stage/build/app/settings.html";
+ assert.throws(() => b.openDialog(), /Could not coordinate/);
+ b.owner.getURL = () => "https://attacker.example/stage/build/app/";
+ assert.throws(() => b.openDialog(), /Could not coordinate/);
+ const unknown = {sender: {id: -1, mainFrame: {}}, senderFrame: {}};
+ handlers.get("siyuan-settings-open-dialog")(unknown);
+ assert.equal(unknown.returnValue, false);
+ assert.equal(children[0].isDestroyed(), false);
+});
diff --git a/app/tests/settingsWindow.test.js b/app/tests/settingsWindow.test.js
index 0c19367ddc..41797e26b1 100644
--- a/app/tests/settingsWindow.test.js
+++ b/app/tests/settingsWindow.test.js
@@ -194,6 +194,7 @@ const runCases = async (sources) => {
class Plugin {openSetting() {}}
const pluginSettings = {};
new Function("Plugin", "exports", sources.pluginSettings)(Plugin, pluginSettings);
+ const settingInterface = loadRendererModule(sources.settingInterface, {electron: {ipcRenderer}});
const native = loadRendererModule(sources.native, {
electron: {ipcRenderer}, "../../util/genID": {genUUID}, "../../protyle/util/compatibility": {setStorageVal() {}},
"../../layout/util": {exportLayout: async options => options.cb()}, "../../dialog/processSystem": {exitSiYuan: async () => {}},
@@ -207,6 +208,7 @@ const runCases = async (sources) => {
"../../protyle/toolbar/catalogSnapshot": {getEditorToolbarCatalogSnapshot: () => []},
"./taskBlocker": {hasNativeSettingTasks: () => false},
"../bazaar/openPath": bazaarPath,
+ "./interface": settingInterface,
});
const {Setting} = loadRendererModule(sources.setting, {
"../util/functions": {isMobile: () => false, getFrontend: () => "desktop"}, "../dialog": {Dialog},
@@ -423,6 +425,11 @@ const runCases = async (sources) => {
await wait();
await native.openNativeSettings(window.siyuan.ws.app, {tab: "editor"});
assert.equal(await ipcRenderer.invoke("test-settings-window-count"), 1);
+ await ipcRenderer.invoke("test-settings-other-dialog");
+ assert.equal(await ipcRenderer.invoke("test-settings-window-count"), 0);
+ await native.openNativeSettings(window.siyuan.ws.app, {tab: "editor"});
+ await ipcRenderer.invoke("test-settings-wait");
+ assert.equal(await ipcRenderer.invoke("test-settings-other-dialog-closed"), true);
};
if (process.versions.electron && process.type === "browser") {
@@ -436,6 +443,7 @@ if (process.versions.electron && process.type === "browser") {
let ready = 0;
let waiting;
const children = new Set();
+ const otherOwners = new Set();
const shown = new Set();
const commands = [];
const ts = require("typescript");
@@ -448,6 +456,7 @@ if (process.versions.electron && process.type === "browser") {
"\n.config__panel {border-radius: var(--b3-border-radius-b);}\n"]));
for (const [key, file] of Object.entries({dialog: "dialog/index.ts", setting: "plugin/Setting.ts",
native: "config/setting/nativeWindow.ts", fit: "config/setting/windowDialog.ts", controls: "boot/windowControls.ts",
+ settingInterface: "config/setting/interface.ts",
paint: "util/windowPaint.ts", frontend: "util/functions.ts", titles: "util/processTitle.ts",
mount: "config/setting/mount.ts", save: "config/setting/save.ts", fragments: "config/render/fragments.ts",
bazaarPath: "config/bazaar/openPath.ts", tooltip: "dialog/tooltip.ts", hoverInput: "util/hoverInput.ts"})) {
@@ -502,7 +511,10 @@ if (process.versions.electron && process.type === "browser") {
});
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
const origin = "http://127.0.0.1:" + server.address().port;
- const policy = createSettingsWindows({ipcMain, screen, getTarget: id => owner?.webContents.id === id ? {origin, mode: "local"} : undefined,
+ const policy = createSettingsWindows({ipcMain, screen,
+ getTarget: id => owner?.webContents.id === id || [...otherOwners].some(win => win.webContents.id === id) ?
+ {origin, mode: "local"} : undefined,
+ getWindows: () => [...(owner ? [owner] : []), ...otherOwners],
initialize: win => {
win.webContents.userAgent = "SiYuan/fixture Electron " + win.webContents.userAgent;
win.webContents.on("console-message", details => {
@@ -531,6 +543,30 @@ if (process.versions.electron && process.type === "browser") {
});
ipcMain.handle("test-settings-wait", () => ready ? (--ready, Promise.resolve()) : new Promise(resolve => { waiting = resolve; }));
ipcMain.handle("test-settings-window-count", () => children.size);
+ ipcMain.handle("test-settings-other-dialog", async () => {
+ const other = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false}});
+ otherOwners.add(other);
+ other.once("closed", () => otherOwners.delete(other));
+ other.webContents.on("console-message", details => {
+ if (details.level === "error") console.error(details.message);
+ });
+ await other.loadURL(origin + "/stage/build/app/window.html");
+ await other.webContents.executeJavaScript(`
+ const loadSecondaryModule = ${loadRendererModule.toString()};
+ window.siyuan = {dialogs: []};
+ const settingInterface = loadSecondaryModule(${JSON.stringify(sources.settingInterface)}, {electron: require("electron")});
+ settingInterface.prepareSettingDialog();
+ window.dialogClosed = false;
+ window.siyuan.dialogs.push({element: {querySelector: () => ({})}, destroy() {
+ window.dialogClosed = true;
+ window.siyuan.dialogs.length = 0;
+ }});
+ `);
+ });
+ ipcMain.handle("test-settings-other-dialog-closed", async () => {
+ const states = await Promise.all([...otherOwners].map(win => win.webContents.executeJavaScript("window.dialogClosed")));
+ return states.every(closed => closed === true);
+ });
ipcMain.on("siyuan-cmd", (event, command) => {
if (event.sender === owner.webContents) {
assert.equal(command, "show");
@@ -612,6 +648,7 @@ if (process.versions.electron && process.type === "browser") {
code = 1;
} finally {
for (const child of children) child.destroy();
+ for (const other of otherOwners) other.destroy();
if (owner && !owner.isDestroyed()) owner.destroy();
server.close();
app.exit(code);