An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:zap: Improve first settings window startup https://github.com/siyuan-note/siyuan/issues/20106
Liang Dingd2a55b25d4b4
diff --git a/app/electron/settingsWindows.js b/app/electron/settingsWindows.jsindex b4551eecd0..2333fc7963 100644--- a/app/electron/settingsWindows.js+++ b/app/electron/settingsWindows.js@@ -95,6 +95,7 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, loif (approved?.owner === event.sender && approved.data.token === data.token) cancel(approved);});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 ||!/^[a-zA-Z0-9-]{1,100}$/.test(data.token) ||@@ -132,7 +133,7 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, lourl.searchParams.set("remote", "1");}const frameName = "siyuan-settings-" + data.token;- const approved = {key, target, owner: event.sender, url: url.href, frameName, data,+ const approved = {key, target, owner: event.sender, url: url.href, frameName, data, requestedAt,active: true, expires: Date.now() + 60000};watchOwner(event.sender).records.add(approved);approved.timer = setTimeout(() => cancel(approved), 60000);@@ -160,6 +161,9 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, lostate.shown = true;if (state.data.geometry?.maximized) win.maximize();show(win);+ win.webContents.setBackgroundThrottling(true);+ win.webContents.send("siyuan-settings-shown");+ log("settings window revealed [" + (Date.now() - approved.requestedAt) + "ms since open request]");};windowStates.set(win, state);win.once("ready-to-show", () => {@@ -235,6 +239,8 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, lonodeIntegrationInWorker: false,webviewTag: approved.target.mode !== "remote",webSecurity: approved.target.mode === "remote",+ // 首次显示前保持帧和定时器正常调度,显示后恢复后台节流。+ backgroundThrottling: false,},},};diff --git a/app/electron/settingsWindows.test.js b/app/electron/settingsWindows.test.jsindex ef675d828d..45cb739749 100644--- a/app/electron/settingsWindows.test.js+++ b/app/electron/settingsWindows.test.js@@ -138,6 +138,7 @@ test("settings popup authorization requires the registered top-level page and exassert.equal(allowed.overrideBrowserWindowOptions.autoHideMenuBar, true);assert.equal(allowed.overrideBrowserWindowOptions.parent, undefined);assert.equal(allowed.overrideBrowserWindowOptions.webPreferences.webSecurity, true);+ assert.equal(allowed.overrideBrowserWindowOptions.webPreferences.backgroundThrottling, false);assert.equal(policy(owner, prepared), undefined);event.senderFrame = {};assert.equal(open({token: "second-token"}).create, false);@@ -148,7 +149,8 @@ test("settings windows reuse their workspace instance and close with the owningconst prepared = open();assert.equal(open({token: "second-token", command: {tab: "appearance"}}).create, false);policy(owner, prepared);- const contents = Object.assign(new EventEmitter(), {mainFrame: {}, sent: [], send(...message) { this.sent.push(message); }});+ const contents = Object.assign(new EventEmitter(), {mainFrame: {}, sent: [], setBackgroundThrottling() {},+ send(...message) { this.sent.push(message); }});let destroyed = false;const win = Object.assign(new EventEmitter(), {webContents: contents, isDestroyed: () => destroyed,@@ -181,8 +183,12 @@ for (const rendererFirst of [false, true]) {const prepared = open({geometry: {maximized: true}});policy(owner, prepared);let maximized = 0;+ const throttling = [];const contents = Object.assign(new EventEmitter(), {mainFrame: {}, sent: [],- send(...message) { this.sent.push(message); }});+ send(...message) {+ if (message[0] === "siyuan-settings-shown") assert.deepEqual(shown, [win]);+ this.sent.push(message);+ }, setBackgroundThrottling: value => throttling.push(value)});const win = Object.assign(new EventEmitter(), {webContents: contents, isDestroyed: () => false,setMenu() {}, maximize() { maximized++; }});owner.emit("did-create-window", win, {url: prepared.url});@@ -193,6 +199,7 @@ for (const rendererFirst of [false, true]) {assert.deepEqual(contents.sent.at(-1), ["siyuan-settings-command", {tab: "appearance"}]);assert.equal(maximized, 0);assert.equal(shown.length, 0);+ assert.deepEqual(throttling, []);const rendererReady = () => ready({sender: contents, senderFrame: contents.mainFrame});const paintReady = () => win.emit("ready-to-show");(rendererFirst ? rendererReady : paintReady)();@@ -201,8 +208,11 @@ for (const rendererFirst of [false, true]) {(rendererFirst ? paintReady : rendererReady)();assert.equal(maximized, 1);assert.deepEqual(shown, [win]);+ assert.deepEqual(throttling, [true]);+ assert.deepEqual(contents.sent.at(-1), ["siyuan-settings-shown"]);rendererReady();assert.equal(shown.length, 1);+ assert.equal(contents.sent.filter(message => message[0] === "siyuan-settings-shown").length, 1);});}diff --git a/app/src/config/setting/window.ts b/app/src/config/setting/window.tsindex f4cac8aa10..0428994bd1 100644--- a/app/src/config/setting/window.ts+++ b/app/src/config/setting/window.ts@@ -83,7 +83,10 @@ const initialize = async () => {listeners.push({channel, listener});ipcRenderer.on(channel, listener);};- const runtime = createSettingsWindowRuntime(isActive);+ const runtime = createSettingsWindowRuntime(isActive, true);+ listen("siyuan-settings-shown", () => {+ void runtime.enableSnippetScripts();+ });let dialog: Dialog;let command: ISettingsCommand;const applyCommand = async () => {diff --git a/app/src/config/setting/windowPaint.test.ts b/app/src/config/setting/windowPaint.test.tsnew file mode 100644index 0000000000..a9c897664c--- /dev/null+++ b/app/src/config/setting/windowPaint.test.ts@@ -0,0 +1,72 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";++const fixture = () => {+ let id = 0;+ let disconnected = false;+ const frames = new Map<number, () => void>();+ const timers = new Map<number, () => void>();+ const listeners = new Map<string, () => void>();+ const styles: unknown[] = [];+ const exports = {} as typeof import("./windowPaint");+ runInNewContext(transpileModule(readFileSync("src/config/setting/windowPaint.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText, {exports, document: {head: {querySelectorAll: () => styles}},+ MutationObserver: class {observe() {} disconnect() { disconnected = true; }},+ window: {+ setTimeout: (callback: () => void, delay: number) => {+ assert.equal(delay, 250);+ timers.set(++id, callback);+ return id;+ }, clearTimeout: (timer: number) => timers.delete(timer),+ },+ requestAnimationFrame: (callback: () => void) => { frames.set(++id, callback); return id; },+ cancelAnimationFrame: (frame: number) => frames.delete(frame),+ });+ const addStyle = () => styles.push({isConnected: true, disabled: false, sheet: null,+ addEventListener: (name: string, callback: () => void) => listeners.set(name, callback),+ removeEventListener: (name: string) => listeners.delete(name),+ });+ const nextFrame = () => {+ const callbacks = [...frames.values()];+ frames.clear();+ callbacks.forEach(callback => callback());+ };+ return {wait: exports.waitForSettingsWindowPaint, frames, timers, listeners, addStyle, nextFrame,+ disconnected: () => disconnected};+};++for (const finishBy of ["frames", "timeout"]) {+ test(`settings paint waits for styles and releases frame resources on ${finishBy}`, async () => {+ const f = fixture();+ let complete = false;+ const pending = f.wait(async () => { f.addStyle(); }).then(() => { complete = true; });+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(f.timers.size, 0);+ assert.equal(f.frames.size, 0);+ assert.equal(complete, false);+ f.listeners.get("load")();+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(f.timers.size, 1);+ f.nextFrame();+ assert.equal(complete, false);+ if (finishBy === "frames") f.nextFrame();+ else [...f.timers.values()][0]();+ await pending;+ assert.equal(f.frames.size, 0);+ assert.equal(f.timers.size, 0);+ assert.equal(f.listeners.size, 0);+ assert.equal(f.disconnected(), true);+ });+}++test("settings paint releases its observer when rendering fails", async () => {+ const f = fixture();+ await assert.rejects(f.wait(async () => { throw new Error("render failed"); }), /render failed/);+ assert.equal(f.disconnected(), true);+ assert.equal(f.frames.size, 0);+ assert.equal(f.timers.size, 0);+});diff --git a/app/src/config/setting/windowPaint.ts b/app/src/config/setting/windowPaint.tsindex f1e366199b..9374eb2a35 100644--- a/app/src/config/setting/windowPaint.ts+++ b/app/src/config/setting/windowPaint.ts@@ -1,3 +1,5 @@+const FRAME_WAIT_LIMIT = 250;+// 等主题样式和设置内容绘制完成,再通知主进程显示原生窗口。export const waitForSettingsWindowPaint = async (render: () => Promise<void>) => {const initialStyles = new Set(document.head.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]'));@@ -27,7 +29,17 @@ export const waitForSettingsWindowPaint = async (render: () => Promise<void>) =>await render();collectStyles();await Promise.all(pending);- await new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));+ await new Promise<void>(resolve => {+ let frame = 0;+ const finish = () => {+ window.clearTimeout(timer);+ cancelAnimationFrame(frame);+ resolve();+ };+ // 帧回调未及时执行时允许继续显示,原生窗口仍需满足 ready-to-show。+ const timer = window.setTimeout(finish, FRAME_WAIT_LIMIT);+ frame = requestAnimationFrame(() => { frame = requestAnimationFrame(finish); });+ });} finally {observer.disconnect();styles.forEach(complete => complete());diff --git a/app/src/config/setting/windowRuntime.test.ts b/app/src/config/setting/windowRuntime.test.tsindex b295d8ff91..750d97b867 100644--- a/app/src/config/setting/windowRuntime.test.ts+++ b/app/src/config/setting/windowRuntime.test.ts@@ -14,13 +14,14 @@ const deferred = () => {};const tick = () => new Promise(resolve => setImmediate(resolve));-const fixture = () => {+const fixture = (deferSnippetScripts = false) => {let active = true;let notebooks: () => Promise<unknown> = async () => {};let fetch: (url: string) => Promise<unknown> = async url => url.endsWith("getConf") ?{code: 0, data: {conf: {snippet: {enabledCSS: true, enabledJS: true}}}} : {code: 0, data: {zoom: 1.25}};const calls: {type: string; value?: unknown}[] = [];const guards: (() => boolean)[] = [];+ const scriptModes: boolean[] = [];const storage: Record<string, unknown> = {zoom: 1};const config = {snippet: {enabledCSS: true, enabledJS: false}, appearance: {hideToolbar: true}};const window = {siyuan: {storage, config, notebooks: [{id: "a", name: "Renamed", closed: false}],@@ -35,8 +36,9 @@ const fixture = () => {isMac: () => true,setNoteBook: async (callback: () => void) => { calls.push({type: "notebooks"}); await notebooks(); callback(); },fetchSyncPost: (url: string) => { calls.push({type: "fetch", value: url}); return fetch(url); },- renderSnippet: async (_timeout: number, guard: () => boolean, beforeJS: () => Promise<void>) => {- if (config.snippet.enabledJS) await beforeJS();+ renderSnippet: async (_timeout: number, guard: () => boolean, beforeJS: () => Promise<void>, includeJS: boolean) => {+ scriptModes.push(includeJS);+ if (includeJS && config.snippet.enabledJS) await beforeJS();calls.push({type: "snippet", value: config.snippet}); guards.push(guard);},getHostCapabilities: () => ({customAppearance: true}),@@ -54,13 +56,36 @@ const fixture = () => {document: {getElementById: (id: string) => elements.get(id), createElement: () => ({}),querySelectorAll: () => elements.has("history") ? [elements.get("history")] : []},require: () => dependencies});- const runtime = exports.createSettingsWindowRuntime(() => active);- return {runtime, exports, calls, guards, config, storage, window, location, elements,+ const runtime = exports.createSettingsWindowRuntime(() => active, deferSnippetScripts);+ return {runtime, exports, calls, guards, scriptModes, config, storage, window, location, elements,setActive: (value: boolean) => { active = value; },setNotebooks: (value: typeof notebooks) => { notebooks = value; },setFetch: (value: typeof fetch) => { fetch = value; }};};+test("startup snippet refreshes and configuration messages defer Lute until the window is shown", async () => {+ const f = fixture(true);+ f.config.snippet.enabledJS = true;+ await f.runtime.refreshSnippets();+ f.runtime.handleMessage({cmd: "setSnippet", data: {enabledCSS: true, enabledJS: true}} as IWebSocketData);+ await tick();+ await f.runtime.reconnect();+ assert.deepEqual(f.scriptModes, [false, false, false]);+ assert.equal(f.calls.some(call => call.type === "lute"), false);+ await f.runtime.enableSnippetScripts();+ assert.deepEqual(f.scriptModes, [false, false, false, true]);+ assert.equal(f.calls.filter(call => call.type === "lute").length, 1);+ await f.runtime.enableSnippetScripts();+ assert.equal(f.scriptModes.length, 4);+});++test("deferred snippet scripts stay disabled when the owner has been disposed", async () => {+ const f = fixture(true);+ f.setActive(false);+ await f.runtime.enableSnippetScripts();+ assert.equal(f.scriptModes.length, 0);+});+test("settings host handshake fails closed for missing, stale, asynchronous and cross-origin owners", () => {const f = fixture();const host = {isActive: () => true};diff --git a/app/src/config/setting/windowRuntime.ts b/app/src/config/setting/windowRuntime.tsindex ff0c7ff62f..aaea72e406 100644--- a/app/src/config/setting/windowRuntime.ts+++ b/app/src/config/setting/windowRuntime.ts@@ -85,13 +85,14 @@ export const patchSettingsNotebookOptions = () => {});};-export const createSettingsWindowRuntime = (isActive: () => boolean) => {+export const createSettingsWindowRuntime = (isActive: () => boolean, deferSnippetScripts = false) => {let notebooksPending = false;let notebooksLoading: Promise<void>;let snippetRevision = 0;let snippetsPending = false;let snippetConfigPending = false;let snippetsLoading: Promise<void>;+ let snippetScriptsEnabled = !deferSnippetScripts;let zoomRevision = 0;const applyZoom = () => {@@ -149,7 +150,7 @@ export const createSettingsWindowRuntime = (isActive: () => boolean) => {}if (!isActive()) return;await renderSnippet(Constants.TIMEOUT_SNIPPET_LOAD, () => isActive() && revision === snippetRevision,- () => ensureLute({reloadOnFailure: false}));+ () => ensureLute({reloadOnFailure: false}), snippetScriptsEnabled);}})().catch(error => console.error("Could not refresh settings snippets", error)).finally(() => {snippetsLoading = undefined;@@ -158,6 +159,13 @@ export const createSettingsWindowRuntime = (isActive: () => boolean) => {return snippetsLoading;};+ // 原生窗口首次显示后启用脚本,启动期间的刷新只应用 CSS。+ const enableSnippetScripts = () => {+ if (snippetScriptsEnabled || !isActive()) return Promise.resolve();+ snippetScriptsEnabled = true;+ return refreshSnippets();+ };+const refreshZoom = async () => {const revision = ++zoomRevision;const response = await fetchSyncPost("/api/storage/getLocalStorage");@@ -214,5 +222,5 @@ export const createSettingsWindowRuntime = (isActive: () => boolean) => {if (!isActive()) return;await Promise.all([refreshNotebooks(), refreshSnippets(true), refreshZoom()]);};- return {applyZoom, refreshNotebooks, refreshSnippets, handleMessage, reconnect};+ return {applyZoom, refreshNotebooks, refreshSnippets, enableSnippetScripts, handleMessage, reconnect};};diff --git a/app/src/config/util/snippets.test.ts b/app/src/config/util/snippets.test.tsindex a8a3bcde12..88d9f34ef0 100644--- a/app/src/config/util/snippets.test.ts+++ b/app/src/config/util/snippets.test.ts@@ -128,3 +128,34 @@ test("JS waits for its dependency and respects disposal while the dependency isawait render;assert.equal(f.executed.length, 0);});++test("styles-only initialization applies CSS without loading Lute or executing enabled JS", async () => {+ const f = fixture();+ let dependencies = 0;+ const beforeJS = async () => { dependencies++; };+ const snippets = [{id: "style", type: "css", enabled: true, content: "body {color: red;}"},+ {id: "script", type: "js", enabled: true, content: "run();"}];+ const styles = f.exports.renderSnippet(0, () => true, beforeJS, false);+ f.requests.at(-1).complete(snippets);+ await styles;+ assert.equal(f.elements.get("snippetCSSstyle").textContent, snippets[0].content);+ assert.equal(dependencies, 0);+ assert.equal(f.executed.length, 0);+ const scripts = f.exports.renderSnippet(0, () => true, beforeJS);+ f.requests.at(-1).complete(snippets);+ await scripts;+ assert.equal(dependencies, 1);+ assert.deepEqual(f.executed, [snippets[1].content]);+ assert.equal(f.measurements(), 1);+});++test("disabled JS snippets never load their dependency", async () => {+ const f = fixture();+ f.config.snippet.enabledJS = false;+ let dependencies = 0;+ const rendered = f.exports.renderSnippet(0, () => true, async () => { dependencies++; });+ f.requests.at(-1).complete([{id: "script", type: "js", enabled: true, content: "run();"}]);+ await rendered;+ assert.equal(dependencies, 0);+ assert.equal(f.executed.length, 0);+});diff --git a/app/src/config/util/snippets.ts b/app/src/config/util/snippets.tsindex a520591ae7..c0052bf75a 100644--- a/app/src/config/util/snippets.ts+++ b/app/src/config/util/snippets.ts@@ -6,7 +6,7 @@ import {Constants} from "../../constants";import {refreshHeadingNumberMeasurements} from "../../util/assets";import {getExtensionScriptNonce, getHostCapabilities} from "../../util/hostCapabilities";-export const renderSnippet = (timeout = 0, isActive = () => true, beforeJS?: () => Promise<void>) => {+export const renderSnippet = (timeout = 0, isActive = () => true, beforeJS?: () => Promise<void>, includeJS = true) => {if (!isActive() || !getHostCapabilities().customAppearance) {return Promise.resolve();}@@ -39,6 +39,7 @@ export const renderSnippet = (timeout = 0, isActive = () => true, beforeJS?: ()});response.data.snippets.forEach((item: ISnippet) => {if (!isActive()) return;+ if (item.type === "js" && !includeJS) return;const id = `snippet${item.type === "css" ? "CSS" : "JS"}${item.id}`;const exitElement = document.getElementById(id) as HTMLScriptElement | HTMLStyleElement;if ((!window.siyuan.config.snippet.enabledCSS && item.type === "css") ||diff --git a/app/tests/settingsBoot.test.js b/app/tests/settingsBoot.test.jsindex 20630aff15..a98e60c746 100644--- a/app/tests/settingsBoot.test.js+++ b/app/tests/settingsBoot.test.js@@ -4,7 +4,7 @@ const {test} = require("node:test");const {runInNewContext} = require("node:vm");const {ModuleKind, ScriptTarget, transpileModule} = require("typescript");-const createBoot = (plugin = false, failed = "") => {+const createBoot = (plugin = false, failed = "", waitForStyles = false) => {const source = readFileSync("src/config/setting/window.ts", "utf8");const code = transpileModule(source.slice(0, source.indexOf("void startSettingsWindow(")) + "\nexport {initialize};", {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},@@ -13,6 +13,7 @@ const createBoot = (plugin = false, failed = "") => {const calls = [];let luteLoaded = false;let command;+ let shown;const wait = name => {calls.push(name);return new Promise(resolve => pending.set(name, resolve));@@ -40,6 +41,7 @@ const createBoot = (plugin = false, failed = "") => {const modules = {"electron": {ipcRenderer: {on: (name, callback) => {if (name === "siyuan-settings-command") command = callback;+ if (name === "siyuan-settings-shown") shown = callback;}, removeListener() {}, send: name => calls.push(name), invoke: async () => false}, webFrame: {setZoomFactor() {}}},"../../constants": {Constants: constants},"../../layout/Model": {Model: class {@@ -94,9 +96,14 @@ const createBoot = (plugin = false, failed = "") => {"./tabs": {getSettingTabDefs: () => []},"../search/dialog": {switchSettingTab: () => wait("assets")},"./windowPaint": {waitForSettingsWindowPaint: async render => render()},- "./windowRuntime": {resolveSettingsWindowHost: () => host, createSettingsWindowRuntime: () => ({- refreshNotebooks: () => wait("notebooks"), refreshSnippets: async () => {}, applyZoom() {}, handleMessage() {},- })},+ "./windowRuntime": {resolveSettingsWindowHost: () => host, createSettingsWindowRuntime: (_active, deferScripts) => {+ assert.equal(deferScripts, true);+ return {+ refreshNotebooks: () => wait("notebooks"),+ refreshSnippets: async () => { if (waitForStyles) await wait("snippet-styles"); },+ enableSnippetScripts: async () => calls.push("snippet-scripts"), applyZoom() {}, handleMessage() {},+ };+ }},"../../plugin/Setting": {Setting: class {addItem() {} open() { calls.push("render"); }}},};const context = {exports: {}, window, document: {body: {classList: {toggle() {}}},@@ -108,10 +115,35 @@ const createBoot = (plugin = false, failed = "") => {window.location = context.location;runInNewContext(code, context);return {initialize: context.exports.initialize, calls, pending, command: next => command({}, next),+ shown: () => shown({}),unload: () => events.get("unload")(), deactivate: () => { active = false; },window, menu, events, eventOptions, documentEvents};};+test("settings wait for snippet styles and start scripts only after the native window is shown", async () => {+ const boot = createBoot(false, "", true);+ const initialized = boot.initialize();+ await new Promise(resolve => setImmediate(resolve));+ for (const complete of boot.pending.values()) complete();+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(boot.calls.includes("snippet-styles"), true);+ assert.equal(boot.calls.includes("siyuan-settings-ready"), false);+ assert.equal(boot.calls.includes("snippet-scripts"), false);+ boot.pending.get("snippet-styles")();+ await initialized;+ assert.equal(boot.calls.includes("siyuan-settings-ready"), true);+ assert.equal(boot.calls.includes("snippet-scripts"), false);+ boot.shown();+ assert.equal(boot.calls.includes("snippet-scripts"), true);+});++test("a late native show notification cannot start scripts after disposal", async () => {+ const boot = await bootReady();+ boot.unload();+ boot.shown();+ assert.equal(boot.calls.includes("snippet-scripts"), false);+});+const bootReady = async () => {const boot = createBoot();const initialized = boot.initialize();