Skip to content

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

:art: Improve plugin storage change notifications https://github.com/siyuan-note/siyuan/issues/19132

Daniel8d7e1df21cb8
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index d6691b68eb..e3d18b21e5 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "تعطيل SSE المستقل",
+ "aiMcpDisableStandaloneSSETip": "يمنع اتصال SSE المستقل مع إبقاء طلبات Streamable HTTP متاحة",
"textDirection": "اتجاه النص",
"contextFilter": "مرشح السياق",
"contextFilterTip": "يُطبّق على جميع طرق العرض في كتلة قاعدة البيانات هذه",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index bf62a7c830..9efb8a2260 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "Eigenständiges SSE deaktivieren",
+ "aiMcpDisableStandaloneSSETip": "Verhindert die eigenständige SSE-Verbindung, während Streamable-HTTP-Anfragen verfügbar bleiben",
"textDirection": "Textrichtung",
"contextFilter": "Kontextfilter",
"contextFilterTip": "Gilt für alle Ansichten in diesem Datenbankblock",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 1bef8f8e20..900e0b77d3 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "Disable standalone SSE",
+ "aiMcpDisableStandaloneSSETip": "Prevents the standalone SSE connection while keeping Streamable HTTP requests available",
"textDirection": "Text direction",
"contextFilter": "Context filter",
"contextFilterTip": "Applies to every view in this database block",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 5d6bc0b237..46a10023e2 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "Desactivar SSE independiente",
+ "aiMcpDisableStandaloneSSETip": "Impide la conexión SSE independiente mientras mantiene disponibles las solicitudes de Streamable HTTP",
"textDirection": "Dirección del texto",
"contextFilter": "Filtro contextual",
"contextFilterTip": "Se aplica a todas las vistas de este bloque de base de datos",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index b94a75b95a..4b39d71b80 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "Désactiver le SSE autonome",
+ "aiMcpDisableStandaloneSSETip": "Empêche la connexion SSE autonome tout en maintenant les requêtes Streamable HTTP disponibles",
"textDirection": "Direction du texte",
"contextFilter": "Filtre contextuel",
"contextFilterTip": "S’applique à toutes les vues de ce bloc de base de données",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 95d61bf0e6..4622717e93 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "השבתת SSE עצמאי",
+ "aiMcpDisableStandaloneSSETip": "מונע את חיבור ה-SSE העצמאי תוך שמירה על בקשות Streamable HTTP זמינות",
"textDirection": "כיוון הטקסט",
"contextFilter": "מסנן הקשר",
"contextFilterTip": "חל על כל התצוגות בבלוק מסד הנתונים הזה",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 3ffea8d776..1f0e2af530 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "स्वतंत्र SSE अक्षम करें",
+ "aiMcpDisableStandaloneSSETip": "Streamable HTTP अनुरोधों को उपलब्ध रखते हुए स्वतंत्र SSE कनेक्शन को रोकता है",
"textDirection": "पाठ की दिशा",
"contextFilter": "संदर्भ फ़िल्टर",
"contextFilterTip": "इस डेटाबेस ब्लॉक के हर दृश्य पर लागू होता है",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 6167f4ccc1..e79e836673 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "Nonaktifkan SSE mandiri",
+ "aiMcpDisableStandaloneSSETip": "Mencegah koneksi SSE mandiri sambil mempertahankan permintaan Streamable HTTP",
"textDirection": "Arah teks",
"contextFilter": "Filter konteks",
"contextFilterTip": "Berlaku untuk setiap tampilan dalam blok basis data ini",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 1eee527bef..6254c63384 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "Disabilita SSE autonomo",
+ "aiMcpDisableStandaloneSSETip": "Impedisce la connessione SSE autonoma mantenendo disponibili le richieste Streamable HTTP",
"textDirection": "Direzione del testo",
"contextFilter": "Filtro contestuale",
"contextFilterTip": "Si applica a tutte le viste di questo blocco database",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 7aed6aaa18..b7bbac95f1 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "独立 SSE を無効化",
+ "aiMcpDisableStandaloneSSETip": "Streamable HTTP リクエストを維持したまま独立 SSE 接続を無効にします",
"textDirection": "テキストの方向",
"contextFilter": "コンテキストフィルター",
"contextFilterTip": "このデータベースブロックのすべてのビューに適用します",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index b6753945c8..a033125aeb 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "독립 SSE 비활성화",
+ "aiMcpDisableStandaloneSSETip": "Streamable HTTP 요청을 유지하면서 독립 SSE 연결을 차단합니다",
"textDirection": "텍스트 방향",
"contextFilter": "컨텍스트 필터",
"contextFilterTip": "이 데이터베이스 블록의 모든 보기에 적용됩니다",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 45a8061817..ed64960c46 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "Zelfstandige SSE uitschakelen",
+ "aiMcpDisableStandaloneSSETip": "Voorkomt de zelfstandige SSE-verbinding terwijl Streamable HTTP-verzoeken beschikbaar blijven",
"textDirection": "Tekstrichting",
"contextFilter": "Contextfilter",
"contextFilterTip": "Is van toepassing op alle weergaven in dit databaseblok",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 3a9897d537..6ea57d24dd 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "Wyłącz niezależne SSE",
+ "aiMcpDisableStandaloneSSETip": "Zapobiega niezależnemu połączeniu SSE, zachowując dostępność żądań Streamable HTTP",
"textDirection": "Kierunek tekstu",
"contextFilter": "Filtr kontekstowy",
"contextFilterTip": "Dotyczy wszystkich widoków w tym bloku bazy danych",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index ac24aaedb2..f9182e18f9 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "Desativar SSE independente",
+ "aiMcpDisableStandaloneSSETip": "Impede a conexão SSE independente, mantendo disponíveis as solicitações Streamable HTTP",
"textDirection": "Direção do texto",
"contextFilter": "Filtro contextual",
"contextFilterTip": "Aplica-se a todas as visualizações deste bloco de banco de dados",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 6ad514e532..41af371b3e 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "Отключить автономный SSE",
+ "aiMcpDisableStandaloneSSETip": "Предотвращает автономное SSE-подключение, сохраняя доступность запросов Streamable HTTP",
"textDirection": "Направление текста",
"contextFilter": "Контекстный фильтр",
"contextFilterTip": "Применяется ко всем представлениям в этом блоке базы данных",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index e3f01e57a8..62717b9078 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "Zakázať samostatné SSE",
+ "aiMcpDisableStandaloneSSETip": "Zabráni samostatnému pripojeniu SSE a zachová požiadavky Streamable HTTP dostupné",
"textDirection": "Smer textu",
"contextFilter": "Kontextový filter",
"contextFilterTip": "Použije sa na všetky zobrazenia v tomto databázovom bloku",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index ffcdf148cc..4f47ee32ea 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "ปิดใช้งาน SSE แบบสแตนด์อโลน",
+ "aiMcpDisableStandaloneSSETip": "ป้องกันการเชื่อมต่อ SSE แบบสแตนด์อโลนโดยยังคงใช้คำขอ Streamable HTTP ได้",
"textDirection": "ทิศทางข้อความ",
"contextFilter": "ตัวกรองบริบท",
"contextFilterTip": "ใช้กับทุกมุมมองในบล็อกฐานข้อมูลนี้",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index d2ad307aab..b5fb15cf86 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "Bağımsız SSE'yi devre dışı bırak",
+ "aiMcpDisableStandaloneSSETip": "Streamable HTTP isteklerini kullanılabilir tutarken bağımsız SSE bağlantısını engeller",
"textDirection": "Metin yönü",
"contextFilter": "Bağlam filtresi",
"contextFilterTip": "Bu veritabanı bloğundaki tüm görünümlere uygulanır",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 43ed237177..1275276132 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "Вимкнути автономний SSE",
+ "aiMcpDisableStandaloneSSETip": "Запобігає автономному SSE-з’єднанню, зберігаючи доступність запитів Streamable HTTP",
"textDirection": "Напрямок тексту",
"contextFilter": "Контекстний фільтр",
"contextFilterTip": "Застосовується до всіх подань у цьому блоці бази даних",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 3eeb5ae84b..073f53ca85 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "禁用独立 SSE",
+ "aiMcpDisableStandaloneSSETip": "禁止建立独立 SSE 连接,同时保留 Streamable HTTP 请求",
"textDirection": "文本方向",
"contextFilter": "上下文筛选",
"contextFilterTip": "应用于当前数据库块的所有视图",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index b31f00999f..1f7a0f31ac 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,6 @@
{
+ "aiMcpDisableStandaloneSSE": "停用獨立 SSE",
+ "aiMcpDisableStandaloneSSETip": "禁止建立獨立 SSE 連線,同時保留 Streamable HTTP 請求",
"textDirection": "文字方向",
"contextFilter": "情境篩選",
"contextFilterTip": "套用於此資料庫區塊的所有檢視",
diff --git a/app/src/config/tabs/ai/aiUi.ts b/app/src/config/tabs/ai/aiUi.ts
index e5e66a9c65..ba2eabe5f2 100644
--- a/app/src/config/tabs/ai/aiUi.ts
+++ b/app/src/config/tabs/ai/aiUi.ts
@@ -744,6 +744,7 @@ const openMcpServerDialogWithEnvironment = (root: HTMLElement, serverName: strin
url: "",
headers: {},
timeout: 30,
+ disableStandaloneSSE: false,
trustToolAnnotations: false,
} : existingServer;
const mcpTypeHidden = (fieldType: string) => initialServer.type !== fieldType ? " fn__none" : "";
@@ -818,6 +819,14 @@ const openMcpServerDialogWithEnvironment = (root: HTMLElement, serverName: strin
<div class="fn__hr"></div>
<textarea class="b3-text-field fn__block" id="aiMcpServerHeaders" rows="3" style="resize: vertical;" placeholder='{"Authorization":"Bearer ..."}'>${Lute.EscapeHTMLStr(headersText)}</textarea>
</div>
+ <div class="b3-label b3-label--inner fn__flex${mcpTypeHidden("http")}" data-mcp-type="http">
+ <div class="fn__flex-1">
+ <div class="config-name">${window.siyuan.languages.aiMcpDisableStandaloneSSE}</div>
+ <div class="b3-label__text">${window.siyuan.languages.aiMcpDisableStandaloneSSETip}</div>
+ </div>
+ <span class="fn__space"></span>
+ <input class="b3-switch fn__flex-center" id="aiMcpDisableStandaloneSSE" type="checkbox"${initialServer.disableStandaloneSSE ? " checked" : ""}/>
+ </div>
<div class="b3-label b3-label--inner">
<div class="config-name">${window.siyuan.languages.apiTimeout}</div>
<div class="fn__hr"></div>
@@ -888,6 +897,7 @@ const openMcpServerDialogWithEnvironment = (root: HTMLElement, serverName: strin
url: dialog.element.querySelector<HTMLInputElement>("#aiMcpServerUrl").value,
headers,
timeout: dialog.element.querySelector<HTMLInputElement>("#aiMcpServerTimeout").valueAsNumber,
+ disableStandaloneSSE: dialog.element.querySelector<HTMLInputElement>("#aiMcpDisableStandaloneSSE").checked,
trustToolAnnotations: dialog.element.querySelector<HTMLInputElement>("#aiMcpTrustToolAnnotations").checked,
};
if (!nextServer.name) {
diff --git a/app/src/plugin/index.ts b/app/src/plugin/index.ts
index b105cd2a7a..114d931f01 100644
--- a/app/src/plugin/index.ts
+++ b/app/src/plugin/index.ts
@@ -41,6 +41,8 @@ import {isBuiltinToolbarItemName} from "../protyle/toolbar/defaults";
import {getLegacyPluginTopBarEntryKey, getPluginTopBarEntryKey} from "./topBarKey";
import {applyTopBarEntryVisibility} from "../config/entryVisibility/runtime";
+export type TPluginDataChangeReason = "sync" | "overwrite";
+
const disposedPlugins = new WeakSet<Plugin>();
const isPluginDisposed = (plugin: Plugin) => disposedPlugins.has(plugin);
@@ -143,8 +145,14 @@ export class Plugin {
// 卸载
}
- public onDataChanged(): Promise<void> | void {
- // 存储数据变更
+ /**
+ * 插件实例就绪后存储数据发生变化时运行,思源会等待返回的 Promise;
+ * 未覆盖该方法时则重载整个插件。
+ * @param reason 数据变更来源,sync 为跨设备同步合并,overwrite 为其他前端实例通过文件接口写入
+ */
+ public onDataChanged(reason?: TPluginDataChangeReason): Promise<void> | void {
+ // 存储数据变更,子类可根据来源区分处理
+ void reason;
}
public async updateCards(options: ICardData) {
@@ -425,6 +433,7 @@ export class Plugin {
formData.append("path", pathString);
formData.append("file", file);
formData.append("isDir", "false");
+ formData.append("app", Constants.SIYUAN_APPID);
fetchPost("/api/file/putFile", formData, (response) => {
this.data[storageName] = data;
resolve(response);
@@ -447,7 +456,10 @@ export class Plugin {
if (!this.data) {
this.data = {};
}
- fetchPost("/api/file/removeFile", {path: `/data/storage/petal/${this.name}/${normalizeStoragePath(storageName)}`}, (response) => {
+ fetchPost("/api/file/removeFile", {
+ path: `/data/storage/petal/${this.name}/${normalizeStoragePath(storageName)}`,
+ app: Constants.SIYUAN_APPID,
+ }, (response) => {
delete this.data[storageName];
resolve(response);
});
diff --git a/app/src/plugin/lifecycle.test.ts b/app/src/plugin/lifecycle.test.ts
index be229a0c5a..a5d5b89925 100644
--- a/app/src/plugin/lifecycle.test.ts
+++ b/app/src/plugin/lifecycle.test.ts
@@ -707,6 +707,24 @@ describe("plugin lifecycle coordinator", () => {
assert.ok(mountIndex >= 0 && mountIndex < events.indexOf("data:sample:1"));
});
+ it("passes the latest coalesced data change reason to onDataChanged", async () => {
+ const {coordinator, events} = createHarness({
+ onDataChanged(plugin, reason) {
+ events.push(`data:${plugin.name}:${reason}`);
+ },
+ });
+ coordinator.start();
+ await coordinator.requestLoad("sample", getSampleData());
+ await coordinator.setLayoutReady();
+
+ const syncChange = coordinator.requestDataChange("sample", getSampleData(), "sync");
+ const overwriteChange = coordinator.requestDataChange("sample", getSampleData(), "overwrite");
+ await Promise.all([syncChange, overwriteChange]);
+
+ assert.equal(events.filter(event => event === "data:sample:overwrite").length, 1);
+ assert.equal(events.includes("data:sample:sync"), false);
+ });
+
it("decides the default data-change reload after the pending instance reaches ready", async () => {
const data = deferred<ITestPluginData>();
const inspectedRevisions: number[] = [];
diff --git a/app/src/plugin/lifecycle.ts b/app/src/plugin/lifecycle.ts
index 009e9178cb..0a01e037f7 100644
--- a/app/src/plugin/lifecycle.ts
+++ b/app/src/plugin/lifecycle.ts
@@ -1,3 +1,5 @@
+import type {TPluginDataChangeReason} from "./index";
+
export type TPluginLifecycleState =
"absent" |
"loading" |
@@ -28,7 +30,7 @@ export interface IPluginLifecycleAdapter<TData, TPlugin> {
onLayoutReady(plugin: TPlugin): Promise<void> | void;
mount(plugin: TPlugin): void;
shouldReloadOnDataChange(plugin: TPlugin): boolean;
- onDataChanged(plugin: TPlugin): Promise<void> | void;
+ onDataChanged(plugin: TPlugin, reason?: TPluginDataChangeReason): Promise<void> | void;
onunload(plugin: TPlugin): Promise<void> | void;
uninstall(plugin: TPlugin): Promise<void> | void;
markDisposed(plugin: TPlugin): void;
@@ -48,6 +50,7 @@ interface IPluginLifecycleTask<TData> {
kind: TPluginLifecycleTaskKind;
sequence: number;
dataProvider?: () => Promise<TData | undefined>;
+ dataChangeReason?: TPluginDataChangeReason;
uninstallHandled?: boolean;
waiters: Array<() => void>;
}
@@ -170,7 +173,8 @@ export class PluginLifecycleCoordinator<TData, TPlugin> {
return this.enqueueStructural(this.getRecord(name), "uninstall");
}
- public requestDataChange(name: string, dataProvider: () => Promise<TData | undefined>) {
+ public requestDataChange(name: string, dataProvider: () => Promise<TData | undefined>,
+ reason?: TPluginDataChangeReason) {
const record = this.getRecord(name);
const finalStructuralKind = this.getFinalStructuralKind(record);
if (finalStructuralKind === "unload" || finalStructuralKind === "uninstall" ||
@@ -179,12 +183,14 @@ export class PluginLifecycleCoordinator<TData, TPlugin> {
}
const existing = record.tasks.find((task) => task.kind === "dataChange");
if (existing) {
+ existing.dataChangeReason = reason;
return new Promise<void>((resolve) => existing.waiters.push(resolve));
}
return this.enqueue(record, {
kind: "dataChange",
sequence: 0,
dataProvider,
+ dataChangeReason: reason,
waiters: [],
});
}
@@ -434,7 +440,8 @@ export class PluginLifecycleCoordinator<TData, TPlugin> {
await this.runLoad(record, task, true);
return;
}
- await this.runInterruptibleHook(record, "onDataChanged", () => this.adapter.onDataChanged(plugin));
+ await this.runInterruptibleHook(record, "onDataChanged",
+ () => this.adapter.onDataChanged(plugin, task.dataChangeReason));
}
private async teardown(record: IPluginLifecycleRecord<TData, TPlugin>,
diff --git a/app/src/plugin/loader.ts b/app/src/plugin/loader.ts
index b62f9b7adc..421ccef53a 100644
--- a/app/src/plugin/loader.ts
+++ b/app/src/plugin/loader.ts
@@ -1,6 +1,6 @@
import {fetchSyncPost} from "../util/fetch";
import type {App} from "../index";
-import {markPluginDisposed, Plugin} from "./index";
+import {markPluginDisposed, Plugin, type TPluginDataChangeReason} from "./index";
/// #if !MOBILE
import {resizeTopBar, saveLayout} from "../layout/util";
import {getDockByType} from "../layout/tabUtil";
@@ -104,7 +104,7 @@ const getLifecycleManager = (app: App) => {
activateCustomBlockPlugin(plugin.name);
},
shouldReloadOnDataChange: (plugin) => plugin.onDataChanged === Plugin.prototype.onDataChanged,
- onDataChanged: (plugin) => plugin.onDataChanged(),
+ onDataChanged: (plugin, reason) => plugin.onDataChanged(reason),
onunload: (plugin) => {
deactivateCustomBlockPlugin(plugin.name);
beginPluginTeardown(plugin);
@@ -337,6 +337,7 @@ export interface IPluginReloadData {
unloadPlugins?: string[], // 插件禁用
reloadPlugins?: string[], // 插件启用,或插件代码变更
dataChangePlugins?: string[], // 插件存储数据变更
+ dataChangeReason?: TPluginDataChangeReason, // 插件存储数据变更来源
globalPetalEnabled?: boolean,
globalPetalDisabled?: boolean,
globalPetalRevision?: number,
@@ -359,7 +360,8 @@ export const reloadPlugin = async (app: App, data: IPluginReloadData = {}) => {
uninstallNames.forEach(name => tasks.push(manager.requestUninstall(name)));
unloadNames.forEach(name => tasks.push(manager.requestUnload(name)));
reloadNames.forEach(name => tasks.push(manager.requestReload(name, () => loadPluginData(name))));
- dataChangeNames.forEach(name => tasks.push(manager.requestDataChange(name, () => loadPluginData(name))));
+ dataChangeNames.forEach(name => tasks.push(manager.requestDataChange(name, () => loadPluginData(name),
+ data.dataChangeReason)));
await Promise.all(tasks);
if (reloadNames.size > 0 || dataChangeNames.size > 0) {
getAllEditor().forEach(editor => {
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index 3cb40cea02..86efea3601 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -281,6 +281,7 @@ declare namespace Config {
env?: Record<string, string>;
headers?: Record<string, string>;
timeout: number;
+ disableStandaloneSSE: boolean;
trustToolAnnotations: boolean;
}
diff --git a/kernel/api/file.go b/kernel/api/file.go
index d62b0ac8e8..e481721dd2 100644
--- a/kernel/api/file.go
+++ b/kernel/api/file.go
@@ -772,8 +772,9 @@ func removeFile(c *gin.Context) {
return
}
- var filePath string
+ var app, filePath string
if !util.ParseJsonArgs(arg, ret,
+ util.BindJsonArg("app", &app, false, false),
util.BindJsonArg("path", &filePath, true, true),
) {
return
@@ -811,6 +812,7 @@ func removeFile(c *gin.Context) {
ret.Msg = http.StatusText(http.StatusInternalServerError) + errMsgSeeKernelLog
return
}
+ model.PushPluginStorageDataChanged(fileAbsPath, app)
if affectsSync {
model.IncSync()
@@ -823,6 +825,7 @@ func putFile(c *gin.Context) {
isDirStr := c.PostForm("isDir")
isDir, _ := strconv.ParseBool(isDirStr)
+ app := c.PostForm("app")
var err error
filePath := c.PostForm("path")
@@ -937,6 +940,7 @@ func putFile(c *gin.Context) {
}
if !isDir {
+ model.PushPluginStorageDataChanged(fileAbsPath, app)
model.IncSyncIfNeeded(fileAbsPath)
}
}
diff --git a/kernel/api/petal.go b/kernel/api/petal.go
index cfd2589f11..dba3395a46 100644
--- a/kernel/api/petal.go
+++ b/kernel/api/petal.go
@@ -73,10 +73,10 @@ func setPetalEnabled(c *gin.Context) {
ret.Data = data
if enabled {
reloadPluginSet := hashset.New(packageName)
- model.PushReloadPlugin(nil, nil, reloadPluginSet, nil, app)
+ model.PushReloadPlugin(nil, nil, reloadPluginSet, nil, app, "")
} else {
unloadPluginSet := hashset.New(packageName)
- model.PushReloadPlugin(nil, unloadPluginSet, nil, nil, app)
+ model.PushReloadPlugin(nil, unloadPluginSet, nil, nil, app, "")
}
}
diff --git a/kernel/conf/ai.go b/kernel/conf/ai.go
index 8294fc2001..19adcc64b9 100644
--- a/kernel/conf/ai.go
+++ b/kernel/conf/ai.go
@@ -160,6 +160,7 @@ type MCPServer struct {
URL string `json:"url"`
Headers map[string]string `json:"headers"`
Timeout int `json:"timeout"`
+ DisableStandaloneSSE bool `json:"disableStandaloneSSE"`
TrustToolAnnotations bool `json:"trustToolAnnotations"`
}
@@ -926,6 +927,7 @@ func migrateMCP(raw map[string]any) *MCP {
URL: getString(sm, "url"),
Headers: getStringMap(sm, "headers"),
Timeout: getInt(sm, "timeout"),
+ DisableStandaloneSSE: getBool(sm, "disableStandaloneSSE"),
TrustToolAnnotations: getBool(sm, "trustToolAnnotations"),
})
}
diff --git a/kernel/conf/ai_mcp_test.go b/kernel/conf/ai_mcp_test.go
index a94cf29f32..196f28091f 100644
--- a/kernel/conf/ai_mcp_test.go
+++ b/kernel/conf/ai_mcp_test.go
@@ -84,8 +84,9 @@ func TestMigrateMCPEnvironment(t *testing.T) {
mcp := migrateMCP(map[string]any{
"servers": []any{
map[string]any{
- "name": "stdio",
- "inheritEnv": []any{"PATH", "HOME"},
+ "name": "stdio",
+ "inheritEnv": []any{"PATH", "HOME"},
+ "disableStandaloneSSE": true,
"env": map[string]any{
"TOKEN": "{{secrets.TOKEN}}",
},
@@ -96,7 +97,8 @@ func TestMigrateMCPEnvironment(t *testing.T) {
t.Fatalf("unexpected MCP servers: %#v", mcp.Servers)
}
server := mcp.Servers[0]
- if len(server.InheritEnv) != 2 || server.InheritEnv[0] != "PATH" || server.Env["TOKEN"] != "{{secrets.TOKEN}}" {
+ if len(server.InheritEnv) != 2 || server.InheritEnv[0] != "PATH" || server.Env["TOKEN"] != "{{secrets.TOKEN}}" ||
+ !server.DisableStandaloneSSE {
t.Fatalf("unexpected migrated environment: %#v", server)
}
}
diff --git a/kernel/mcp/client/mcp.go b/kernel/mcp/client/mcp.go
index f3b9ae8ff5..d11a3becc4 100644
--- a/kernel/mcp/client/mcp.go
+++ b/kernel/mcp/client/mcp.go
@@ -618,9 +618,7 @@ func connectHTTP(ctx context.Context, client *mcp.Client, server conf.MCPServer,
return nil, nil, nil, fmt.Errorf("url is required for http server")
}
- transport := &mcp.StreamableClientTransport{
- Endpoint: server.URL,
- }
+ transport := newStreamableClientTransport(server)
var oauthHandler *mcpOAuthHandler
if !hasAuthorizationHeader(server.Headers) {
oauthHandler = newMCPOAuthHandler(server, interactive)
@@ -653,6 +651,13 @@ func connectHTTP(ctx context.Context, client *mcp.Client, server conf.MCPServer,
return session, nil, oauthHandler, nil
}
+func newStreamableClientTransport(server conf.MCPServer) *mcp.StreamableClientTransport {
+ return &mcp.StreamableClientTransport{
+ Endpoint: server.URL,
+ DisableStandaloneSSE: server.DisableStandaloneSSE,
+ }
+}
+
func hasAuthorizationHeader(headers map[string]string) bool {
for name := range headers {
if strings.EqualFold(name, "Authorization") {
diff --git a/kernel/mcp/client/mcp_test.go b/kernel/mcp/client/mcp_test.go
index adc7266f42..71669eae21 100644
--- a/kernel/mcp/client/mcp_test.go
+++ b/kernel/mcp/client/mcp_test.go
@@ -42,6 +42,22 @@ func TestIsReconnectableError(t *testing.T) {
}
}
+func TestNewStreamableClientTransport(t *testing.T) {
+ for _, disableStandaloneSSE := range []bool{false, true} {
+ server := conf.MCPServer{
+ URL: "https://example.com/mcp",
+ DisableStandaloneSSE: disableStandaloneSSE,
+ }
+ transport := newStreamableClientTransport(server)
+ if transport.Endpoint != server.URL {
+ t.Fatalf("unexpected endpoint: %s", transport.Endpoint)
+ }
+ if transport.DisableStandaloneSSE != disableStandaloneSSE {
+ t.Fatalf("unexpected standalone SSE setting: %v", transport.DisableStandaloneSSE)
+ }
+ }
+}
+
func TestBuildStdioEnvironment(t *testing.T) {
server := conf.MCPServer{
InheritEnv: []string{"PATH", "MISSING"},
diff --git a/kernel/model/bazaar.go b/kernel/model/bazaar.go
index 5c0e4cc9aa..cba668ae1e 100644
--- a/kernel/model/bazaar.go
+++ b/kernel/model/bazaar.go
@@ -557,7 +557,7 @@ func finishInstall(pkgType string, items []batchInstallItem, themeOptions *Theme
}
}
if 0 < reloadPluginSet.Size() {
- PushReloadPlugin(nil, nil, reloadPluginSet, nil, "")
+ PushReloadPlugin(nil, nil, reloadPluginSet, nil, "", "")
}
case "themes":
for _, item := range items {
@@ -724,7 +724,7 @@ func UninstallPackage(pkgType, packageName string) error {
savePetals(petals)
uninstallPluginSet := hashset.New(packageName)
- PushReloadPlugin(uninstallPluginSet, nil, nil, nil, "")
+ PushReloadPlugin(uninstallPluginSet, nil, nil, nil, "", "")
case "themes":
InitAppearance()
WatchThemes()
diff --git a/kernel/model/push_reload.go b/kernel/model/push_reload.go
index f3558029a7..6bebb2fe49 100644
--- a/kernel/model/push_reload.go
+++ b/kernel/model/push_reload.go
@@ -46,7 +46,13 @@ func PushReloadSnippet(snippet *conf.Snpt) {
util.BroadcastByType("main", "setSnippet", 0, "", snippet)
}
-func PushReloadPlugin(uninstallPluginNameSet, unloadPluginNameSet, reloadPluginSet, dataChangePluginSet *hashset.Set, excludeApp string) {
+const (
+ DataChangeReasonSync = "sync"
+ DataChangeReasonOverwrite = "overwrite"
+)
+
+func PushReloadPlugin(uninstallPluginNameSet, unloadPluginNameSet, reloadPluginSet, dataChangePluginSet *hashset.Set,
+ excludeApp, dataChangeReason string) {
// 按优先级从高到低排列,同一插件只保留在优先级最高的集合中
orderedSets := []*hashset.Set{uninstallPluginNameSet, unloadPluginNameSet, reloadPluginSet, dataChangePluginSet}
slices := make([][]string, len(orderedSets))
@@ -79,10 +85,11 @@ func PushReloadPlugin(uninstallPluginNameSet, unloadPluginNameSet, reloadPluginS
logging.LogInfof("reload plugins, uninstalls=%v, unloads=%v, reloads=%v, dataChanges=%v", slices[0], slices[1], slices[2], slices[3])
payload := map[string]any{
- "uninstallPlugins": slices[0], // 插件卸载
- "unloadPlugins": slices[1], // 插件禁用
- "reloadPlugins": slices[2], // 插件启用,或插件代码变更
- "dataChangePlugins": slices[3], // 插件存储数据变更
+ "uninstallPlugins": slices[0], // 插件卸载
+ "unloadPlugins": slices[1], // 插件禁用
+ "reloadPlugins": slices[2], // 插件启用,或插件代码变更
+ "dataChangePlugins": slices[3], // 插件存储数据变更
+ "dataChangeReason": dataChangeReason, // 插件存储数据变更来源
}
if 0 < len(slices[0])+len(slices[1])+len(slices[2]) {
util.ReloadPublishServiceSessions()
@@ -95,6 +102,28 @@ func PushReloadPlugin(uninstallPluginNameSet, unloadPluginNameSet, reloadPluginS
util.BroadcastByTypeAndExcludeApp(excludeApp, "main", "reloadPlugin", 0, "", payload)
}
+// PushPluginStorageDataChanged 通知其他前端实例插件存储数据已变更。
+func PushPluginStorageDataChanged(absPath, excludeApp string) {
+ pluginName, ok := pluginStorageName(absPath)
+ if !ok {
+ return
+ }
+ PushReloadPlugin(nil, nil, nil, hashset.New(pluginName), excludeApp, DataChangeReasonOverwrite)
+}
+
+func pluginStorageName(absPath string) (pluginName string, ok bool) {
+ relPath, err := filepath.Rel(util.DataDir, absPath)
+ if nil != err {
+ return "", false
+ }
+ parts := strings.Split(filepath.ToSlash(relPath), "/")
+ if 3 > len(parts) || "storage" != parts[0] || "petal" != parts[1] || "" == parts[2] ||
+ "petals.json" == parts[2] {
+ return "", false
+ }
+ return parts[2], true
+}
+
// PushReloadAllEnabledPlugins 向前端推送已启用插件的全局状态,并返回相同的权威状态供请求方应用。
func PushReloadAllEnabledPlugins(enabled, petalDisabled bool, revision uint64, changed bool) map[string]any {
pluginNames := []string{}
diff --git a/kernel/model/push_reload_test.go b/kernel/model/push_reload_test.go
new file mode 100644
index 0000000000..4112a7e18e
--- /dev/null
+++ b/kernel/model/push_reload_test.go
@@ -0,0 +1,78 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "path/filepath"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestPluginStorageName(t *testing.T) {
+ originalDataDir := util.DataDir
+ util.DataDir = filepath.Join(t.TempDir(), "data")
+ t.Cleanup(func() {
+ util.DataDir = originalDataDir
+ })
+
+ tests := []struct {
+ name string
+ path string
+ pluginName string
+ ok bool
+ }{
+ {
+ name: "nested plugin data",
+ path: filepath.Join(util.DataDir, "storage", "petal", "sample", "nested", "data.json"),
+ pluginName: "sample",
+ ok: true,
+ },
+ {
+ name: "plugin storage root",
+ path: filepath.Join(util.DataDir, "storage", "petal", "sample"),
+ pluginName: "sample",
+ ok: true,
+ },
+ {
+ name: "petal configuration",
+ path: filepath.Join(util.DataDir, "storage", "petal", "petals.json"),
+ },
+ {
+ name: "petal storage root",
+ path: filepath.Join(util.DataDir, "storage", "petal"),
+ },
+ {
+ name: "other storage",
+ path: filepath.Join(util.DataDir, "storage", "local.json"),
+ },
+ {
+ name: "outside data directory",
+ path: filepath.Join(filepath.Dir(util.DataDir), "outside.json"),
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ pluginName, ok := pluginStorageName(test.path)
+ if test.pluginName != pluginName || test.ok != ok {
+ t.Fatalf("expected plugin name [%s] and ok [%v], got [%s] and [%v]",
+ test.pluginName, test.ok, pluginName, ok)
+ }
+ })
+ }
+}
diff --git a/kernel/model/repository.go b/kernel/model/repository.go
index 6572eccaba..f4397d81d1 100644
--- a/kernel/model/repository.go
+++ b/kernel/model/repository.go
@@ -2483,7 +2483,8 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,
}
if needReloadPlugin {
- PushReloadPlugin(uninstallPluginSet, unloadPluginSet, reloadPluginSet, dataChangePluginSet, "")
+ PushReloadPlugin(uninstallPluginSet, unloadPluginSet, reloadPluginSet, dataChangePluginSet, "",
+ DataChangeReasonSync)
}
if needReloadSnippet {