Skip to content

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

:sparkles: Support opt-in plugins in independent settings windows https://github.com/siyuan-note/siyuan/issues/20002

Daniele5cab2816421
diff --git a/app/src/config/entryVisibility/mobileUi.test.ts b/app/src/config/entryVisibility/mobileUi.test.ts
index c5de72aefd..c8eae53aa6 100644
--- a/app/src/config/entryVisibility/mobileUi.test.ts
+++ b/app/src/config/entryVisibility/mobileUi.test.ts
@@ -45,6 +45,7 @@ const browserCases = async (sources: Record<string, string>, languages: Record<s
"dialog/message": {showMessage: noop},
"protyle/util/compatibility": {isInMobileApp: () => true},
"config/setting/windowContext": {isSettingsWindow: () => settingsWindow,
+ getSettingsOwnerApp: () => window.siyuan.ws?.app,
getSettingsWindowHost: () => ({getDockOrderSnapshot: () => { ownerReads++; return ownerSnapshot; }})},
};
check(id in mocks, `Missing module ${id}`);
diff --git a/app/src/config/entryVisibility/runtime.test.ts b/app/src/config/entryVisibility/runtime.test.ts
index 1cd2e57236..d0b45fcab0 100644
--- a/app/src/config/entryVisibility/runtime.test.ts
+++ b/app/src/config/entryVisibility/runtime.test.ts
@@ -97,6 +97,7 @@ test("entry profile saves in settings windows send requests and flush pending ch
runInNewContext(compile("config/entryVisibility/runtime.ts"), {...context, exports, require: () => ({
syncDockBarVisibility: bar.syncDockBarVisibility,
refreshDockCatalog: () => {},
+ getSettingsOwnerApp: (): undefined => undefined,
getDockEntryOrderSnapshot: () => Object.fromEntries(DOCK_ORDER_SCOPES.map(scope => [scope, []])),
mergeDockEntryOrderSnapshot,
applyDockEntryOrderSnapshot: () => {},
diff --git a/app/src/config/entryVisibility/runtime.ts b/app/src/config/entryVisibility/runtime.ts
index 6ab80bf8e6..433f17703e 100644
--- a/app/src/config/entryVisibility/runtime.ts
+++ b/app/src/config/entryVisibility/runtime.ts
@@ -1,5 +1,6 @@
import {fetchPost} from "../../util/fetch";
import {Constants} from "../../constants";
+import {getSettingsOwnerApp} from "../setting/windowContext";
import {
getEntryCatalogDefaultVisibility,
getEntryCatalogCustomDefaultVisibility,
@@ -216,7 +217,7 @@ export const syncDockEntryOrders = () => {
if (window.siyuan.config.readonly) {
return;
}
- refreshDockCatalog(window.siyuan.ws?.app?.plugins || []);
+ refreshDockCatalog(getSettingsOwnerApp()?.plugins || []);
const currentOrders = getCurrentDockEntryOrderSnapshot();
const config = cloneEntryVisibilityConfig();
const profile = getWritableEntryProfile(config);
@@ -356,7 +357,7 @@ export const applyMenuEntryVisibility = (menuElement: HTMLElement) => {
export const applyDockEntryVisibility = () => {
/// #if !MOBILE
- refreshDockCatalog(window.siyuan.ws?.app?.plugins || []);
+ refreshDockCatalog(getSettingsOwnerApp()?.plugins || []);
const profile = getActiveEntryProfile();
const current = getDockEntryOrderSnapshot();
applyDockEntryOrderSnapshot(mergeDockEntryOrderSnapshot(
@@ -418,7 +419,7 @@ export const applyToolbarEntryVisibility = (toolbarElement: HTMLElement) => {
export const refreshTopBarEntryCatalog = () => {
/// #if !MOBILE
- refreshTopBarCatalog(window.siyuan.ws?.app?.plugins || []);
+ refreshTopBarCatalog(getSettingsOwnerApp()?.plugins || []);
/// #endif
};
diff --git a/app/src/config/entryVisibility/ui.ts b/app/src/config/entryVisibility/ui.ts
index a0ddef9425..0631c2ccf2 100644
--- a/app/src/config/entryVisibility/ui.ts
+++ b/app/src/config/entryVisibility/ui.ts
@@ -49,7 +49,7 @@ import {bindTouchOrder} from "./touchOrder";
import {TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";
import {MOBILE_TOOLBAR_CONTEXT_KEYS} from "./mobileToolbarContext";
/// #if !MOBILE
-import {getSettingsWindowHost, isSettingsWindow} from "../setting/windowContext";
+import {getSettingsOwnerApp, getSettingsWindowHost, isSettingsWindow} from "../setting/windowContext";
/// #endif
import {
DOCK_ORDER_SCOPES,
@@ -580,7 +580,7 @@ const getProfileDockOrderSnapshot = (builtin: boolean) => {
};
const openProfileEditor = (root: HTMLElement, profileID?: string) => {
- const plugins = window.siyuan.ws?.app?.plugins || [];
+ const plugins = getSettingsOwnerApp()?.plugins || [];
refreshTopBarCatalog(plugins);
refreshDockCatalog(plugins);
refreshSlashMenuCatalog(plugins);
@@ -1035,7 +1035,7 @@ export const genEntryVisibilityHtml = () => `<div class="b3-label config-item" d
</div>`;
export const mountEntryVisibility = (root: HTMLElement) => {
- const plugins = window.siyuan.ws?.app?.plugins || [];
+ const plugins = getSettingsOwnerApp()?.plugins || [];
refreshDockCatalog(plugins);
refreshSlashMenuCatalog(plugins);
renderProfileCards(root);
diff --git a/app/src/config/setting/mount.test.ts b/app/src/config/setting/mount.test.ts
index 497766d1fb..320f67023e 100644
--- a/app/src/config/setting/mount.test.ts
+++ b/app/src/config/setting/mount.test.ts
@@ -12,9 +12,11 @@ for (const keywords of ["", "gradient"]) {
const root = {innerHTML: "settings", scrollTop: 235.5, scrollLeft: 12, contains: () => false,
querySelector: (): Element | null => null};
const visibleItemIds = new Set(["bodyGradient"]);
+ const owner = {plugins: [{name: "main-only"}]};
const tab = {
scanSearch: () => ({visibleItemIds}),
- mount: async (element: typeof root, search: {visibleItemIds?: Set<string>}, _app: unknown, rebuild: boolean) => {
+ mount: async (element: typeof root, search: {visibleItemIds?: Set<string>}, app: unknown, rebuild: boolean) => {
+ assert.equal(app, owner);
assert.equal(element, root);
assert.equal(rebuild, true);
assert.equal(search.visibleItemIds, keywords ? visibleItemIds : undefined);
@@ -42,6 +44,7 @@ for (const keywords of ["", "gradient"]) {
if (name === "./tabs") {
return {getSettingTab: () => tab};
}
+ if (name === "./windowContext") return {getSettingsOwnerApp: () => owner};
return {};
},
});
@@ -63,6 +66,7 @@ test("all settings refreshes preserve focused inputs and remount when focus leav
const timers: Array<() => void> = [];
const document = {activeElement: input, addEventListener: (_name: string, callback: () => void) => { focusout = callback; }};
const dependencies = {Constants: {DIALOG_SETTING: "settings"}, getSearchKeywordsLower: () => "",
+ getSettingsOwnerApp: () => ({}),
getSettingTab: () => ({mount: async () => { mounted++; }})};
const exports = {} as {remountOpenSettingTab: (tab: string) => Promise<void>};
runInNewContext(code, {exports, require: () => dependencies, document,
@@ -89,6 +93,7 @@ test("settings refresh preserves an unfocused profile draft and resumes after th
const root = {innerHTML: "draft", scrollTop: 12, scrollLeft: 0, contains: () => false,
querySelector: () => view};
const dependencies = {Constants: {DIALOG_SETTING: "settings"}, getSearchKeywordsLower: () => "",
+ getSettingsOwnerApp: () => ({}),
getSettingTab: () => ({mount: async () => { mounted++; root.innerHTML = "refreshed"; }})};
const exports = {} as {remountOpenSettingTab: (tab: string) => Promise<void>};
runInNewContext(code, {exports, require: () => dependencies,
@@ -132,6 +137,7 @@ test("deferred refresh preserves a pressed label until its click completes or is
const exports = {} as {remountOpenSettingTab: (tab: string) => Promise<void>; watchSettingTabInteractions: () => void};
runInNewContext(code, {exports, document, setTimeout: (callback: () => void) => timers.push(callback),
require: () => ({Constants: {DIALOG_SETTING: "settings"}, getSearchKeywordsLower: () => "",
+ getSettingsOwnerApp: () => ({}),
getSettingTab: () => ({mount: async () => { mounted++; }})}),
window: {siyuan: {ws: {app: {}}, dialogs: [{element: {getAttribute: () => "settings", querySelector: () => root}}]}}});
exports.watchSettingTabInteractions();
diff --git a/app/src/config/setting/mount.ts b/app/src/config/setting/mount.ts
index 8404f8fe10..1d7634dc75 100644
--- a/app/src/config/setting/mount.ts
+++ b/app/src/config/setting/mount.ts
@@ -3,6 +3,7 @@ import {getSearchKeywordsLower, normalizeSearchText} from "../search/normalize";
import {Constants} from "../../constants";
import type {SettingSearchUnavailableItem, SettingTabMountContext} from "./builder";
import {getSettingTab, type TSettingTab} from "./tabs";
+import {getSettingsOwnerApp} from "./windowContext";
const deferredTabs = new Set<TSettingTab>();
let watchingFocus = false;
@@ -75,7 +76,7 @@ export const remountOpenSettingTab = async (tabId: TSettingTab) => {
}
// 重建和异步初始化配置项会改变内容高度,完成后恢复面板的滚动位置。
const {scrollTop, scrollLeft} = root;
- await tab.mount(root, search, window.siyuan.ws.app, true);
+ await tab.mount(root, search, getSettingsOwnerApp(), true);
root.scrollTop = scrollTop;
root.scrollLeft = scrollLeft;
};
diff --git a/app/src/config/setting/window.ts b/app/src/config/setting/window.ts
index 0428994bd1..52efd93aaf 100644
--- a/app/src/config/setting/window.ts
+++ b/app/src/config/setting/window.ts
@@ -30,6 +30,10 @@ import {hideTooltip, initTooltips} from "../../dialog/tooltip";
import {applyCloudUserState} from "../tabs/accountUi";
import {updateServerAddresses} from "../tabs/accessRuntime";
import {installPluginStorageFetchAppId} from "../../util/fetchAppId";
+import {createSettingsPluginApp} from "../../plugin/settingsApp";
+import {afterLayoutReady, disposePlugins, loadPlugins, refreshPlugins} from "../../plugin/loader";
+import {applyPluginReload} from "../../plugin/globalState";
+import {emitToPlugins} from "../../plugin/EventBusCore";
import type {Dialog} from "../../dialog";
import type {ISettingsCommand} from "./nativeWindow";
import {getSettingTabDefs} from "./tabs";
@@ -49,12 +53,14 @@ const initialize = async () => {
}
setSettingsWindowHost(host);
let disposed = false;
- const ws = new Model({app: host.app});
+ const app = createSettingsPluginApp(Constants.SIYUAN_APPID);
+ const ws = new Model({app});
const listeners: {channel: string; listener: Parameters<typeof ipcRenderer.on>[1]}[] = [];
disposeSettingsWindow = () => {
if (disposed) return;
disposed = true;
if (window.siyuan) window.siyuan.isReady = false;
+ disposePlugins(app);
ws.destroy();
listeners.forEach(({channel, listener}) => ipcRenderer.removeListener(channel, listener));
setSettingsWindowHost(undefined);
@@ -123,9 +129,12 @@ const initialize = async () => {
ws.connect({id: genUUID(), type: "main", callback: () => {
if (isActive() && window.siyuan.isReady) {
void runtime.reconnect().catch(error => console.error("Could not reconnect settings runtime", error));
+ void refreshPlugins(app).catch(error => console.error("Could not reconnect settings plugins", error));
}
}, msgCallback: data => {
- if (!isActive() || !data || runtime.handleMessage(data)) return;
+ if (!isActive() || !data) return;
+ emitToPlugins("ws-main", data);
+ if (runtime.handleMessage(data)) return;
switch (data.cmd) {
case "logoutAuth": redirectToCheckAuth(); break;
case "settingChanged": void refreshSettingConfig(data.data.namespace); break;
@@ -137,7 +146,10 @@ const initialize = async () => {
case "refreshAppearance": void refreshAppearance(data.data); break;
case "reloadInlineStyles": void reloadInlineStyles(); break;
case "refreshtheme": refreshThemeStyle(data.data.theme); break;
- case "reloadPlugin": void refreshSettingConfig("bazaar"); break;
+ case "reloadPlugin":
+ void refreshSettingConfig("bazaar");
+ void applyPluginReload(app, data.data).catch(error => console.error("Could not update settings plugins", error));
+ break;
case "readonly": window.siyuan.config.editor.readOnly = data.data; break;
case "progress": progressLoading(data); break;
case "downloadProgress": downloadProgress(data.data); break;
@@ -253,6 +265,14 @@ const initialize = async () => {
window.addEventListener("resize", () => window.siyuan.menus.menu.resetPosition());
await runtime.refreshSnippets();
if (!isActive()) return;
+ try {
+ await loadPlugins(app);
+ if (!isActive()) return;
+ void afterLayoutReady(app);
+ } catch (error) {
+ console.error("Could not load settings plugins", error);
+ }
+ if (!isActive()) return;
window.siyuan.isReady = true;
ws.flushMainMessages();
await applyCommand();
diff --git a/app/src/config/setting/windowContext.ts b/app/src/config/setting/windowContext.ts
index 5bcc5f053f..70e6feb850 100644
--- a/app/src/config/setting/windowContext.ts
+++ b/app/src/config/setting/windowContext.ts
@@ -38,7 +38,9 @@ export interface ISettingsWindowHost {
let host: ISettingsWindowHost;
export const setSettingsWindowHost = (value: ISettingsWindowHost) => { host = value; };
export const getSettingsWindowHost = () => host;
-export const isSettingsWindow = () => typeof document !== "undefined" && document.body.classList.contains("body--settings");
+export const getSettingsOwnerApp = () => host?.app || window.siyuan.ws?.app;
+export const isSettingsWindow = () => Boolean(host) ||
+ (typeof document !== "undefined" && document.body.classList.contains("body--settings"));
// 重载和重置结束设置会话,不触发关闭时的旧窗口偏好保存。
export const closeSettingsWindow = () => {
diff --git a/app/src/config/tabs/keymapUi.test.ts b/app/src/config/tabs/keymapUi.test.ts
index 5b3e938d64..296dbbd531 100644
--- a/app/src/config/tabs/keymapUi.test.ts
+++ b/app/src/config/tabs/keymapUi.test.ts
@@ -4,6 +4,18 @@ import {test} from "node:test";
import {runInNewContext} from "node:vm";
import {createSourceFile, isClassDeclaration, isMethodDeclaration, isVariableStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";
+test("settings keymap search keeps undeclared owner plugins visible", () => {
+ const source = createSourceFile("keymapUi.ts", readFileSync("src/config/tabs/keymapUi.ts", "utf8"), ScriptTarget.ES2021, true);
+ const declarations = source.statements.filter(statement => isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(item => ["buildKeymapPluginDisplayNames", "pluginHasKeymapItems"].includes(item.name.getText(source))));
+ const code = transpileModule(declarations.map(item => item.getText(source)).join("\n") +
+ "\nexports.names = buildKeymapPluginDisplayNames;", {compilerOptions: {module: ModuleKind.CommonJS}}).outputText;
+ const owner = {plugins: [{displayName: "Main-only plugin", commands: [{}]}]};
+ const exports = {} as {names: () => string[]};
+ runInNewContext(code, {exports, getSettingsOwnerApp: () => owner, window: {siyuan: {ws: {app: {plugins: []}}}}});
+ assert.deepEqual(Array.from(exports.names()), ["Main-only plugin"]);
+});
+
test("panel mounts forward refresh intent without changing search and navigation arguments", async () => {
const source = createSourceFile("builder.ts", readFileSync("src/config/setting/builder.ts", "utf8"),
ScriptTarget.ES2021, true);
diff --git a/app/src/config/tabs/keymapUi.ts b/app/src/config/tabs/keymapUi.ts
index c33a91b73d..c5a1009165 100644
--- a/app/src/config/tabs/keymapUi.ts
+++ b/app/src/config/tabs/keymapUi.ts
@@ -20,6 +20,7 @@ import {escapeHtml} from "../../util/escape";
import {Menu} from "../../plugin/Menu";
import {refreshSettingConfig} from "../setting/sync";
import {trackSettingSave} from "../setting/pending";
+import {getSettingsOwnerApp} from "../setting/windowContext";
import type {App} from "../../index";
const keymapToolbarSearchStrings = (): string[] => [
@@ -173,7 +174,7 @@ const buildKeymapCommandTexts = (): string[] => {
const buildKeymapPluginDisplayNames = (): string[] => {
const names: string[] = [];
- window.siyuan.ws.app.plugins.forEach((item) => {
+ getSettingsOwnerApp().plugins.forEach((item) => {
if (pluginHasKeymapItems(item) && item.displayName) {
names.push(item.displayName);
}
@@ -208,7 +209,7 @@ const genKeymapListHtml = () => {
).join("");
const pluginHtmlParts: string[] = [];
- for (const item of window.siyuan.ws.app.plugins) {
+ for (const item of getSettingsOwnerApp().plugins) {
if (!pluginHasKeymapItems(item)) {
continue;
}
@@ -348,7 +349,7 @@ const bindKeymapList = (root: HTMLElement) => {
searchKeymapList(keymapListElement, searchElement.value, searchKeymapElement.dataset.keymap);
});
searchKeymapElement.addEventListener("focus", () => {
- sendUnregisterGlobalShortcut(window.siyuan.ws.app);
+ sendUnregisterGlobalShortcut(getSettingsOwnerApp());
});
searchKeymapElement.addEventListener("blur", () => {
sendGlobalShortcut(window.siyuan.ws.app);
diff --git a/app/src/plugin/Setting.ts b/app/src/plugin/Setting.ts
index f900d863fe..b2af8eaf32 100644
--- a/app/src/plugin/Setting.ts
+++ b/app/src/plugin/Setting.ts
@@ -67,6 +67,7 @@ export class Setting {
});
return;
}
+ const windowRoot = isSettingsWindow() && window.siyuan.dialogs.length === 0;
const dialog = new Dialog({
title: name,
content: `<div class="b3-dialog__content">
@@ -82,7 +83,7 @@ export class Setting {
if (this.destroyCallback) {
this.destroyCallback();
}
- if (isSettingsWindow()) {
+ if (windowRoot) {
window.close();
}
}
@@ -147,7 +148,7 @@ export class Setting {
dialog.destroy();
});
this.dialog = dialog;
- if (isSettingsWindow()) {
+ if (windowRoot) {
fitSettingsWindowDialog(dialog);
}
}
diff --git a/app/src/plugin/globalState.ts b/app/src/plugin/globalState.ts
index 0ea77a8f7c..ee83eb8b9b 100644
--- a/app/src/plugin/globalState.ts
+++ b/app/src/plugin/globalState.ts
@@ -7,6 +7,7 @@ import {
} from "./globalStateCoordinator";
import {type IPluginReloadData, reloadPlugin} from "./loader";
import {getSettingsWindowHost} from "../config/setting/windowContext";
+import {isSettingsPluginApp} from "./settingsApp";
type TGlobalPluginReloadData = IPluginReloadData & IGlobalPluginStatePayload;
@@ -36,7 +37,7 @@ const isGlobalPluginState = (data: IPluginReloadData): data is TGlobalPluginRelo
export const applyPluginReload = (app: App, data: IPluginReloadData = {}) => {
const host = getSettingsWindowHost();
- if (host) {
+ if (host && !isSettingsPluginApp(app)) {
return host.applyPluginReload(data);
}
if (!isGlobalPluginState(data)) {
@@ -50,7 +51,7 @@ export const syncGlobalPluginConfig = (app: App, petalDisabled: boolean) => {
};
export const subscribeGlobalPluginState = (app: App, listener: (state: IGlobalPluginStateSnapshot) => void) =>
- getSettingsWindowHost()?.subscribePlugins(listener) || getCoordinator(app).subscribe(listener);
+ (!isSettingsPluginApp(app) && getSettingsWindowHost()?.subscribePlugins(listener)) || getCoordinator(app).subscribe(listener);
export const setGlobalPluginsDisabled = async (app: App, petalDisabled: boolean) => {
const response = await fetchSyncPost("/api/setting/setBazaarPetalDisabled", {petalDisabled});
diff --git a/app/src/plugin/index.ts b/app/src/plugin/index.ts
index 811895b704..590c704fc9 100644
--- a/app/src/plugin/index.ts
+++ b/app/src/plugin/index.ts
@@ -40,6 +40,7 @@ import {
import {isBuiltinToolbarItemName} from "../protyle/toolbar/defaults";
import {getLegacyPluginTopBarEntryKey, getPluginTopBarEntryKey} from "./topBarKey";
import {applyTopBarEntryVisibility} from "../config/entryVisibility/runtime";
+import {getSettingsWindowHost, isSettingsWindow} from "../config/setting/windowContext";
export type TPluginDataChangeReason = "sync" | "overwrite";
@@ -129,6 +130,7 @@ export class Plugin {
writable: false,
});
+ if (isSettingsWindow()) return;
resolvePluginToolbar(this, []).forEach(toolbarItem => {
if (typeof toolbarItem === "string" || Constants.INLINE_TYPE.concat("|").includes(toolbarItem.name)) {
return;
@@ -171,7 +173,7 @@ export class Plugin {
}
public addToolbarItem(item: IMenuItem) {
- if (isPluginDisposed(this)) {
+ if (isPluginDisposed(this) || isSettingsWindow()) {
return;
}
if (typeof item?.name !== "string" || !item.name.trim() || item.name !== item.name.trim() ||
@@ -196,7 +198,7 @@ export class Plugin {
}
public addCommand(command: ICommand) {
- if (isPluginDisposed(this)) {
+ if (isPluginDisposed(this) || isSettingsWindow()) {
return;
}
if (typeof command.hotkey !== "string") {
@@ -246,7 +248,7 @@ export class Plugin {
contextMenu?: (menu: subMenu) => void,
callback?: (evt: MouseEvent) => void
}) {
- if (isPluginDisposed(this)) {
+ if (isPluginDisposed(this) || isSettingsWindow()) {
return;
}
if (options.element && (isMobile() || isWindow())) {
@@ -378,7 +380,7 @@ export class Plugin {
title: string,
callback: (event: MouseEvent, protyle: IProtyle) => void,
}) {
- if (isPluginDisposed(this)) {
+ if (isPluginDisposed(this) || isSettingsWindow()) {
return options.id;
}
options.icon = options.icon.trim();
@@ -401,7 +403,7 @@ export class Plugin {
element: HTMLElement,
position?: "right" | "left",
}) {
- if (isPluginDisposed(this)) {
+ if (isPluginDisposed(this) || isSettingsWindow()) {
return options.element;
}
/// #if !MOBILE
@@ -423,6 +425,10 @@ export class Plugin {
if (isPluginDisposed(this) || !this.setting) {
return;
}
+ if (isSettingsWindow()) {
+ void getSettingsWindowHost()?.openPluginSetting(this.name).catch(error => console.error(error));
+ return;
+ }
this.setting.open(this.displayName || this.name);
}
@@ -588,7 +594,7 @@ export class Plugin {
update?: (this: Custom) => void,
init: (this: Custom, custom: Custom) => void
}) {
- if (isPluginDisposed(this)) {
+ if (isPluginDisposed(this) || isSettingsWindow()) {
return;
}
/// #if !MOBILE
@@ -655,7 +661,7 @@ 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)) {
+ if (isPluginDisposed(this) || isSettingsWindow()) {
return id;
}
if (!this.agentCapabilities.some((capability) => capability.id === id)) {
@@ -687,7 +693,7 @@ export class Plugin {
update?: (this: Custom | MobileCustom) => void,
init: (this: Custom | MobileCustom, custom: Custom | MobileCustom) => void
}) {
- if (isPluginDisposed(this)) {
+ if (isPluginDisposed(this) || isSettingsWindow()) {
return;
}
const id = options.id || options.type;
@@ -758,7 +764,7 @@ export class Plugin {
originalRefBlockIDs?: Record<string, string>,
isBacklink: boolean,
}) => {
- if (isPluginDisposed(this)) {
+ if (isPluginDisposed(this) || isSettingsWindow()) {
return;
}
window.siyuan.blockPanels.push(new BlockPanel({
diff --git a/app/src/plugin/lifecycle.test.ts b/app/src/plugin/lifecycle.test.ts
index a5d5b89925..9935960c71 100644
--- a/app/src/plugin/lifecycle.test.ts
+++ b/app/src/plugin/lifecycle.test.ts
@@ -119,6 +119,51 @@ const createHarness = (overrides: Partial<IPluginLifecycleAdapter<ITestPluginDat
};
describe("plugin lifecycle coordinator", () => {
+ it("a reconnect snapshot cannot unload or replace a newer plugin instance", async () => {
+ const {coordinator} = createHarness();
+ coordinator.start();
+ await coordinator.setLayoutReady();
+ await coordinator.requestLoad("sample", async () => ({name: "sample", revision: 1}));
+ const snapshot = coordinator.beginLoadBatch();
+ await coordinator.requestReload("sample", async () => ({name: "sample", revision: 2}));
+ const latest = coordinator.getInstance("sample");
+ await coordinator.requestBatchUnload("sample", snapshot);
+ await coordinator.requestBatchLoad("sample", {name: "sample", revision: 0}, snapshot, true);
+ assert.equal(coordinator.getInstance("sample"), latest);
+ assert.equal(latest.revision, 2);
+ });
+ it("window disposal invalidates pending loads and tears down its own instances exactly once", async () => {
+ const loading = deferred<void>();
+ const {coordinator, events} = createHarness({onload: () => loading.promise});
+ coordinator.start();
+ await coordinator.setLayoutReady();
+ const loaded = coordinator.requestLoad("sample", async () => ({name: "sample", revision: 1}));
+ await new Promise(resolve => setImmediate(resolve));
+ coordinator.dispose();
+ coordinator.dispose();
+ assert.equal(coordinator.getInstance("sample"), undefined);
+ assert.equal(events.filter(item => item === "onunload:sample").length, 1);
+ assert.equal(events.filter(item => item === "dispose:sample:false").length, 1);
+ loading.resolve();
+ await loaded;
+ await coordinator.requestLoad("sample", async () => ({name: "sample", revision: 2}));
+ assert.equal(events.filter(item => item.startsWith("create:")).length, 1);
+ assert.equal(events.includes("mount:sample"), false);
+ });
+
+ it("disposal during asynchronous teardown does not duplicate cleanup or invoke uninstall", async () => {
+ const unloading = deferred<void>();
+ const {coordinator, events} = createHarness({onunload: () => unloading.promise});
+ coordinator.start();
+ await coordinator.requestLoad("sample", async () => ({name: "sample", revision: 1}));
+ const removed = coordinator.requestUninstall("sample");
+ await new Promise(resolve => setImmediate(resolve));
+ coordinator.dispose();
+ unloading.resolve();
+ await removed;
+ assert.equal(events.filter(item => item.startsWith("dispose:")).length, 1);
+ assert.equal(events.includes("uninstall:sample"), false);
+ });
it("keeps one instance and one layout hook for repeated loads", async () => {
const {coordinator, events, instances} = createHarness();
coordinator.start();
diff --git a/app/src/plugin/lifecycle.ts b/app/src/plugin/lifecycle.ts
index 163dfcf5c3..03401e0fd6 100644
--- a/app/src/plugin/lifecycle.ts
+++ b/app/src/plugin/lifecycle.ts
@@ -115,6 +115,7 @@ export class PluginLifecycleCoordinator<TData, TPlugin> {
private latestLoadBatch = 0;
private started = false;
private layoutReady = false;
+ private disposed = false;
constructor(adapter: IPluginLifecycleAdapter<TData, TPlugin>, options: IPluginLifecycleOptions = {}) {
this.adapter = adapter;
@@ -125,7 +126,7 @@ export class PluginLifecycleCoordinator<TData, TPlugin> {
}
public start() {
- if (this.started) {
+ if (this.started || this.disposed) {
return;
}
this.started = true;
@@ -148,13 +149,21 @@ export class PluginLifecycleCoordinator<TData, TPlugin> {
return batch.id === this.latestLoadBatch;
}
- public requestBatchLoad(name: string, data: TData, batch: IPluginLoadBatch) {
+ public requestBatchLoad(name: string, data: TData, batch: IPluginLoadBatch, reload = false) {
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);
+ return this.enqueueStructural(record, reload ? "reload" : "load", async () => data, batch.sequence);
+ }
+
+ public requestBatchUnload(name: string, batch: IPluginLoadBatch) {
+ const record = this.getRecord(name);
+ if (batch.id !== this.latestLoadBatch || record.lastStructuralSequence > batch.sequence) {
+ return Promise.resolve();
+ }
+ return this.enqueueStructural(record, "unload", undefined, batch.sequence);
}
public requestLoad(name: string, dataProvider: () => Promise<TData | undefined>) {
@@ -196,7 +205,7 @@ export class PluginLifecycleCoordinator<TData, TPlugin> {
}
public setLayoutReady() {
- if (this.layoutReady) {
+ if (this.layoutReady || this.disposed) {
return Promise.resolve();
}
this.layoutReady = true;
@@ -227,6 +236,29 @@ export class PluginLifecycleCoordinator<TData, TPlugin> {
return this.records.get(name)?.instance;
}
+ public dispose() {
+ if (this.disposed) return;
+ this.disposed = true;
+ this.latestLoadBatch = ++this.loadBatchSequence;
+ this.records.forEach(record => {
+ record.lastStructuralSequence = ++this.sequence;
+ this.signalRemoval(record, this.now());
+ record.tasks.splice(0).forEach(task => task.waiters.forEach(resolve => resolve()));
+ const plugin = record.instance;
+ const unloading = record.state === "unloading" || record.state === "uninstalling";
+ record.instance = undefined;
+ record.state = "absent";
+ if (!plugin) return;
+ this.markDisposed(record.name, plugin);
+ if (!unloading) void this.observe(record.name, "onunload", () => this.adapter.onunload(plugin));
+ try {
+ this.adapter.dispose(plugin, false);
+ } catch (error) {
+ this.adapter.onError(record.name, "dispose", error);
+ }
+ });
+ }
+
private getRecord(name: string) {
let record = this.records.get(name);
if (!record) {
@@ -269,6 +301,7 @@ export class PluginLifecycleCoordinator<TData, TPlugin> {
}
private enqueue(record: IPluginLifecycleRecord<TData, TPlugin>, task: IPluginLifecycleTask<TData>) {
+ if (this.disposed) return Promise.resolve();
const promise = new Promise<void>((resolve) => task.waiters.push(resolve));
record.tasks.push(task);
this.schedule(record);
@@ -276,7 +309,7 @@ export class PluginLifecycleCoordinator<TData, TPlugin> {
}
private schedule(record: IPluginLifecycleRecord<TData, TPlugin>) {
- if (!this.started || record.processing || record.tasks.length === 0 ||
+ if (this.disposed || !this.started || record.processing || record.tasks.length === 0 ||
this.isDataChangeWaitingForReady(record)) {
return;
}
@@ -460,6 +493,7 @@ export class PluginLifecycleCoordinator<TData, TPlugin> {
deadlineReached = true;
this.reportTimeout(record.name, "onunload");
}
+ if (record.instance !== plugin) return;
uninstall = uninstall || this.hasPendingUninstall(record);
if (uninstall) {
record.state = "uninstalling";
@@ -469,6 +503,7 @@ export class PluginLifecycleCoordinator<TData, TPlugin> {
}
this.markPendingUninstallsHandled(record, task);
}
+ if (record.instance !== plugin) return;
this.markDisposed(record.name, plugin);
record.instance = undefined;
record.state = "absent";
diff --git a/app/src/plugin/loader.ts b/app/src/plugin/loader.ts
index d2e3d20dd1..371dbc21e8 100644
--- a/app/src/plugin/loader.ts
+++ b/app/src/plugin/loader.ts
@@ -28,6 +28,8 @@ import {
deactivateCustomBlockPlugin,
} from "./customBlockRender";
import {getHostCapabilities} from "../util/hostCapabilities";
+import {isSettingsWindow} from "../config/setting/windowContext";
+import {ensureLute} from "../protyle/util/lute";
const requireFunc = (key: string) => {
if (key === "siyuan") {
@@ -121,10 +123,24 @@ const getLifecycleManager = (app: App) => {
return manager;
};
+const fetchPluginData = async () => {
+ const settingsWindow = isSettingsWindow();
+ const response = await fetchSyncPost("/api/petal/loadPetals", {
+ frontend: getFrontend(), ...(settingsWindow ? {settingsWindow: true} : {}),
+ });
+ if (settingsWindow && response.code !== 0) {
+ throw new Error(response.msg || "Could not read settings plugins");
+ }
+ const items = response.code === 0 && Array.isArray(response.data) ?
+ response.data.filter(item => !settingsWindow || item.settingsWindow === true) : [];
+ if (settingsWindow && items.length) await ensureLute({reloadOnFailure: false});
+ return items;
+};
+
const createPluginDataLoader = () => {
let promise: Promise<IPluginData[]>;
return (name: string) => {
- promise ??= fetchSyncPost("/api/petal/loadPetals", {frontend: getFrontend()}).then(response => response.code === 0 && Array.isArray(response.data) ? response.data : []);
+ promise ??= fetchPluginData();
return promise.then(items => items.find(item => item.name === name));
};
};
@@ -141,8 +157,8 @@ export const loadPlugins = async (app: App, names?: string[], init = true) => {
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.code === 0 && Array.isArray(response.data) ? response.data : []).map(item => manager.requestBatchLoad(item.name, item, batch));
+ const items = await fetchPluginData();
+ tasks = items.map(item => manager.requestBatchLoad(item.name, item, batch));
shouldStart = manager.isLatestLoadBatch(batch);
}
if (shouldStart) {
@@ -180,6 +196,10 @@ export const loadPlugin = async (app: App, item: IPluginData) => {
return;
}
const manager = getLifecycleManager(app);
+ if (isSettingsWindow()) {
+ await loadPlugins(app, [item.name], false);
+ return manager.getInstance(item.name);
+ }
manager.start();
await manager.requestLoad(item.name, async () => item);
saveLayout();
@@ -237,6 +257,7 @@ const updateDock = (dockItem: Config.IUILayoutDockTab[], index: number, plugin:
};
const mountPlugin = (plugin: Plugin) => {
+ if (isSettingsWindow()) return;
if (!isWindow() || isMobile()) {
plugin.topBarIcons.forEach(element => {
if (document.contains(element)) {
@@ -257,6 +278,7 @@ const mountPlugin = (plugin: Plugin) => {
return;
}
const statusElement = document.getElementById("status");
+ if (!statusElement) return;
if (element.getAttribute("data-location") === "right") {
statusElement.insertAdjacentElement("beforeend", element);
} else {
@@ -271,7 +293,7 @@ const mountPlugin = (plugin: Plugin) => {
export const afterLayoutReady = (app: App) => {
const manager = getLifecycleManager(app);
- void manager.setLayoutReady();
+ return manager.setLayoutReady();
};
const getPluginCatalogPlugins = (plugin: Plugin) => window.siyuan.ws?.app?.plugins || [plugin];
@@ -412,3 +434,20 @@ export const uninstallPlugin = async (app: App, name: string) => {
manager.start();
await manager.requestUninstall(name);
};
+
+// 窗口销毁时同步撤销实例,异步钩子的迟到完成不能重新挂载界面。
+export const disposePlugins = (app: App) => lifecycleManagers.get(app)?.dispose();
+
+// 重连后以当前启用清单恢复实例,期间收到的更新请求优先于这次快照。
+export const refreshPlugins = async (app: App) => {
+ if (!getHostCapabilities().plugins) return;
+ const manager = getLifecycleManager(app);
+ const batch = manager.beginLoadBatch();
+ const items = await fetchPluginData();
+ if (!manager.isLatestLoadBatch(batch)) return;
+ const names = new Set(items.map(item => item.name));
+ const tasks = app.plugins.filter(plugin => !names.has(plugin.name)).map(plugin => manager.requestBatchUnload(plugin.name, batch));
+ tasks.push(...items.map(item => manager.requestBatchLoad(item.name, item, batch, true)));
+ manager.start();
+ await Promise.all(tasks);
+};
diff --git a/app/src/plugin/settingsApp.ts b/app/src/plugin/settingsApp.ts
new file mode 100644
index 0000000000..848cb003ee
--- /dev/null
+++ b/app/src/plugin/settingsApp.ts
@@ -0,0 +1,12 @@
+import type {App} from "../index";
+
+const settingsApps = new WeakSet<App>();
+
+// 设置窗口的插件实例独立于宿主,设置界面的宿主操作仍通过原有桥接处理。
+export const createSettingsPluginApp = (appId: string): App => {
+ const app: App = {appId, plugins: []};
+ settingsApps.add(app);
+ return app;
+};
+
+export const isSettingsPluginApp = (app: App) => settingsApps.has(app);
diff --git a/app/src/plugin/topBar.test.ts b/app/src/plugin/topBar.test.ts
index e124fd9765..c7e4b8ecd2 100644
--- a/app/src/plugin/topBar.test.ts
+++ b/app/src/plugin/topBar.test.ts
@@ -147,6 +147,7 @@ const setup = (mobile = false, detached = false, mounted = false) => {
setTopBarContextMenu,
isMobile: () => mobile,
isWindow: () => detached,
+ isSettingsWindow: () => false,
getPluginTopBarEntryKey,
getLegacyPluginTopBarEntryKey,
applyTopBarEntryVisibility: () => refreshes++,
diff --git a/app/src/plugin/uninstall.ts b/app/src/plugin/uninstall.ts
index 0dc5dfd18b..abeaf87061 100644
--- a/app/src/plugin/uninstall.ts
+++ b/app/src/plugin/uninstall.ts
@@ -17,6 +17,7 @@ import {destroyEventBus} from "./EventBusCore";
import {unregisterPluginCommands} from "./commandAdapter";
import {sendGlobalShortcut} from "../boot/globalEvent/globalShortcut";
import {releaseTrackedRangesByPlugin} from "../protyle/util/trackedRange";
+import {isSettingsWindow} from "../config/setting/windowContext";
/// #if !MOBILE
import {applyTopBarEntryVisibility} from "../config/entryVisibility/runtime";
/// #endif
@@ -44,7 +45,7 @@ export const destroyPlugin = (app: App, plugin: Plugin, isUninstall: boolean) =>
beginPluginTeardown(plugin);
runCleanup(plugin, "kernel", () => plugin.kernel.destroy());
runCleanup(plugin, "event bus", () => destroyEventBus(plugin.eventBus));
- if (isUninstall) {
+ if (isUninstall && !isSettingsWindow()) {
runCleanup(plugin, "dock storage", () => {
const pluginDocks = window.siyuan.storage?.[Constants.LOCAL_PLUGIN_DOCKS] || {};
pluginDocks[plugin.name] = {};
@@ -106,7 +107,7 @@ export const destroyPlugin = (app: App, plugin: Plugin, isUninstall: boolean) =>
if (index > -1) {
app.plugins.splice(index, 1);
}
- runCleanup(plugin, "dock catalog", () => refreshDockCatalog(app.plugins));
+ if (!isSettingsWindow()) runCleanup(plugin, "dock catalog", () => refreshDockCatalog(app.plugins));
/// #if !MOBILE
runCleanup(plugin, "top bar catalog", () => applyTopBarEntryVisibility());
runCleanup(plugin, "top bar layout", () => resizeTopBar());
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 38710f3f6d..fdd50af62c 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -668,7 +668,7 @@ export type BazaarLocalInstallResult = (BazaarLocalInstallData & { "reason"?: ne
export type BazaarNotifications = { "browserCompatibility": boolean; "docTreeMaxList": boolean; "formatPainterTip"?: boolean; "selectAllIncompleteTip"?: boolean; "selectAllTip"?: boolean; "tagMaxList": boolean; "workspaceNotSSD": boolean; };
-export type BazaarPackage = { "alternatives"?: Array<string>; "author": string; "backends": Array<string> | null; "bazaarIncompatible"?: boolean; "bootAppearances"?: Array<string>; "current": boolean; "deprecated"?: boolean; "deprecatedReason"?: Record<string, string>; "description": Record<string, string> | null; "disabledInPublish": boolean; "disallowInstall": boolean; "disallowUpdate": boolean; "displayName": Record<string, string> | null; "downloads": number; "enabled"?: boolean; "frontends": Array<string> | null; "funding": BazaarFunding | null; "hInstallDate": string; "hInstallSize": string; "hSize": string; "hUpdated": string; "hasStorageData"?: boolean; "icon"?: string; "iconURL": string; "installSize": number; "installTime": number; "installed": boolean; "installedIncompatible"?: boolean; "invalidReason"?: "missing-manifest" | "invalid-manifest" | "name-mismatch"; "kernels": Array<string> | null; "keywords": Array<string> | null; "minAppVersion": string; "modes"?: Array<string> | null; "name": string; "openIssues": number; "outdated": boolean; "preferredDeprecatedReason"?: string; "preferredDesc": string; "preferredFunding": string; "preferredName": string; "preferredReadme": string; "preview"?: string; "previewURL": string; "rating"?: BazaarPackageRating; "ratingAvailable": boolean; "readme": Record<string, string> | null; "repoHash": string; "repoRef"?: string; "repoURL": string; "size": number; "stars": number; "updateRequiredMinAppVer"?: string; "updateTime": number; "updated": string; "url": string; "userDisabledInPublish"?: boolean; "version": string; };
+export type BazaarPackage = { "alternatives"?: Array<string>; "author": string; "backends": Array<string> | null; "bazaarIncompatible"?: boolean; "bootAppearances"?: Array<string>; "current": boolean; "deprecated"?: boolean; "deprecatedReason"?: Record<string, string>; "description": Record<string, string> | null; "disabledInPublish": boolean; "disallowInstall": boolean; "disallowUpdate": boolean; "displayName": Record<string, string> | null; "downloads": number; "enabled"?: boolean; "frontends": Array<string> | null; "funding": BazaarFunding | null; "hInstallDate": string; "hInstallSize": string; "hSize": string; "hUpdated": string; "hasStorageData"?: boolean; "icon"?: string; "iconURL": string; "installSize": number; "installTime": number; "installed": boolean; "installedIncompatible"?: boolean; "invalidReason"?: "missing-manifest" | "invalid-manifest" | "name-mismatch"; "kernels": Array<string> | null; "keywords": Array<string> | null; "minAppVersion": string; "modes"?: Array<string> | null; "name": string; "openIssues": number; "outdated": boolean; "preferredDeprecatedReason"?: string; "preferredDesc": string; "preferredFunding": string; "preferredName": string; "preferredReadme": string; "preview"?: string; "previewURL": string; "rating"?: BazaarPackageRating; "ratingAvailable": boolean; "readme": Record<string, string> | null; "repoHash": string; "repoRef"?: string; "repoURL": string; "settingsWindow"?: boolean; "size": number; "stars": number; "updateRequiredMinAppVer"?: string; "updateTime": number; "updated": string; "url": string; "userDisabledInPublish"?: boolean; "version": string; };
export type BazaarPackageDetail = { "available": BazaarPackage | null; "installed": BazaarPackage | null; };
@@ -1328,7 +1328,7 @@ export type ListNotebooksData = { "boxDocEnabled": boolean; "notebooks": Array<N
export type ListNotebooksRequestInput = { "flashcard"?: boolean | null; };
-export type LoadPetalsRequestInput = { "frontend": string; };
+export type LoadPetalsRequestInput = { "frontend": string; "settingsWindow"?: boolean; };
export type LoadedPlugin = { "methods": Array<PluginRPCMethod | null> | null; "name": string; "state": string; "stateCode": number; };
@@ -1516,7 +1516,7 @@ export type PerformSyncRequestInput = { "mobileSwitch"?: boolean | null; "upload
export type PerformTransactionsRequestInput = { "app"?: string; "reqId": number; "session"?: string; "transactions": Array<TransactionInput | null>; };
-export type Petal = { "css": string; "disabledInPublish": boolean; "disallowInstall": boolean; "displayName": string; "enabled": boolean; "i18n": { [key: string]: JSONValue } | null; "incompatible": boolean; "js": string; "kernel": KernelPetal; "name": string; "userDisabledInPublish": boolean; "version": string; };
+export type Petal = { "css": string; "disabledInPublish": boolean; "disallowInstall": boolean; "displayName": string; "enabled": boolean; "i18n": { [key: string]: JSONValue } | null; "incompatible": boolean; "js": string; "kernel": KernelPetal; "name": string; "settingsWindow"?: boolean; "userDisabledInPublish": boolean; "version": string; };
export type PinnedDoc = { "childrenSortMode": number | null; "icon": string; "id": string; "name": string; "notebook": string; "path": string; "subFileCount": number; "unavailable": boolean; };
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index 39133c5fab..c2fe21ff2a 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -799,6 +799,8 @@ interface ICommand {
}
interface IPluginData {
+ /** 内核已验证 plugin.json 的设置窗口运行声明;省略时不在设置窗口加载 */
+ settingsWindow?: boolean,
displayName: string,
name: string,
js: string,
diff --git a/app/tests/settingsBoot.test.js b/app/tests/settingsBoot.test.js
index a98e60c746..f1941df7ec 100644
--- a/app/tests/settingsBoot.test.js
+++ b/app/tests/settingsBoot.test.js
@@ -22,6 +22,7 @@ const createBoot = (plugin = false, failed = "", waitForStyles = false) => {
const events = new Map();
const eventOptions = new Map();
const documentEvents = new Map();
+ const pluginApp = {appId: "settings-app", plugins: []};
const menu = {hidden: true, handledKey: false,
element: {style: {zIndex: "12"}, classList: {contains: () => menu.hidden}},
remove: isKey => { calls.push(isKey ? "close-menu-key" : "close-menu"); menu.hidden = true; },
@@ -45,12 +46,19 @@ const createBoot = (plugin = false, failed = "", waitForStyles = false) => {
}, removeListener() {}, send: name => calls.push(name), invoke: async () => false}, webFrame: {setZoomFactor() {}}},
"../../constants": {Constants: constants},
"../../layout/Model": {Model: class {
+ constructor({app}) { assert.equal(app, pluginApp); }
ws = {close() {}};
connect() {}
flushMainMessages() {}
destroy() { calls.push("disconnect"); }
}},
"../../menus": {Menus: class {menu = menu;}},
+ "../../plugin/settingsApp": {createSettingsPluginApp: () => pluginApp},
+ "../../plugin/loader": {loadPlugins: async app => {
+ assert.equal(app, pluginApp);
+ calls.push("load-plugins");
+ }, afterLayoutReady: app => { assert.equal(app, pluginApp); calls.push("plugin-layout"); },
+ disposePlugins: app => { assert.equal(app, pluginApp); calls.push("dispose-plugins"); }},
"../../menus/Menu": {bindMenuKeydown: () => { calls.push("menu-keydown"); return menu.handledKey; }},
"../../menus/menuClick": {globalClickHideMenu: target => calls.push(target)},
"../../util/zIndex": {isAbove: (element, reference) => Number(element.style.zIndex) > Number(reference.style.zIndex)},
@@ -225,6 +233,9 @@ for (const plugin of [false, true]) {
assert.ok(boot.calls.indexOf("render") < boot.calls.indexOf("siyuan-settings-ready"));
assert.ok(boot.calls.indexOf("render") < boot.calls.indexOf("tooltips"));
assert.ok(boot.calls.indexOf("tooltips") < boot.calls.indexOf("siyuan-settings-ready"));
+ assert.ok(boot.calls.indexOf("render") < boot.calls.indexOf("load-plugins"));
+ assert.ok(boot.calls.indexOf("load-plugins") < boot.calls.indexOf("plugin-layout"));
+ assert.ok(boot.calls.indexOf("plugin-layout") < boot.calls.indexOf("siyuan-settings-ready"));
});
}
diff --git a/app/tests/settingsPlugins.test.js b/app/tests/settingsPlugins.test.js
new file mode 100644
index 0000000000..b64675d865
--- /dev/null
+++ b/app/tests/settingsPlugins.test.js
@@ -0,0 +1,220 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+
+const runCases = async sources => {
+ const check = require("node:assert/strict");
+ const load = (code, modules) => {
+ const exports = {};
+ new Function("require", "exports", code)(name => modules[name] || dependencies, exports);
+ return exports;
+ };
+ const errors = [];
+ const originalError = console.error;
+ console.error = (...args) => errors.push(args);
+ let preferences = {color: "red"};
+ let permitted = true;
+ let available = true;
+ let luteLoads = 0;
+ const requests = [];
+ const notifications = [];
+ const {PluginLifecycleCoordinator} = load(sources.lifecycle, {});
+ const settingsApps = load(sources.settingsApp, {});
+ const {GlobalPluginStateCoordinator} = load(sources.globalCoordinator, {});
+ const events = load(sources.events, {});
+ const owner = {appId: "owner", plugins: [{name: "dynamic", data: {color: "owner"}}]};
+ const app = settingsApps.createSettingsPluginApp("settings");
+ const host = {app: owner, applyPluginReload: data => { notifications.push(data); return Promise.resolve(); },
+ openPluginSetting: () => Promise.resolve()};
+ const windowContext = load(sources.windowContext, {electron: require("electron")});
+ windowContext.setSettingsWindowHost(host);
+ const dependencies = {
+ Constants: {INLINE_TYPE: [], TIMEOUT_INPUT: 0},
+ ...events,
+ Kernel: class {init() {} destroy() {}},
+ isSettingsWindow: windowContext.isSettingsWindow, getSettingsWindowHost: windowContext.getSettingsWindowHost,
+ isWindow: () => true, isMobile: () => false,
+ getFrontend: () => "desktop", getHostCapabilities: () => ({plugins: permitted}),
+ normalizeStoragePath: value => value,
+ fetchPost: (_url, _body, callback) => callback({...preferences}),
+ getAllEditor: () => [], getAllModels: () => ({custom: []}),
+ resolvePluginToolbar: () => [], clearPluginToolbarItems() {},
+ activateCustomBlockPlugin() {}, deactivateCustomBlockPlugin() {},
+ refreshDockCatalog() {}, applyTopBarEntryVisibility() {},
+ resizeTopBar() {}, setTabPosition() {}, saveLayout() {},
+ unregisterPluginCommands() {}, cancelAssetUploadsByPlugin() {}, releaseTrackedRangesByPlugin() {},
+ removeBreadcrumbButtons() {}, unregisterCapability() {},
+ registerPluginCommand() { throw new Error("settings registered a command"); },
+ sendGlobalShortcut() { throw new Error("settings changed global shortcuts"); },
+ updatePluginKeymap() { throw new Error("settings changed keymaps"); },
+ };
+ window.siyuan = {config: {bazaar: {petalDisabled: false}, readonly: false}, dialogs: [], layout: {}, storage: {}, ws: {app}};
+ document.body.className = "body--settings";
+ const pluginAPI = load(sources.plugin, {});
+ Object.assign(dependencies, pluginAPI);
+ const uninstall = load(sources.uninstall, {});
+ const dynamicCode = `const {Plugin} = require("siyuan"); module.exports = class extends Plugin {
+ async onload() {
+ window.pluginLoads = (window.pluginLoads || 0) + 1;
+ await this.onDataChanged();
+ this.eventBus.on("ws-main", () => window.pluginMessages = (window.pluginMessages || 0) + 1);
+ this.addCommand({langKey: "action", globalCallback() {}});
+ this.addTopBar({icon: "iconSettings", title: "Settings"});
+ this.addStatusBar({element: document.createElement("span")});
+ this.addToolbarItem({name: "custom"});
+ this.addDock({type: "custom", config: {}});
+ this.addTab({type: "custom"});
+ this.addBreadcrumbButton({id: "custom"});
+ }
+ onLayoutReady() { window.pluginLayouts = (window.pluginLayouts || 0) + 1; }
+ async onDataChanged(reason) {
+ const data = await this.loadData("prefs.json");
+ document.getElementById("dynamicStyle")?.remove();
+ const style = document.createElement("style"); style.id = "dynamicStyle";
+ style.textContent = ".dynamic-control {color: " + data.color + ";}";
+ document.head.append(style); document.body.classList.add("dynamic-enabled");
+ window.pluginReason = reason;
+ }
+ onunload() {
+ window.pluginUnloads = (window.pluginUnloads || 0) + 1;
+ document.getElementById("dynamicStyle")?.remove();
+ document.body.classList.remove("dynamic-enabled");
+ }
+ };`;
+ const declared = {name: "dynamic", displayName: "Dynamic", js: dynamicCode, css: "", i18n: {}, settingsWindow: true};
+ const legacy = {name: "legacy", displayName: "Legacy", js: "window.legacyExecuted = true;", css: "", i18n: {}};
+ const fetchSyncPost = async (url, data) => {
+ check.equal(url, "/api/petal/loadPetals");
+ requests.push(data);
+ return {code: 0, data: available ? [legacy, declared] : [legacy]};
+ };
+ const loader = load(sources.loader, {
+ "../util/fetch": {fetchSyncPost}, "./index": pluginAPI, "./uninstall": uninstall,
+ "./lifecycle": {PluginLifecycleCoordinator},
+ "./API": {getAPI: () => pluginAPI},
+ "../protyle/util/lute": {ensureLute: async () => luteLoads++},
+ });
+ const state = load(sources.global, {
+ "./loader": loader, "./settingsApp": settingsApps,
+ "./globalStateCoordinator": {GlobalPluginStateCoordinator}, "../util/fetch": {fetchSyncPost},
+ });
+ const control = document.createElement("div");
+ control.className = "dynamic-control";
+ control.textContent = "Settings";
+ document.body.append(control);
+ try {
+ await loader.loadPlugins(app, undefined, false);
+ await loader.afterLayoutReady(app);
+ check.equal(app.plugins.length, 1);
+ const first = app.plugins[0];
+ check.notEqual(first, owner.plugins[0]);
+ check.equal(owner.plugins[0].data.color, "owner");
+ check.equal(window.legacyExecuted, undefined);
+ check.equal(getComputedStyle(control).color, "rgb(255, 0, 0)");
+ check.equal(window.pluginLoads, 1);
+ check.equal(window.pluginLayouts, 1);
+ document.body.classList.remove("body--settings");
+ check.equal(windowContext.isSettingsWindow(), true);
+ check.equal(windowContext.getSettingsOwnerApp(), owner);
+ first.addCommand({langKey: "after-style-change", globalCallback() {}});
+ check.deepEqual(first.commands, []);
+ check.deepEqual(first.docks, {});
+ check.deepEqual(first.statusBarIcons, []);
+ events.emitToPlugins("ws-main", {cmd: "setLocalStorageVal"});
+ check.equal(window.pluginMessages, 1);
+ preferences = {color: "blue"};
+ await state.applyPluginReload(app, {dataChangePlugins: ["dynamic"], dataChangeReason: "overwrite"});
+ check.equal(app.plugins[0], first);
+ check.equal(getComputedStyle(control).color, "rgb(0, 0, 255)");
+ check.equal(window.pluginReason, "overwrite");
+ check.equal(notifications.length, 0);
+ await state.applyPluginReload(owner, {reloadPlugins: ["dynamic"]});
+ check.equal(notifications.length, 1);
+ await state.applyPluginReload(app, {unloadPlugins: ["dynamic"]});
+ check.equal(app.plugins.length, 0);
+ check.equal(document.getElementById("dynamicStyle"), null);
+ check.equal(document.body.classList.contains("dynamic-enabled"), false);
+ events.emitToPlugins("ws-main", {});
+ check.equal(window.pluginMessages, 1);
+ await state.applyPluginReload(app, {reloadPlugins: ["dynamic"]});
+ check.equal(app.plugins.length, 1);
+ check.notEqual(app.plugins[0], first);
+ await state.applyPluginReload(app, {globalPetalEnabled: false, globalPetalDisabled: true,
+ globalPetalRevision: 1, globalPetalChanged: true, unloadPlugins: ["dynamic"]});
+ check.equal(app.plugins.length, 0);
+ check.equal(window.siyuan.config.bazaar.petalDisabled, true);
+ await state.applyPluginReload(app, {globalPetalEnabled: true, globalPetalDisabled: false,
+ globalPetalRevision: 2, globalPetalChanged: true, reloadPlugins: ["dynamic"]});
+ check.equal(app.plugins.length, 1);
+ available = false;
+ const luteBefore = luteLoads;
+ await loader.refreshPlugins(app);
+ check.equal(app.plugins.length, 0);
+ check.equal(luteLoads, luteBefore);
+ available = true;
+ await loader.refreshPlugins(app);
+ check.equal(app.plugins.length, 1);
+ loader.disposePlugins(app);
+ loader.disposePlugins(app);
+ check.equal(app.plugins.length, 0);
+ check.equal(owner.plugins.length, 1);
+ check.equal(document.getElementById("dynamicStyle"), null);
+ check.ok(requests.every(item => item.settingsWindow === true && item.frontend === "desktop"));
+ check.ok(luteLoads > 0);
+ permitted = false;
+ const requestCount = requests.length;
+ await loader.loadPlugins(settingsApps.createSettingsPluginApp("untrusted"), undefined, false);
+ check.equal(requests.length, requestCount);
+ check.deepEqual(errors, []);
+ } finally {
+ loader.disposePlugins(app);
+ console.error = originalError;
+ }
+};
+
+if (process.versions.electron && process.type === "browser") {
+ const {app, BrowserWindow} = require("electron");
+ const ts = require("typescript");
+ app.setPath("userData", process.argv[2]);
+ app.commandLine.appendSwitch("disable-gpu");
+ app.whenReady().then(async () => {
+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false}});
+ let code = 0;
+ try {
+ const sources = Object.fromEntries(Object.entries({loader: "loader", plugin: "index", lifecycle: "lifecycle",
+ settingsApp: "settingsApp", global: "globalState", globalCoordinator: "globalStateCoordinator",
+ events: "EventBusCore", uninstall: "uninstall"}).map(([key, file]) => [key,
+ ts.transpileModule(fs.readFileSync(path.join(__dirname, "../src/plugin", file + ".ts"), "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},
+ }).outputText]));
+ sources.windowContext = ts.transpileModule(fs.readFileSync(path.join(__dirname,
+ "../src/config/setting/windowContext.ts"), "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},
+ }).outputText;
+ await win.loadURL("about:blank");
+ await win.webContents.executeJavaScript(`(${runCases.toString()})(${JSON.stringify(sources)})`);
+ } catch (error) {
+ console.error(error);
+ code = 1;
+ } finally {
+ win.destroy();
+ app.exit(code);
+ }
+ });
+} else {
+ const {test} = require("node:test");
+ const {execFile} = require("node:child_process");
+ const {promisify} = require("node:util");
+ test("settings plugin instances isolate lifecycle, UI, dynamic styles, configuration and event resources", async () => {
+ const profile = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-settings-plugins-"));
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ await promisify(execFile)(require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 30000});
+ } finally {
+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));
+ fs.rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});
+ }
+ });
+}
diff --git a/app/tests/settingsWindow.test.js b/app/tests/settingsWindow.test.js
index 40c756b1d7..80d6878627 100644
--- a/app/tests/settingsWindow.test.js
+++ b/app/tests/settingsWindow.test.js
@@ -161,6 +161,17 @@ const bootChild = async (sources) => {
check.ok(pluginEvents.includes("before-show-tooltip"));
check.ok(pluginEvents.includes("before-hide-tooltip"));
button.remove();
+ const {Setting: NestedSetting} = loadRendererModule(sources.setting, {
+ "../util/functions": {isMobile: () => false, getFrontend: frontend.getFrontend}, "../dialog": {Dialog},
+ "../config/setting/nativeWindow": {}, "../config/setting/windowContext": context,
+ "../config/setting/windowDialog": fit, "../util/genID": {genUUID},
+ });
+ const rootDialog = window.siyuan.dialogs[0];
+ const nested = new NestedSetting({});
+ nested.open("Nested settings");
+ check.equal(nested.dialog.element.querySelector(".toolbar"), null);
+ nested.close();
+ check.equal(window.siyuan.dialogs.includes(rootDialog), true);
if (!document.getElementById("pendingTheme").sheet) throw new Error("settings shown before theme loaded");
ipcRenderer.send("siyuan-settings-ready");
ipcRenderer.send("test-settings-ready");
@@ -216,6 +227,7 @@ const runCases = async (sources) => {
"../render/render": {}, "../search/normalize": {getSearchKeywordsLower: () => ""},
"../../constants": {Constants: {DIALOG_SETTING: "settings"}},
"./tabs": {getSettingTab: () => ({mount: async root => { remounted++; root.innerHTML = markup(); }})},
+ "./windowContext": {getSettingsOwnerApp: () => window.siyuan.ws.app},
});
const saving = loadRendererModule(sources.save, {
"./mount": mounting,
diff --git a/kernel/api/contract_petal.go b/kernel/api/contract_petal.go
index 15bca54317..c9573a0ffb 100644
--- a/kernel/api/contract_petal.go
+++ b/kernel/api/contract_petal.go
@@ -23,7 +23,8 @@ func petalContract(value *model.Petal) (*apicontract.Petal, error) {
Name: value.Name, DisplayName: value.DisplayName, Version: value.Version,
Enabled: value.Enabled, Incompatible: value.Incompatible, DisabledInPublish: value.DisabledInPublish,
UserDisabledInPublish: value.UserDisabledInPublish, DisallowInstall: value.DisallowInstall,
- JS: value.JS, CSS: value.CSS, I18n: i18n,
+ SettingsWindow: value.SettingsWindow,
+ JS: value.JS, CSS: value.CSS, I18n: i18n,
Kernel: apicontract.KernelPetal{JS: value.Kernel.JS, Existed: value.Kernel.Existed, Incompatible: value.Kernel.Incompatible},
}, nil
}
diff --git a/kernel/api/contract_petal_test.go b/kernel/api/contract_petal_test.go
index e077c8a6fb..36b8b41614 100644
--- a/kernel/api/contract_petal_test.go
+++ b/kernel/api/contract_petal_test.go
@@ -3,14 +3,18 @@ package api
import (
"encoding/json"
"github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
"net/http/httptest"
+ "os"
+ "path/filepath"
"strings"
"testing"
)
func TestAPIContractPetalConversion(t *testing.T) {
- for _, value := range []*model.Petal{nil, {}, {Name: "plugin", Enabled: true, I18n: map[string]any{"nested": map[string]any{"label": "text"}, "array": []any{true, nil, 1.5}}, Kernel: model.KernelPetal{JS: "code", Existed: true}}} {
+ for _, value := range []*model.Petal{nil, {}, {Name: "plugin", Enabled: true, SettingsWindow: true, I18n: map[string]any{"nested": map[string]any{"label": "text"}, "array": []any{true, nil, 1.5}}, Kernel: model.KernelPetal{JS: "code", Existed: true}}} {
result, err := petalContract(value)
if err != nil {
t.Fatal(err)
@@ -37,3 +41,55 @@ func TestAPIContractPetalInvalidRequests(t *testing.T) {
}
}
}
+
+func TestAPIContractPetalSettingsWindow(t *testing.T) {
+ originalConf, originalDataDir := model.Conf, util.DataDir
+ model.Conf = model.NewAppConf()
+ model.Conf.Sync = conf.NewSync()
+ model.Conf.Bazaar = &conf.Bazaar{Trust: true}
+ util.DataDir = t.TempDir()
+ t.Cleanup(func() { model.Conf, util.DataDir = originalConf, originalDataDir })
+ for _, name := range []string{"opted", "legacy"} {
+ dir := filepath.Join(util.DataDir, "plugins", name)
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ manifest, _ := json.Marshal(map[string]any{"name": name, "version": "1.0.0", "minAppVersion": "0.0.1", "settingsWindow": name == "opted"})
+ if err := os.WriteFile(filepath.Join(dir, "plugin.json"), manifest, 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "index.js"), []byte("module.exports = class {};"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := model.SetPetalEnabled(name, true); err != nil {
+ t.Fatal(err)
+ }
+ }
+ engine := gin.New()
+ engine.POST("/api/petal/loadPetals", loadPetals)
+ for _, item := range []struct {
+ body string
+ count int
+ }{
+ {`{"frontend":"desktop"}`, 2},
+ {`{"frontend":"desktop","settingsWindow":false}`, 2},
+ {`{"frontend":"desktop","settingsWindow":true}`, 1},
+ } {
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/petal/loadPetals", strings.NewReader(item.body)))
+ requireAPIContract(t, "POST", "/api/petal/loadPetals", recorder)
+ var response struct {
+ Code int `json:"code"`
+ Data []*model.Petal `json:"data"`
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
+ t.Fatal(err)
+ }
+ if response.Code != 0 || len(response.Data) != item.count {
+ t.Fatalf("unexpected plugin response: %s", recorder.Body.String())
+ }
+ if item.count == 1 && (response.Data[0].Name != "opted" || !response.Data[0].SettingsWindow) {
+ t.Fatal("opt-in proof missing")
+ }
+ }
+}
diff --git a/kernel/api/petal.go b/kernel/api/petal.go
index 023321f459..817a1048b1 100644
--- a/kernel/api/petal.go
+++ b/kernel/api/petal.go
@@ -28,7 +28,12 @@ var loadPetals = contractHandler(apicontract.LoadPetals, func(c *gin.Context, re
if model.IsReadOnlyRoleContext(c) {
c.Header("Cache-Control", "private, no-store")
}
- values := model.LoadPetals(request.Frontend, model.IsReadOnlyRoleContext(c))
+ var values []*model.Petal
+ if request.SettingsWindow {
+ values = model.LoadSettingsWindowPetals(request.Frontend, model.IsReadOnlyRoleContext(c))
+ } else {
+ values = model.LoadPetals(request.Frontend, model.IsReadOnlyRoleContext(c))
+ }
var result []*apicontract.Petal
if values != nil {
result = make([]*apicontract.Petal, len(values))
diff --git a/kernel/apicontract/bazaar.go b/kernel/apicontract/bazaar.go
index 562d303612..b99541535d 100644
--- a/kernel/apicontract/bazaar.go
+++ b/kernel/apicontract/bazaar.go
@@ -235,6 +235,7 @@ type BazaarPackage struct {
Kernels []string `json:"kernels"`
Backends []string `json:"backends"`
Frontends []string `json:"frontends"`
+ SettingsWindow bool `json:"settingsWindow,omitempty"` // 声明支持在独立设置窗口运行
BootAppearances []string `json:"bootAppearances,omitempty"`
DisplayName BazaarLocaleStrings `json:"displayName"`
Description BazaarLocaleStrings `json:"description"`
diff --git a/kernel/apicontract/petal.go b/kernel/apicontract/petal.go
index 679f2eef52..ca8d0cb667 100644
--- a/kernel/apicontract/petal.go
+++ b/kernel/apicontract/petal.go
@@ -2,6 +2,9 @@ package apicontract
type LoadPetalsRequest struct {
Frontend string `json:"frontend" api:"trim"`
+ // 为 true 时仅返回 plugin.json 声明 settingsWindow: true 的已启用兼容插件;省略或 false 保持原有行为。
+ // 设置窗口仍使用 desktop 的前端兼容性,不影响插件的 frontends 声明和发布权限检查。
+ SettingsWindow bool `json:"settingsWindow,omitempty" api:"optional"`
}
type SetPetalEnabledRequest struct {
@@ -16,18 +19,20 @@ type SetPetalPublishEnabledRequest struct {
}
type Petal struct {
- Name string `json:"name"`
- DisplayName string `json:"displayName"`
- Version string `json:"version"`
- Enabled bool `json:"enabled"`
- Incompatible bool `json:"incompatible"`
- DisabledInPublish bool `json:"disabledInPublish"`
- UserDisabledInPublish bool `json:"userDisabledInPublish"`
- DisallowInstall bool `json:"disallowInstall"`
- JS string `json:"js"`
- CSS string `json:"css"`
- I18n map[string]JSONValue `json:"i18n"`
- Kernel KernelPetal `json:"kernel"`
+ Name string `json:"name"`
+ DisplayName string `json:"displayName"`
+ Version string `json:"version"`
+ Enabled bool `json:"enabled"`
+ Incompatible bool `json:"incompatible"`
+ DisabledInPublish bool `json:"disabledInPublish"`
+ UserDisabledInPublish bool `json:"userDisabledInPublish"`
+ DisallowInstall bool `json:"disallowInstall"`
+ // 设置窗口筛选响应中为 true;旧内核或普通加载响应可以省略,客户端不能把省略当成主动声明。
+ SettingsWindow bool `json:"settingsWindow,omitempty"`
+ JS string `json:"js"`
+ CSS string `json:"css"`
+ I18n map[string]JSONValue `json:"i18n"`
+ Kernel KernelPetal `json:"kernel"`
}
type KernelPetal struct {
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 8478e79066..5263e5c14e 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -16628,6 +16628,9 @@
"repoURL": {
"type": "string"
},
+ "settingsWindow": {
+ "type": "boolean"
+ },
"size": {
"type": "integer"
},
@@ -29851,6 +29854,9 @@
"properties": {
"frontend": {
"type": "string"
+ },
+ "settingsWindow": {
+ "type": "boolean"
}
},
"required": [
@@ -34047,6 +34053,9 @@
"name": {
"type": "string"
},
+ "settingsWindow": {
+ "type": "boolean"
+ },
"userDisabledInPublish": {
"type": "boolean"
},
diff --git a/kernel/bazaar/package.go b/kernel/bazaar/package.go
index 422c45f2e2..c8e7323a1f 100644
--- a/kernel/bazaar/package.go
+++ b/kernel/bazaar/package.go
@@ -71,6 +71,7 @@ type Package struct {
Kernels []string `json:"kernels"`
Backends []string `json:"backends"`
Frontends []string `json:"frontends"`
+ SettingsWindow bool `json:"settingsWindow,omitempty"` // 声明支持在独立设置窗口运行
BootAppearances []string `json:"bootAppearances,omitempty"`
DisplayName LocaleStrings `json:"displayName"`
Description LocaleStrings `json:"description"`
diff --git a/kernel/model/plugin.go b/kernel/model/plugin.go
index e8ff804285..57dda87b1a 100644
--- a/kernel/model/plugin.go
+++ b/kernel/model/plugin.go
@@ -34,14 +34,15 @@ import (
// Petal represents a plugin's management status.
type Petal struct {
- Name string `json:"name"` // Plugin name
- DisplayName string `json:"displayName"` // Plugin display name
- Version string `json:"version"` // Plugin version
- Enabled bool `json:"enabled"` // Whether enabled
- Incompatible bool `json:"incompatible"` // Whether incompatible
- DisabledInPublish bool `json:"disabledInPublish"` // Whether disabled in publish mode
- UserDisabledInPublish bool `json:"userDisabledInPublish"` // 是否由用户在发布服务中禁用
- DisallowInstall bool `json:"disallowInstall"` // Whether disallow install
+ Name string `json:"name"` // Plugin name
+ DisplayName string `json:"displayName"` // Plugin display name
+ Version string `json:"version"` // Plugin version
+ Enabled bool `json:"enabled"` // Whether enabled
+ Incompatible bool `json:"incompatible"` // Whether incompatible
+ DisabledInPublish bool `json:"disabledInPublish"` // Whether disabled in publish mode
+ UserDisabledInPublish bool `json:"userDisabledInPublish"` // 是否由用户在发布服务中禁用
+ DisallowInstall bool `json:"disallowInstall"` // Whether disallow install
+ SettingsWindow bool `json:"settingsWindow,omitempty"` // 已验证设置窗口运行声明
JS string `json:"js"` // JS code
CSS string `json:"css"` // CSS code
@@ -201,6 +202,20 @@ func LoadKernelPetals() (ret []*Petal) {
return v.([]*Petal)
}
+// LoadSettingsWindowPetals 保留启用、信任、前端兼容和发布权限检查,只返回主动声明支持设置窗口的插件。
+func LoadSettingsWindowPetals(frontend string, isPublish bool) (ret []*Petal) {
+ ret = []*Petal{}
+ for _, petal := range LoadPetals(frontend, isPublish) {
+ manifest, err := bazaar.ParsePackageJSON(filepath.Join(util.DataDir, "plugins", petal.Name, "plugin.json"))
+ if err == nil && bazaar.IsValidInstalledPackage(manifest, petal.Name) && manifest.SettingsWindow {
+ copy := *petal
+ copy.SettingsWindow = true
+ ret = append(ret, &copy)
+ }
+ }
+ return
+}
+
func loadPetals(frontend string, isPublish, isKernel bool) (ret []*Petal) {
ret = []*Petal{}
diff --git a/kernel/model/plugin_settings_test.go b/kernel/model/plugin_settings_test.go
new file mode 100644
index 0000000000..a0684643cf
--- /dev/null
+++ b/kernel/model/plugin_settings_test.go
@@ -0,0 +1,65 @@
+package model
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestLoadSettingsWindowPetals(t *testing.T) {
+ originalConf, originalDataDir := Conf, util.DataDir
+ Conf = NewAppConf()
+ Conf.Sync = conf.NewSync()
+ Conf.Bazaar = &conf.Bazaar{Trust: true}
+ util.DataDir = t.TempDir()
+ t.Cleanup(func() { Conf, util.DataDir = originalConf, originalDataDir })
+ for _, item := range []struct {
+ name, declaration, frontend string
+ enabled bool
+ }{
+ {"opted", `,"settingsWindow":true`, "desktop", true},
+ {"legacy", "", "desktop", true},
+ {"rejected", `,"settingsWindow":false`, "desktop", true},
+ {"disabled", `,"settingsWindow":true`, "desktop", false},
+ {"incompatible", `,"settingsWindow":true`, "browser-desktop", true},
+ } {
+ dir := filepath.Join(util.DataDir, "plugins", item.name)
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ manifest := fmt.Sprintf(`{"name":%q,"version":"1.0.0","minAppVersion":"0.0.1","frontends":[%q]%s}`, item.name, item.frontend, item.declaration)
+ if err := os.WriteFile(filepath.Join(dir, "plugin.json"), []byte(manifest), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "index.js"), []byte("module.exports = class {};"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := SetPetalEnabled(item.name, item.enabled); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if ordinary := LoadPetals("desktop", false); len(ordinary) != 3 {
+ t.Fatalf("ordinary loading changed: %+v", ordinary)
+ }
+ selected := LoadSettingsWindowPetals("desktop", false)
+ if len(selected) != 1 || selected[0].Name != "opted" || !selected[0].SettingsWindow {
+ t.Fatalf("unexpected settings plugins: %+v", selected)
+ }
+ if ordinary := LoadPetals("desktop", false); len(ordinary) != 3 {
+ t.Fatal("settings loading changed ordinary loading")
+ }
+ Conf.Bazaar.PetalDisabled = true
+ if len(LoadSettingsWindowPetals("desktop", false)) != 0 {
+ t.Fatal("globally disabled plugins loaded")
+ }
+ Conf.Bazaar.PetalDisabled, Conf.Bazaar.Trust = false, false
+ if util.Container == util.ContainerStd || util.Container == util.ContainerDocker {
+ if len(LoadSettingsWindowPetals("desktop", false)) != 0 {
+ t.Fatal("untrusted plugins loaded")
+ }
+ }
+}