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: Repair native settings lifecycle and runtime synchronization https://github.com/siyuan-note/siyuan/issues/20068 https://github.com/siyuan-note/siyuan/issues/20069
Danielcda245ac7ebf
diff --git a/app/electron/settingsWindows.js b/app/electron/settingsWindows.jsindex 6e61893339..b4551eecd0 100644--- a/app/electron/settingsWindows.js+++ b/app/electron/settingsWindows.js@@ -8,16 +8,59 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, loconst reservations = new Map();const windows = new Map();const windowStates = new WeakMap();+ const owners = new WeakMap();const release = approved => {clearTimeout(approved.timer);- pending.delete(approved.owner.id + ":" + approved.frameName);+ const key = approved.owner.id + ":" + approved.frameName;+ if (pending.get(key) === approved) pending.delete(key);if (reservations.get(approved.key) === approved) reservations.delete(approved.key);- approved.owner.removeListener("destroyed", approved.cancel);- if (approved.created) approved.owner.removeListener("did-create-window", approved.created);};- const cancel = approved => {+ const finish = (approved, ownerInvalidated = false) => {+ if (!approved.active) return;+ approved.active = false;release(approved);- if (!approved.owner.isDestroyed()) approved.owner.send("siyuan-settings-closed", approved.data.token);+ owners.get(approved.owner).records.delete(approved);+ if (windows.get(approved.key) === approved.win) windows.delete(approved.key);+ if (!approved.owner.isDestroyed()) {+ try {+ approved.owner.send("siyuan-settings-closed", approved.data.token, ownerInvalidated);+ } catch (error) {+ log("settings owner failed to receive close notification: " + error);+ }+ }+ };+ const cancel = (approved, ownerInvalidated = false) => {+ finish(approved, ownerInvalidated);+ if (approved.win && !approved.win.isDestroyed()) approved.win.destroy();+ };+ const watchOwner = owner => {+ let state = owners.get(owner);+ if (state) return state;+ state = {records: new Set()};+ owners.set(owner, state);+ const invalidate = () => {+ for (const approved of [...state.records]) cancel(approved, true);+ };+ owner.on("did-start-navigation", details => {+ if (details.isMainFrame && !details.isSameDocument) invalidate();+ });+ owner.on("render-process-gone", invalidate);+ owner.once("destroyed", invalidate);+ owner.on("did-create-window", (win, details) => {+ const approved = [...state.records].find(item => item.url === details.url && item.created);+ if (approved) {+ approved.created(win);+ return;+ }+ // 授权失效后才创建的子窗口不能继续使用旧文档的宿主。+ try {+ const url = new URL(details.url);+ if (url.pathname === settingsPath && url.searchParams.has("settingsWindowToken")) win.destroy();+ } catch {+ return;+ }+ });+ return state;};ipcMain.on("siyuan-settings-ready", event => {if (event.senderFrame !== event.sender.mainFrame) return;@@ -30,15 +73,26 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, lo}}});- ipcMain.on("siyuan-settings-close", (event, key) => {+ ipcMain.on("siyuan-settings-close-self", event => {+ if (event.senderFrame !== event.sender.mainFrame) return;+ for (const win of windows.values()) {+ if (!win.isDestroyed() && win.webContents === event.sender) {+ cancel(windowStates.get(win).approved);+ return;+ }+ }+ });+ ipcMain.on("siyuan-settings-close", (event, data) => {const target = getTarget(event.sender.id);- if (!target || event.senderFrame !== event.sender.mainFrame || typeof key !== "string" ||- !/^plugin-[a-zA-Z0-9-]+$/.test(key)) return;- const registryKey = `${target.origin}:${event.sender.id}:${key}`;+ if (!target || event.senderFrame !== event.sender.mainFrame || !data ||+ !/^(builtin|plugin-[a-zA-Z0-9-]+)$/.test(data.key) ||+ !/^[a-zA-Z0-9-]{1,100}$/.test(data.token)) return;+ const registryKey = `${target.origin}:${data.key === "builtin" ? "builtin" : event.sender.id + ":" + data.key}`;const reserved = reservations.get(registryKey);- if (reserved) cancel(reserved);+ if (reserved && reserved.owner === event.sender && reserved.data.token === data.token) cancel(reserved);const win = windows.get(registryKey);- if (win && !win.isDestroyed()) win.close();+ const approved = win && windowStates.get(win).approved;+ if (approved?.owner === event.sender && approved.data.token === data.token) cancel(approved);});ipcMain.handle("siyuan-settings-prepare", (event, data) => {const target = getTarget(event.sender.id);@@ -78,14 +132,14 @@ 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, expires: Date.now() + 60000};- approved.cancel = () => cancel(approved);- approved.timer = setTimeout(approved.cancel, 60000);+ const approved = {key, target, owner: event.sender, url: url.href, frameName, data,+ active: true, expires: Date.now() + 60000};+ watchOwner(event.sender).records.add(approved);+ approved.timer = setTimeout(() => cancel(approved), 60000);approved.timer.unref();- event.sender.once("destroyed", approved.cancel);pending.set(event.sender.id + ":" + frameName, approved);reservations.set(key, approved);- return {create: true, url: approved.url, frameName};+ return {create: true, token: data.token, url: approved.url, frameName};});return (contents, details) => {const pendingKey = contents.id + ":" + details.frameName;@@ -95,13 +149,14 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, loreturn undefined;}pending.delete(pendingKey);- approved.created = (win, created) => {- if (created.url !== approved.url) return;+ approved.created = win => {+ approved.created = undefined;+ approved.win = win;release(approved);windows.set(approved.key, win);- const state = {painted: false, ready: false, shown: false, data: approved.data};+ const state = {painted: false, ready: false, shown: false, data: approved.data, approved};state.reveal = () => {- if (!state.ready || !state.painted || state.shown || win.isDestroyed()) return;+ if (!approved.active || !state.ready || !state.painted || state.shown || win.isDestroyed()) return;state.shown = true;if (state.data.geometry?.maximized) win.maximize();show(win);@@ -120,22 +175,13 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, lowin.webContents.toggleDevTools();}});- initialize(win, approved.target);- const close = () => { if (!win.isDestroyed()) win.destroy(); };- contents.once("destroyed", close);- win.on("closed", () => {- windows.delete(approved.key);- contents.removeListener("destroyed", close);- if (!contents.isDestroyed()) {- contents.send("siyuan-settings-closed", approved.data.token);- }- });+ win.once("closed", () => finish(approved));if (approved.data.key === "builtin") {let geometryTimer;let lastGeometry;const saveGeometry = () => {clearTimeout(geometryTimer);- if (win.isDestroyed() || contents.isDestroyed()) return;+ if (!approved.active || win.isDestroyed() || contents.isDestroyed()) return;const geometry = captureWindowGeometry(win);if (lastGeometry && Object.keys(geometry).every(key => geometry[key] === lastGeometry[key])) return;contents.send("siyuan-settings-geometry", geometry);@@ -152,13 +198,20 @@ const createSettingsWindows = ({ipcMain, screen, getTarget, initialize, show, lowin.once("closed", () => clearTimeout(geometryTimer));}win.webContents.once("did-finish-load", () => {- win.webContents.send("siyuan-settings-command", approved.data.command);+ if (approved.active) win.webContents.send("siyuan-settings-command", approved.data.command);});- win.webContents.on("did-fail-load", (_event, code, description) => {+ win.webContents.on("did-fail-load", (_event, code, description, _url, isMainFrame) => {if (code !== -3) log("settings window failed to load: " + description);+ if (code !== -3 && isMainFrame) cancel(approved);});+ win.webContents.once("render-process-gone", () => cancel(approved));+ try {+ initialize(win, approved.target);+ } catch (error) {+ cancel(approved);+ log("settings window failed to initialize: " + error);+ }};- contents.on("did-create-window", approved.created);return {action: "allow",overrideBrowserWindowOptions: {diff --git a/app/electron/settingsWindows.test.js b/app/electron/settingsWindows.test.jsindex 83dd1c49ca..ef675d828d 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 closeSelf;let ready;const shown = [];const initialized = [];@@ -18,14 +19,15 @@ const setup = (platform = "win32") => {platform,ipcMain: {handle: (_name, callback) => { prepare = callback; }, on: (name, callback) => {if (name === "siyuan-settings-close") close = callback;+ if (name === "siyuan-settings-close-self") closeSelf = callback;if (name === "siyuan-settings-ready") ready = callback;}},- screen: {}, getTarget: id => id === 1 ? target : undefined,+ screen: {}, getTarget: id => [1, 2].includes(id) ? 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, ready, shown, initialized};+ return {policy, owner, event, open, close, closeSelf, ready, shown, initialized, prepare, target};};const setupGeometry = (key = "builtin") => {@@ -169,7 +171,7 @@ test("settings windows reuse their workspace instance and close with the owningassert.equal(shown.length, 2);owner.emit("destroyed");assert.equal(destroyed, true);- assert.deepEqual(owner.sent.at(-1), ["siyuan-settings-closed", "first-token"]);+ assert.deepEqual(owner.sent.at(-1), ["siyuan-settings-closed", "first-token", true]);assert.equal(open({token: "fourth-token"}).create, true);});@@ -228,9 +230,9 @@ test("simultaneous popups initialize their own windows and canceled reservationsconst builtinWindow = create(builtin);assert.deepEqual(initialized.map(args => args[0]), [pluginWindow, builtinWindow]);const canceled = open({token: "canceled-token", key: "plugin-other"});- close(event, "plugin-other");+ close(event, {key: "plugin-other", token: "canceled-token"});assert.equal(policy(owner, canceled), undefined);- assert.deepEqual(owner.sent.at(-1), ["siyuan-settings-closed", "canceled-token"]);+ assert.deepEqual(owner.sent.at(-1), ["siyuan-settings-closed", "canceled-token", false]);assert.equal(open({token: "reopened-token", key: "plugin-other"}).create, true);});@@ -267,3 +269,128 @@ for (const platform of ["win32", "linux", "darwin"]) {assert.equal(prevented, 2);});}++const createWindow = (owner, prepared) => {+ let destroyed = false;+ const webContents = Object.assign(new EventEmitter(), {mainFrame: {}, send() {}});+ const win = Object.assign(new EventEmitter(), {+ webContents, setMenu() {}, isDestroyed: () => destroyed,+ destroy() { destroyed = true; this.emit("closed"); },+ });+ owner.emit("did-create-window", win, {url: prepared.url});+ return win;+};++for (const invalidation of ["navigation", "render-process-gone", "destroyed"]) {+ test(`owner ${invalidation} invalidates windows, reservations and authorized late children`, () => {+ const {owner, open, policy, initialized} = setup();+ const builtin = open();+ policy(owner, builtin);+ const win = createWindow(owner, builtin);+ const pending = open({key: "plugin-pending", token: "pending-token"});+ const late = open({key: "plugin-late", token: "late-token"});+ policy(owner, late);+ if (invalidation === "navigation") owner.emit("did-start-navigation", {isSameDocument: false, isMainFrame: true});+ else owner.emit(invalidation);+ assert.equal(win.isDestroyed(), true);+ assert.equal(policy(owner, pending), undefined);+ assert.equal(createWindow(owner, late).isDestroyed(), true);+ assert.equal(initialized.length, 1);+ assert.deepEqual(owner.sent.filter(item => item[0] === "siyuan-settings-closed").map(item => item.slice(1)),+ [["first-token", true], ["pending-token", true], ["late-token", true]]);+ assert.equal(open({token: "manually-reopened"}).create, true);+ });+}++test("same-document and subframe navigations preserve the settings owner", () => {+ const {owner, open, policy} = setup();+ const prepared = open();+ policy(owner, prepared);+ const win = createWindow(owner, prepared);+ owner.emit("did-start-navigation", {isSameDocument: true, isMainFrame: true});+ owner.emit("did-start-navigation", {isSameDocument: false, isMainFrame: false});+ assert.equal(win.isDestroyed(), false);+ assert.equal(open({token: "reuse-token"}).create, false);+});++test("workspace reuse keeps the original creator as owner until it is invalidated", () => {+ const {owner, open, policy, prepare, target} = setup();+ const secondOwner = Object.assign(new EventEmitter(), {id: 2, mainFrame: {}, getURL: () => target.origin + "/stage/build/app/",+ isDestroyed: () => false, send() {}});+ const event = {sender: secondOwner, senderFrame: secondOwner.mainFrame};+ const prepared = open();+ policy(owner, prepared);+ const win = createWindow(owner, prepared);+ assert.equal(prepare(event, {key: "builtin", token: "second-owner", command: {tab: "appearance"}}).create, false);+ secondOwner.emit("did-start-navigation", {isSameDocument: false, isMainFrame: true});+ assert.equal(win.isDestroyed(), false);+ owner.emit("did-start-navigation", {isSameDocument: false, isMainFrame: true});+ assert.equal(win.isDestroyed(), true);+ const reopened = prepare(event, {key: "builtin", token: "new-owner"});+ assert.equal(reopened.create, true);+ policy(secondOwner, reopened);+ const replacement = createWindow(secondOwner, reopened);+ owner.emit("render-process-gone");+ assert.equal(replacement.isDestroyed(), false);+ secondOwner.emit("render-process-gone");+ assert.equal(replacement.isDestroyed(), true);+});++test("stale token cancellation cannot close a reopened plugin session", () => {+ const {owner, event, open, close, policy} = setup();+ const old = open({key: "plugin-example", token: "old-token"});+ policy(owner, old);+ close(event, {key: "plugin-example", token: "old-token"});+ const replacement = open({key: "plugin-example", token: "new-token"});+ close(event, {key: "plugin-example", token: "old-token"});+ assert.equal(policy(owner, replacement).action, "allow");+ const win = createWindow(owner, replacement);+ assert.equal(createWindow(owner, old).isDestroyed(), true);+ close(event, {key: "plugin-example", token: "old-token"});+ assert.equal(win.isDestroyed(), false);+ close(event, {key: "plugin-example", token: "new-token"});+ assert.equal(win.isDestroyed(), true);+});++test("only the creating owner and matching token may cancel built-in settings", () => {+ const {owner, event, open, close, policy} = setup();+ const prepared = open();+ policy(owner, prepared);+ const win = createWindow(owner, prepared);+ const other = Object.assign(new EventEmitter(), {id: 2, mainFrame: {}});+ close({sender: other, senderFrame: other.mainFrame}, {key: "builtin", token: "first-token"});+ assert.equal(win.isDestroyed(), false);+ close(event, {key: "builtin", token: "wrong-token"});+ assert.equal(win.isDestroyed(), false);+ close(event, {key: "builtin", token: "first-token"});+ assert.equal(win.isDestroyed(), true);+});++test("forced child close validates the sender and skips geometry persistence", () => {+ const {owner, event, open, closeSelf, policy} = setup();+ const prepared = open();+ policy(owner, prepared);+ const win = createWindow(owner, prepared);+ closeSelf(event);+ closeSelf({sender: win.webContents, senderFrame: {}});+ assert.equal(win.isDestroyed(), false);+ closeSelf({sender: win.webContents, senderFrame: win.webContents.mainFrame});+ assert.equal(win.isDestroyed(), true);+ assert.equal(owner.sent.some(item => item[0] === "siyuan-settings-geometry"), false);+});++for (const failure of ["did-fail-load", "render-process-gone"]) {+ test(`child ${failure} releases its owner session and singleton reservation`, () => {+ const {owner, open, policy} = setup();+ const prepared = open();+ policy(owner, prepared);+ const win = createWindow(owner, prepared);+ if (failure === "did-fail-load") {+ win.webContents.emit(failure, {}, -105, "failed", prepared.url, false);+ assert.equal(win.isDestroyed(), false);+ win.webContents.emit(failure, {}, -105, "failed", prepared.url, true);+ } else win.webContents.emit(failure);+ assert.equal(win.isDestroyed(), true);+ assert.equal(open({token: "retry-token"}).create, true);+ });+}diff --git a/app/src/config/entryVisibility/mobileUi.test.ts b/app/src/config/entryVisibility/mobileUi.test.tsindex 30be8a8b04..8519439650 100644--- a/app/src/config/entryVisibility/mobileUi.test.ts+++ b/app/src/config/entryVisibility/mobileUi.test.ts@@ -14,6 +14,9 @@ const browserCases = async (sources: Record<string, string>, languages: Record<s}};let mobile = true;+ let settingsWindow = false;+ const ownerSnapshot: Record<string, string[]> = {};+ let ownerReads = 0;const cache: Record<string, Record<string, any>> = {};const noop = () => {};window.siyuan = {languages, mobile: {}, storage: {}, config: {editor: {codeTabSpaces: 4}, appearance: {@@ -41,6 +44,8 @@ const browserCases = async (sources: Record<string, string>, languages: Record<s"dialog/confirmDialog": {confirmDialog: (_title: string, _text: string, callback: () => void) => callback()},"dialog/message": {showMessage: noop},"protyle/util/compatibility": {isInMobileApp: () => true},+ "config/setting/windowContext": {isSettingsWindow: () => settingsWindow,+ getSettingsWindowHost: () => ({getDockOrderSnapshot: () => { ownerReads++; return ownerSnapshot; }})},};check(id in mocks, `Missing module ${id}`);return mocks[id];@@ -263,6 +268,32 @@ const browserCases = async (sources: Record<string, string>, languages: Record<sview.querySelector<HTMLElement>("[data-action='confirm']").click();check(!("dock.order.LeftTop" in config().profiles[0].orders), "Dock reset must remove its scope record");check(config().profiles[0].orders["dock.order.RightTop"], "Dock reset must preserve the other scopes");+ settingsWindow = true;+ Object.assign(ownerSnapshot, load("config/entryVisibility/dockOrder").createDockEntryOrderSnapshot({+ RightBottom: ["outline", "plugin:unavailable:dock", "file"], BottomLeft: ["graph"],+ }));+ config().profiles[0].orders["dock.order.RightBottom"] = ["outline", "plugin:unavailable:dock", "file"];+ const savedOrders = JSON.stringify(config().profiles[0].orders);+ view = open();+ view.querySelector<HTMLElement>("[data-entry-section='dock']").click();+ const ownerRows = () => view.querySelectorAll("[data-entry-row][data-entry-parent='dock.order.RightBottom']");+ check(ownerRows().length === 2, "Detached settings must use the owner's live dock placement");+ check(ownerRows()[0].getAttribute("data-entry-key") === "outline", "Saved dock order must take precedence");+ const reads = ownerReads;+ ownerSnapshot["dock.order.RightBottom"] = ["outline", "plugin:unavailable:dock"];+ ownerSnapshot["dock.order.LeftBottom"] = ["file"];+ const ownerSearch = view.querySelector<HTMLInputElement>("[data-type='entry-search']");+ ownerSearch.dispatchEvent(new Event("input", {bubbles: true}));+ check(ownerReads === reads && ownerRows().length === 2, "Rerendering a draft must retain its opening snapshot");+ check(JSON.stringify(config().profiles[0].orders) === savedOrders, "Editing must not rewrite saved orders");+ view.querySelector<HTMLElement>("[data-action='confirm']").click();+ check(JSON.stringify(config().profiles[0].orders) === savedOrders, "Saving visibility must preserve unknown order slots");+ view = open("full");+ view.querySelector<HTMLElement>("[data-entry-section='dock']").click();+ check(ownerReads === reads + 1, "A reopened editor must read the owner's current dock snapshot");+ check(view.querySelector("[data-entry-key='file'][data-entry-parent='dock.order.LeftBottom']"),+ "Built-in profiles must display the updated owner placement");+ settingsWindow = false;mobile = true;window.siyuan.mobile = {} as typeof window.siyuan.mobile;view = open();diff --git a/app/src/config/entryVisibility/ui.test.ts b/app/src/config/entryVisibility/ui.test.tsindex 282ad9cbdd..e5cbe73483 100644--- a/app/src/config/entryVisibility/ui.test.ts+++ b/app/src/config/entryVisibility/ui.test.ts@@ -6,6 +6,7 @@ import {runInNewContext} from "node:vm";import {ModuleKind, transpileModule} from "typescript";import {entryCatalog, TOP_BAR_ROOT_PATH} from "./catalog";import {MOBILE_TOOLBAR_NAMES, TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";+import * as dockOrder from "./dockOrder";test("entry settings show exit only on native tablets without changing the persisted catalog", () => {const source = readFileSync(resolve(process.cwd(), "src/config/entryVisibility/ui.ts"), "utf8");@@ -42,3 +43,111 @@ test("entry settings show exit only on native tablets without changing the persiassert.ok(catalog[0].children.some(item => item.key === `mobile-${name}`));}});++const loadDockSnapshot = () => {+ const code = transpileModule(readFileSync("src/config/entryVisibility/ui.ts", "utf8") ++ "\nexports.snapshot = getProfileDockOrderSnapshot;", {+ compilerOptions: {module: ModuleKind.CommonJS},+ }).outputText;+ let settingsWindow = true;+ let reads = 0;+ let ownerSnapshot: unknown = dockOrder.createDockEntryOrderSnapshot({+ RightBottom: ["outline", "plugin:unavailable:dock", "file"], BottomLeft: ["graph"],+ });+ const localSnapshot = dockOrder.createDockEntryOrderSnapshot({LeftTop: ["file", "outline"]});+ const exports = {} as {snapshot: (builtin: boolean) => dockOrder.TDockOrderSnapshot};+ runInNewContext(code, {exports, console: {warn() {}}, require: () => ({+ ...dockOrder,+ isSettingsWindow: () => settingsWindow,+ getSettingsWindowHost: () => ({getDockOrderSnapshot: () => {+ reads++;+ if (ownerSnapshot instanceof Error) throw ownerSnapshot;+ return ownerSnapshot;+ }}),+ getDockEntryOrderSnapshot: () => localSnapshot,+ })});+ return {snapshot: exports.snapshot, localSnapshot, reads: () => reads,+ owner: () => ownerSnapshot as dockOrder.TDockOrderSnapshot,+ setOwner: (snapshot: unknown) => { ownerSnapshot = snapshot; },+ local: () => { settingsWindow = false; }};+};++test("detached entry editors use an isolated owner snapshot and retain unknown dock slots", () => {+ const fixture = loadDockSnapshot();+ const builtin = fixture.snapshot(true);+ const custom = fixture.snapshot(false);+ assert.deepEqual(Array.from(builtin["dock.order.RightBottom"]), ["outline", "plugin:unavailable:dock", "file"]);+ assert.deepEqual(Array.from(custom["dock.order.RightBottom"]), ["file", "plugin:unavailable:dock", "outline"]);+ assert.deepEqual(Array.from(custom["dock.order.BottomLeft"]), ["graph"]);+ assert.deepEqual(Array.from(custom["dock.order.LeftTop"]), []);+ fixture.owner()["dock.order.RightBottom"].push("plugin:new:dock");+ assert.equal(builtin["dock.order.RightBottom"].includes("plugin:new:dock"), false);+ assert.equal(custom["dock.order.RightBottom"].includes("plugin:new:dock"), false);+ assert.equal(fixture.snapshot(true)["dock.order.RightBottom"].includes("plugin:new:dock"), true);+ assert.equal(fixture.reads(), 3);+});++test("owner dock placement merges saved orders without changing configuration or plugin IDs", () => {+ const fixture = loadDockSnapshot();+ const saved = {+ "dock.order.RightBottom": ["outline", "plugin:unavailable:dock", "file"],+ "dock.order.LeftBottom": ["graph", "plugin:disabled:dock"],+ "desktopMenu.plugin:disabled": ["plugin:unknown:item"],+ };+ const original = JSON.stringify(saved);+ const merged = dockOrder.mergeDockEntryOrderSnapshot(fixture.snapshot(false), saved);+ assert.deepEqual(merged["dock.order.RightBottom"], ["outline", "plugin:unavailable:dock", "file"]);+ assert.deepEqual(merged["dock.order.LeftBottom"], ["graph", "plugin:disabled:dock"]);+ assert.deepEqual(merged["dock.order.BottomLeft"], []);+ assert.equal(JSON.stringify(saved), original);+});++test("in-app and mobile entry editors retain local dock defaults", () => {+ const fixture = loadDockSnapshot();+ fixture.local();+ assert.equal(fixture.snapshot(true), fixture.localSnapshot);+ assert.deepEqual(fixture.snapshot(false)["dock.order.LeftTop"], ["file", "outline"]);+ assert.equal(fixture.reads(), 0);+});++test("unavailable or invalid owner dock snapshots fall back to the local layout", () => {+ const fixture = loadDockSnapshot();+ const malformed = dockOrder.createDockEntryOrderSnapshot({});+ for (const owner of [undefined, {}, new Error("owner closed"),+ {...malformed, "dock.order.LeftTop": [42]},+ {...malformed, "dock.order.LeftTop": ["file"], "dock.order.RightTop": ["file"]}]) {+ fixture.setOwner(owner);+ assert.equal(fixture.snapshot(true), fixture.localSnapshot);+ }+});++test("closing an entry editor flushes deferred settings once, after the view is removed", () => {+ const code = transpileModule(readFileSync("src/config/entryVisibility/ui.ts", "utf8") ++ "\nexports.remove = removeEntryView;", {+ compilerOptions: {module: ModuleKind.CommonJS},+ }).outputText;+ let transition: (event: {propertyName: string}) => void;+ let timeout: () => void;+ let dispatched = 0;+ const view = {parentElement: {}, classList: {remove() {}}, remove: () => { view.parentElement = null; },+ addEventListener: (_name: string, callback: typeof transition) => { transition = callback; }};+ const root = {dispatchEvent: (event: {type: string; bubbles: boolean}) => {+ assert.equal(view.parentElement, null);+ assert.equal(event.type, "siyuan-entry-profile-closed");+ assert.equal(event.bubbles, true);+ dispatched++;+ }};+ const exports = {} as {remove: (root: any, view: any) => void};+ runInNewContext(code, {exports, require: () => ({DOCK_ORDER_SCOPES_BY_SIDE: {}}),+ window: {setTimeout: (callback: () => void) => { timeout = callback; }},+ CustomEvent: class {+ public bubbles: boolean;+ constructor(public type: string, options: {bubbles: boolean}) { this.bubbles = options.bubbles; }+ }});+ exports.remove(root, view);+ assert.equal(dispatched, 0);+ transition({propertyName: "opacity"});+ assert.equal(dispatched, 1);+ timeout();+ assert.equal(dispatched, 1);+});diff --git a/app/src/config/entryVisibility/ui.ts b/app/src/config/entryVisibility/ui.tsindex 8d4a129a7b..024dceaf25 100644--- a/app/src/config/entryVisibility/ui.ts+++ b/app/src/config/entryVisibility/ui.ts@@ -46,6 +46,9 @@ import {isMobile} from "../../util/functions";import {isInMobileApp} from "../../protyle/util/compatibility";import {bindTouchOrder} from "./touchOrder";import {MOBILE_TOOLBAR_NAMES, TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";+/// #if !MOBILE+import {getSettingsWindowHost, isSettingsWindow} from "../setting/windowContext";+/// #endifimport {DOCK_ORDER_SCOPES,DOCK_ORDER_SCOPES_BY_SIDE,@@ -156,13 +159,20 @@ const getEntryViews = (root: HTMLElement) => Array.from(getEntryViewHost(root).cconst removeEntryView = (root: HTMLElement, view?: HTMLElement) => {const views = view ? [view] : getEntryViews(root);views.forEach((item) => {+ const remove = () => {+ if (!item.parentElement) {+ return;+ }+ item.remove();+ root.dispatchEvent(new CustomEvent("siyuan-entry-profile-closed", {bubbles: true}));+ };item.classList.remove("config__view--show");item.addEventListener("transitionend", (event) => {if (event.propertyName === "opacity") {- item.remove();+ remove();}});- window.setTimeout(() => item.remove(), 300);+ window.setTimeout(remove, 300);});};@@ -541,13 +551,40 @@ const getEntrySearchFilter = (query: string) => {return {results, visiblePaths, visibleSectionKeys};};+const getProfileDockOrderSnapshot = (builtin: boolean) => {+ let snapshot: TDockOrderSnapshot;+ /// #if !MOBILE+ if (isSettingsWindow()) {+ try {+ const ownerSnapshot = getSettingsWindowHost()?.getDockOrderSnapshot();+ const seen = new Set<string>();+ if (ownerSnapshot && DOCK_ORDER_SCOPES.every(scope => Array.isArray(ownerSnapshot[scope]) &&+ ownerSnapshot[scope].every(key => {+ if (typeof key !== "string" || !key || seen.has(key)) {+ return false;+ }+ seen.add(key);+ return true;+ }))) {+ snapshot = Object.fromEntries(DOCK_ORDER_SCOPES.map(scope => [scope, [...ownerSnapshot[scope]]])) as+ TDockOrderSnapshot;+ }+ } catch (error) {+ console.warn("Could not read settings owner dock order", error);+ }+ }+ /// #endif+ snapshot ||= getDockEntryOrderSnapshot();+ return builtin ? snapshot : getDefaultDockEntryOrderSnapshot(snapshot);+};+const openProfileEditor = (root: HTMLElement, profileID?: string) => {const plugins = window.siyuan.ws?.app?.plugins || [];refreshTopBarCatalog(plugins);refreshDockCatalog(plugins);refreshSlashMenuCatalog(plugins);const builtin = profileID === ENTRY_PROFILE_SIMPLE || profileID === ENTRY_PROFILE_FULL;- const dockOrderSnapshot = builtin ? getDockEntryOrderSnapshot() : getDefaultDockEntryOrderSnapshot();+ const dockOrderSnapshot = getProfileDockOrderSnapshot(builtin);let selectedTemplate: TEntryVisibilityTemplate | "current" = ENTRY_PROFILE_SIMPLE;const existing = profileID? window.siyuan.config.appearance.entryVisibility.profiles.find((item) => item.id === profileID)diff --git a/app/src/config/notebookArchive.ts b/app/src/config/notebookArchive.tsindex fb4caaffd3..78cd0922de 100644--- a/app/src/config/notebookArchive.ts+++ b/app/src/config/notebookArchive.ts@@ -5,6 +5,9 @@ import {ContractFormData} from "../util/contractFormData";import {saveExportFile} from "../protyle/util/compatibility";import {escapeHtml} from "../util/escape";import {isMobile} from "../util/functions";+/// #if !MOBILE+import {reloadUI} from "../layout/util";+/// #endifexport const openNotebookArchiveDialog = async (refresh: () => void) => {const response = await fetchSyncPost("/api/notebook/getNotebookArchiveCandidates", {});@@ -144,7 +147,11 @@ export const openNotebookArchiveImportDialog = (refresh: () => void) => {showMessage(lang.imported);refresh();// 导入保留锁定状态,刷新导航即可显示新恢复的笔记本。+ /// #if MOBILEwindow.location.reload();+ /// #else+ void reloadUI();+ /// #endif} finally {button.disabled = false;}diff --git a/app/src/config/setting/mount.test.ts b/app/src/config/setting/mount.test.tsindex e541c3231e..7d23da58f9 100644--- a/app/src/config/setting/mount.test.ts+++ b/app/src/config/setting/mount.test.ts@@ -9,7 +9,8 @@ for (const keywords of ["", "gradient"]) {test(`remount restores scroll after asynchronous initialization and search (keywords=${keywords})`, async () => {const source = readFileSync(resolve(process.cwd(), "src/config/setting/mount.ts"), "utf8");const code = transpileModule(source, {compilerOptions: {module: ModuleKind.CommonJS}}).outputText;- const root = {innerHTML: "settings", scrollTop: 235.5, scrollLeft: 12, contains: () => false};+ const root = {innerHTML: "settings", scrollTop: 235.5, scrollLeft: 12, contains: () => false,+ querySelector: (): Element | null => null};const visibleItemIds = new Set(["bodyGradient"]);const tab = {scanSearch: () => ({visibleItemIds}),@@ -55,7 +56,8 @@ test("all settings refreshes preserve focused inputs and remount when focus leavcompilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},}).outputText;const input = {};- const root = {innerHTML: "settings", scrollTop: 12, scrollLeft: 0, contains: (element: unknown) => element === input};+ const root = {innerHTML: "settings", scrollTop: 12, scrollLeft: 0, contains: (element: unknown) => element === input,+ querySelector: (): Element | null => null};let mounted = 0;let focusout: () => void;const timers: Array<() => void> = [];@@ -75,3 +77,40 @@ test("all settings refreshes preserve focused inputs and remount when focus leavassert.equal(mounted, 1);assert.equal(root.scrollTop, 12);});++test("settings refresh preserves an unfocused profile draft and resumes after the editor closes", async () => {+ const code = transpileModule(readFileSync("src/config/setting/mount.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText;+ let view: object = {};+ let mounted = 0;+ const listeners = new Map<string, () => void>();+ const timers: Array<() => void> = [];+ const root = {innerHTML: "draft", scrollTop: 12, scrollLeft: 0, contains: () => false,+ querySelector: () => view};+ const dependencies = {Constants: {DIALOG_SETTING: "settings"}, getSearchKeywordsLower: () => "",+ getSettingTab: () => ({mount: async () => { mounted++; root.innerHTML = "refreshed"; }})};+ const exports = {} as {remountOpenSettingTab: (tab: string) => Promise<void>};+ runInNewContext(code, {exports, require: () => dependencies,+ document: {activeElement: {}, addEventListener: (name: string, callback: () => void) => listeners.set(name, callback)},+ setTimeout: (callback: () => void) => timers.push(callback),+ window: {siyuan: {ws: {app: {}}, dialogs: [{element: {getAttribute: () => "settings", querySelector: () => root}}]}}});+ await exports.remountOpenSettingTab("appearance");+ await exports.remountOpenSettingTab("appearance");+ assert.equal(mounted, 0);+ assert.equal(root.innerHTML, "draft");+ listeners.get("focusout")();+ timers.splice(0).forEach(callback => callback());+ await Promise.resolve();+ assert.equal(mounted, 0);+ view = undefined;+ listeners.get("siyuan-entry-profile-closed")();+ timers.splice(0).forEach(callback => callback());+ await Promise.resolve();+ assert.equal(mounted, 1);+ assert.equal(root.innerHTML, "refreshed");+ listeners.get("siyuan-entry-profile-closed")();+ timers.splice(0).forEach(callback => callback());+ await Promise.resolve();+ assert.equal(mounted, 1);+});diff --git a/app/src/config/setting/mount.ts b/app/src/config/setting/mount.tsindex 8c89bf0529..7d86a84817 100644--- a/app/src/config/setting/mount.ts+++ b/app/src/config/setting/mount.ts@@ -27,16 +27,18 @@ export const remountOpenSettingTab = async (tabId: TSettingTab) => {if (!root?.innerHTML) {return;}- if (root.contains(document.activeElement)) {+ if (root.contains(document.activeElement) || root.querySelector(".config-entry-visibility__view")) {deferredTabs.add(tabId);if (!watchingFocus) {watchingFocus = true;- // 离开正在输入的面板后更新控件,避免替换用户尚未提交的输入。- document.addEventListener("focusout", () => setTimeout(() => {+ // 离开输入控件或关闭入口方案编辑器后再刷新,保留尚未提交的输入与草稿。+ const refreshDeferredTabs = () => setTimeout(() => {const tabs = [...deferredTabs];deferredTabs.clear();tabs.forEach(tab => { void remountOpenSettingTab(tab); });- }, 0));+ }, 0);+ document.addEventListener("focusout", refreshDeferredTabs);+ document.addEventListener("siyuan-entry-profile-closed", refreshDeferredTabs);}return;}diff --git a/app/src/config/setting/nativeWindow.ts b/app/src/config/setting/nativeWindow.tsindex 56113e58c5..823f743fb1 100644--- a/app/src/config/setting/nativeWindow.ts+++ b/app/src/config/setting/nativeWindow.ts@@ -3,7 +3,7 @@ import {ipcRenderer} from "electron";/// #endifimport {genUUID} from "../../util/genID";import {setStorageVal} from "../../protyle/util/compatibility";-import {exportLayout} from "../../layout/util";+import {exportLayout, reloadUI, resetLayout} from "../../layout/util";import {exitSiYuan} from "../../dialog/processSystem";import {subscribeGlobalPluginState, applyPluginReload} from "../../plugin/globalState";import {loadPlugin, unloadPlugin} from "../../plugin/loader";@@ -11,6 +11,8 @@ import {sendGlobalShortcut, sendUnregisterGlobalShortcut} from "../../boot/globaimport {Constants} from "../../constants";import {hasPluginSetting} from "../../plugin";import {getWorkspaceName} from "../../util/processTitle";+import {getDockEntryOrderSnapshot} from "../entryVisibility/dockOrder";+import {hasNativeSettingTasks} from "./taskBlocker";import type {App} from "../../index";import type {ISettingsWindowHost} from "./windowContext";import type {TSettingTab} from "./tabs";@@ -21,81 +23,170 @@ export interface ISettingsCommand {}const geometryKey = "settingsWindowGeometry";-const hosts = new Map<string, {host: ISettingsWindowHost; listener: EventListener}>();+const hosts = new Map<string, {key: string; dispose: (notifyPlugin?: boolean, restoreShortcuts?: boolean) => void}>();+const shortcutSuspensions = new Set<string>();let listening = false;let openSequence = 0;+let ownerActive = true;++const safelyDispose = (callback: () => void) => {+ try {+ callback();+ } catch (error) {+ console.error("Could not dispose settings window resources", error);+ }+};export const closeNativeSettings = (key: string) => {/// #if !BROWSER- ipcRenderer.send("siyuan-settings-close", key);+ for (const [token, entry] of [...hosts]) {+ if (entry.key !== key) continue;+ try {+ ipcRenderer.send("siyuan-settings-close", {key, token});+ } finally {+ entry.dispose();+ }+ }/// #endif};export const openNativeSettings = async (app: App, command: ISettingsCommand = {},plugin?: ISettingsWindowHost["plugin"], key = "builtin") => {/// #if !BROWSER+ if (!ownerActive) return;openSequence++;if (!listening) {listening = true;window.addEventListener("unload", () => {- hosts.forEach(entry => entry.host.plugin?.closed());+ ownerActive = false;+ for (const entry of [...hosts.values()]) entry.dispose(true, false);});ipcRenderer.on("siyuan-settings-geometry", (_event, geometry) => {+ if (!ownerActive || hasNativeSettingTasks()) return;window.siyuan.storage[geometryKey] = geometry;setStorageVal(geometryKey, geometry);});- ipcRenderer.on("siyuan-settings-closed", (_event, token: string) => {- const entry = hosts.get(token);- if (entry) {- window.removeEventListener("siyuan-settings-host-" + token, entry.listener);- entry.host.plugin?.closed();- entry.host.restoreShortcuts();- hosts.delete(token);- }+ ipcRenderer.on("siyuan-settings-closed", (_event, token: string, ownerInvalidated: boolean) => {+ if (ownerInvalidated) ownerActive = false;+ hosts.get(token)?.dispose(true, !ownerInvalidated);});}const token = genUUID();const title = plugin?.name || `${window.siyuan.languages.config} - ${getWorkspaceName()}`;- const prepared = await ipcRenderer.invoke("siyuan-settings-prepare", {- token, key, command, title,- geometry: key === "builtin" ? window.siyuan.storage[geometryKey] : undefined,- });- if (!prepared.create) {- return;- }- if (plugin && !plugin.isOpen()) {- closeNativeSettings(key);- return;- }+ const subscriptions = new Set<() => void>();+ let listener: EventListener;+ const isActive = () => ownerActive && hosts.has(token);+ const assertActive = () => {+ if (!isActive()) throw new Error("The settings window owner is no longer available");+ };+ const dispose = (notifyPlugin = true, restoreShortcuts = true) => {+ // 先撤销宿主令牌,再调用插件,避免重入或异常留下已关闭窗口的资源。+ if (!hosts.delete(token)) return;+ const shortcutsSuspended = shortcutSuspensions.delete(token);+ if (listener) window.removeEventListener("siyuan-settings-host-" + token, listener);+ for (const unsubscribe of [...subscriptions]) safelyDispose(unsubscribe);+ if (notifyPlugin && plugin) safelyDispose(() => plugin.closed());+ if (shortcutsSuspended && restoreShortcuts && ownerActive && !shortcutSuspensions.size && !hasNativeSettingTasks()) {+ safelyDispose(() => sendGlobalShortcut(app));+ }+ };+ const close = () => {+ if (!hosts.has(token)) return;+ try {+ ipcRenderer.send("siyuan-settings-close", {key, token});+ } finally {+ dispose();+ }+ };+ hosts.set(token, {key, dispose});const host: ISettingsWindowHost = {- app, title, exportLayout, exit: exitSiYuan, plugin,- suspendShortcuts: () => sendUnregisterGlobalShortcut(app),- restoreShortcuts: () => sendGlobalShortcut(app),- subscribePlugins: listener => subscribeGlobalPluginState(app, listener),- applyPluginReload: async data => { await applyPluginReload(app, data); },- loadPlugin: async data => { await loadPlugin(app, data); },- unloadPlugin: async name => { await unloadPlugin(app, name); },+ app, title, isActive, dispose: close,+ exportLayout: options => { assertActive(); return exportLayout(options); },+ reload: () => { assertActive(); return reloadUI(); },+ resetLayout: () => { assertActive(); return resetLayout(); },+ getDockOrderSnapshot: () => { assertActive(); return getDockEntryOrderSnapshot(); },+ exit: setCurrentWorkspace => { assertActive(); return exitSiYuan(setCurrentWorkspace); },+ plugin: plugin && {+ name: plugin.name,+ isOpen: () => isActive() && plugin.isOpen(),+ mount: create => { assertActive(); plugin.mount(create); },+ closed: close,+ },+ suspendShortcuts: () => {+ assertActive();+ shortcutSuspensions.add(token);+ sendUnregisterGlobalShortcut(app);+ },+ restoreShortcuts: () => {+ assertActive();+ shortcutSuspensions.delete(token);+ if (!shortcutSuspensions.size && !hasNativeSettingTasks()) sendGlobalShortcut(app);+ },+ subscribePlugins: callback => {+ assertActive();+ let unsubscribe: () => void;+ let disposed = false;+ const remove = () => {+ if (disposed) return;+ disposed = true;+ subscriptions.delete(remove);+ unsubscribe?.();+ };+ subscriptions.add(remove);+ try {+ unsubscribe = subscribeGlobalPluginState(app, state => {+ if (isActive() && !disposed) safelyDispose(() => callback(state));+ });+ if (disposed) unsubscribe();+ } catch (error) {+ remove();+ throw error;+ }+ return remove;+ },+ applyPluginReload: async data => { assertActive(); await applyPluginReload(app, data); },+ loadPlugin: async data => { assertActive(); await loadPlugin(app, data); },+ unloadPlugin: async name => { assertActive(); await unloadPlugin(app, name); },hasPluginSetting: name => {+ assertActive();const item = app.plugins.find(item => item.name === name);return Boolean(item && hasPluginSetting(item));},openPluginSetting: async name => {+ assertActive();const item = app.plugins.find(item => item.name === name);if (!item || !hasPluginSetting(item)) return;const sequence = openSequence;await item.openSetting();// 插件沿用原窗口对话框时显示其所属窗口,原生设置窗口自行接管焦点。- if (sequence === openSequence) ipcRenderer.send(Constants.SIYUAN_CMD, "show");+ if (isActive() && sequence === openSequence) ipcRenderer.send(Constants.SIYUAN_CMD, "show");},};- const listener = ((event: CustomEvent<(host: ISettingsWindowHost) => void>) => event.detail(host)) as EventListener;- hosts.set(token, {host, listener});- window.addEventListener("siyuan-settings-host-" + token, listener);- const child = window.open(prepared.url, prepared.frameName);- if (!child) {- window.removeEventListener("siyuan-settings-host-" + token, listener);- hosts.delete(token);- throw new Error("Could not open the settings window");+ try {+ const prepared = await ipcRenderer.invoke("siyuan-settings-prepare", {+ token, key, command, title,+ geometry: key === "builtin" ? window.siyuan.storage[geometryKey] : undefined,+ });+ if (!prepared.create) {+ dispose(false, false);+ return;+ }+ if (!isActive() || (plugin && !plugin.isOpen())) {+ try {+ ipcRenderer.send("siyuan-settings-close", {key, token});+ } finally {+ dispose();+ }+ return;+ }+ listener = ((event: CustomEvent<(host: ISettingsWindowHost) => void>) => {+ if (isActive() && typeof event.detail === "function") event.detail(host);+ }) as EventListener;+ window.addEventListener("siyuan-settings-host-" + token, listener);+ if (!window.open(prepared.url, prepared.frameName)) throw new Error("Could not open the settings window");+ } catch (error) {+ close();+ throw error;}/// #endif};diff --git a/app/src/config/setting/reload.test.ts b/app/src/config/setting/reload.test.tsnew file mode 100644index 0000000000..66a6818757--- /dev/null+++ b/app/src/config/setting/reload.test.ts@@ -0,0 +1,131 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {createSourceFile, isVariableStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";++const source = createSourceFile("util.ts", readFileSync("src/layout/util.ts", "utf8"), ScriptTarget.Latest);+const selected = new Set(["reloadingUI", "reloadUI", "resetLayout"]);+const code = transpileModule(source.statements.filter(statement => isVariableStatement(statement) &&+ statement.declarationList.declarations.some(declaration => selected.has(declaration.name.getText(source))))+ .map(statement => statement.getText(source)).join("\n"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++const setup = (options: {host?: object; fail?: boolean; readonly?: boolean; storageFail?: boolean;+ save?: () => Promise<void>} = {}) => {+ const calls: string[] = [];+ const api = {} as {reloadUI: () => Promise<void>; resetLayout: () => Promise<void>};+ class Element { blur() { calls.push("blur"); } }+ const storage: Record<string, unknown> = {};+ let failedStorage = false;+ runInNewContext(code, {+ exports: api, console: {error() {}}, HTMLElement: Element,+ document: {activeElement: new Element()},+ window: {siyuan: {config: {readonly: options.readonly}, storage, languages: {}},+ location: {reload: () => calls.push("reload")}},+ getSettingsWindowHost: () => options.host,+ settingSaveFailures: () => 0,+ flushSettingSaves: async () => {+ calls.push("settings");+ if (failedStorage) throw new Error("storage request failed");+ await options.save?.();+ },+ exportLayout: async ({cb}: {cb: () => void}) => {+ calls.push("layout");+ if (options.fail) return;+ await Promise.resolve();+ calls.push("saved");+ cb();+ },+ suspendLayoutSaving: async () => { calls.push("suspend"); return () => calls.push("resume"); },+ fetchSyncPost: async () => { calls.push("clear"); return {code: options.fail ? -1 : 0}; },+ Constants: {LOCAL_FILEPOSITION: "file", LOCAL_DIALOGPOSITION: "dialog"},+ setStorageVal: async (key: string) => { calls.push(key); failedStorage ||= options.storageFail; },+ showMessage: () => calls.push("error"),+ });+ return {api, calls, storage};+};++test("settings reload and layout reset execute in their owner", async () => {+ const owner: string[] = [];+ const {api, calls} = setup({host: {+ reload: async () => { owner.push("reload"); },+ resetLayout: async () => { owner.push("reset"); },+ }});+ await api.reloadUI();+ await api.resetLayout();+ assert.deepEqual(owner, ["reload", "reset"]);+ assert.deepEqual(calls, ["blur", "settings", "blur", "settings"]);+});++test("reload flushes settings and waits for layout callback, combining repeated requests", async () => {+ let ready: () => void;+ const saving = new Promise<void>(resolve => { ready = resolve; });+ const {api, calls} = setup({save: () => saving});+ const first = api.reloadUI();+ await api.reloadUI();+ assert.deepEqual(calls, ["blur", "settings"]);+ ready();+ await first;+ assert.deepEqual(calls, ["blur", "settings", "layout", "saved", "reload"]);+});++test("a failed layout save does not reload and permits a later retry", async () => {+ const {api, calls} = setup({fail: true});+ await api.reloadUI();+ await api.reloadUI();+ assert.equal(calls.includes("reload"), false);+ assert.equal(calls.filter(call => call === "layout").length, 2);+});++test("pending settings failure prevents layout save and reload", async () => {+ const {api, calls} = setup({save: async () => { throw new Error("failed"); }});+ await api.reloadUI();+ assert.deepEqual(calls, ["blur", "settings", "error"]);+});++test("pending child settings finish before owner delegation and failures prevent it", async () => {+ for (const reset of [false, true]) {+ const calls: string[] = [];+ let ready: () => void;+ const pending = new Promise<void>(resolve => { ready = resolve; });+ const host = {reload: async () => { calls.push("reload"); }, resetLayout: async () => { calls.push("reset"); }};+ const {api} = setup({host, save: () => pending});+ const saving = reset ? api.resetLayout() : api.reloadUI();+ assert.deepEqual(calls, []);+ ready();+ await saving;+ assert.deepEqual(calls, [reset ? "reset" : "reload"]);+ const failed = setup({host, save: async () => { throw new Error("offline"); }});+ await (reset ? failed.api.resetLayout() : failed.api.reloadUI());+ assert.equal(calls.length, 1);+ assert.equal(failed.calls.at(-1), "error");+ }+});++test("reset suspends old layout saving and clears storage before reload without export", async () => {+ const {api, calls, storage} = setup();+ await api.resetLayout();+ assert.deepEqual(calls, ["blur", "settings", "suspend", "clear", "file", "dialog", "settings", "reload"]);+ assert.deepEqual(Object.keys(storage).sort(), ["dialog", "file"]);+});++test("failed reset resumes layout saving without clearing positions or reloading", async () => {+ const {api, calls} = setup({fail: true});+ await api.resetLayout();+ assert.deepEqual(calls, ["blur", "settings", "suspend", "clear", "resume", "error"]);+});++test("resolved storage failures still prevent layout reset reload", async () => {+ const {api, calls} = setup({storageFail: true});+ await api.resetLayout();+ assert.equal(calls.includes("reload"), false);+ assert.deepEqual(calls.slice(-3), ["settings", "resume", "error"]);+});++test("readonly layout reset does not write preferences", async () => {+ const {api, calls} = setup({readonly: true});+ await api.resetLayout();+ assert.deepEqual(calls, ["reload"]);+});diff --git a/app/src/config/setting/reset.test.ts b/app/src/config/setting/reset.test.tsindex 7335869af6..a6a6cddd8d 100644--- a/app/src/config/setting/reset.test.ts+++ b/app/src/config/setting/reset.test.ts@@ -5,7 +5,7 @@ import {runInNewContext} from "node:vm";import {ModuleKind, ScriptTarget, transpileModule} from "typescript";const {parse} = require("ifdef-loader/preprocessor");-const loadReset = (browser: boolean, mobile: boolean, failed = false) => {+const loadReset = (browser: boolean, mobile: boolean, failed = false, settingsWindow = false) => {const calls: string[] = [];const source = parse(readFileSync("src/config/setting/reset.ts", "utf8"), {BROWSER: browser, MOBILE: mobile}, false, true);const code = transpileModule(source, {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021}}).outputText;@@ -26,7 +26,11 @@ const loadReset = (browser: boolean, mobile: boolean, failed = false) => {flushSettingSaves: async () => { calls.push("save settings"); },fetchSyncPost: async (_path: string, data: {saved: boolean}) => { calls.push("ack " + data.saved); return {code: 0}; },getHostCapabilities: () => ({ownsKernel: !browser}),- isWindow: () => false, isSettingsWindow: () => false,+ isWindow: () => false, isSettingsWindow: () => settingsWindow,+ closeSettingsWindow: () => {+ if (settingsWindow) calls.push("close settings");+ return settingsWindow;+ },exitSiYuan: async () => { calls.push("exit"); },};class Element { blur() { calls.push("blur"); } }@@ -69,3 +73,16 @@ test("cancellation resumes layout saving and prepared reconnect reloads withoutassert.equal(api.reloadSettingsResetOnReconnect(), true);assert.equal(calls.at(-1), "reload");});++test("settings reset completion and prepared reconnect close the child without reload or exit", async () => {+ for (const reconnect of [false, true]) {+ const {api, calls} = loadReset(false, false, false, true);+ await api.prepareSettingsReset({id: "settings", token: "settings-token"});+ if (reconnect) assert.equal(api.reloadSettingsResetOnReconnect(), true);+ else api.completeSettingsReset({id: "settings", exit: true});+ api.exitAfterSettingsReset();+ assert.equal(calls.at(-1), "close settings");+ assert.equal(calls.includes("reload"), false);+ assert.equal(calls.includes("exit"), false);+ }+});diff --git a/app/src/config/setting/reset.ts b/app/src/config/setting/reset.tsindex 454a655ad4..4e858825b8 100644--- a/app/src/config/setting/reset.ts+++ b/app/src/config/setting/reset.ts@@ -10,7 +10,7 @@ import {suspendLayoutSaving} from "../../layout/util";/// #endif/// #if !BROWSERimport {isWindow} from "../../util/functions";-import {isSettingsWindow} from "./windowContext";+import {closeSettingsWindow, isSettingsWindow} from "./windowContext";import {exitSiYuan} from "../../dialog/processSystem";/// #endif@@ -76,6 +76,9 @@ export const reloadSettingsResetOnReconnect = () => {cancelSettingsReset(preparation.id);return false;}+ /// #if !BROWSER+ if (closeSettingsWindow()) return true;+ /// #endifwindow.location.reload();return true;};@@ -83,6 +86,7 @@ export const reloadSettingsResetOnReconnect = () => {export const completeSettingsReset = (data: {id: string; exit: boolean}) => {if (preparation) window.clearTimeout(preparation.timer);/// #if !BROWSER+ if (closeSettingsWindow()) return;if (data.exit && getHostCapabilities().ownsKernel && !isWindow() && !isSettingsWindow()) {sessionStorage.setItem(EXIT_AFTER_RESET, "true");}diff --git a/app/src/config/setting/window.ts b/app/src/config/setting/window.tsindex 202ed52d6d..d4c64cee83 100644--- a/app/src/config/setting/window.ts+++ b/app/src/config/setting/window.ts@@ -1,12 +1,11 @@import "../../assets/scss/base.scss";-import {ipcRenderer, webFrame} from "electron";+import {ipcRenderer} from "electron";import {Constants} from "../../constants";-import {onAgentStreamingMarkdownStorageChanged} from "../tabs/ai/agentStreamingMarkdown";import {Model} from "../../layout/Model";import {Menus} from "../../menus";import {genUUID} from "../../util/genID";import {fetchSyncPost} from "../../util/fetch";-import {addBaseURL, redirectToCheckAuth, setNoteBook} from "../../util/pathName";+import {addBaseURL, redirectToCheckAuth} from "../../util/pathName";import {getLocalStorage, initNativeDialogOverride, initWindowOpenOverride, isMac, isWindows} from "../../protyle/util/compatibility";import {addScriptSync} from "../../protyle/util/addScript";import {ensureLute} from "../../protyle/util/lute";@@ -16,7 +15,7 @@ import {systemConfig} from "../systemConfig";import {loadAssets, setInlineStyle, initAssets, reloadInlineStyles, refreshThemeStyle} from "../../util/assets";import {initMessage} from "../../dialog/message";import {progressLoading, processSync, downloadProgress} from "../../dialog/processSystem";-import {setSettingsWindowHost, type ISettingsWindowHost} from "./windowContext";+import {setSettingsWindowHost} from "./windowContext";import {refreshSettingConfig} from "./sync";import {openSettingDialog} from "../index";import {switchSettingTab} from "../search/dialog";@@ -35,22 +34,58 @@ import {getSettingTabDefs} from "./tabs";import {onWindowsMsg} from "../../window/onWindowsMsg";import {applyWindowState} from "../../boot/windowControls";import {waitForSettingsWindowPaint} from "./windowPaint";+import {createSettingsWindowRuntime, resolveSettingsWindowHost, startSettingsWindow} from "./windowRuntime";++let disposeSettingsWindow = () => {};const initialize = async () => {addBaseURL();- const token = new URLSearchParams(location.search).get("settingsWindowToken");- if (!token || !window.opener || window.opener.location.origin !== location.origin) {+ const host = resolveSettingsWindowHost();+ if (!host) {window.close();return;}- const host = await new Promise<ISettingsWindowHost>(resolve => {- window.opener.dispatchEvent(new CustomEvent("siyuan-settings-host-" + token, {detail: resolve}));- });setSettingsWindowHost(host);+ let disposed = false;+ const ws = new Model({app: host.app});+ const listeners: {channel: string; listener: Parameters<typeof ipcRenderer.on>[1]}[] = [];+ disposeSettingsWindow = () => {+ if (disposed) return;+ disposed = true;+ if (window.siyuan) window.siyuan.isReady = false;+ ws.destroy();+ listeners.forEach(({channel, listener}) => ipcRenderer.removeListener(channel, listener));+ setSettingsWindowHost(undefined);+ try {+ host.dispose();+ } catch (error) {+ console.warn("Could not release the settings window owner", error);+ }+ };+ window.addEventListener("unload", disposeSettingsWindow, {once: true});+ const isActive = () => {+ if (disposed) return false;+ try {+ if (host.isActive()) return true;+ } catch (error) {+ console.warn("Could not reach the settings window owner", error);+ }+ disposeSettingsWindow();+ window.close();+ return false;+ };+ const listen = (channel: string, callback: Parameters<typeof ipcRenderer.on>[1]) => {+ const listener: Parameters<typeof ipcRenderer.on>[1] = (event, ...args) => {+ if (isActive()) callback(event, ...args);+ };+ listeners.push({channel, listener});+ ipcRenderer.on(channel, listener);+ };+ const runtime = createSettingsWindowRuntime(isActive);let dialog: Dialog;let command: ISettingsCommand;const applyCommand = async () => {- if (!dialog || !command || host.plugin) return;+ if (!isActive() || !dialog || !command || host.plugin) return;const next = command;command = undefined;if (next.tab) {@@ -60,31 +95,39 @@ const initialize = async () => {history.replaceState(null, "", url);if (next.tab === "assets") {await mounted;+ if (!isActive()) return;}}if (next.readme) {const {type, from, resource} = next.readme;await withMountedBazaar(({bazaar, renderReadme}) => {+ if (!isActive()) return;bazaar.switchBazaarTab(host.app, type, from);renderReadme(type, from, resource);});}};- ipcRenderer.on("siyuan-settings-command", (_event, next: ISettingsCommand) => {+ listen("siyuan-settings-command", (_event, next: ISettingsCommand) => {command = next;- void applyCommand();+ void applyCommand().catch(error => console.error("Could not apply settings window command", error));});- const ws = new Model({app: host.app});window.siyuan = {zIndex: 10, isReady: false, notebooks: [], reqIds: {}, backStack: [], layout: {}, dialogs: [],blockPanels: [], closedTabs: [], ctrlIsPressed: false, altIsPressed: false, ws,};- ws.connect({id: genUUID(), type: "main", msgCallback: data => {- if (!data) return;+ ws.connect({id: genUUID(), type: "main", callback: () => {+ if (isActive() && window.siyuan.isReady) {+ void runtime.reconnect().catch(error => console.error("Could not reconnect settings runtime", error));+ }+ }, msgCallback: data => {+ if (!isActive() || !data || runtime.handleMessage(data)) return;switch (data.cmd) {case "logoutAuth": redirectToCheckAuth(); break;case "settingChanged": void refreshSettingConfig(data.data.namespace); break;- case "setConf": void refreshSettingConfig(); break;+ case "setConf":+ void refreshSettingConfig();+ void runtime.refreshSnippets(true);+ break;case "setAppearance": appearanceConfigApi.apply(data.data); break;case "refreshAppearance": void refreshAppearance(data.data); break;case "reloadInlineStyles": void reloadInlineStyles(); break;@@ -96,43 +139,31 @@ const initialize = async () => {case "syncing": processSync(data); break;case "setCloudUser": applyCloudUserState(data.data.user, data.data.userName); break;case "setServerAddrs": updateServerAddresses(data.data); break;- case "setLocalStorageVal":- window.siyuan.storage[data.data.key] = data.data.val;- onAgentStreamingMarkdownStorageChanged(data.data.key);- break;- case "setLocalStorageVals":- Object.assign(window.siyuan.storage, data.data.keyVals);- Object.keys(data.data.keyVals).forEach(onAgentStreamingMarkdownStorageChanged);- break;- case "removeLocalStorageVal":- delete window.siyuan.storage[data.data.key];- onAgentStreamingMarkdownStorageChanged(data.data.key);- break;- case "removeLocalStorageVals":- data.data.keys.forEach((key: string) => delete window.siyuan.storage[key]);- data.data.keys.forEach(onAgentStreamingMarkdownStorageChanged);- break;}}});const response = await fetchSyncPost("/api/system/getConf", {});+ if (!isActive()) return;if (response.code !== 0) {+ disposeSettingsWindow();window.close();return;}window.siyuan.config = systemConfig(response.data.conf);window.siyuan.isPublish = response.data.isPublish;await loadDesktopHostConnection();+ if (!isActive()) return;const [user, emoji] = await Promise.all([fetchSyncPost("/api/setting/getCloudUser", {cached: true}),fetchSyncPost("/api/system/getEmojiConf", {}),- setNoteBook(),+ runtime.refreshNotebooks(),new Promise<void>(resolve => getLocalStorage(resolve)),addScriptSync(`${Constants.PROTYLE_CDN}/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}`, "protyleWcHtmlScript"),loadLanguages(window.siyuan.config.appearance.lang, Constants.SIYUAN_VERSION, languages => {- window.siyuan.languages = languages;+ if (isActive()) window.siyuan.languages = languages;}),- host.plugin ? ensureLute() : Promise.resolve(),+ host.plugin ? ensureLute({reloadOnFailure: false}) : Promise.resolve(),]);+ if (!isActive()) return;if (!window.siyuan.languages || !window.DOMPurify) {throw new Error("Could not load settings window dependencies");}@@ -142,25 +173,27 @@ const initialize = async () => {}window.siyuan.menus = new Menus(host.app);await initDesktopHost();- ipcRenderer.on(Constants.SIYUAN_SEND_WINDOWS, (_event, data: IWebSocketData) => onWindowsMsg(data));- webFrame.setZoomFactor(window.siyuan.storage[Constants.LOCAL_ZOOM]);+ if (!isActive()) return;+ listen(Constants.SIYUAN_SEND_WINDOWS, (_event, data: IWebSocketData) => onWindowsMsg(data));+ runtime.applyZoom();document.body.classList.toggle("body--windows", isWindows());document.body.classList.toggle("body--win32", !isMac());- ipcRenderer.on(Constants.SIYUAN_EVENT, (_event, command: string) => applyWindowState(command));+ listen(Constants.SIYUAN_EVENT, (_event, command: string) => applyWindowState(command));ipcRenderer.send(Constants.SIYUAN_EVENT);const [fullscreen, maximized] = await Promise.all([ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "isFullScreen"}),ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "isMaximized"}),]);+ if (!isActive()) return;applyWindowState(fullscreen ? "enter-full-screen" : "leave-full-screen");applyWindowState(maximized ? "maximize" : "unmaximize");- const zoom = window.siyuan.storage[Constants.LOCAL_ZOOM];- const position = Constants.SIZE_ZOOM.find(item => item.zoom === zoom)?.position;- if (position) ipcRenderer.send(Constants.SIYUAN_CMD, {cmd: "setTrafficLightPosition", zoom, position});await waitForSettingsWindowPaint(async () => {await loadAssets(window.siyuan.config.appearance);+ if (!isActive()) return;await setInlineStyle();+ if (!isActive()) return;initAssets();+ runtime.applyZoom();initMessage();initNativeDialogOverride();initWindowOpenOverride(host.app);@@ -175,7 +208,8 @@ const initialize = async () => {} else {const tab = getSettingTabDefs().find(def => def.id === new URLSearchParams(location.search).get("tab"))?.id;if (tab === "assets") {- await ensureLute();+ await ensureLute({reloadOnFailure: false});+ if (!isActive()) return;}dialog = openSettingDialog(host.app, tab);dialog.element.querySelectorAll(".config__side .b3-list-item").forEach(item => {@@ -195,21 +229,22 @@ const initialize = async () => {});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.addEventListener("focus", () => {+ void runtime.refreshNotebooks().catch(error => console.error("Could not refresh settings notebooks", error));});+ window.addEventListener("resize", () => window.siyuan.menus.menu.resetPosition());+ await runtime.refreshSnippets();+ if (!isActive()) return;window.siyuan.isReady = true;ws.flushMainMessages();await applyCommand();});- ipcRenderer.send("siyuan-settings-ready");+ if (isActive()) ipcRenderer.send("siyuan-settings-ready");};installPluginStorageFetchAppId(window, Constants.SIYUAN_APPID, window.location.href);-void initialize().catch(error => {+void startSettingsWindow(initialize, error => {console.error("Could not initialize the settings window", error);+ disposeSettingsWindow();window.close();});diff --git a/app/src/config/setting/windowContext.ts b/app/src/config/setting/windowContext.tsindex a3d7085509..ecd6fe0c21 100644--- a/app/src/config/setting/windowContext.ts+++ b/app/src/config/setting/windowContext.ts@@ -2,10 +2,19 @@ import type {App} from "../../index";import type {Dialog} from "../../dialog";import type {IPluginReloadData} from "../../plugin/loader";import type {IGlobalPluginStateSnapshot} from "../../plugin/globalStateCoordinator";+import type {TDockOrderSnapshot} from "../entryVisibility/dockOrder";+/// #if !BROWSER+import {ipcRenderer} from "electron";+/// #endifexport interface ISettingsWindowHost {app: App;title: string;+ isActive: () => boolean;+ dispose: () => void;+ reload: () => Promise<void>;+ resetLayout: () => Promise<void>;+ getDockOrderSnapshot: () => TDockOrderSnapshot;exportLayout: (options: {cb: () => void; errorExit: boolean}) => Promise<void>;exit: (setCurrentWorkspace?: boolean) => Promise<void>;subscribePlugins: (listener: (state: IGlobalPluginStateSnapshot) => void) => () => void;@@ -29,3 +38,14 @@ let host: ISettingsWindowHost;export const setSettingsWindowHost = (value: ISettingsWindowHost) => { host = value; };export const getSettingsWindowHost = () => host;export const isSettingsWindow = () => typeof document !== "undefined" && document.body.classList.contains("body--settings");++// 重载和重置结束设置会话,不触发关闭时的旧窗口偏好保存。+export const closeSettingsWindow = () => {+ /// #if !BROWSER+ if (isSettingsWindow()) {+ ipcRenderer.send("siyuan-settings-close-self");+ return true;+ }+ /// #endif+ return false;+};diff --git a/app/src/config/setting/windowRuntime.test.ts b/app/src/config/setting/windowRuntime.test.tsnew file mode 100644index 0000000000..b295d8ff91--- /dev/null+++ b/app/src/config/setting/windowRuntime.test.ts@@ -0,0 +1,240 @@+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 compiled = transpileModule(readFileSync("src/config/setting/windowRuntime.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;+const deferred = () => {+ let resolve: (value?: unknown) => void;+ const promise = new Promise(done => { resolve = done; });+ return {promise, resolve};+};+const tick = () => new Promise(resolve => setImmediate(resolve));++const fixture = () => {+ 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 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}],+ languages: {allNotebooks: "All notebooks"}}, opener: undefined as unknown};+ const elements = new Map();+ const dependencies = {+ Constants: {LOCAL_ZOOM: "zoom", SIYUAN_CMD: "cmd", TIMEOUT_SNIPPET_LOAD: 5000,+ SIZE_ZOOM: [{zoom: 1, position: {x: 8, y: 8}}, {zoom: 1.25, position: {x: 18, y: 12}}]},+ ipcRenderer: {send: (_channel: string, data: unknown) => calls.push({type: "position", value: data})},+ webFrame: {setZoomFactor: (value: number) => calls.push({type: "zoom", value})},+ setToolbarLeftMac: (value: number) => calls.push({type: "left", value}),+ 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();+ calls.push({type: "snippet", value: config.snippet}); guards.push(guard);+ },+ getHostCapabilities: () => ({customAppearance: true}),+ ensureLute: async () => { calls.push({type: "lute"}); },+ onAgentStreamingMarkdownStorageChanged: (key: string) => calls.push({type: "storage", value: key}),+ genNotebookOption: (id: string, _box: string, shorthand: boolean, filter: (notebook: unknown) => boolean) => {+ calls.push({type: "options", value: {id, shorthand, filter}});+ return '<option value="">Current</option><option value="a">Renamed</option>';+ },+ };+ const exports = {} as typeof import("./windowRuntime");+ const location = {search: "?settingsWindowToken=token", origin: "https://siyuan"};+ runInNewContext(compiled, {exports, window, location, URLSearchParams, console, setTimeout, clearTimeout,+ CustomEvent: class {constructor(public type: string, public options: unknown) {}},+ 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,+ setActive: (value: boolean) => { active = value; },+ setNotebooks: (value: typeof notebooks) => { notebooks = value; },+ setFetch: (value: typeof fetch) => { fetch = value; }};+};++test("settings host handshake fails closed for missing, stale, asynchronous and cross-origin owners", () => {+ const f = fixture();+ const host = {isActive: () => true};+ let late: (value: unknown) => void;+ f.window.opener = {location: {origin: f.location.origin}, dispatchEvent: (event: {options: {detail: typeof late}}) => {+ late = event.options.detail;+ }};+ assert.equal(f.exports.resolveSettingsWindowHost(), undefined);+ late(host);+ f.window.opener = {location: {origin: f.location.origin}, dispatchEvent: (event: {options: {detail: typeof late}}) => {+ event.options.detail(host);+ }};+ assert.equal(f.exports.resolveSettingsWindowHost(), host);+ f.window.opener = {location: {origin: "https://other"}};+ assert.equal(f.exports.resolveSettingsWindowHost(), undefined);+ f.location.search = "";+ assert.equal(f.exports.resolveSettingsWindowHost(), undefined);+});++test("main notebook mutations coalesce serial refreshes and ignore filetree-only commands", async () => {+ const f = fixture();+ const first = deferred();+ f.setNotebooks(() => first.promise);+ const initial = f.runtime.refreshNotebooks();+ for (const cmd of ["createnotebook", "renamenotebook", "mount", "closeBox", "removeBox", "syncMergeResult", "notebookSortChanged"]) {+ assert.equal(f.runtime.handleMessage({cmd} as IWebSocketData), true);+ }+ assert.equal(f.runtime.handleMessage({cmd: "reloadFiletree"} as IWebSocketData), false);+ assert.equal(f.runtime.handleMessage({cmd: "reloadNotebookInfo"} as IWebSocketData), false);+ assert.equal(f.calls.filter(call => call.type === "notebooks").length, 1);+ f.setNotebooks(async () => {});+ first.resolve();+ await initial;+ assert.equal(f.calls.filter(call => call.type === "notebooks").length, 2);+ f.setActive(false);+ await f.runtime.refreshNotebooks();+ assert.equal(f.calls.filter(call => call.type === "notebooks").length, 2);+});++test("notebook options preserve a renamed or removed selection without replacing inputs or filters", () => {+ const f = fixture();+ const select = (value: string) => ({+ value, selectedOptions: [{textContent: "Old name"}], options: [] as {value: string; disabled?: boolean}[],+ set innerHTML(_html: string) { this.options = [{value: ""}, {value: "a"}]; },+ append(option: {value: string}) { this.options.push(option); },+ replaceChildren(...options: {value: string}[]) { this.options = options; },+ });+ const renamed = select("a");+ const removed = select("removed");+ const shorthand = select("a");+ f.elements.set("fileTree.docCreateSaveBox", renamed);+ f.elements.set("fileTree.refCreateSaveBox", removed);+ f.elements.set("fileTree.shorthandSaveBox", shorthand);+ const history = select("a");+ f.elements.set("history", history);+ const input = {value: "unsaved/path"};+ const search = {value: "filtered"};+ f.elements.set("fileTree.docCreateSavePath", input);+ f.elements.set("settingsSearch", search);+ f.exports.patchSettingsNotebookOptions();+ assert.equal(renamed.value, "a");+ assert.equal(removed.value, "removed");+ assert.equal(removed.options.at(-1).disabled, true);+ assert.equal(input.value, "unsaved/path");+ assert.equal(search.value, "filtered");+ assert.equal(history.value, "a");+ assert.deepEqual(history.options.map(option => option.value), ["%", "a"]);+ const options = f.calls.filter(call => call.type === "options");+ const filter = (options[2].value as {filter: (notebook: unknown) => boolean}).filter;+ assert.equal(filter({closed: false, encrypted: false}), true);+ assert.equal(filter({closed: true, encrypted: false}), false);+ assert.equal(filter({closed: false, encrypted: true}), false);+});++test("stalled or failed initialization closes through the failure callback exactly once", async () => {+ const f = fixture();+ const stalled = deferred();+ const errors: unknown[] = [];+ await f.exports.startSettingsWindow(() => stalled.promise as Promise<void>, error => errors.push(error), 1);+ assert.equal(errors.length, 1);+ assert.match(String(errors[0]), /timed out/);+ stalled.resolve();+ await tick();+ assert.equal(errors.length, 1);+ await f.exports.startSettingsWindow(async () => { throw new Error("render failure"); }, error => errors.push(error));+ assert.equal(errors.length, 2);+ assert.match(String(errors[1]), /render failure/);+});++test("settings receive all zoom storage messages without persistence or owner toolbar offsets", () => {+ const f = fixture();+ const send = (cmd: string, data: unknown) => f.runtime.handleMessage({cmd, data} as IWebSocketData);+ f.runtime.applyZoom();+ send("setLocalStorageVal", {key: "zoom", val: 1.25});+ send("removeLocalStorageVal", {key: "zoom"});+ send("setLocalStorageVals", {keyVals: {zoom: 1.25, unrelated: true}});+ send("removeLocalStorageVals", {keys: ["zoom", "unrelated"]});+ assert.deepEqual(f.calls.filter(call => call.type === "zoom").map(call => call.value), [1, 1.25, 1, 1.25, 1]);+ assert.equal(JSON.stringify(f.calls.filter(call => call.type === "position")[1].value),+ JSON.stringify({cmd: "setTrafficLightPosition", zoom: 1.25, position: {x: 18, y: 12}}));+ assert.equal(f.calls.filter(call => call.type === "fetch").length, 0);+ f.setActive(false);+ send("setLocalStorageVal", {key: "zoom", val: 1.25});+ assert.equal(f.storage.zoom, undefined);+});++test("snippets assign configuration first and wait for Lute before rendering JS", async () => {+ const f = fixture();+ await f.runtime.refreshSnippets();+ const next = {enabledCSS: false, enabledJS: true};+ f.runtime.handleMessage({cmd: "setSnippet", data: next} as IWebSocketData);+ assert.equal(f.config.snippet, next);+ await tick();+ assert.deepEqual(f.calls.map(call => call.type), ["snippet", "lute", "snippet"]);+ assert.equal(f.guards[0](), false);+ assert.equal(f.guards[1](), true);+ f.setActive(false);+ assert.equal(f.guards[1](), false);+});++test("reconnection refreshes notebooks, snippet flags and zoom and ignores stale responses", async () => {+ const f = fixture();+ await f.runtime.reconnect();+ assert.equal(f.config.snippet.enabledJS, true);+ assert.equal(f.storage.zoom, 1.25);+ assert.ok(f.calls.some(call => call.type === "notebooks"));+ assert.ok(f.calls.some(call => call.type === "snippet"));+ const delayed = deferred();+ f.setFetch(() => delayed.promise);+ const reconnected = f.runtime.reconnect();+ f.runtime.handleMessage({cmd: "setLocalStorageVal", data: {key: "zoom", val: 1}} as IWebSocketData);+ f.runtime.handleMessage({cmd: "setSnippet", data: {enabledCSS: false, enabledJS: false}} as IWebSocketData);+ delayed.resolve({code: 0, data: {zoom: 1.25, conf: {snippet: {enabledCSS: true, enabledJS: true}}}});+ await reconnected;+ assert.equal(f.storage.zoom, 1);+ assert.equal(f.config.snippet.enabledCSS, false);+ assert.equal(f.config.snippet.enabledJS, false);+ const closed = deferred();+ f.setFetch(() => closed.promise);+ const pending = f.runtime.reconnect();+ f.setActive(false);+ closed.resolve({code: 0, data: {zoom: 1.25, conf: {snippet: {enabledCSS: true, enabledJS: true}}}});+ await pending;+ assert.equal(f.storage.zoom, 1);+ assert.equal(f.config.snippet.enabledJS, false);+});++test("a newer reconnect zoom read cannot be overwritten by an older reconnect", async () => {+ const f = fixture();+ const older = deferred();+ const newer = deferred();+ let reads = 0;+ f.setFetch(url => url.endsWith("getConf") ? Promise.resolve({code: 0, data: {conf: {snippet: f.config.snippet}}}) :+ (++reads === 1 ? older.promise : newer.promise));+ const first = f.runtime.reconnect();+ const second = f.runtime.reconnect();+ newer.resolve({code: 0, data: {zoom: 1.25}});+ await second;+ older.resolve({code: 0, data: {zoom: 1}});+ await first;+ assert.equal(f.storage.zoom, 1.25);+});++test("notebook entry refresh reports failures and can retry without replacing a disposed view", async () => {+ const f = fixture();+ f.setNotebooks(async () => { throw new Error("offline"); });+ await assert.rejects(f.exports.refreshSettingsWindowNotebooks(), /offline/);+ f.setNotebooks(async () => {});+ await f.exports.refreshSettingsWindowNotebooks();+ const pending = deferred();+ f.setNotebooks(() => pending.promise);+ const refresh = f.exports.refreshSettingsWindowNotebooks();+ f.setActive(false);+ pending.resolve();+ await refresh;+ assert.equal(f.calls.filter(call => call.type === "notebooks").length, 3);+});diff --git a/app/src/config/setting/windowRuntime.ts b/app/src/config/setting/windowRuntime.tsnew file mode 100644index 0000000000..ff0c7ff62f--- /dev/null+++ b/app/src/config/setting/windowRuntime.ts@@ -0,0 +1,218 @@+import {ipcRenderer, webFrame} from "electron";+import {Constants} from "../../constants";+import {setNoteBook} from "../../util/pathName";+import {fetchSyncPost} from "../../util/fetch";+import {genNotebookOption} from "../../menus/onGetnotebookconf";+import {isMac} from "../../protyle/util/compatibility";+import {setToolbarLeftMac} from "../../util/functions";+import {ensureLute} from "../../protyle/util/lute";+import {renderSnippet} from "../util/snippets";+import {onAgentStreamingMarkdownStorageChanged} from "../tabs/ai/agentStreamingMarkdown";+import type {ISettingsWindowHost} from "./windowContext";++let notebookRefresh = () => Promise.resolve();+export const refreshSettingsWindowNotebooks = () => notebookRefresh();++// 初始化失败或依赖请求一直未完成时关闭窗口,迟到的回调由生命周期检查拦截。+export const startSettingsWindow = async (initialize: () => Promise<void>, failed: (error: unknown) => void, timeout = 30000) => {+ let timer: ReturnType<typeof setTimeout>;+ try {+ await Promise.race([initialize(), new Promise<never>((_resolve, reject) => {+ timer = setTimeout(() => reject(new Error("Settings window initialization timed out")), timeout);+ })]);+ } catch (error) {+ failed(error);+ } finally {+ clearTimeout(timer);+ }+};++// 宿主握手仅接受同步应答,失效令牌不能让隐藏窗口无限等待。+export const resolveSettingsWindowHost = (): ISettingsWindowHost | undefined => {+ const token = new URLSearchParams(location.search).get("settingsWindowToken");+ if (!token) return;+ try {+ if (!window.opener || window.opener.closed || window.opener.location.origin !== location.origin) return;+ let accepting = true;+ let host: ISettingsWindowHost;+ window.opener.dispatchEvent(new CustomEvent("siyuan-settings-host-" + token, {+ detail: (value: ISettingsWindowHost) => {+ if (accepting && !host && value?.isActive()) host = value;+ },+ }));+ accepting = false;+ return host;+ } catch (error) {+ console.warn("Could not connect to the settings window owner", error);+ }+};++// 只更新笔记本选项,保留当前选择、未保存输入和设置搜索过滤状态。+export const patchSettingsNotebookOptions = () => {+ const patch = (select: HTMLSelectElement, render: (selected: string) => void) => {+ const selected = select.value;+ const label = select.selectedOptions[0]?.textContent || selected;+ render(selected);+ if (![...select.options].some(option => option.value === selected)) {+ const unavailable = document.createElement("option");+ unavailable.value = selected;+ unavailable.textContent = label;+ unavailable.disabled = true;+ select.append(unavailable);+ }+ select.value = selected;+ };+ for (const key of ["docCreateSaveBox", "refCreateSaveBox", "shorthandSaveBox"]) {+ const select = document.getElementById("fileTree." + key) as HTMLSelectElement;+ if (!select) continue;+ patch(select, selected => {+ const shorthand = key === "shorthandSaveBox";+ select.innerHTML = genNotebookOption(selected, undefined, shorthand,+ shorthand ? item => !item.closed && !item.encrypted : undefined);+ });+ }+ document.querySelectorAll<HTMLSelectElement>('#historyContainer select[data-type="notebookselect"]').forEach(select => {+ patch(select, () => {+ const options = [{id: "%", name: window.siyuan.languages.allNotebooks},+ ...window.siyuan.notebooks.filter(item => !item.closed)];+ select.replaceChildren(...options.map(item => {+ const option = document.createElement("option");+ option.value = item.id;+ option.textContent = item.name;+ return option;+ }));+ });+ });+};++export const createSettingsWindowRuntime = (isActive: () => boolean) => {+ let notebooksPending = false;+ let notebooksLoading: Promise<void>;+ let snippetRevision = 0;+ let snippetsPending = false;+ let snippetConfigPending = false;+ let snippetsLoading: Promise<void>;+ let zoomRevision = 0;++ const applyZoom = () => {+ if (!isActive()) return;+ const value = window.siyuan.storage[Constants.LOCAL_ZOOM];+ const size = Constants.SIZE_ZOOM.find(item => item.zoom === value) ||+ Constants.SIZE_ZOOM.find(item => item.zoom === 1);+ webFrame.setZoomFactor(size.zoom);+ setToolbarLeftMac(size.zoom);+ if (isMac()) {+ // 设置窗口有自己的标题栏,不使用主窗口隐藏工具栏的偏移。+ ipcRenderer.send(Constants.SIYUAN_CMD, {+ cmd: "setTrafficLightPosition", zoom: size.zoom, position: {...size.position},+ });+ }+ };++ const refreshNotebooks = (): Promise<void> => {+ if (!isActive()) return Promise.resolve();+ notebooksPending = true;+ if (notebooksLoading) return notebooksLoading;+ notebooksLoading = (async () => {+ while (notebooksPending && isActive()) {+ notebooksPending = false;+ let refreshed = false;+ await setNoteBook(() => { refreshed = true; });+ if (!isActive()) return;+ if (!refreshed) throw new Error("Could not refresh settings notebooks");+ patchSettingsNotebookOptions();+ }+ })().finally(() => {+ notebooksLoading = undefined;+ if (notebooksPending && isActive()) return refreshNotebooks();+ });+ return notebooksLoading;+ };+ notebookRefresh = refreshNotebooks;++ const refreshSnippets = (reloadConfig = false): Promise<void> => {+ if (!isActive()) return Promise.resolve();+ snippetsPending = true;+ snippetConfigPending ||= reloadConfig;+ snippetRevision++;+ if (snippetsLoading) return snippetsLoading;+ snippetsLoading = (async () => {+ while (snippetsPending && isActive()) {+ snippetsPending = false;+ const revision = snippetRevision;+ if (snippetConfigPending) {+ snippetConfigPending = false;+ const response = await fetchSyncPost("/api/system/getConf", {});+ if (!isActive()) return;+ if (revision !== snippetRevision) continue;+ if (response.code === 0) window.siyuan.config.snippet = response.data.conf.snippet;+ }+ if (!isActive()) return;+ await renderSnippet(Constants.TIMEOUT_SNIPPET_LOAD, () => isActive() && revision === snippetRevision,+ () => ensureLute({reloadOnFailure: false}));+ }+ })().catch(error => console.error("Could not refresh settings snippets", error)).finally(() => {+ snippetsLoading = undefined;+ if (snippetsPending && isActive()) return refreshSnippets();+ });+ return snippetsLoading;+ };++ const refreshZoom = async () => {+ const revision = ++zoomRevision;+ const response = await fetchSyncPost("/api/storage/getLocalStorage");+ if (!isActive() || revision !== zoomRevision || response.code !== 0) return;+ window.siyuan.storage[Constants.LOCAL_ZOOM] = response.data[Constants.LOCAL_ZOOM] ?? 1;+ applyZoom();+ };++ const onStorageChanged = (keys: string[]) => {+ keys.forEach(onAgentStreamingMarkdownStorageChanged);+ if (keys.includes(Constants.LOCAL_ZOOM)) {+ zoomRevision++;+ applyZoom();+ }+ };++ const handleMessage = (data: IWebSocketData): boolean => {+ if (!isActive()) return true;+ switch (data.cmd) {+ case "createnotebook":+ case "renamenotebook":+ case "mount":+ case "closeBox":+ case "removeBox":+ case "syncMergeResult":+ case "notebookSortChanged":+ void refreshNotebooks().catch(error => console.error("Could not refresh settings notebooks", error));+ return true;+ case "setSnippet":+ window.siyuan.config.snippet = data.data;+ void refreshSnippets();+ return true;+ case "setLocalStorageVal":+ window.siyuan.storage[data.data.key] = data.data.val;+ onStorageChanged([data.data.key]);+ return true;+ case "setLocalStorageVals":+ Object.assign(window.siyuan.storage, data.data.keyVals);+ onStorageChanged(Object.keys(data.data.keyVals));+ return true;+ case "removeLocalStorageVal":+ delete window.siyuan.storage[data.data.key];+ onStorageChanged([data.data.key]);+ return true;+ case "removeLocalStorageVals":+ data.data.keys.forEach((key: string) => delete window.siyuan.storage[key]);+ onStorageChanged(data.data.keys);+ return true;+ }+ return false;+ };++ const reconnect = async () => {+ if (!isActive()) return;+ await Promise.all([refreshNotebooks(), refreshSnippets(true), refreshZoom()]);+ };+ return {applyZoom, refreshNotebooks, refreshSnippets, handleMessage, reconnect};+};diff --git a/app/src/config/tabs/appTab.ts b/app/src/config/tabs/appTab.tsindex 09aa2b20f4..32c302c5fc 100644--- a/app/src/config/tabs/appTab.ts+++ b/app/src/config/tabs/appTab.ts@@ -12,7 +12,7 @@ import {Constants} from "../../constants";import {fetchPost} from "../../util/fetch";import {ContractFormData} from "../../util/contractFormData";/// #if !MOBILE-import {exportLayout} from "../../layout/util";+import {exportLayout, reloadUI} from "../../layout/util";/// #endifimport {exitSiYuan} from "../../dialog/processSystem";import {showMessage} from "../../dialog/message";@@ -400,12 +400,7 @@ const mountNetworkProxy = (root: HTMLElement) => {proxyMode: scheme === "system" ? "system" : scheme === "" ? "direct" : "fixed_servers",proxyURL: scheme === "system" ? "://" : `${scheme}://${host}:${port}`,}).then(() => {- exportLayout({- errorExit: false,- cb() {- window.location.reload();- },- });+ void reloadUI();});/// #endif});diff --git a/app/src/config/tabs/appearanceRuntime.test.ts b/app/src/config/tabs/appearanceRuntime.test.tsindex 358cb1e83f..329255374b 100644--- a/app/src/config/tabs/appearanceRuntime.test.ts+++ b/app/src/config/tabs/appearanceRuntime.test.ts@@ -111,7 +111,10 @@ for (const mobile of [true, false]) {}});}if (name === "../../layout/util") {- return {exportLayout: (options: {cb: () => void}) => options.cb()};+ return {reloadUI: () => calls.push("reload")};+ }+ if (name === "../setting/windowContext") {+ return {isSettingsWindow: () => false, closeSettingsWindow: () => false};}return new Proxy({}, {get: (_, key) => () => calls.push(String(key))});},diff --git a/app/src/config/tabs/appearanceRuntime.ts b/app/src/config/tabs/appearanceRuntime.tsindex b3ee3ccc50..56490f5fdb 100644--- a/app/src/config/tabs/appearanceRuntime.ts+++ b/app/src/config/tabs/appearanceRuntime.ts@@ -2,7 +2,7 @@import {saveScroll} from "../../protyle/scroll/saveScroll";/// #elseimport {adjustDockPadding} from "../../layout/dock/util";-import {exportLayout} from "../../layout/util";+import {reloadUI as reloadDesktopUI} from "../../layout/util";import {syncHideToolbarLayout, updateBarModeIcon} from "../../layout/topBar";/// #endifimport {fetchPost} from "../../util/fetch";@@ -22,7 +22,7 @@ import {remountOpenSettingTab} from "../setting/mount";import {createConfigNamespaceApi} from "../util/namespaceApi";import {syncBodyGradient} from "./bodyGradient";import {refreshDynamicIcons} from "../../emoji/dynamicIcon";-import {isSettingsWindow} from "../setting/windowContext";+import {closeSettingsWindow, isSettingsWindow} from "../setting/windowContext";/** 主题模式下拉框初值:合并 mode / modeOS */export const appearanceThemeModeValue = (): number =>@@ -56,19 +56,14 @@ interface IAppearanceRefresh {const applyAppearanceConfig = async (data: Config.IAppearance, refresh?: IAppearanceRefresh) => {if (data.lang !== window.siyuan.config.appearance.lang) {if (isSettingsWindow()) {- window.location.reload();+ closeSettingsWindow();return;}markAppearanceReloadPending();/// #if MOBILEvoid reloadUI();/// #else- void exportLayout({- cb() {- window.location.reload();- },- errorExit: false,- });+ void reloadDesktopUI();/// #endifreturn;}@@ -90,16 +85,12 @@ const applyAppearanceConfig = async (data: Config.IAppearance, refresh?: IAppear}const unloadChangedTheme = themeChanged && prevAppearance.themeJS && isCurrentThemeSupported(prevAppearance, getFrontend());if ((unloadChangedTheme || shouldUnloadThemeScript(prevAppearance, data, getFrontend())) && !await unloadThemeScript()) {+ if (closeSettingsWindow()) return;markAppearanceReloadPending();/// #if MOBILEvoid reloadUI();/// #else- void exportLayout({- errorExit: false,- cb() {- window.location.reload();- },- });+ void reloadDesktopUI();/// #endifreturn;}diff --git a/app/src/config/tabs/keymapUi.ts b/app/src/config/tabs/keymapUi.tsindex 624c883851..c33a91b73d 100644--- a/app/src/config/tabs/keymapUi.ts+++ b/app/src/config/tabs/keymapUi.ts@@ -4,7 +4,7 @@ import {matchHotKey} from "../../protyle/util/hotKey";import {Constants} from "../../constants";import {hideMessage, showMessage} from "../../dialog/message";import {fetchSyncPost} from "../../util/fetch";-import {exportLayout} from "../../layout/util";+import {reloadUI} from "../../layout/util";import {applyKeymap} from "./keymapRuntime";import {confirmDialog} from "../../dialog/confirmDialog";import {sendGlobalShortcut, sendUnregisterGlobalShortcut} from "../../boot/globalEvent/globalShortcut";@@ -57,12 +57,7 @@ const genKeymapTabHtml = () => genKeymapToolbarHtml() + genConfigGroup(genKeymapconst bindKeymapToolbar = (root: HTMLElement) => {root.querySelector("#keymapRefreshBtn")?.addEventListener("click", () => {- void exportLayout({- cb() {- window.location.reload();- },- errorExit: false,- });+ void reloadUI();});root.querySelector("#keymapResetBtn")?.addEventListener("click", () => {confirmDialog("⚠️ " + window.siyuan.languages.reset, window.siyuan.languages.confirmReset, () => {@@ -75,7 +70,7 @@ const bindKeymapToolbar = (root: HTMLElement) => {}savedKeymap = data;applyKeymap(data);- void exportLayout({cb: () => window.location.reload(), errorExit: false});+ void reloadUI();} catch (error) {console.error("Could not reset shortcuts:", error);showMessage(window.siyuan.languages.keymapSaveFailed);diff --git a/app/src/config/tabs/syncTab.test.ts b/app/src/config/tabs/syncTab.test.tsnew file mode 100644index 0000000000..4d976a0801--- /dev/null+++ b/app/src/config/tabs/syncTab.test.ts@@ -0,0 +1,173 @@+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 preprocess = require("ifdef-loader/preprocessor").parse;++const createSnapshotButton = ({mobile = false, browser = false, settingsWindow = true} = {}) => {+ const nativeSettings = !mobile && !browser && settingsWindow;+ const source = preprocess(readFileSync("src/config/tabs/syncTab.ts", "utf8"), {MOBILE: mobile, BROWSER: browser});+ const code = transpileModule(source ++ "\nexports.mount = mountSyncCloudBackup;", {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText;+ let click: () => Promise<void>;+ let complete: () => void;+ let fail: (error: Error) => void;+ let loading: Promise<void>;+ let loads = 0;+ let opened = 0;+ let errors = 0;+ let attached = true;+ let dialogOpen = true;+ let ownerActive = true;+ let notebookReads = 0;+ let runtimeImports = 0;+ let notebooksLoading = Promise.resolve();+ let completeNotebooks: () => void;+ let failNotebooks: (error: Error) => void;+ let openedNotebooks: string[];+ const app = {};+ const window = {closed: false, siyuan: {ws: {app}, notebooks: ["old"], languages: {_kernel: {258: "Operation failed"}}}};+ const button = {isConnected: true, disabled: false, addEventListener: (_type: string, callback: typeof click) => {+ click = callback;+ }};+ const root = {isConnected: true, contains: () => attached, querySelector: () => button,+ closest: () => mobile ? null : {classList: {contains: () => dialogOpen}}};+ const exports = {} as {mount: (root: any) => void};+ runInNewContext(code, {exports, window, console: {error() {}}, require: (name: string) => {+ if (name === "../../constants") return {Constants: {DIALOG_SETTING: "settings"}};+ if (name === "../../protyle/util/lute") return {ensureLute: (options?: {reloadOnFailure: boolean}) => {+ assert.equal(options?.reloadOnFailure, nativeSettings ? false : undefined);+ loads++;+ return loading;+ }};+ if (name === "../setting/windowContext") return {isSettingsWindow: () => settingsWindow,+ getSettingsWindowHost: () => ({isActive: () => ownerActive})};+ if (name === "../setting/windowRuntime") {+ runtimeImports++;+ return {refreshSettingsWindowNotebooks: () => { notebookReads++; return notebooksLoading; }};+ }+ if (name === "../../history/history") return {openHistory: (historyApp: unknown, type: string, openOnly: boolean) => {+ assert.equal(historyApp, app);+ assert.equal(type, "repo");+ assert.equal(openOnly, true);+ openedNotebooks = [...window.siyuan.notebooks];+ opened++;+ }};+ if (name === "../../dialog/message") return {showMessage: () => errors++};+ return {};+ }});+ const retry = () => loading = new Promise<void>((resolve, reject) => { complete = resolve; fail = reject; });+ const waitForNotebooks = () => notebooksLoading = new Promise<void>((resolve, reject) => {+ completeNotebooks = resolve;+ failNotebooks = reject;+ });+ retry();+ exports.mount(root);+ return {button, root, window, retry, click: () => click(), complete: () => complete(),+ fail: () => fail(new Error("Lute unavailable")), loads: () => loads, opened: () => opened,+ errors: () => errors, unmount: () => { attached = false; }, close: () => { dialogOpen = false; },+ dispose: () => { ownerActive = false; }, notebookReads: () => notebookReads, runtimeImports: () => runtimeImports,+ waitForNotebooks, completeNotebooks: () => { window.siyuan.notebooks = ["latest"]; completeNotebooks(); },+ failNotebooks: () => failNotebooks(new Error("Notebook refresh failed")), openedNotebooks: () => openedNotebooks};+};++test("snapshot history waits for Lute and coalesces repeated clicks", async () => {+ const snapshot = createSnapshotButton();+ const first = snapshot.click();+ const second = snapshot.click();+ assert.equal(snapshot.loads(), 1);+ assert.equal(snapshot.opened(), 0);+ assert.equal(snapshot.button.disabled, true);+ snapshot.complete();+ await Promise.all([first, second]);+ assert.equal(snapshot.opened(), 1);+ assert.equal(snapshot.button.disabled, false);+});++test("a failed snapshot dependency leaves no history dialog and can be retried", async () => {+ const snapshot = createSnapshotButton();+ const pending = snapshot.click();+ snapshot.fail();+ await pending;+ assert.equal(snapshot.opened(), 0);+ assert.equal(snapshot.errors(), 1);+ assert.equal(snapshot.button.disabled, false);+ snapshot.retry();+ const retried = snapshot.click();+ snapshot.complete();+ await retried;+ assert.equal(snapshot.opened(), 1);+ assert.equal(snapshot.loads(), 2);+});++test("snapshot completion ignores detached, replaced, closing, and closed settings", async () => {+ for (const action of ["detach", "replace", "close", "closed", "dispose"]) {+ for (const fail of [false, true]) {+ const snapshot = createSnapshotButton();+ const pending = snapshot.click();+ if (action === "detach") snapshot.root.isConnected = false;+ if (action === "replace") snapshot.unmount();+ if (action === "close") snapshot.close();+ if (action === "closed") snapshot.window.closed = true;+ if (action === "dispose") snapshot.dispose();+ if (fail) snapshot.fail();+ else snapshot.complete();+ await pending;+ assert.equal(snapshot.opened(), 0, action);+ assert.equal(snapshot.errors(), 0, action);+ }+ }+});++test("ordinary and mobile snapshots retain default Lute recovery without importing the native runtime", async () => {+ for (const options of [{mobile: true}, {browser: true}, {settingsWindow: false}]) {+ const snapshot = createSnapshotButton(options);+ const pending = snapshot.click();+ snapshot.complete();+ await pending;+ assert.equal(snapshot.opened(), 1);+ assert.equal(snapshot.runtimeImports(), 0);+ assert.equal(snapshot.notebookReads(), 0);+ }+});++test("native snapshot history waits for the coalesced notebook refresh as well as Lute", async () => {+ const snapshot = createSnapshotButton();+ snapshot.waitForNotebooks();+ const pending = snapshot.click();+ const repeated = snapshot.click();+ snapshot.complete();+ await Promise.resolve();+ await Promise.resolve();+ assert.equal(snapshot.opened(), 0);+ assert.equal(snapshot.loads(), 1);+ assert.equal(snapshot.notebookReads(), 1);+ snapshot.completeNotebooks();+ await Promise.all([pending, repeated]);+ assert.equal(snapshot.opened(), 1);+ assert.deepEqual(snapshot.openedNotebooks(), ["latest"]);+});++test("snapshot notebook failure and a disposed owner cannot open a partial history", async () => {+ for (const disposed of [false, true]) {+ const snapshot = createSnapshotButton();+ snapshot.waitForNotebooks();+ const pending = snapshot.click();+ snapshot.complete();+ await Promise.resolve();+ if (disposed) {+ snapshot.dispose();+ snapshot.completeNotebooks();+ } else {+ snapshot.failNotebooks();+ }+ await pending;+ assert.equal(snapshot.opened(), 0);+ assert.equal(snapshot.errors(), disposed ? 0 : 1);+ assert.equal(snapshot.button.disabled, false);+ }+});diff --git a/app/src/config/tabs/syncTab.ts b/app/src/config/tabs/syncTab.tsindex 12bec63613..4f649367c6 100644--- a/app/src/config/tabs/syncTab.ts+++ b/app/src/config/tabs/syncTab.ts@@ -12,6 +12,58 @@ import {genConfigItemMainHtml, genConfigItemName} from "../render/fragments";import {getLANSyncSearchAvailability, getSyncProviderConfigKeywords} from "./syncUi";import {mountLANSyncStatus, mountSyncAssetDownloadMode, mountSyncProvider} from "./syncRuntime";import {openHistory} from "../../history/history";+import {ensureLute} from "../../protyle/util/lute";+/// #if !MOBILE && !BROWSER+import {getSettingsWindowHost, isSettingsWindow} from "../setting/windowContext";+/// #endif++const mountSyncCloudBackup = (root: HTMLElement) => {+ const button = root.querySelector<HTMLButtonElement>("#openCloudBackup");+ if (!button) {+ return;+ }+ let pending = false;+ const isMounted = () => {+ /// #if !MOBILE && !BROWSER+ if (isSettingsWindow() && !getSettingsWindowHost()?.isActive()) {+ return false;+ }+ /// #endif+ const dialog = root.closest(`[data-key="${Constants.DIALOG_SETTING}"]`);+ return !window.closed && root.isConnected && button.isConnected && root.contains(button) &&+ (!dialog || dialog.classList.contains("b3-dialog--open"));+ };+ button.addEventListener("click", async () => {+ if (pending || !isMounted()) {+ return;+ }+ pending = true;+ button.disabled = true;+ try {+ const dependencies: Promise<void>[] = [];+ let luteOptions: {reloadOnFailure: boolean};+ /// #if !MOBILE && !BROWSER+ if (isSettingsWindow()) {+ luteOptions = {reloadOnFailure: false};+ dependencies.push(import("../setting/windowRuntime").then(runtime => runtime.refreshSettingsWindowNotebooks()));+ }+ /// #endif+ dependencies.push(ensureLute(luteOptions));+ await Promise.all(dependencies);+ if (isMounted()) {+ openHistory(window.siyuan.ws.app, "repo", true);+ }+ } catch (error) {+ if (isMounted()) {+ console.error("Could not initialize snapshot history", error);+ showMessage(window.siyuan.languages._kernel["258"], 6000, "error");+ }+ } finally {+ pending = false;+ button.disabled = false;+ }+ });+};const registerSyncGroup = (tab: SettingTabBuilder) => {const group = tab.group("sync", window.siyuan.languages.configGroupSync);@@ -111,11 +163,7 @@ const registerSyncGroup = (tab: SettingTabBuilder) => {</button></div></div>`,- afterMount: (root) => {- root.querySelector("#openCloudBackup")?.addEventListener("click", () => {- openHistory(window.siyuan.ws.app, "repo");- });- },+ afterMount: mountSyncCloudBackup,});};diff --git a/app/src/config/util/snippets.test.ts b/app/src/config/util/snippets.test.tsnew file mode 100644index 0000000000..a8a3bcde12--- /dev/null+++ b/app/src/config/util/snippets.test.ts@@ -0,0 +1,130 @@+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 = () => {+ const elements = new Map<string, {id: string; tagName: string; textContent?: string; text?: string; nonce?: string}>();+ const requests: {complete: (snippets: unknown[]) => void}[] = [];+ let allowed = true;+ let measurements = 0;+ const executed: string[] = [];+ const config = {snippet: {enabledCSS: true, enabledJS: true}};+ const exports = {} as typeof import("./snippets");+ runInNewContext(transpileModule(readFileSync("src/config/util/snippets.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText, {exports, AbortController, window: {siyuan: {config}, setTimeout, clearTimeout},+ document: {+ getElementById: (id: string) => elements.get(id),+ querySelectorAll: () => [...elements.values()],+ createElement: (tag: string) => ({id: "", tagName: tag.toUpperCase(), textContent: "", nonce: "",+ get text() { return this.textContent; }, set text(value: string) { this.textContent = value; },+ remove() { elements.delete(this.id); }}),+ head: {appendChild: (element: {id: string; tagName: string; text: string}) => {+ elements.set(element.id, element);+ if (element.tagName === "SCRIPT") executed.push(element.text);+ }},+ }, require: () => ({+ getHostCapabilities: () => ({customAppearance: allowed}), getExtensionScriptNonce: () => "extension-nonce",+ refreshHeadingNumberMeasurements: () => { measurements++; },+ fetchPost: (_url: string, _data: unknown, callback: (response: unknown) => void) => new Promise<void>(resolve => {+ requests.push({complete: snippets => { callback({data: {snippets}}); resolve(); }});+ }),+ })});+ const render = async (snippets: unknown[], active = () => true) => {+ const pending = exports.renderSnippet(0, active);+ requests.at(-1).complete(snippets);+ await pending;+ };+ return {exports, config, elements, requests, executed, render, setAllowed: (value: boolean) => { allowed = value; },+ measurements: () => measurements};+};++test("shared snippet renderer preserves CSS, JS enable flags, nonce and unchanged script semantics", async () => {+ const f = fixture();+ const css = {id: "css", type: "css", enabled: true, content: "body {color: red;}"};+ const js = {id: "js", type: "js", enabled: true, content: "window.customSetting = true;"};+ await f.render([css, js]);+ assert.equal(f.elements.get("snippetCSScss").textContent, css.content);+ assert.equal(f.elements.get("snippetJSjs").nonce, "extension-nonce");+ assert.deepEqual(f.executed, [js.content]);+ assert.equal(f.measurements(), 1);+ await f.render([css, js]);+ assert.equal(f.executed.length, 1);+ assert.equal(f.measurements(), 1);+ f.config.snippet.enabledJS = false;+ await f.render([css, js]);+ assert.equal(f.elements.has("snippetJSjs"), false);+ assert.equal(f.elements.has("snippetCSScss"), true);+ f.config.snippet.enabledCSS = false;+ await f.render([css, js]);+ assert.equal(f.elements.size, 0);+ f.config.snippet.enabledCSS = true;+ f.config.snippet.enabledJS = true;+ await f.render([css, {...js, enabled: false}]);+ assert.equal(f.elements.size, 1);+ await f.render([]);+ assert.equal(f.elements.size, 0);+});++test("snippet capability and active guards prevent fetches and late script/style execution", async () => {+ const f = fixture();+ f.setAllowed(false);+ await f.exports.renderSnippet();+ assert.equal(f.requests.length, 0);+ f.setAllowed(true);+ await f.exports.renderSnippet(0, () => false);+ assert.equal(f.requests.length, 0);+ let active = true;+ const pending = f.exports.renderSnippet(0, () => active);+ active = false;+ f.requests.at(-1).complete([{id: "late", type: "js", enabled: true, content: "late();"}]);+ await pending;+ assert.equal(f.elements.size, 0);+ assert.equal(f.executed.length, 0);+ const untrusted = f.exports.renderSnippet();+ f.setAllowed(false);+ f.requests.at(-1).complete([{id: "late", type: "css", enabled: true, content: "body {}"}]);+ await untrusted;+ assert.equal(f.elements.size, 0);+});++test("CSS-only snippets never load JS dependencies and CSS updates survive dependency failure", async () => {+ const f = fixture();+ let dependencies = 0;+ const beforeJS = async () => { dependencies++; throw new Error("Lute failed"); };+ const css = {id: "style", type: "css", enabled: true, content: "body {color: red;}"};+ const onlyCSS = f.exports.renderSnippet(0, () => true, beforeJS);+ f.requests.at(-1).complete([css]);+ await onlyCSS;+ assert.equal(dependencies, 0);+ assert.equal(f.elements.get("snippetCSSstyle").textContent, css.content);+ const withJS = f.exports.renderSnippet(0, () => true, beforeJS);+ f.requests.at(-1).complete([{id: "script", type: "js", enabled: true, content: "run();"},+ {...css, content: "body {color: blue;}"}]);+ assert.equal(f.elements.get("snippetCSSstyle").textContent, "body {color: blue;}");+ await withJS;+ assert.equal(dependencies, 1);+ assert.equal(f.executed.length, 0);+ f.config.snippet.enabledCSS = false;+ const disabled = f.exports.renderSnippet(0, () => true, beforeJS);+ f.requests.at(-1).complete([css]);+ await disabled;+ assert.equal(f.elements.size, 0);+ assert.equal(dependencies, 1);+});++test("JS waits for its dependency and respects disposal while the dependency is pending", async () => {+ const f = fixture();+ let ready: () => void;+ let active = true;+ const render = f.exports.renderSnippet(0, () => active, () => new Promise<void>(resolve => { ready = resolve; }));+ f.requests.at(-1).complete([{id: "script", type: "js", enabled: true, content: "run();"}]);+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(f.executed.length, 0);+ active = false;+ ready();+ await render;+ assert.equal(f.executed.length, 0);+});diff --git a/app/src/config/util/snippets.ts b/app/src/config/util/snippets.tsindex c4d603fe9a..a520591ae7 100644--- a/app/src/config/util/snippets.ts+++ b/app/src/config/util/snippets.ts@@ -6,19 +6,41 @@ import {Constants} from "../../constants";import {refreshHeadingNumberMeasurements} from "../../util/assets";import {getExtensionScriptNonce, getHostCapabilities} from "../../util/hostCapabilities";-export const renderSnippet = (timeout = 0) => {- if (!getHostCapabilities().customAppearance) {+export const renderSnippet = (timeout = 0, isActive = () => true, beforeJS?: () => Promise<void>) => {+ if (!isActive() || !getHostCapabilities().customAppearance) {return Promise.resolve();}const abortController = timeout > 0 ? new AbortController() : undefined;const timeoutId = abortController ? window.setTimeout(() => {abortController.abort();}, timeout) : 0;+ let scriptsReady = Promise.resolve();return fetchPost("/api/snippet/getSnippet", {type: "all", enabled: 2}, (response) => {+ if (!isActive() || !getHostCapabilities().customAppearance) return;let cssChanged = false;+ const scripts: ISnippet[] = [];+ const appendScript = (item: ISnippet) => {+ if (!isActive() || !getHostCapabilities().customAppearance || !window.siyuan.config.snippet.enabledJS) return;+ const script = document.createElement("script");+ script.type = "text/javascript";+ const nonce = getExtensionScriptNonce();+ if (nonce) script.nonce = nonce;+ script.text = item.content;+ script.id = `snippetJS${item.id}`;+ document.head.appendChild(script);+ };+ const snippetIds = new Set(response.data.snippets.map((item: ISnippet) =>+ `snippet${item.type === "css" ? "CSS" : "JS"}${item.id}`));+ document.querySelectorAll('style[id^="snippetCSS"], script[id^="snippetJS"]').forEach(element => {+ if (!snippetIds.has(element.id)) {+ cssChanged ||= element.tagName === "STYLE";+ element.remove();+ }+ });response.data.snippets.forEach((item: ISnippet) => {+ if (!isActive()) return;const id = `snippet${item.type === "css" ? "CSS" : "JS"}${item.id}`;- let exitElement = document.getElementById(id) as HTMLScriptElement | HTMLStyleElement;+ const exitElement = document.getElementById(id) as HTMLScriptElement | HTMLStyleElement;if ((!window.siyuan.config.snippet.enabledCSS && item.type === "css") ||(!window.siyuan.config.snippet.enabledJS && item.type === "js")) {if (exitElement) {@@ -48,21 +70,22 @@ export const renderSnippet = (timeout = 0) => {document.head.appendChild(styleEl);cssChanged = true;} else if (item.type === "js") {- exitElement = document.createElement("script");- exitElement.type = "text/javascript";- const nonce = getExtensionScriptNonce();- if (nonce) {- exitElement.nonce = nonce;- }- exitElement.text = item.content;- exitElement.id = id;- document.head.appendChild(exitElement);+ if (beforeJS) scripts.push(item);+ else appendScript(item);}});if (cssChanged) {refreshHeadingNumberMeasurements();}- }, undefined, undefined, abortController?.signal).finally(() => {+ if (scripts.length) {+ // CSS 先独立生效,脚本依赖失败不阻塞样式更新或禁用。+ scriptsReady = Promise.resolve().then(async () => {+ if (!isActive() || !getHostCapabilities().customAppearance || !window.siyuan.config.snippet.enabledJS) return;+ await beforeJS();+ scripts.forEach(appendScript);+ }).catch(error => console.error("Could not initialize snippet scripts", error));+ }+ }, undefined, undefined, abortController?.signal).then(() => scriptsReady).finally(() => {window.clearTimeout(timeoutId);});};diff --git a/app/src/layout/Model.ts b/app/src/layout/Model.tsindex f338ea662b..06475a4f53 100644--- a/app/src/layout/Model.ts+++ b/app/src/layout/Model.ts@@ -14,6 +14,8 @@ interface IConnectOptions {export class Model {public ws: WebSocket;public reqId: number;+ private socketDisposed = false;+ private reconnectTimer: ReturnType<typeof setTimeout>;private mainMessageQueue: {data: string,callback: (data: IWebSocketData) => void@@ -42,24 +44,29 @@ export class Model {}public flushMainMessages() {+ if (this.socketDisposed) return;const messages = this.mainMessageQueue.splice(0);messages.forEach((message) => {+ if (this.socketDisposed) return;try {this.processWebSocketMessage(message.data, message.callback);} catch (error) {console.error("Failed to process queued WebSocket message:", error);}});- if (window.siyuan.isReady) {+ if (!this.socketDisposed && window.siyuan.isReady) {const {refreshSettingConfig}: typeof import("../config/setting/sync") = require("../config/setting/sync");void refreshSettingConfig();}}public connect(options: IConnectOptions) {+ if (this.socketDisposed) return;+ clearTimeout(this.reconnectTimer);const websocketURL = `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.host}/ws`;const ws = new WebSocket(`${websocketURL}?app=${Constants.SIYUAN_APPID}&id=${options.id}${options.type ? "&type=" + options.type : ""}`);ws.onopen = () => {+ if (this.socketDisposed || this.ws !== ws) return;if (options.type === "main" && window.siyuan.isReady) {const {reloadSettingsResetOnReconnect}: typeof import("../config/setting/reset") = require("../config/setting/reset");if (reloadSettingsResetOnReconnect()) return;@@ -85,7 +92,7 @@ export class Model {}};ws.onmessage = (event) => {- if (!options.msgCallback) {+ if (this.socketDisposed || this.ws !== ws || !options.msgCallback) {return;}if (options.type === "main" && !window.siyuan.isReady) {@@ -101,18 +108,20 @@ export class Model {}};ws.onclose = (ev) => {+ if (this.socketDisposed || this.ws !== ws) return;if (0 <= ev.reason.indexOf("unauthenticated")) {return;}if (0 > ev.reason.indexOf("close websocket")) {console.warn("WebSocket is closed. Reconnect will be attempted in 3 second.", ev);- setTimeout(() => {+ this.reconnectTimer = setTimeout(() => {this.connect(options);}, 3000);}};ws.onerror = (err: Event & { target: { url: string, readyState: number } }) => {+ if (this.socketDisposed || this.ws !== ws) return;if (err.target.url.endsWith("&type=main") && err.target.readyState === 3) {const {kernelError}: typeof import("../util/kernelFault") = require("../util/kernelFault");kernelError();@@ -126,7 +135,7 @@ export class Model {}public send(cmd: string, param: Record<string, unknown>, process = false) {- if (!this.ws ||+ if (this.socketDisposed || !this.ws ||this.ws.readyState === WebSocket.CLOSING ||this.ws.readyState === WebSocket.CLOSED) { // Inbox 无 WebSocket,关闭中的连接不能继续发送return;@@ -147,6 +156,16 @@ export class Model {}public destroy() {- // 子类按需释放模型持有的资源。+ if (this.socketDisposed) return;+ this.socketDisposed = true;+ clearTimeout(this.reconnectTimer);+ this.mainMessageQueue.length = 0;+ if (this.ws) {+ this.ws.onopen = null;+ this.ws.onmessage = null;+ this.ws.onclose = null;+ this.ws.onerror = null;+ this.ws.close();+ }}}diff --git a/app/src/layout/ModelLifecycle.test.ts b/app/src/layout/ModelLifecycle.test.tsnew file mode 100644index 0000000000..9fa9fbed6b--- /dev/null+++ b/app/src/layout/ModelLifecycle.test.ts@@ -0,0 +1,59 @@+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";++test("destroying a main Model cancels reconnects, queued messages and late socket callbacks", () => {+ const sockets: Socket[] = [];+ const timers = new Map<number, () => void>();+ const calls: string[] = [];+ class Socket {+ onopen: () => void;+ onclose: (event: {reason: string}) => void;+ onmessage: (event: {data: string}) => void;+ onerror: () => void;+ readyState = 1;+ constructor() { sockets.push(this); }+ close() { calls.push("close"); }+ send() { calls.push("send"); }+ }+ const exports = {} as {Model: new (options: unknown) => {+ connect: (options: unknown) => void; destroy: () => void; flushMainMessages: () => void; send: (cmd: string, data: unknown) => void;+ }};+ const window = {location: {protocol: "https:", host: "siyuan"}, siyuan: {isReady: false, config: {}}};+ runInNewContext(transpileModule(readFileSync("src/layout/Model.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText, {exports, window, WebSocket: Socket, document: {getElementById: (): HTMLElement | null => null}, console,+ setTimeout: (callback: () => void) => { timers.set(1, callback); return 1; },+ clearTimeout: (id: number) => timers.delete(id),+ require: () => ({Constants: {SIYUAN_APPID: "test"}, processMessage: (value: unknown) => value,+ refreshSettingConfig: () => calls.push("refresh")})});+ const model = new exports.Model({app: {}});+ const options = {id: "test", type: "main", callback: () => calls.push("open"), msgCallback: () => calls.push("message")};+ model.connect(options);+ const socket = sockets[0];+ const lateOpen = socket.onopen;+ const lateMessage = socket.onmessage;+ const lateClose = socket.onclose;+ socket.onmessage({data: '{"cmd":"test"}'});+ socket.onclose({reason: "network interrupted"});+ const reconnect = timers.get(1);+ assert.equal(timers.size, 1);+ model.destroy();+ model.destroy();+ assert.equal(timers.size, 0);+ reconnect();+ lateOpen();+ lateMessage({data: '{"cmd":"test"}'});+ lateClose({reason: "network interrupted"});+ window.siyuan.isReady = true;+ model.flushMainMessages();+ model.send("test", {});+ model.connect(options);+ assert.equal(sockets.length, 1);+ assert.deepEqual(calls, ["close"]);+ assert.equal(socket.onopen, null);+ assert.equal(socket.onmessage, null);+ assert.equal(socket.onerror, null);+});diff --git a/app/src/layout/util.ts b/app/src/layout/util.tsindex ad30c2d195..5bfe243517 100644--- a/app/src/layout/util.ts+++ b/app/src/layout/util.ts@@ -16,7 +16,7 @@ import {Search} from "../search";import {Dock} from "./dock";import {focusByRange} from "../protyle/util/selection";import {hideElements} from "../protyle/ui/hideElements";-import {fetchPost} from "../util/fetch";+import {fetchPost, fetchSyncPost} from "../util/fetch";import {hasClosestByClassName} from "../protyle/util/hasClosest";import {Constants} from "../constants";import {saveScroll} from "../protyle/scroll/saveScroll";@@ -46,6 +46,7 @@ import {applyDockEntryVisibility} from "../config/entryVisibility/runtime";import {MIN_HORIZONTAL_PANE_SIZE, MIN_VERTICAL_PANE_SIZE, panePercentages, resizePanePercentages} from "./resizePane";import {requestResponsiveDockLayout} from "./dock/responsive";import {stickyRow} from "../protyle/render/av/row";+import {flushSettingSaves, settingSaveFailures} from "../config/setting/pending";const isBuiltInCustomModel = (type: string) => {return type === "siyuan-card" || type === "siyuan-database-row";@@ -150,17 +151,71 @@ const dockToJSON = (dock: Dock) => {};};-export const resetLayout = () => {- if (window.siyuan.config.readonly) {- window.location.reload();- } else {- fetchPost("/api/system/setUILayout", {layout: {}}, () => {- window.siyuan.storage[Constants.LOCAL_FILEPOSITION] = {};- setStorageVal(Constants.LOCAL_FILEPOSITION, window.siyuan.storage[Constants.LOCAL_FILEPOSITION]);- window.siyuan.storage[Constants.LOCAL_DIALOGPOSITION] = {};- setStorageVal(Constants.LOCAL_DIALOGPOSITION, window.siyuan.storage[Constants.LOCAL_DIALOGPOSITION]);+let reloadingUI = false;++// 重载由持有布局的窗口执行,子窗口不能将自己的重载回调传给宿主。+export const reloadUI = async () => {+ const host = getSettingsWindowHost();+ if (reloadingUI) return;+ reloadingUI = true;+ let reloaded = false;+ try {+ const failures = settingSaveFailures();+ if (document.activeElement instanceof HTMLElement) document.activeElement.blur();+ await flushSettingSaves(failures);+ if (host) {+ await host.reload();+ return;+ }+ await exportLayout({errorExit: false, cb: () => {+ reloaded = true;window.location.reload();- });+ }});+ } catch (error) {+ console.error("Could not reload the interface", error);+ showMessage(window.siyuan.languages.settingsPendingSaveError, 6000, "error");+ } finally {+ if (!reloaded) reloadingUI = false;+ }+};++export const resetLayout = async () => {+ const host = getSettingsWindowHost();+ if (reloadingUI) return;+ if (!host && window.siyuan.config.readonly) {+ window.location.reload();+ return;+ }+ reloadingUI = true;+ let resume: () => void;+ try {+ const failures = settingSaveFailures();+ if (document.activeElement instanceof HTMLElement) document.activeElement.blur();+ await flushSettingSaves(failures);+ if (host) {+ try {+ await host.resetLayout();+ } finally {+ reloadingUI = false;+ }+ return;+ }+ resume = await suspendLayoutSaving();+ const response = await fetchSyncPost("/api/system/setUILayout", {layout: {}});+ if (response.code !== 0) throw new Error(response.msg);+ window.siyuan.storage[Constants.LOCAL_FILEPOSITION] = {};+ window.siyuan.storage[Constants.LOCAL_DIALOGPOSITION] = {};+ await Promise.all([+ setStorageVal(Constants.LOCAL_FILEPOSITION, {}),+ setStorageVal(Constants.LOCAL_DIALOGPOSITION, {}),+ ]);+ await flushSettingSaves(failures);+ window.location.reload();+ } catch (error) {+ resume?.();+ reloadingUI = false;+ console.error("Could not reset the layout", error);+ showMessage(window.siyuan.languages.settingsPendingSaveError, 6000, "error");}};@@ -287,8 +342,8 @@ export const exportLayout = async (options: {layout: layoutJSON,errorExit: options.errorExit // 后台不接受该参数,用于请求发生错误时退出程序};- fetchPost("/api/system/setUILayout", request, () => {- options.cb();+ await fetchPost("/api/system/setUILayout", request, (response) => {+ if (response.code === 0) options.cb();});}};diff --git a/app/src/protyle/util/addScript.ts b/app/src/protyle/util/addScript.tsindex 0845c21e36..c4e4e34d7d 100644--- a/app/src/protyle/util/addScript.ts+++ b/app/src/protyle/util/addScript.ts@@ -1,13 +1,18 @@-const pendingScripts = new Map<string, Promise<boolean>>();+const pendingScripts = new Map<string, {promise: Promise<boolean>; reloadOnFailure: boolean}>();-export const addScriptSync = async (path: string, id: string) => {+export const addScriptSync = async (path: string, id: string, options: {reloadOnFailure?: boolean} = {}) => {if (pendingScripts.has(id)) {- return pendingScripts.get(id);+ const pending = pendingScripts.get(id);+ if (options.reloadOnFailure === false) {+ pending.reloadOnFailure = false;+ }+ return pending.promise;}if (document.getElementById(id)) {return false;}- const pending = new Promise<boolean>((resolve) => {+ const pending = {promise: undefined as Promise<boolean>, reloadOnFailure: options.reloadOnFailure !== false};+ pending.promise = new Promise<boolean>((resolve) => {const scriptElement = document.createElement("script");scriptElement.type = "text/javascript";scriptElement.src = path;@@ -16,6 +21,11 @@ export const addScriptSync = async (path: string, id: string) => {scriptElement.onload = () => {pendingScripts.delete(id);if (id === "protyleLuteScript" && typeof Lute === "undefined") {+ if (!pending.reloadOnFailure) {+ scriptElement.remove();+ resolve(false);+ return;+ }// 鸿蒙系统上首次加载可能没有初始化 Lute,重新载入页面恢复编辑器。window.location.reload();}@@ -29,7 +39,7 @@ export const addScriptSync = async (path: string, id: string) => {document.head.appendChild(scriptElement);});pendingScripts.set(id, pending);- return pending;+ return pending.promise;};export const addScript = (path: string, id: string) => {diff --git a/app/src/protyle/util/lute.test.ts b/app/src/protyle/util/lute.test.tsnew file mode 100644index 0000000000..1daf3c952a--- /dev/null+++ b/app/src/protyle/util/lute.test.ts@@ -0,0 +1,74 @@+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 createLoader = () => {+ const scripts = new Map<string, any>();+ let reloads = 0;+ let loads = 0;+ const context = {+ exports: {} as Record<string, any>, Lute: undefined as unknown,+ window: {location: {reload: () => reloads++}},+ document: {+ getElementById: (id: string) => scripts.get(id),+ createElement: () => {+ const script = {id: "", remove: () => scripts.delete(script.id)};+ return script;+ },+ head: {appendChild: (script: {id: string}) => { loads++; scripts.set(script.id, script); }},+ },+ require: (() => ({})) as (name: string) => unknown,+ };+ const compile = (name: string) => transpileModule(readFileSync("src/protyle/util/" + name + ".ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText;+ runInNewContext(compile("addScript"), context);+ const loader = context.exports;+ context.exports = {};+ context.require = (name: string) => name === "./addScript" ? loader :+ {Constants: {PROTYLE_CDN: "/stage/protyle", SIYUAN_VERSION: "test"}};+ runInNewContext(compile("lute"), context);+ return {ensureLute: context.exports.ensureLute as (options?: {reloadOnFailure?: boolean}) => Promise<void>,+ scripts, context, reloads: () => reloads, loads: () => loads};+};++test("settings Lute failures never reload, remove the failed script, and permit retry", async () => {+ for (const failure of ["load", "error"]) {+ const fixture = createLoader();+ const first = fixture.ensureLute({reloadOnFailure: false});+ const repeated = fixture.ensureLute({reloadOnFailure: false});+ assert.equal(fixture.loads(), 1);+ fixture.scripts.get("protyleLuteScript")[failure === "load" ? "onload" : "onerror"]();+ const results = await Promise.allSettled([first, repeated]);+ assert.ok(results.every(result => result.status === "rejected"));+ assert.equal(fixture.reloads(), 0);+ assert.equal(fixture.scripts.size, 0);+ const retried = fixture.ensureLute({reloadOnFailure: false});+ fixture.context.Lute = {};+ fixture.scripts.get("protyleLuteScript").onload();+ await retried;+ await fixture.ensureLute({reloadOnFailure: false});+ assert.equal(fixture.loads(), 2);+ }+});++test("ordinary Lute loading retains the Harmony recovery behavior", async () => {+ const fixture = createLoader();+ const pending = fixture.ensureLute();+ fixture.scripts.get("protyleLuteScript").onload();+ await assert.rejects(pending, /Could not load Lute/);+ assert.equal(fixture.reloads(), 1);+});++test("a settings caller suppresses reload for an already pending shared Lute request", async () => {+ const fixture = createLoader();+ const first = fixture.ensureLute();+ const settings = fixture.ensureLute({reloadOnFailure: false});+ fixture.scripts.get("protyleLuteScript").onload();+ await Promise.allSettled([first, settings]);+ assert.equal(fixture.loads(), 1);+ assert.equal(fixture.reloads(), 0);+ assert.equal(fixture.scripts.size, 0);+});diff --git a/app/src/protyle/util/lute.ts b/app/src/protyle/util/lute.tsindex 2419b99733..1469204320 100644--- a/app/src/protyle/util/lute.ts+++ b/app/src/protyle/util/lute.ts@@ -2,11 +2,12 @@ import {Constants} from "../../constants";import {addScriptSync} from "./addScript";// 创建编辑器或执行依赖 Lute 的扩展脚本前,等待引擎加载完成。-export const ensureLute = async () => {+export const ensureLute = async (options: {reloadOnFailure?: boolean} = {}) => {if (typeof Lute !== "undefined") {return;}- await addScriptSync(`${Constants.PROTYLE_CDN}/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}`, "protyleLuteScript");+ await addScriptSync(`${Constants.PROTYLE_CDN}/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}`,+ "protyleLuteScript", options);if (typeof Lute === "undefined") {throw new Error("Could not load Lute");}diff --git a/app/src/util/assets.ts b/app/src/util/assets.tsindex e3b7c17c90..00424dd067 100644--- a/app/src/util/assets.ts+++ b/app/src/util/assets.ts@@ -7,7 +7,8 @@ import {getAllEditor, getAllModels} from "../layout/getAll";import {invalidateHeadingNumberMeasurements} from "../protyle/util/headingNumberCore";import {renderHeadingNumbers} from "../protyle/util/headingNumber";/// #if !MOBILE-import {exportLayout} from "../layout/util";+import {reloadUI} from "../layout/util";+import {closeSettingsWindow} from "../config/setting/windowContext";/// #endifimport {fetchPost} from "./fetch";import {@@ -324,12 +325,7 @@ export const initAssets = (keepLoading = false) => {!await unloadThemeScript()) {markAppearanceReloadPending();/// #if !MOBILE- exportLayout({- cb() {- window.location.reload();- },- errorExit: false,- });+ if (!closeSettingsWindow()) void reloadUI();/// #elsewindow.location.reload();/// #endifdiff --git a/app/src/util/processMessage.ts b/app/src/util/processMessage.tsindex 272568d518..850163f95a 100644--- a/app/src/util/processMessage.ts+++ b/app/src/util/processMessage.ts@@ -1,5 +1,6 @@/// #if !MOBILE-import {exportLayout} from "../layout/util";+import {reloadUI} from "../layout/util";+import {closeSettingsWindow} from "../config/setting/windowContext";/// #endifimport {hideMessage, showMessage} from "../dialog/message";import {setStorageVal} from "../protyle/util/compatibility";@@ -56,30 +57,23 @@ export const processMessage = (response: IWebSocketData) => {return false;}if ("reloadui" === response.cmd) {+ /// #if !MOBILE+ if (closeSettingsWindow()) return false;+ /// #endifif (response.data?.resetScroll) {window.siyuan.storage[Constants.LOCAL_FILEPOSITION] = {};setStorageVal(Constants.LOCAL_FILEPOSITION, window.siyuan.storage[Constants.LOCAL_FILEPOSITION], () => {/// #if MOBILEwindow.location.reload();/// #else- exportLayout({- cb() {- window.location.reload();- },- errorExit: false,- });+ void reloadUI();/// #endif});} else {/// #if MOBILEwindow.location.reload();/// #else- exportLayout({- cb() {- window.location.reload();- },- errorExit: false,- });+ void reloadUI();/// #endif}return false;diff --git a/app/tests/nativeSettingsOwner.test.js b/app/tests/nativeSettingsOwner.test.jsnew file mode 100644index 0000000000..02daac5b95--- /dev/null+++ b/app/tests/nativeSettingsOwner.test.js@@ -0,0 +1,262 @@+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 {ModuleKind, ScriptTarget, transpileModule} = require("typescript");++const code = transpileModule(readFileSync("src/config/setting/nativeWindow.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++const setup = () => {+ let sequence = 0;+ let nativeTask = false;+ const calls = [];+ const requests = [];+ const subscriptions = [];+ const events = new EventEmitter();+ const window = {+ siyuan: {storage: {}, languages: {config: "Settings"}},+ addEventListener: (...args) => events.on(...args),+ removeEventListener: (...args) => events.removeListener(...args),+ open: (...args) => { calls.push(["open", ...args]); return {}; },+ };+ const ipcRenderer = Object.assign(new EventEmitter(), {+ send: (...args) => calls.push(args),+ invoke: (channel, data) => {+ calls.push(["prepare", data.token]);+ return new Promise((resolve, reject) => requests.push({channel, data, resolve, reject}));+ },+ });+ const record = name => (...args) => { calls.push([name, ...args]); };+ const modules = {+ electron: {ipcRenderer},+ "../../util/genID": {genUUID: () => "token-" + (++sequence)},+ "../../protyle/util/compatibility": {setStorageVal: record("storage")},+ "../../layout/util": {exportLayout: record("export"), reloadUI: record("reload"), resetLayout: record("reset")},+ "../../dialog/processSystem": {exitSiYuan: record("exit")},+ "../../plugin/globalState": {+ subscribeGlobalPluginState: (_app, callback) => {+ const subscription = {callback, disposed: 0, throwOnDispose: false};+ subscriptions.push(subscription);+ callback({pending: false});+ return () => {+ subscription.disposed++;+ if (subscription.throwOnDispose) throw new Error("unsubscribe failed");+ };+ },+ applyPluginReload: record("applyPluginReload"),+ },+ "../../plugin/loader": {loadPlugin: record("loadPlugin"), unloadPlugin: record("unloadPlugin")},+ "../../boot/globalEvent/globalShortcut": {+ sendGlobalShortcut: record("restore"), sendUnregisterGlobalShortcut: record("suspend"),+ },+ "../../constants": {Constants: {SIYUAN_CMD: "siyuan-cmd"}},+ "../../plugin": {hasPluginSetting: () => true},+ "../../util/processTitle": {getWorkspaceName: () => "Workspace"},+ "../entryVisibility/dockOrder": {getDockEntryOrderSnapshot: () => ({left: ["outline"]})},+ "./taskBlocker": {hasNativeSettingTasks: () => nativeTask},+ };+ const context = {exports: {}, window, console: {error: record("error")}, require: name => {+ assert.ok(modules[name], name);+ return modules[name];+ }};+ runInNewContext(code, context);+ const app = {plugins: []};+ const plugin = name => ({name, isOpen: () => true, mount: record("mount"), closed: record("closed")});+ const prepare = (index = requests.length - 1, create = true) => {+ const request = requests[index];+ request.resolve({create, token: request.data.token, url: "/settings?token=" + request.data.token, frameName: request.data.token});+ };+ const host = (index = requests.length - 1) => {+ let value;+ events.emit("siyuan-settings-host-" + requests[index].data.token, {detail: candidate => { value = candidate; }});+ return value;+ };+ return {native: context.exports, app, plugin, prepare, host, calls, requests, events, window, ipcRenderer, subscriptions,+ setTask: active => { nativeTask = active; }};+};++test("host cleanup removes the token before throwing plugin callbacks and disposes every subscription", async () => {+ const fixture = setup();+ const {native, app, prepare, host, requests, calls, ipcRenderer, subscriptions, plugin} = fixture;+ const settings = plugin("Plugin");+ settings.closed = () => {+ calls.push(["closed"]);+ assert.equal(host(), undefined);+ native.closeNativeSettings("plugin-example");+ throw new Error("plugin destroy failed");+ };+ const opened = native.openNativeSettings(app, {}, settings, "plugin-example");+ prepare();+ await opened;+ const owner = host();+ let notifications = 0;+ owner.subscribePlugins(() => notifications++);+ owner.subscribePlugins(() => notifications++);+ subscriptions[0].throwOnDispose = true;+ owner.suspendShortcuts();+ ipcRenderer.emit("siyuan-settings-closed", {}, requests[0].data.token, false);+ assert.equal(owner.isActive(), false);+ assert.deepEqual(subscriptions.map(item => item.disposed), [1, 1]);+ subscriptions.forEach(item => item.callback({pending: true}));+ assert.equal(notifications, 2);+ assert.equal(calls.filter(item => item[0] === "restore").length, 1);+ assert.equal(calls.filter(item => item[0] === "closed").length, 1);+ ipcRenderer.emit("siyuan-settings-closed", {}, requests[0].data.token, false);+ owner.dispose();+ assert.equal(calls.filter(item => item[0] === "closed").length, 1);+ assert.throws(() => owner.reload(), /no longer available/);+ assert.throws(() => owner.plugin.mount(() => {}), /no longer available/);+ await assert.rejects(owner.loadPlugin({}), /no longer available/);+});++test("owner unload disposes all hosts without restoring stale shortcuts even when a plugin throws", async () => {+ const {native, app, plugin, prepare, host, events, calls} = setup();+ const first = plugin("First");+ first.closed = () => { throw new Error("first failed"); };+ const openFirst = native.openNativeSettings(app, {}, first, "plugin-first");+ prepare();+ await openFirst;+ const firstHost = host();+ firstHost.suspendShortcuts();+ const openSecond = native.openNativeSettings(app, {}, plugin("Second"), "plugin-second");+ prepare();+ await openSecond;+ const secondHost = host();+ secondHost.suspendShortcuts();+ events.emit("unload");+ assert.equal(firstHost.isActive(), false);+ assert.equal(secondHost.isActive(), false);+ assert.equal(calls.filter(item => item[0] === "closed").length, 1);+ assert.equal(calls.filter(item => item[0] === "restore").length, 0);+});++test("pending close and rapid reopen cancel only the captured old token", async () => {+ const {native, app, plugin, prepare, host, calls} = setup();+ const first = native.openNativeSettings(app, {}, plugin("First"), "plugin-example");+ native.closeNativeSettings("plugin-example");+ const second = native.openNativeSettings(app, {}, plugin("Second"), "plugin-example");+ prepare(1);+ await second;+ const activeHost = host(1);+ prepare(0);+ await first;+ assert.equal(activeHost.isActive(), true);+ assert.equal(host(0), undefined);+ assert.equal(calls.filter(item => item[0] === "open").length, 1);+ assert.deepEqual(calls.filter(item => item[0] === "siyuan-settings-close").map(item => item[1].token), ["token-1", "token-1"]);+ assert.equal(calls.filter(item => item[0] === "closed").length, 1);+});++test("reusing a singleton does not close the live plugin session", async () => {+ const {native, app, plugin, prepare, host, calls} = setup();+ const settings = plugin("Plugin");+ const first = native.openNativeSettings(app, {}, settings, "plugin-example");+ prepare();+ await first;+ const activeHost = host();+ const second = native.openNativeSettings(app, {}, settings, "plugin-example");+ prepare(1, false);+ await second;+ assert.equal(activeHost.isActive(), true);+ assert.equal(calls.some(item => item[0] === "closed"), false);+ assert.equal(calls.filter(item => item[0] === "open").length, 1);+});++test("plugin close callbacks may reopen immediately after cancellation is sent", async () => {+ const {native, app, plugin, prepare, host, calls} = setup();+ let reopened;+ const settings = plugin("Plugin");+ settings.closed = () => {+ assert.equal(host(0), undefined);+ reopened = native.openNativeSettings(app, {}, plugin("Reopened"), "plugin-example");+ };+ const opened = native.openNativeSettings(app, {}, settings, "plugin-example");+ prepare();+ await opened;+ native.closeNativeSettings("plugin-example");+ const cancellation = calls.findIndex(item => item[0] === "siyuan-settings-close");+ const replacement = calls.findIndex(item => item[0] === "prepare" && item[1] === "token-2");+ assert.ok(cancellation < replacement);+ prepare(1);+ await reopened;+ assert.equal(host(1).isActive(), true);+});++for (const failure of ["blocked", "throws", "prepare"]) {+ test(`failed ${failure} popup boot disposes the plugin and cancels its reservation`, async () => {+ const {native, app, plugin, prepare, requests, host, calls, window} = setup();+ window.open = () => {+ if (failure === "throws") throw new Error("window.open failed");+ return null;+ };+ const opened = native.openNativeSettings(app, {}, plugin("Plugin"), "plugin-example");+ if (failure === "prepare") requests[0].reject(new Error("prepare failed"));+ else prepare();+ await assert.rejects(opened, /failed|Could not open/);+ assert.equal(host(), undefined);+ assert.equal(calls.filter(item => item[0] === "closed").length, 1);+ assert.equal(calls.find(item => item[0] === "siyuan-settings-close")[1].token, "token-1");+ });+}++test("owner invalidation while prepare is pending rejects the old session without opening a child", async () => {+ const {native, app, plugin, prepare, ipcRenderer, calls, requests} = setup();+ const opened = native.openNativeSettings(app, {}, plugin("Plugin"), "plugin-example");+ ipcRenderer.emit("siyuan-settings-closed", {}, requests[0].data.token, true);+ prepare();+ await opened;+ assert.equal(calls.some(item => item[0] === "open"), false);+ assert.equal(calls.some(item => item[0] === "restore"), false);+ assert.equal(calls.filter(item => item[0] === "closed").length, 1);+ await native.openNativeSettings(app);+ assert.equal(requests.length, 1);+});++test("closing one host preserves another host's shortcut suspension and native reset blocks geometry", async () => {+ const {native, app, plugin, prepare, host, calls, ipcRenderer, setTask} = setup();+ for (const key of ["plugin-first", "plugin-second"]) {+ const opened = native.openNativeSettings(app, {}, plugin(key), key);+ prepare();+ await opened;+ host().suspendShortcuts();+ }+ native.closeNativeSettings("plugin-first");+ assert.equal(calls.some(item => item[0] === "restore"), false);+ setTask(true);+ native.closeNativeSettings("plugin-second");+ ipcRenderer.emit("siyuan-settings-geometry", {}, {width: 1000});+ assert.equal(calls.some(item => item[0] === "restore"), false);+ assert.equal(calls.some(item => item[0] === "storage"), false);+ setTask(false);+ ipcRenderer.emit("siyuan-settings-geometry", {}, {width: 900});+ assert.equal(calls.filter(item => item[0] === "storage").length, 1);+});++test("a subscription created during its immediate close notification is still disposed exactly once", async () => {+ const {native, app, prepare, host, subscriptions} = setup();+ const opened = native.openNativeSettings(app);+ prepare();+ await opened;+ const owner = host();+ const remove = owner.subscribePlugins(() => owner.dispose());+ remove();+ assert.equal(owner.isActive(), false);+ assert.equal(subscriptions[0].disposed, 1);+});++test("a plugin dialog finishing asynchronously cannot focus an invalidated owner", async () => {+ const {native, app, prepare, host, ipcRenderer, requests, calls} = setup();+ let finish;+ app.plugins.push({name: "legacy", openSetting: () => new Promise(resolve => { finish = resolve; })});+ const opened = native.openNativeSettings(app);+ prepare();+ await opened;+ const dialog = host().openPluginSetting("legacy");+ ipcRenderer.emit("siyuan-settings-closed", {}, requests[0].data.token, true);+ finish();+ await dialog;+ assert.equal(calls.some(item => item[0] === "siyuan-cmd"), false);+});diff --git a/app/tests/settingsBoot.test.js b/app/tests/settingsBoot.test.jsindex b92d90b682..0de09c17fe 100644--- a/app/tests/settingsBoot.test.js+++ b/app/tests/settingsBoot.test.js@@ -6,7 +6,7 @@ const {ModuleKind, ScriptTarget, transpileModule} = require("typescript");const createBoot = (plugin = false, failed = "") => {const source = readFileSync("src/config/setting/window.ts", "utf8");- const code = transpileModule(source.slice(0, source.indexOf("void initialize().catch")) + "\nexport {initialize};", {+ const code = transpileModule(source.slice(0, source.indexOf("void startSettingsWindow(")) + "\nexport {initialize};", {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},}).outputText;const pending = new Map();@@ -17,25 +17,30 @@ const createBoot = (plugin = false, failed = "") => {calls.push(name);return new Promise(resolve => pending.set(name, resolve));};- const host = {app: {}, plugin: plugin ? {name: "Plugin", mount: create => {+ let active = true;+ const events = new Map();+ const host = {app: {}, isActive: () => active, dispose: () => { active = false; calls.push("dispose"); },+ plugin: plugin ? {name: "Plugin", mount: create => {assert.equal(luteLoaded, true);create({items: []});}} : undefined};const window = {opener: {location: {origin: "http://localhost"}, dispatchEvent: event => event.detail(host)},- addEventListener() {},+ addEventListener: (name, callback) => events.set(name, callback),+ close: () => calls.push("close"),DOMPurify: undefined,};const constants = {PROTYLE_CDN: "/stage/protyle", SIYUAN_VERSION: "test", LOCAL_ZOOM: "zoom", SIZE_ZOOM: []};const modules = {"electron": {ipcRenderer: {on: (name, callback) => {if (name === "siyuan-settings-command") command = callback;- }, send: name => calls.push(name), invoke: async () => false}, webFrame: {setZoomFactor() {}}},+ }, removeListener() {}, send: name => calls.push(name), invoke: async () => false}, webFrame: {setZoomFactor() {}}},"../../constants": {Constants: constants},"../../layout/Model": {Model: class {ws = {close() {}};connect() {}flushMainMessages() {}+ destroy() { calls.push("disconnect"); }}},"../../menus": {Menus: class {}},"../../util/genID": {genUUID: () => "id"},@@ -75,6 +80,9 @@ 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() {},+ })},"../../plugin/Setting": {Setting: class {addItem() {} open() { calls.push("render"); }}},};const context = {exports: {}, window, document: {body: {classList: {toggle() {}}}, addEventListener() {}},@@ -84,7 +92,8 @@ const createBoot = (plugin = false, failed = "") => {require: name => modules[name] || new Proxy({}, {get: () => () => {}})};window.location = context.location;runInNewContext(code, context);- return {initialize: context.exports.initialize, calls, pending, command: next => command({}, next)};+ return {initialize: context.exports.initialize, calls, pending, command: next => command({}, next),+ unload: () => events.get("unload")(), deactivate: () => { active = false; }};};for (const plugin of [false, true]) {@@ -102,6 +111,21 @@ for (const plugin of [false, true]) {});}+for (const dispose of ["unload", "deactivate"]) {+ test(`settings ignore dependency completions after ${dispose}`, async () => {+ const boot = createBoot();+ const initialized = boot.initialize();+ await new Promise(resolve => setImmediate(resolve));+ boot[dispose]();+ for (const complete of boot.pending.values()) complete();+ await initialized;+ assert.equal(boot.calls.includes("render"), false);+ assert.equal(boot.calls.includes("siyuan-settings-ready"), false);+ assert.equal(boot.calls.filter(call => call === "disconnect").length, 1);+ assert.equal(boot.calls.filter(call => call === "dispose").length, 1);+ });+}+test("opening directly into assets waits for its preview before showing settings", async () => {const boot = createBoot();const initialized = boot.initialize();diff --git a/app/tests/settingsNotifications.test.js b/app/tests/settingsNotifications.test.jsindex 9d1197a4d2..eea12d2fb5 100644--- a/app/tests/settingsNotifications.test.js+++ b/app/tests/settingsNotifications.test.js@@ -10,11 +10,14 @@ const compile = source => ts.transpileModule(source, {}).outputText;const storageCommands = ["setLocalStorageVal", "setLocalStorageVals", "removeLocalStorageVal", "removeLocalStorageVals"];-for (const file of ["src/index.ts", "src/window/index.ts", "src/mobile/util/onMessage.ts", "src/config/setting/window.ts"]) {+for (const file of ["src/index.ts", "src/window/index.ts", "src/mobile/util/onMessage.ts", "src/config/setting/windowRuntime.ts"]) {test(`storage pushes notify the active streaming renderer without losing platform hooks (${file})`, () => {const source = sourceFile(file);const clauses = [];+ let storageChanged = "";const visit = node => {+ if (ts.isVariableStatement(node) && node.declarationList.declarations.some(item =>+ item.name.getText(source) === "onStorageChanged")) storageChanged = node.getText(source);if (ts.isCaseClause(node) && ts.isStringLiteral(node.expression) && storageCommands.includes(node.expression.text)) {clauses.push(node.getText(source));}@@ -48,7 +51,8 @@ for (const file of ["src/index.ts", "src/window/index.ts", "src/mobile/util/onMe});const platformCalls = [];const receiver = {};- runInNewContext(compile(`export const receive = data => {switch(data.cmd){${clauses.join("\n")}}};`), {+ runInNewContext(compile(`let zoomRevision = 0; const applyZoom = () => {}; ${storageChanged}+export const receive = data => {switch(data.cmd){${clauses.join("\n")}}};`), {exports: receiver, window, ...preference,onWindowWorkspaceStorageChanged: key => platformCalls.push(key),MOBILE_BARS_CONFIG_KEY: "mobile-bars", Constants: {LOCAL_MOBILE_BOTTOM_BAR: "mobile-bottom", LOCAL_MOBILE_SIDE_PANEL: "mobile-side"},diff --git a/app/tests/settingsWindow.test.js b/app/tests/settingsWindow.test.jsindex 46b4f2e85b..e6c45f099c 100644--- a/app/tests/settingsWindow.test.js+++ b/app/tests/settingsWindow.test.js@@ -18,7 +18,7 @@ const rendererModules = (sources) => {languages: {cancel: "Cancel", save: "Save", config: "Settings", workspace: "Workspace",min: "Minimize", max: "Maximize", restore: "Restore", close: "Close"},menus: {menu: {element: document.createElement("div"), remove() {}}}, ws: {app: {plugins: [], appId: "test"}}};- const genUUID = () => "test-" + (++sequence);+ const genUUID = () => "test-" + Date.now() + "-" + (++sequence);const {Dialog} = loadRendererModule(sources.dialog, {"../util/genID": {genUUID}, "../util/zIndex": {isAbove: () => false}, "./moveResize": {moveResize() {}},"../util/functions": {isMobile: () => false}, "../protyle/util/compatibility": {isNotCtrl: () => true},@@ -120,6 +120,8 @@ const runCases = async (sources) => {"../../constants": {Constants: {SIYUAN_CMD: "siyuan-cmd"}},"../../plugin": pluginSettings,"../../util/processTitle": titles,+ "../entryVisibility/dockOrder": {getDockEntryOrderSnapshot: () => ({})},+ "./taskBlocker": {hasNativeSettingTasks: () => false},});const {Setting} = loadRendererModule(sources.setting, {"../util/functions": {isMobile: () => false, getFrontend: () => "desktop"}, "../dialog": {Dialog},@@ -440,7 +442,23 @@ if (process.versions.electron && process.type === "browser") {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)})`);+ const runRendererCases = () => owner.webContents.executeJavaScript(`const loadRendererModule = ${loadRendererModule.toString()}; const rendererModules = ${rendererModules.toString()}; (${runCases.toString()})(${JSON.stringify(sources)})`);+ await runRendererCases();+ const previousTokens = new Set([...children].map(child => new URL(child.webContents.getURL()).searchParams.get("settingsWindowToken")));+ assert.ok(previousTokens.size > 0);+ const reloaded = new Promise(resolve => owner.webContents.once("did-finish-load", resolve));+ const closedForReload = [...children].map(child => new Promise(resolve => child.once("closed", resolve)));+ owner.reload();+ await Promise.all([reloaded, ...closedForReload]);+ await new Promise(resolve => setTimeout(resolve, 100));+ assert.equal(children.size, 0, "owner reload closes settings without restoring them");+ commands.length = 0;+ ready = 0;+ await runRendererCases();+ assert.ok(children.size > 0, "settings can be manually reopened after owner reload");+ for (const child of children) {+ assert.equal(previousTokens.has(new URL(child.webContents.getURL()).searchParams.get("settingsWindowToken")), false);+ }const closed = [...children].map(child => new Promise(resolve => child.once("closed", resolve)));owner.destroy();await Promise.all(closed);