An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Scope operation notifications to the requesting frontend https://github.com/siyuan-note/siyuan/issues/20074
Daniel7d4a356314fc
diff --git a/app/src/ai/editorSSE.test.ts b/app/src/ai/editorSSE.test.tsindex bcc619c69a..f92f17847a 100644--- a/app/src/ai/editorSSE.test.ts+++ b/app/src/ai/editorSSE.test.ts@@ -1,6 +1,13 @@import * as assert from "node:assert/strict";-import test from "node:test";-import {createAIEditorSSEParserState, parseAIEditorSSE} from "./editorSSE";+import test, {before} from "node:test";++let createAIEditorSSEParserState: typeof import("./editorSSE").createAIEditorSSEParserState;+let parseAIEditorSSE: typeof import("./editorSSE").parseAIEditorSSE;+before(async () => {+ // 运行时常量通常由 webpack 提供。+ Object.assign(globalThis, {SIYUAN_VERSION: "test", NODE_ENV: "test"});+ ({createAIEditorSSEParserState, parseAIEditorSSE} = await import("./editorSSE"));+});test("parses fragmented AI editor SSE events", () => {const state = createAIEditorSSEParserState();diff --git a/app/src/ai/editorSSE.ts b/app/src/ai/editorSSE.tsindex a89ea07a02..65911c6cf9 100644--- a/app/src/ai/editorSSE.ts+++ b/app/src/ai/editorSSE.ts@@ -1,3 +1,4 @@+import {fetchWithAppId} from "../util/fetchWithAppId";export interface IAIEditorMessage {role: "user" | "assistant";content: string;@@ -92,7 +93,7 @@ export const fetchAIEditorSSE = async (onEvent: (event: TAIEditorSSEEvent) => void,signal: AbortSignal,) => {- const response = await fetch("/api/ai/editor/chat", {+ const response = await fetchWithAppId("/api/ai/editor/chat", {method: "POST",headers: {"Content-Type": "application/json"},body: JSON.stringify(request),diff --git a/app/src/config/setting/window.ts b/app/src/config/setting/window.tsindex d4c64cee83..c7d8d196e4 100644--- a/app/src/config/setting/window.ts+++ b/app/src/config/setting/window.ts@@ -242,7 +242,7 @@ const initialize = async () => {if (isActive()) ipcRenderer.send("siyuan-settings-ready");};-installPluginStorageFetchAppId(window, Constants.SIYUAN_APPID, window.location.href);+installPluginStorageFetchAppId(window, Constants.SIYUAN_APPID, document.baseURI, location.origin);void startSettingsWindow(initialize, error => {console.error("Could not initialize the settings window", error);disposeSettingsWindow();diff --git a/app/src/config/tabs/accessTab.ts b/app/src/config/tabs/accessTab.tsindex 5d55da54cb..8adf2734b4 100644--- a/app/src/config/tabs/accessTab.ts+++ b/app/src/config/tabs/accessTab.ts@@ -1,3 +1,4 @@+import {fetchWithAppId} from "../../util/fetchWithAppId";import {escapeHtmlTextAndAttr} from "../../util/escape";import type {SettingTabBuilder} from "../setting/builder";import {fetchPost, fetchSyncPost} from "../../util/fetch";@@ -541,7 +542,7 @@ const registerAccessServerGroup = (tab: SettingTabBuilder) => {if (input.files && input.files[0]) {const formData = new FormData();formData.append("file", input.files[0]);- fetch("/api/system/importTLSCABundle", {+ fetchWithAppId("/api/system/importTLSCABundle", {method: "POST",body: formData,}).then(res => res.json()).then((response) => {diff --git a/app/src/index.ts b/app/src/index.tsindex 2f1d987daa..abae0eefe5 100644--- a/app/src/index.ts+++ b/app/src/index.ts@@ -372,7 +372,7 @@ export class App {}}-installPluginStorageFetchAppId(window, Constants.SIYUAN_APPID, window.location.href);+installPluginStorageFetchAppId(window, Constants.SIYUAN_APPID, document.baseURI, location.origin);const siyuanApp = new App();window.openFileByURL = (openURL) => {diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.tsindex fc8b7a44fc..e2e4befa9a 100644--- a/app/src/layout/dock/agent/AgentChat.ts+++ b/app/src/layout/dock/agent/AgentChat.ts@@ -1,3 +1,4 @@+import {fetchWithAppId} from "../../../util/fetchWithAppId";import {Model} from "../../Model";import type {App} from "../../../index";import {AgentHttpError, fetchAgentSSE, IEditorContext, ISSEResult, IToolEffects} from "./agentSSE";@@ -3825,7 +3826,7 @@ export class AgentChat extends Model {const requestSessionID = this.sessionId;const userEntry = this.entries.find((e): e is { type: "user"; content: string } => e.type === "user");const userMsg = userEntry?.content?.slice(0, 500) || "";- fetch("/api/ai/agent/title", {+ fetchWithAppId("/api/ai/agent/title", {method: "POST",headers: {"Content-Type": "application/json"},body: JSON.stringify({@@ -4152,7 +4153,7 @@ export class AgentChat extends Model {body.always = true;}try {- const resp = await fetch("/api/ai/agent/confirm", {+ const resp = await fetchWithAppId("/api/ai/agent/confirm", {method: "POST",headers: {"Content-Type": "application/json"},body: JSON.stringify(body),@@ -4219,7 +4220,7 @@ export class AgentChat extends Model {structuredContentSet: boolean, isError: boolean) {for (let attempt = 0; attempt < 3; attempt++) {try {- const resp = await fetch("/api/ai/agent/browserCapabilityResult", {+ const resp = await fetchWithAppId("/api/ai/agent/browserCapabilityResult", {method: "POST",headers: {"Content-Type": "application/json"},body: JSON.stringify({callID, result, structuredContent, structuredContentSet, isError}),@@ -4358,7 +4359,7 @@ export class AgentChat extends Model {private async postQuestionAnswer(questionID: string, answers: string[],sessionID: string, questionEntryID: string): Promise<boolean> {try {- const resp = await fetch("/api/ai/agent/question", {+ const resp = await fetchWithAppId("/api/ai/agent/question", {method: "POST",headers: {"Content-Type": "application/json"},body: JSON.stringify({questionID: questionID, answers: answers}),diff --git a/app/src/layout/dock/agent/agentSSE.ts b/app/src/layout/dock/agent/agentSSE.tsindex 8cb2cd7e0b..2c9b264249 100644--- a/app/src/layout/dock/agent/agentSSE.ts+++ b/app/src/layout/dock/agent/agentSSE.ts@@ -1,3 +1,4 @@+import {fetchWithAppId} from "../../../util/fetchWithAppId";import {buildAgentConfirmEvent, IToolEffects} from "./agentConfirmEvent";export type {IToolEffects} from "./agentConfirmEvent";@@ -150,7 +151,7 @@ export async function fetchAgentSSE(if (typeof contentRevision === "number") { body.contentRevision = contentRevision; }if (blockHTML !== undefined) { body.blockHTML = blockHTML; }- const response = await fetch("/api/ai/agent/chat", {+ const response = await fetchWithAppId("/api/ai/agent/chat", {method: "POST",headers: {"Content-Type": "application/json",diff --git a/app/src/mobile/index.ts b/app/src/mobile/index.tsindex 5f9f692ca1..24fcb94093 100644--- a/app/src/mobile/index.ts+++ b/app/src/mobile/index.ts@@ -293,7 +293,7 @@ class App {}}-installPluginStorageFetchAppId(window, Constants.SIYUAN_APPID, window.location.href);+installPluginStorageFetchAppId(window, Constants.SIYUAN_APPID, document.baseURI, location.origin);const siyuanApp = new App();initWindowOpenOverride(siyuanApp, openByMobile);diff --git a/app/src/plugin/kernel.ts b/app/src/plugin/kernel.tsindex bd93e3e5b3..8eec346ed0 100644--- a/app/src/plugin/kernel.ts+++ b/app/src/plugin/kernel.ts@@ -1,3 +1,4 @@+import {fetchWithAppId} from "../util/fetchWithAppId";import {fetchSyncPost} from "../util/fetch";import type {EventBus} from "./EventBus";@@ -172,7 +173,7 @@ export class Kernel implements IKernelPlugin {if (this.#destroyed) {throw new Error("Plugin lifecycle has ended");}- const response = await fetch(this.#rpcCallUrl, {+ const response = await fetchWithAppId(this.#rpcCallUrl, {method: "POST",headers: { "Content-Type": "application/json" },body,diff --git a/app/src/protyle/toolbar/templatePreview.test.ts b/app/src/protyle/toolbar/templatePreview.test.tsindex c454d5ba96..b0c86c7402 100644--- a/app/src/protyle/toolbar/templatePreview.test.ts+++ b/app/src/protyle/toolbar/templatePreview.test.ts@@ -30,6 +30,7 @@ const loadPreview = () => {"../dialog/message": {showMessage: (message: string) => messages.push(message)},});const fetchModule = loadModule("../../util/fetch.ts", {+ "./fetchWithAppId": {fetchWithAppId: () => new Promise<Response>((resolve, reject) => requests.push({resolve, reject}))},"./processMessage": messagesModule,"./fetchTimeout": {withFetchTimeout},"../config/setting/pending": {trackSettingRequest},diff --git a/app/src/protyle/upload/index.test.ts b/app/src/protyle/upload/index.test.tsindex e9f5480d30..d80ea80750 100644--- a/app/src/protyle/upload/index.test.ts+++ b/app/src/protyle/upload/index.test.ts@@ -6,12 +6,14 @@ import {runInNewContext} from "node:vm";import * as ts from "typescript";import * as insertPosition from "./insertPosition";import * as uploadResult from "./uploadResult";+import * as fetchAppId from "../../util/fetchAppId";// 执行完整上传模块,替换网络、界面和插件等待,以控制文档切换发生的时刻。const createHarness = (failLocalUpload = false) => {const results: Array<{status: string}> = [];const completions: Array<Omit<IAssetUploadResult, "requestId" | "input"> | undefined> = [];const requests: Array<{id: string; respond(): void}> = [];+ const headers = new Headers();let resolvePlugin: (prepared: unknown) => void;let onComplete = () => {};let confirm: (() => void) | undefined;@@ -42,6 +44,7 @@ const createHarness = (failLocalUpload = false) => {upload = {};onreadystatechange: () => void;open() {}+ setRequestHeader(name: string, value: string) { headers.set(name, value); }send(form: FormDataStub) {requests.push({id: form.values.get("id") as string, respond: () => {this.readyState = 4;@@ -51,10 +54,11 @@ const createHarness = (failLocalUpload = false) => {}const mocks: Record<string, unknown> = {"./insertPosition": insertPosition,+ "../../util/fetchAppId": fetchAppId,"./uploadResult": uploadResult,"../runtimeCapabilities": {isProtyleUploadDisabled: () => false},"../../util/hostCapabilities": {getHostCapabilities: () => ({localFileSystem: true})},- "../../constants": {Constants: {SIZE_UPLOAD_TIP_SIZE: 1024}},+ "../../constants": {Constants: {SIZE_UPLOAD_TIP_SIZE: 1024, SIYUAN_APPID: "upload-window"}},"../../util/escape": {escapeHtml: (value: string) => value},"../../dialog/message": {showMessage: () => "message", hideMessage: () => {}},"../../dialog/confirmDialog": {confirmDialog: (_title: string, _msg: string, yes: () => void) => {@@ -85,7 +89,8 @@ const createHarness = (failLocalUpload = false) => {runInNewContext(compiled, {module, exports: module.exports, require: (name: string) => mocks[name] || {}, Promise,FormData: FormDataStub, XMLHttpRequest: XHRStub, DataTransferItem: class {},- document: {body: {contains: () => protyle.element.isConnected}},+ location: {origin: "https://siyuan.test"},+ document: {baseURI: "https://siyuan.test/stage/build/app/", body: {contains: () => protyle.element.isConnected}},window: {siyuan: {languages: {uploading: "uploading"}}}, console,});const api = module.exports as typeof import("./index");@@ -101,7 +106,7 @@ const createHarness = (failLocalUpload = false) => {true, options, () => { consumed++; }, (_succeeded, result) => completions.push(result));}};- return {protyle, requests, results, completions, start, resume: () => resolvePlugin(undefined),+ return {protyle, requests, results, completions, start, headers, resume: () => resolvePlugin(undefined),delayConfirmation: () => { delayConfirmation = true; }, confirm: () => confirm(),consumed: () => consumed, onComplete: (callback: () => void) => { onComplete = callback; }};};@@ -196,3 +201,17 @@ describe("upload document binding", () => {}}});+++it("limits upload app headers to same-origin API URLs", async () => {+ for (const url of ["/api/asset/upload", "../../../api/asset/upload", "/upload", "https://external.test/api/upload"]) {+ const harness = createHarness();+ harness.protyle.options.upload.url = url;+ harness.start("files");+ harness.resume();+ await settle();+ assert.equal(harness.requests.length, 1);+ assert.equal(harness.headers.get(fetchAppId.SIYUAN_APP_ID_HEADER),+ url.includes("/api/asset/upload") ? "upload-window" : null);+ }+});diff --git a/app/src/protyle/upload/index.ts b/app/src/protyle/upload/index.tsindex 38453f4078..2a8135ad93 100644--- a/app/src/protyle/upload/index.ts+++ b/app/src/protyle/upload/index.ts@@ -1,3 +1,4 @@+import {isSameOriginAPIRequest, SIYUAN_APP_ID_HEADER} from "../../util/fetchAppId";import {insertHTML} from "../util/insertHTML";import {hideMessage, showMessage} from "../../dialog/message";import {Constants} from "../../constants";@@ -479,6 +480,9 @@ const uploadPreparedFiles = (input: Extract<IAssetUploadInput, { kind: "files" }}const xhr = new XMLHttpRequest();xhr.open("POST", protyle.options.upload.url);+ if (isSameOriginAPIRequest(protyle.options.upload.url, document.baseURI, location.origin)) {+ xhr.setRequestHeader(SIYUAN_APP_ID_HEADER, Constants.SIYUAN_APPID);+ }if (protyle.options.upload.token) {xhr.setRequestHeader("X-Upload-Token", protyle.options.upload.token);}diff --git a/app/src/protyle/util/compatibility.ts b/app/src/protyle/util/compatibility.tsindex c0e7824121..f77d13a65c 100644--- a/app/src/protyle/util/compatibility.ts+++ b/app/src/protyle/util/compatibility.ts@@ -1,3 +1,4 @@+import {fetchWithAppId} from "../../util/fetchWithAppId";import {focusByRange} from "./selection";import {fetchPost, fetchSyncPost} from "../../util/fetch";import {Constants} from "../../constants";@@ -119,7 +120,7 @@ export const saveExportFile = async (uri: string, msgId?: string): Promise<TSave}return {status: "canceled"};}- const copyResponse = await (await fetch("/api/export/copyExportFile", {+ const copyResponse = await (await fetchWithAppId("/api/export/copyExportFile", {method: "POST",headers: {"Content-Type": "application/json"},body: JSON.stringify({diff --git a/app/src/protyle/util/richClipboard.ts b/app/src/protyle/util/richClipboard.tsindex 1901e22a89..a5473e2394 100644--- a/app/src/protyle/util/richClipboard.ts+++ b/app/src/protyle/util/richClipboard.ts@@ -1,3 +1,4 @@+import {fetchWithAppId} from "../../util/fetchWithAppId";import {Constants} from "../../constants";import {looseJsonParse} from "../../util/functions";import {getHostCapabilities} from "../../util/hostCapabilities";@@ -463,7 +464,7 @@ export const prepareRichClipboardHTML = (html: string) => {};const postRichClipboard = async (url: string, data: Record<string, unknown>) => {- const response = await fetch(url, {+ const response = await fetchWithAppId(url, {method: "POST",body: JSON.stringify(data),});diff --git a/app/src/util/fetch.test.ts b/app/src/util/fetch.test.tsindex 3febe643af..0c432f2ed4 100644--- a/app/src/util/fetch.test.ts+++ b/app/src/util/fetch.test.ts@@ -22,6 +22,7 @@ const loadFetchPost = (fetchImplementation: typeof fetch = () => new Promise(()exports,require: (name: string) => {switch (name) {+ case "./fetchWithAppId": return {fetchWithAppId: fetchImplementation};case "../constants": return {Constants: {SIYUAN_QUIT: "quit"}};case "electron": return {ipcRenderer: {send: (...args: unknown[]) => sends.push(args)}};case "./processMessage": return {processMessage: processResponse};diff --git a/app/src/util/fetch.ts b/app/src/util/fetch.tsindex 5d1ac1f6fa..c7a5d84864 100644--- a/app/src/util/fetch.ts+++ b/app/src/util/fetch.ts@@ -1,3 +1,4 @@+import {fetchWithAppId} from "./fetchWithAppId";import {Constants} from "../constants";/// #if !BROWSERimport {ipcRenderer} from "electron";@@ -46,7 +47,7 @@ export const fetchPost = ((init.signal = signal;}let isGetFile202 = false;- return trackSettingRequest(url, withFetchTimeout((requestSignal) => fetch(url, {...init, signal: requestSignal}).then((response) => {+ return trackSettingRequest(url, withFetchTimeout((requestSignal) => fetchWithAppId(url, {...init, signal: requestSignal}).then((response) => {switch (response.status) {case 403:case 404:@@ -142,7 +143,7 @@ export const fetchSyncPost = (async (url: string, data?: any, headers?: Record<sinit.body = JSON.stringify(data);}}- return trackSettingRequest(url, fetch(url, init).then(async res => {+ return trackSettingRequest(url, fetchWithAppId(url, init).then(async res => {const res2 = await res.json() as IWebSocketData;if (process) {processMessage(res2);@@ -152,7 +153,7 @@ export const fetchSyncPost = (async (url: string, data?: any, headers?: Record<s}) as FetchSyncPost<IWebSocketData>;export const fetchGet = ((url: string, cb: (response: IWebSocketData | IObject | string) => void) => {- fetch(url, {cache: "no-store"}).then((response) => {+ fetchWithAppId(url, {cache: "no-store"}).then((response) => {if (response.headers.get("content-type")?.indexOf("application/json") > -1) {return response.json();} else {diff --git a/app/src/util/fetchAppId.test.ts b/app/src/util/fetchAppId.test.tsindex 9e7643457b..ea9eb03da6 100644--- a/app/src/util/fetchAppId.test.ts+++ b/app/src/util/fetchAppId.test.ts@@ -5,6 +5,8 @@ import {installPluginStorageFetchAppId,isPluginStorageWriteRequest,SIYUAN_APP_ID_HEADER,+ isSameOriginAPIRequest,+ withAPIAppId,} from "./fetchAppId";const baseURL = "http://127.0.0.1:6806/stage/build/app/";@@ -105,3 +107,72 @@ describe("plugin storage fetch app id", () => {assert.equal(getHeader(calls[0].init, SIYUAN_APP_ID_HEADER), "app-current");});});+++describe("host API app id", () => {+ const origin = new URL(baseURL).origin;++ it("resolves document-relative URLs but compares the window origin", () => {+ for (const input of ["/api/test", "../../../api/test?q=1", new URL("/api/test", baseURL),+ new Request(new URL("/api/test", baseURL))]) {+ assert.equal(isSameOriginAPIRequest(input, baseURL, origin), true);+ }+ for (const input of ["/api", "/apis/test", "/assets/test", "https://example.com/api/test", "http://["]) {+ assert.equal(isSameOriginAPIRequest(input, baseURL, origin), false);+ }+ assert.equal(isSameOriginAPIRequest("/api/test", "https://example.com/", origin), false);+ assert.equal(isSameOriginAPIRequest(`${origin}/api/test`, "https://example.com/", origin), true);+ });++ it("preserves Request body, signal and init header override semantics", async () => {+ const controller = new AbortController();+ const request = new Request(`${origin}/api/test`, {method: "POST", body: "request-body",+ headers: {Authorization: "request-auth"}, signal: controller.signal});+ const inherited = withAPIAppId(request, undefined, "caller", baseURL, origin);+ assert.equal(getHeader(inherited, "Authorization"), "request-auth");+ const effective = new Request(request, inherited);+ assert.equal(await effective.text(), "request-body");+ assert.equal(effective.method, "POST");+ assert.equal(request.headers.has(SIYUAN_APP_ID_HEADER), false);+ controller.abort();+ assert.equal(effective.signal.aborted, true);++ const headers = new Headers({Accept: "text/event-stream", [SIYUAN_APP_ID_HEADER]: "other"});+ const init = Object.freeze({headers, cache: "no-store" as RequestCache});+ const overridden = withAPIAppId(request, init, "caller", baseURL, origin);+ assert.equal(getHeader(overridden, "Authorization"), null);+ assert.equal(getHeader(overridden, "Accept"), "text/event-stream");+ assert.equal(getHeader(overridden, SIYUAN_APP_ID_HEADER), "caller");+ assert.equal(headers.get(SIYUAN_APP_ID_HEADER), "other");+ assert.equal(overridden.cache, "no-store");+ });++ it("preserves FormData without setting its content type and leaves external init untouched", () => {+ const body = new FormData();+ body.append("file", "data");+ const signal = new AbortController().signal;+ const init: RequestInit = {method: "POST", body, signal, credentials: "include", keepalive: true,+ headers: [["Accept", "application/json"]]};+ const updated = withAPIAppId("/api/asset/upload", init, "caller", baseURL, origin);+ assert.equal(updated.body, body);+ assert.equal(updated.signal, signal);+ assert.equal(updated.credentials, "include");+ assert.equal(updated.keepalive, true);+ assert.equal(getHeader(updated, "Content-Type"), null);+ assert.equal(getHeader(init, SIYUAN_APP_ID_HEADER), null);+ assert.equal(withAPIAppId("https://example.com/api/upload", init, "caller", baseURL, origin), init);+ assert.equal(withAPIAppId("/assets/test", undefined, "caller", baseURL, origin), undefined);+ });++ it("does not expand the global plugin wrapper to other APIs or external document bases", async () => {+ const {calls, fetcher} = createMockFetch();+ const wrapped = injectPluginStorageAppId(fetcher, "caller", "https://example.com/", origin);+ const init = {method: "POST"};+ await wrapped("/api/file/putFile", init);+ await wrapped(`${origin}/api/transactions`, init);+ await wrapped(`${origin}/api/file/putFile`, init);+ assert.equal(calls[0].init, init);+ assert.equal(calls[1].init, init);+ assert.equal(getHeader(calls[2].init, SIYUAN_APP_ID_HEADER), "caller");+ });+});diff --git a/app/src/util/fetchAppId.ts b/app/src/util/fetchAppId.tsindex 111b0e6ca6..d966a7fb7c 100644--- a/app/src/util/fetchAppId.ts+++ b/app/src/util/fetchAppId.ts@@ -38,39 +38,59 @@ const getRequestHeaders = (input: RequestInfo | URL, init?: RequestInit) => {return undefined;};-export const isPluginStorageWriteRequest = (input: RequestInfo | URL, init: RequestInit | undefined,- baseURL: string) => {- if (getRequestMethod(input, init).toUpperCase() !== "POST") {- return false;- }+const getSameOriginURL = (input: RequestInfo | URL, baseURL: string, origin?: string) => {try {- const frontendURL = new URL(baseURL);- const requestURL = new URL(getRequestURL(input), frontendURL);- // 只处理当前思源前端对应的精确接口,避免向插件访问的外部服务发送应用标识。- return requestURL.origin === frontendURL.origin && pluginStorageWritePaths.has(requestURL.pathname);+ const requestURL = new URL(getRequestURL(input), baseURL);+ return requestURL.origin === (origin ?? new URL(baseURL).origin) ? requestURL : undefined;} catch {+ return undefined;+ }+};++export const isSameOriginAPIRequest = (input: RequestInfo | URL, baseURL: string, origin: string) =>+ getSameOriginURL(input, baseURL, origin)?.pathname.startsWith("/api/") ?? false;++const withAppIdHeaders = (input: RequestInfo | URL, init: RequestInit | undefined, appId: string): RequestInit => {+ const headers = new Headers(getRequestHeaders(input, init));+ headers.set(SIYUAN_APP_ID_HEADER, appId);+ return {...(init || {}), headers};+};++export const withAPIAppId = (input: RequestInfo | URL, init: RequestInit | undefined, appId: string,+ baseURL: string, origin: string): RequestInit | undefined => {+ if (!isSameOriginAPIRequest(input, baseURL, origin)) {+ return init;+ }+ return withAppIdHeaders(input, init, appId);+};++export const isPluginStorageWriteRequest = (input: RequestInfo | URL, init: RequestInit | undefined,+ baseURL: string, origin?: string) => {+ if (getRequestMethod(input, init).toUpperCase() !== "POST") {return false;}+ const requestURL = getSameOriginURL(input, baseURL, origin);+ // 仅拦截与宿主共享窗口的插件使用的精确存储接口。+ return requestURL !== undefined && pluginStorageWritePaths.has(requestURL.pathname);};-export const injectPluginStorageAppId = (inputFetch: typeof fetch, appId: string, baseURL: string): typeof fetch => {+export const injectPluginStorageAppId = (inputFetch: typeof fetch, appId: string, baseURL: string,+ origin?: string): typeof fetch => {return ((input: RequestInfo | URL, init?: RequestInit) => {- if (!isPluginStorageWriteRequest(input, init, baseURL)) {+ if (!isPluginStorageWriteRequest(input, init, baseURL, origin)) {return inputFetch(input, init);}- const headers = new Headers(getRequestHeaders(input, init));- headers.set(SIYUAN_APP_ID_HEADER, appId);- return inputFetch(input, {...(init || {}), headers});+ return inputFetch(input, withAppIdHeaders(input, init, appId));}) as typeof fetch;};// 插件与宿主共享 window,提前包装原生 fetch 后可覆盖插件直接调用文件接口的场景。-export const installPluginStorageFetchAppId = (target: TFetchTarget, appId: string, baseURL: string) => {+export const installPluginStorageFetchAppId = (target: TFetchTarget, appId: string, baseURL: string, origin?: string) => {const currentFetch = target.fetch as typeof fetch & Record<symbol, boolean | undefined>;if (currentFetch[fetchAppIdMarker]) {return;}- const wrappedFetch = injectPluginStorageAppId(currentFetch.bind(target), appId, baseURL) as+ const wrappedFetch = injectPluginStorageAppId(currentFetch.bind(target), appId, baseURL, origin) astypeof fetch & Record<symbol, boolean | undefined>;Object.defineProperty(wrappedFetch, fetchAppIdMarker, {value: true});target.fetch = wrappedFetch;diff --git a/app/src/util/fetchWithAppId.test.ts b/app/src/util/fetchWithAppId.test.tsnew file mode 100644index 0000000000..a52f006561--- /dev/null+++ b/app/src/util/fetchWithAppId.test.ts@@ -0,0 +1,97 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import {SIYUAN_APP_ID_HEADER, withAPIAppId} from "./fetchAppId";+import {ContractFormData} from "./contractFormData";++const load = (path: string, globals: Record<string, unknown>, dependencies: Record<string, unknown>) => {+ const exports = {};+ const compiled = transpileModule(readFileSync(path, "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText;+ runInNewContext(compiled, {...globals, exports, require: (name: string) => {+ assert.ok(name in dependencies, `Unexpected dependency: ${name}`);+ return dependencies[name];+ }});+ return exports;+};++const fixture = () => {+ const calls: Array<{input: RequestInfo | URL; init?: RequestInit}> = [];+ const response = new Response('{"code":0,"data":null,"msg":""}', {+ headers: {"Content-Type": "application/json"},+ });+ const fetch = (input: RequestInfo | URL, init?: RequestInit) => {+ calls.push({input, init});+ return Promise.resolve(response);+ };+ const document = {baseURI: "https://siyuan.test/stage/build/app/"};+ const location = {origin: "https://siyuan.test"};+ const {fetchWithAppId} = load("src/util/fetchWithAppId.ts", {fetch, document, location}, {+ "../constants": {Constants: {SIYUAN_APPID: "window-id"}},+ "./fetchAppId": {withAPIAppId},+ }) as typeof import("./fetchWithAppId");+ return {calls, response, fetchWithAppId};+};++test("host fetch preserves input, response and abort signal, including SSE", async () => {+ const {calls, response, fetchWithAppId} = fixture();+ const input = new URL("https://siyuan.test/api/ai/editor/chat");+ const signal = new AbortController().signal;+ const init = Object.freeze({method: "POST", signal, headers: {Accept: "text/event-stream"}, body: "{}"});+ assert.equal(await fetchWithAppId(input, init), response);+ assert.equal(calls[0].input, input);+ assert.equal(calls[0].init.signal, signal);+ assert.equal(calls[0].init.body, "{}");+ assert.equal(new Headers(calls[0].init.headers).get("Accept"), "text/event-stream");+ assert.equal(new Headers(calls[0].init.headers).get(SIYUAN_APP_ID_HEADER), "window-id");+ assert.equal(new Headers(init.headers).has(SIYUAN_APP_ID_HEADER), false);+});++test("shared fetch helpers attach the caller and preserve payloads", async () => {+ for (const method of ["fetchPost", "fetchSyncPost", "fetchGet"] as const) {+ const {calls, fetchWithAppId} = fixture();+ const api = load("src/util/fetch.ts", {FormData, console, setTimeout}, {+ "./fetchWithAppId": {fetchWithAppId},+ "../constants": {Constants: {}},+ electron: {ipcRenderer: {}},+ "./processMessage": {processMessage: () => true},+ "./kernelFault": {kernelError: () => assert.fail("Unexpected kernel error")},+ "./fetchTimeout": {withFetchTimeout: (run: (signal: AbortSignal) => unknown, signal: AbortSignal) => run(signal)},+ "../config/setting/pending": {trackSettingRequest: (_url: string, promise: Promise<unknown>) => promise},+ }) as typeof import("./fetch");+ const signal = new AbortController().signal;+ const headers = Object.freeze({Authorization: "Token test"});+ if (method === "fetchGet") {+ await new Promise<void>(resolve => api.fetchGet("/api/test", () => resolve()));+ assert.equal(calls[0].init.cache, "no-store");+ } else {+ const data = new ContractFormData({path: "test.txt", file: new Blob(["test"])});+ if (method === "fetchPost") {+ await api.fetchPost("/api/file/putFile", data, undefined, headers, undefined, signal);+ } else {+ await api.fetchSyncPost("/api/file/putFile", data, headers, false, signal);+ }+ assert.equal(calls[0].init.body, data);+ assert.equal(calls[0].init.signal, signal);+ assert.equal(new Headers(calls[0].init.headers).get("Authorization"), "Token test");+ assert.equal(new Headers(calls[0].init.headers).has("Content-Type"), false);+ }+ assert.equal(new Headers(calls[0].init.headers).get(SIYUAN_APP_ID_HEADER), "window-id");+ }+});++test("host API paths use scoped fetch, including dynamic RPC and clipboard URLs", () => {+ const paths = ["ai/editorSSE.ts", "layout/dock/agent/agentSSE.ts", "layout/dock/agent/AgentChat.ts",+ "config/tabs/accessTab.ts", "protyle/util/compatibility.ts", "protyle/util/richClipboard.ts", "plugin/kernel.ts"];+ for (const path of paths) {+ const source = readFileSync(`src/${path}`, "utf8");+ assert.match(source, /import \{fetchWithAppId\} from /, path);+ assert.match(source, /fetchWithAppId\(/, path);+ assert.doesNotMatch(source, /\bfetch\(/, path);+ }+ const upload = readFileSync("src/protyle/upload/index.ts", "utf8");+ assert.match(upload, /if \(isSameOriginAPIRequest\(protyle.options.upload.url, document.baseURI, location.origin\)\) \{\s*xhr.setRequestHeader\(SIYUAN_APP_ID_HEADER, Constants.SIYUAN_APPID\);/);+});diff --git a/app/src/util/fetchWithAppId.ts b/app/src/util/fetchWithAppId.tsnew file mode 100644index 0000000000..3ca7104f0b--- /dev/null+++ b/app/src/util/fetchWithAppId.ts@@ -0,0 +1,6 @@+import {Constants} from "../constants";+import {withAPIAppId} from "./fetchAppId";++// 宿主接口请求携带调用窗口标识,其他地址保持原生 fetch 行为。+export const fetchWithAppId: typeof fetch = (input: RequestInfo | URL, init?: RequestInit) =>+ fetch(input, withAPIAppId(input, init, Constants.SIYUAN_APPID, document.baseURI, location.origin));diff --git a/app/src/window/index.ts b/app/src/window/index.tsindex 2a54b2dfd4..cf6688d59d 100644--- a/app/src/window/index.ts+++ b/app/src/window/index.ts@@ -265,5 +265,5 @@ class App {}}-installPluginStorageFetchAppId(window, Constants.SIYUAN_APPID, window.location.href);+installPluginStorageFetchAppId(window, Constants.SIYUAN_APPID, document.baseURI, location.origin);new App();diff --git a/kernel/api/asset.go b/kernel/api/asset.goindex efd16dcb5c..b677d26a7d 100644--- a/kernel/api/asset.go+++ b/kernel/api/asset.go@@ -360,7 +360,7 @@ var getUnusedAssets = contractHandler(apicontract.GetUnusedAssets, func(c *gin.Cif total > maxUnusedAssets {unusedAssets = unusedAssets[:maxUnusedAssets]// 提示仅发送给发起查询的前端;未提供应用标识的调用保留广播行为。- util.PushMsgWithApp(c.GetHeader("X-SiYuan-App-ID"), fmt.Sprintf(model.Conf.Language(251), total, maxUnusedAssets), 5000)+ util.PushMsgWithApp(resolveRequestAppID(c, ""), fmt.Sprintf(model.Conf.Language(251), total, maxUnusedAssets), 5000)}return apicontract.Success(assetUnusedItems(unusedAssets))@@ -400,12 +400,13 @@ var uploadCloud = contractHandler(apicontract.AssetUploadCloud, func(c *gin.ContignorePushMsg := request.IgnorePushMsgid := request.ID- count, err := model.UploadAssets2Cloud(id, ignorePushMsg)+ app := resolveRequestAppID(c, "")+ count, err := model.UploadAssets2CloudWithApp(id, ignorePushMsg, app)if err != nil {return apicontract.FailureWithTimeout[apicontract.Null](-1, err.Error(), 3000)}- util.PushMsg(fmt.Sprintf(model.Conf.Language(41), count), 3000)+ util.PushMsgWithApp(app, fmt.Sprintf(model.Conf.Language(41), count), 3000)return apicontract.Success(apicontract.Null{})})@@ -415,13 +416,14 @@ var uploadCloudByAssetsPaths = contractHandler(apicontract.AssetUploadCloudByAssassets := append([]string(nil), request.Paths...)ignorePushMsg := request.IgnorePushMsg- count, err := model.UploadAssets2CloudByAssetsPaths(assets, ignorePushMsg)+ app := resolveRequestAppID(c, "")+ count, err := model.UploadAssets2CloudByAssetsPathsWithApp(assets, ignorePushMsg, app)if err != nil {return apicontract.FailureWithTimeout[apicontract.Null](-1, err.Error(), 3000)}if !ignorePushMsg {- util.PushMsg(fmt.Sprintf(model.Conf.Language(41), count), 3000)+ util.PushMsgWithApp(app, fmt.Sprintf(model.Conf.Language(41), count), 3000)}return apicontract.Success(apicontract.Null{})diff --git a/kernel/api/asset_notification_test.go b/kernel/api/asset_notification_test.goindex 926a3fdbd5..015ac1f73c 100644--- a/kernel/api/asset_notification_test.go+++ b/kernel/api/asset_notification_test.go@@ -21,6 +21,19 @@ import ()func TestAPIContractUnusedAssetNotificationScope(t *testing.T) {+ testAPIContractUnusedNotificationScope(t, false)+}++func TestAPIContractUnusedAttributeViewNotificationScope(t *testing.T) {+ testAPIContractUnusedNotificationScope(t, true)+}++func testAPIContractUnusedNotificationScope(t *testing.T, attributeViews bool) {+ t.Helper()+ endpoint, handler := "/api/asset/getUnusedAssets", getUnusedAssets+ if attributeViews {+ endpoint, handler = "/api/av/getUnusedAttributeViews", getUnusedAttributeViews+ }for _, test := range []struct {name stringcount int@@ -37,8 +50,19 @@ func TestAPIContractUnusedAssetNotificationScope(t *testing.T) {t.Run(test.name, func(t *testing.T) {assets := setupAssetContractWorkspace(t)model.Conf.FileTree = conf.NewFileTree()+ if attributeViews {+ assets = filepath.Join(util.DataDir, "storage", "av")+ if err := os.MkdirAll(assets, 0755); err != nil {+ t.Fatal(err)+ }+ }for i := 0; i < test.count; i++ {- if err := os.WriteFile(filepath.Join(assets, fmt.Sprintf("unused-%04d.txt", i)), []byte("unused"), 0644); err != nil {+ name, content := fmt.Sprintf("unused-%04d.txt", i), []byte("unused")+ if attributeViews {+ name = fmt.Sprintf("20261003000000-%07d.json", i)+ content = []byte(`{"name":"unused","keyValues":[]}`)+ }+ if err := os.WriteFile(filepath.Join(assets, name), content, 0644); err != nil {t.Fatal(err)}}@@ -53,7 +77,7 @@ func TestAPIContractUnusedAssetNotificationScope(t *testing.T) {})push.HandleDisconnect(util.RemovePushChan)engine := gin.New()- engine.POST("/api/asset/getUnusedAssets", getUnusedAssets)+ engine.POST(endpoint, handler)engine.GET("/ws", func(c *gin.Context) { _ = push.HandleRequest(c.Writer, c.Request) })server := httptest.NewServer(engine)t.Cleanup(func() { _ = push.Close(); server.Close() })@@ -79,13 +103,13 @@ func TestAPIContractUnusedAssetNotificationScope(t *testing.T) {}connections = append(connections, connection)}- request := httptest.NewRequest("POST", "/api/asset/getUnusedAssets", strings.NewReader(`{}`))+ request := httptest.NewRequest("POST", endpoint, strings.NewReader(`{}`))if test.app != "" {request.Header.Set("X-SiYuan-App-ID", appPrefix+test.app)}recorder := httptest.NewRecorder()engine.ServeHTTP(recorder, request)- requireAPIContract(t, "POST", "/api/asset/getUnusedAssets", recorder)+ requireAPIContract(t, "POST", endpoint, recorder)var response struct {Code intData []apicontract.AssetUnusedItemdiff --git a/kernel/api/av.go b/kernel/api/av.goindex f78776dac1..65158dac85 100644--- a/kernel/api/av.go+++ b/kernel/api/av.go@@ -52,7 +52,7 @@ var getUnusedAttributeViews = contractHandler(apicontract.GetUnusedAttributeViewtotal := len(values)if total > 512 {values = values[:512]- util.PushMsg(fmt.Sprintf(model.Conf.Language(279), total, 512), 5000)+ util.PushMsgWithApp(resolveRequestAppID(c, ""), fmt.Sprintf(model.Conf.Language(279), total, 512), 5000)}return apicontract.Success(assetUnusedItems(values))})diff --git a/kernel/api/bazaar.go b/kernel/api/bazaar.goindex 17e266e639..35086f5ebb 100644--- a/kernel/api/bazaar.go+++ b/kernel/api/bazaar.go@@ -125,7 +125,7 @@ var updateBazaarPackage = contractHandler(apicontract.UpdateBazaarPackage, func(if err := model.UpdateBazaarPackage(request.PackageType, request.PackageName, request.Frontend); err != nil {return apicontract.Failure[apicontract.BazaarPackagesData](1, err.Error())}- util.PushMsg(model.Conf.Language(69), 3000)+ util.PushMsgWithApp(resolveRequestAppID(c, ""), model.Conf.Language(69), 3000)data := apicontract.BazaarPackagesData{Packages: bazaarPackages(model.GetBazaarPackages(request.PackageType, request.Frontend, request.Keyword))}return apicontract.Success(data)@@ -251,7 +251,7 @@ var installBazaarPlugin = contractHandler(apicontract.InstallBazaarPlugin, func(return apicontract.Failure[apicontract.BazaarPackagesData](1, err.Error())}- util.PushMsg(model.Conf.Language(69), 3000)+ util.PushMsgWithApp(resolveRequestAppID(c, ""), model.Conf.Language(69), 3000)data := apicontract.BazaarPackagesData{Packages: bazaarPackages(model.GetBazaarPackages("plugins", request.Frontend, request.Keyword))}return apicontract.Success(data)@@ -291,7 +291,7 @@ var installBazaarWidget = contractHandler(apicontract.InstallBazaarWidget, func(return apicontract.Failure[apicontract.BazaarPackagesData](1, err.Error())}- util.PushMsg(model.Conf.Language(69), 3000)+ util.PushMsgWithApp(resolveRequestAppID(c, ""), model.Conf.Language(69), 3000)data := apicontract.BazaarPackagesData{Packages: bazaarPackages(model.GetBazaarPackages("widgets", "", request.Keyword))}return apicontract.Success(data)@@ -325,7 +325,7 @@ var installBazaarIcon = contractHandler(apicontract.InstallBazaarIcon, func(c *gif err != nil {return apicontract.Failure[apicontract.BazaarAppearancePackagesData](1, err.Error())}- util.PushMsg(model.Conf.Language(69), 3000)+ util.PushMsgWithApp(resolveRequestAppID(c, ""), model.Conf.Language(69), 3000)data := apicontract.BazaarAppearancePackagesData{Packages: bazaarPackages(model.GetBazaarPackages("icons", "", request.Keyword)), Appearance: bazaarAppearance(model.Conf.Appearance)}@@ -363,7 +363,7 @@ var installBazaarTemplate = contractHandler(apicontract.InstallBazaarTemplate, fdata := apicontract.BazaarPackagesData{Packages: bazaarPackages(model.GetBazaarPackages("templates", "", request.Keyword))}- util.PushMsg(model.Conf.Language(69), 3000)+ util.PushMsgWithApp(resolveRequestAppID(c, ""), model.Conf.Language(69), 3000)return apicontract.Success(data)})@@ -402,7 +402,7 @@ var installBazaarTheme = contractHandler(apicontract.InstallBazaarTheme, func(creturn apicontract.Failure[apicontract.BazaarAppearancePackagesData](1, err.Error())}- util.PushMsg(model.Conf.Language(69), 3000)+ util.PushMsgWithApp(resolveRequestAppID(c, ""), model.Conf.Language(69), 3000)data := apicontract.BazaarAppearancePackagesData{Packages: bazaarPackages(model.GetBazaarPackages("themes", request.Frontend, request.Keyword)), Appearance: bazaarAppearance(model.Conf.Appearance)}return apicontract.Success(data)diff --git a/kernel/api/file.go b/kernel/api/file.goindex 236394d515..3f2026fa86 100644--- a/kernel/api/file.go+++ b/kernel/api/file.go@@ -42,17 +42,8 @@ import (// errMsgSeeKernelLog 接在 API 错误提示末尾,引导用户查看内核日志以获取完整信息(避免在 Msg 暴露工作空间绝对路径)。const (errMsgSeeKernelLog = ". For details, see the SiYuan kernel log."- siyuanAppIDHeader = "X-SiYuan-App-ID")-// resolveFileAPIAppID 优先使用宿主统一注入的应用标识,同时兼容旧请求体中的 app。-func resolveFileAPIAppID(c *gin.Context, bodyApp string) string {- if headerApp := c.GetHeader(siyuanAppIDHeader); headerApp != "" {- return headerApp- }- return bodyApp-}-// rejectEncryptedBoxPath 检查 absPath 是否落在加密笔记本目录下(含 symlink 绕过),是则返回 true。// 原始文件 API(getFile/putFile/copyFile/renameFile/removeFile)是绕过加密层的逃生口,// 对加密笔记本的任何文件读写都应拒绝——合法读写走专用 API(upload/getBlockKramdown 等,已加密感知),@@ -703,7 +694,7 @@ var renameFile = contractHandler(apicontract.RenameFile, func(c *gin.Context, revar removeFile = contractHandler(apicontract.RemoveFile, func(c *gin.Context, request apicontract.RemoveFileRequest) apicontract.Response[apicontract.Null] {ret := gulu.Ret.NewResult()app, filePath := request.App, request.Path- app = resolveFileAPIAppID(c, app)+ app = resolveRequestAppID(c, app)fileAbsPath, err := util.GetAbsPathInWorkspace(filePath)if err != nil {@@ -761,7 +752,7 @@ var putFile = contractHandler(apicontract.PutFile, func(c *gin.Context, requestisDirStr := request.IsDirisDir, _ := strconv.ParseBool(isDirStr)- app := resolveFileAPIAppID(c, request.App)+ app := resolveRequestAppID(c, request.App)var err errorfilePath := request.Pathdiff --git a/kernel/api/file_test.go b/kernel/api/file_test.goindex c2c013fd5a..40e413f83c 100644--- a/kernel/api/file_test.go+++ b/kernel/api/file_test.go@@ -15,7 +15,7 @@ import ("github.com/siyuan-note/siyuan/kernel/util")-func TestResolveFileAPIAppID(t *testing.T) {+func TestResolveRequestAppID(t *testing.T) {tests := []struct {name stringheader string@@ -34,7 +34,7 @@ func TestResolveFileAPIAppID(t *testing.T) {if test.header != "" {context.Request.Header.Set(siyuanAppIDHeader, test.header)}- if actual := resolveFileAPIAppID(context, test.body); actual != test.expected {+ if actual := resolveRequestAppID(context, test.body); actual != test.expected {t.Fatalf("expected app [%s], got [%s]", test.expected, actual)}})diff --git a/kernel/api/notification_scope_source_test.go b/kernel/api/notification_scope_source_test.gonew file mode 100644index 0000000000..80d5f0186e--- /dev/null+++ b/kernel/api/notification_scope_source_test.go@@ -0,0 +1,64 @@+package api++import (+ "go/ast"+ "go/parser"+ "go/token"+ "testing"+)++// 已分类的操作提示不得改回全局广播;网络安装、上传的结果仍由各自功能测试覆盖。+func TestOperationNotificationScopeCallsites(t *testing.T) {+ for file, names := range map[string][]string{+ "asset.go": {"getUnusedAssets", "uploadCloud", "uploadCloudByAssetsPaths"},+ "av.go": {"getUnusedAttributeViews"},+ "bazaar.go": {"updateBazaarPackage", "installBazaarPlugin", "installBazaarWidget",+ "installBazaarIcon", "installBazaarTemplate", "installBazaarTheme"},+ } {+ parsed, err := parser.ParseFile(token.NewFileSet(), file, nil, 0)+ if err != nil {+ t.Fatal(err)+ }+ for _, name := range names {+ t.Run(name, func(t *testing.T) {+ var handler ast.Node+ ast.Inspect(parsed, func(node ast.Node) bool {+ value, ok := node.(*ast.ValueSpec)+ if ok && len(value.Names) == 1 && value.Names[0].Name == name && len(value.Values) == 1 {+ handler = value.Values[0]+ return false+ }+ return true+ })+ if handler == nil {+ t.Fatal("notification handler was not found")+ }+ scoped := false+ ast.Inspect(handler, func(node ast.Node) bool {+ call, ok := node.(*ast.CallExpr)+ if !ok {+ return true+ }+ selector, ok := call.Fun.(*ast.SelectorExpr)+ if !ok {+ return true+ }+ pkg, ok := selector.X.(*ast.Ident)+ if !ok || pkg.Name != "util" {+ return true+ }+ switch selector.Sel.Name {+ case "PushMsg", "PushErrMsg", "PushUpdateMsg", "PushClearMsg":+ t.Errorf("operation notification uses global %s", selector.Sel.Name)+ case "PushMsgWithApp":+ scoped = true+ }+ return true+ })+ if !scoped {+ t.Fatal("operation completion must use scoped notification")+ }+ })+ }+ }+}diff --git a/kernel/api/ref.go b/kernel/api/ref.goindex 639a1ec331..f4192c3066 100644--- a/kernel/api/ref.go+++ b/kernel/api/ref.go@@ -45,9 +45,20 @@ func isBacklinkDocAccessible(c *gin.Context, refTreeID string) bool {return model.CheckBlockIdAccessableByPublishAccess(c, model.GetPublishAccess(), refTreeID)}+func backlinkRequestNotifier(c *gin.Context) model.BackmentionNotifier {+ if model.IsReadOnlyRoleContext(c) {+ return nil+ }+ app := resolveRequestAppID(c, "")+ return func(msg string, timeout int) string {+ return util.PushMsgWithApp(app, msg, timeout)+ }+}+var getBackmentionDoc = contractHandler(apicontract.GetBackmentionDoc, func(c *gin.Context, request apicontract.BackmentionDocumentRequest) apicontract.Response[apicontract.BacklinkContextData] {defID, refTreeID := request.DefID, request.RefTreeIDknownRevision, keyword, notebook := request.KnownRevision, request.Keyword, request.Notebook+ notify := backlinkRequestNotifier(c)encryptedNotebookDenied := isEncryptedNotebookDeniedForPublish(c, notebook)if notebook != "" && !model.IsEncryptedBox(notebook) {notebook = ""@@ -71,9 +82,9 @@ var getBackmentionDoc = contractHandler(apicontract.GetBackmentionDoc, func(c *gif encryptedNotebookDenied || !isBacklinkDocAccessible(c, refTreeID) {backlinks, keywords = []*model.Backlink{}, []string{}} else if notebook != "" && model.IsEncryptedBox(notebook) {- backlinks, keywords = model.GetBackmentionDocInBox(defID, refTreeID, keyword, containChildren, highlight, notebook)+ backlinks, keywords = model.GetBackmentionDocInBox(defID, refTreeID, keyword, containChildren, highlight, notebook, notify)} else {- backlinks, keywords = model.GetBackmentionDoc(defID, refTreeID, keyword, containChildren, highlight)+ backlinks, keywords = model.GetBackmentionDoc(defID, refTreeID, keyword, containChildren, highlight, notify)}keywords = canonicalBacklinkKeywords(keywords)items := newBacklinkContextResponses(backlinks)@@ -188,6 +199,7 @@ var getBacklink2 = contractHandler(apicontract.GetBacklink2, func(c *gin.Context}id, knownRevision := *request.ID, request.KnownRevisionkeyword, mentionKeyword := request.K, request.MK+ notify := backlinkRequestNotifier(c)includeMentions := trueif request.IncludeMentions != nil {includeMentions = *request.IncludeMentions@@ -241,9 +253,9 @@ var getBacklink2 = contractHandler(apicontract.GetBacklink2, func(c *gin.Contextreturn apicontract.Failure[apicontract.BacklinkListData](1, err.Error())}if notebook != "" && model.IsEncryptedBox(notebook) {- boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword, sort, mentionSort, containChildren, notebook, sourceFilter, includeMentions, includeBacklinks)+ boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword, sort, mentionSort, containChildren, notebook, sourceFilter, includeMentions, includeBacklinks, notify)} else {- boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword, sort, mentionSort, containChildren, "", sourceFilter, includeMentions, includeBacklinks)+ boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword, sort, mentionSort, containChildren, "", sourceFilter, includeMentions, includeBacklinks, notify)}}if model.IsReadOnlyRoleContext(c) {diff --git a/kernel/api/ref_notification_test.go b/kernel/api/ref_notification_test.gonew file mode 100644index 0000000000..9dc1333d2c--- /dev/null+++ b/kernel/api/ref_notification_test.go@@ -0,0 +1,95 @@+package api++import (+ "github.com/gorilla/websocket"+ "github.com/olahol/melody"+ "github.com/siyuan-note/siyuan/kernel/util"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/model"+)++func TestBacklinkRequestNotifierSuppressesReadOnly(t *testing.T) {+ for _, role := range []model.Role{model.RoleReader, model.RoleVisitor, model.RoleAdministrator, model.RoleEditor} {+ c, _ := gin.CreateTestContext(httptest.NewRecorder())+ c.Request = httptest.NewRequest("POST", "/api/ref/getBacklink2", nil)+ c.Request.Header.Set(siyuanAppIDHeader, "administrator-window")+ c.Set(model.RoleContextKey, role)+ if got := backlinkRequestNotifier(c); (got == nil) != model.IsReadOnlyRole(role) {+ t.Fatalf("role %d notification suppression mismatch", role)+ }+ }+ if backlinkRequestNotifier(nil) != nil {+ t.Fatal("missing request context must not notify an administrator")+ }+}++func TestBacklinkRequestNotifierCapturesApp(t *testing.T) {+ push := melody.New()+ connected := make(chan *melody.Session, 1)+ push.HandleConnect(func(session *melody.Session) {+ util.AddPushChan(session)+ connected <- session+ })+ push.HandleDisconnect(util.RemovePushChan)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _ = push.HandleRequest(w, r) }))+ t.Cleanup(func() { _ = push.Close(); server.Close() })+ var connections []*websocket.Conn+ for _, app := range []string{"backlink-notification-first", "backlink-notification-second"} {+ connection, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http")+"/?app="+app+"&id=main&type=main", nil)+ if err != nil {+ t.Fatal(err)+ }+ select {+ case session := <-connected:+ t.Cleanup(func() { _ = connection.Close(); util.RemovePushChan(session) })+ case <-time.After(5 * time.Second):+ _ = connection.Close()+ t.Fatal("websocket registration timed out")+ }+ connections = append(connections, connection)+ }+ c, _ := gin.CreateTestContext(httptest.NewRecorder())+ c.Request = httptest.NewRequest("POST", "/api/ref/getBacklink2", nil)+ c.Set(model.RoleContextKey, model.RoleAdministrator)+ c.Request.Header.Set(siyuanAppIDHeader, "backlink-notification-first")+ notify := backlinkRequestNotifier(c)+ c.Request.Header.Set(siyuanAppIDHeader, "backlink-notification-second")+ notify("scoped warning", 5000)+ if err := push.Broadcast([]byte(`{"cmd":"barrier"}`)); err != nil {+ t.Fatal(err)+ }+ for i, connection := range connections {+ if err := connection.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {+ t.Fatal(err)+ }+ messages := 0+ for {+ var event struct {+ Cmd string+ Msg string+ }+ if err := connection.ReadJSON(&event); err != nil {+ t.Fatal(err)+ }+ if event.Cmd == "barrier" {+ break+ }+ if event.Cmd == "msg" && event.Msg == "scoped warning" {+ messages+++ }+ }+ want := 0+ if i == 0 {+ want = 1+ }+ if messages != want {+ t.Fatalf("window %d received %d warnings, want %d", i, messages, want)+ }+ }+}diff --git a/kernel/api/request_app.go b/kernel/api/request_app.gonew file mode 100644index 0000000000..8e8b2896d8--- /dev/null+++ b/kernel/api/request_app.go@@ -0,0 +1,14 @@+package api++import "github.com/gin-gonic/gin"++const siyuanAppIDHeader = "X-SiYuan-App-ID"++// resolveRequestAppID 优先使用请求头,兼容已经解析的请求体 app;空标识保留旧调用的广播语义。+// 应用标识只用于通知路由,不参与认证或访问控制。+func resolveRequestAppID(c *gin.Context, bodyApp string) string {+ if headerApp := c.GetHeader(siyuanAppIDHeader); headerApp != "" {+ return headerApp+ }+ return bodyApp+}diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex b3d8c95a8c..8e563f7d37 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -564,10 +564,12 @@ var GetLocalGraph = define[LocalGraphRequest, LocalGraphData]("getLocalGraph", "var RefreshBacklink = define[RefreshBacklinkRequest, Null]("refreshBacklink", "/api/ref/refreshBacklink", JSONBody, ResponseOptions{}, "POST")+// 提及数量提示使用可选请求头 X-SiYuan-App-ID 定向;无标识时广播,发布读者不发送提示。var GetBackmentionDoc = define[BackmentionDocumentRequest, BacklinkContextData]("getBackmentionDoc", "/api/ref/getBackmentionDoc", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var GetBacklinkDoc = define[BacklinkDocumentRequest, BacklinkContextData]("getBacklinkDoc", "/api/ref/getBacklinkDoc", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")+// 提及数量提示使用可选请求头 X-SiYuan-App-ID 定向;无标识时广播,发布读者不发送提示。var GetBacklink2 = define[BacklinkListRequest, BacklinkListData]("getBacklink2", "/api/ref/getBacklink2", JSONBody, ResponseOptions{AdditionalCodes: []int{1}, DataOnError: true}, "POST")var GetGlobalBacklinks = define[GlobalBacklinkListRequest, GlobalBacklinkListData]("getGlobalBacklinks", "/api/ref/getGlobalBacklinks", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var GetGlobalBacklinkContexts = define[GlobalBacklinkContextRequest, GlobalBacklinkContextData]("getGlobalBacklinkContexts", "/api/ref/getGlobalBacklinkContexts", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")@@ -672,6 +674,8 @@ var PluginRPCWebSocketByName = define[EmptyRequest, PluginRPCFailure]("pluginJsovar InstallLocalBazaarPackage = define[InstallLocalBazaarPackageRequest, BazaarLocalInstallResult]("installLocalBazaarPackage", "/api/bazaar/installLocalBazaarPackage", MultipartBody, ResponseOptions{AdditionalCodes: []int{1}, DataOnError: true}, "POST")var BatchUpdatePackage = define[BatchUpdatePackageRequest, Null]("batchUpdatePackage", "/api/bazaar/batchUpdatePackage", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var GetUpdatedPackage = define[GetUpdatedPackageRequest, BazaarUpdatedData]("getUpdatedPackage", "/api/bazaar/getUpdatedPackage", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")++// 下载完成提示使用可选请求头 X-SiYuan-App-ID 定向;无标识时广播,离线目标不回退广播。var UpdateBazaarPackage = define[UpdateBazaarPackageRequest, BazaarPackagesData]("updateBazaarPackage", "/api/bazaar/updateBazaarPackage", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var GetInstalledPackageSize = define[GetInstalledPackageSizeRequest, BazaarPackageSizeData]("getInstalledPackageSize", "/api/bazaar/getInstalledPackageSize", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var GetBazaarPackage = define[GetBazaarPackageRequest, BazaarPackageDetail]("getBazaarPackage", "/api/bazaar/getBazaarPackage", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")@@ -682,22 +686,32 @@ var SetBazaarPackageRating = define[SetBazaarPackageRatingRequest, BazaarRatingRvar GetBazaarPackageREADME = define[GetBazaarPackageREADMERequest, BazaarREADMEData]("getBazaarPackageREADME", "/api/bazaar/getBazaarPackageREADME", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var GetBazaarPlugin = define[GetBazaarPluginRequest, BazaarPackagesData]("getBazaarPlugin", "/api/bazaar/getBazaarPlugin", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var GetInstalledPlugin = define[GetInstalledPluginRequest, BazaarPackagesData]("getInstalledPlugin", "/api/bazaar/getInstalledPlugin", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")++// 下载完成提示使用可选请求头 X-SiYuan-App-ID 定向;插件重载事件仍广播。var InstallBazaarPlugin = define[InstallBazaarPluginRequest, BazaarPackagesData]("installBazaarPlugin", "/api/bazaar/installBazaarPlugin", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var UninstallBazaarPlugin = define[UninstallBazaarPluginRequest, BazaarPackagesData]("uninstallBazaarPlugin", "/api/bazaar/uninstallBazaarPlugin", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var GetBazaarWidget = define[GetBazaarWidgetRequest, BazaarPackagesData]("getBazaarWidget", "/api/bazaar/getBazaarWidget", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var GetInstalledWidget = define[GetInstalledWidgetRequest, BazaarPackagesData]("getInstalledWidget", "/api/bazaar/getInstalledWidget", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")++// 下载完成提示使用可选请求头 X-SiYuan-App-ID 定向;无标识时广播。var InstallBazaarWidget = define[InstallBazaarWidgetRequest, BazaarPackagesData]("installBazaarWidget", "/api/bazaar/installBazaarWidget", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var UninstallBazaarWidget = define[UninstallBazaarWidgetRequest, BazaarPackagesData]("uninstallBazaarWidget", "/api/bazaar/uninstallBazaarWidget", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var GetBazaarIcon = define[GetBazaarIconRequest, BazaarPackagesData]("getBazaarIcon", "/api/bazaar/getBazaarIcon", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var GetInstalledIcon = define[GetInstalledIconRequest, BazaarPackagesData]("getInstalledIcon", "/api/bazaar/getInstalledIcon", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")++// 下载完成提示使用可选请求头 X-SiYuan-App-ID 定向;外观刷新事件仍广播。var InstallBazaarIcon = define[InstallBazaarIconRequest, BazaarAppearancePackagesData]("installBazaarIcon", "/api/bazaar/installBazaarIcon", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var UninstallBazaarIcon = define[UninstallBazaarIconRequest, BazaarAppearancePackagesData]("uninstallBazaarIcon", "/api/bazaar/uninstallBazaarIcon", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var GetBazaarTemplate = define[GetBazaarTemplateRequest, BazaarPackagesData]("getBazaarTemplate", "/api/bazaar/getBazaarTemplate", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var GetInstalledTemplate = define[GetInstalledTemplateRequest, BazaarPackagesData]("getInstalledTemplate", "/api/bazaar/getInstalledTemplate", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")++// 下载完成提示使用可选请求头 X-SiYuan-App-ID 定向;无标识时广播。var InstallBazaarTemplate = define[InstallBazaarTemplateRequest, BazaarPackagesData]("installBazaarTemplate", "/api/bazaar/installBazaarTemplate", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var UninstallBazaarTemplate = define[UninstallBazaarTemplateRequest, BazaarPackagesData]("uninstallBazaarTemplate", "/api/bazaar/uninstallBazaarTemplate", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var GetBazaarTheme = define[GetBazaarThemeRequest, BazaarPackagesData]("getBazaarTheme", "/api/bazaar/getBazaarTheme", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var GetInstalledTheme = define[GetInstalledThemeRequest, BazaarPackagesData]("getInstalledTheme", "/api/bazaar/getInstalledTheme", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")++// 下载完成提示使用可选请求头 X-SiYuan-App-ID 定向;外观刷新事件仍广播。var InstallBazaarTheme = define[InstallBazaarThemeRequest, BazaarAppearancePackagesData]("installBazaarTheme", "/api/bazaar/installBazaarTheme", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var UninstallBazaarTheme = define[UninstallBazaarThemeRequest, BazaarAppearancePackagesData]("uninstallBazaarTheme", "/api/bazaar/uninstallBazaarTheme", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")@@ -877,7 +891,11 @@ var GetMissingAssets = define[EmptyRequest, []*AssetUnusedItem]("getMissingAsset// ResolveAssetPath 返回普通资源路径;已解锁的加密资源返回保留原始名称的受管临时明文副本路径。var ResolveAssetPath = define[AssetPathRequest, string]("resolveAssetPath", "/api/asset/resolveAssetPath", JSONBody, ResponseOptions{}, "POST")++// 上传提示生命周期使用可选请求头 X-SiYuan-App-ID 定向;无标识时广播,状态栏仍全局更新。var AssetUploadCloud = define[AssetCloudUploadRequest, Null]("uploadCloud", "/api/asset/uploadCloud", JSONBody, ResponseOptions{}, "POST")++// 上传提示生命周期使用可选请求头 X-SiYuan-App-ID 定向;无标识时广播,保留 ignorePushMsg 语义。var AssetUploadCloudByAssetsPaths = define[AssetPathsCloudUploadRequest, Null]("uploadCloudByAssetsPaths", "/api/asset/uploadCloudByAssetsPaths", JSONBody, ResponseOptions{}, "POST")var InsertLocalAssets = define[InsertLocalAssetsRequest, AssetUploadData]("insertLocalAssets", "/api/asset/insertLocalAssets", JSONBody, ResponseOptions{DataOnError: true}, "POST")var InsertCover = define[InsertCoverRequest, AssetInsertCoverData]("insertCover", "/api/asset/insertCover", JSONBody, ResponseOptions{}, "POST")@@ -915,6 +933,8 @@ var SetEmoji = define[SettingEmojiRequest, Null]("setEmoji", "/api/setting/setEmvar RemoveUnusedAttributeView = define[RemoveUnusedAttributeViewRequest, AVIDData]("removeUnusedAttributeView", "/api/av/removeUnusedAttributeView", JSONBody, ResponseOptions{}, "POST")var RemoveUnusedAttributeViews = define[EmptyRequest, AVPathsData]("removeUnusedAttributeViews", "/api/av/removeUnusedAttributeViews", NoBody, ResponseOptions{}, "POST")++// 截断提示使用可选请求头 X-SiYuan-App-ID 定向;无标识时广播,离线目标不回退广播。var GetUnusedAttributeViews = define[EmptyRequest, []*AssetUnusedItem]("getUnusedAttributeViews", "/api/av/getUnusedAttributeViews", NoBody, ResponseOptions{}, "POST")var GetAttributeViewItemIDsByBoundIDs = define[GetAttributeViewItemIDsByBoundIDsRequest, map[string]string]("getAttributeViewItemIDsByBoundIDs", "/api/av/getAttributeViewItemIDsByBoundIDs", JSONBody, ResponseOptions{}, "POST")var GetAttributeViewBoundBlockIDsByItemIDs = define[GetAttributeViewBoundBlockIDsByItemIDsRequest, map[string]string]("getAttributeViewBoundBlockIDsByItemIDs", "/api/av/getAttributeViewBoundBlockIDsByItemIDs", JSONBody, ResponseOptions{}, "POST")diff --git a/kernel/model/assets.go b/kernel/model/assets.goindex 8a6c5dd339..0fc79cc6c5 100644--- a/kernel/model/assets.go+++ b/kernel/model/assets.go@@ -1438,6 +1438,11 @@ func getAssetAbsPath(relativePath string, includeEncrypted bool) (absPath string}func UploadAssets2Cloud(id string, ignorePushMsg bool) (count int, err error) {+ return UploadAssets2CloudWithApp(id, ignorePushMsg, "")+}++// UploadAssets2CloudWithApp 将块资源上传提示限定到发起实例;空标识保留广播。+func UploadAssets2CloudWithApp(id string, ignorePushMsg bool, app string) (count int, err error) {if !IsSubscriber() {return}@@ -1464,7 +1469,7 @@ func UploadAssets2Cloud(id string, ignorePushMsg bool) (count int, err error) {assets = append(assets, getQueryEmbedNodesAssetsLinkDests(n)...)}assets = gulu.Str.RemoveDuplicatedElem(assets)- count, err = uploadAssets2Cloud(assets, bizTypeUploadAssets, ignorePushMsg)+ count, err = uploadAssets2CloudWithApp(assets, bizTypeUploadAssets, ignorePushMsg, app)if err != nil {return}@@ -1472,11 +1477,16 @@ func UploadAssets2Cloud(id string, ignorePushMsg bool) (count int, err error) {}func UploadAssets2CloudByAssetsPaths(assetPaths []string, ignorePushMsg bool) (count int, err error) {+ return UploadAssets2CloudByAssetsPathsWithApp(assetPaths, ignorePushMsg, "")+}++// UploadAssets2CloudByAssetsPathsWithApp 在同一实例显示、更新和清除本次上传的提示。+func UploadAssets2CloudByAssetsPathsWithApp(assetPaths []string, ignorePushMsg bool, app string) (count int, err error) {if !IsSubscriber() {return}- count, err = uploadAssets2Cloud(assetPaths, bizTypeUploadAssets, ignorePushMsg)+ count, err = uploadAssets2CloudWithApp(assetPaths, bizTypeUploadAssets, ignorePushMsg, app)return}@@ -1487,6 +1497,10 @@ const (// uploadAssets2Cloud 将资源文件上传到云端图床。func uploadAssets2Cloud(assetPaths []string, bizType string, ignorePushMsg bool) (count int, err error) {+ return uploadAssets2CloudWithApp(assetPaths, bizType, ignorePushMsg, "")+}++func uploadAssets2CloudWithApp(assetPaths []string, bizType string, ignorePushMsg bool, app string) (count int, err error) {var uploadAbsAssets []stringfor _, assetPath := range assetPaths {var absPath string@@ -1512,10 +1526,11 @@ func uploadAssets2Cloud(assetPaths []string, bizType string, ignorePushMsg bool)var msgId stringif !ignorePushMsg {- msgId = util.PushMsg(fmt.Sprintf(Conf.Language(27), len(uploadAbsAssets)), 3000)+ msgId = util.PushMsgWithApp(app, fmt.Sprintf(Conf.Language(27), len(uploadAbsAssets)), 3000)+ defer util.PushClearMsgWithApp(app, msgId)}if loadErr := LoadUploadToken(); nil != loadErr {- util.PushMsg(loadErr.Error(), 5000)+ util.PushMsgWithApp(app, loadErr.Error(), 5000)return}@@ -1551,7 +1566,7 @@ func uploadAssets2Cloud(assetPaths []string, bizType string, ignorePushMsg bool)logging.LogWarnf("file [%s] larger than limit size [%s], ignore uploading it", absAsset, humanize.IBytes(limitSize))if 3 > pushErrMsgCount {msg := fmt.Sprintf(Conf.Language(247), filepath.Base(absAsset), humanize.IBytes(limitSize))- util.PushErrMsg(msg, 30000)+ util.PushErrMsgWithApp(app, msg, 30000)}pushErrMsgCount++continue@@ -1560,7 +1575,7 @@ func uploadAssets2Cloud(assetPaths []string, bizType string, ignorePushMsg bool)if !ignorePushMsg {msg := fmt.Sprintf(Conf.Language(27), html.EscapeString(absAsset))util.PushStatusBar(msg)- util.PushUpdateMsg(msgId, msg, 3000)+ util.PushUpdateMsgWithApp(app, msgId, msg, 3000)}requestResult := gulu.Ret.NewResult()@@ -1595,10 +1610,6 @@ func uploadAssets2Cloud(assetPaths []string, bizType string, ignorePushMsg bool)count++}- if !ignorePushMsg {- util.PushClearMsg(msgId)- }-if 0 < len(completedUploadAssets) {logging.LogInfof("uploaded [%d] assets", len(completedUploadAssets))}diff --git a/kernel/model/assets_notification_test.go b/kernel/model/assets_notification_test.gonew file mode 100644index 0000000000..edbacd53d7--- /dev/null+++ b/kernel/model/assets_notification_test.go@@ -0,0 +1,180 @@+package model++import (+ "fmt"+ "net/http"+ "net/http/httptest"+ "net/url"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/gorilla/websocket"+ "github.com/olahol/melody"+ "github.com/siyuan-note/siyuan/kernel/util"+)++type assetUploadNotificationEvent struct {+ Cmd string+ Code int+ Msg string+ Data struct {+ ID string+ CloseTimeout int+ }+}++func TestUploadAssetsNotificationScope(t *testing.T) {+ originalConf, originalLangs := Conf, util.Langs+ originalWorkspace, originalData, originalConfDir, originalRepo := util.WorkspaceDir, util.DataDir, util.ConfDir, util.RepoDir+ originalToken, originalTokenTime := uploadToken, uploadTokenTime+ t.Cleanup(func() {+ Conf, util.Langs = originalConf, originalLangs+ util.WorkspaceDir, util.DataDir, util.ConfDir, util.RepoDir = originalWorkspace, originalData, originalConfDir, originalRepo+ uploadToken, uploadTokenTime = originalToken, originalTokenTime+ })+ Conf = NewAppConf()+ Conf.Lang = "en"+ util.Langs = map[string]map[int]string{"en": {+ 27: "Uploading %v", 31: "Sign in required", 247: "Asset %s exceeds %s",+ }}+ util.WorkspaceDir = t.TempDir()+ util.DataDir = filepath.Join(util.WorkspaceDir, "data")+ util.ConfDir = filepath.Join(util.WorkspaceDir, "conf")+ util.RepoDir = filepath.Join(util.WorkspaceDir, "repo")+ assetPath := filepath.Join(util.DataDir, "assets", "oversized.dat")+ if err := os.MkdirAll(filepath.Dir(assetPath), 0755); err != nil {+ t.Fatal(err)+ }+ file, err := os.Create(assetPath)+ if err != nil {+ t.Fatal(err)+ }+ err = file.Truncate(3*1024*1024 + 1)+ closeErr := file.Close()+ if err != nil || closeErr != nil {+ t.Fatalf("prepare oversized asset: %v, %v", err, closeErr)+ }++ push := melody.New()+ connected := make(chan *melody.Session, 1)+ push.HandleConnect(func(session *melody.Session) {+ if session.Request.URL.Query().Get("publish") == "true" {+ session.Set("isPublish", true)+ }+ if session.Request.URL.Query().Get("auth") == "true" {+ session.Set("authSession", true)+ }+ util.AddPushChan(session)+ connected <- session+ })+ push.HandleDisconnect(util.RemovePushChan)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _ = push.HandleRequest(w, r)+ }))+ var connections []*websocket.Conn+ var sessions []*melody.Session+ t.Cleanup(func() {+ for _, connection := range connections {+ _ = connection.Close()+ }+ for _, session := range sessions {+ util.RemovePushChan(session)+ }+ _ = push.Close()+ server.Close()+ })+ first, second := util.WorkspaceDir+"-first", util.WorkspaceDir+"-second"+ for _, query := range []string{+ "app=" + url.QueryEscape(first) + "&id=main&type=main",+ "app=" + url.QueryEscape(second) + "&id=main&type=main",+ "app=" + url.QueryEscape(first) + "&id=publish&type=main&publish=true",+ "app=" + url.QueryEscape(first) + "&id=auth&type=main&auth=true",+ "app=" + url.QueryEscape(first) + "&id=tree&type=filetree",+ } {+ connection, response, dialErr := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http")+"/ws?"+query, nil)+ if dialErr != nil {+ t.Fatal(dialErr)+ }+ _ = response.Body.Close()+ connections = append(connections, connection)+ select {+ case session := <-connected:+ sessions = append(sessions, session)+ case <-time.After(5 * time.Second):+ t.Fatal("notification connection was not registered")+ }+ }++ for _, failure := range []string{"token", "size"} {+ for _, ignore := range []bool{false, true} {+ for _, target := range []string{"first", "second", "absent", "legacy"} {+ t.Run(fmt.Sprintf("%s/ignore=%v/%s", failure, ignore, target), func(t *testing.T) {+ // 未登录直接拒绝令牌请求;缓存令牌配合超限本地文件在上传请求前退出。+ uploadToken, uploadTokenTime = "unused-test-token", 0+ if failure == "size" {+ uploadTokenTime = time.Now().Unix()+ }+ app := map[string]string{"first": first, "second": second, "absent": first + "-closed"}[target]+ count, uploadErr := uploadAssets2CloudWithApp([]string{"assets/oversized.dat"}, bizTypeUploadAssets, ignore, app)+ if count != 0 || uploadErr != nil {+ t.Fatalf("unexpected upload result: count=%d err=%v", count, uploadErr)+ }+ // 屏障与通知按连接排队,断言没有通知时无需等待读超时。+ if broadcastErr := push.Broadcast([]byte(`{"cmd":"asset-notification-barrier"}`)); broadcastErr != nil {+ t.Fatal(broadcastErr)+ }+ for i, connection := range connections {+ if deadlineErr := connection.SetReadDeadline(time.Now().Add(5 * time.Second)); deadlineErr != nil {+ t.Fatal(deadlineErr)+ }+ var events []assetUploadNotificationEvent+ for {+ var event assetUploadNotificationEvent+ if readErr := connection.ReadJSON(&event); readErr != nil {+ t.Fatal(readErr)+ }+ if event.Cmd == "asset-notification-barrier" {+ break+ }+ events = append(events, event)+ }+ receives := i == 0 && (target == "first" || target == "legacy") || i == 1 && (target == "second" || target == "legacy")+ if !receives {+ if len(events) != 0 {+ t.Fatalf("client %d received unrelated events: %+v", i, events)+ }+ continue+ }+ wantCount, errorIndex := 3, 1+ if ignore {+ wantCount, errorIndex = 1, 0+ }+ if len(events) != wantCount {+ t.Fatalf("client %d received %+v, want %d events", i, events, wantCount)+ }+ if !ignore {+ initial, clear := events[0], events[2]+ if initial.Cmd != "msg" || initial.Code != 0 || initial.Msg != "Uploading 1" || initial.Data.ID == "" || initial.Data.CloseTimeout != 3000 {+ t.Fatalf("unexpected initial notification: %+v", initial)+ }+ if clear.Cmd != "cmsg" || clear.Code != 0 || clear.Msg != "" || clear.Data.ID != initial.Data.ID {+ t.Fatalf("cleanup did not clear the operation's notification: %+v", clear)+ }+ }+ failureEvent := events[errorIndex]+ wantCode, wantTimeout, wantMessage := 0, 5000, "Sign in required"+ if failure == "size" {+ wantCode, wantTimeout, wantMessage = -1, 30000, "Asset oversized.dat exceeds 3.0 MiB"+ }+ if failureEvent.Cmd != "msg" || failureEvent.Code != wantCode || failureEvent.Data.ID == "" || failureEvent.Data.CloseTimeout != wantTimeout || failureEvent.Msg != wantMessage {+ t.Fatalf("unexpected failure notification: %+v", failureEvent)+ }+ }+ })+ }+ }+ }+}diff --git a/kernel/model/backlink.go b/kernel/model/backlink.goindex aba6d255b0..b4099644be 100644--- a/kernel/model/backlink.go+++ b/kernel/model/backlink.go@@ -194,7 +194,17 @@ func NormalizeBacklinkSourceFilter(filter *BacklinkSourceFilter) *BacklinkSource}}-func GetBackmentionDoc(defID, refTreeID, keyword string, containChildren, highlight bool) (ret []*Backlink, keywords []string) {+// BackmentionNotifier 向本次提及查询的发起端发送提示;显式传入 nil 时不发送。+type BackmentionNotifier func(msg string, timeout int) string++func backmentionNotifier(notifiers []BackmentionNotifier) BackmentionNotifier {+ if len(notifiers) == 0 {+ return util.PushMsg+ }+ return notifiers[0]+}++func GetBackmentionDoc(defID, refTreeID, keyword string, containChildren, highlight bool, notifiers ...BackmentionNotifier) (ret []*Backlink, keywords []string) {keyword = strings.TrimSpace(keyword)if "" != keyword {keywords = strings.Split(keyword, " ")@@ -211,7 +221,7 @@ func GetBackmentionDoc(defID, refTreeID, keyword string, containChildren, highlirefs = removeDuplicatedRefs(refs)linkRefs, _, excludeBacklinkIDs, originalRefBlockIDs := buildLinkRefs(rootID, refs, keywords)- tmpMentions, mentionKeywords := buildTreeBackmention(sqlBlock, linkRefs, keyword, excludeBacklinkIDs, beforeLen)+ tmpMentions, mentionKeywords := buildTreeBackmention(sqlBlock, linkRefs, keyword, excludeBacklinkIDs, beforeLen, notifiers...)luteEngine := util.NewLute()var mentions []*Blockfor _, mention := range tmpMentions {@@ -386,7 +396,7 @@ func GetBacklinkDocInBoxWithSort(defID, refTreeID, keyword string, containChildrreturn}-func GetBackmentionDocInBox(defID, refTreeID, keyword string, containChildren, highlight bool, boxID string) (ret []*Backlink, keywords []string) {+func GetBackmentionDocInBox(defID, refTreeID, keyword string, containChildren, highlight bool, boxID string, notifiers ...BackmentionNotifier) (ret []*Backlink, keywords []string) {keyword = strings.TrimSpace(keyword)if "" != keyword {keywords = strings.Split(keyword, " ")@@ -403,7 +413,7 @@ func GetBackmentionDocInBox(defID, refTreeID, keyword string, containChildren, hrefs = removeDuplicatedRefs(refs)linkRefs, _, excludeBacklinkIDs, originalRefBlockIDs := buildLinkRefsInBox(rootID, refs, keywords, boxID)- tmpMentions, mentionKeywords := buildTreeBackmentionInBox(sqlBlock, linkRefs, keyword, excludeBacklinkIDs, beforeLen, boxID)+ tmpMentions, mentionKeywords := buildTreeBackmentionInBox(sqlBlock, linkRefs, keyword, excludeBacklinkIDs, beforeLen, boxID, notifiers...)luteEngine := util.NewLute()var mentions []*Blockfor _, mention := range tmpMentions {@@ -606,7 +616,7 @@ func GetBacklink2InBoxWithFilter(id, keyword, mentionKeyword string, sortMode, m}// GetBacklink2InBoxWithOptions 按需查询反链文档分组与提及列表。-func GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword string, sortMode, mentionSortMode int, containChildren bool, boxID string, sourceFilter *BacklinkSourceFilter, includeMentions, includeBacklinks bool) (boxIDOut string, backlinks, backmentions []*Path, linkRefsCount, mentionsCount int) {+func GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword string, sortMode, mentionSortMode int, containChildren bool, boxID string, sourceFilter *BacklinkSourceFilter, includeMentions, includeBacklinks bool, notifiers ...BackmentionNotifier) (boxIDOut string, backlinks, backmentions []*Path, linkRefsCount, mentionsCount int) {keyword = strings.TrimSpace(keyword)var keywords []stringif "" != keyword {@@ -662,7 +672,7 @@ func GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword string, sortMode,})if includeMentions {- mentionRefs, _ := buildTreeBackmentionInBox(sqlBlock, linkRefs, mentionKeyword, excludeBacklinkIDs, 12, boxID)+ mentionRefs, _ := buildTreeBackmentionInBox(sqlBlock, linkRefs, mentionKeyword, excludeBacklinkIDs, 12, boxID, notifiers...)backmentions = backlinkListPaths(mentionRefs, boxID)}@@ -1003,12 +1013,12 @@ func removeDuplicatedRefs(refs []*sql.Ref) (ret []*sql.Ref) {return}-func buildTreeBackmention(defSQLBlock *sql.Block, refBlocks []*Block, keyword string, excludeBacklinkIDs *hashset.Set, beforeLen int) (ret []*Block, mentionKeywords []string) {- return buildTreeBackmentionInBox(defSQLBlock, refBlocks, keyword, excludeBacklinkIDs, beforeLen, "")+func buildTreeBackmention(defSQLBlock *sql.Block, refBlocks []*Block, keyword string, excludeBacklinkIDs *hashset.Set, beforeLen int, notifiers ...BackmentionNotifier) (ret []*Block, mentionKeywords []string) {+ return buildTreeBackmentionInBox(defSQLBlock, refBlocks, keyword, excludeBacklinkIDs, beforeLen, "", notifiers...)}// buildTreeBackmentionInBox 与 buildTreeBackmention 一致,但按 boxID 路由到加密 db 或全局 db。-func buildTreeBackmentionInBox(defSQLBlock *sql.Block, refBlocks []*Block, keyword string, excludeBacklinkIDs *hashset.Set, beforeLen int, boxID string) (ret []*Block, mentionKeywords []string) {+func buildTreeBackmentionInBox(defSQLBlock *sql.Block, refBlocks []*Block, keyword string, excludeBacklinkIDs *hashset.Set, beforeLen int, boxID string, notifiers ...BackmentionNotifier) (ret []*Block, mentionKeywords []string) {ret = []*Block{}var names, aliases []string@@ -1067,12 +1077,12 @@ func buildTreeBackmentionInBox(defSQLBlock *sql.Block, refBlocks []*Block, keywo}mentionKeywords = excludeKeywords(mentionKeywords, Conf.Editor.BacklinkMentionExclude)mentionKeywords = prepareMarkKeywords(mentionKeywords)- mentionKeywords, ret = searchBackmentionInBox(mentionKeywords, keyword, excludeBacklinkIDs, rootID, beforeLen, boxID)+ mentionKeywords, ret = searchBackmentionInBox(mentionKeywords, keyword, excludeBacklinkIDs, rootID, beforeLen, boxID, notifiers...)return}-func searchBackmention(mentionKeywords []string, keyword string, excludeBacklinkIDs *hashset.Set, rootID string, beforeLen int) (retMentionKeywords []string, ret []*Block) {- return searchBackmentionInBox(mentionKeywords, keyword, excludeBacklinkIDs, rootID, beforeLen, "")+func searchBackmention(mentionKeywords []string, keyword string, excludeBacklinkIDs *hashset.Set, rootID string, beforeLen int, notifiers ...BackmentionNotifier) (retMentionKeywords []string, ret []*Block) {+ return searchBackmentionInBox(mentionKeywords, keyword, excludeBacklinkIDs, rootID, beforeLen, "", notifiers...)}func quoteFTSPhrase(phrase string) string {@@ -1093,7 +1103,7 @@ func buildBackmentionQuery(matchExpression, rootID, beforeID string, limit int)}// searchBackmentionInBox 与 searchBackmention 一致,但按 boxID 路由到加密 db 或全局 db。-func searchBackmentionInBox(mentionKeywords []string, keyword string, excludeBacklinkIDs *hashset.Set, rootID string, beforeLen int, boxID string) (retMentionKeywords []string, ret []*Block) {+func searchBackmentionInBox(mentionKeywords []string, keyword string, excludeBacklinkIDs *hashset.Set, rootID string, beforeLen int, boxID string, notifiers ...BackmentionNotifier) (retMentionKeywords []string, ret []*Block) {ret = []*Block{}if 1 > len(mentionKeywords) {return@@ -1103,7 +1113,9 @@ func searchBackmentionInBox(mentionKeywords []string, keyword string, excludeBacbuf.WriteString(columnFilter() + ":(")for i, mentionKeyword := range mentionKeywords {if Conf.Search.BacklinkMentionKeywordsLimit < i {- util.PushMsg(fmt.Sprintf(Conf.Language(38), len(mentionKeywords)), 5000)+ if notify := backmentionNotifier(notifiers); notify != nil {+ notify(fmt.Sprintf(Conf.Language(38), len(mentionKeywords)), 5000)+ }buf.WriteString(quoteFTSPhrase(mentionKeyword))break}diff --git a/kernel/model/backlink_notification_fts5_test.go b/kernel/model/backlink_notification_fts5_test.gonew file mode 100644index 0000000000..a6634b6f9c--- /dev/null+++ b/kernel/model/backlink_notification_fts5_test.go@@ -0,0 +1,129 @@+//go:build fts5 && (sqlcipher || libsqlcipher)++package model++import (+ "bytes"+ "encoding/json"+ "os"+ "path/filepath"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestBackmentionNotificationPlainAndEncrypted(t *testing.T) {+ for _, encrypted := range []bool{false, true} {+ name := "plain"+ if encrypted {+ name = "encrypted"+ }+ t.Run(name, func(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ Conf.Search = conf.NewSearch()+ Conf.Search.BacklinkMentionDoc = true+ Conf.Search.BacklinkMentionName = true+ Conf.Search.BacklinkMentionKeywordsLimit = 0+ var trees []*parse.Tree+ for _, id := range []string{fixture.sourceID, fixture.targetID} {+ tree, err := LoadTreeByBlockID(id)+ if err != nil {+ t.Fatal(err)+ }+ trees = append(trees, tree)+ }+ boxID := ""+ if encrypted {+ boxID = fixture.box.ID+ dek := bytes.Repeat([]byte{0x65}, 32)+ markRuntimeEncryptedBox(boxID)+ setDEKForTest(boxID, dek)+ boxConf := conf.NewBoxConf()+ boxConf.Encrypted = true+ boxConf.BoxCrypt = &conf.BoxEncryption{Spec: boxEncryptionSpec}+ if err := encryptBoxMetadata(boxID, boxConf, dek); err != nil {+ t.Fatal(err)+ }+ data, err := json.Marshal(boxConf)+ if err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json"), data, 0600); err != nil {+ t.Fatal(err)+ }+ mountedEncryptedBoxes.Store(boxID, true)+ t.Cleanup(func() {+ sql.CloseEncryptedDB(boxID)+ treenode.CloseEncryptedBlockTreeDB(boxID)+ mountedEncryptedBoxes.Delete(boxID)+ forgetRuntimeEncryptedBox(boxID)+ encryptedBoxLifecycles.Delete(boxID)+ cachedDEKsLock.Lock()+ delete(cachedDEKs, boxID)+ cachedDEKsLock.Unlock()+ })+ if err = treenode.OpenEncryptedBlockTreeDB(boxID, dek); err != nil {+ t.Fatal(err)+ }+ if err = sql.OpenEncryptedDB(boxID, dek); err != nil {+ t.Fatal(err)+ }+ }+ for _, tree := range trees {+ var err error+ id := tree.Root.ID+ for tree.Root.FirstChild != nil {+ tree.Root.FirstChild.Unlink()+ }+ p := treenode.NewParagraph(ast.NewNodeID())+ if id == fixture.sourceID {+ tree.Root.SetIALAttr("title", "needle")+ tree.HPath = "/needle"+ p.SetIALAttr("name", "second")+ p.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("source")})+ } else {+ p.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("needle second")})+ }+ tree.Root.AppendChild(p)+ if _, err = filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ sql.IndexTreeQueue(tree)+ }+ sql.FlushQueue()+ calls := 0+ notify := func(msg string, timeout int) string {+ calls+++ if timeout != 5000 {+ t.Fatalf("warning timeout = %d", timeout)+ }+ return "warning"+ }+ var docs []*Backlink+ if encrypted {+ docs, _ = GetBackmentionDocInBox(fixture.sourceID, fixture.targetID, "", false, true, boxID, notify)+ } else {+ docs, _ = GetBackmentionDoc(fixture.sourceID, fixture.targetID, "", false, true, notify)+ }+ if calls != 1 || len(docs) == 0 {+ t.Fatalf("document warning calls=%d results=%d", calls, len(docs))+ }+ _, _, mentions, _, count := GetBacklink2InBoxWithOptions(fixture.sourceID, "", "", 0, 0, false, boxID, nil, true, true, notify)+ if calls != 2 || len(mentions) == 0 || count == 0 {+ t.Fatalf("list warning calls=%d results=%d count=%d", calls, len(mentions), count)+ }+ _, _, _, _, silentCount := GetBacklink2InBoxWithOptions(fixture.sourceID, "", "", 0, 0, false, boxID, nil, true, true, nil)+ if silentCount != count || calls != 2 {+ t.Fatal("suppression changed search results")+ }+ })+ }+}diff --git a/kernel/model/backlink_notification_test.go b/kernel/model/backlink_notification_test.gonew file mode 100644index 0000000000..72773324eb--- /dev/null+++ b/kernel/model/backlink_notification_test.go@@ -0,0 +1,45 @@+package model++import (+ "reflect"+ "testing"++ "github.com/emirpasic/gods/sets/hashset"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestBackmentionNotifierLegacyAndSuppressed(t *testing.T) {+ if reflect.ValueOf(backmentionNotifier(nil)).Pointer() != reflect.ValueOf(util.PushMsg).Pointer() {+ t.Fatal("omitted notifier must retain legacy broadcast")+ }+ if backmentionNotifier([]BackmentionNotifier{nil}) != nil {+ t.Fatal("explicit nil notifier must suppress notification")+ }+}++func TestBackmentionKeywordWarningNotifier(t *testing.T) {+ previous := Conf+ Conf = NewAppConf()+ Conf.Search = conf.NewSearch()+ Conf.Search.BacklinkMentionKeywordsLimit = 0+ Conf.Search.Limit = 0+ t.Cleanup(func() { Conf = previous })+ calls := 0+ notify := func(msg string, timeout int) string {+ calls+++ if timeout != 5000 {+ t.Fatalf("warning timeout = %d", timeout)+ }+ return "warning"+ }+ searchBackmention([]string{"first", "second"}, "", hashset.New(), "root", 12, notify)+ if calls != 1 {+ t.Fatalf("warning invoked notifier %d times", calls)+ }+ searchBackmention([]string{"first", "second"}, "", hashset.New(), "root", 12, nil)+ searchBackmention([]string{"first"}, "", hashset.New(), "root", 12, notify)+ if calls != 1 {+ t.Fatal("suppressed or below-limit search emitted warning")+ }+}diff --git a/kernel/util/websocket.go b/kernel/util/websocket.goindex 8eba819867..506a321bd3 100644--- a/kernel/util/websocket.go+++ b/kernel/util/websocket.go@@ -284,31 +284,43 @@ func PushTxErr(msg string, code int, data any) {}func PushUpdateMsg(msgId string, msg string, timeout int) {- BroadcastByType("main", "msg", 0, msg, map[string]any{"id": msgId, "closeTimeout": timeout})+ PushUpdateMsgWithApp("", msgId, msg, timeout)+}++// PushUpdateMsgWithApp 在指定实例更新提示;未指定实例时广播,实例离线时丢弃。+func PushUpdateMsgWithApp(app, msgId, msg string, timeout int) {+ pushNotificationWithApp(app, "msg", 0, msg, map[string]any{"id": msgId, "closeTimeout": timeout})}func PushMsg(msg string, timeout int) (msgId string) {- msgId = gulu.Rand.String(7)- BroadcastByType("main", "msg", 0, msg, map[string]any{"id": msgId, "closeTimeout": timeout})- return+ return PushMsgWithApp("", msg, timeout)}func PushMsgWithApp(app, msg string, timeout int) (msgId string) {msgId = gulu.Rand.String(7)- if "" == app {- BroadcastByType("main", "msg", 0, msg, map[string]any{"id": msgId, "closeTimeout": timeout})- return- }- BroadcastByTypeAndApp("main", app, "msg", 0, msg, map[string]any{"id": msgId, "closeTimeout": timeout})+ PushUpdateMsgWithApp(app, msgId, msg, timeout)return}func PushErrMsg(msg string, timeout int) (msgId string) {+ return PushErrMsgWithApp("", msg, timeout)+}++// PushErrMsgWithApp 在指定实例显示错误;未指定实例时广播,实例离线时丢弃。+func PushErrMsgWithApp(app, msg string, timeout int) (msgId string) {msgId = gulu.Rand.String(7)- BroadcastByType("main", "msg", -1, msg, map[string]any{"id": msgId, "closeTimeout": timeout})+ pushNotificationWithApp(app, "msg", -1, msg, map[string]any{"id": msgId, "closeTimeout": timeout})return}+func pushNotificationWithApp(app, cmd string, code int, msg string, data any) {+ if "" == app {+ BroadcastByType("main", cmd, code, msg, data)+ return+ }+ BroadcastByTypeAndApp("main", app, cmd, code, msg, data)+}+func PushStatusBar(msg string) {msg += " (" + time.Now().Format("2006-01-02 15:04:05") + ")"BroadcastByType("main", "statusbar", 0, msg, nil)@@ -388,6 +400,14 @@ func PushClearMsg(msgId string) {BroadcastByType("main", "cmsg", 0, "", map[string]any{"id": msgId})}+// PushClearMsgWithApp 清除指定实例的单条提示;空消息 ID 不执行清除,避免影响其他任务。+func PushClearMsgWithApp(app, msgId string) {+ if "" == msgId {+ return+ }+ pushNotificationWithApp(app, "cmsg", 0, "", map[string]any{"id": msgId})+}+// PushClearProgress 取消进度遮罩。func PushClearProgress() {BroadcastByType("main", "cprogress", 0, "", nil)diff --git a/kernel/util/websocket_notification_test.go b/kernel/util/websocket_notification_test.gonew file mode 100644index 0000000000..d0f5a213f2--- /dev/null+++ b/kernel/util/websocket_notification_test.go@@ -0,0 +1,215 @@+package util++import (+ "net/http"+ "net/http/httptest"+ "net/url"+ "reflect"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/gorilla/websocket"+ "github.com/olahol/melody"+)++type notificationTestEvent struct {+ Cmd string+ Code int+ Msg string+ Data struct {+ ID string+ CloseTimeout int+ }+}++type notificationTestClient struct {+ connection *websocket.Conn+ session *melody.Session+}++type notificationTestHub struct {+ push *melody.Melody+ clients []notificationTestClient+ first string+ second string+}++func newNotificationTestHub(t *testing.T) *notificationTestHub {+ t.Helper()+ hub := ¬ificationTestHub{push: melody.New(), first: t.TempDir() + "-first", second: t.TempDir() + "-second"}+ connected := make(chan *melody.Session, 1)+ hub.push.HandleConnect(func(session *melody.Session) {+ query := session.Request.URL.Query()+ if query.Get("publish") == "true" {+ session.Set("isPublish", true)+ }+ if query.Get("auth") == "true" {+ session.Set("authSession", true)+ }+ AddPushChan(session)+ connected <- session+ })+ hub.push.HandleDisconnect(RemovePushChan)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _ = hub.push.HandleRequest(w, r)+ }))+ t.Cleanup(func() {+ for _, client := range hub.clients {+ _ = client.connection.Close()+ RemovePushChan(client.session)+ }+ _ = hub.push.Close()+ server.Close()+ })+ for _, query := range []string{+ "app=" + url.QueryEscape(hub.first) + "&id=main&type=main",+ "app=" + url.QueryEscape(hub.second) + "&id=main&type=main",+ "app=" + url.QueryEscape(hub.first) + "&id=publish&type=main&publish=true",+ "app=" + url.QueryEscape(hub.first) + "&id=auth&type=main&auth=true",+ "app=" + url.QueryEscape(hub.first) + "&id=tree&type=filetree",+ } {+ connection, response, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http")+"/ws?"+query, nil)+ if err != nil {+ t.Fatal(err)+ }+ _ = response.Body.Close()+ select {+ case session := <-connected:+ hub.clients = append(hub.clients, notificationTestClient{connection: connection, session: session})+ case <-time.After(5 * time.Second):+ _ = connection.Close()+ t.Fatal("notification connection was not registered")+ }+ }+ return hub+}++func (hub *notificationTestHub) readEvents(t *testing.T) [][]notificationTestEvent {+ t.Helper()+ // 屏障与提示进入同一连接队列,无需等待超时来断言未收到提示。+ if err := hub.push.Broadcast([]byte(`{"cmd":"notification-test-barrier"}`)); err != nil {+ t.Fatal(err)+ }+ result := make([][]notificationTestEvent, len(hub.clients))+ for i, client := range hub.clients {+ if err := client.connection.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {+ t.Fatal(err)+ }+ for {+ var event notificationTestEvent+ if err := client.connection.ReadJSON(&event); err != nil {+ t.Fatal(err)+ }+ if event.Cmd == "notification-test-barrier" {+ break+ }+ result[i] = append(result[i], event)+ }+ }+ return result+}++func notificationEvent(cmd string, code int, msg, id string, timeout int) notificationTestEvent {+ event := notificationTestEvent{Cmd: cmd, Code: code, Msg: msg}+ event.Data.ID = id+ event.Data.CloseTimeout = timeout+ return event+}++func TestNotificationAppScopeLifecycle(t *testing.T) {+ for _, target := range []string{"first", "second", "absent", "legacy"} {+ t.Run(target, func(t *testing.T) {+ hub := newNotificationTestHub(t)+ app := map[string]string{"first": hub.first, "second": hub.second, "absent": hub.first + "-closed"}[target]+ id := PushMsgWithApp(app, "started", 1)+ PushUpdateMsgWithApp(app, id, "finished", 7000)+ errID := PushErrMsgWithApp(app, "failed", 5000)+ PushClearMsgWithApp(app, id)+ PushClearMsgWithApp(app, "")+ if id == "" || errID == "" {+ t.Fatal("notification IDs must not be empty")+ }+ want := []notificationTestEvent{+ notificationEvent("msg", 0, "started", id, 1),+ notificationEvent("msg", 0, "finished", id, 7000),+ notificationEvent("msg", -1, "failed", errID, 5000),+ notificationEvent("cmsg", 0, "", id, 0),+ }+ for i, got := range hub.readEvents(t) {+ var expected []notificationTestEvent+ if i == 0 && (target == "first" || target == "legacy") || i == 1 && (target == "second" || target == "legacy") {+ expected = want+ }+ if !reflect.DeepEqual(got, expected) {+ t.Fatalf("client %d received %+v, want %+v", i, got, expected)+ }+ }+ })+ }+}++func TestNotificationGlobalHelpersPreserveBroadcast(t *testing.T) {+ hub := newNotificationTestHub(t)+ id := PushMsg("started", 3000)+ PushUpdateMsg("fixed-global-id", "updated", 7000)+ errID := PushErrMsg("failed", 5000)+ PushClearMsg(id)+ PushClearMsg("")+ want := []notificationTestEvent{+ notificationEvent("msg", 0, "started", id, 3000),+ notificationEvent("msg", 0, "updated", "fixed-global-id", 7000),+ notificationEvent("msg", -1, "failed", errID, 5000),+ notificationEvent("cmsg", 0, "", id, 0),+ notificationEvent("cmsg", 0, "", "", 0),+ }+ for i, got := range hub.readEvents(t) {+ var expected []notificationTestEvent+ if i < 2 {+ expected = want+ }+ if !reflect.DeepEqual(got, expected) {+ t.Fatalf("client %d received %+v, want %+v", i, got, expected)+ }+ }+}++func TestNotificationConcurrentOperationsAndLateUpdates(t *testing.T) {+ hub := newNotificationTestHub(t)+ var workers sync.WaitGroup+ for _, app := range []string{hub.first, hub.second} {+ workers.Go(func() {+ // 同名消息仍须由每次调用携带的实例标识决定接收方。+ PushUpdateMsgWithApp(app, "same-id", app, 1)+ PushClearMsgWithApp(app, "same-id")+ PushUpdateMsgWithApp(app, "same-id", "late-"+app, 7000)+ })+ }+ workers.Wait()+ for i, got := range hub.readEvents(t) {+ var expected []notificationTestEvent+ if i < 2 {+ app := []string{hub.first, hub.second}[i]+ expected = []notificationTestEvent{+ notificationEvent("msg", 0, app, "same-id", 1),+ notificationEvent("cmsg", 0, "", "same-id", 0),+ notificationEvent("msg", 0, "late-"+app, "same-id", 7000),+ }+ }+ if !reflect.DeepEqual(got, expected) {+ t.Fatalf("client %d received %+v, want %+v", i, got, expected)+ }+ }++ // 实例离线后迟到的更新、错误和清理不能退化为广播。+ RemovePushChan(hub.clients[0].session)+ PushUpdateMsgWithApp(hub.first, "same-id", "offline", 7000)+ PushErrMsgWithApp(hub.first, "offline-error", 7000)+ PushClearMsgWithApp(hub.first, "same-id")+ for i, got := range hub.readEvents(t) {+ if len(got) != 0 {+ t.Fatalf("client %d received offline notification: %+v", i, got)+ }+ }+}