Skip to content

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

:art: Improve plugin lifecycle sequencing and unload/uninstall semantics https://github.com/siyuan-note/siyuan/issues/18979

Daniel519b0e82eded
diff --git a/app/electron/main.js b/app/electron/main.js
index 46629ad931..79c699ac04 100644
--- a/app/electron/main.js
+++ b/app/electron/main.js
@@ -71,6 +71,17 @@ let bootWindow;
let latestActiveWindow;
let firstOpen = false;
let workspaces = []; // workspaceDir, id, port, webContentsId, browserWindow, tray, hideShortcut
+
+const getGlobalShortcutWorkspace = (fallbackWorkspace) => {
+ const focusedWorkspace = workspaces.find(item => item.browserWindow &&
+ !item.browserWindow.isDestroyed() && item.browserWindow.isFocused());
+ if (focusedWorkspace) {
+ return focusedWorkspace;
+ }
+ if (fallbackWorkspace?.browserWindow && !fallbackWorkspace.browserWindow.isDestroyed()) {
+ return fallbackWorkspace;
+ }
+};
const initEventId = [];
const appMenuByWorkspaceDir = new Map();
const appMenuWorkspaceByWebContentsId = new Map();
@@ -2187,23 +2198,34 @@ app.whenReady().then(() => {
case "toggleDevTools":
event.sender.toggleDevTools();
break;
- case "unregisterGlobalShortcut":
+ case "unregisterGlobalShortcut": {
+ const workspaceItem = workspaces.find(item => item.webContentsId === event.sender.id);
+ if (!workspaceItem) {
+ break;
+ }
if (data.accelerator) {
globalShortcut.unregister(hotKey2Electron(data.accelerator));
}
break;
- case "registerGlobalShortcut":
+ }
+ case "registerGlobalShortcut": {
+ const workspaceItem = workspaces.find(item => item.webContentsId === event.sender.id);
+ if (!workspaceItem) {
+ break;
+ }
if (data.accelerator) {
globalShortcut.unregister(hotKey2Electron(data.accelerator));
globalShortcut.register(hotKey2Electron(data.accelerator), () => {
- BrowserWindow.getAllWindows().forEach(itemB => {
- itemB.webContents.send("siyuan-hotkey", {
+ const targetWorkspace = getGlobalShortcutWorkspace(workspaceItem);
+ if (targetWorkspace) {
+ targetWorkspace.browserWindow.webContents.send("siyuan-hotkey", {
hotkey: data.accelerator
});
- });
+ }
});
}
break;
+ }
case "setTrafficLightPosition":
if (!currentWindow || !currentWindow.setWindowButtonPosition) {
return;
@@ -2464,12 +2486,12 @@ app.whenReady().then(() => {
if (!data.hotkeys || data.hotkeys.length === 0) {
return;
}
- workspaces.find(workspaceItem => {
- if (event.sender.id === workspaceItem.browserWindow.webContents.id) {
- workspaceItem.hotkeys = data.hotkeys;
- return true;
- }
- });
+ const ownerWorkspace = workspaces.find(workspaceItem =>
+ event.sender.id === workspaceItem.browserWindow.webContents.id);
+ if (!ownerWorkspace) {
+ return;
+ }
+ ownerWorkspace.hotkeys = data.hotkeys;
data.hotkeys.forEach((item, index) => {
const shortcut = hotKey2Electron(item);
if (!shortcut) {
@@ -2507,11 +2529,12 @@ app.whenReady().then(() => {
});
} else {
globalShortcut.register(shortcut, () => {
- BrowserWindow.getAllWindows().forEach(itemB => {
- itemB.webContents.send("siyuan-hotkey", {
+ const targetWorkspace = getGlobalShortcutWorkspace(ownerWorkspace);
+ if (targetWorkspace) {
+ targetWorkspace.browserWindow.webContents.send("siyuan-hotkey", {
hotkey: item
});
- });
+ }
});
}
});
diff --git a/app/src/boot/globalEvent/command/panel.ts b/app/src/boot/globalEvent/command/panel.ts
index 30eb70fcae..bb6ce118df 100644
--- a/app/src/boot/globalEvent/command/panel.ts
+++ b/app/src/boot/globalEvent/command/panel.ts
@@ -2,7 +2,7 @@ import {Dialog} from "../../../dialog";
import type {App} from "../../../index";
import {upDownHint} from "../../../util/upDownHint";
import {updateHotkeyTip} from "../../../protyle/util/compatibility";
-import {isMobile} from "../../../util/functions";
+import {isMobile, isWindow} from "../../../util/functions";
import {Constants} from "../../../constants";
/// #if MOBILE
import {getCurrentEditor} from "../../../mobile/editor";
@@ -103,7 +103,7 @@ export const commandPanel = (app: App) => {
liElement.addEventListener("click", (event) => {
if (command.callback) {
command.callback();
- } else if (command.globalCallback) {
+ } else if (command.globalCallback && !isWindow()) {
command.globalCallback();
}
dialog.destroy();
diff --git a/app/src/boot/globalEvent/keydown.ts b/app/src/boot/globalEvent/keydown.ts
index 911594c16b..69d33f7e13 100644
--- a/app/src/boot/globalEvent/keydown.ts
+++ b/app/src/boot/globalEvent/keydown.ts
@@ -1856,6 +1856,9 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {
export const sendGlobalShortcut = (app: App) => {
/// #if !BROWSER
+ if (isWindow()) {
+ return;
+ }
const hotkeys = [clearDisallowedTextInputHotkey(window.siyuan.config.keymap.general.toggleWin.custom)];
app.plugins.forEach(plugin => {
plugin.commands.forEach(command => {
@@ -1877,6 +1880,9 @@ export const sendGlobalShortcut = (app: App) => {
export const sendUnregisterGlobalShortcut = (app: App) => {
/// #if !BROWSER
+ if (isWindow()) {
+ return;
+ }
ipcRenderer.send(Constants.SIYUAN_CMD, {
cmd: "unregisterGlobalShortcut",
accelerator: window.siyuan.config.keymap.general.toggleWin.custom
diff --git a/app/src/boot/onGetConfig.ts b/app/src/boot/onGetConfig.ts
index 476665efe4..7c2ff77121 100644
--- a/app/src/boot/onGetConfig.ts
+++ b/app/src/boot/onGetConfig.ts
@@ -36,6 +36,7 @@ import {processSiYuanUri} from "../util/uri";
import {getAllEditor} from "../layout/getAll";
import {openDesktopOnboarding} from "../onboarding";
import {ensureUILayout} from "../util/ensureUILayout";
+import {dispatchPluginGlobalShortcut} from "../plugin/globalShortcut";
export const onGetConfig = (isStart: boolean, app: App) => {
correctHotkey(app);
@@ -206,19 +207,9 @@ export const initWindow = async (app: App) => {
onWindowsMsg(ipcData);
});
ipcRenderer.on(Constants.SIYUAN_HOTKEY, (e, data) => {
- let matchCommand = false;
- app.plugins.find(item => {
- item.commands.find(command => {
- if (command.globalCallback && data.hotkey === command.customHotkey) {
- matchCommand = true;
- command.globalCallback();
- return true;
- }
- });
- if (matchCommand) {
- return true;
- }
- });
+ if (!isWindow()) {
+ dispatchPluginGlobalShortcut(app.plugins, data.hotkey);
+ }
});
ipcRenderer.on(Constants.SIYUAN_EXPORT_PDF, async (e, ipcData) => {
const msgId = showMessage(window.siyuan.languages.exporting, -1);
diff --git a/app/src/config/bazaar.ts b/app/src/config/bazaar.ts
index 0f4db7443d..bbcbe5faa2 100644
--- a/app/src/config/bazaar.ts
+++ b/app/src/config/bazaar.ts
@@ -16,8 +16,7 @@ import {Plugin} from "../plugin";
import type {App} from "../index";
import {escapeAttr, escapeHtml} from "../util/escape";
import {formatCount} from "../util/number";
-import {uninstall} from "../plugin/uninstall";
-import {afterLoadPlugin, loadPlugin, loadPlugins} from "../plugin/loader";
+import {loadPlugin, loadPlugins, unloadPlugin} from "../plugin/loader";
import {useShell} from "../util/pathName";
import {switchSettingPanelSubTab} from "./setting/mount";
import {isThemeFrontendSupported} from "../util/themeCompatibility";
@@ -2115,8 +2114,7 @@ type="checkbox">
callback();
};
if (!enabled) {
- uninstall(app, item.name, true);
- finish();
+ unloadPlugin(app, item.name).then(finish);
return;
}
if (window.siyuan.config.bazaar.petalDisabled) {
@@ -2414,13 +2412,18 @@ type="checkbox">
fetchPost("/api/setting/setBazaar", {
...window.siyuan.config.bazaar,
trust: true,
+ app: Constants.SIYUAN_APPID,
}, (response) => {
window.siyuan.config.bazaar = response.data;
- if (!bazaar._isMountCurrent(mount)) {
- return;
- }
- bazaar.element.innerHTML = bazaar.genHTML();
- bazaar.bindEvent(app);
+ void loadPlugins(app, null, false).then(() => {
+ if (!bazaar._isMountCurrent(mount)) {
+ return;
+ }
+ bazaar.element.innerHTML = bazaar.genHTML();
+ bazaar.bindEvent(app);
+ }).catch(error => {
+ console.error(error);
+ });
});
});
return;
@@ -2743,40 +2746,41 @@ type="checkbox">
} else if (type === "plugins-enable") {
if (!target.getAttribute("disabled")) {
target.setAttribute("disabled", "disabled");
- const pluginCards = mount.element.querySelectorAll(
- "#configBazaarDownloaded .b3-card[data-name]"
- ) as NodeListOf<HTMLElement>;
- const pluginNames = Array.from(pluginCards).map((item) => item.dataset.name)
- .filter((name): name is string => Boolean(name));
+ const pluginNames = app.plugins.map(item => item.name);
window.siyuan.config.bazaar.petalDisabled = !(target as HTMLInputElement).checked;
- fetchPost("/api/setting/setBazaar", window.siyuan.config.bazaar, () => {
- if (bazaar._isMountCurrent(mount)) {
- target.removeAttribute("disabled");
- target.setAttribute("aria-label", window.siyuan.languages[
- window.siyuan.config.bazaar.petalDisabled ? "enable" : "disableAll"
- ]);
- }
- if (window.siyuan.config.bazaar.petalDisabled) {
+ fetchPost("/api/setting/setBazaar", {
+ ...window.siyuan.config.bazaar,
+ app: Constants.SIYUAN_APPID,
+ }, () => {
+ const finish = () => {
if (bazaar._isMountCurrent(mount)) {
- mount.element.querySelectorAll("#configBazaarDownloaded .b3-card").forEach((item: HTMLElement) => {
- item.querySelector('[data-type="setting"]')?.classList.add("fn__none");
- });
+ target.removeAttribute("disabled");
+ target.setAttribute("aria-label", window.siyuan.languages[
+ window.siyuan.config.bazaar.petalDisabled ? "enable" : "disableAll"
+ ]);
}
- pluginNames.forEach((pluginName) => {
- uninstall(app, pluginName, true);
- });
+ };
+ if (window.siyuan.config.bazaar.petalDisabled) {
+ void Promise.all(pluginNames.map((pluginName) => unloadPlugin(app, pluginName))).then(() => {
+ if (bazaar._isMountCurrent(mount)) {
+ mount.element.querySelectorAll("#configBazaarDownloaded .b3-card").forEach((item: HTMLElement) => {
+ item.querySelector('[data-type="setting"]')?.classList.add("fn__none");
+ });
+ }
+ }).catch(error => {
+ console.error(error);
+ }).finally(finish);
} else {
- loadPlugins(app, null, false).then(() => {
- app.plugins.forEach(item => {
- afterLoadPlugin(item);
- });
+ void loadPlugins(app, null, false).then(() => {
if (bazaar._isMountCurrent(mount)) {
this._genMyHTML("plugins", app, false);
}
- });
- /// #if !MOBILE
- saveLayout();
- /// #endif
+ /// #if !MOBILE
+ saveLayout();
+ /// #endif
+ }).catch(error => {
+ console.error(error);
+ }).finally(finish);
}
});
}
diff --git a/app/src/config/tabs/keymapUi.ts b/app/src/config/tabs/keymapUi.ts
index 506ad331b8..7189fa5fcc 100644
--- a/app/src/config/tabs/keymapUi.ts
+++ b/app/src/config/tabs/keymapUi.ts
@@ -15,6 +15,7 @@ import {normalizeSearchText} from "../search/normalize";
import {genButtonRowHtml, genConfigGroup} from "../render/render";
import type {Plugin} from "../../plugin";
import {isDisallowedTextInputHotkey, isReservedKeymap} from "../../util/hotKeyPolicy";
+import {isWindow} from "../../util/functions";
const keymapToolbarSearchStrings = (): string[] => [
window.siyuan.languages.keymapTip,
window.siyuan.languages.keymapTip2,
@@ -59,7 +60,8 @@ const bindKeymapToolbar = (root: HTMLElement) => {
cmd: "writeLog",
msg: "user reset keymap",
});
- if (window.siyuan.config.keymap.general.toggleWin.default !== window.siyuan.config.keymap.general.toggleWin.custom) {
+ if (!isWindow() && window.siyuan.config.keymap.general.toggleWin.default !==
+ window.siyuan.config.keymap.general.toggleWin.custom) {
ipcRenderer.send(Constants.SIYUAN_CMD, {
cmd: "unregisterGlobalShortcut",
accelerator: window.siyuan.config.keymap.general.toggleWin.custom,
@@ -644,7 +646,7 @@ const setKeymapFromDom = (root: HTMLElement) => {
return;
}
/// #if !BROWSER
- if (command.globalCallback && command.customHotkey && command.customHotkey !== newHotkey) {
+ if (!isWindow() && command.globalCallback && command.customHotkey && command.customHotkey !== newHotkey) {
ipcRenderer.send(Constants.SIYUAN_CMD, {
cmd: "unregisterGlobalShortcut",
accelerator: command.customHotkey,
@@ -665,7 +667,7 @@ const setKeymapFromDom = (root: HTMLElement) => {
cmd: "writeLog",
msg: "user update keymap:" + JSON.stringify(window.siyuan.config.keymap),
});
- if (oldToggleWin !== window.siyuan.config.keymap.general.toggleWin.custom) {
+ if (!isWindow() && oldToggleWin !== window.siyuan.config.keymap.general.toggleWin.custom) {
ipcRenderer.send(Constants.SIYUAN_CMD, {
cmd: "unregisterGlobalShortcut",
accelerator: oldToggleWin,
diff --git a/app/src/plugin/globalShortcut.test.ts b/app/src/plugin/globalShortcut.test.ts
new file mode 100644
index 0000000000..c21b743853
--- /dev/null
+++ b/app/src/plugin/globalShortcut.test.ts
@@ -0,0 +1,26 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {dispatchPluginGlobalShortcut} from "./globalShortcut";
+
+describe("plugin global shortcuts", () => {
+ it("runs only the first matching command", () => {
+ const calls: string[] = [];
+ const plugins = ["first", "second"].map(name => ({
+ commands: [{
+ customHotkey: "⌘A",
+ globalCallback: () => calls.push(name),
+ }],
+ }));
+
+ assert.equal(dispatchPluginGlobalShortcut(plugins, "⌘A"), true);
+ assert.deepEqual(calls, ["first"]);
+ });
+
+ it("ignores commands that do not match", () => {
+ let calls = 0;
+ const plugins = [{commands: [{customHotkey: "⌘A", globalCallback: () => calls++}]}];
+
+ assert.equal(dispatchPluginGlobalShortcut(plugins, "⌘B"), false);
+ assert.equal(calls, 0);
+ });
+});
diff --git a/app/src/plugin/globalShortcut.ts b/app/src/plugin/globalShortcut.ts
new file mode 100644
index 0000000000..7356d361cf
--- /dev/null
+++ b/app/src/plugin/globalShortcut.ts
@@ -0,0 +1,19 @@
+interface IPluginGlobalShortcutCommand {
+ customHotkey?: string;
+ globalCallback?: () => void;
+}
+
+interface IPluginGlobalShortcutOwner {
+ commands: IPluginGlobalShortcutCommand[];
+}
+
+export const dispatchPluginGlobalShortcut = (plugins: IPluginGlobalShortcutOwner[], hotkey: string) => {
+ for (const plugin of plugins) {
+ const command = plugin.commands.find(item => item.globalCallback && item.customHotkey === hotkey);
+ if (command) {
+ command.globalCallback();
+ return true;
+ }
+ }
+ return false;
+};
diff --git a/app/src/plugin/index.ts b/app/src/plugin/index.ts
index de321940b3..84c9f3ca9e 100644
--- a/app/src/plugin/index.ts
+++ b/app/src/plugin/index.ts
@@ -4,7 +4,7 @@ import {fetchPost} from "../util/fetch";
import {isMobile, isWindow} from "../util/functions";
/// #if !MOBILE
import {Custom} from "../layout/dock/Custom";
-import {getAllEditor, getAllModels} from "../layout/getAll";
+import {getAllModels} from "../layout/getAll";
import {Tab} from "../layout/Tab";
import {resizeTopBar, setPanelFocus} from "../layout/util";
import {getDockByType, setTabPosition} from "../layout/tabUtil";
@@ -19,8 +19,7 @@ import {hasClosestByAttribute} from "../protyle/util/hasClosest";
import {BlockPanel} from "../block/Panel";
import {Setting} from "./Setting";
import {Constants} from "../constants";
-import {uninstall} from "./uninstall";
-import {addPluginDock, afterLoadPlugin, loadPlugins, removePluginDock} from "./loader";
+import {addPluginDock, removePluginDock} from "./loader";
import {normalizeStoragePath} from "../util/pathName";
import {Kernel} from "./kernel";
import {IAgentCapabilityEffects, registerCapability} from "../layout/dock/agent/frontendCapabilities";
@@ -30,6 +29,14 @@ import {
removeBreadcrumbButton as removePluginBreadcrumbButton,
} from "./breadcrumbButton";
+const disposedPlugins = new WeakSet<Plugin>();
+
+const isPluginDisposed = (plugin: Plugin) => disposedPlugins.has(plugin);
+
+export const markPluginDisposed = (plugin: Plugin) => {
+ disposedPlugins.add(plugin);
+};
+
const updatePluginKeymap = (pluginName: string, key: string, hotkey: unknown) => {
if (!window.siyuan.config.keymap.plugin) {
window.siyuan.config.keymap.plugin = {};
@@ -137,40 +144,30 @@ export class Plugin {
// 加载
}
- public onunload() {
- // 禁用/关闭
+ public onunload(): Promise<void> | void {
+ // 禁用
}
- public uninstall() {
+ public uninstall(): Promise<void> | void {
// 卸载
}
public onDataChanged() {
// 存储数据变更
- // 兼容 3.4.1 以前同步数据使用重载插件的问题
- uninstall(this.app, this.name, true);
- loadPlugins(this.app, [this.name], false).then(() => {
- this.app.plugins.find(item => {
- if (this.name === item.name) {
- afterLoadPlugin(item);
- getAllEditor().forEach(editor => {
- editor.protyle.toolbar.update(editor.protyle);
- });
- return true;
- }
- });
- });
}
public async updateCards(options: ICardData) {
return options;
}
- public onLayoutReady() {
+ public onLayoutReady(): Promise<void> | void {
// 布局加载完成
}
public addCommand(command: ICommand) {
+ if (isPluginDisposed(this)) {
+ return;
+ }
if (typeof command.hotkey !== "string") {
command.hotkey = "";
}
@@ -182,7 +179,8 @@ export class Plugin {
} else {
this.commands.push(command);
/// #if !BROWSER
- if (command.globalCallback && command.customHotkey && !isDisallowedTextInputHotkey(command.customHotkey)) {
+ if (!isWindow() && command.globalCallback && command.customHotkey &&
+ !isDisallowedTextInputHotkey(command.customHotkey)) {
ipcRenderer.send(Constants.SIYUAN_CMD, {
cmd: "registerGlobalShortcut",
accelerator: command.customHotkey
@@ -193,6 +191,9 @@ export class Plugin {
}
public addIcons(svg: string) {
+ if (isPluginDisposed(this)) {
+ return;
+ }
const svgElement = document.querySelector(`svg[data-name="${this.name}"] defs`);
if (svgElement) {
svgElement.insertAdjacentHTML("afterbegin", svg);
@@ -215,6 +216,9 @@ export class Plugin {
position?: "right" | "left",
callback: (evt: MouseEvent) => void
}) {
+ if (isPluginDisposed(this)) {
+ return;
+ }
options.icon = options.icon.trim();
if (!options.icon.startsWith("icon") && !options.icon.startsWith("<svg")) {
console.error(`plugin ${this.name} addTopBar error: icon must be svg id or svg tag`);
@@ -278,6 +282,9 @@ export class Plugin {
}
public removeTopBar(id: string) {
+ if (isPluginDisposed(this)) {
+ return;
+ }
const index = this.topBarIcons.findIndex(item => item.getAttribute("data-id") === id);
if (index === -1) {
return;
@@ -298,6 +305,9 @@ export class Plugin {
title: string,
callback: (event: MouseEvent, protyle: IProtyle) => void,
}) {
+ if (isPluginDisposed(this)) {
+ return options.id;
+ }
options.icon = options.icon.trim();
if (!options.icon.startsWith("icon") && !options.icon.startsWith("<svg")) {
console.error(`plugin ${this.name} addBreadcrumbButton error: icon must be svg id or svg tag`);
@@ -308,6 +318,9 @@ export class Plugin {
}
public removeBreadcrumbButton(id: string) {
+ if (isPluginDisposed(this)) {
+ return;
+ }
removePluginBreadcrumbButton(this.name, id);
}
@@ -315,6 +328,9 @@ export class Plugin {
element: HTMLElement,
position?: "right" | "left",
}) {
+ if (isPluginDisposed(this)) {
+ return options.element;
+ }
/// #if !MOBILE
options.element.setAttribute("data-location", options.position || "right");
this.statusBarIcons.push(options.element);
@@ -331,13 +347,16 @@ export class Plugin {
}
public openSetting() {
- if (!this.setting) {
+ if (isPluginDisposed(this) || !this.setting) {
return;
}
this.setting.open(this.displayName || this.name);
}
public loadData(storageName: string): Promise<any> {
+ if (isPluginDisposed(this)) {
+ return Promise.reject({code: 410, msg: "Plugin lifecycle has ended", data: null});
+ }
if (typeof this.data[storageName] === "undefined") {
this.data[storageName] = "";
}
@@ -354,6 +373,9 @@ export class Plugin {
}
public saveData(storageName: string, data: any): Promise<any | IWebSocketData> {
+ if (isPluginDisposed(this)) {
+ return Promise.reject({code: 410, msg: "Plugin lifecycle has ended", data: null});
+ }
if (window.siyuan.config.readonly || window.siyuan.isPublish) {
return Promise.reject({
code: 403,
@@ -393,6 +415,9 @@ export class Plugin {
}
public removeData(storageName: string): Promise<IWebSocketData> {
+ if (isPluginDisposed(this)) {
+ return Promise.reject({code: 410, msg: "Plugin lifecycle has ended", data: null} as IWebSocketData);
+ }
if (window.siyuan.config.readonly || window.siyuan.isPublish) {
return Promise.reject({
code: 403,
@@ -435,6 +460,9 @@ export class Plugin {
update?: () => void,
init: () => void
}) {
+ if (isPluginDisposed(this)) {
+ return;
+ }
/// #if !MOBILE
const type2 = this.name + options.type;
this.models[type2] = (arg: { data: any, tab: Tab }) => {
@@ -499,6 +527,9 @@ export class Plugin {
throw new Error("Agent capability name and description are required");
}
const id = "plugin/frontend/" + encodeURIComponent(this.name) + "/" + encodeURIComponent(name);
+ if (isPluginDisposed(this)) {
+ return id;
+ }
if (!this.agentCapabilities.some((capability) => capability.id === id)) {
const generation = registerCapability({
id,
@@ -528,6 +559,9 @@ export class Plugin {
update?: () => void,
init: () => void
}) {
+ if (isPluginDisposed(this)) {
+ return;
+ }
const id = options.id || options.type;
const type2 = this.name + options.type;
const existingID = this.docks[type2]?.id;
@@ -582,6 +616,9 @@ export class Plugin {
}
public removeDock(id: string) {
+ if (isPluginDisposed(this)) {
+ return;
+ }
removePluginDock(this, id);
}
@@ -593,6 +630,9 @@ export class Plugin {
originalRefBlockIDs?: IObject,
isBacklink: boolean,
}) => {
+ if (isPluginDisposed(this)) {
+ return;
+ }
window.siyuan.blockPanels.push(new BlockPanel({
app: this.app,
originalRefBlockIDs: options.originalRefBlockIDs,
diff --git a/app/src/plugin/kernel.ts b/app/src/plugin/kernel.ts
index b87ddba0ee..12d994251a 100644
--- a/app/src/plugin/kernel.ts
+++ b/app/src/plugin/kernel.ts
@@ -38,6 +38,8 @@ export class Kernel implements IKernelPlugin {
#rpcCallUrl: string;
+ #destroyed = false;
+
constructor(options: {
appId: string;
name: string;
@@ -57,6 +59,9 @@ export class Kernel implements IKernelPlugin {
#createState(): IKernelPluginState {
return new KernelState((state) => {
+ if (this.#destroyed) {
+ return;
+ }
switch (state.code) {
case 2: // running
if (this.#rpcWs == null) {
@@ -99,6 +104,9 @@ export class Kernel implements IKernelPlugin {
notify,
batch: this.#rpcBatchCall.bind(this),
bind: (method: TJsonRpcMethod, handler: TJsonRpcHandler<void>) => {
+ if (this.#destroyed) {
+ return;
+ }
const handlers = (() => {
let handlers = this.#handlers.get(method);
if (!handlers) {
@@ -157,7 +165,13 @@ export class Kernel implements IKernelPlugin {
}
async #fetchRpc(body: string): Promise<any> {
+ if (this.#destroyed) {
+ throw new Error("Plugin lifecycle has ended");
+ }
for (let retry = 0; ; retry++) {
+ if (this.#destroyed) {
+ throw new Error("Plugin lifecycle has ended");
+ }
const response = await fetch(this.#rpcCallUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -215,6 +229,9 @@ export class Kernel implements IKernelPlugin {
}
public async init() {
+ if (this.#destroyed) {
+ return;
+ }
try {
await this.#initState();
} catch (error) {
@@ -223,11 +240,16 @@ export class Kernel implements IKernelPlugin {
}
public async destroy() {
+ if (this.#destroyed) {
+ return;
+ }
+ this.#destroyed = true;
try {
this.#rpcWs?.close();
} catch (error) {
console.error("Failed to close JSON-RPC WebSocket connection:", error);
}
+ this.#handlers.clear();
}
}
diff --git a/app/src/plugin/lifecycle.test.ts b/app/src/plugin/lifecycle.test.ts
new file mode 100644
index 0000000000..8cc430586d
--- /dev/null
+++ b/app/src/plugin/lifecycle.test.ts
@@ -0,0 +1,563 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {
+ PluginLifecycleCoordinator,
+ type IPluginLifecycleAdapter,
+ type IPluginLifecycleOptions,
+} from "./lifecycle";
+
+interface ITestPluginData {
+ name: string;
+ revision: number;
+}
+
+interface ITestPlugin extends ITestPluginData {
+ disposed: boolean;
+}
+
+const deferred = <T>() => {
+ let resolve: (value: T) => void;
+ let reject: (reason?: unknown) => void;
+ const promise = new Promise<T>((promiseResolve, promiseReject) => {
+ resolve = promiseResolve;
+ reject = promiseReject;
+ });
+ return {promise, resolve, reject};
+};
+
+const nextTurn = () => new Promise<void>(resolve => setTimeout(resolve, 0));
+
+const flushMicrotasks = async () => {
+ for (let i = 0; i < 8; i++) {
+ await Promise.resolve();
+ }
+};
+
+class FakeClock {
+ public now = 0;
+ private nextTimer = 1;
+ private readonly timers = new Map<number, {at: number, callback: () => void}>();
+
+ public setTimeout = (callback: () => void, delay: number) => {
+ const timer = this.nextTimer++;
+ this.timers.set(timer, {at: this.now + delay, callback});
+ return timer as unknown as ReturnType<typeof setTimeout>;
+ };
+
+ public clearTimeout = (timer: ReturnType<typeof setTimeout>) => {
+ this.timers.delete(timer as unknown as number);
+ };
+
+ public advance(milliseconds: number) {
+ this.now += milliseconds;
+ Array.from(this.timers.entries())
+ .filter(([, timer]) => timer.at <= this.now)
+ .sort((first, second) => first[1].at - second[1].at)
+ .forEach(([id, timer]) => {
+ this.timers.delete(id);
+ timer.callback();
+ });
+ }
+}
+
+const createHarness = (overrides: Partial<IPluginLifecycleAdapter<ITestPluginData, ITestPlugin>> = {},
+ teardownTimeout = 20, options: IPluginLifecycleOptions = {}) => {
+ const events: string[] = [];
+ const instances: ITestPlugin[] = [];
+ const adapter: IPluginLifecycleAdapter<ITestPluginData, ITestPlugin> = {
+ create(data) {
+ events.push(`create:${data.name}:${data.revision}`);
+ return {...data, disposed: false};
+ },
+ attach(plugin) {
+ assert.equal(instances.some(item => item.name === plugin.name && !item.disposed), false);
+ instances.push(plugin);
+ events.push(`attach:${plugin.name}`);
+ },
+ onload(plugin) {
+ events.push(`onload:${plugin.name}`);
+ },
+ init(plugin) {
+ events.push(`init:${plugin.name}`);
+ },
+ onLayoutReady(plugin) {
+ events.push(`layout:${plugin.name}`);
+ },
+ mount(plugin) {
+ events.push(`mount:${plugin.name}`);
+ },
+ onDataChanged(plugin) {
+ events.push(`data:${plugin.name}`);
+ },
+ onunload(plugin) {
+ events.push(`onunload:${plugin.name}`);
+ },
+ uninstall(plugin) {
+ events.push(`uninstall:${plugin.name}`);
+ },
+ markDisposed(plugin) {
+ plugin.disposed = true;
+ events.push(`markDisposed:${plugin.name}`);
+ },
+ dispose(plugin, uninstall) {
+ events.push(`dispose:${plugin.name}:${uninstall}`);
+ },
+ onError(name, hook) {
+ events.push(`error:${name}:${hook}`);
+ },
+ ...overrides,
+ };
+ return {
+ coordinator: new PluginLifecycleCoordinator(adapter, {...options, teardownTimeout}),
+ events,
+ instances,
+ };
+};
+
+describe("plugin lifecycle coordinator", () => {
+ it("keeps one instance and one layout hook for repeated loads", async () => {
+ const {coordinator, events, instances} = createHarness();
+ coordinator.start();
+ await coordinator.setLayoutReady();
+
+ await Promise.all([
+ coordinator.requestLoad("sample", async () => ({name: "sample", revision: 1})),
+ coordinator.requestLoad("sample", async () => ({name: "sample", revision: 2})),
+ ]);
+ await coordinator.setLayoutReady();
+
+ assert.equal(instances.length, 1);
+ assert.equal(instances[0].revision, 2);
+ assert.equal(events.filter(item => item === "layout:sample").length, 1);
+ assert.equal(events.filter(item => item === "mount:sample").length, 1);
+ assert.equal(coordinator.getState("sample"), "ready");
+ });
+
+ it("disposes a created instance when attaching it fails", async () => {
+ const {coordinator, events} = createHarness({
+ attach() {
+ throw new Error("duplicate instance");
+ },
+ });
+ coordinator.start();
+
+ await coordinator.requestLoad("sample", async () => ({name: "sample", revision: 1}));
+
+ assert.equal(coordinator.getState("sample"), "absent");
+ assert.deepEqual(events.slice(-3), [
+ "error:sample:attach",
+ "markDisposed:sample",
+ "dispose:sample:false",
+ ]);
+ });
+
+ it("discards stale and out-of-order batch responses", async () => {
+ const {coordinator, events} = createHarness();
+ coordinator.start();
+ const firstBatch = coordinator.beginLoadBatch();
+ const secondBatch = coordinator.beginLoadBatch();
+
+ await coordinator.requestBatchLoad("sample", {name: "sample", revision: 1}, firstBatch);
+ await coordinator.requestUnload("sample");
+ await coordinator.requestBatchLoad("sample", {name: "sample", revision: 2}, secondBatch);
+
+ assert.deepEqual(events.filter(item => item.startsWith("create:")), []);
+ assert.equal(coordinator.getState("sample"), "absent");
+ });
+
+ it("keeps buffered structural intent ahead of the initial catalog", async () => {
+ const {coordinator, events} = createHarness();
+ const unloading = coordinator.requestUnload("sample");
+ const initialBatch = coordinator.beginLoadBatch(true);
+ const loading = coordinator.requestBatchLoad("sample", {name: "sample", revision: 1}, initialBatch);
+
+ coordinator.start();
+ await Promise.all([unloading, loading]);
+
+ assert.deepEqual(events.filter(item => item.startsWith("create:")), []);
+ assert.equal(coordinator.getState("sample"), "absent");
+ });
+
+ it("accepts the latest load batch", async () => {
+ const {coordinator} = createHarness();
+ coordinator.start();
+ coordinator.beginLoadBatch();
+ const latestBatch = coordinator.beginLoadBatch();
+
+ await coordinator.requestBatchLoad("sample", {name: "sample", revision: 2}, latestBatch);
+
+ assert.equal(coordinator.getInstance("sample")?.revision, 2);
+ });
+
+ it("latches layout readiness while onload is pending", async () => {
+ const loaded = deferred<void>();
+ const {coordinator, events} = createHarness({
+ onload(plugin) {
+ events.push(`onload:${plugin.name}`);
+ return loaded.promise;
+ },
+ });
+ coordinator.start();
+ const loading = coordinator.requestLoad("sample", async () => ({name: "sample", revision: 1}));
+ await nextTurn();
+
+ await coordinator.setLayoutReady();
+ loaded.resolve();
+ await loading;
+
+ assert.deepEqual(events.slice(-3), ["init:sample", "layout:sample", "mount:sample"]);
+ assert.equal(coordinator.getState("sample"), "ready");
+ });
+
+ it("continues initialization and mounting after load hook rejections", async () => {
+ const {coordinator, events} = createHarness({
+ onload(plugin) {
+ events.push(`onload:${plugin.name}`);
+ return Promise.reject(new Error("onload failed"));
+ },
+ onLayoutReady(plugin) {
+ events.push(`layout:${plugin.name}`);
+ return Promise.reject(new Error("layout failed"));
+ },
+ });
+ coordinator.start();
+ await coordinator.setLayoutReady();
+
+ await coordinator.requestLoad("sample", async () => ({name: "sample", revision: 1}));
+
+ assert.equal(events.includes("error:sample:onload"), true);
+ assert.equal(events.includes("init:sample"), true);
+ assert.equal(events.includes("error:sample:onLayoutReady"), true);
+ assert.equal(events.includes("mount:sample"), true);
+ assert.equal(coordinator.getState("sample"), "ready");
+ });
+
+ it("skips construction when unload arrives while load data is pending", async () => {
+ const never = new Promise<ITestPluginData>(() => undefined);
+ const {coordinator, events} = createHarness();
+ coordinator.start();
+ const loading = coordinator.requestLoad("sample", () => never);
+ await nextTurn();
+
+ const unloading = coordinator.requestUnload("sample");
+ await Promise.all([loading, unloading]);
+
+ assert.deepEqual(events.filter(item => item.startsWith("create:")), []);
+ assert.equal(coordinator.getState("sample"), "absent");
+ });
+
+ it("waits for onload before unloading and skips layout", async () => {
+ const loaded = deferred<void>();
+ const {coordinator, events} = createHarness({
+ onload(plugin) {
+ events.push(`onload:${plugin.name}`);
+ return loaded.promise;
+ },
+ });
+ coordinator.start();
+ await coordinator.setLayoutReady();
+ const loading = coordinator.requestLoad("sample", async () => ({name: "sample", revision: 1}));
+ await nextTurn();
+ const unloading = coordinator.requestUnload("sample");
+ loaded.resolve();
+
+ await Promise.all([loading, unloading]);
+
+ assert.equal(events.includes("layout:sample"), false);
+ assert.ok(events.indexOf("init:sample") < events.indexOf("onunload:sample"));
+ assert.equal(coordinator.getState("sample"), "absent");
+ });
+
+ it("abandons a pending layout hook before unloading", async () => {
+ const never = new Promise<void>(() => undefined);
+ const {coordinator, events} = createHarness({
+ onLayoutReady(plugin) {
+ events.push(`layout:${plugin.name}`);
+ return never;
+ },
+ }, 10);
+ coordinator.start();
+ await coordinator.setLayoutReady();
+ const loading = coordinator.requestLoad("sample", async () => ({name: "sample", revision: 1}));
+ await nextTurn();
+
+ const unloading = coordinator.requestUnload("sample");
+ await Promise.all([loading, unloading]);
+
+ assert.equal(events.includes("error:sample:onLayoutReady"), true);
+ assert.equal(events.includes("mount:sample"), false);
+ assert.equal(events.includes("dispose:sample:false"), true);
+ });
+
+ it("abandons pending onload before applying the teardown timeout", async () => {
+ const never = new Promise<void>(() => undefined);
+ const {coordinator, events} = createHarness({
+ onload(plugin) {
+ events.push(`onload:${plugin.name}`);
+ return never;
+ },
+ onunload(plugin) {
+ events.push(`onunload:${plugin.name}`);
+ return never;
+ },
+ }, 10);
+ coordinator.start();
+ const loading = coordinator.requestLoad("sample", async () => ({name: "sample", revision: 1}));
+ await nextTurn();
+
+ const unloading = coordinator.requestUnload("sample");
+ await Promise.all([loading, unloading]);
+
+ assert.equal(events.includes("init:sample"), false);
+ assert.equal(events.includes("error:sample:onload"), true);
+ assert.equal(events.includes("error:sample:onunload"), true);
+ assert.equal(events.includes("dispose:sample:false"), true);
+ assert.equal(coordinator.getState("sample"), "absent");
+ });
+
+ it("uses separate loading and teardown timeout budgets", async () => {
+ const clock = new FakeClock();
+ const never = new Promise<void>(() => undefined);
+ const {coordinator, events} = createHarness({
+ onload(plugin) {
+ events.push(`onload:${plugin.name}`);
+ return never;
+ },
+ onunload(plugin) {
+ events.push(`onunload:${plugin.name}`);
+ return never;
+ },
+ }, 5000, {
+ now: () => clock.now,
+ setTimeout: clock.setTimeout,
+ clearTimeout: clock.clearTimeout,
+ });
+ coordinator.start();
+ const loading = coordinator.requestLoad("sample", async () => ({name: "sample", revision: 1}));
+ await flushMicrotasks();
+ const unloading = coordinator.requestUnload("sample");
+ await flushMicrotasks();
+
+ clock.advance(4999);
+ await flushMicrotasks();
+ assert.equal(events.includes("onunload:sample"), false);
+ clock.advance(1);
+ await flushMicrotasks();
+ assert.equal(events.includes("onunload:sample"), true);
+ assert.equal(events.includes("dispose:sample:false"), false);
+
+ clock.advance(4999);
+ await flushMicrotasks();
+ assert.equal(events.includes("dispose:sample:false"), false);
+ clock.advance(1);
+ await flushMicrotasks();
+ await Promise.all([loading, unloading]);
+
+ assert.equal(clock.now, 10000);
+ assert.equal(events.includes("dispose:sample:false"), true);
+ });
+
+ it("observes a load rejection that arrives after timeout", async () => {
+ const loaded = deferred<void>();
+ const {coordinator, events} = createHarness({
+ onload(plugin) {
+ events.push(`onload:${plugin.name}`);
+ return loaded.promise;
+ },
+ }, 10);
+ coordinator.start();
+ const loading = coordinator.requestLoad("sample", async () => ({name: "sample", revision: 1}));
+ await nextTurn();
+
+ const unloading = coordinator.requestUnload("sample");
+ await Promise.all([loading, unloading]);
+ loaded.reject(new Error("late failure"));
+ await nextTurn();
+
+ assert.equal(events.filter(item => item === "error:sample:onload").length, 2);
+ });
+
+ it("invokes uninstall even when onunload exhausts the shared deadline", async () => {
+ const never = new Promise<void>(() => undefined);
+ let uninstallCalls = 0;
+ const {coordinator, events} = createHarness({
+ onunload(plugin) {
+ events.push(`onunload:${plugin.name}`);
+ return never;
+ },
+ uninstall(plugin) {
+ events.push(`uninstall:${plugin.name}`);
+ uninstallCalls++;
+ return never;
+ },
+ }, 10);
+ coordinator.start();
+ await coordinator.requestLoad("sample", async () => ({name: "sample", revision: 1}));
+
+ await coordinator.requestUninstall("sample");
+
+ assert.equal(uninstallCalls, 1);
+ assert.equal(events.includes("error:sample:onunload"), true);
+ assert.equal(events.includes("error:sample:uninstall"), true);
+ assert.equal(events.includes("dispose:sample:true"), true);
+ });
+
+ it("shares one teardown deadline between onunload and uninstall", async () => {
+ const clock = new FakeClock();
+ const never = new Promise<void>(() => undefined);
+ const {coordinator, events} = createHarness({
+ onunload(plugin) {
+ events.push(`onunload:${plugin.name}`);
+ return never;
+ },
+ uninstall(plugin) {
+ events.push(`uninstall:${plugin.name}`);
+ return never;
+ },
+ }, 5000, {
+ now: () => clock.now,
+ setTimeout: clock.setTimeout,
+ clearTimeout: clock.clearTimeout,
+ });
+ coordinator.start();
+ await coordinator.requestLoad("sample", async () => ({name: "sample", revision: 1}));
+ const uninstalling = coordinator.requestUninstall("sample");
+ await flushMicrotasks();
+
+ clock.advance(4999);
+ await flushMicrotasks();
+ assert.equal(events.includes("uninstall:sample"), false);
+ clock.advance(1);
+ await flushMicrotasks();
+ assert.equal(events.includes("uninstall:sample"), true);
+ assert.equal(events.includes("dispose:sample:true"), false);
+ clock.advance(0);
+ await flushMicrotasks();
+ await uninstalling;
+
+ assert.equal(clock.now, 5000);
+ assert.equal(events.includes("dispose:sample:true"), true);
+ });
+
+ it("disposes after teardown hook rejections", async () => {
+ const {coordinator, events} = createHarness({
+ onunload(plugin) {
+ events.push(`onunload:${plugin.name}`);
+ return Promise.reject(new Error("onunload failed"));
+ },
+ uninstall(plugin) {
+ events.push(`uninstall:${plugin.name}`);
+ return Promise.reject(new Error("uninstall failed"));
+ },
+ });
+ coordinator.start();
+ await coordinator.requestLoad("sample", async () => ({name: "sample", revision: 1}));
+
+ await coordinator.requestUninstall("sample");
+
+ assert.equal(events.includes("error:sample:onunload"), true);
+ assert.equal(events.includes("error:sample:uninstall"), true);
+ assert.equal(events.includes("dispose:sample:true"), true);
+ assert.equal(coordinator.getState("sample"), "absent");
+ });
+
+ it("recovers from a host cleanup error", async () => {
+ let disposeCalls = 0;
+ const {coordinator, events} = createHarness({
+ dispose() {
+ disposeCalls++;
+ if (disposeCalls === 1) {
+ throw new Error("cleanup failed");
+ }
+ },
+ });
+ coordinator.start();
+ await coordinator.requestLoad("sample", async () => ({name: "sample", revision: 1}));
+ await coordinator.requestUnload("sample");
+
+ await coordinator.requestLoad("sample", async () => ({name: "sample", revision: 2}));
+
+ assert.equal(events.includes("error:sample:dispose"), true);
+ assert.equal(coordinator.getInstance("sample")?.revision, 2);
+ });
+
+ it("keeps uninstall as a barrier before a later load", async () => {
+ const unloaded = deferred<void>();
+ const {coordinator, events} = createHarness({
+ onunload(plugin) {
+ events.push(`onunload:${plugin.name}`);
+ return unloaded.promise;
+ },
+ });
+ coordinator.start();
+ await coordinator.requestLoad("sample", async () => ({name: "sample", revision: 1}));
+
+ const unloading = coordinator.requestUnload("sample");
+ await nextTurn();
+ const uninstalling = coordinator.requestUninstall("sample");
+ const loading = coordinator.requestLoad("sample", async () => ({name: "sample", revision: 2}));
+ unloaded.resolve();
+ await Promise.all([unloading, uninstalling, loading]);
+
+ assert.ok(events.indexOf("uninstall:sample") < events.indexOf("create:sample:2"));
+ assert.equal(events.includes("dispose:sample:true"), true);
+ assert.equal(coordinator.getInstance("sample")?.revision, 2);
+ });
+
+ it("coalesces a reload waiting for data into the latest reload", async () => {
+ const never = new Promise<ITestPluginData>(() => undefined);
+ const {coordinator, events} = createHarness();
+ coordinator.start();
+ await coordinator.requestLoad("sample", async () => ({name: "sample", revision: 0}));
+
+ const firstReload = coordinator.requestReload("sample", () => never);
+ await nextTurn();
+ const secondReload = coordinator.requestReload("sample",
+ async () => ({name: "sample", revision: 2}));
+ await Promise.all([firstReload, secondReload]);
+
+ assert.deepEqual(events.filter(item => item.startsWith("create:")), [
+ "create:sample:0",
+ "create:sample:2",
+ ]);
+ assert.equal(coordinator.getInstance("sample")?.revision, 2);
+ });
+
+ it("drops data changes when a structural task is pending", async () => {
+ const unloaded = deferred<void>();
+ const {coordinator, events} = createHarness({
+ onunload(plugin) {
+ events.push(`onunload:${plugin.name}`);
+ return unloaded.promise;
+ },
+ });
+ coordinator.start();
+ await coordinator.requestLoad("sample", async () => ({name: "sample", revision: 1}));
+
+ const unloading = coordinator.requestUnload("sample");
+ await coordinator.requestDataChange("sample");
+ unloaded.resolve();
+ await unloading;
+
+ assert.equal(events.includes("data:sample"), false);
+ });
+
+ it("runs different plugin queues in parallel", async () => {
+ const loads = new Map(["first", "second"].map(name => [name, deferred<void>()]));
+ const {coordinator} = createHarness({
+ onload(plugin) {
+ return loads.get(plugin.name).promise;
+ },
+ });
+ coordinator.start();
+ const first = coordinator.requestLoad("first", async () => ({name: "first", revision: 1}));
+ const second = coordinator.requestLoad("second", async () => ({name: "second", revision: 1}));
+ await nextTurn();
+
+ assert.equal(coordinator.getState("first"), "loading");
+ assert.equal(coordinator.getState("second"), "loading");
+ loads.get("first").resolve();
+ loads.get("second").resolve();
+ await Promise.all([first, second]);
+ });
+});
diff --git a/app/src/plugin/lifecycle.ts b/app/src/plugin/lifecycle.ts
new file mode 100644
index 0000000000..28286f9de2
--- /dev/null
+++ b/app/src/plugin/lifecycle.ts
@@ -0,0 +1,590 @@
+export type TPluginLifecycleState =
+ "absent" |
+ "loading" |
+ "loaded" |
+ "layouting" |
+ "ready" |
+ "unloading" |
+ "uninstalling";
+
+export type TPluginLifecycleHook =
+ "create" |
+ "attach" |
+ "loadData" |
+ "onload" |
+ "kernelInit" |
+ "onLayoutReady" |
+ "mount" |
+ "onDataChanged" |
+ "onunload" |
+ "uninstall" |
+ "dispose";
+
+export interface IPluginLifecycleAdapter<TData, TPlugin> {
+ create(data: TData): TPlugin | undefined;
+ attach(plugin: TPlugin): void;
+ onload(plugin: TPlugin): Promise<void> | void;
+ init(plugin: TPlugin): Promise<void> | void;
+ onLayoutReady(plugin: TPlugin): Promise<void> | void;
+ mount(plugin: TPlugin): void;
+ onDataChanged(plugin: TPlugin): void;
+ onunload(plugin: TPlugin): Promise<void> | void;
+ uninstall(plugin: TPlugin): Promise<void> | void;
+ markDisposed(plugin: TPlugin): void;
+ dispose(plugin: TPlugin, uninstall: boolean): void;
+ onError(name: string, hook: TPluginLifecycleHook, error: unknown): void;
+}
+
+type TPluginLifecycleTaskKind = "load" | "reload" | "unload" | "uninstall" | "layout" | "dataChange";
+type TPluginStructuralTaskKind = "load" | "reload" | "unload" | "uninstall";
+
+interface IDeferred<T> {
+ promise: Promise<T>;
+ resolve: (value: T) => void;
+}
+
+interface IPluginLifecycleTask<TData> {
+ kind: TPluginLifecycleTaskKind;
+ sequence: number;
+ dataProvider?: () => Promise<TData | undefined>;
+ uninstallHandled?: boolean;
+ waiters: Array<() => void>;
+}
+
+interface IPluginLifecycleInterrupt {
+ promise: Promise<number>;
+ resolve: (deadline: number) => void;
+ resolved: boolean;
+}
+
+interface IPluginLifecycleRecord<TData, TPlugin> {
+ name: string;
+ state: TPluginLifecycleState;
+ instance?: TPlugin;
+ tasks: IPluginLifecycleTask<TData>[];
+ currentTask?: IPluginLifecycleTask<TData>;
+ processing: boolean;
+ lastStructuralSequence: number;
+ latestStructuralKind?: TPluginStructuralTaskKind;
+ interrupt: IPluginLifecycleInterrupt;
+ removalDeadline?: number;
+}
+
+export interface IPluginLifecycleOptions {
+ teardownTimeout?: number;
+ now?: () => number;
+ setTimeout?: (callback: () => void, delay: number) => ReturnType<typeof setTimeout>;
+ clearTimeout?: (timer: ReturnType<typeof setTimeout>) => void;
+}
+
+export interface IPluginLoadBatch {
+ id: number;
+ sequence: number;
+}
+
+const createDeferred = <T>(): IDeferred<T> => {
+ let resolve: (value: T) => void;
+ const promise = new Promise<T>((promiseResolve) => {
+ resolve = promiseResolve;
+ });
+ return {promise, resolve};
+};
+
+const createInterrupt = (): IPluginLifecycleInterrupt => {
+ const deferred = createDeferred<number>();
+ return {
+ promise: deferred.promise,
+ resolve: deferred.resolve,
+ resolved: false,
+ };
+};
+
+export class PluginLifecycleCoordinator<TData, TPlugin> {
+ private readonly adapter: IPluginLifecycleAdapter<TData, TPlugin>;
+ private readonly records = new Map<string, IPluginLifecycleRecord<TData, TPlugin>>();
+ private readonly teardownTimeout: number;
+ private readonly now: () => number;
+ private readonly setTimeout: (callback: () => void, delay: number) => ReturnType<typeof setTimeout>;
+ private readonly clearTimeout: (timer: ReturnType<typeof setTimeout>) => void;
+ private sequence = 0;
+ private loadBatchSequence = 0;
+ private latestLoadBatch = 0;
+ private started = false;
+ private layoutReady = false;
+
+ constructor(adapter: IPluginLifecycleAdapter<TData, TPlugin>, options: IPluginLifecycleOptions = {}) {
+ this.adapter = adapter;
+ this.teardownTimeout = options.teardownTimeout ?? 5000;
+ this.now = options.now ?? Date.now;
+ this.setTimeout = options.setTimeout ?? ((callback, delay) => setTimeout(callback, delay));
+ this.clearTimeout = options.clearTimeout ?? ((timer) => clearTimeout(timer));
+ }
+
+ public start() {
+ if (this.started) {
+ return;
+ }
+ this.started = true;
+ this.records.forEach((record) => this.schedule(record));
+ }
+
+ public isStarted() {
+ return this.started;
+ }
+
+ public beginLoadBatch(initial = false): IPluginLoadBatch {
+ this.latestLoadBatch = ++this.loadBatchSequence;
+ return {
+ id: this.latestLoadBatch,
+ sequence: initial ? 0 : ++this.sequence,
+ };
+ }
+
+ public isLatestLoadBatch(batch: IPluginLoadBatch) {
+ return batch.id === this.latestLoadBatch;
+ }
+
+ public requestBatchLoad(name: string, data: TData, batch: IPluginLoadBatch) {
+ this.sequence = Math.max(this.sequence, batch.sequence);
+ const record = this.getRecord(name);
+ if (batch.id !== this.latestLoadBatch || record.lastStructuralSequence > batch.sequence) {
+ return Promise.resolve();
+ }
+ return this.enqueueStructural(record, "load", async () => data, batch.sequence);
+ }
+
+ public requestLoad(name: string, dataProvider: () => Promise<TData | undefined>) {
+ return this.enqueueStructural(this.getRecord(name), "load", dataProvider);
+ }
+
+ public requestReload(name: string, dataProvider: () => Promise<TData | undefined>) {
+ return this.enqueueStructural(this.getRecord(name), "reload", dataProvider);
+ }
+
+ public requestUnload(name: string) {
+ return this.enqueueStructural(this.getRecord(name), "unload");
+ }
+
+ public requestUninstall(name: string) {
+ return this.enqueueStructural(this.getRecord(name), "uninstall");
+ }
+
+ public requestDataChange(name: string) {
+ const record = this.getRecord(name);
+ if (!record.instance || record.currentTask && this.isStructural(record.currentTask.kind) ||
+ record.tasks.some((task) => this.isStructural(task.kind))) {
+ return Promise.resolve();
+ }
+ const existing = record.tasks.find((task) => task.kind === "dataChange");
+ if (existing) {
+ return new Promise<void>((resolve) => existing.waiters.push(resolve));
+ }
+ return this.enqueue(record, {
+ kind: "dataChange",
+ sequence: 0,
+ waiters: [],
+ });
+ }
+
+ public setLayoutReady() {
+ if (this.layoutReady) {
+ return Promise.resolve();
+ }
+ this.layoutReady = true;
+ const tasks: Promise<void>[] = [];
+ this.records.forEach((record) => {
+ if (record.instance && record.state === "loaded" &&
+ !record.tasks.some((task) => task.kind === "layout")) {
+ tasks.push(this.enqueue(record, {
+ kind: "layout",
+ sequence: 0,
+ waiters: [],
+ }));
+ }
+ });
+ return Promise.all(tasks).then(() => undefined);
+ }
+
+ public getState(name: string): TPluginLifecycleState {
+ return this.records.get(name)?.state ?? "absent";
+ }
+
+ public getInstance(name: string) {
+ return this.records.get(name)?.instance;
+ }
+
+ private getRecord(name: string) {
+ let record = this.records.get(name);
+ if (!record) {
+ record = {
+ name,
+ state: "absent",
+ tasks: [],
+ processing: false,
+ lastStructuralSequence: 0,
+ interrupt: createInterrupt(),
+ };
+ this.records.set(name, record);
+ }
+ return record;
+ }
+
+ private enqueueStructural(record: IPluginLifecycleRecord<TData, TPlugin>, kind: TPluginStructuralTaskKind,
+ dataProvider?: () => Promise<TData | undefined>, sequence = ++this.sequence) {
+ record.lastStructuralSequence = sequence;
+ record.latestStructuralKind = kind;
+ this.dropPendingDataChanges(record);
+ const task: IPluginLifecycleTask<TData> = {
+ kind,
+ sequence,
+ dataProvider,
+ waiters: [],
+ };
+ if (kind === "reload" || kind === "unload" || kind === "uninstall") {
+ this.signalRemoval(record, this.now() + this.teardownTimeout);
+ }
+ return this.enqueue(record, task);
+ }
+
+ private enqueue(record: IPluginLifecycleRecord<TData, TPlugin>, task: IPluginLifecycleTask<TData>) {
+ const promise = new Promise<void>((resolve) => task.waiters.push(resolve));
+ record.tasks.push(task);
+ this.schedule(record);
+ return promise;
+ }
+
+ private schedule(record: IPluginLifecycleRecord<TData, TPlugin>) {
+ if (!this.started || record.processing || record.tasks.length === 0) {
+ return;
+ }
+ record.processing = true;
+ queueMicrotask(() => void this.process(record));
+ }
+
+ private async process(record: IPluginLifecycleRecord<TData, TPlugin>) {
+ try {
+ while (record.tasks.length > 0) {
+ const task = record.tasks.shift()!;
+ record.currentTask = task;
+ try {
+ await this.runTask(record, task);
+ } catch (error) {
+ this.adapter.onError(record.name, "dispose", error);
+ } finally {
+ task.waiters.forEach((resolve) => resolve());
+ record.currentTask = undefined;
+ }
+ }
+ } finally {
+ record.processing = false;
+ this.schedule(record);
+ }
+ }
+
+ private async runTask(record: IPluginLifecycleRecord<TData, TPlugin>, task: IPluginLifecycleTask<TData>) {
+ switch (task.kind) {
+ case "load":
+ await this.runLoad(record, task, false);
+ break;
+ case "reload":
+ await this.runLoad(record, task, true);
+ break;
+ case "unload":
+ await this.teardown(record, task, false);
+ break;
+ case "uninstall":
+ if (!task.uninstallHandled) {
+ await this.teardown(record, task, true);
+ }
+ break;
+ case "layout":
+ await this.runLayout(record);
+ break;
+ case "dataChange":
+ this.runDataChange(record);
+ break;
+ }
+ }
+
+ private async runLoad(record: IPluginLifecycleRecord<TData, TPlugin>, task: IPluginLifecycleTask<TData>,
+ reload: boolean) {
+ if (this.isLoadTaskObsolete(record, task, reload)) {
+ return;
+ }
+ if (reload && record.instance) {
+ await this.teardown(record, task, false);
+ }
+ if (task.sequence < record.lastStructuralSequence) {
+ return;
+ }
+ if (record.instance) {
+ return;
+ }
+ this.resetInterrupt(record);
+ record.state = "loading";
+ const data = await this.resolveLoadData(record, task);
+ if (!data || task.sequence < record.lastStructuralSequence || record.removalDeadline !== undefined) {
+ record.state = "absent";
+ return;
+ }
+ let plugin: TPlugin | undefined;
+ try {
+ plugin = this.adapter.create(data);
+ } catch (error) {
+ this.adapter.onError(record.name, "create", error);
+ record.state = "absent";
+ return;
+ }
+ if (!plugin) {
+ record.state = "absent";
+ return;
+ }
+ record.instance = plugin;
+ try {
+ this.adapter.attach(plugin);
+ } catch (error) {
+ this.adapter.onError(record.name, "attach", error);
+ this.markDisposed(record.name, plugin);
+ record.instance = undefined;
+ record.state = "absent";
+ try {
+ this.adapter.dispose(plugin, false);
+ } catch (disposeError) {
+ this.adapter.onError(record.name, "dispose", disposeError);
+ }
+ this.resetInterrupt(record);
+ return;
+ }
+ const loaded = await this.runInterruptibleHook(record, "onload", () => this.adapter.onload(plugin));
+ if (!loaded || record.instance !== plugin) {
+ record.state = "loaded";
+ return;
+ }
+ const initialized = await this.runInterruptibleHook(record, "kernelInit", () => this.adapter.init(plugin));
+ record.state = "loaded";
+ if (!initialized || record.instance !== plugin || this.hasPendingTeardown(record)) {
+ return;
+ }
+ if (this.layoutReady) {
+ await this.runLayout(record);
+ }
+ }
+
+ private async resolveLoadData(record: IPluginLifecycleRecord<TData, TPlugin>, task: IPluginLifecycleTask<TData>) {
+ const provider = this.observe(record.name, "loadData", () => task.dataProvider?.());
+ const result = await Promise.race([
+ provider.then((data) => ({type: "data" as const, data})),
+ record.interrupt.promise.then(() => ({type: "interrupt" as const, data: undefined})),
+ ]);
+ return result.type === "data" ? result.data : undefined;
+ }
+
+ private async runLayout(record: IPluginLifecycleRecord<TData, TPlugin>) {
+ if (!this.layoutReady || !record.instance || record.state === "ready" || this.hasPendingTeardown(record)) {
+ return;
+ }
+ const plugin = record.instance;
+ record.state = "layouting";
+ const completed = await this.runInterruptibleHook(record, "onLayoutReady",
+ () => this.adapter.onLayoutReady(plugin));
+ if (!completed || record.instance !== plugin || this.hasPendingTeardown(record)) {
+ record.state = "loaded";
+ return;
+ }
+ try {
+ this.adapter.mount(plugin);
+ } catch (error) {
+ this.adapter.onError(record.name, "mount", error);
+ }
+ record.state = "ready";
+ }
+
+ private runDataChange(record: IPluginLifecycleRecord<TData, TPlugin>) {
+ if (!record.instance || record.tasks.some((task) => this.isStructural(task.kind))) {
+ return;
+ }
+ try {
+ const result = this.adapter.onDataChanged(record.instance) as unknown;
+ if (result && typeof (result as Promise<void>).then === "function") {
+ void Promise.resolve(result).catch((error) =>
+ this.adapter.onError(record.name, "onDataChanged", error));
+ }
+ } catch (error) {
+ this.adapter.onError(record.name, "onDataChanged", error);
+ }
+ }
+
+ private async teardown(record: IPluginLifecycleRecord<TData, TPlugin>,
+ task: IPluginLifecycleTask<TData>, uninstall: boolean) {
+ const plugin = record.instance;
+ if (!plugin) {
+ record.state = "absent";
+ return;
+ }
+ const deadline = this.now() + this.teardownTimeout;
+ record.state = "unloading";
+ const unloadPromise = this.observe(record.name, "onunload", () => this.adapter.onunload(plugin));
+ if (!await this.waitUntilDeadline(unloadPromise, deadline)) {
+ this.reportTimeout(record.name, "onunload");
+ }
+ uninstall = uninstall || this.hasPendingUninstall(record);
+ if (uninstall) {
+ record.state = "uninstalling";
+ const uninstallPromise = this.observe(record.name, "uninstall", () => this.adapter.uninstall(plugin));
+ if (!await this.waitUntilDeadline(uninstallPromise, deadline)) {
+ this.reportTimeout(record.name, "uninstall");
+ }
+ this.markPendingUninstallsHandled(record, task);
+ }
+ this.markDisposed(record.name, plugin);
+ record.instance = undefined;
+ record.state = "absent";
+ try {
+ this.adapter.dispose(plugin, uninstall);
+ } catch (error) {
+ this.adapter.onError(record.name, "dispose", error);
+ }
+ this.resetInterrupt(record);
+ }
+
+ private runInterruptibleHook(record: IPluginLifecycleRecord<TData, TPlugin>, hook: TPluginLifecycleHook,
+ callback: () => Promise<void> | void) {
+ const hookPromise = this.observe(record.name, hook, callback).then(() => true);
+ return new Promise<boolean>((resolve) => {
+ let settled = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ hookPromise.then(() => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ if (timer !== undefined) {
+ this.clearTimeout(timer);
+ }
+ resolve(true);
+ });
+ record.interrupt.promise.then((deadline) => {
+ if (settled) {
+ return;
+ }
+ const remaining = Math.max(0, deadline - this.now());
+ timer = this.setTimeout(() => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ this.reportTimeout(record.name, hook);
+ resolve(false);
+ }, remaining);
+ });
+ });
+ }
+
+ private waitUntilDeadline(promise: Promise<unknown>, deadline: number) {
+ return new Promise<boolean>((resolve) => {
+ let settled = false;
+ const remaining = Math.max(0, deadline - this.now());
+ const timer = this.setTimeout(() => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ resolve(false);
+ }, remaining);
+ promise.then(() => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ this.clearTimeout(timer);
+ resolve(true);
+ });
+ });
+ }
+
+ private observe<T>(name: string, hook: TPluginLifecycleHook, callback: () => Promise<T> | T): Promise<T | undefined> {
+ try {
+ return Promise.resolve(callback()).catch((error) => {
+ this.adapter.onError(name, hook, error);
+ return undefined;
+ });
+ } catch (error) {
+ this.adapter.onError(name, hook, error);
+ return Promise.resolve(undefined);
+ }
+ }
+
+ private reportTimeout(name: string, hook: TPluginLifecycleHook) {
+ this.adapter.onError(name, hook, new Error(`plugin lifecycle hook timed out after ${this.teardownTimeout}ms`));
+ }
+
+ private markDisposed(name: string, plugin: TPlugin) {
+ try {
+ this.adapter.markDisposed(plugin);
+ } catch (error) {
+ this.adapter.onError(name, "dispose", error);
+ }
+ }
+
+ private signalRemoval(record: IPluginLifecycleRecord<TData, TPlugin>, deadline: number) {
+ if (record.state !== "loading" && record.state !== "layouting") {
+ return;
+ }
+ record.removalDeadline = Math.min(record.removalDeadline ?? Number.POSITIVE_INFINITY, deadline);
+ if (!record.interrupt.resolved) {
+ record.interrupt.resolved = true;
+ record.interrupt.resolve(record.removalDeadline);
+ }
+ }
+
+ private resetInterrupt(record: IPluginLifecycleRecord<TData, TPlugin>) {
+ record.interrupt = createInterrupt();
+ record.removalDeadline = undefined;
+ }
+
+ private hasPendingTeardown(record: IPluginLifecycleRecord<TData, TPlugin>) {
+ return record.removalDeadline !== undefined || record.tasks.some((task) =>
+ task.kind === "reload" || task.kind === "unload" || task.kind === "uninstall");
+ }
+
+ private hasPendingUninstall(record: IPluginLifecycleRecord<TData, TPlugin>) {
+ return record.tasks.some((task) => task.kind === "uninstall" && !task.uninstallHandled);
+ }
+
+ private markPendingUninstallsHandled(record: IPluginLifecycleRecord<TData, TPlugin>,
+ current: IPluginLifecycleTask<TData>) {
+ if (current.kind === "uninstall") {
+ current.uninstallHandled = true;
+ }
+ record.tasks.forEach((task) => {
+ if (task.kind === "uninstall") {
+ task.uninstallHandled = true;
+ }
+ });
+ }
+
+ private isLoadTaskObsolete(record: IPluginLifecycleRecord<TData, TPlugin>,
+ task: IPluginLifecycleTask<TData>, reload: boolean) {
+ if (task.sequence >= record.lastStructuralSequence) {
+ return false;
+ }
+ if (!reload) {
+ return true;
+ }
+ return record.latestStructuralKind !== "load";
+ }
+
+ private dropPendingDataChanges(record: IPluginLifecycleRecord<TData, TPlugin>) {
+ record.tasks = record.tasks.filter((task) => {
+ if (task.kind !== "dataChange") {
+ return true;
+ }
+ task.waiters.forEach((resolve) => resolve());
+ return false;
+ });
+ }
+
+ private isStructural(kind: TPluginLifecycleTaskKind): kind is TPluginStructuralTaskKind {
+ return kind === "load" || kind === "reload" || kind === "unload" || kind === "uninstall";
+ }
+}
diff --git a/app/src/plugin/loader.ts b/app/src/plugin/loader.ts
index 38c2632cb5..e5e2631046 100644
--- a/app/src/plugin/loader.ts
+++ b/app/src/plugin/loader.ts
@@ -1,6 +1,6 @@
import {fetchSyncPost} from "../util/fetch";
import type {App} from "../index";
-import {Plugin} from "./index";
+import {markPluginDisposed, Plugin} from "./index";
/// #if !MOBILE
import {resizeTopBar, saveLayout} from "../layout/util";
import {getDockByType} from "../layout/tabUtil";
@@ -13,11 +13,12 @@ import {
import {API} from "./API";
import {getFrontend, isMobile, isWindow} from "../util/functions";
import {Constants} from "../constants";
-import {uninstall} from "./uninstall";
+import {destroyPlugin} from "./uninstall";
import {setStorageVal} from "../protyle/util/compatibility";
import {getAllEditor} from "../layout/getAll";
import {getPluginDockEntryKey, refreshDockCatalog} from "../config/entryVisibility/catalog";
import {applyDockEntryVisibility, isEntryVisible} from "../config/entryVisibility/runtime";
+import {PluginLifecycleCoordinator} from "./lifecycle";
const requireFunc = (key: string) => {
const modules = {
@@ -35,62 +36,99 @@ const runCode = (code: string, sourceURL: string) => {
return window.eval("(function anonymous(require, module, exports){".concat(code, "\n})\n//# sourceURL=").concat(sourceURL, "\n"));
};
-const pluginLoadPromises = new WeakMap<Plugin, Promise<void>>();
+const lifecycleManagers = new WeakMap<App, PluginLifecycleCoordinator<IPluginData, Plugin>>();
-export const loadPlugins = async (app: App, names?: string[], init = true) => {
- const response = await fetchSyncPost("/api/petal/loadPetals", {frontend: getFrontend()});
- const pluginsStyle = getPluginsStyle();
- for (let i = 0; i < response.data.length; i++) {
- const item = response.data[i] as IPluginData;
- if (!names || (names && names.includes(item.name))) {
- // 先插入 CSS,避免 onload 里插入的 DOM 在样式生效前先按无样式排版
- insertPluginCSS(item, pluginsStyle);
- if (init) {
- // 初始化时为加快启动速度,已特殊处理,不进行 await
- loadPluginJS(app, item);
- } else {
- await loadPluginJS(app, item);
- }
- }
- }
-};
-
-const loadPluginJS = async (app: App, item: IPluginData) => {
+const createPlugin = (app: App, item: IPluginData) => {
const exportsObj: { [key: string]: any } = {};
const moduleObj = {exports: exportsObj};
try {
runCode(item.js, "plugin:" + encodeURIComponent(item.name))(requireFunc, moduleObj, exportsObj);
- } catch (e) {
- console.error(`plugin ${item.name} run error:`, e);
+ } catch (error) {
+ document.getElementById("pluginsStyle" + item.name)?.remove();
+ console.error(`plugin ${item.name} run error:`, error);
return;
}
const pluginClass = (moduleObj.exports || exportsObj).default || moduleObj.exports;
if (typeof pluginClass !== "function") {
+ document.getElementById("pluginsStyle" + item.name)?.remove();
console.error(`plugin ${item.name} has no export`);
return;
}
if (!(pluginClass.prototype instanceof Plugin)) {
+ document.getElementById("pluginsStyle" + item.name)?.remove();
console.error(`plugin ${item.name} does not extends Plugin`);
return;
}
- const plugin = new pluginClass({
- app,
- displayName: item.displayName,
- name: item.name,
- i18n: item.i18n
- }) as Plugin;
- app.plugins.push(plugin);
- const loadPromise = (async () => {
- try {
- await plugin.onload();
- } catch (e) {
- console.error(`plugin ${item.name} onload error:`, e);
- }
- await plugin.kernel.init();
- })();
- pluginLoadPromises.set(plugin, loadPromise);
- await loadPromise;
- return plugin;
+ try {
+ const plugin = new pluginClass({
+ app,
+ displayName: item.displayName,
+ name: item.name,
+ i18n: item.i18n
+ }) as Plugin;
+ insertPluginCSS(item, getPluginsStyle());
+ return plugin;
+ } catch (error) {
+ document.getElementById("pluginsStyle" + item.name)?.remove();
+ throw error;
+ }
+};
+
+const getLifecycleManager = (app: App) => {
+ let manager = lifecycleManagers.get(app);
+ if (manager) {
+ return manager;
+ }
+ manager = new PluginLifecycleCoordinator<IPluginData, Plugin>({
+ create: (item) => createPlugin(app, item),
+ attach: (plugin) => {
+ if (app.plugins.some((item) => item.name === plugin.name)) {
+ throw new Error(`plugin ${plugin.name} has already been loaded`);
+ }
+ app.plugins.push(plugin);
+ },
+ onload: (plugin) => plugin.onload(),
+ init: (plugin) => plugin.kernel.init(),
+ onLayoutReady: (plugin) => plugin.onLayoutReady(),
+ mount: (plugin) => mountPlugin(plugin),
+ onDataChanged: (plugin) => plugin.onDataChanged(),
+ onunload: (plugin) => plugin.onunload(),
+ uninstall: (plugin) => plugin.uninstall(),
+ markDisposed: (plugin) => markPluginDisposed(plugin),
+ dispose: (plugin, isUninstall) => destroyPlugin(app, plugin, isUninstall),
+ onError: (name, hook, error) => console.error(`plugin ${name} ${hook} error:`, error),
+ });
+ lifecycleManagers.set(app, manager);
+ return manager;
+};
+
+const createPluginDataLoader = () => {
+ let promise: Promise<IPluginData[]>;
+ return (name: string) => {
+ promise ??= fetchSyncPost("/api/petal/loadPetals", {frontend: getFrontend()}).then(response => response.data);
+ return promise.then(items => items.find(item => item.name === name));
+ };
+};
+
+export const loadPlugins = async (app: App, names?: string[], init = true) => {
+ const manager = getLifecycleManager(app);
+ let tasks: Promise<void>[];
+ let shouldStart = true;
+ if (names) {
+ const loadPluginData = createPluginDataLoader();
+ tasks = Array.from(new Set(names)).map(name => manager.requestLoad(name, () => loadPluginData(name)));
+ } else {
+ const batch = manager.beginLoadBatch(!manager.isStarted());
+ const response = await fetchSyncPost("/api/petal/loadPetals", {frontend: getFrontend()});
+ tasks = (response.data as IPluginData[]).map(item => manager.requestBatchLoad(item.name, item, batch));
+ shouldStart = manager.isLatestLoadBatch(batch);
+ }
+ if (shouldStart) {
+ manager.start();
+ }
+ if (!init) {
+ await Promise.all(tasks);
+ }
};
const getPluginsStyle = () => {
@@ -104,6 +142,7 @@ const getPluginsStyle = () => {
};
const insertPluginCSS = (item: IPluginData, pluginsStyle: HTMLElement) => {
+ document.getElementById("pluginsStyle" + item.name)?.remove();
if (!item.css) {
return;
}
@@ -115,14 +154,14 @@ const insertPluginCSS = (item: IPluginData, pluginsStyle: HTMLElement) => {
// 启用插件
export const loadPlugin = async (app: App, item: IPluginData) => {
- insertPluginCSS(item, getPluginsStyle());
- const plugin = await loadPluginJS(app, item);
- afterLoadPlugin(plugin);
+ const manager = getLifecycleManager(app);
+ manager.start();
+ await manager.requestLoad(item.name, async () => item);
saveLayout();
getAllEditor().forEach(editor => {
editor.protyle.toolbar.update(editor.protyle);
});
- return plugin;
+ return manager.getInstance(item.name);
};
const updateDock = (dockItem: Config.IUILayoutDockTab[], index: number, plugin: Plugin, type: string) => {
@@ -152,13 +191,7 @@ const updateDock = (dockItem: Config.IUILayoutDockTab[], index: number, plugin:
});
};
-export const afterLoadPlugin = (plugin: Plugin) => {
- try {
- plugin.onLayoutReady();
- } catch (e) {
- console.error(`plugin ${plugin.name} onLayoutReady error:`, e);
- }
-
+const mountPlugin = (plugin: Plugin) => {
if (!isWindow() || isMobile()) {
plugin.topBarIcons.forEach(element => {
if (document.contains(element)) {
@@ -194,16 +227,8 @@ export const afterLoadPlugin = (plugin: Plugin) => {
};
export const afterLayoutReady = (app: App) => {
- app.plugins.forEach((plugin) => {
- const loadPromise = pluginLoadPromises.get(plugin);
- if (loadPromise) {
- loadPromise.then(() => {
- afterLoadPlugin(plugin);
- });
- } else {
- afterLoadPlugin(plugin);
- }
- });
+ const manager = getLifecycleManager(app);
+ void manager.setLayoutReady();
};
const getPluginCatalogPlugins = (plugin: Plugin) => window.siyuan.ws?.app?.plugins || [plugin];
@@ -289,38 +314,47 @@ export const reloadPlugin = async (app: App, data: {
reloadPlugins?: string[], // 插件启用,或插件代码变更
dataChangePlugins?: string[], // 插件存储数据变更
} = {}) => {
- const {uninstallPlugins = [], unloadPlugins = [], reloadPlugins = [], dataChangePlugins = []} = data;
- // 禁用
- unloadPlugins.forEach((item) => {
- uninstall(app, item, true);
- });
- // 卸载
- uninstallPlugins.forEach((item) => {
- uninstall(app, item, false);
- });
- reloadPlugins.forEach((item) => {
- uninstall(app, item, true);
- });
- loadPlugins(app, reloadPlugins, false).then(() => {
- app.plugins.forEach(item => {
- if (reloadPlugins.includes(item.name)) {
- afterLoadPlugin(item);
- getAllEditor().forEach(editor => {
- editor.protyle.toolbar.update(editor.protyle);
- });
- }
- });
- });
- app.plugins.forEach(item => {
- if (dataChangePlugins.includes(item.name)) {
- try {
- item.onDataChanged();
- } catch (e) {
- console.error(`plugin ${item.name} onDataChanged error:`, e);
- }
+ const manager = getLifecycleManager(app);
+ const uninstallNames = new Set(data.uninstallPlugins || []);
+ const unloadNames = new Set((data.unloadPlugins || []).filter(name => !uninstallNames.has(name)));
+ const reloadNames = new Set((data.reloadPlugins || []).filter(name =>
+ !uninstallNames.has(name) && !unloadNames.has(name)));
+ const dataChangeNames = new Set((data.dataChangePlugins || []).filter(name =>
+ !uninstallNames.has(name) && !unloadNames.has(name) && !reloadNames.has(name)));
+ const defaultReloadNames = new Set<string>();
+ dataChangeNames.forEach(name => {
+ const plugin = manager.getInstance(name);
+ if (plugin && plugin.onDataChanged === Plugin.prototype.onDataChanged) {
+ defaultReloadNames.add(name);
}
});
+ defaultReloadNames.forEach(name => dataChangeNames.delete(name));
+ const loadPluginData = createPluginDataLoader();
+ const tasks: Promise<void>[] = [];
+ uninstallNames.forEach(name => tasks.push(manager.requestUninstall(name)));
+ unloadNames.forEach(name => tasks.push(manager.requestUnload(name)));
+ reloadNames.forEach(name => tasks.push(manager.requestReload(name, () => loadPluginData(name))));
+ defaultReloadNames.forEach(name => tasks.push(manager.requestReload(name, () => loadPluginData(name))));
+ dataChangeNames.forEach(name => tasks.push(manager.requestDataChange(name)));
+ await Promise.all(tasks);
+ if (reloadNames.size > 0 || defaultReloadNames.size > 0) {
+ getAllEditor().forEach(editor => {
+ editor.protyle.toolbar.update(editor.protyle);
+ });
+ }
/// #if !MOBILE
saveLayout();
/// #endif
};
+
+export const unloadPlugin = async (app: App, name: string) => {
+ const manager = getLifecycleManager(app);
+ manager.start();
+ await manager.requestUnload(name);
+};
+
+export const uninstallPlugin = async (app: App, name: string) => {
+ const manager = getLifecycleManager(app);
+ manager.start();
+ await manager.requestUninstall(name);
+};
diff --git a/app/src/plugin/uninstall.ts b/app/src/plugin/uninstall.ts
index 9209ee7815..bc454d2503 100644
--- a/app/src/plugin/uninstall.ts
+++ b/app/src/plugin/uninstall.ts
@@ -1,5 +1,5 @@
import type {App} from "../index";
-import {Plugin} from "./index";
+import type {Plugin} from "./index";
/// #if !MOBILE
import {getAllModels} from "../layout/getAll";
import {resizeTopBar} from "../layout/util";
@@ -15,66 +15,72 @@ import {unregisterCapability} from "../layout/dock/agent/frontendCapabilities";
import {cancelAssetUploadsByPlugin} from "../protyle/upload/pluginEvent";
import {removeBreadcrumbButtons} from "./breadcrumbButton";
import {refreshDockCatalog} from "../config/entryVisibility/catalog";
+import {isWindow} from "../util/functions";
-export const uninstall = (app: App, name: string, isReload: boolean) => {
- app.plugins.find((plugin: Plugin, index) => {
- if (plugin.name === name) {
- cancelAssetUploadsByPlugin(plugin);
- try {
- plugin.onunload();
- } catch (e) {
- console.error(`plugin ${plugin.name} onunload error:`, e);
- }
- try {
- plugin.kernel.destroy();
- } catch (e) {
- console.error(`plugin ${plugin.name} kernel destroy error:`, e);
- }
- if (!isReload) {
- try {
- plugin.uninstall();
- } catch (e) {
- console.error(`plugin ${plugin.name} uninstall error:`, e);
- }
- }
- plugin.eventBus.destroy();
- if (!isReload) {
- window.siyuan.storage[Constants.LOCAL_PLUGIN_DOCKS][plugin.name] = {};
- setStorageVal(Constants.LOCAL_PLUGIN_DOCKS, window.siyuan.storage[Constants.LOCAL_PLUGIN_DOCKS]);
+const runCleanup = (plugin: Plugin, step: string, callback: () => unknown) => {
+ try {
+ const result = callback();
+ if (result && typeof (result as Promise<void>).then === "function") {
+ void Promise.resolve(result).catch(error => {
+ console.error(`plugin ${plugin.name} ${step} cleanup error:`, error);
+ });
+ }
+ } catch (error) {
+ console.error(`plugin ${plugin.name} ${step} cleanup error:`, error);
+ }
+};
+
+export const destroyPlugin = (app: App, plugin: Plugin, isUninstall: boolean) => {
+ runCleanup(plugin, "asset upload", () => cancelAssetUploadsByPlugin(plugin));
+ runCleanup(plugin, "kernel", () => plugin.kernel.destroy());
+ runCleanup(plugin, "event bus", () => plugin.eventBus.destroy());
+ if (isUninstall) {
+ runCleanup(plugin, "dock storage", () => {
+ const pluginDocks = window.siyuan.storage?.[Constants.LOCAL_PLUGIN_DOCKS] || {};
+ pluginDocks[plugin.name] = {};
+ if (window.siyuan.storage) {
+ window.siyuan.storage[Constants.LOCAL_PLUGIN_DOCKS] = pluginDocks;
}
- // rm tab
- /// #if !MOBILE
- const modelsKeys = Object.keys(plugin.models);
- getAllModels().custom.forEach(custom => {
- if (modelsKeys.includes(custom.type)) {
- if (isReload) {
- if (custom.update) {
- custom.update();
- }
- } else {
+ setStorageVal(Constants.LOCAL_PLUGIN_DOCKS, pluginDocks);
+ });
+ }
+ // 移除插件页签。
+ /// #if !MOBILE
+ runCleanup(plugin, "custom tabs", () => {
+ const modelsKeys = Object.keys(plugin.models);
+ getAllModels().custom.forEach(custom => {
+ if (modelsKeys.includes(custom.type)) {
+ runCleanup(plugin, "custom tab", () => {
+ if (isUninstall) {
custom.parent.parent.removeTab(custom.parent.id);
+ } else if (custom.update) {
+ return custom.update();
}
- }
- });
- /// #endif
- // rm topBar
- for (let i = 0; i < plugin.topBarIcons.length; i++) {
- const item = plugin.topBarIcons[i];
- item.remove();
- plugin.topBarIcons.splice(i, 1);
- i--;
+ });
}
- removeBreadcrumbButtons(plugin.name);
- // 移除插件注册的 Agent 能力
- plugin.agentCapabilities.forEach((capability) => unregisterCapability(capability.id, capability.generation));
- /// #if !MOBILE
- // rm statusBar
- plugin.statusBarIcons.forEach(item => {
- item.remove();
- });
- // rm dock
- const docksKeys = Object.keys(plugin.docks);
- docksKeys.forEach(key => {
+ });
+ });
+ /// #endif
+ // 移除顶栏按钮。
+ runCleanup(plugin, "top bar", () => {
+ plugin.topBarIcons.forEach(item => runCleanup(plugin, "top bar", () => item.remove()));
+ plugin.topBarIcons.length = 0;
+ });
+ runCleanup(plugin, "breadcrumb", () => removeBreadcrumbButtons(plugin.name));
+ // 移除插件注册的 Agent 能力。
+ runCleanup(plugin, "agent capability", () => {
+ plugin.agentCapabilities.forEach((capability) => runCleanup(plugin, "agent capability", () =>
+ unregisterCapability(capability.id, capability.generation)));
+ });
+ /// #if !MOBILE
+ // 移除状态栏元素。
+ runCleanup(plugin, "status bar", () => {
+ plugin.statusBarIcons.forEach(item => runCleanup(plugin, "status bar", () => item.remove()));
+ });
+ // 移除插件停靠栏。
+ runCleanup(plugin, "dock", () => {
+ Object.keys(plugin.docks).forEach(key => {
+ runCleanup(plugin, "dock", () => {
if (window.siyuan.layout.leftDock && Object.keys(window.siyuan.layout.leftDock.data).includes(key)) {
window.siyuan.layout.leftDock.remove(key);
} else if (window.siyuan.layout.rightDock && Object.keys(window.siyuan.layout.rightDock.data).includes(key)) {
@@ -83,50 +89,61 @@ export const uninstall = (app: App, name: string, isReload: boolean) => {
window.siyuan.layout.bottomDock.remove(key);
}
});
- resizeTopBar();
- setTabPosition(true);
- /// #endif
- // rm plugin
- app.plugins.splice(index, 1);
- refreshDockCatalog(app.plugins);
- /// #if MOBILE
- // 移动端卸载插件后,若无任何插件 dock 则隐藏插件入口图标
- if (app.plugins.every(p => Object.keys(p.docks).length === 0)) {
- const pluginTabElement = document.querySelector("[data-type='sidebar-plugin-tab']");
- pluginTabElement?.classList.add("fn__none");
- if (pluginTabElement?.classList.contains("toolbar__icon--active")) {
- const fallbackTabElement = pluginTabElement.parentElement.querySelector<HTMLElement>(
- "[data-type$='-tab']:not(.fn__none)"
- );
- if (fallbackTabElement) {
- fallbackTabElement.dispatchEvent(new MouseEvent("click", {bubbles: true}));
- } else {
- pluginTabElement.classList.remove("toolbar__icon--active");
- document.querySelector("[data-type='sidebar-plugin']")?.classList.add("fn__none");
- (pluginTabElement.closest(".side-panel") as HTMLElement).style.transform = "";
+ });
+ });
+ runCleanup(plugin, "top bar layout", () => resizeTopBar());
+ runCleanup(plugin, "tab layout", () => setTabPosition(true));
+ /// #endif
+ const index = app.plugins.indexOf(plugin);
+ if (index > -1) {
+ app.plugins.splice(index, 1);
+ }
+ runCleanup(plugin, "dock catalog", () => refreshDockCatalog(app.plugins));
+ /// #if MOBILE
+ // 移动端卸载插件后,若无任何插件停靠栏则隐藏插件入口图标。
+ runCleanup(plugin, "mobile plugin entry", () => {
+ if (app.plugins.every(item => Object.keys(item.docks).length === 0)) {
+ const pluginTabElement = document.querySelector("[data-type='sidebar-plugin-tab']");
+ pluginTabElement?.classList.add("fn__none");
+ if (pluginTabElement?.classList.contains("toolbar__icon--active")) {
+ const fallbackTabElement = pluginTabElement.parentElement?.querySelector<HTMLElement>(
+ "[data-type$='-tab']:not(.fn__none)"
+ );
+ if (fallbackTabElement) {
+ fallbackTabElement.dispatchEvent(new MouseEvent("click", {bubbles: true}));
+ } else {
+ pluginTabElement.classList.remove("toolbar__icon--active");
+ document.querySelector("[data-type='sidebar-plugin']")?.classList.add("fn__none");
+ const sidePanel = pluginTabElement.closest<HTMLElement>(".side-panel");
+ if (sidePanel) {
+ sidePanel.style.transform = "";
}
}
}
- /// #endif
- // rm icons
- document.querySelector(`svg[data-name="${plugin.name}"]`)?.remove();
- // rm protyle toolbar
- getAllEditor().forEach(editor => {
- editor.protyle.toolbar.update(editor.protyle);
- });
- // rm style
- document.getElementById("pluginsStyle" + name)?.remove();
- /// #if !BROWSER
+ }
+ });
+ /// #endif
+ runCleanup(plugin, "icons", () => document.querySelector(`svg[data-name="${plugin.name}"]`)?.remove());
+ runCleanup(plugin, "editor toolbar", () => {
+ getAllEditor().forEach(editor => {
+ runCleanup(plugin, "editor toolbar", () => editor.protyle.toolbar.update(editor.protyle));
+ });
+ });
+ runCleanup(plugin, "style", () => document.getElementById("pluginsStyle" + plugin.name)?.remove());
+ /// #if !BROWSER
+ if (!isWindow()) {
+ runCleanup(plugin, "global shortcut", () => {
plugin.commands.forEach(command => {
if (command.globalCallback && command.customHotkey) {
- ipcRenderer.send(Constants.SIYUAN_CMD, {
- cmd: "unregisterGlobalShortcut",
- accelerator: command.customHotkey
+ runCleanup(plugin, "global shortcut", () => {
+ ipcRenderer.send(Constants.SIYUAN_CMD, {
+ cmd: "unregisterGlobalShortcut",
+ accelerator: command.customHotkey
+ });
});
}
});
- /// #endif
- return true;
- }
- });
+ });
+ }
+ /// #endif
};
diff --git a/app/src/window/closeWin.ts b/app/src/window/closeWin.ts
index a4d93a9a51..84c63bec84 100644
--- a/app/src/window/closeWin.ts
+++ b/app/src/window/closeWin.ts
@@ -1,20 +1,9 @@
import type {App} from "../index";
import {Constants} from "../constants";
-import { ipcRenderer } from "electron";
+import {ipcRenderer} from "electron";
+import {destroyWindowPluginKernels} from "./closeWinCore";
-export const closeWindow = async (app: App) => {
- for (let i = 0; i < app.plugins.length; i++) {
- const plugin = app.plugins[i];
- try {
- await plugin.onunload();
- } catch (e) {
- console.error(e);
- }
- try {
- await plugin.kernel?.destroy();
- } catch (e) {
- console.error(e);
- }
- }
+export const closeWindow = (app: App) => {
+ destroyWindowPluginKernels(app.plugins, error => console.error(error));
ipcRenderer.send(Constants.SIYUAN_CMD, "destroy");
};
diff --git a/app/src/window/closeWinCore.test.ts b/app/src/window/closeWinCore.test.ts
new file mode 100644
index 0000000000..dbb1a658fc
--- /dev/null
+++ b/app/src/window/closeWinCore.test.ts
@@ -0,0 +1,52 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {destroyWindowPluginKernels} from "./closeWinCore";
+
+describe("independent window plugin cleanup", () => {
+ it("destroys every kernel without invoking lifecycle hooks", () => {
+ let destroyed = 0;
+ let lifecycleCalls = 0;
+ const plugins = [1, 2].map(() => ({
+ kernel: {
+ destroy() {
+ destroyed++;
+ },
+ },
+ onunload() {
+ lifecycleCalls++;
+ },
+ uninstall() {
+ lifecycleCalls++;
+ },
+ }));
+
+ destroyWindowPluginKernels(plugins, () => undefined);
+
+ assert.equal(destroyed, 2);
+ assert.equal(lifecycleCalls, 0);
+ });
+
+ it("does not wait for pending destruction", async () => {
+ let finished = false;
+ const pending = new Promise<void>(() => undefined);
+
+ destroyWindowPluginKernels([{kernel: {destroy: () => pending}}], () => undefined);
+ finished = true;
+
+ assert.equal(finished, true);
+ });
+
+ it("observes synchronous and asynchronous destruction errors", async () => {
+ const errors: string[] = [];
+ destroyWindowPluginKernels([
+ {kernel: {destroy: () => {
+ throw new Error("sync");
+ }}},
+ {kernel: {destroy: () => Promise.reject(new Error("async"))}},
+ ], error => errors.push((error as Error).message));
+
+ await Promise.resolve();
+
+ assert.deepEqual(errors.sort(), ["async", "sync"]);
+ });
+});
diff --git a/app/src/window/closeWinCore.ts b/app/src/window/closeWinCore.ts
new file mode 100644
index 0000000000..27d3d35570
--- /dev/null
+++ b/app/src/window/closeWinCore.ts
@@ -0,0 +1,15 @@
+interface IWindowPluginKernel {
+ kernel?: {
+ destroy: () => Promise<void> | void;
+ };
+}
+
+export const destroyWindowPluginKernels = (plugins: IWindowPluginKernel[], onError: (error: unknown) => void) => {
+ plugins.forEach(plugin => {
+ try {
+ void Promise.resolve(plugin.kernel?.destroy()).catch(onError);
+ } catch (error) {
+ onError(error);
+ }
+ });
+};
diff --git a/kernel/api/setting.go b/kernel/api/setting.go
index 4109cde217..c6ff5e4e92 100644
--- a/kernel/api/setting.go
+++ b/kernel/api/setting.go
@@ -43,7 +43,6 @@ func setEditorReadOnly(c *gin.Context) {
if !ok {
return
}
-
readOnly := arg["readonly"].(bool)
oldReadOnly := model.Conf.Editor.ReadOnly
@@ -146,6 +145,8 @@ func setBazaar(c *gin.Context) {
if !ok {
return
}
+ app, _ := arg["app"].(string)
+ delete(arg, "app")
param, err := gulu.JSON.MarshalJSON(arg)
if err != nil {
@@ -164,6 +165,7 @@ func setBazaar(c *gin.Context) {
petalsEnabled := model.IsPetalsEnabled()
model.Conf.Bazaar = bazaar
model.Conf.Save()
+ util.BroadcastByType("main", "setConf", 0, "", model.Conf)
newPetalsEnabled := model.IsPetalsEnabled()
if petalsEnabled != newPetalsEnabled {
if newPetalsEnabled {
@@ -173,6 +175,7 @@ func setBazaar(c *gin.Context) {
} else if model.OnKernelPluginsStop != nil {
model.OnKernelPluginsStop()
}
+ model.PushReloadAllEnabledPlugins(newPetalsEnabled, app)
}
ret.Data = bazaar
diff --git a/kernel/model/push_reload.go b/kernel/model/push_reload.go
index ed97a6b444..3921035362 100644
--- a/kernel/model/push_reload.go
+++ b/kernel/model/push_reload.go
@@ -94,6 +94,24 @@ func PushReloadPlugin(uninstallPluginNameSet, unloadPluginNameSet, reloadPluginS
util.BroadcastByTypeAndExcludeApp(excludeApp, "main", "reloadPlugin", 0, "", payload)
}
+// PushReloadAllEnabledPlugins 向所有其他前端推送已启用插件的全局启用或禁用状态。
+func PushReloadAllEnabledPlugins(enabled bool, excludeApp string) {
+ pluginNameSet := hashset.New()
+ for _, petal := range getPetals() {
+ if petal.Enabled {
+ pluginNameSet.Add(petal.Name)
+ }
+ }
+ if pluginNameSet.Empty() {
+ return
+ }
+ if enabled {
+ PushReloadPlugin(nil, nil, pluginNameSet, nil, excludeApp)
+ } else {
+ PushReloadPlugin(nil, pluginNameSet, nil, nil, excludeApp)
+ }
+}
+
func refreshDocInfo(tree *parse.Tree) {
if nil == tree {
return