An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Show settings windows after the interface is painted https://github.com/siyuan-note/siyuan/issues/20002
Danielc1cd16a2aa30
diff --git a/app/electron/settingsWindows.js b/app/electron/settingsWindows.jsindex d7b94a6845..c2079708d3 100644--- a/app/electron/settingsWindows.js+++ b/app/electron/settingsWindows.js@@ -7,6 +7,7 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, loconst pending = new Map();const reservations = new Map();const windows = new Map();+ const windowStates = new WeakMap();const release = approved => {clearTimeout(approved.timer);pending.delete(approved.owner.id + ":" + approved.frameName);@@ -18,6 +19,17 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, lorelease(approved);if (!approved.owner.isDestroyed()) approved.owner.send("siyuan-settings-closed", approved.data.token);};+ ipcMain.on("siyuan-settings-ready", event => {+ if (event.senderFrame !== event.sender.mainFrame) return;+ for (const win of windows.values()) {+ if (!win.isDestroyed() && win.webContents === event.sender) {+ const state = windowStates.get(win);+ state.ready = true;+ state.reveal();+ return;+ }+ }+ });ipcMain.on("siyuan-settings-close", (event, key) => {const target = getTarget(event.sender.id);if (!target || event.senderFrame !== event.sender.mainFrame || typeof key !== "string" ||@@ -48,8 +60,10 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, loconst key = `${target.origin}:${data.key === "builtin" ? "builtin" : event.sender.id + ":" + data.key}`;const existing = windows.get(key);if (existing && !existing.isDestroyed()) {- show(existing);+ const state = windowStates.get(existing);+ state.data.command = data.command;existing.webContents.send("siyuan-settings-command", data.command);+ if (state.shown) show(existing);return {create: false};}const reserved = reservations.get(key);@@ -85,6 +99,18 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, loif (created.url !== approved.url) return;release(approved);windows.set(approved.key, win);+ const state = {painted: false, ready: false, shown: false, data: approved.data};+ state.reveal = () => {+ if (!state.ready || !state.painted || state.shown || win.isDestroyed()) return;+ state.shown = true;+ if (state.data.geometry?.maximized) win.maximize();+ show(win);+ };+ windowStates.set(win, state);+ win.once("ready-to-show", () => {+ state.painted = true;+ state.reveal();+ });if (platform !== "darwin") win.setMenu(null);initialize(win, approved.target);const close = () => { if (!win.isDestroyed()) win.destroy(); };@@ -105,7 +131,6 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, lowin.on(event, saveGeometry);}win.webContents.once("did-finish-load", () => {- if (approved.data.geometry?.maximized) win.maximize();win.webContents.send("siyuan-settings-command", approved.data.command);});win.webContents.on("did-fail-load", (_event, code, description) => {@@ -116,6 +141,7 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, loreturn {action: "allow",overrideBrowserWindowOptions: {+ show: false,title: approved.data.title || "SiYuan",frame: platform === "darwin",titleBarStyle: "hidden",diff --git a/app/electron/settingsWindows.test.js b/app/electron/settingsWindows.test.jsindex c0d9f14743..aa6534f2cc 100644--- a/app/electron/settingsWindows.test.js+++ b/app/electron/settingsWindows.test.js@@ -6,6 +6,7 @@ const {createSettingsWindows} = require("./settingsWindows");const setup = (platform = "win32") => {let prepare;let close;+ let ready;const shown = [];const initialized = [];const target = {origin: "https://example.com", mode: "remote"};@@ -15,13 +16,16 @@ const setup = (platform = "win32") => {});const policy = createSettingsWindows({platform,- ipcMain: {handle: (_name, callback) => { prepare = callback; }, on: (_name, callback) => { close = callback; }},+ ipcMain: {handle: (_name, callback) => { prepare = callback; }, on: (name, callback) => {+ if (name === "siyuan-settings-close") close = callback;+ if (name === "siyuan-settings-ready") ready = callback;+ }},screen: {}, getTarget: id => id === 1 ? target : undefined,initialize: (...args) => initialized.push(args), show: win => shown.push(win), log() {},});const event = {sender: owner, senderFrame: owner.mainFrame};const open = (data = {}) => prepare(event, {key: "builtin", token: "first-token", command: {tab: "editor"}, ...data});- return {policy, owner, event, open, close, shown, initialized};+ return {policy, owner, event, open, close, ready, shown, initialized};};test("settings popup authorization requires the registered top-level page and exact URL and frame", () => {@@ -36,6 +40,7 @@ test("settings popup authorization requires the registered top-level page and exassert.equal(policy(owner, {url: prepared.url, frameName: "other-frame"}), undefined);const allowed = policy(owner, prepared);assert.equal(allowed.action, "allow");+ assert.equal(allowed.overrideBrowserWindowOptions.show, false);assert.equal(allowed.overrideBrowserWindowOptions.frame, false);assert.equal(allowed.overrideBrowserWindowOptions.titleBarStyle, "hidden");assert.equal(allowed.overrideBrowserWindowOptions.autoHideMenuBar, true);@@ -47,11 +52,11 @@ test("settings popup authorization requires the registered top-level page and ex});test("settings windows reuse their workspace instance and close with the owning renderer", () => {- const {policy, owner, open, shown, initialized} = setup();+ const {policy, owner, open, ready, shown, initialized} = setup();const prepared = open();assert.equal(open({token: "second-token", command: {tab: "appearance"}}).create, false);policy(owner, prepared);- const contents = Object.assign(new EventEmitter(), {sent: [], send(...message) { this.sent.push(message); }});+ const contents = Object.assign(new EventEmitter(), {mainFrame: {}, sent: [], send(...message) { this.sent.push(message); }});let destroyed = false;const win = Object.assign(new EventEmitter(), {webContents: contents, isDestroyed: () => destroyed,@@ -64,14 +69,51 @@ test("settings windows reuse their workspace instance and close with the owningcontents.emit("did-finish-load");assert.deepEqual(contents.sent[0], ["siyuan-settings-command", {tab: "appearance"}]);assert.equal(open({token: "third-token", command: {tab: "search"}}).create, false);- assert.equal(shown[0], win);+ assert.equal(shown.length, 0);assert.deepEqual(contents.sent[1], ["siyuan-settings-command", {tab: "search"}]);+ win.emit("ready-to-show");+ assert.equal(shown.length, 0);+ ready({sender: contents, senderFrame: contents.mainFrame});+ assert.equal(shown[0], win);+ assert.equal(open({token: "visible-token"}).create, false);+ assert.equal(shown.length, 2);owner.emit("destroyed");assert.equal(destroyed, true);assert.deepEqual(owner.sent.at(-1), ["siyuan-settings-closed", "first-token"]);assert.equal(open({token: "fourth-token"}).create, true);});+for (const rendererFirst of [false, true]) {+ test(`settings wait for the renderer and first paint before maximizing or showing (rendererFirst=${rendererFirst})`, () => {+ const {policy, owner, open, ready, shown} = setup();+ const prepared = open({geometry: {maximized: true}});+ policy(owner, prepared);+ let maximized = 0;+ const contents = Object.assign(new EventEmitter(), {mainFrame: {}, sent: [],+ send(...message) { this.sent.push(message); }});+ const win = Object.assign(new EventEmitter(), {webContents: contents, isDestroyed: () => false,+ setMenu() {}, maximize() { maximized++; }});+ owner.emit("did-create-window", win, {url: prepared.url});+ assert.equal(open({token: "loading-token", command: {tab: "appearance"}}).create, false);+ ready({sender: owner, senderFrame: owner.mainFrame});+ ready({sender: contents, senderFrame: {}});+ contents.emit("did-finish-load");+ assert.deepEqual(contents.sent.at(-1), ["siyuan-settings-command", {tab: "appearance"}]);+ assert.equal(maximized, 0);+ assert.equal(shown.length, 0);+ const rendererReady = () => ready({sender: contents, senderFrame: contents.mainFrame});+ const paintReady = () => win.emit("ready-to-show");+ (rendererFirst ? rendererReady : paintReady)();+ assert.equal(maximized, 0);+ assert.equal(shown.length, 0);+ (rendererFirst ? paintReady : rendererReady)();+ assert.equal(maximized, 1);+ assert.deepEqual(shown, [win]);+ rendererReady();+ assert.equal(shown.length, 1);+ });+}+test("plugin windows are distinct from built-in settings and reject other origins", () => {const {open, owner} = setup();assert.equal(open().create, true);diff --git a/app/src/assets/scss/component/_dialog.scss b/app/src/assets/scss/component/_dialog.scssindex d546b49ae8..b269f4a4f8 100644--- a/app/src/assets/scss/component/_dialog.scss+++ b/app/src/assets/scss/component/_dialog.scss@@ -1,5 +1,11 @@.b3-dialog {&--window {+ & > .b3-dialog__container {+ transform: none;+ opacity: 1;+ transition: none;+ }+& > .b3-dialog__container > .toolbar {flex-shrink: 0;}diff --git a/app/src/config/setting/window.ts b/app/src/config/setting/window.tsindex 7813a52d68..eba096bd4a 100644--- a/app/src/config/setting/window.ts+++ b/app/src/config/setting/window.ts@@ -32,6 +32,7 @@ import type {ISettingsCommand} from "./nativeWindow";import {getSettingTabDefs} from "./tabs";import {onWindowsMsg} from "../../window/onWindowsMsg";import {applyWindowState} from "../../boot/windowControls";+import {waitForSettingsWindowPaint} from "./windowPaint";const initialize = async () => {addBaseURL();@@ -139,50 +140,56 @@ const initialize = async () => {if (Array.isArray(emoji.data)) {window.siyuan.emojis = emoji.data;}- await loadAssets(window.siyuan.config.appearance);- await setInlineStyle();- initAssets();- initMessage();- initNativeDialogOverride();- initWindowOpenOverride(host.app);- document.title = host.plugin?.name || window.siyuan.languages.config;- if (host.plugin) {- host.plugin.mount(options => {- const setting = new Setting(options);- options.items.forEach(item => setting.addItem(item));- setting.open(host.plugin.name);- return setting.dialog;- });- } else {- const tab = getSettingTabDefs().find(def => def.id === new URLSearchParams(location.search).get("tab"))?.id;- dialog = openSettingDialog(host.app, tab);- dialog.element.querySelectorAll(".config__side .b3-list-item").forEach(item => {- item.addEventListener("click", () => {- const url = new URL(location.href);- url.searchParams.set("tab", item.getAttribute("data-name"));- history.replaceState(null, "", url);+ await waitForSettingsWindowPaint(async () => {+ await loadAssets(window.siyuan.config.appearance);+ await setInlineStyle();+ initAssets();+ initMessage();+ initNativeDialogOverride();+ initWindowOpenOverride(host.app);+ document.title = host.plugin?.name || window.siyuan.languages.config;+ if (host.plugin) {+ host.plugin.mount(options => {+ const setting = new Setting(options);+ options.items.forEach(item => setting.addItem(item));+ setting.open(host.plugin.name);+ return setting.dialog;+ });+ } else {+ const tab = getSettingTabDefs().find(def => def.id === new URLSearchParams(location.search).get("tab"))?.id;+ dialog = openSettingDialog(host.app, tab);+ dialog.element.querySelectorAll(".config__side .b3-list-item").forEach(item => {+ item.addEventListener("click", () => {+ const url = new URL(location.href);+ url.searchParams.set("tab", item.getAttribute("data-name"));+ history.replaceState(null, "", url);+ });});- });- }- document.addEventListener("keydown", event => {- if (!window.siyuan.menus.menu.element.classList.contains("fn__none") && bindMenuKeydown(event)) return;- if (event.key === "Escape" && !event.isComposing && !event.repeat) {- window.siyuan.dialogs[window.siyuan.dialogs.length - 1]?.destroy();- event.preventDefault();}+ document.addEventListener("keydown", event => {+ if (!window.siyuan.menus.menu.element.classList.contains("fn__none") && bindMenuKeydown(event)) return;+ if (event.key === "Escape" && !event.isComposing && !event.repeat) {+ window.siyuan.dialogs[window.siyuan.dialogs.length - 1]?.destroy();+ event.preventDefault();+ }+ });+ window.addEventListener("mousemove", windowMouseMove);+ window.addEventListener("blur", hideTooltip);+ window.addEventListener("resize", () => window.siyuan.menus.menu.resetPosition());+ window.addEventListener("unload", () => {+ ws.ws.onclose = null;+ ws.ws.close();+ host.plugin?.closed();+ });+ window.siyuan.isReady = true;+ ws.flushMainMessages();+ await applyCommand();});- window.addEventListener("mousemove", windowMouseMove);- window.addEventListener("blur", hideTooltip);- window.addEventListener("resize", () => window.siyuan.menus.menu.resetPosition());- window.addEventListener("unload", () => {- ws.ws.onclose = null;- ws.ws.close();- host.plugin?.closed();- });- window.siyuan.isReady = true;- ws.flushMainMessages();- await applyCommand();+ ipcRenderer.send("siyuan-settings-ready");};installPluginStorageFetchAppId(window, Constants.SIYUAN_APPID, window.location.href);-void initialize().catch(error => console.error("Could not initialize the settings window", error));+void initialize().catch(error => {+ console.error("Could not initialize the settings window", error);+ window.close();+});diff --git a/app/src/config/setting/windowPaint.ts b/app/src/config/setting/windowPaint.tsnew file mode 100644index 0000000000..f1e366199b--- /dev/null+++ b/app/src/config/setting/windowPaint.ts@@ -0,0 +1,35 @@+// 等主题样式和设置内容绘制完成,再通知主进程显示原生窗口。+export const waitForSettingsWindowPaint = async (render: () => Promise<void>) => {+ const initialStyles = new Set(document.head.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]'));+ const styles = new Map<HTMLLinkElement, () => void>();+ const pending: Promise<void>[] = [];+ const collectStyles = () => {+ document.head.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]').forEach(style => {+ if (initialStyles.has(style) || style.sheet || styles.has(style) || style.disabled) return;+ pending.push(new Promise<void>(resolve => {+ const complete = () => {+ style.removeEventListener("load", complete);+ style.removeEventListener("error", complete);+ resolve();+ };+ styles.set(style, complete);+ style.addEventListener("load", complete, {once: true});+ style.addEventListener("error", complete, {once: true});+ }));+ });+ styles.forEach((complete, style) => {+ if (!style.isConnected || style.disabled) complete();+ });+ };+ const observer = new MutationObserver(collectStyles);+ observer.observe(document.head, {childList: true});+ try {+ await render();+ collectStyles();+ await Promise.all(pending);+ await new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));+ } finally {+ observer.disconnect();+ styles.forEach(complete => complete());+ }+};diff --git a/app/tests/settingsWindow.test.js b/app/tests/settingsWindow.test.jsindex bed22efd55..14688f760b 100644--- a/app/tests/settingsWindow.test.js+++ b/app/tests/settingsWindow.test.js@@ -37,27 +37,50 @@ const rendererModules = (sources) => {};const bootChild = async (sources) => {+ const {ipcRenderer} = require("electron");+ const {waitForSettingsWindowPaint} = loadRendererModule(sources.paint, {});const {Dialog, genUUID, context, fit} = rendererModules(sources);const host = await new Promise(resolve => {const token = new URLSearchParams(location.search).get("settingsWindowToken");window.opener.dispatchEvent(new CustomEvent("siyuan-settings-host-" + token, {detail: resolve}));});- if (host.plugin) {- const {Setting} = loadRendererModule(sources.setting, {- "../util/functions": {isMobile: () => false, getFrontend: () => "desktop-window"},- "../dialog": {Dialog}, "../config/setting/nativeWindow": {},- "../config/setting/windowContext": context, "../config/setting/windowDialog": fit,- "../util/genID": {genUUID},- });- host.plugin.mount(options => {- const setting = new Setting(options);- options.items.forEach(item => setting.addItem(item));- setting.open(host.plugin.name);- return setting.dialog;- });- window.addEventListener("unload", () => host.plugin.closed());- }- require("electron").ipcRenderer.send("test-settings-ready");+ await waitForSettingsWindowPaint(async () => {+ const theme = document.createElement("link");+ theme.id = "pendingTheme";+ theme.rel = "stylesheet";+ theme.href = "/fixture/pending.css";+ document.head.append(theme);+ const missing = document.createElement("link");+ missing.rel = "stylesheet";+ missing.href = "/fixture/missing.css";+ document.head.append(missing);+ const canceled = document.createElement("link");+ canceled.rel = "stylesheet";+ canceled.href = "/fixture/pending.css?canceled";+ document.head.append(canceled);+ await ipcRenderer.invoke("test-settings-initializing");+ canceled.remove();+ if (host.plugin) {+ const {Setting} = loadRendererModule(sources.setting, {+ "../util/functions": {isMobile: () => false, getFrontend: () => "desktop-window"},+ "../dialog": {Dialog}, "../config/setting/nativeWindow": {},+ "../config/setting/windowContext": context, "../config/setting/windowDialog": fit,+ "../util/genID": {genUUID},+ });+ host.plugin.mount(options => {+ const setting = new Setting(options);+ options.items.forEach(item => setting.addItem(item));+ setting.open(host.plugin.name);+ return setting.dialog;+ });+ window.addEventListener("unload", () => host.plugin.closed());+ } else {+ document.body.append(document.createElement("div"));+ }+ });+ if (!document.getElementById("pendingTheme").sheet) throw new Error("settings shown before theme loaded");+ ipcRenderer.send("siyuan-settings-ready");+ ipcRenderer.send("test-settings-ready");};const runCases = async (sources) => {@@ -164,6 +187,7 @@ if (process.versions.electron && process.type === "browser") {let ready = 0;let waiting;const children = new Set();+ const shown = new Set();const commands = [];const ts = require("typescript");const sources = {};@@ -173,7 +197,8 @@ if (process.versions.electron && process.type === "browser") {const themes = Object.fromEntries(["daylight", "midnight"].map(name => [name,fs.readFileSync(path.join(__dirname, "../appearance/themes", name, "theme.css"), "utf8")]));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"})) {+ native: "config/setting/nativeWindow.ts", fit: "config/setting/windowDialog.ts", controls: "boot/windowControls.ts",+ paint: "config/setting/windowPaint.ts"})) {sources[key] = ts.transpileModule(fs.readFileSync(path.join(__dirname, "../src", file), "utf8"), {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},}).outputText;@@ -182,6 +207,15 @@ if (process.versions.electron && process.type === "browser") {const pathname = new URL(request.url, "http://localhost").pathname;if (pathname.startsWith("/fixture/")) {response.setHeader("Content-Type", "text/css; charset=utf-8");+ if (pathname === "/fixture/missing.css") {+ response.writeHead(404);+ response.end();+ return;+ }+ if (pathname === "/fixture/pending.css") {+ setTimeout(() => response.end(themes.midnight), 200);+ return;+ }response.end(pathname === "/fixture/base.css" ? styles : themes[path.basename(pathname, ".css")]);return;}@@ -205,9 +239,18 @@ if (process.versions.electron && process.type === "browser") {assert.equal(win.getParentWindow(), null);assert.equal(win.isModal(), false);if (process.platform !== "darwin") assert.equal(win.isMenuBarVisible(), false);- win.on("closed", () => children.delete(win));- }, show() {}, log() {}});- ipcMain.on("test-settings-ready", () => {+ assert.equal(win.isVisible(), false);+ win.on("closed", () => { children.delete(win); shown.delete(win); });+ }, show(win) { shown.add(win); }, log() {}});+ ipcMain.handle("test-settings-initializing", event => {+ const win = [...children].find(child => child.webContents === event.sender);+ assert.ok(win);+ assert.equal(shown.has(win), false);+ assert.equal(win.isVisible(), false);+ });+ ipcMain.on("test-settings-ready", event => {+ const win = [...children].find(child => child.webContents === event.sender);+ assert.equal(shown.has(win), true);if (waiting) { waiting(); waiting = undefined; } else ready++;});ipcMain.handle("test-settings-wait", () => ready ? (--ready, Promise.resolve()) : new Promise(resolve => { waiting = resolve; }));@@ -224,7 +267,7 @@ if (process.versions.electron && process.type === "browser") {owner = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});owner.webContents.setWindowOpenHandler(details => {const result = policy(owner.webContents, details);- return result ? {...result, overrideBrowserWindowOptions: {...result.overrideBrowserWindowOptions, show: false}} : {action: "deny"};+ return result || {action: "deny"};});await owner.loadURL(origin + "/stage/build/app/");await owner.webContents.executeJavaScript(`const loadRendererModule = ${loadRendererModule.toString()}; const rendererModules = ${rendererModules.toString()}; (${runCases.toString()})(${JSON.stringify(sources)})`);