Skip to content

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

:art: Improve global plugin lifecycle synchronization https://github.com/siyuan-note/siyuan/issues/19057

Daniel262e028572de
diff --git a/app/src/config/bazaar.ts b/app/src/config/bazaar.ts
index c20417f9da..53304d16da 100644
--- a/app/src/config/bazaar.ts
+++ b/app/src/config/bazaar.ts
@@ -2,9 +2,6 @@ import {showMessage} from "../dialog/message";
import {fetchPost} from "../util/fetch";
import {confirmDialog} from "../dialog/confirmDialog";
import {highlightRender} from "../protyle/render/highlightRender";
-/// #if !MOBILE
-import {saveLayout} from "../layout/util";
-/// #endif
import {Constants} from "../constants";
/// #if !BROWSER
import * as path from "path";
@@ -16,7 +13,8 @@ import {Plugin} from "../plugin";
import type {App} from "../index";
import {escapeAttr, escapeHtml} from "../util/escape";
import {formatCount} from "../util/number";
-import {loadPlugin, loadPlugins, unloadPlugin} from "../plugin/loader";
+import {loadPlugin, unloadPlugin} from "../plugin/loader";
+import {setGlobalPluginsDisabled, subscribeGlobalPluginState} from "../plugin/globalState";
import {useShell} from "../util/pathName";
import {switchSettingPanelSubTab} from "./setting/mount";
import {isThemeFrontendSupported} from "../util/themeCompatibility";
@@ -110,6 +108,12 @@ export const bazaar = {
_updateRequestID: 0,
_localPackageUploading: false,
_pluginEnablePending: new Set<string>(),
+ _downloadedPluginsReady: false,
+ _pluginGlobalRequestPending: false,
+ _pluginGlobalLifecyclePending: false,
+ _pluginGlobalRequestID: 0,
+ _lastGlobalPluginSettledRevision: -1,
+ _globalPluginStateUnsubscribe: undefined as (() => void) | undefined,
_ratingUserID: "",
_ratingUserChangeHandler: undefined as (() => void) | undefined,
_activateMount(element: HTMLElement, force = false) {
@@ -122,6 +126,13 @@ export const bazaar = {
_invalidateMount() {
this._mountGeneration++;
this._updateRequestID++;
+ this._pluginGlobalRequestID++;
+ this._downloadedPluginsReady = false;
+ this._pluginGlobalRequestPending = false;
+ this._pluginGlobalLifecyclePending = false;
+ this._lastGlobalPluginSettledRevision = -1;
+ this._globalPluginStateUnsubscribe?.();
+ this._globalPluginStateUnsubscribe = undefined;
this._data.deprecationMetadata.clear();
this._data.deprecationTypesLoaded.clear();
this._data.deprecationTypesLoading.clear();
@@ -154,6 +165,20 @@ export const bazaar = {
return this._isMountCurrent(mount) && (mount.requestID === undefined ||
this._bazaarRequestIDs.get(bazaarType) === mount.requestID);
},
+ _syncPluginGlobalSwitch() {
+ const switchElement = this.element?.querySelector('[data-type="plugins-enable"]') as HTMLInputElement;
+ if (!switchElement) {
+ return;
+ }
+ const petalDisabled = this._pluginGlobalRequestPending ?
+ !switchElement.checked : window.siyuan.config.bazaar.petalDisabled;
+ if (!this._pluginGlobalRequestPending) {
+ switchElement.checked = !petalDisabled;
+ }
+ switchElement.disabled = !this._downloadedPluginsReady || this._pluginGlobalRequestPending ||
+ this._pluginGlobalLifecyclePending;
+ switchElement.setAttribute("aria-label", window.siyuan.languages[petalDisabled ? "enable" : "disableAll"]);
+ },
genHTML() {
if (!window.siyuan.config.bazaar.trust) {
return `<div class="config-bazaar__trust fn__flex-column" style="margin: 0 48px;">
@@ -249,7 +274,7 @@ export const bazaar = {
<input class="b3-form__upload" data-type="local-package-file" type="file" accept=".zip,application/zip">
</label>
<button class="b3-button fn__none" data-type="install-all">${window.siyuan.languages.updateAll}</button>
- <input ${window.siyuan.config.bazaar.petalDisabled ? "" : " checked"} data-type="plugins-enable" data-position="north" type="checkbox" class="b3-switch fn__flex-center ariaLabel" aria-label="${window.siyuan.languages[window.siyuan.config.bazaar.petalDisabled ? "enable" : "disableAll"]}">
+ <input ${window.siyuan.config.bazaar.petalDisabled ? "" : " checked"} data-type="plugins-enable" data-position="north" type="checkbox" class="b3-switch fn__flex-center ariaLabel" aria-label="${window.siyuan.languages[window.siyuan.config.bazaar.petalDisabled ? "enable" : "disableAll"]}" disabled>
<div class="counter counter--bg fn__none fn__flex-center ariaLabel" data-position="north" aria-label="${window.siyuan.languages.total}"></div>
</div>
</div>
@@ -1007,6 +1032,10 @@ ${primaryAction ? '<div class="fn__hr"></div>' : ""}
typeBtn?.classList.contains("b3-button--outline")) {
return false;
}
+ if (bazaarType === "plugins") {
+ bazaar._downloadedPluginsReady = false;
+ bazaar._syncPluginGlobalSwitch();
+ }
bazaar._updateDownloadedToolbar(bazaarType);
contentElement.setAttribute("data-loading", "true");
const installedAPI: Record<TBazaarType, string> = {
@@ -1117,6 +1146,10 @@ type="checkbox">
bazaar._data.downloaded = packages;
bazaar._data.downloadedType = bazaarType;
contentElement.innerHTML = html ? html : `<ul class="b3-list b3-list--background"><li class="b3-list--empty">${window.siyuan.languages.emptyContent}</li></ul>`;
+ if (bazaarType === "plugins") {
+ bazaar._downloadedPluginsReady = true;
+ bazaar._syncPluginGlobalSwitch();
+ }
bazaar._loadDownloadedRatings(bazaarType, packageItems);
bazaar._loadDownloadedUserRatings(bazaarType, packageItems);
bazaar._loadDownloadedDeprecations(bazaarType, app);
@@ -2416,15 +2449,11 @@ type="checkbox">
app: Constants.SIYUAN_APPID,
}, (response) => {
window.siyuan.config.bazaar = response.data;
- void loadPlugins(app, null, false).then(() => {
- if (!bazaar._isMountCurrent(mount)) {
- return;
- }
- bazaar.element.innerHTML = bazaar.genHTML();
- bazaar.bindEvent(app);
- }).catch(error => {
- console.error(error);
- });
+ if (!bazaar._isMountCurrent(mount)) {
+ return;
+ }
+ bazaar.element.innerHTML = bazaar.genHTML();
+ bazaar.bindEvent(app);
});
});
return;
@@ -2438,6 +2467,25 @@ type="checkbox">
(["plugins", "themes", "icons", "templates", "widgets"] as TBazaarType[]).forEach((type) => {
this._data.update[type] = [];
});
+ this._downloadedPluginsReady = false;
+ this._pluginGlobalRequestPending = false;
+ this._pluginGlobalLifecyclePending = false;
+ let initialGlobalPluginState = true;
+ this._globalPluginStateUnsubscribe?.();
+ this._globalPluginStateUnsubscribe = subscribeGlobalPluginState(app, (state) => {
+ const shouldRefresh = !initialGlobalPluginState && !state.pending &&
+ state.revision > this._lastGlobalPluginSettledRevision;
+ this._pluginGlobalLifecyclePending = state.pending;
+ this._syncPluginGlobalSwitch();
+ if (!state.pending) {
+ this._lastGlobalPluginSettledRevision = Math.max(
+ this._lastGlobalPluginSettledRevision, state.revision);
+ }
+ initialGlobalPluginState = false;
+ if (shouldRefresh && bazaar._isMountCurrent(mount)) {
+ this._genMyHTML("plugins", app, true);
+ }
+ });
this._genMyHTML("plugins", app);
this._checkUpdate(true);
this._setLocalPackageUploading(this._localPackageUploading, mount);
@@ -2741,43 +2789,17 @@ type="checkbox">
break;
} else if (type === "plugins-enable") {
if (!target.getAttribute("disabled")) {
- target.setAttribute("disabled", "disabled");
- 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,
- app: Constants.SIYUAN_APPID,
- }, () => {
- const finish = () => {
- 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) {
- 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 {
- void loadPlugins(app, null, false).then(() => {
- if (bazaar._isMountCurrent(mount)) {
- this._genMyHTML("plugins", app, false);
- }
- /// #if !MOBILE
- saveLayout();
- /// #endif
- }).catch(error => {
- console.error(error);
- }).finally(finish);
+ const requestID = ++this._pluginGlobalRequestID;
+ this._pluginGlobalRequestPending = true;
+ this._syncPluginGlobalSwitch();
+ void setGlobalPluginsDisabled(app, !(target as HTMLInputElement).checked).catch((error) => {
+ console.error(error);
+ }).finally(() => {
+ if (requestID !== this._pluginGlobalRequestID) {
+ return;
}
+ this._pluginGlobalRequestPending = false;
+ this._syncPluginGlobalSwitch();
});
}
event.stopPropagation();
diff --git a/app/src/index.ts b/app/src/index.ts
index 2da6535b9b..94ffd1d4cd 100644
--- a/app/src/index.ts
+++ b/app/src/index.ts
@@ -36,7 +36,8 @@ import {getLocalStorage, isChromeBrowser, isInMobileApp, isIOSDevice} from "./pr
import {isBrowser} from "./util/functions";
import {checkPublishServiceClosed} from "./util/processMessage";
import {hideAllElements} from "./protyle/ui/hideElements";
-import {loadPlugins, reloadPlugin} from "./plugin/loader";
+import {loadPlugins} from "./plugin/loader";
+import {applyPluginReload, syncGlobalPluginConfig} from "./plugin/globalState";
import "./assets/scss/base.scss";
import {reloadEmoji} from "./emoji";
import {processIOSPurchaseResponse} from "./util/iOSPurchase";
@@ -109,7 +110,7 @@ export class App {
setRefDynamicText(data.data);
break;
case "reloadPlugin":
- reloadPlugin(this, data.data);
+ void applyPluginReload(this, data.data).catch((error) => console.error(error));
break;
case "reloadEmojiConf":
reloadEmoji();
@@ -126,6 +127,7 @@ export class App {
break;
case "setConf":
window.siyuan.config = data.data;
+ syncGlobalPluginConfig(this, data.data.bazaar.petalDisabled);
break;
case "setCloudUser":
applyCloudUserState(data.data.user, data.data.userName);
diff --git a/app/src/mobile/util/onMessage.ts b/app/src/mobile/util/onMessage.ts
index 063ce660e4..c15b3bcb75 100644
--- a/app/src/mobile/util/onMessage.ts
+++ b/app/src/mobile/util/onMessage.ts
@@ -8,7 +8,7 @@ import {
transactionError
} from "../../dialog/processSystem";
import type {App} from "../../index";
-import {reloadPlugin} from "../../plugin/loader";
+import {applyPluginReload, syncGlobalPluginConfig} from "../../plugin/globalState";
import {reloadEmoji} from "../../emoji";
import {renderSnippet} from "../../config/util/snippets";
import {redirectToCheckAuth} from "../../util/pathName";
@@ -70,7 +70,7 @@ export const onMessage = (app: App, data: IWebSocketData) => {
setRefDynamicText(data.data);
break;
case "reloadPlugin":
- reloadPlugin(app, data.data);
+ void applyPluginReload(app, data.data).catch((error) => console.error(error));
break;
case "reloadEmojiConf":
reloadEmoji();
@@ -80,6 +80,7 @@ export const onMessage = (app: App, data: IWebSocketData) => {
break;
case "setConf":
window.siyuan.config = data.data;
+ syncGlobalPluginConfig(app, data.data.bazaar.petalDisabled);
break;
case "setCloudUser":
applyCloudUserState(data.data.user, data.data.userName);
diff --git a/app/src/plugin/globalState.ts b/app/src/plugin/globalState.ts
new file mode 100644
index 0000000000..6f108208b5
--- /dev/null
+++ b/app/src/plugin/globalState.ts
@@ -0,0 +1,56 @@
+import type {App} from "../index";
+import {fetchSyncPost} from "../util/fetch";
+import {
+ GlobalPluginStateCoordinator,
+ type IGlobalPluginStatePayload,
+ type IGlobalPluginStateSnapshot,
+} from "./globalStateCoordinator";
+import {type IPluginReloadData, reloadPlugin} from "./loader";
+
+type TGlobalPluginReloadData = IPluginReloadData & IGlobalPluginStatePayload;
+
+const coordinators = new WeakMap<App, GlobalPluginStateCoordinator<TGlobalPluginReloadData>>();
+
+const getCoordinator = (app: App) => {
+ let coordinator = coordinators.get(app);
+ if (coordinator) {
+ return coordinator;
+ }
+ coordinator = new GlobalPluginStateCoordinator<TGlobalPluginReloadData>({
+ initialPetalDisabled: window.siyuan.config.bazaar.petalDisabled,
+ applyLifecycle: (payload) => reloadPlugin(app, payload),
+ applyConfig: (petalDisabled) => {
+ window.siyuan.config.bazaar.petalDisabled = petalDisabled;
+ },
+ });
+ coordinators.set(app, coordinator);
+ return coordinator;
+};
+
+const isGlobalPluginState = (data: IPluginReloadData): data is TGlobalPluginReloadData =>
+ typeof data.globalPetalEnabled === "boolean" &&
+ typeof data.globalPetalDisabled === "boolean" &&
+ typeof data.globalPetalRevision === "number" &&
+ typeof data.globalPetalChanged === "boolean";
+
+export const applyPluginReload = (app: App, data: IPluginReloadData = {}) => {
+ if (!isGlobalPluginState(data)) {
+ return reloadPlugin(app, data);
+ }
+ return getCoordinator(app).apply(data);
+};
+
+export const syncGlobalPluginConfig = (app: App, petalDisabled: boolean) => {
+ getCoordinator(app).syncConfig(petalDisabled);
+};
+
+export const subscribeGlobalPluginState = (app: App, listener: (state: IGlobalPluginStateSnapshot) => void) =>
+ getCoordinator(app).subscribe(listener);
+
+export const setGlobalPluginsDisabled = async (app: App, petalDisabled: boolean) => {
+ const response = await fetchSyncPost("/api/setting/setBazaarPetalDisabled", {petalDisabled});
+ if (response.code !== 0 || !response.data) {
+ throw new Error(response.msg || "Failed to update the global plugin state");
+ }
+ await applyPluginReload(app, response.data as TGlobalPluginReloadData);
+};
diff --git a/app/src/plugin/globalStateCoordinator.test.ts b/app/src/plugin/globalStateCoordinator.test.ts
new file mode 100644
index 0000000000..bb39d4cfe3
--- /dev/null
+++ b/app/src/plugin/globalStateCoordinator.test.ts
@@ -0,0 +1,93 @@
+import * as assert from "node:assert/strict";
+import {describe, it} from "node:test";
+import {GlobalPluginStateCoordinator, type IGlobalPluginStatePayload} from "./globalStateCoordinator";
+
+const deferred = () => {
+ let resolve!: () => void;
+ const promise = new Promise<void>((done) => {
+ resolve = done;
+ });
+ return {promise, resolve};
+};
+
+const payload = (revision: number, petalDisabled: boolean): IGlobalPluginStatePayload => ({
+ globalPetalEnabled: !petalDisabled,
+ globalPetalDisabled: petalDisabled,
+ globalPetalRevision: revision,
+ globalPetalChanged: true,
+});
+
+describe("global plugin state coordinator", () => {
+ it("applies each revision once and ignores older state", async () => {
+ const revisions: number[] = [];
+ const coordinator = new GlobalPluginStateCoordinator({
+ initialPetalDisabled: false,
+ applyLifecycle: async (state: IGlobalPluginStatePayload) => {
+ revisions.push(state.globalPetalRevision);
+ },
+ });
+
+ await coordinator.apply(payload(2, true));
+ await coordinator.apply(payload(2, true));
+ await coordinator.apply(payload(1, false));
+
+ assert.deepEqual(revisions, [2]);
+ });
+
+ it("keeps the latest revision pending until its lifecycle settles", async () => {
+ const first = deferred();
+ const second = deferred();
+ const snapshots: Array<{pending: boolean, revision: number}> = [];
+ const coordinator = new GlobalPluginStateCoordinator({
+ initialPetalDisabled: false,
+ applyLifecycle: (state: IGlobalPluginStatePayload) =>
+ state.globalPetalRevision === 1 ? first.promise : second.promise,
+ });
+ coordinator.subscribe((state) => snapshots.push({pending: state.pending, revision: state.revision}));
+
+ const firstApply = coordinator.apply(payload(1, true));
+ const secondApply = coordinator.apply(payload(2, false));
+ first.resolve();
+ await firstApply;
+ assert.deepEqual(snapshots.at(-1), {pending: true, revision: 2});
+
+ second.resolve();
+ await secondApply;
+ assert.deepEqual(snapshots.at(-1), {pending: false, revision: 2});
+ });
+
+ it("updates configuration state without starting a lifecycle transition", () => {
+ let lifecycleCalls = 0;
+ let latestDisabled = false;
+ const coordinator = new GlobalPluginStateCoordinator({
+ initialPetalDisabled: false,
+ applyLifecycle: async () => {
+ lifecycleCalls++;
+ },
+ });
+ coordinator.subscribe((state) => {
+ latestDisabled = state.petalDisabled;
+ });
+
+ coordinator.syncConfig(true);
+
+ assert.equal(latestDisabled, true);
+ assert.equal(lifecycleCalls, 0);
+ });
+
+ it("applies a changed broadcast that follows a same-revision no-change response", async () => {
+ const revisions: number[] = [];
+ const coordinator = new GlobalPluginStateCoordinator({
+ initialPetalDisabled: false,
+ applyLifecycle: async (state: IGlobalPluginStatePayload) => {
+ revisions.push(state.globalPetalRevision);
+ },
+ });
+ const unchanged = {...payload(3, true), globalPetalChanged: false};
+
+ await coordinator.apply(unchanged);
+ await coordinator.apply(payload(3, true));
+
+ assert.deepEqual(revisions, [3]);
+ });
+});
diff --git a/app/src/plugin/globalStateCoordinator.ts b/app/src/plugin/globalStateCoordinator.ts
new file mode 100644
index 0000000000..a45313a1ea
--- /dev/null
+++ b/app/src/plugin/globalStateCoordinator.ts
@@ -0,0 +1,99 @@
+export interface IGlobalPluginStatePayload {
+ globalPetalEnabled: boolean;
+ globalPetalDisabled: boolean;
+ globalPetalRevision: number;
+ globalPetalChanged: boolean;
+}
+
+export interface IGlobalPluginStateSnapshot {
+ petalDisabled: boolean;
+ pending: boolean;
+ revision: number;
+}
+
+interface IGlobalPluginStateCoordinatorOptions<TPayload extends IGlobalPluginStatePayload> {
+ initialPetalDisabled: boolean;
+ applyLifecycle: (payload: TPayload) => Promise<void>;
+ applyConfig?: (petalDisabled: boolean) => void;
+}
+
+export class GlobalPluginStateCoordinator<TPayload extends IGlobalPluginStatePayload> {
+ private readonly applyLifecycle: (payload: TPayload) => Promise<void>;
+ private readonly applyConfig: (petalDisabled: boolean) => void;
+ private readonly listeners = new Set<(state: IGlobalPluginStateSnapshot) => void>();
+ private revision = -1;
+ private lifecycleRevision = -1;
+ private petalDisabled: boolean;
+ private pending = false;
+ private transition?: {revision: number, promise: Promise<void>};
+
+ constructor(options: IGlobalPluginStateCoordinatorOptions<TPayload>) {
+ this.petalDisabled = options.initialPetalDisabled;
+ this.applyLifecycle = options.applyLifecycle;
+ this.applyConfig = options.applyConfig || (() => undefined);
+ }
+
+ public subscribe(listener: (state: IGlobalPluginStateSnapshot) => void) {
+ this.listeners.add(listener);
+ listener(this.snapshot());
+ return () => this.listeners.delete(listener);
+ }
+
+ public syncConfig(petalDisabled: boolean) {
+ this.petalDisabled = petalDisabled;
+ this.applyConfig(petalDisabled);
+ this.notify();
+ }
+
+ public apply(payload: TPayload) {
+ const revision = payload.globalPetalRevision;
+ if (!Number.isSafeInteger(revision) || revision < 0) {
+ return Promise.reject(new Error(`invalid global plugin state revision: ${revision}`));
+ }
+ if (revision < this.revision) {
+ return Promise.resolve();
+ }
+
+ this.petalDisabled = payload.globalPetalDisabled;
+ this.applyConfig(this.petalDisabled);
+ const isNewRevision = revision > this.revision;
+ if (isNewRevision) {
+ this.revision = revision;
+ }
+ if (!payload.globalPetalChanged) {
+ this.notify();
+ return this.transition?.revision === revision ? this.transition.promise : Promise.resolve();
+ }
+ if (this.lifecycleRevision >= revision) {
+ this.notify();
+ return this.transition?.revision === revision ? this.transition.promise : Promise.resolve();
+ }
+
+ this.lifecycleRevision = revision;
+ this.pending = true;
+ this.notify();
+ const promise = Promise.resolve().then(() => this.applyLifecycle(payload)).finally(() => {
+ if (this.revision !== revision) {
+ return;
+ }
+ this.pending = false;
+ this.transition = undefined;
+ this.notify();
+ });
+ this.transition = {revision, promise};
+ return promise;
+ }
+
+ private snapshot(): IGlobalPluginStateSnapshot {
+ return {
+ petalDisabled: this.petalDisabled,
+ pending: this.pending,
+ revision: this.revision,
+ };
+ }
+
+ private notify() {
+ const state = this.snapshot();
+ this.listeners.forEach((listener) => listener(state));
+ }
+}
diff --git a/app/src/plugin/loader.ts b/app/src/plugin/loader.ts
index 69162760d6..6b5a33745c 100644
--- a/app/src/plugin/loader.ts
+++ b/app/src/plugin/loader.ts
@@ -323,12 +323,18 @@ export const addPluginDock = (plugin: Plugin) => {
/// #endif
};
-export const reloadPlugin = async (app: App, data: {
+export interface IPluginReloadData {
uninstallPlugins?: string[], // 插件卸载
unloadPlugins?: string[], // 插件禁用
reloadPlugins?: string[], // 插件启用,或插件代码变更
dataChangePlugins?: string[], // 插件存储数据变更
-} = {}) => {
+ globalPetalEnabled?: boolean,
+ globalPetalDisabled?: boolean,
+ globalPetalRevision?: number,
+ globalPetalChanged?: boolean,
+}
+
+export const reloadPlugin = async (app: App, data: IPluginReloadData = {}) => {
const manager = getLifecycleManager(app);
const uninstallNames = new Set(data.uninstallPlugins || []);
const unloadNames = new Set((data.unloadPlugins || []).filter(name => !uninstallNames.has(name)));
diff --git a/app/src/window/index.ts b/app/src/window/index.ts
index 219ae4487c..e44964b12d 100644
--- a/app/src/window/index.ts
+++ b/app/src/window/index.ts
@@ -22,7 +22,8 @@ import {initMessage} from "../dialog/message";
import {getAllTabs} from "../layout/getAll";
import {getLocalStorage} from "../protyle/util/compatibility";
import {init} from "./init";
-import {loadPlugins, reloadPlugin} from "../plugin/loader";
+import {loadPlugins} from "../plugin/loader";
+import {applyPluginReload, syncGlobalPluginConfig} from "../plugin/globalState";
import {hideAllElements} from "../protyle/ui/hideElements";
import {reloadEmoji} from "../emoji";
import {appearanceConfigApi} from "../config/tabs/appearanceRuntime";
@@ -79,7 +80,7 @@ class App {
setRefDynamicText(data.data);
break;
case "reloadPlugin":
- reloadPlugin(this, data.data);
+ void applyPluginReload(this, data.data).catch((error) => console.error(error));
break;
case "reloadEmojiConf":
reloadEmoji();
@@ -96,6 +97,7 @@ class App {
break;
case "setConf":
window.siyuan.config = data.data;
+ syncGlobalPluginConfig(this, data.data.bazaar.petalDisabled);
break;
case "setCloudUser":
applyCloudUserState(data.data.user, data.data.userName);
diff --git a/kernel/api/router.go b/kernel/api/router.go
index ad9c68662b..771f22b008 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -476,6 +476,7 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/setting/setSecrets", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setSecrets)
ginServer.Handle("POST", "/api/setting/setVariables", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setVariables)
ginServer.Handle("POST", "/api/setting/setBazaar", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setBazaar)
+ ginServer.Handle("POST", "/api/setting/setBazaarPetalDisabled", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setBazaarPetalDisabled)
ginServer.Handle("POST", "/api/setting/setPublish", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setPublish)
ginServer.Handle("POST", "/api/setting/getPublish", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, getPublish)
ginServer.Handle("POST", "/api/setting/refreshVirtualBlockRef", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, refreshVirtualBlockRef)
diff --git a/kernel/api/setting.go b/kernel/api/setting.go
index 4c805570f5..06234af15e 100644
--- a/kernel/api/setting.go
+++ b/kernel/api/setting.go
@@ -21,6 +21,7 @@ import (
"net/http"
"reflect"
"strings"
+ "sync"
"github.com/88250/gulu"
"github.com/gin-gonic/gin"
@@ -35,6 +36,11 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
+var (
+ bazaarPetalStateMu sync.Mutex
+ bazaarPetalStateRevision uint64
+)
+
func setEditorReadOnly(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
@@ -145,7 +151,6 @@ func setBazaar(c *gin.Context) {
if !ok {
return
}
- app, _ := arg["app"].(string)
delete(arg, "app")
param, err := gulu.JSON.MarshalJSON(arg)
@@ -162,30 +167,69 @@ func setBazaar(c *gin.Context) {
return
}
+ bazaarPetalStateMu.Lock()
+ defer bazaarPetalStateMu.Unlock()
+
petalsEnabled := model.IsPetalsEnabled()
+ petalDisabled := model.Conf.Bazaar.PetalDisabled
model.Conf.Bazaar = bazaar
model.Conf.Save()
- util.BroadcastByType("main", "setConf", 0, "", model.Conf)
newPetalsEnabled := model.IsPetalsEnabled()
if petalsEnabled != newPetalsEnabled {
- if newPetalsEnabled {
- if model.OnKernelPluginsStart != nil {
- model.OnKernelPluginsStart()
- }
- } else if model.OnKernelPluginsStop != nil {
- model.OnKernelPluginsStop()
- }
- model.PushReloadAllEnabledPlugins(newPetalsEnabled, bazaarPluginReloadExcludeApp(newPetalsEnabled, app))
+ setKernelPluginsEnabled(newPetalsEnabled)
+ }
+ util.BroadcastByType("main", "setConf", 0, "", model.Conf)
+ if petalsEnabled != newPetalsEnabled || petalDisabled != bazaar.PetalDisabled {
+ bazaarPetalStateRevision++
+ model.PushReloadAllEnabledPlugins(newPetalsEnabled, bazaar.PetalDisabled, bazaarPetalStateRevision, true)
}
ret.Data = bazaar
}
-func bazaarPluginReloadExcludeApp(enabled bool, app string) string {
+func setBazaarPetalDisabled(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+ petalDisabled, ok := arg["petalDisabled"].(bool)
+ if !ok {
+ ret.Code = -1
+ ret.Msg = "invalid petalDisabled"
+ return
+ }
+
+ bazaarPetalStateMu.Lock()
+ defer bazaarPetalStateMu.Unlock()
+
+ petalsEnabled := model.IsPetalsEnabled()
+ changed := model.Conf.Bazaar.PetalDisabled != petalDisabled
+ model.Conf.Bazaar.PetalDisabled = petalDisabled
+ model.Conf.Save()
+ newPetalsEnabled := model.IsPetalsEnabled()
+ if petalsEnabled != newPetalsEnabled {
+ setKernelPluginsEnabled(newPetalsEnabled)
+ }
+ util.BroadcastByType("main", "setConf", 0, "", model.Conf)
+ if changed {
+ bazaarPetalStateRevision++
+ }
+ ret.Data = model.PushReloadAllEnabledPlugins(newPetalsEnabled, petalDisabled, bazaarPetalStateRevision, changed)
+}
+
+func setKernelPluginsEnabled(enabled bool) {
if enabled {
- return app
+ if model.OnKernelPluginsStart != nil {
+ model.OnKernelPluginsStart()
+ }
+ return
+ }
+ if model.OnKernelPluginsStop != nil {
+ model.OnKernelPluginsStop()
}
- return ""
}
func setAI(c *gin.Context) {
diff --git a/kernel/api/setting_test.go b/kernel/api/setting_test.go
index 665d789c3c..89e208180a 100644
--- a/kernel/api/setting_test.go
+++ b/kernel/api/setting_test.go
@@ -21,7 +21,9 @@ import (
"net/http"
"net/http/httptest"
"strings"
+ "sync"
"testing"
+ "time"
"github.com/gin-gonic/gin"
"github.com/siyuan-note/siyuan/kernel/conf"
@@ -29,21 +31,114 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
-func TestBazaarPluginReloadExcludeApp(t *testing.T) {
- for _, test := range []struct {
- name string
- enabled bool
- app string
- want string
- }{
- {name: "enable excludes requesting app", enabled: true, app: "current-app", want: "current-app"},
- {name: "disable includes requesting app", enabled: false, app: "current-app", want: ""},
- } {
- t.Run(test.name, func(t *testing.T) {
- if got := bazaarPluginReloadExcludeApp(test.enabled, test.app); got != test.want {
- t.Fatalf("unexpected excluded app: got %q, want %q", got, test.want)
- }
- })
+func TestSetBazaarPetalDisabledSerializesTransitions(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ previousConf := model.Conf
+ previousReadOnly := util.ReadOnly
+ previousDataDir := util.DataDir
+ previousStart := model.OnKernelPluginsStart
+ previousStop := model.OnKernelPluginsStop
+ util.ReadOnly = true
+ util.DataDir = t.TempDir()
+ model.Conf = model.NewAppConf()
+ model.Conf.Bazaar = &conf.Bazaar{Trust: true}
+ bazaarPetalStateMu.Lock()
+ bazaarPetalStateRevision = 0
+ bazaarPetalStateMu.Unlock()
+ t.Cleanup(func() {
+ bazaarPetalStateMu.Lock()
+ bazaarPetalStateRevision = 0
+ bazaarPetalStateMu.Unlock()
+ model.Conf = previousConf
+ util.ReadOnly = previousReadOnly
+ util.DataDir = previousDataDir
+ model.OnKernelPluginsStart = previousStart
+ model.OnKernelPluginsStop = previousStop
+ })
+
+ stopEntered := make(chan struct{})
+ releaseStop := make(chan struct{})
+ startCalled := make(chan struct{})
+ var transitionMu sync.Mutex
+ transitions := []string{}
+ model.OnKernelPluginsStop = func() {
+ transitionMu.Lock()
+ transitions = append(transitions, "stop")
+ transitionMu.Unlock()
+ close(stopEntered)
+ <-releaseStop
+ }
+ model.OnKernelPluginsStart = func() {
+ transitionMu.Lock()
+ transitions = append(transitions, "start")
+ transitionMu.Unlock()
+ close(startCalled)
+ }
+
+ engine := gin.New()
+ engine.POST("/api/setting/setBazaarPetalDisabled", setBazaarPetalDisabled)
+ type response struct {
+ Code int `json:"code"`
+ Data struct {
+ Enabled bool `json:"globalPetalEnabled"`
+ PetalDisabled bool `json:"globalPetalDisabled"`
+ Revision uint64 `json:"globalPetalRevision"`
+ Changed bool `json:"globalPetalChanged"`
+ } `json:"data"`
+ }
+ request := func(body string) (*httptest.ResponseRecorder, response) {
+ recorder := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPost, "/api/setting/setBazaarPetalDisabled", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ engine.ServeHTTP(recorder, req)
+ result := response{}
+ if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil {
+ t.Errorf("unmarshal setBazaarPetalDisabled response failed: %v", err)
+ }
+ return recorder, result
+ }
+
+ disableResult := make(chan response, 1)
+ go func() {
+ _, result := request(`{"petalDisabled":true}`)
+ disableResult <- result
+ }()
+ <-stopEntered
+
+ enableResult := make(chan response, 1)
+ go func() {
+ _, result := request(`{"petalDisabled":false}`)
+ enableResult <- result
+ }()
+ select {
+ case <-startCalled:
+ t.Fatal("enable transition started before the preceding disable transition completed")
+ case <-time.After(20 * time.Millisecond):
+ }
+ close(releaseStop)
+
+ disabled := <-disableResult
+ enabled := <-enableResult
+ if disabled.Code != 0 || !disabled.Data.Changed || !disabled.Data.PetalDisabled || disabled.Data.Enabled ||
+ disabled.Data.Revision != 1 {
+ t.Fatalf("unexpected disabled response: %#v", disabled)
+ }
+ if enabled.Code != 0 || !enabled.Data.Changed || enabled.Data.PetalDisabled || !enabled.Data.Enabled ||
+ enabled.Data.Revision != 2 {
+ t.Fatalf("unexpected enabled response: %#v", enabled)
+ }
+ if model.Conf.Bazaar.PetalDisabled {
+ t.Fatal("final bazaar plugin state is disabled")
+ }
+ _, unchanged := request(`{"petalDisabled":false}`)
+ if unchanged.Code != 0 || unchanged.Data.Changed || unchanged.Data.PetalDisabled || !unchanged.Data.Enabled ||
+ unchanged.Data.Revision != 2 {
+ t.Fatalf("unexpected unchanged response: %#v", unchanged)
+ }
+ transitionMu.Lock()
+ defer transitionMu.Unlock()
+ if len(transitions) != 2 || transitions[0] != "stop" || transitions[1] != "start" {
+ t.Fatalf("unexpected transition order: %v", transitions)
}
}
diff --git a/kernel/model/push_reload.go b/kernel/model/push_reload.go
index c06998bbf7..3502fe0010 100644
--- a/kernel/model/push_reload.go
+++ b/kernel/model/push_reload.go
@@ -20,6 +20,7 @@ import (
"os"
"path"
"path/filepath"
+ "sort"
"strings"
"sync"
"time"
@@ -94,22 +95,43 @@ func PushReloadPlugin(uninstallPluginNameSet, unloadPluginNameSet, reloadPluginS
util.BroadcastByTypeAndExcludeApp(excludeApp, "main", "reloadPlugin", 0, "", payload)
}
-// PushReloadAllEnabledPlugins 向前端推送已启用插件的全局启用或禁用状态。
-func PushReloadAllEnabledPlugins(enabled bool, excludeApp string) {
- pluginNameSet := hashset.New()
+// PushReloadAllEnabledPlugins 向前端推送已启用插件的全局状态,并返回相同的权威状态供请求方应用。
+func PushReloadAllEnabledPlugins(enabled, petalDisabled bool, revision uint64, changed bool) map[string]any {
+ pluginNames := []string{}
for _, petal := range getPetals() {
if petal.Enabled {
- pluginNameSet.Add(petal.Name)
+ pluginNames = append(pluginNames, petal.Name)
}
}
- if pluginNameSet.Empty() {
- return
+ sort.Strings(pluginNames)
+
+ unloadPlugins, reloadPlugins := []string{}, []string{}
+ if changed {
+ if enabled {
+ reloadPlugins = pluginNames
+ } else {
+ unloadPlugins = pluginNames
+ }
}
- if enabled {
- PushReloadPlugin(nil, nil, pluginNameSet, nil, excludeApp)
- } else {
- PushReloadPlugin(nil, pluginNameSet, nil, nil, excludeApp)
+ payload := map[string]any{
+ "uninstallPlugins": []string{},
+ "unloadPlugins": unloadPlugins,
+ "reloadPlugins": reloadPlugins,
+ "dataChangePlugins": []string{},
+ "globalPetalEnabled": enabled,
+ "globalPetalDisabled": petalDisabled,
+ "globalPetalRevision": revision,
+ "globalPetalChanged": changed,
+ }
+ if changed {
+ logging.LogInfof("reload plugins for global state, unloads=%v, reloads=%v, revision=%d",
+ unloadPlugins, reloadPlugins, revision)
+ if 0 < len(unloadPlugins)+len(reloadPlugins) {
+ util.ReloadPublishServiceSessions()
+ }
+ util.BroadcastByType("main", "reloadPlugin", 0, "", payload)
}
+ return payload
}
func refreshDocInfo(tree *parse.Tree) {