An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:recycle: Unify kernel and frontend configuration handling https://github.com/siyuan-note/siyuan/issues/20443
Daniel6f97d80a3dd1
diff --git a/app/src/boot/globalEvent/commonHotkey.ts b/app/src/boot/globalEvent/commonHotkey.tsindex bb0dbb93cc..f3ffa2728f 100644--- a/app/src/boot/globalEvent/commonHotkey.ts+++ b/app/src/boot/globalEvent/commonHotkey.ts@@ -1,7 +1,7 @@+import {config as configApi} from "../../config/util/configApi";import {keymapPayload} from "../../config/keymapPayload";import {mergeKeymapDefault} from "../../util/keymapBindings";import {Constants} from "../../constants";-import {fetchPost} from "../../util/fetch";/// #if !BROWSERimport {sendGlobalShortcut} from "./globalShortcut";import {ipcRenderer} from "electron";@@ -151,9 +151,7 @@ export const correctHotkey = (app: App) => {msg: "update keymap"});/// #endif- fetchPost("/api/setting/setKeymap", {- data: keymapPayload(window.siyuan.config.keymap)- }, () => {+ configApi.set("keymap", keymapPayload(window.siyuan.config.keymap), () => {/// #if !BROWSERsendGlobalShortcut(app);syncAppMenuShortcuts();diff --git a/app/src/config/bazaar.ts b/app/src/config/bazaar.tsindex 42f7ad205a..23a501c521 100644--- a/app/src/config/bazaar.ts+++ b/app/src/config/bazaar.ts@@ -1,4 +1,4 @@-import {refreshSettingConfig} from "./setting/sync";+import {config as configApi} from "./util/configApi";import {showMessage} from "../dialog/message";import {fetchPost} from "../util/fetch";import {ContractFormData} from "../util/contractFormData";@@ -1547,14 +1547,7 @@ type="checkbox">callback();return;}- fetchPost("/api/setting/patch", {appearance: patch}, response => {- if (response.code !== 0) {- showMessage(response.msg);- callback();- return;- }- void refreshSettingConfig("appearance").then(callback);- });+ void configApi.set("appearance", patch).catch(error => console.warn("Could not update appearance", error)).finally(callback);},_initBazaarPanel(bazaarType: TBazaarType, panel: HTMLElement) {if (panel.getAttribute("data-init")) {@@ -1742,11 +1735,7 @@ type="checkbox">if (!window.siyuan.config.bazaar.trust) {bazaar.element.querySelector("button").addEventListener("click", () => {const mount = bazaar._captureMount();- fetchPost("/api/setting/setBazaar", {- ...window.siyuan.config.bazaar,- trust: true,- }, (response) => {- window.siyuan.config.bazaar = response.data;+ configApi.set("bazaar.trust", true, () => {if (!bazaar._isMountCurrent(mount)) {return;}diff --git a/app/src/config/entryVisibility/runtime.test.ts b/app/src/config/entryVisibility/runtime.test.tsindex 3a9981877f..0831c48637 100644--- a/app/src/config/entryVisibility/runtime.test.ts+++ b/app/src/config/entryVisibility/runtime.test.ts@@ -315,7 +315,7 @@ test("dock visibility menus follow profile scope order instead of the catalog orassert.deepEqual(Array.from(exports.getEntryOrder("dock")), ["file", "outline"]);});-test("entry profile saves in settings windows send requests and flush pending changes", () => {+test("entry profile saves in settings windows send requests and flush pending changes", async () => {const initial: Config.IEntryVisibility = {version: 6, active: "full", profiles: []};const events: string[] = [];const requests: Array<{url: string; config: Config.IEntryVisibility;@@ -343,25 +343,28 @@ test("entry profile saves in settings windows send requests and flush pending chgetDockEntryOrderSnapshot: () => Object.fromEntries(DOCK_ORDER_SCOPES.map(scope => [scope, []])),mergeDockEntryOrderSnapshot,applyDockEntryOrderSnapshot: () => {},- fetchPost: (url: string, config: Config.IEntryVisibility,- respond: (response: {code: number; data: Config.IEntryVisibility}) => void) => {- requests.push({url, config, respond});- },+ config: {set: (path: string, config: Config.IEntryVisibility, applied: (data: unknown) => void) => {+ return new Promise<{code: number; data: Config.IEntryVisibility}>(resolve => {+ requests.push({url: path, config, respond: resolve});+ }).then(response => { if (response.code === 0) applied({entryVisibility: response.data}); });+ }},})});const simple = {...initial, active: "simple"};const full = {...initial};exports.saveEntryVisibility(simple);assert.equal(window.siyuan.config.appearance.entryVisibility, simple);assert.equal(requests.length, 1);- assert.equal(requests[0].url, "/api/setting/setEntryVisibility");+ assert.equal(requests[0].url, "appearance.entryVisibility");assert.equal(requests[0].config, simple);assert.deepEqual(events, ["siyuan-entry-visibility"]);exports.saveEntryVisibility(full);assert.equal(requests.length, 1);requests[0].respond({code: 0, data: simple});+ await new Promise(setImmediate);assert.equal(requests.length, 2);assert.equal(requests[1].config, full);assert.equal(window.siyuan.config.appearance.entryVisibility, full);requests[1].respond({code: 0, data: full});- assert.deepEqual(events, ["siyuan-entry-visibility", "siyuan-entry-visibility", "siyuan-entry-visibility"]);+ await new Promise(setImmediate);+ assert.deepEqual(events, ["siyuan-entry-visibility", "siyuan-entry-visibility"]);});diff --git a/app/src/config/entryVisibility/runtime.ts b/app/src/config/entryVisibility/runtime.tsindex c00b166ecd..9c87ff9592 100644--- a/app/src/config/entryVisibility/runtime.ts+++ b/app/src/config/entryVisibility/runtime.ts@@ -1,4 +1,4 @@-import {fetchPost} from "../../util/fetch";+import {config as configApi} from "../util/configApi";import {Constants} from "../../constants";import {getSettingsOwnerApp} from "../setting/windowContext";import {@@ -209,11 +209,10 @@ const flushEntryVisibility = () => {saveRunning = true;const next = savePending;savePending = undefined;- fetchPost("/api/setting/setEntryVisibility", next, (response) => {+ void configApi.set("appearance.entryVisibility", next, data => {+ if (!savePending) applyEntryVisibility((data as Config.IAppearance).entryVisibility);+ }).catch(error => console.warn("Could not save entry visibility", error)).finally(() => {saveRunning = false;- if (response.code === 0 && !savePending) {- applyEntryVisibility(response.data as Config.IEntryVisibility);- }flushEntryVisibility();});};diff --git a/app/src/config/ocr.test.ts b/app/src/config/ocr.test.tsindex 14cce206bc..74abdffa14 100644--- a/app/src/config/ocr.test.ts+++ b/app/src/config/ocr.test.ts@@ -96,6 +96,14 @@ const createOCRPanel = async () => {options.signal.addEventListener("abort", () => notifications.delete(name));},}, require: () => ({+ config: {set: (_path: string, value: typeof config.ocr, applied: (next: typeof config.ocr) => void) => {+ return new Promise<{code: number; data?: typeof config.ocr}>((resolve, reject) => requests.push({config: value, resolve, reject}))+ .then(response => {+ if (response.code !== 0) throw new Error("save failed");+ config.ocr = response.data;+ applied(response.data);+ });+ }},OCR_CHANGED_EVENT: "ocr-test",AI_CONFIG_CHANGED_EVENT: "ai-test",trackSettingSave: (task: Promise<boolean>) => task,@@ -380,7 +388,7 @@ test("undoing an uncommitted threshold edit resumes updates from another window"panel.close();});-test("closing the OCR panel cancels queued saves and ignores a late response", async () => {+test("closing the OCR panel cancels queued saves while confirmed shared configuration remains synchronized", async () => {const panel = await createOCRPanel();const first = panel.changeAuto(true);await new Promise(setImmediate);@@ -389,7 +397,8 @@ test("closing the OCR panel cancels queued saves and ignores a late response", apanel.requests[0].resolve({code: 0, data: panel.requests[0].config});await Promise.all([first, second]);assert.equal(panel.requests.length, 1);- assert.equal(panel.config.ocr.auto, false);+ assert.equal(panel.config.ocr.auto, true);+ assert.equal(panel.controls.ocrAuto.checked, false);});test("OCR notifications update configuration and model options without replacing the form or file choices", async () => {diff --git a/app/src/config/ocr.ts b/app/src/config/ocr.tsindex 1f8b387a8c..a10d009a39 100644--- a/app/src/config/ocr.ts+++ b/app/src/config/ocr.ts@@ -1,3 +1,4 @@+import {config as configApi} from "./util/configApi";import type {OCRConfigData, OCRThresholds, SettingOCR} from "../types/api";import {fetchSyncPost} from "../util/fetch";import {ContractFormData} from "../util/contractFormData";@@ -266,12 +267,12 @@ export const mountOCRSettings = (root: HTMLElement): (() => void) => {if (closed) {return false;}- const response = await fetchSyncPost("/api/asset/setOCRConfig", config, undefined, true, controller.signal);- if (response.code === 0 && !closed) {- data.config = response.data;- window.siyuan.config.ocr = response.data;- saved = true;- }+ await configApi.set("ocr", config, next => {+ if (!closed) {+ data.config = next as SettingOCR;+ saved = true;+ }+ });} catch (error) {handleError(error);} finally {diff --git a/app/src/config/setting/sync.test.ts b/app/src/config/setting/sync.test.tsindex 91a130f9e4..8d5c4e75ae 100644--- a/app/src/config/setting/sync.test.ts+++ b/app/src/config/setting/sync.test.ts@@ -4,8 +4,8 @@ import {test} from "node:test";import {runInNewContext} from "node:vm";import {createSourceFile, isClassDeclaration, isMethodDeclaration, isVariableStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";import {getAgentDefaultModelID, getUsableAgentModels} from "../../layout/dock/agent/agentModel";-import {createNamespacePatchQueue} from "../util/namespacePatchQueue";import {mergeRecordByDottedPath} from "../util/dotPath";+import {createSectionRuntime, type Reaction} from "../util/sectionRuntime";for (const mobile of [false, true]) {@@ -38,8 +38,11 @@ for (const mobile of [false, true]) {const api = {} as {createConfigNamespaceApi: (options: {namespace: string; getConfig: () => typeof config.editor;}) => {patch: (path: string, value: number, applied: (value: typeof config.editor) => void) => Promise<void>}};+ const gateway = {} as typeof import("../util/configApi");+ runInNewContext(compile("src/config/util/configApi.ts"), {exports: gateway, window: {siyuan: {config}}, structuredClone,+ require: () => ({...refresh, fetchSyncPost, mergeRecordByDottedPath, trackSettingSave: (task: Promise<void>) => task})});runInNewContext(compile("src/config/util/namespaceApi.ts"), {exports: api, require: () => ({- ...refresh, fetchSyncPost, createNamespacePatchQueue, mergeRecordByDottedPath,+ config: gateway.config, createSectionRuntime,})});let confirmed: typeof config.editor;await api.createConfigNamespaceApi({namespace: "editor", getConfig: () => config.editor})@@ -217,7 +220,10 @@ for (const mobile of [false, true]) {const aiExports = {} as {aiConfigApi: {apply: (value: AIConfig) => void}};runInNewContext(compile("src/config/tabs/ai/aiRuntime.ts"), {exports: aiExports, window: windowContext, CustomEvent: class {constructor(public type: string) {}},- require: () => ({createConfigNamespaceApi: (options: {setConfig: (value: AIConfig) => void}) => ({apply: options.setConfig})}),+ require: () => ({createConfigNamespaceApi: (options: {namespace: string; getConfig: () => AIConfig;+ setConfig: (value: AIConfig) => void; reactions: Reaction<AIConfig>[]}) =>+ createSectionRuntime({namespace: options.namespace, get: options.getConfig, set: options.setConfig,+ reactions: options.reactions || []})}),});const dependencies = {fetchSyncPost: async () => ({code: 0, data: {conf: JSON.parse(JSON.stringify({...config, ai: next}))}}),diff --git a/app/src/config/setting/sync.ts b/app/src/config/setting/sync.tsindex bad7b9c414..33fb728d76 100644--- a/app/src/config/setting/sync.ts+++ b/app/src/config/setting/sync.ts@@ -1,6 +1,7 @@import {fetchSyncPost} from "../../util/fetch";import {systemConfig} from "../systemConfig";import {editorConfigApi} from "../tabs/editorRuntime";+import {exportConfigApi} from "../tabs/exportRuntime";import {appearanceConfigApi} from "../tabs/appearanceRuntime";import {aiConfigApi} from "../tabs/ai/aiRuntime";import {objEquals} from "../../util/functions";@@ -54,13 +55,16 @@ export const refreshSettingConfig = (namespace = "*"): Promise<void> => {syncSettingTasks(response.data.settingTasks);const includes = (key: string) => namespaces.has("*") || namespaces.has(key);if (includes("editor") && !objEquals(window.siyuan.config.editor, next.editor)) {- editorConfigApi.apply(next.editor);+ await editorConfigApi.apply(next.editor);}if (includes("appearance") && !objEquals(window.siyuan.config.appearance, next.appearance)) {- appearanceConfigApi.apply(next.appearance);+ await appearanceConfigApi.apply(next.appearance);+ }+ if (includes("export") && !objEquals(window.siyuan.config.export, next.export)) {+ await exportConfigApi.apply(next.export);}if (includes("ai") && !objEquals(window.siyuan.config.ai, next.ai)) {- aiConfigApi.apply(next.ai);+ await aiConfigApi.apply(next.ai);}if (includes("sync") && !objEquals(window.siyuan.config.sync, next.sync)) {window.siyuan.config.sync = next.sync;@@ -85,9 +89,9 @@ export const refreshSettingConfig = (namespace = "*"): Promise<void> => {window.siyuan.config.keymap = next.keymap;}/// #endif- const simple = ["export", "fileTree", "search", "flashcard", "secrets", "variables", "repo", "system", "bazaar", "publish", "ocr"] as const;+ const simple = ["fileTree", "search", "flashcard", "secrets", "variables", "repo", "system", "bazaar", "publish", "ocr", "snippet", "tag", "graph", "uiLayout", "stat"] as const;for (const key of simple) {- if (includes(key)) {+ if (includes(key) && (key !== "graph" || !window.siyuan.config.readonly)) {Object.assign(window.siyuan.config, {[key]: next[key]});}}@@ -100,7 +104,7 @@ export const refreshSettingConfig = (namespace = "*"): Promise<void> => {/// #if !MOBILEconst tabs: Record<string, TSettingTab> = {fileTree: "file", secrets: "secretsVariables", variables: "secretsVariables", system: "app", publish: "access"};const remountTabs = new Set<TSettingTab>();- for (const namespace of namespaces.has("*") ? [...simple, "editor", "keymap", "appearance", "ai", "sync"] : namespaces) {+ for (const namespace of namespaces.has("*") ? [...simple, "editor", "export", "keymap", "appearance", "ai", "sync"] : namespaces) {const tab = getSettingTabDefs().find(definition => definition.id === (tabs[namespace] || namespace));if (tab && tab.id !== "ocr") remountTabs.add(tab.id);}diff --git a/app/src/config/tabs/accessRuntime.ts b/app/src/config/tabs/accessRuntime.tsindex 87abb80656..b583c2a29d 100644--- a/app/src/config/tabs/accessRuntime.ts+++ b/app/src/config/tabs/accessRuntime.ts@@ -1,3 +1,4 @@+import {config as configApi} from "../util/configApi";import {escapeHtmlTextAndAttr} from "../../util/escape";import {fetchPost} from "../../util/fetch";import {isMobile} from "../../util/functions";@@ -44,15 +45,15 @@ export const savePublish = (authEnable?: boolean;},) => {- fetchPost("/api/setting/setPublish", {+ configApi.set("publish", {enable: overrides?.enable ?? window.siyuan.config.publish.enable,port: overrides?.port ?? window.siyuan.config.publish.port,auth: {enable: overrides?.authEnable ?? window.siyuan.config.publish.auth.enable,accounts: window.siyuan.config.publish.auth.accounts,},- }, (response: IWebSocketData) => {- updatePublishConfig(reloadAccounts, response);+ }, () => {+ fetchPost("/api/setting/getPublish", {}, response => updatePublishConfig(reloadAccounts, response));});};@@ -113,7 +114,7 @@ export const sendAccessSetting = (controlId: string, value: unknown) => {switch (controlId) {case "api.token": {const token = value as Config.IAPI["token"];- fetchPost("/api/system/setAPIToken", {token}, () => {+ configApi.set("api.token", token, () => {window.siyuan.config.api.token = token;const tokenTipEl = accessTabElement?.querySelector(`#${CSS.escape("api.token")}`)?.closest(".config-item")?.querySelector(".b3-label__text");if (tokenTipEl) {diff --git a/app/src/config/tabs/accessTab.ts b/app/src/config/tabs/accessTab.tsindex d082abab48..0e1b2a20d1 100644--- a/app/src/config/tabs/accessTab.ts+++ b/app/src/config/tabs/accessTab.ts@@ -1,3 +1,4 @@+import {config as configApi} from "../util/configApi";import {fetchWithAppId} from "../../util/fetchWithAppId";import {escapeHtmlTextAndAttr} from "../../util/escape";import type {SettingTabBuilder} from "../setting/builder";@@ -427,8 +428,7 @@ const mountOIDCButton = (root: HTMLElement) => {}).catch((error) => validationFailed(error instanceof Error ? error.message : String(error), attempt));return;}- fetchPost("/api/system/setOIDC", nextConfig, (response) => {- window.siyuan.config.oidc = response.data;+ configApi.set("oidc", nextConfig, () => {dialog.destroy();});} catch (error) {@@ -446,7 +446,7 @@ const mountAuthCodeButton = (root: HTMLElement) => {placeholder: window.siyuan.languages.about5,description: window.siyuan.languages.about6,onConfirm: (value) => {- fetchPost("/api/system/setAccessAuthCode", {accessAuthCode: value});+ configApi.set("accessAuthCode", value);},});dialog.element.setAttribute("data-key", Constants.DIALOG_ACCESSAUTHCODE);diff --git a/app/src/config/tabs/ai/aiRuntime.ts b/app/src/config/tabs/ai/aiRuntime.tsindex ca8d025c8d..a20c014d83 100644--- a/app/src/config/tabs/ai/aiRuntime.ts+++ b/app/src/config/tabs/ai/aiRuntime.ts@@ -11,7 +11,9 @@ const aiConfigNamespaceApi = createConfigNamespaceApi<Config.IAI>({setConfig: (data) => {window.siyuan.config.ai = data;},- apiPath: "/api/setting/setAI",+ reactions: [{name: "model-pickers", changed: () => true, apply: () => {+ window.dispatchEvent(new CustomEvent(AI_CONFIG_CHANGED_EVENT));+ }}],});export const aiConfigApi = {@@ -19,17 +21,15 @@ export const aiConfigApi = {let applied = false;const task = aiConfigNamespaceApi.patch(relOrFullId, value, (data) => {applied = true;- window.dispatchEvent(new CustomEvent(AI_CONFIG_CHANGED_EVENT));onApplied?.(data);});- pendingSave = task.then(() => applied);+ pendingSave = task.then(() => applied, () => false);return task;},waitForSave() {return pendingSave;},apply(data: Config.IAI) {- aiConfigNamespaceApi.apply(data);- window.dispatchEvent(new CustomEvent(AI_CONFIG_CHANGED_EVENT));+ return aiConfigNamespaceApi.apply(data);},};diff --git a/app/src/config/tabs/appRuntime.test.ts b/app/src/config/tabs/appRuntime.test.tsindex c1cb6d91f4..4b532554e0 100644--- a/app/src/config/tabs/appRuntime.test.ts+++ b/app/src/config/tabs/appRuntime.test.ts@@ -19,6 +19,13 @@ const fixture = () => {console: {warn: (): void => undefined},window: {siyuan: {config: {system}}},require: (name: string) => {+ if (name === "../util/configApi") {+ return {config: {set: (path: string, value: unknown, onApplied?: () => void) => {+ posted.push([path, value]);+ onApplied?.();+ return Promise.resolve();+ }}};+ }if (name === "../../util/fetch") {return {fetchPost: (url: string, payload: unknown, cb?: () => void) => {posted.push([url, payload]);@@ -46,9 +53,9 @@ test("settings window preference submits the boolean and mirrors it locally", ()f.api.sendAppSetting("system.settingsWindow", undefined);assert.equal(f.system.settingsWindow, false);assert.equal(JSON.stringify(f.posted), JSON.stringify([- ["/api/system/setSettingsWindow", {settingsWindow: true}],- ["/api/system/setSettingsWindow", {settingsWindow: false}],- ["/api/system/setSettingsWindow", {settingsWindow: false}],+ ["system.settingsWindow", true],+ ["system.settingsWindow", false],+ ["system.settingsWindow", false],]));});diff --git a/app/src/config/tabs/appRuntime.ts b/app/src/config/tabs/appRuntime.tsindex 7d3266ad02..71ce1625bc 100644--- a/app/src/config/tabs/appRuntime.ts+++ b/app/src/config/tabs/appRuntime.ts@@ -1,7 +1,7 @@+import {config as configApi} from "../util/configApi";/// #if !BROWSERimport {ipcRenderer} from "electron";/// #endif-import {fetchPost} from "../../util/fetch";import {Constants} from "../../constants";/// #if !MOBILEimport {exportLayout} from "../../layout/util";@@ -13,7 +13,7 @@ export const sendAppSetting = (controlId: string, value: unknown) => {switch (controlId) {case "system.autoLaunch2": {const autoLaunchMode = value as Config.ISystem["autoLaunch2"];- fetchPost("/api/system/setAutoLaunch", {autoLaunch: autoLaunchMode}, () => {+ configApi.set("system.autoLaunch2", autoLaunchMode, () => {window.siyuan.config.system.autoLaunch2 = autoLaunchMode;/// #if !BROWSERipcRenderer.send(Constants.SIYUAN_AUTO_LAUNCH, {@@ -26,14 +26,14 @@ export const sendAppSetting = (controlId: string, value: unknown) => {}case "system.lockScreenMode": {const lockScreenMode = (value ? 1 : 0) as Config.ISystem["lockScreenMode"];- fetchPost("/api/system/setFollowSystemLockScreen", {lockScreenMode}, () => {+ configApi.set("system.lockScreenMode", lockScreenMode, () => {window.siyuan.config.system.lockScreenMode = lockScreenMode;});break;}case "system.networkServe": {const networkServe = Boolean(value) as Config.ISystem["networkServe"];- fetchPost("/api/system/setNetworkServe", {networkServe}, () => {+ configApi.set("system.networkServe", networkServe, () => {/// #if MOBILEvoid exitSiYuan();/// #else@@ -47,7 +47,7 @@ export const sendAppSetting = (controlId: string, value: unknown) => {}case "system.networkServeTLS": {const networkServeTLS = Boolean(value) as Config.ISystem["networkServeTLS"];- fetchPost("/api/system/setNetworkServeTLS", {networkServeTLS}, () => {+ configApi.set("system.networkServeTLS", networkServeTLS, () => {/// #if MOBILEvoid exitSiYuan();/// #else@@ -61,21 +61,21 @@ export const sendAppSetting = (controlId: string, value: unknown) => {}case "system.downloadInstallPkg": {const downloadInstallPkg = Boolean(value) as Config.ISystem["downloadInstallPkg"];- fetchPost("/api/system/setDownloadInstallPkg", {downloadInstallPkg}, () => {+ configApi.set("system.downloadInstallPkg", downloadInstallPkg, () => {window.siyuan.config.system.downloadInstallPkg = downloadInstallPkg;});break;}case "system.updateChannel": {const updateChannel = value as Config.TUpdateChannel;- fetchPost("/api/system/setUpdateChannel", {updateChannel}, () => {+ configApi.set("system.updateChannel", updateChannel, () => {window.siyuan.config.system.updateChannel = updateChannel;});break;}case "system.settingsWindow": {const settingsWindow = Boolean(value) as Config.ISystem["settingsWindow"];- fetchPost("/api/system/setSettingsWindow", {settingsWindow}, () => {+ configApi.set("system.settingsWindow", settingsWindow, () => {window.siyuan.config.system.settingsWindow = settingsWindow;});break;diff --git a/app/src/config/tabs/appTab.ts b/app/src/config/tabs/appTab.tsindex 8cfdb7fa7d..dc74e3857d 100644--- a/app/src/config/tabs/appTab.ts+++ b/app/src/config/tabs/appTab.ts@@ -1,3 +1,4 @@+import {config as configApi} from "../util/configApi";/// #if !BROWSERimport {ipcRenderer} from "electron";import * as path from "path";@@ -387,7 +388,7 @@ const mountNetworkProxy = (root: HTMLElement) => {const scheme = schemeElement.value as Config.TSystemNetworkProxyScheme;const host = hostElement.value;const port = portElement.value;- fetchPost("/api/system/setNetworkProxy", {scheme, host, port}, async () => {+ configApi.set("system.networkProxy", {scheme, host, port}, async () => {Object.assign(window.siyuan.config.system.networkProxy, {scheme, host, port});/// #if !BROWSERipcRenderer.invoke(Constants.SIYUAN_GET, {diff --git a/app/src/config/tabs/appearanceRuntime.test.ts b/app/src/config/tabs/appearanceRuntime.test.tsindex 329255374b..148a69d8fa 100644--- a/app/src/config/tabs/appearanceRuntime.test.ts+++ b/app/src/config/tabs/appearanceRuntime.test.ts@@ -4,6 +4,7 @@ import {resolve} from "node:path";import {test} from "node:test";import {runInNewContext} from "node:vm";import {ModuleKind, transpileModule} from "typescript";+import {createSectionRuntime} from "../util/sectionRuntime";const {parse} = require("ifdef-loader/preprocessor");@@ -32,6 +33,7 @@ for (const mobile of [true, false]) {window: {siyuan},document: {getElementById: (): HTMLElement | null => null},require: (name: string) => {+ if (name === "../util/sectionRuntime") return {createSectionRuntime};if (name === "../util/namespaceApi") {return {createConfigNamespaceApi: (options: {setConfig: (data: unknown) => void}) => ({apply: options.setConfig})};}@@ -79,6 +81,7 @@ for (const mobile of [true, false]) {window: {siyuan, location: {reload: () => calls.push("reload")}},document: {getElementById: (): HTMLElement | null => null},require: (name: string) => {+ if (name === "../util/sectionRuntime") return {createSectionRuntime};if (name === "../util/namespaceApi") {return {createConfigNamespaceApi: () => ({})};}diff --git a/app/src/config/tabs/appearanceRuntime.ts b/app/src/config/tabs/appearanceRuntime.tsindex 56490f5fdb..cb6a6fa60d 100644--- a/app/src/config/tabs/appearanceRuntime.ts+++ b/app/src/config/tabs/appearanceRuntime.ts@@ -1,3 +1,4 @@+import {config as configApi} from "../util/configApi";/// #if MOBILEimport {saveScroll} from "../../protyle/scroll/saveScroll";/// #else@@ -5,7 +6,6 @@ import {adjustDockPadding} from "../../layout/dock/util";import {reloadUI as reloadDesktopUI} from "../../layout/util";import {syncHideToolbarLayout, updateBarModeIcon} from "../../layout/topBar";/// #endif-import {fetchPost} from "../../util/fetch";import {enqueueAppearanceUpdate,invalidateAppearancePackages,@@ -20,6 +20,7 @@ import {getFrontend} from "../../util/functions";import {getCurrentThemeName, isCurrentThemeSupported, shouldUnloadThemeScript} from "../../util/themeCompatibility";import {remountOpenSettingTab} from "../setting/mount";import {createConfigNamespaceApi} from "../util/namespaceApi";+import {createSectionRuntime} from "../util/sectionRuntime";import {syncBodyGradient} from "./bodyGradient";import {refreshDynamicIcons} from "../../emoji/dynamicIcon";import {closeSettingsWindow, isSettingsWindow} from "../setting/windowContext";@@ -31,10 +32,10 @@ export const appearanceThemeModeValue = (): number =>/** 主题模式选择:合并 mode / modeOS 后提交 */export const saveThemeMode = (value: number) => {const OSThemeMode = window.matchMedia("(prefers-color-scheme: dark)").matches ? 1 : 0;- fetchPost("/api/setting/patch", {appearance: {+ configApi.set("appearance", {mode: (value === 2 ? OSThemeMode : value) as Config.IAppearance["mode"],modeOS: value === 2,- }});+ });};/// #if MOBILE@@ -95,30 +96,37 @@ const applyAppearanceConfig = async (data: Config.IAppearance, refresh?: IAppearreturn;}- window.siyuan.config.appearance = data;-- document.getElementById("status")?.classList.toggle("fn__none", data.hideStatusBar);- /// #if !MOBILE- if (!isSettingsWindow() && data.hideStatusBar !== prevAppearance.hideStatusBar) {- adjustDockPadding();- }- if (!isSettingsWindow() && data.hideToolbar !== prevAppearance.hideToolbar) {- syncHideToolbarLayout();- }- if (!isSettingsWindow()) {- updateBarModeIcon();- }- /// #endif-- await loadAssets(data);- if (JSON.stringify(data.globalFontFamilies) !== JSON.stringify(prevAppearance.globalFontFamilies)) {- await setInlineStyle();- refreshHeadingNumberMeasurements();- refreshDynamicIcons();- }- /// #if !MOBILE- void remountOpenSettingTab("appearance");- /// #endif+ await createSectionRuntime<Config.IAppearance>({+ namespace: "appearance",+ get: () => prevAppearance,+ set: next => { window.siyuan.config.appearance = next; },+ reactions: [{+ name: "bars",+ changed: () => true,+ apply: (old, next) => {+ document.getElementById("status")?.classList.toggle("fn__none", next.hideStatusBar);+ /// #if !MOBILE+ if (!isSettingsWindow() && next.hideStatusBar !== old.hideStatusBar) adjustDockPadding();+ if (!isSettingsWindow() && next.hideToolbar !== old.hideToolbar) syncHideToolbarLayout();+ if (!isSettingsWindow()) updateBarModeIcon();+ /// #endif+ },+ }, {+ name: "appearance-resources",+ changed: () => true,+ apply: async (old, next) => {+ await loadAssets(next);+ if (JSON.stringify(next.globalFontFamilies) !== JSON.stringify(old.globalFontFamilies)) {+ await setInlineStyle();+ refreshHeadingNumberMeasurements();+ refreshDynamicIcons();+ }+ /// #if !MOBILE+ void remountOpenSettingTab("appearance");+ /// #endif+ },+ }],+ }).apply(data);};export const refreshAppearance = (data: IAppearanceRefresh) =>@@ -128,9 +136,6 @@ export const refreshAppearance = (data: IAppearanceRefresh) =>export const appearanceConfigApi = createConfigNamespaceApi<Config.IAppearance>({namespace: "appearance",getConfig: () => window.siyuan.config.appearance,- setConfig: (data) => {- void enqueueAppearanceUpdate(() => applyAppearanceConfig(data));- },- apiPath: "/api/setting/setAppearance",- applyFromResponse: false,+ setConfig: data => enqueueAppearanceUpdate(() => applyAppearanceConfig(data)),+});diff --git a/app/src/config/tabs/editorRuntime.ts b/app/src/config/tabs/editorRuntime.tsindex 344f7d1392..11443e13da 100644--- a/app/src/config/tabs/editorRuntime.ts+++ b/app/src/config/tabs/editorRuntime.ts@@ -4,6 +4,7 @@ import {refreshHeadingNumberMeasurements, setInlineStyle} from "../../util/assetimport {reloadProtyle} from "../../protyle/util/reload";import {resize} from "../../protyle/util/resize";import {createConfigNamespaceApi} from "../util/namespaceApi";+import {createSectionRuntime} from "../util/sectionRuntime";import {shouldResetBottomBacklinkPanel} from "./editorRuntimeState";import {objEquals} from "../../util/functions";import {lineNumberRender} from "../../protyle/render/highlightRender";@@ -11,76 +12,73 @@ import {lineNumberRender} from "../../protyle/render/highlightRender";import {setTitleAutoDirection} from "../../protyle/render/autoDirection";/// #endif-const applyEditorConfig = (data: Config.IEditor) => {- const refreshKeepLoadedContent = window.siyuan.config.editor.keepLoadedContent !== data.keepLoadedContent;- const refreshDatabaseRowLayout = window.siyuan.config.editor.fullWidth !== data.fullWidth;- const resetBottomBacklinkPanel = shouldResetBottomBacklinkPanel(window.siyuan.config.editor, data);- const refreshHeadingNumbers = window.siyuan.config.editor.headingNumber !== data.headingNumber ||- window.siyuan.config.editor.headingNumberFormat !== data.headingNumberFormat;- const remeasureHeadingNumbers = window.siyuan.config.editor.fontSize !== data.fontSize ||- !objEquals(window.siyuan.config.editor.fontFamilies, data.fontFamilies);- const refreshCodeLineNumbers = !objEquals(window.siyuan.config.editor.codeFontFamilies, data.codeFontFamilies);- window.siyuan.config.editor = data;- /// #if MOBILE- setTitleAutoDirection(document.getElementById("toolbarName"), data.autoDirection);- /// #endif- const models = getAllModels();- models.editor.forEach(item => item.updateBacklinkPanel(resetBottomBacklinkPanel));- if (refreshDatabaseRowLayout) {- models.custom.forEach(item => {- if (item.type === "siyuan-database-row") {- item.resize?.();- }- });- }- getAllEditor().forEach((editorItem) => {- const protyle = editorItem.protyle;- if (refreshKeepLoadedContent) {- protyle.scroll.keepLoadedContent = data.keepLoadedContent;- }- protyle.databaseAttributePanel?.updateDisplayConfig();- reloadProtyle(protyle, false);- let isFullWidth = protyle.wysiwyg.element.getAttribute(Constants.CUSTOM_SY_FULLWIDTH);- if (!isFullWidth) {- isFullWidth = window.siyuan.config.editor.fullWidth ? "true" : "false";- }- if (isFullWidth === "true" && protyle.contentElement.getAttribute("data-fullwidth") === "true") {- return;- }- resize(protyle);- if (isFullWidth === "true") {- protyle.contentElement.setAttribute("data-fullwidth", "true");- protyle.preview.element.setAttribute("data-fullwidth", "true");- } else {- protyle.contentElement.removeAttribute("data-fullwidth");- protyle.preview.element.removeAttribute("data-fullwidth");- }- });- if (refreshHeadingNumbers) {- /// #if MOBILE- window.siyuan.mobile.docks.outline?.reload();- /// #else- models.outline.forEach(item => item.refresh());- /// #endif- }-- void setInlineStyle().then(() => {- if (remeasureHeadingNumbers) {- refreshHeadingNumberMeasurements();- }- if (refreshCodeLineNumbers) {- getAllEditor().forEach((editorItem) => {- editorItem.protyle.wysiwyg.element.querySelectorAll(".code-block .protyle-linenumber__rows")- .forEach((rowsElement: HTMLElement) => lineNumberRender(rowsElement.parentElement));+const runtime = createSectionRuntime<Config.IEditor>({+ namespace: "editor",+ get: () => window.siyuan.config.editor,+ set: data => { window.siyuan.config.editor = data; },+ reactions: [{+ name: "backlink-panel",+ changed: () => true,+ apply: (old, next) => {+ getAllModels().editor.forEach(item => item.updateBacklinkPanel(shouldResetBottomBacklinkPanel(old, next)));+ },+ }, {+ name: "database-row-layout",+ changed: (old, next) => old.fullWidth !== next.fullWidth,+ apply: () => {+ getAllModels().custom.forEach(item => {+ if (item.type === "siyuan-database-row") item.resize?.();+ });+ },+ }, {+ name: "editor-layout",+ changed: () => true,+ apply: (old, next) => {+ /// #if MOBILE+ setTitleAutoDirection(document.getElementById("toolbarName"), next.autoDirection);+ /// #endif+ getAllEditor().forEach(({protyle}) => {+ if (old.keepLoadedContent !== next.keepLoadedContent) protyle.scroll.keepLoadedContent = next.keepLoadedContent;+ protyle.databaseAttributePanel?.updateDisplayConfig();+ reloadProtyle(protyle, false);+ const fullWidth = protyle.wysiwyg.element.getAttribute(Constants.CUSTOM_SY_FULLWIDTH) || String(next.fullWidth);+ if (fullWidth === "true" && protyle.contentElement.getAttribute("data-fullwidth") === "true") return;+ resize(protyle);+ for (const element of [protyle.contentElement, protyle.preview.element]) {+ if (fullWidth === "true") element.setAttribute("data-fullwidth", "true");+ else element.removeAttribute("data-fullwidth");+ }});- }- });-};+ },+ }, {+ name: "heading-numbers",+ changed: (old, next) => old.headingNumber !== next.headingNumber || old.headingNumberFormat !== next.headingNumberFormat,+ apply: () => {+ /// #if MOBILE+ window.siyuan.mobile.docks.outline?.reload();+ /// #else+ getAllModels().outline.forEach(item => item.refresh());+ /// #endif+ },+ }, {+ name: "editor-styles",+ changed: () => true,+ apply: async (old, next) => {+ await setInlineStyle();+ if (old.fontSize !== next.fontSize || !objEquals(old.fontFamilies, next.fontFamilies)) refreshHeadingNumberMeasurements();+ if (!objEquals(old.codeFontFamilies, next.codeFontFamilies)) {+ getAllEditor().forEach(({protyle}) => {+ protyle.wysiwyg.element.querySelectorAll(".code-block .protyle-linenumber__rows")+ .forEach((rowsElement: HTMLElement) => lineNumberRender(rowsElement.parentElement));+ });+ }+ },+ }],+});-/** 编辑器命名空间:设置面板注册项 save、设置面板外入口共用 */export const editorConfigApi = createConfigNamespaceApi<Config.IEditor>({namespace: "editor",getConfig: () => window.siyuan.config.editor,- setConfig: applyEditorConfig,- apiPath: "/api/setting/setEditor",+ setConfig: runtime.apply,+});diff --git a/app/src/config/tabs/exportRuntime.ts b/app/src/config/tabs/exportRuntime.tsindex 70bd19f887..7f4f692c25 100644--- a/app/src/config/tabs/exportRuntime.ts+++ b/app/src/config/tabs/exportRuntime.ts@@ -1,17 +1,12 @@import {createConfigNamespaceApi} from "../util/namespaceApi";-const applyExportConfig = (data: Config.IExport) => {- window.siyuan.config.export = data;- const pathDisplay = document.getElementById("pandocBinPathDisplay");- if (pathDisplay) {- pathDisplay.textContent = data.pandocBin || `${window.siyuan.languages.builtIn} Pandoc`;- }-};-/** 导出 Tab 命名空间:设置面板注册项 save、stack 内按钮 bind */export const exportConfigApi = createConfigNamespaceApi<Config.IExport>({namespace: "export",getConfig: () => window.siyuan.config.export,- setConfig: applyExportConfig,- apiPath: "/api/setting/setExport",+ setConfig: data => { window.siyuan.config.export = data; },+ reactions: [{name: "pandoc-path", changed: () => true, apply: (_old, next) => {+ const pathDisplay = document.getElementById("pandocBinPathDisplay");+ if (pathDisplay) pathDisplay.textContent = next.pandocBin || `${window.siyuan.languages.builtIn} Pandoc`;+ }}],});diff --git a/app/src/config/tabs/fileRuntime.ts b/app/src/config/tabs/fileRuntime.tsindex b604738697..6199182a81 100644--- a/app/src/config/tabs/fileRuntime.ts+++ b/app/src/config/tabs/fileRuntime.ts@@ -7,5 +7,5 @@ export const fileConfigApi = createConfigNamespaceApi<Config.IFileTree>({setConfig: (data) => {window.siyuan.config.fileTree = data;},- apiPath: "/api/setting/setFiletree",+});diff --git a/app/src/config/tabs/flashcardRuntime.ts b/app/src/config/tabs/flashcardRuntime.tsindex 49ab6300f3..6ee17eeac0 100644--- a/app/src/config/tabs/flashcardRuntime.ts+++ b/app/src/config/tabs/flashcardRuntime.ts@@ -7,5 +7,5 @@ export const flashcardConfigApi = createConfigNamespaceApi<Config.IFlashCard>({setConfig: (data) => {window.siyuan.config.flashcard = data;},- apiPath: "/api/setting/setFlashcard",+});diff --git a/app/src/config/tabs/keymapUi.ts b/app/src/config/tabs/keymapUi.tsindex c5a1009165..65565a98b8 100644--- a/app/src/config/tabs/keymapUi.ts+++ b/app/src/config/tabs/keymapUi.ts@@ -1,9 +1,9 @@+import {config as configApi} from "../util/configApi";import {keymapPayload, keymapRowPatch} from "../keymapPayload";import {isMac, updateHotkeyTip} from "../../protyle/util/compatibility";import {matchHotKey} from "../../protyle/util/hotKey";import {Constants} from "../../constants";import {hideMessage, showMessage} from "../../dialog/message";-import {fetchSyncPost} from "../../util/fetch";import {reloadUI} from "../../layout/util";import {applyKeymap} from "./keymapRuntime";import {confirmDialog} from "../../dialog/confirmDialog";@@ -18,7 +18,6 @@ import {getKeymapBindings, getKeymapItem, setKeymapBindings, normalizeShortcutKeimport {genKeymapRowHtml, getRowBindings, renderRowBindings} from "./keymapRow";import {escapeHtml} from "../../util/escape";import {Menu} from "../../plugin/Menu";-import {refreshSettingConfig} from "../setting/sync";import {trackSettingSave} from "../setting/pending";import {getSettingsOwnerApp} from "../setting/windowContext";import type {App} from "../../index";@@ -65,13 +64,11 @@ const bindKeymapToolbar = (root: HTMLElement) => {keymapSaveQueue = trackSettingSave(keymapSaveQueue.then(async () => {try {const data = JSON.parse(JSON.stringify(Constants.SIYUAN_KEYMAP));- const response = await fetchSyncPost("/api/setting/setKeymap", {data: keymapPayload(data)});- if (response.code !== 0) {- throw new Error(response.msg);- }- savedKeymap = data;- applyKeymap(data);- void reloadUI();+ await configApi.set("keymap", keymapPayload(data), () => {+ savedKeymap = data;+ applyKeymap(data);+ void reloadUI();+ });} catch (error) {console.error("Could not reset shortcuts:", error);showMessage(window.siyuan.languages.keymapSaveFailed);@@ -738,15 +735,11 @@ const saveKeymapRow = (root: HTMLElement, row: HTMLElement, keys: string[], chanconst revision = ++keymapRevision;keymapSaveQueue = trackSettingSave(keymapSaveQueue.then(async () => {try {- const response = await fetchSyncPost("/api/setting/patch", {- keymap: keymapRowPatch(row.dataset.key.split(Constants.ZWSP), {- ...item, bindings: item.bindings ? {...item.bindings, priority: item.bindings.priority || null} : undefined,- }),- });- if (response.code !== 0) {- throw new Error(response.msg);- }- await refreshSettingConfig("keymap");+ let applied = false;+ await configApi.set("keymap", keymapRowPatch(row.dataset.key.split(Constants.ZWSP), {+ ...item, bindings: item.bindings ? {...item.bindings, priority: item.bindings.priority || null} : undefined,+ }), () => { applied = true; });+ if (!applied) throw new Error("Could not save shortcuts");savedKeymap = JSON.parse(JSON.stringify(window.siyuan.config.keymap));} catch (error) {console.error("Could not save shortcuts:", error);diff --git a/app/src/config/tabs/searchRuntime.ts b/app/src/config/tabs/searchRuntime.tsindex 32ca286797..86dbf84c67 100644--- a/app/src/config/tabs/searchRuntime.ts+++ b/app/src/config/tabs/searchRuntime.ts@@ -7,5 +7,5 @@ export const searchConfigApi = createConfigNamespaceApi<Config.ISearch>({setConfig: (data) => {window.siyuan.config.search = data;},- apiPath: "/api/setting/setSearch",+});diff --git a/app/src/config/tabs/secretsVariablesRuntime.ts b/app/src/config/tabs/secretsVariablesRuntime.tsindex 239aa99149..094a0740d9 100644--- a/app/src/config/tabs/secretsVariablesRuntime.ts+++ b/app/src/config/tabs/secretsVariablesRuntime.ts@@ -7,7 +7,7 @@ export const secretsConfigApi = createConfigNamespaceApi<Config.ISecrets>({setConfig: (data) => {window.siyuan.config.secrets = data;},- apiPath: "/api/setting/setSecrets",+});/** 变量库 Tab 命名空间:设置面板注册项 save */@@ -17,5 +17,5 @@ export const variablesConfigApi = createConfigNamespaceApi<Config.IVariables>({setConfig: (data) => {window.siyuan.config.variables = data;},- apiPath: "/api/setting/setVariables",+});diff --git a/app/src/config/tabs/syncRuntime.ts b/app/src/config/tabs/syncRuntime.tsindex 750b364928..0615760a8e 100644--- a/app/src/config/tabs/syncRuntime.ts+++ b/app/src/config/tabs/syncRuntime.ts@@ -1,4 +1,5 @@-import {fetchPost, fetchSyncPost} from "../../util/fetch";+import {config as configApi} from "../util/configApi";+import {fetchSyncPost} from "../../util/fetch";import {processSync, progressLoading} from "../../dialog/processSystem";import {confirmDialog} from "../../dialog/confirmDialog";import {updateAccountPanelVisibility} from "./accountUi";@@ -84,10 +85,7 @@ const setSyncAssetDownloadMode = async (mode: Config.ISync["assetDownloadMode"])messageId = showMessage(window.siyuan.languages.syncAssetDownloadModeUpdating, -1);}, 300);try {- const response = await fetchSyncPost("/api/sync/setSyncAssetDownloadMode", {mode});- if (response.code === 0 && (response.data.assetDownloadMode === 0 || response.data.assetDownloadMode === 1)) {- window.siyuan.config.sync.assetDownloadMode = response.data.assetDownloadMode;- }+ await configApi.set("sync.assetDownloadMode", mode);} catch (error) {console.warn("[config] failed to update asset download mode", error);showMessage(window.siyuan.languages.syncAssetDownloadModeFailed, 5000, "error");@@ -173,7 +171,7 @@ export const patchSyncConfig = (controlId: string, value: unknown) => {}case "sync.enabled": {const enabled = Boolean(value) as Config.ISync["enabled"];- fetchPost("/api/sync/setSyncEnable", {enabled}, () => {+ configApi.set("sync.enabled", enabled, () => {window.siyuan.config.sync.enabled = enabled;if (syncTabElement) {refreshLANSyncConfigItemVisibility(syncTabElement);@@ -185,14 +183,14 @@ export const patchSyncConfig = (controlId: string, value: unknown) => {}case "sync.generateConflictDoc": {const generateConflictDoc = Boolean(value) as Config.ISync["generateConflictDoc"];- fetchPost("/api/sync/setSyncGenerateConflictDoc", {enabled: generateConflictDoc}, () => {+ configApi.set("sync.generateConflictDoc", generateConflictDoc, () => {window.siyuan.config.sync.generateConflictDoc = generateConflictDoc;});break;}case "sync.mode": {const mode = value as Config.ISync["mode"];- fetchPost("/api/sync/setSyncMode", {mode}, () => {+ configApi.set("sync.mode", mode, () => {window.siyuan.config.sync.mode = mode;if (syncTabElement) {refreshSyncModeRelatedItems(syncTabElement);@@ -205,7 +203,7 @@ export const patchSyncConfig = (controlId: string, value: unknown) => {}case "sync.interval": {const interval = value as Config.ISync["interval"];- fetchPost("/api/sync/setSyncInterval", {interval}, () => {+ configApi.set("sync.interval", interval, () => {window.siyuan.config.sync.interval = interval;processSync();});@@ -213,7 +211,7 @@ export const patchSyncConfig = (controlId: string, value: unknown) => {}case "sync.perception": {const perception = Boolean(value) as Config.ISync["perception"];- fetchPost("/api/sync/setSyncPerception", {enabled: perception}, () => {+ configApi.set("sync.perception", perception, () => {window.siyuan.config.sync.perception = perception;processSync();});@@ -221,10 +219,7 @@ export const patchSyncConfig = (controlId: string, value: unknown) => {}case "sync.lan.enabled": {const enabled = Boolean(value) as Config.ISyncLAN["enabled"];- fetchPost("/api/sync/setSyncLAN", {- enabled,- maxConcurrentReqs: window.siyuan.config.sync.lan.maxConcurrentReqs,- }, () => {+ configApi.set("sync.lan.enabled", enabled, () => {window.siyuan.config.sync.lan.enabled = enabled;if (syncTabElement) {refreshLANSyncStatus(syncTabElement);@@ -235,14 +230,14 @@ export const patchSyncConfig = (controlId: string, value: unknown) => {case "repo.indexRetentionDays": {const indexRetentionDays = value as Config.IRepo["indexRetentionDays"];- fetchPost("/api/repo/setRepoIndexRetentionDays", {days: indexRetentionDays}, () => {+ configApi.set("repo.indexRetentionDays", indexRetentionDays, () => {window.siyuan.config.repo.indexRetentionDays = indexRetentionDays;});break;}case "repo.retentionIndexesDaily": {const retentionIndexesDaily = value as Config.IRepo["retentionIndexesDaily"];- fetchPost("/api/repo/setRetentionIndexesDaily", {indexes: retentionIndexesDaily}, () => {+ configApi.set("repo.retentionIndexesDaily", retentionIndexesDaily, () => {window.siyuan.config.repo.retentionIndexesDaily = retentionIndexesDaily;});break;diff --git a/app/src/config/tabs/syncUi.test.ts b/app/src/config/tabs/syncUi.test.tsindex d566775f45..0cdc296bb1 100644--- a/app/src/config/tabs/syncUi.test.ts+++ b/app/src/config/tabs/syncUi.test.ts@@ -74,6 +74,20 @@ const setup = (provider = 2, mobile = false) => {if (name === "../../dialog/confirmDialog") {return {confirmDialog: (_title: string, _text: string, confirm: () => void, cancel: () => void) => confirmations.push({confirm, cancel})};}+ if (name === "../util/configApi") {+ return {config: {set: (path: string, value: unknown, applied: () => void) => {+ const key = path.split(".")[1];+ return new Promise((resolve, reject) => requests.push({url: "/api/setting/patch", data: {sync: {[key]: value}}, resolve, reject}))+ .then((response: any) => {+ if (response.code === 0) {+ Object.assign(sync, response.data);+ applied();+ } else {+ throw new Error(response.msg);+ }+ });+ }}};+ }if (name === "../../util/fetch") {return {fetchSyncPost: (url: string, data: any) => new Promise((resolve, reject) => requests.push({url, data, resolve, reject}))};}@@ -102,11 +116,11 @@ for (const provider of [2, 3, 4]) {ui.click("save");ui.click("save");assert.equal(ui.requests.length, 1);- assert.equal(ui.requests[0].data[key].endpoint, "new.example.com");+ assert.equal(ui.requests[0].data.sync[key].endpoint, "new.example.com");assert.equal(ui.buttons.save.disabled, true);ui.close();assert.equal(ui.closed(), 0);- ui.requests[0].resolve({code: 0, data: {[key]: {...ui.requests[0].data[key], endpoint: "https://new.example.com"}}});+ ui.requests[0].resolve({code: 0, data: {[key]: {...ui.requests[0].data.sync[key], endpoint: "https://new.example.com"}}});await settle();assert.equal(ui.sync[key].endpoint, "https://new.example.com");assert.equal(ui.closed(), 1);@@ -166,7 +180,7 @@ test("failed saves keep drafts after panel replacement and allow retry", async (assert.equal(ui.status.textContent, "Not confirmed");assert.equal(ui.buttons.save.disabled, false);ui.click("save");- ui.requests[2].resolve({code: 0, data: {s3: ui.requests[2].data.s3}});+ ui.requests[2].resolve({code: 0, data: {s3: ui.requests[2].data.sync.s3}});await settle();assert.equal(ui.closed(), 1);});@@ -218,8 +232,8 @@ test("draft stays bound to the opened provider even if another window changes thui.sync.provider = 3;ui.inputs.endpoint.value = "changed.example.com";ui.click("save");- assert.equal(ui.requests[0].url, "/api/sync/setSyncProviderS3");- assert.equal(ui.requests[0].data.s3.endpoint, "changed.example.com");+ assert.equal(ui.requests[0].url, "/api/setting/patch");+ assert.equal(ui.requests[0].data.sync.s3.endpoint, "changed.example.com");});test("mobile uses the shared dialog and bucket warnings never submit the draft", () => {diff --git a/app/src/config/tabs/syncUi.ts b/app/src/config/tabs/syncUi.tsindex 717ad55051..a843c97a0e 100644--- a/app/src/config/tabs/syncUi.ts+++ b/app/src/config/tabs/syncUi.ts@@ -1,3 +1,4 @@+import {config as configApi} from "../util/configApi";import {showMessage} from "../../dialog/message";import {fetchPost, fetchSyncPost} from "../../util/fetch";import {ContractFormData} from "../../util/contractFormData";@@ -149,7 +150,7 @@ const SYNC_PROVIDER_DEFS: Record<Config.ISync["provider"], SyncProviderDef> = {isProviderConfigAllowed: isPaidUser,configKey: "s3",requiredFields: ["endpoint", "accessKey", "secretKey", "bucket", "region"],- api: "/api/sync/setSyncProviderS3",+getConfig: () => window.siyuan.config.sync.s3,genIntro: () => `<div class="b3-label b3-label--inner">${window.siyuan.languages.syncThirdPartyProviderS3Intro}@@ -181,7 +182,7 @@ const SYNC_PROVIDER_DEFS: Record<Config.ISync["provider"], SyncProviderDef> = {isProviderConfigAllowed: isPaidUser,configKey: "webdav",requiredFields: ["endpoint"],- api: "/api/sync/setSyncProviderWebDAV",+getConfig: () => window.siyuan.config.sync.webdav,genIntro: () => `<div class="b3-label b3-label--inner">${window.siyuan.languages.syncThirdPartyProviderWebDAVIntro}@@ -207,7 +208,7 @@ const SYNC_PROVIDER_DEFS: Record<Config.ISync["provider"], SyncProviderDef> = {isProviderConfigAllowed: isPaidUser,configKey: "local",requiredFields: ["endpoint"],- api: "/api/sync/setSyncProviderLocal",+getConfig: () => window.siyuan.config.sync.local,genIntro: () => `<div class="b3-label b3-label--inner"><div class="ft__error">@@ -509,16 +510,15 @@ const openSyncProviderConfigDialog = (root: Element) => {setPending(true);setError("");try {- const response = await fetchSyncPost(def.api, {[def.configKey]: readProviderConfigFields(configElement, template)});- if (response.code !== 0 || !response.data?.[def.configKey]) {- setError(response.msg || L.syncConfigSaveFailed);- return;- }- window.siyuan.config.sync[def.configKey] = response.data[def.configKey];- refresh();- destroy();- } catch {- setError(L.syncConfigSaveFailed);+ let saved = false;+ await configApi.set(`sync.${def.configKey}`, readProviderConfigFields(configElement, template), () => {+ saved = true;+ refresh();+ destroy();+ });+ if (!saved) setError(L.syncConfigSaveFailed);+ } catch (error) {+ setError(error?.message || L.syncConfigSaveFailed);} finally {setPending(false);}diff --git a/app/src/config/util/configApi.test.ts b/app/src/config/util/configApi.test.tsnew file mode 100644index 0000000000..8bd118eba1--- /dev/null+++ b/app/src/config/util/configApi.test.ts@@ -0,0 +1,71 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, transpileModule} from "typescript";+import {mergeRecordByDottedPath} from "./dotPath";++const fixture = () => {+ const memory = {editor: {fontSize: 16, markdown: {inlineMath: true}}, sync: {interval: 30}};+ const requests: Array<{body: any; resolve: (response: any) => void}> = [];+ const exports = {} as typeof import("./configApi");+ const source = transpileModule(readFileSync("src/config/util/configApi.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS},+ }).outputText;+ runInNewContext(source, {exports, window: {siyuan: {config: memory}}, structuredClone, require: (name: string) => {+ if (name === "../../util/fetch") return {fetchSyncPost: (_url: string, body: any) =>+ new Promise(resolve => requests.push({body, resolve}))};+ if (name === "./dotPath") return {mergeRecordByDottedPath};+ if (name === "../setting/pending") return {trackSettingSave: (operation: Promise<void>) => operation};+ if (name === "../setting/sync") return {refreshSettingConfigAfter: async (namespace: keyof typeof memory, save: () => Promise<boolean>) => {+ if (!await save()) return false;+ if (namespace === "editor") memory.editor.fontSize = 24;+ return true;+ }};+ throw new Error("unexpected module: " + name);+ }});+ return {memory, requests, config: exports.config};+};++const settle = () => new Promise<void>(resolve => setImmediate(resolve));++test("config.set queues a namespace, preserves submitted values and returns normalized memory", async () => {+ const f = fixture();+ const markdown = {inlineMath: false};+ let applied: unknown;+ const first = f.config.set("editor.fontSize", 200, data => { applied = data; });+ const second = f.config.set("editor.markdown", markdown);+ markdown.inlineMath = true;+ await settle();+ assert.equal(f.requests.length, 1);+ assert.equal(JSON.stringify(f.requests[0].body), '{"editor":{"fontSize":200}}');+ f.requests[0].resolve({code: 0});+ await first;+ assert.equal(applied, f.memory.editor);+ assert.equal(f.config.get("editor.fontSize"), 24);+ await settle();+ assert.equal(f.requests.length, 2);+ assert.equal(JSON.stringify(f.requests[1].body), '{"editor":{"markdown":{"inlineMath":false}}}');+ f.requests[1].resolve({code: 0});+ await second;+});++test("config.set allows independent namespaces and retries after a rejected save", async () => {+ const f = fixture();+ let applied = false;+ const failed = f.config.set("editor.fontSize", 20, () => { applied = true; });+ const retry = f.config.set("editor.fontSize", 24);+ const independent = f.config.set("sync.interval", 60);+ await settle();+ assert.equal(f.requests.length, 2);+ const rejection = assert.rejects(failed, /refused/);+ f.requests[0].resolve({code: -1, msg: "refused"});+ f.requests[1].resolve({code: 0});+ await rejection;+ await independent;+ assert.equal(applied, false);+ await settle();+ assert.equal(f.requests.length, 3);+ f.requests[2].resolve({code: 0});+ await retry;+});diff --git a/app/src/config/util/configApi.ts b/app/src/config/util/configApi.tsnew file mode 100644index 0000000000..fb725b4db2--- /dev/null+++ b/app/src/config/util/configApi.ts@@ -0,0 +1,77 @@+import {fetchSyncPost} from "../../util/fetch";+import {mergeRecordByDottedPath} from "./dotPath";+import {refreshSettingConfigAfter} from "../setting/sync";+import {trackSettingSave} from "../setting/pending";++const pending = new Map<string, Promise<void>>();++const get = <T>(path: string): T => {+ let value: unknown = window.siyuan.config;+ for (const key of path.split(".")) {+ if (!value || typeof value !== "object") {+ return undefined;+ }+ value = Reflect.get(value, key);+ }+ return value as T;+};++// 同一配置段按提交顺序保存,成功后通过统一刷新流程应用内核的规范化结果。+const set = (path: string, value: unknown, onApplied?: (data: unknown, response?: IWebSocketData) => void): Promise<void> => {+ value = structuredClone(value);+ const separator = path.indexOf(".");+ const namespace = separator === -1 ? path : path.slice(0, separator);+ const relativePath = separator === -1 ? "" : path.slice(separator + 1);+ const patch = relativePath ? mergeRecordByDottedPath({}, relativePath, value) : value;+ const operation = (pending.get(namespace) || Promise.resolve()).catch(() => {}).then(async () => {+ let response: IWebSocketData;+ const save = async () => {+ response = await submit(path, value, namespace, patch);+ if (response.code !== 0) {+ throw new Error(response.msg);+ }+ return true;+ };+ const changed = namespace === "graph" && window.siyuan.config.readonly ? await save() :+ await refreshSettingConfigAfter(["api", "oidc", "accessAuthCode"].includes(namespace) ? "system" : namespace, save);+ if (changed) {+ onApplied?.(get(namespace), response);+ }+ });+ pending.set(namespace, operation);+ void operation.finally(() => {+ if (pending.get(namespace) === operation) {+ pending.delete(namespace);+ }+ }).catch(() => {});+ const tracked = trackSettingSave(operation);+ void tracked.catch(() => {});+ return tracked;+};++// 凭据校验、全局状态和插件生命周期保留专用协议,但共用排队与刷新入口。+const submit = (path: string, value: unknown, namespace: string, patch: unknown): Promise<IWebSocketData> => {+ switch (path) {+ case "system.downloadInstallPkg":+ return fetchSyncPost("/api/system/setDownloadInstallPkg", {downloadInstallPkg: Boolean(value)});+ case "system.updateChannel":+ return fetchSyncPost("/api/system/setUpdateChannel", {updateChannel: value as Config.TUpdateChannel});+ case "api.token":+ return fetchSyncPost("/api/system/setAPIToken", {token: String(value)});+ case "accessAuthCode":+ return fetchSyncPost("/api/system/setAccessAuthCode", {accessAuthCode: String(value)});+ case "oidc":+ return fetchSyncPost("/api/system/setOIDC", value as Config.IOIDC);+ case "bazaar.petalDisabled":+ return fetchSyncPost("/api/setting/setBazaarPetalDisabled", {petalDisabled: Boolean(value)});+ // 关系图专用接口允许来宾与只读用户使用当前界面的临时偏好。+ case "graph.global":+ return fetchSyncPost("/api/graph/setGraphConf", {type: "global", conf: value as Config.IGraph["global"]});+ case "graph.local":+ return fetchSyncPost("/api/graph/setGraphConf", {type: "local", conf: value as Config.IGraph["local"]});+ default:+ return fetchSyncPost("/api/setting/patch", {[namespace]: patch});+ }+};++export const config = {get, set};diff --git a/app/src/config/util/configWriteCoverage.test.ts b/app/src/config/util/configWriteCoverage.test.tsnew file mode 100644index 0000000000..66b3907290--- /dev/null+++ b/app/src/config/util/configWriteCoverage.test.ts@@ -0,0 +1,26 @@+import * as assert from "node:assert/strict";+import {readdirSync, readFileSync} from "node:fs";+import {join, relative} from "node:path";+import {test} from "node:test";++// 独立资源、工作空间切换、布局和同步来源事务保留其专用协议。+const dedicated = new Set([+ "/api/setting/setBootAppearance", "/api/system/setWorkspaceDir", "/api/system/setUILayout",+ "/api/sync/setSyncProvider", "/api/repo/setSnapshotMemo",+]);++test("desktop and mobile configuration writes use the shared gateway", () => {+ const walk = (directory: string) => {+ for (const entry of readdirSync(directory, {withFileTypes: true})) {+ const path = join(directory, entry.name);+ if (entry.isDirectory()) { walk(path); continue; }+ if (!path.endsWith(".ts") || path.endsWith(".test.ts")) continue;+ const file = relative("src", path).replaceAll("\\", "/");+ if (file === "config/util/configApi.ts") continue;+ const source = readFileSync(path, "utf8");+ const writes = source.matchAll(/(?:fetchPost|fetchSyncPost)\(\s*"(\/api\/(?:setting\/(?:patch|set\w+)|system\/set\w+|sync\/set\w+|repo\/set\w+|asset\/setOCRConfig|graph\/setGraphConf))"/g);+ for (const write of writes) assert.ok(dedicated.has(write[1]), `${file} bypasses config.set through ${write[1]}`);+ }+ };+ walk("src");+});diff --git a/app/src/config/util/namespaceApi.ts b/app/src/config/util/namespaceApi.tsindex 6a306294e1..c7a7dcd3ab 100644--- a/app/src/config/util/namespaceApi.ts+++ b/app/src/config/util/namespaceApi.ts@@ -1,52 +1,23 @@-import {fetchPost, fetchSyncPost} from "../../util/fetch";-import {createNamespacePatchQueue} from "./namespacePatchQueue";-import {mergeRecordByDottedPath} from "./dotPath";-import {refreshSettingConfigAfter} from "../setting/sync";+import {config} from "./configApi";+import {createSectionRuntime, type Reaction} from "./sectionRuntime";export function createConfigNamespaceApi<TData>(options: {namespace: string;getConfig: () => TData;- setConfig: (data: TData) => void;- apiPath: string;- /** 为 true(默认)时 POST 成功后用响应数据 apply 本地 config;为 false 时依赖内核推送到各前端实例 */- applyFromResponse?: boolean;+ setConfig: (data: TData) => void | Promise<void>;+ reactions?: Reaction<TData>[];}): {- /**- * @param onApplied POST 成功后的回调,参数为接口返回的命名空间配置(与 `getConfig()` 同结构)。- * `applyFromResponse` 为 true 时,调用前已执行 `setConfig`;为 false 时本地 `getConfig()` 可能尚未同步。- */+ /** onApplied 在已确认配置与运行时动作应用完成后执行 */patch: (relOrFullId: string, value: unknown, onApplied?: (data: TData) => void) => Promise<void>;- apply: (data: TData) => void;+ apply: (data: TData) => void | Promise<void>;} {- const {namespace, getConfig, setConfig, apiPath, applyFromResponse = true} = options;- const submit = (payload: TData) => new Promise<TData | undefined>((resolve) => {- let completed = false;- void fetchPost(apiPath, payload, (response) => {- completed = true;- const data = response.data as TData;- if (applyFromResponse) {- // 当前修改设置之后内核不推送到所有前端实例,用响应数据更新本地 config- setConfig(data);- }- resolve(data);- }).finally(() => {- if (!completed) {- resolve(undefined);- }- });- });- const patch = createNamespacePatchQueue({namespace, getConfig, submit, submitPatch: async (path, value) => {- const changed = await refreshSettingConfigAfter(namespace, async () => {- const response = await fetchSyncPost("/api/setting/patch", {- [namespace]: mergeRecordByDottedPath({}, path, value),- });- return response.code === 0;- });- return changed ? getConfig() : undefined;- }});+ const {namespace} = options;+ const runtime = createSectionRuntime({namespace, get: options.getConfig, set: options.setConfig,+ reactions: options.reactions || []});return {- patch,- apply: setConfig,+ patch: (path, value, onApplied) => config.set(path.startsWith(`${namespace}.`) ? path : `${namespace}.${path}`,+ value, data => onApplied?.(data as TData)),+ apply: runtime.apply,};}diff --git a/app/src/config/util/sectionRuntime.test.ts b/app/src/config/util/sectionRuntime.test.tsnew file mode 100644index 0000000000..13c2631b98--- /dev/null+++ b/app/src/config/util/sectionRuntime.test.ts@@ -0,0 +1,27 @@+import * as assert from "node:assert/strict";+import {test} from "node:test";+import {createSectionRuntime} from "./sectionRuntime";++test("reactions compare coherent snapshots and finish asynchronous actions before resolving", async () => {+ let current = {font: 16, theme: "light"};+ const old = current;+ const events: string[] = [];+ let finish: () => void;+ const runtime = createSectionRuntime({namespace: "appearance", get: () => current, set: next => { current = next; },+ reactions: [{name: "font", changed: (before, after) => before.font !== after.font,+ apply: async (before, after) => {+ assert.equal(before, old);+ assert.equal(after, current);+ events.push("font");+ await new Promise<void>(resolve => { finish = resolve; });+ events.push("complete");+ }}, {name: "theme", changed: (before, after) => before.theme !== after.theme, apply: () => { events.push("theme"); }}],+ });+ const pending = runtime.apply({font: 24, theme: "light"});+ assert.deepEqual(events, ["font"]);+ finish();+ await pending;+ assert.deepEqual(events, ["font", "complete"]);+ await runtime.apply(current);+ assert.deepEqual(events, ["font", "complete"]);+});diff --git a/app/src/config/util/sectionRuntime.ts b/app/src/config/util/sectionRuntime.tsnew file mode 100644index 0000000000..d3d8d1f2a6--- /dev/null+++ b/app/src/config/util/sectionRuntime.ts@@ -0,0 +1,21 @@+export type Reaction<T> = {+ name: string;+ changed: (old: T, next: T) => boolean;+ apply: (old: T, next: T) => void | Promise<void>;+};++// 在替换配置前确定变更动作,动作始终接收同一组前后快照。+export const createSectionRuntime = <T>(options: {+ namespace: string;+ get: () => T;+ set: (data: T) => void | Promise<void>;+ reactions: Reaction<T>[];+}) => ({+ apply: (next: T) => {+ const old = options.get();+ const reactions = options.reactions.filter(reaction => reaction.changed(old, next));+ const applied = options.set(next);+ const applyReactions = () => Promise.all(reactions.map(reaction => reaction.apply(old, next))).then(() => {});+ return applied ? applied.then(applyReactions) : applyReactions();+ },+});diff --git a/app/src/config/util/snippets.save.test.ts b/app/src/config/util/snippets.save.test.tsindex e159baaa1f..98603d1359 100644--- a/app/src/config/util/snippets.save.test.ts+++ b/app/src/config/util/snippets.save.test.ts@@ -47,6 +47,10 @@ const browserCases = async (source: string) => {languages: {snippetConflict: "Keep your draft and reopen"},}});const dependencies = {+ config: {set: async (_path: string, value: Config.ISnippet) => {+ settingsWrites++;+ Object.assign(window.siyuan.config.snippet, value);+ }},Dialog: FakeDialog, isMobile: () => mobile,Constants: {DIALOG_SNIPPETS: "snippets"},objEquals: (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b),diff --git a/app/src/config/util/snippets.ts b/app/src/config/util/snippets.tsindex e76c1efbdf..26abfa879a 100644--- a/app/src/config/util/snippets.ts+++ b/app/src/config/util/snippets.ts@@ -1,3 +1,4 @@+import {config as configApi} from "./configApi";import {fetchPost, fetchSyncPost} from "../../util/fetch";import {Dialog} from "../../dialog";import {showMessage} from "../../dialog/message";@@ -314,9 +315,7 @@ const setSnippetPost = async (dialog: Dialog, snippets: ISnippet[], removeIds: sif (cssChanged) {refreshHeadingNumberMeasurements();}- window.siyuan.config.snippet.enabledCSS = settings.enabledCSS;- window.siyuan.config.snippet.enabledJS = settings.enabledJS;- fetchPost("/api/setting/setSnippet", window.siyuan.config.snippet);+ await configApi.set("snippet", settings);completedSnippetSaves.add(dialog);dialog.destroy({cancel: "true"});} catch (error) {diff --git a/app/src/emoji/index.ts b/app/src/emoji/index.tsindex 474e9a24e5..d8e24b3492 100644--- a/app/src/emoji/index.ts+++ b/app/src/emoji/index.ts@@ -1,3 +1,4 @@+import {config as configApi} from "../config/util/configApi";import {getRandom, isMobile} from "../util/functions";import {fetchPost} from "../util/fetch";import {ContractFormData} from "../util/contractFormData";@@ -813,7 +814,7 @@ export const addEmoji = (unicode: string) => {Constants.SIZE_UNDO,);- fetchPost("/api/setting/setEmoji", {emoji: window.siyuan.config.editor.emoji});+ configApi.set("editor.emoji", window.siyuan.config.editor.emoji);};const genWeekdayOptions = (lang: string, weekdayType: string) => {diff --git a/app/src/layout/dock/BacklinkContent.ts b/app/src/layout/dock/BacklinkContent.tsindex 2cb45bf367..0033f16a4c 100644--- a/app/src/layout/dock/BacklinkContent.ts+++ b/app/src/layout/dock/BacklinkContent.ts@@ -1,3 +1,4 @@+import {config as configApi} from "../../config/util/configApi";import {toggleMenu} from "../../menus/menuToggle";import {GlobalBacklinkList} from "./GlobalBacklinkList";import {bindPanelSearch} from "./panelSearch";@@ -796,8 +797,8 @@ export class BacklinkContent extends Model {} else {window.siyuan.config.editor.backmentionSort = sortValue;}- fetchPost("/api/setting/patch", {editor: type === "sort" ?- {backlinkSort: sortValue, backlinkGlobalSort: 0} : {backmentionSort: sortValue}});+ configApi.set("editor", type === "sort" ?+ {backlinkSort: sortValue, backlinkGlobalSort: 0} : {backmentionSort: sortValue});this.searchBacklinks();};window.siyuan.menus.menu.remove();@@ -889,7 +890,7 @@ export class BacklinkContent extends Model {click: () => {window.siyuan.config.editor.backlinkBlockSort = mode;window.siyuan.config.editor.backlinkGlobalSort = 0;- fetchPost("/api/setting/patch", {editor: {backlinkBlockSort: mode, backlinkGlobalSort: 0}});+ configApi.set("editor", {backlinkBlockSort: mode, backlinkGlobalSort: 0});this.cancelContextRequests(this.tree.element, false);if (this.globalList) {this.searchBacklinks(true);@@ -908,7 +909,7 @@ export class BacklinkContent extends Model {label, iconHTML: "", checked: globalSort === index + 1,click: () => {window.siyuan.config.editor.backlinkGlobalSort = index + 1;- fetchPost("/api/setting/patch", {editor: {backlinkGlobalSort: index + 1}});+ configApi.set("editor", {backlinkGlobalSort: index + 1});this.searchBacklinks();},}).element);diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.tsindex 8fd56b9eb6..035b402728 100644--- a/app/src/layout/dock/Files.ts+++ b/app/src/layout/dock/Files.ts@@ -1,3 +1,4 @@+import {config as configApi} from "../../config/util/configApi";import {escapeAriaLabel, escapeHtml, escapeLessThans, escapeHtmlTextAndAttr} from "../../util/escape";import {Tab} from "../Tab";import {Model} from "../Model";@@ -2255,17 +2256,7 @@ aria-label="${ariaLabel}">${getDocDisplayName(item.name, item.titleEmpty, true)}if (sort === null) {return;}- fetchPost("/api/setting/setFiletree", {- ...window.siyuan.config.fileTree,- sort,- }, (response) => {- if (response.code !== 0) {- return;- }- window.siyuan.config.fileTree = {- ...response.data,- tabStartupMode: response.data.tabStartupMode === 1 ? 1 : response.data.tabStartupMode === 2 ? 2 : 0,- };+ configApi.set("fileTree.sort", sort, () => {this.onDocSortModeChanged({scope: "global",box: "",diff --git a/app/src/layout/dock/Graph.ts b/app/src/layout/dock/Graph.tsindex 43b62ee972..ec78fcad76 100644--- a/app/src/layout/dock/Graph.ts+++ b/app/src/layout/dock/Graph.ts@@ -17,6 +17,7 @@ import {GraphEngine} from "./graph/GraphEngine";import {IGraphNodeClick, IGraphNodeContextMenu, IGraphSourceLink, IGraphSourceNode} from "./graph/types";import {openDocumentMenu} from "../../protyle/header/documentMenu";import {Constants} from "../../constants";+import {config as configApi} from "../../config/util/configApi";interface IGraphSearchOptions {id?: string;@@ -630,10 +631,7 @@ export class Graph extends Model {if (!this.pendingGraphConf) {return;}- fetchPost("/api/graph/setGraphConf", {- type: this.type === "global" ? "global" : "local",- conf: this.pendingGraphConf,- });+ void configApi.set(`graph.${this.type === "global" ? "global" : "local"}`, this.pendingGraphConf);this.pendingGraphConf = undefined;}diff --git a/app/src/mobile/dock/MobileFiles.ts b/app/src/mobile/dock/MobileFiles.tsindex b6f6ae133b..7a7b3baa38 100644--- a/app/src/mobile/dock/MobileFiles.ts+++ b/app/src/mobile/dock/MobileFiles.ts@@ -1,3 +1,4 @@+import {config as configApi} from "../../config/util/configApi";import {hasClosestByClassName, hasClosestByTag, hasTopClosestByTag} from "../../protyle/util/hasClosest";import {escapeHtml, escapeHtmlTextAndAttr} from "../../util/escape";import {getTreeItemTailHTML} from "../../util/treeItemTail";@@ -850,17 +851,7 @@ export class MobileFiles extends Model {if (sort === null) {return;}- fetchPost("/api/setting/setFiletree", {- ...window.siyuan.config.fileTree,- sort,- }, (response) => {- if (response.code !== 0) {- return;- }- window.siyuan.config.fileTree = {- ...response.data,- tabStartupMode: response.data.tabStartupMode === 1 ? 1 : response.data.tabStartupMode === 2 ? 2 : 0,- };+ configApi.set("fileTree.sort", sort, () => {this.onDocSortModeChanged({scope: "global",box: "",diff --git a/app/src/plugin/globalState.ts b/app/src/plugin/globalState.tsindex ee83eb8b9b..b6bf6a2711 100644--- a/app/src/plugin/globalState.ts+++ b/app/src/plugin/globalState.ts@@ -1,5 +1,5 @@+import {config as configApi} from "../config/util/configApi";import type {App} from "../index";-import {fetchSyncPost} from "../util/fetch";import {GlobalPluginStateCoordinator,type IGlobalPluginStatePayload,@@ -54,9 +54,10 @@ export const subscribeGlobalPluginState = (app: App, listener: (state: IGlobalPl(!isSettingsPluginApp(app) && getSettingsWindowHost()?.subscribePlugins(listener)) || getCoordinator(app).subscribe(listener);export const setGlobalPluginsDisabled = async (app: App, petalDisabled: boolean) => {- const response = await fetchSyncPost("/api/setting/setBazaarPetalDisabled", {petalDisabled});- if (response.code !== 0 || !response.data) {- throw new Error(response.msg || "Failed to update the global plugin state");- }- await applyPluginReload(app, response.data as TGlobalPluginReloadData);+ let applied: Promise<void>;+ await configApi.set("bazaar.petalDisabled", petalDisabled, (_, response) => {+ applied = applyPluginReload(app, response.data as TGlobalPluginReloadData);+ });+ if (!applied) throw new Error("Failed to update the global plugin state");+ await applied;};diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.tsindex f9e37f4450..637140f174 100644--- a/app/src/protyle/wysiwyg/keydown.ts+++ b/app/src/protyle/wysiwyg/keydown.ts@@ -1,3 +1,4 @@+import {config as configApi} from "../../config/util/configApi";import type {BlockQueryRequestInput} from "../../types/api";import {handleReadonlyAttributeHotkey} from "../util/attributeHotkey";import {isProtyleListItemFragment} from "../runtimeCapabilities";@@ -212,11 +213,11 @@ const showSelectAllTip = () => {selectAllTipShown = true;document.querySelector(`#message [data-id="${messageId}"] button`)?.addEventListener("click", () => {hideMessage(messageId);- fetchPost("/api/setting/patch", {appearance: {+ configApi.set("appearance", {notifications: {selectAllTip: false,}- }});+ });});};diff --git a/app/src/sync/syncGuide.test.ts b/app/src/sync/syncGuide.test.tsindex a0dd55917f..da4ce3ef48 100644--- a/app/src/sync/syncGuide.test.ts+++ b/app/src/sync/syncGuide.test.ts@@ -26,7 +26,7 @@ const loadSyncGuide = (mobile: boolean, provider: number) => {s3: {endpoint: "https://s3.example.com", accessKey: "test-key", secretKey: "test-secret",bucket: "notes.backup", region: "us-east-1"},};- const requests: {url: string, data: {name?: string}, reply: (response: ListResponse) => void}[] = [];+ const requests: {url: string, data: {name?: string; sync?: {cloudName: unknown}}, reply: (response: ListResponse) => void}[] = [];const moduleExports = {} as {renderSyncCloudList: (element: Element, reload: boolean, cb: (ready: boolean) => void) => void;bindSyncCloudListEvent: (element: Element, cb?: (ready: boolean) => void) => void;@@ -35,6 +35,14 @@ const loadSyncGuide = (mobile: boolean, provider: number) => {exports: moduleExports,window: {siyuan: {config: {sync}, languages: {emptyContent: "Empty", cloudConfigTip: "Configure storage"}}},require: (name: string) => {+ if (name === "../config/util/configApi") {+ return {config: {set: (_path: string, value: unknown, applied?: () => void) => {+ requests.push({url: "/api/setting/patch", data: {sync: {cloudName: value}}, reply: (response: ListResponse) => {+ if (response.code === 0) { sync.cloudName = String(value); applied?.(); }+ }});+ return Promise.resolve();+ }}};+ }if (name === "../util/fetch") {return {fetchPost: (url: string, data: {name?: string}, reply: (response: ListResponse) => void) => {requests.push({url, data, reply});@@ -117,8 +125,8 @@ for (const mobile of [false, true]) {assert.equal(guide.list.innerHTML.includes("data-type=\"addCloud\""), provider !== 3);assert.deepEqual(guide.readiness, [false, true]);guide.select();- assert.equal(guide.requests[1].url, "/api/sync/setCloudSyncDir");- assert.equal(guide.requests[1].data.name, "chosen");+ assert.equal(guide.requests[1].url, "/api/setting/patch");+ assert.equal(guide.requests[1].data.sync.cloudName, "chosen");guide.requests[1].reply({code: 0});assert.equal(guide.sync.cloudName, "chosen");assert.equal(guide.requests[2].url, "/api/sync/listCloudSyncDir");diff --git a/app/src/sync/syncGuide.ts b/app/src/sync/syncGuide.tsindex 3360184e04..0d1bf09baf 100644--- a/app/src/sync/syncGuide.ts+++ b/app/src/sync/syncGuide.ts@@ -1,3 +1,4 @@+import {config as configApi} from "../config/util/configApi";import {isPaidUser, needSubscribe} from "../util/needSubscribe";import {showMessage} from "../dialog/message";import {fetchPost} from "../util/fetch";@@ -66,7 +67,7 @@ export const bindSyncCloudListEvent = (cloudListElement: Element, cb?: (ready: bbreak;case "selectCloud":cloudListElement.innerHTML = '<img style="margin: 0 auto;display: block;width: 64px;height: 100%" src="/stage/loading-pure.svg">';- fetchPost("/api/sync/setCloudSyncDir", {name: target.getAttribute("data-name")}, () => {+ configApi.set("sync.cloudName", target.getAttribute("data-name"), () => {window.siyuan.config.sync.cloudName = target.getAttribute("data-name");renderSyncCloudList(cloudListElement, true, cb);});@@ -284,7 +285,7 @@ const setSync = (key?: string, dialog?: Dialog) => {renderSyncCloudList(contentElement, false, updateOpenSyncBtn);btnElement.addEventListener("click", () => {dialog.destroy();- fetchPost("/api/sync/setSyncEnable", {enabled: true}, () => {+ configApi.set("sync.enabled", true, () => {window.siyuan.config.sync.enabled = true;processSync();confirmDialog("🔄 " + window.siyuan.languages.syncConfGuide4, window.siyuan.languages.syncConfGuide5, () => {diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex ac01315b45..f8f1ffb5f4 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -1546,7 +1546,13 @@ export type PandocData = { "path": string; };export type PandocRequestInput = { "args": Array<string>; "dir"?: string | null; };-export type PatchSettingRequestInput = { "ai"?: SettingAIInput | null; "appearance"?: SettingAppearanceInput | null; "editor"?: SettingEditorInput | null; "export"?: SettingExportInput | null; "fileTree"?: SettingFileTreeInput | null; "flashcard"?: SettingFlashcardInput | null; "keymap"?: { [key: string]: JSONValue }; "search"?: SettingSearchInput | null; "secrets"?: SettingSecretsInput | null; "variables"?: SettingVariablesInput | null; };+export type PatchRepoSettingInput = { "indexRetentionDays"?: number | null; "retentionIndexesDaily"?: number | null; };++export type PatchSettingRequestInput = { "ai"?: SettingAIInput | null; "appearance"?: SettingAppearanceInput | null; "bazaar"?: SettingBazaarInput | null; "editor"?: SettingEditorInput | null; "export"?: SettingExportInput | null; "fileTree"?: SettingFileTreeInput | null; "flashcard"?: SettingFlashcardInput | null; "keymap"?: { [key: string]: JSONValue }; "ocr"?: SettingOCRInput | null; "publish"?: SettingPublishInput | null; "repo"?: PatchRepoSettingInput | null; "search"?: SettingSearchInput | null; "secrets"?: SettingSecretsInput | null; "snippet"?: SettingSnptInput | null; "sync"?: PatchSyncSettingInput | null; "system"?: PatchSystemSettingInput | null; "variables"?: SettingVariablesInput | null; };++export type PatchSyncSettingInput = { "assetDownloadMode"?: number | null; "cloudName"?: string | null; "enabled"?: boolean | null; "generateConflictDoc"?: boolean | null; "interval"?: number | null; "lan"?: SyncLANRequestInput | null; "local"?: SyncLocalInput | null; "mode"?: number | null; "perception"?: boolean | null; "s3"?: SyncS3Input | null; "webdav"?: SyncWebDAVInput | null; };++export type PatchSystemSettingInput = { "autoLaunch2"?: number | null; "encryptedNotebookFollowSystemLock"?: boolean | null; "lockScreenMode"?: number | null; "networkProxy"?: NetworkProxyInput | null; "networkServe"?: boolean | null; "networkServeTLS"?: boolean | null; "settingsWindow"?: boolean | null; };export type PerformSyncRequestInput = { "mobileSwitch"?: boolean | null; "upload"?: boolean; };@@ -1936,6 +1942,8 @@ export type SettingBasicAuthInput = { "accounts"?: Array<SettingBasicAuthAccountexport type SettingBazaar = { "petalDisabled": boolean; "trust": boolean; };+export type SettingBazaarInput = { "petalDisabled"?: boolean | null; "trust"?: boolean | null; };+export type SettingBodyGradient = { "dark": SettingBodyGradientColor; "light": SettingBodyGradientColor; "mode": string; };export type SettingBodyGradientColor = { "color": string; "opacity": number; };@@ -2020,6 +2028,8 @@ export type SettingImageGeneration = { "modelId": string; "outputFormat": stringexport type SettingImageGenerationInput = { "modelId"?: string | null; "outputFormat"?: string | null; "quality"?: string | null; "requestTimeout"?: number | null; "size"?: string | null; };+export type SettingIssue = { "field": string; "message": string; "severity": string; };+export type SettingKeymapRequestInput = { "data"?: { [key: string]: JSONValue } | null; };export type SettingLogin2faRequestInput = { "code": string; "token": string; };@@ -2048,6 +2058,8 @@ export type SettingOCR = { "aiModelId"?: string; "auto": boolean; "model": strinexport type SettingOCRInput = { "aiModelId"?: string | null; "auto": boolean; "model": string; "provider": string; "reasoningEffort"?: string | null; "thresholds"?: OCRThresholdsInput | null; };+export type SettingPatchData = { "issues": Array<SettingIssue> | null; };+export type SettingPetalDisabledData = { "dataChangePlugins": Array<string> | null; "globalPetalChanged": boolean; "globalPetalDisabled": boolean; "globalPetalEnabled": boolean; "globalPetalRevision": number; "reloadPlugins": Array<string> | null; "uninstallPlugins": Array<string> | null; "unloadPlugins": Array<string> | null; };export type SettingPetalDisabledRequestInput = { "petalDisabled": boolean; };@@ -2060,6 +2072,8 @@ export type SettingPublish = { "auth": SettingBasicAuth | null; "enable": booleaexport type SettingPublishData = { "port": number; "publish": SettingPublish | null; };+export type SettingPublishInput = { "auth"?: SettingBasicAuthInput | null; "enable"?: boolean | null; "port"?: number | null; };+export type SettingRerank = { "apiKey": string; "candidateCount": number; "enabled": boolean; "endpoint": string; "id": string; "name": string; "requestFormat": string; "timeout": number; };export type SettingRerankInput = { "apiKey"?: string | null; "candidateCount"?: number | null; "enabled"?: boolean | null; "endpoint"?: string | null; "id"?: string | null; "name"?: string | null; "requestFormat"?: string | null; "timeout"?: number | null; };@@ -2078,6 +2092,8 @@ export type SettingSecretsInput = { "items"?: Array<SettingSecretInput | null> |export type SettingSnpt = { "enabledCSS": boolean; "enabledJS": boolean; };+export type SettingSnptInput = { "enabledCSS"?: boolean | null; "enabledJS"?: boolean | null; };+export type SettingStatusBar = { "msgDataSyncDisabled": boolean; "msgTaskAssetDatabaseIndexCommitDisabled": boolean; "msgTaskDatabaseIndexCommitDisabled": boolean; "msgTaskHistoryDatabaseIndexCommitDisabled": boolean; "msgTaskHistoryGenerateFileDisabled": boolean; "version": number; };export type SettingStatusBarInput = { "msgDataSyncDisabled"?: boolean | null; "msgTaskAssetDatabaseIndexCommitDisabled"?: boolean | null; "msgTaskDatabaseIndexCommitDisabled"?: boolean | null; "msgTaskHistoryDatabaseIndexCommitDisabled"?: boolean | null; "msgTaskHistoryGenerateFileDisabled"?: boolean | null; "version"?: number | null; };@@ -6564,7 +6580,7 @@ export interface APIPOSTRoutes {*/"/api/setting/patch": {request: PatchSettingRequestInput;- response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ response: { "code": 0; "data": SettingPatchData | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null | SettingPatchData | null; "msg": string; };body: "json";/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];diff --git a/app/src/util/assets.ts b/app/src/util/assets.tsindex 2871225fcb..cc1142f67c 100644--- a/app/src/util/assets.ts+++ b/app/src/util/assets.ts@@ -1,3 +1,4 @@+import {config as configApi} from "../config/util/configApi";import {Constants} from "../constants";import {getBodyGradientImage} from "./bodyGradient";import {addScript} from "../protyle/util/addScript";@@ -6,11 +7,6 @@ import {addStyle} from "../protyle/util/addStyle";import {getAllEditor, getAllModels} from "../layout/getAll";import {invalidateHeadingNumberMeasurements} from "../protyle/util/headingNumberCore";import {renderHeadingNumbers} from "../protyle/util/headingNumber";-/// #if !MOBILE-import {reloadUI} from "../layout/util";-import {closeSettingsWindow} from "../config/setting/windowContext";-/// #endif-import {fetchPost} from "./fetch";import {isInAndroid,isInHarmony,@@ -28,7 +24,7 @@ import {getWorkspaceName} from "./processTitle";import {ensureSelectedCustomFonts, getExportCustomFontStyle} from "./customFont";import {getGlobalFontStyle} from "./globalFont";import {getEmojiFontStyle} from "./emojiFont";-import {isCurrentThemeSupported, shouldUnloadThemeScript} from "./themeCompatibility";+import {isCurrentThemeSupported} from "./themeCompatibility";import {getInlineStylesCSS,loadInlineStyles@@ -161,7 +157,7 @@ export const loadAssets = async (appearance: Config.IAppearance) => {(window.siyuan.config.appearance.mode === 1 && OSTheme === "light") ||(window.siyuan.config.appearance.mode === 0 && OSTheme === "dark"))) {- fetchPost("/api/system/setAppearanceMode", {mode: OSTheme === "light" ? 0 : 1});+ configApi.set("appearance.mode", OSTheme === "light" ? 0 : 1);window.siyuan.config.appearance.mode = (OSTheme === "light" ? 0 : 1);}if (previousThemeMode && previousThemeMode !== themeMode) {@@ -316,25 +312,7 @@ export const initAssets = (keepLoading = false) => {(window.siyuan.config.appearance.mode === 1 && OSTheme === "dark")) {return;}- fetchPost("/api/system/setAppearanceMode", {- mode: OSTheme === "light" ? 0 : 1- }, response => {- void enqueueAppearanceUpdate(async () => {- const nextAppearance = response.data.appearance as Config.IAppearance;- if (shouldUnloadThemeScript(window.siyuan.config.appearance, nextAppearance, getFrontend()) &&- !await unloadThemeScript()) {- markAppearanceReloadPending();- /// #if !MOBILE- if (!closeSettingsWindow()) void reloadUI();- /// #else- window.location.reload();- /// #endif- return;- }- window.siyuan.config.appearance = nextAppearance;- await loadAssets(nextAppearance);- });- });+ void configApi.set("appearance.mode", OSTheme === "light" ? 0 : 1);});};@@ -419,10 +397,10 @@ export const setMode = (modeElementValue: number) => {mode = 0;}}- fetchPost("/api/setting/patch", {appearance: {+ configApi.set("appearance", {mode,modeOS: modeElementValue === 2,- }});+ });/// #endif};diff --git a/app/tests/backlinkSort.test.js b/app/tests/backlinkSort.test.jsindex c0da877c1e..ea3138473f 100644--- a/app/tests/backlinkSort.test.js+++ b/app/tests/backlinkSort.test.js@@ -17,6 +17,10 @@ const createPanel = () => {runInNewContext(compiled, {exports,require: () => ({+ config: {set: (_path, value) => {+ requests.push({path: "/api/setting/patch", data: {editor: {...value}}});+ return Promise.resolve();+ }},Model: class {},MenuItem: class {constructor(options) { this.element = options; }diff --git a/app/tests/mobileBacklinks.test.js b/app/tests/mobileBacklinks.test.jsindex e64aaa8425..276d868901 100644--- a/app/tests/mobileBacklinks.test.js+++ b/app/tests/mobileBacklinks.test.js@@ -29,6 +29,8 @@ const runCases = async (sources) => {const requests = [];const tick = () => new Promise(resolve => setTimeout(resolve, 10));const stubs = {+ "config/util/configApi": {config: {set: (_path, value) => stubs["util/fetch"].fetchSyncPost("/api/setting/patch", {editor: value})}},+ "dialog/anchoredInput": {getAnchoredInputMask: () => null},"block/panelOwnership": {getDialogBlockPanel() {}, destroyDialogBlockPanels() {}},"editor/assetOpen": {normalizeAssetOpenConfig: value => value},"layout/dock/backlinkRefFilterMenu": {loadBacklinkRefFilterMenu: noop},diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.mdindex 5669a5bdbc..39ee41147a 100644--- a/docs/ENCRYPTED-NOTEBOOK.md+++ b/docs/ENCRYPTED-NOTEBOOK.md@@ -481,6 +481,8 @@ Native mobile save flows must call `AcquireExportFile` to obtain a lease contain### Archiving notebooks that cannot be unlocked+`keys/persisted-conf.json` contains the process's most recently generated persistence form of the notebook encryption configuration, captured before the synchronous configuration write. Archive creation reads this in-memory snapshot instead of reopening `conf/conf.json`; if no persistence form has been generated, it uses the current encryption configuration. The key name and recovery readers remain compatible with existing version 1 archives. Existing backup and password-migration candidates are retained and authenticated during recovery.+Encrypted notebook archives use the separate `siyuan-encrypted-notebooks` container, version 1. Existing document, asset, attribute-view, AAD, and key-envelope formats remain unchanged. Archives include the selected notebook directories, related local history, their files from local repository snapshots, and available global encryption configuration, key backups, and password-migration records. Deferred assets and missing local snapshot chunks must be completed before removal can be committed. File lists, sizes, and SHA-256 digests verify copying completeness, not ciphertext authentication or guaranteed recoverability.Archive preparation and removal confirmation are separate operations. Before confirmation is committed, source directories, history, key material, and remaining relevant snapshots are checked again; changes require a new archive. Starting a download in a browser or older mobile client does not establish that saving completed, so the user must explicitly confirm an independently saved copy. A persistent operation record moves selected source directories to `<workspace>/conf/notebook-archives/<operation ID>/removed/`, preserving the archive and original recovery material. Uncommitted moves are rolled back at startup without generating new deletion history. Partial removal preserves global keys, and removal propagates through normal data synchronization. Repository snapshots are not automatically deleted. Before retiring the old key configuration, encrypted recovery dependencies must be covered by complete archives, and versioned key material is preserved before clearing old key fields, including `HistoryKEKs`.diff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.mdindex 359be46372..18d3f12cb8 100644--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md@@ -481,6 +481,8 @@ assets 加密:### 无法解锁的笔记本归档+`keys/persisted-conf.json` 保存本进程最近一次生成的笔记本加密配置持久化形态,在同步写入配置文件前记录。创建归档读取该内存快照,不重新打开 `conf/conf.json`;尚未生成持久化形态时使用当前加密配置。键名与恢复读取器继续兼容已有第 1 版归档,原有备份和改密迁移候选材料仍被保留,并在恢复时认证。+加密笔记本归档使用独立容器 `siyuan-encrypted-notebooks` 第 1 版,不改变已有文档、资源、数据库定义、AAD 或密钥包络格式。归档包含所选笔记本的原始目录、关联本地历史、本地仓库快照中的对应文件,以及现存全局加密配置、密钥备份和改密迁移记录。按需资源和缺失的本地快照分块必须先补齐,失败时不提交移出。文件清单、大小和 SHA-256 摘要仅用于验证复制完整性,不表示密文已认证或材料必然可恢复。生成归档与确认移出分开执行。确认前复核源目录、历史、密钥材料和仍存在的相关快照;变化时要求重新归档。浏览器或旧版移动端发起下载不等于保存完成,用户必须明确确认已另行保存。提交通过持久化记录把所选源目录移动到 `<工作区>/conf/notebook-archives/<操作 ID>/removed/`,保留归档和原始恢复材料;未提交的移动在启动时回滚,不生成新的删除历史。部分移出不修改全局密钥,移出随正常数据同步传播。仓库快照不自动删除;结束旧密钥配置前,必须确认其加密恢复依赖已由完整归档覆盖,另存版本化密钥材料后再清空旧密钥字段,包括 `HistoryKEKs`。diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex 27b6fc5fc5..3ac6aef971 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -517,8 +517,8 @@ func AgentChat(ctx context.Context, client *util.AIClient, protocol, model, imagreturn}- if kernelModel.Conf.AI.MCP != nil {- mcpclient.EnsureMCPConnected(kernelModel.Conf.AI.MCP.Servers)+ if kernelModel.Conf.AI.Load().MCP != nil {+ mcpclient.EnsureMCPConnected(kernelModel.Conf.AI.Load().MCP.Servers)}select {case <-ctx.Done():@@ -537,7 +537,7 @@ func AgentChat(ctx context.Context, client *util.AIClient, protocol, model, imagrawUserMessage := userMessage// 变量(非敏感)在用户消息注入对话时解析,让 LLM 看到实际值;密钥不进上下文。// 在此统一解析一次,后续 checkpoint 与消息重建均使用解析后的值,保证全链路一致。- userMessage = kernelModel.Conf.Variables.Resolve(userMessage)+ userMessage = kernelModel.Conf.Variables.Load().Resolve(userMessage)capabilityContext := capabilityAccessContext{SessionID: sessionID,@@ -713,12 +713,12 @@ func AgentChat(ctx context.Context, client *util.AIClient, protocol, model, imag}}()- temperature := kernelModel.Conf.AI.Agent.Temperature+ temperature := kernelModel.Conf.AI.Load().Agent.Temperatureif temperature < 0 || 2 < temperature {temperature = 1.0}- maxCompletionTokens := max(kernelModel.Conf.AI.Agent.MaxCompletionTokens, 0)- maxRounds := kernelModel.Conf.AI.Agent.MaxToolCallRounds+ maxCompletionTokens := max(kernelModel.Conf.AI.Load().Agent.MaxCompletionTokens, 0)+ maxRounds := kernelModel.Conf.AI.Load().Agent.MaxToolCallRoundsmodelRound := 0toolCallRounds := 0overflowRetryPending := false@@ -2085,8 +2085,10 @@ func availableSkillsSegment(skills []util.SkillInfo) string {}func buildSystemPrompt(language string, capabilities *capabilitySet, instructions ...string) string {- if kernelModel.Conf != nil && kernelModel.Conf.Appearance != nil && kernelModel.Conf.Appearance.Lang != "" {- language = kernelModel.Conf.Appearance.Lang+ confAppearanceSnapshot := kernelModel.Conf.LoadAppearance()++ if kernelModel.Conf != nil && confAppearanceSnapshot != nil && confAppearanceSnapshot.Lang != "" {+ language = confAppearanceSnapshot.Lang}var sb strings.Builderdiff --git a/kernel/agent/anthropic_test.go b/kernel/agent/anthropic_test.goindex beea78fcb7..a9358da96c 100644--- a/kernel/agent/anthropic_test.go+++ b/kernel/agent/anthropic_test.go@@ -56,9 +56,9 @@ func TestAnthropicAgentToolHistoryRecovery(t *testing.T) {useTestDataDir(t)previous := kernelModel.ConfkernelModel.Conf = kernelModel.NewAppConf()- kernelModel.Conf.AI = kernelConf.NewAI()- kernelModel.Conf.AI.MCP = nil- kernelModel.Conf.Variables = kernelConf.NewVariables()+ kernelModel.Conf.AI.Store(kernelConf.NewAI())+ kernelModel.Conf.AI.Load().MCP = nil+ kernelModel.Conf.Variables.Store(kernelConf.NewVariables())t.Cleanup(func() { kernelModel.Conf = previous })const toolName = "test_anthropic_history"var executions atomic.Int32diff --git a/kernel/agent/assistant_context_test.go b/kernel/agent/assistant_context_test.goindex f1cc000917..391d898e89 100644--- a/kernel/agent/assistant_context_test.go+++ b/kernel/agent/assistant_context_test.go@@ -119,10 +119,10 @@ func TestAgentChatResponsesToolContextSurvivesCommit(t *testing.T) {useTestDataDir(t)originalConf := kernelModel.ConfkernelModel.Conf = kernelModel.NewAppConf()- kernelModel.Conf.AI = kernelConf.NewAI()- kernelModel.Conf.AI.MCP = nil- kernelModel.Conf.AI.Agent.MaxToolCallRounds = 2- kernelModel.Conf.Variables = kernelConf.NewVariables()+ kernelModel.Conf.AI.Store(kernelConf.NewAI())+ kernelModel.Conf.AI.Load().MCP = nil+ kernelModel.Conf.AI.Load().Agent.MaxToolCallRounds = 2+ kernelModel.Conf.Variables.Store(kernelConf.NewVariables())t.Cleanup(func() { kernelModel.Conf = originalConf })const (@@ -360,10 +360,10 @@ func TestAgentChatRestoresCompleteAssistantContextAfterCommit(t *testing.T) {useTestDataDir(t)originalConf := kernelModel.ConfkernelModel.Conf = kernelModel.NewAppConf()- kernelModel.Conf.AI = kernelConf.NewAI()- kernelModel.Conf.AI.MCP = nil- kernelModel.Conf.AI.Agent.MaxToolCallRounds = 2- kernelModel.Conf.Variables = kernelConf.NewVariables()+ kernelModel.Conf.AI.Store(kernelConf.NewAI())+ kernelModel.Conf.AI.Load().MCP = nil+ kernelModel.Conf.AI.Load().Agent.MaxToolCallRounds = 2+ kernelModel.Conf.Variables.Store(kernelConf.NewVariables())t.Cleanup(func() { kernelModel.Conf = originalConf })const (diff --git a/kernel/agent/attachments_test.go b/kernel/agent/attachments_test.goindex c29092fc77..a43d477b64 100644--- a/kernel/agent/attachments_test.go+++ b/kernel/agent/attachments_test.go@@ -617,10 +617,10 @@ func TestAgentChatSendsToolAttachmentToCurrentModel(t *testing.T) {useTestDataDir(t)originalConf := kernelModel.ConfkernelModel.Conf = kernelModel.NewAppConf()- kernelModel.Conf.AI = kernelConf.NewAI()- kernelModel.Conf.AI.MCP = nil- kernelModel.Conf.AI.Agent.MaxToolCallRounds = 1- kernelModel.Conf.Variables = kernelConf.NewVariables()+ kernelModel.Conf.AI.Store(kernelConf.NewAI())+ kernelModel.Conf.AI.Load().MCP = nil+ kernelModel.Conf.AI.Load().Agent.MaxToolCallRounds = 1+ kernelModel.Conf.Variables.Store(kernelConf.NewVariables())t.Cleanup(func() { kernelModel.Conf = originalConf })const toolName = "test_current_model_image"diff --git a/kernel/agent/capability.go b/kernel/agent/capability.goindex 8ac45512da..644f01027c 100644--- a/kernel/agent/capability.go+++ b/kernel/agent/capability.go@@ -74,10 +74,10 @@ type capabilityAuthorizer interface {type configCapabilityAuthorizer struct{}func (configCapabilityAuthorizer) Allows(id string, _ capabilityAccessContext) bool {- if kernelModel.Conf == nil || kernelModel.Conf.AI == nil || kernelModel.Conf.AI.Agent == nil {+ if kernelModel.Conf == nil || kernelModel.Conf.AI.Load() == nil || kernelModel.Conf.AI.Load().Agent == nil {return true}- return kernelModel.Conf.AI.Agent.CapabilityPolicy.Allows(id)+ return kernelModel.Conf.AI.Load().Agent.CapabilityPolicy.Allows(id)}var currentCapabilityAuthorizer capabilityAuthorizer = configCapabilityAuthorizer{}@@ -89,10 +89,10 @@ type capabilityApprover interface {type configCapabilityApprover struct{}func (configCapabilityApprover) Decision(id, action string, _ capabilityAccessContext) string {- if kernelModel.Conf == nil || kernelModel.Conf.AI == nil || kernelModel.Conf.AI.Agent == nil {+ if kernelModel.Conf == nil || kernelModel.Conf.AI.Load() == nil || kernelModel.Conf.AI.Load().Agent == nil {return conf.ApprovalDecisionRisk}- return kernelModel.Conf.AI.Agent.ApprovalPolicy.Decision(id, action)+ return kernelModel.Conf.AI.Load().Agent.ApprovalPolicy.Decision(id, action)}var currentCapabilityApprover capabilityApprover = configCapabilityApprover{}@@ -176,10 +176,10 @@ func capabilityOwnerAvailable(source, runtime, ownerID string) bool {if ownerID == "" {return true}- if kernelModel.Conf == nil || kernelModel.Conf.AI == nil || kernelModel.Conf.AI.MCP == nil {+ if kernelModel.Conf == nil || kernelModel.Conf.AI.Load() == nil || kernelModel.Conf.AI.Load().MCP == nil {return false}- for _, server := range kernelModel.Conf.AI.MCP.Servers {+ for _, server := range kernelModel.Conf.AI.Load().MCP.Servers {if server.ID == ownerID {return server.Enabled}diff --git a/kernel/agent/capability_test.go b/kernel/agent/capability_test.goindex b6433e9f2d..63e48a2582 100644--- a/kernel/agent/capability_test.go+++ b/kernel/agent/capability_test.go@@ -34,7 +34,7 @@ func TestFrontendCapabilityModelNamesAreStableAndDistinct(t *testing.T) {func TestContentCapabilitiesExposeSharedToolDescriptions(t *testing.T) {originalConf := kernelModel.ConfkernelModel.Conf = kernelModel.NewAppConf()- kernelModel.Conf.AI = conf.NewAI()+ kernelModel.Conf.AI.Store(conf.NewAI())t.Cleanup(func() { kernelModel.Conf = originalConf })for _, tc := range []struct {tool *tools.Tool@@ -45,7 +45,7 @@ func TestContentCapabilitiesExposeSharedToolDescriptions(t *testing.T) {} {t.Run(tc.tool.Name, func(t *testing.T) {id := tools.CapabilityIDForTool(tc.tool)- kernelModel.Conf.AI.Agent.CapabilityPolicy = &conf.CapabilityPolicy{+ kernelModel.Conf.AI.Load().Agent.CapabilityPolicy = &conf.CapabilityPolicy{Default: "deny", Overrides: map[string]string{id: "allow"},}set, err := buildCapabilitySet(nil, capabilityAccessContext{})@@ -70,7 +70,7 @@ func TestContentCapabilitiesExposeSharedToolDescriptions(t *testing.T) {if schema.Properties[tc.property].Description != tc.tool.InputSchema.Properties[tc.property].Description {t.Fatal("agent did not receive the shared content syntax")}- kernelModel.Conf.AI.Agent.CapabilityPolicy.Overrides[id] = "deny"+ kernelModel.Conf.AI.Load().Agent.CapabilityPolicy.Overrides[id] = "deny"set, err = buildCapabilitySet(nil, capabilityAccessContext{})if err != nil || len(set.definitions) != 0 {t.Fatalf("disabled content tool descriptions were still exposed: %v", err)@@ -86,8 +86,8 @@ func TestCapabilityPolicyControlsExposureAndExecution(t *testing.T) {originalConf := kernelModel.ConfkernelModel.Conf = kernelModel.NewAppConf()- kernelModel.Conf.AI = conf.NewAI()- kernelModel.Conf.AI.Agent.CapabilityPolicy = &conf.CapabilityPolicy{+ kernelModel.Conf.AI.Store(conf.NewAI())+ kernelModel.Conf.AI.Load().Agent.CapabilityPolicy = &conf.CapabilityPolicy{Default: "deny",Overrides: map[string]string{backendID: "allow",@@ -128,7 +128,7 @@ func TestCapabilityPolicyControlsExposureAndExecution(t *testing.T) {if frontendRegistration == nil {t.Fatal("allowed browser capability was not exposed")}- kernelModel.Conf.AI.Agent.ApprovalPolicy.Overrides[backendID] = &conf.CapabilityApproval{+ kernelModel.Conf.AI.Load().Agent.ApprovalPolicy.Overrides[backendID] = &conf.CapabilityApproval{Default: "allow",Actions: map[string]string{"write": "confirm"},}@@ -142,8 +142,8 @@ func TestCapabilityPolicyControlsExposureAndExecution(t *testing.T) {t.Fatal("explicit confirmation was bypassed by the session approval mode")}- kernelModel.Conf.AI.Agent.CapabilityPolicy.Overrides[backendID] = "deny"- kernelModel.Conf.AI.Agent.CapabilityPolicy.Overrides[frontendID] = "deny"+ kernelModel.Conf.AI.Load().Agent.CapabilityPolicy.Overrides[backendID] = "deny"+ kernelModel.Conf.AI.Load().Agent.CapabilityPolicy.Overrides[frontendID] = "deny"if capabilityStillExecutable(backendRegistration, nil) || capabilityStillExecutable(frontendRegistration, nil) {t.Fatal("disabled capability remained executable from an earlier model round")}@@ -163,7 +163,7 @@ func TestMCPCapabilityRequiresEnabledConfiguredServer(t *testing.T) {originalConf := kernelModel.ConfkernelModel.Conf = kernelModel.NewAppConf()- kernelModel.Conf.AI = conf.NewAI()+ kernelModel.Conf.AI.Store(conf.NewAI())t.Cleanup(func() { kernelModel.Conf = originalConf })tool := &tools.Tool{@@ -191,7 +191,7 @@ func TestMCPCapabilityRequiresEnabledConfiguredServer(t *testing.T) {t.Fatal("MCP capability without a configured server was exposed")}- kernelModel.Conf.AI.MCP.Servers = []conf.MCPServer{{ID: serverID, Enabled: true}}+ kernelModel.Conf.AI.Load().MCP.Servers = []conf.MCPServer{{ID: serverID, Enabled: true}}set, err = buildCapabilitySet(nil, capabilityAccessContext{})if err != nil {t.Fatal(err)@@ -201,7 +201,7 @@ func TestMCPCapabilityRequiresEnabledConfiguredServer(t *testing.T) {t.Fatal("MCP capability for an enabled configured server was unavailable")}- kernelModel.Conf.AI.MCP.Servers[0].Enabled = false+ kernelModel.Conf.AI.Load().MCP.Servers[0].Enabled = falseif capabilityStillExecutable(registration, nil) {t.Fatal("MCP capability remained executable after its server was disabled")}@@ -217,7 +217,7 @@ func TestMCPCapabilityRequiresEnabledConfiguredServer(t *testing.T) {func TestExplicitCapabilityConfirmationOverridesRiskAndSessionApproval(t *testing.T) {originalConf := kernelModel.ConfkernelModel.Conf = kernelModel.NewAppConf()- kernelModel.Conf.AI = conf.NewAI()+ kernelModel.Conf.AI.Store(conf.NewAI())t.Cleanup(func() { kernelModel.Conf = originalConf })registration := &capabilityRegistration{@@ -238,7 +238,7 @@ func TestExplicitCapabilityConfirmationOverridesRiskAndSessionApproval(t *testint.Fatal("session approval did not bypass risk-based confirmation")}- kernelModel.Conf.AI.Agent.ApprovalPolicy.Overrides[registration.ID] = &conf.CapabilityApproval{+ kernelModel.Conf.AI.Load().Agent.ApprovalPolicy.Overrides[registration.ID] = &conf.CapabilityApproval{Default: conf.ApprovalDecisionConfirm,Actions: map[string]string{"semantic": conf.ApprovalDecisionAllow},}diff --git a/kernel/agent/compaction_context_test.go b/kernel/agent/compaction_context_test.goindex 807140ecfe..b86c64ebe1 100644--- a/kernel/agent/compaction_context_test.go+++ b/kernel/agent/compaction_context_test.go@@ -188,7 +188,7 @@ func testAgentChatCompactsCurrentTurnWithoutLosingRecovery(t *testing.T, withVarrawGoal := "complete the whole task"if withVariables {rawGoal = "complete $WORKSPACE task"- kernelModel.Conf.Variables.Items = []*conf.Variable{{Name: "WORKSPACE", Value: "the whole"}}+ kernelModel.Conf.Variables.Load().Items = []*conf.Variable{{Name: "WORKSPACE", Value: "the whole"}}}const toolName = "test_current_turn_compaction"var executions atomic.Int32@@ -205,7 +205,7 @@ func testAgentChatCompactsCurrentTurnWithoutLosingRecovery(t *testing.T, withVart.Fatal(err)}t.Cleanup(func() { tools.RemoveTool(toolName) })- kernelModel.Conf.AI.Agent.CapabilityPolicy = &conf.CapabilityPolicy{Default: "deny", Overrides: map[string]string{tools.CapabilityIDForTool(tool): "allow"}}+ kernelModel.Conf.AI.Load().Agent.CapabilityPolicy = &conf.CapabilityPolicy{Default: "deny", Overrides: map[string]string{tools.CapabilityIDForTool(tool): "allow"}}if _, _, err := SaveSessionState(marshalSession(t, map[string]any{"id": testSessionID, "title": "long task", "entries": []SessionEntry{{ID: "user", Type: "user", Content: rawGoal}}})); err != nil {t.Fatal(err)}@@ -394,7 +394,7 @@ func TestAgentChatReusesOnlyCompatibleCompaction(t *testing.T) {for _, name := range []string{"legacy", "same-scope", "other-model", "other-provider"} {t.Run(name, func(t *testing.T) {setupCompactionAgentTest(t)- kernelModel.Conf.AI.Agent.CapabilityPolicy = &conf.CapabilityPolicy{Default: "deny"}+ kernelModel.Conf.AI.Load().Agent.CapabilityPolicy = &conf.CapabilityPolicy{Default: "deny"}entries := []SessionEntry{{ID: "old-user", Type: "user", Content: "old task"},{ID: "old-answer", Type: "assistant", Content: strings.Repeat("old result ", 12000)},@@ -488,7 +488,7 @@ func testAgentChatNativeCompactsCurrentTurn(t *testing.T, failCompaction bool) {t.Fatal(err)}t.Cleanup(func() { tools.RemoveTool(toolName) })- kernelModel.Conf.AI.Agent.CapabilityPolicy = &conf.CapabilityPolicy{Default: "deny", Overrides: map[string]string{tools.CapabilityIDForTool(tool): "allow"}}+ kernelModel.Conf.AI.Load().Agent.CapabilityPolicy = &conf.CapabilityPolicy{Default: "deny", Overrides: map[string]string{tools.CapabilityIDForTool(tool): "allow"}}if _, _, err := SaveSessionState(marshalSession(t, map[string]any{"id": testSessionID, "title": "native task", "entries": []SessionEntry{{ID: "user", Type: "user", Content: "complete task"}}})); err != nil {t.Fatal(err)}@@ -570,7 +570,7 @@ func testAgentChatNativeCompactsCurrentTurn(t *testing.T, failCompaction bool) {func TestAgentChatCanceledCompactionKeepsCurrentTurn(t *testing.T) {setupCompactionAgentTest(t)- kernelModel.Conf.AI.Agent.CapabilityPolicy = &conf.CapabilityPolicy{Default: "deny"}+ kernelModel.Conf.AI.Load().Agent.CapabilityPolicy = &conf.CapabilityPolicy{Default: "deny"}result := strings.Repeat("completed operation result ", 6000)entries := []SessionEntry{{ID: "user", Type: "user", Content: "complete the task"},diff --git a/kernel/agent/compaction_test.go b/kernel/agent/compaction_test.goindex 8b6ba42d0d..5e227e95cf 100644--- a/kernel/agent/compaction_test.go+++ b/kernel/agent/compaction_test.go@@ -139,10 +139,10 @@ func setupCompactionAgentTest(t *testing.T) {useTestDataDir(t)originalConf := kernelModel.ConfkernelModel.Conf = kernelModel.NewAppConf()- kernelModel.Conf.AI = kernelConf.NewAI()- kernelModel.Conf.AI.MCP = nil- kernelModel.Conf.AI.Agent.MaxCompletionTokens = 512- kernelModel.Conf.Variables = kernelConf.NewVariables()+ kernelModel.Conf.AI.Store(kernelConf.NewAI())+ kernelModel.Conf.AI.Load().MCP = nil+ kernelModel.Conf.AI.Load().Agent.MaxCompletionTokens = 512+ kernelModel.Conf.Variables.Store(kernelConf.NewVariables())t.Cleanup(func() { kernelModel.Conf = originalConf })}diff --git a/kernel/agent/decision_test.go b/kernel/agent/decision_test.goindex b1c306c6ed..fb83186397 100644--- a/kernel/agent/decision_test.go+++ b/kernel/agent/decision_test.go@@ -12,7 +12,7 @@ import (func TestDecisionCapabilityAvailabilityAndApproval(t *testing.T) {original := kernelModel.ConfkernelModel.Conf = kernelModel.NewAppConf()- kernelModel.Conf.AI = conf.NewAI()+ kernelModel.Conf.AI.Store(conf.NewAI())t.Cleanup(func() { kernelModel.Conf = original })check := func(want bool) *capabilitySet {t.Helper()@@ -29,21 +29,21 @@ func TestDecisionCapabilityAvailabilityAndApproval(t *testing.T) {return set}check(false)- kernelModel.Conf.AI.Decision.Enabled = true+ kernelModel.Conf.AI.Load().Decision.Enabled = truecheck(false)- kernelModel.Conf.AI.Decision.Profiles["typesafe"].APIKey = "key"+ kernelModel.Conf.AI.Load().Decision.Profiles["typesafe"].APIKey = "key"set := check(true)registration := set.registration("decision")if required, _ := capabilityConfirmRequirement(registration, "evaluate", nil, false, nil); !tools.DecisionTool.AgentOnly || !required {t.Fatal("decision bypassed data egress/cost confirmation")}- kernelModel.Conf.AI.Decision.Enabled = false+ kernelModel.Conf.AI.Load().Decision.Enabled = falseif capabilityStillExecutable(registration, nil) {t.Fatal("disabled decision remained executable")}check(false)- kernelModel.Conf.AI.Decision.Enabled = true- kernelModel.Conf.AI.Agent.CapabilityPolicy.Overrides["native/backend/decision"] = "deny"+ kernelModel.Conf.AI.Load().Decision.Enabled = true+ kernelModel.Conf.AI.Load().Agent.CapabilityPolicy.Overrides["native/backend/decision"] = "deny"check(false)if capabilityStillExecutable(registration, nil) {t.Fatal("denied decision remained executable")diff --git a/kernel/agent/gemini_parallel_tools_test.go b/kernel/agent/gemini_parallel_tools_test.goindex 8939ebfb69..188db3e641 100644--- a/kernel/agent/gemini_parallel_tools_test.go+++ b/kernel/agent/gemini_parallel_tools_test.go@@ -38,10 +38,10 @@ func TestAgentChatPreservesUnindexedParallelGeminiToolCalls(t *testing.T) {useTestDataDir(t)originalConf := kernelModel.ConfkernelModel.Conf = kernelModel.NewAppConf()- kernelModel.Conf.AI = kernelConf.NewAI()- kernelModel.Conf.AI.MCP = nil- kernelModel.Conf.AI.Agent.MaxToolCallRounds = 1- kernelModel.Conf.Variables = kernelConf.NewVariables()+ kernelModel.Conf.AI.Store(kernelConf.NewAI())+ kernelModel.Conf.AI.Load().MCP = nil+ kernelModel.Conf.AI.Load().Agent.MaxToolCallRounds = 1+ kernelModel.Conf.Variables.Store(kernelConf.NewVariables())t.Cleanup(func() { kernelModel.Conf = originalConf })const (diff --git a/kernel/agent/instructions_test.go b/kernel/agent/instructions_test.goindex 259252582b..95876292b7 100644--- a/kernel/agent/instructions_test.go+++ b/kernel/agent/instructions_test.go@@ -21,7 +21,7 @@ import (func TestAgentInstructionsTurnSnapshot(t *testing.T) {setupCompactionAgentTest(t)- kernelModel.Conf.AI.Agent.MaxToolCallRounds = 1+ kernelModel.Conf.AI.Load().Agent.MaxToolCallRounds = 1initial, err := util.SaveAgentInstructions("original-workspace-preference", "missing")if err != nil {t.Fatal(err)diff --git a/kernel/agent/plugin_workflow_test.go b/kernel/agent/plugin_workflow_test.goindex 2de16b3b93..8e2c6f0a30 100644--- a/kernel/agent/plugin_workflow_test.go+++ b/kernel/agent/plugin_workflow_test.go@@ -34,9 +34,9 @@ func setupPluginWorkflow(t *testing.T) {t.Fatal(err)}kernelModel.Conf = kernelModel.NewAppConf()- kernelModel.Conf.AI = conf.NewAI()- kernelModel.Conf.Bazaar = conf.NewBazaar()- kernelModel.Conf.Bazaar.Trust = false+ kernelModel.Conf.AI.Store(conf.NewAI())+ kernelModel.Conf.Bazaar.Store(conf.NewBazaar())+ kernelModel.Conf.Bazaar.Load().Trust = falset.Cleanup(func() {util.WorkspaceDir, util.DataDir, util.ConfDir, util.WorkingDir, util.TempDir, kernelModel.Conf = origWorkspace, origData, origConfDir, origWorking, origTemp, origConfutil.ReadOnly = origReadOnly@@ -383,14 +383,14 @@ func TestPluginWorkflowTimeoutCancelDisableAndRestart(t *testing.T) {if _, err = pluginWorkflowGrant(testSessionID, "write"); err != nil {t.Fatalf("confirmed state did not survive reload: %v", err)}- kernelModel.Conf.AI.Agent.Skills.BuiltinDisabled = []string{util.BuiltinPluginSkillID}+ kernelModel.Conf.AI.Load().Agent.Skills.BuiltinDisabled = []string{util.BuiltinPluginSkillID}if _, err = pluginWorkflowGrant(testSessionID, "write"); err == nil {t.Fatal("disabled skill retained writes")}if got := pluginSkillResultForContext(AgentToolCall{Name: "skill", Arguments: map[string]any{"source": "builtin"}, Result: "private previous content"}); strings.Contains(got, "private previous") {t.Fatal("disabled skill was reinjected")}- kernelModel.Conf.AI.Agent.Skills.BuiltinDisabled = nil+ kernelModel.Conf.AI.Load().Agent.Skills.BuiltinDisabled = nilpausePluginWorkflow(testSessionID)if _, err = pluginWorkflowGrant(testSessionID, "write"); err == nil {t.Fatal("cancelled task retained writes")diff --git a/kernel/agent/prompt_test.go b/kernel/agent/prompt_test.goindex bda4bf758b..8babfb4b00 100644--- a/kernel/agent/prompt_test.go+++ b/kernel/agent/prompt_test.go@@ -131,8 +131,8 @@ func TestSystemPromptUsesAppearanceLanguage(t *testing.T) {originalConf := kernelModel.ConforiginalWorkingDir := util.WorkingDirkernelModel.Conf = kernelModel.NewAppConf()- kernelModel.Conf.Appearance = kernelConf.NewAppearance()- kernelModel.Conf.Appearance.Lang = "zh-CN"+ kernelModel.Conf.Appearance.Store(kernelConf.NewAppearance())+ kernelModel.Conf.Appearance.Load().Lang = "zh-CN"_, filename, _, _ := runtime.Caller(0)util.WorkingDir = filepath.Join(filepath.Dir(filename), "..", "..", "app")t.Cleanup(func() {diff --git a/kernel/agent/snippet_test.go b/kernel/agent/snippet_test.goindex 2810500f43..0e41bea5d1 100644--- a/kernel/agent/snippet_test.go+++ b/kernel/agent/snippet_test.go@@ -11,10 +11,10 @@ import (func TestSnippetWritesAlwaysRequireExplicitConfirmation(t *testing.T) {previous := kernelModel.ConfkernelModel.Conf = kernelModel.NewAppConf()- kernelModel.Conf.AI = conf.NewAI()+ kernelModel.Conf.AI.Store(conf.NewAI())t.Cleanup(func() { kernelModel.Conf = previous })registration := &capabilityRegistration{ID: "native/backend/snippet", ModelName: "snippet", Source: "native", Runtime: "kernel", Tool: tools.SnippetTool}- kernelModel.Conf.AI.Agent.ApprovalPolicy.Overrides[registration.ID] = &conf.CapabilityApproval{Default: conf.ApprovalDecisionAllow}+ kernelModel.Conf.AI.Load().Agent.ApprovalPolicy.Overrides[registration.ID] = &conf.CapabilityApproval{Default: conf.ApprovalDecisionAllow}for _, action := range []string{"create", "update", "replace", "enable", "disable", "remove"} {for _, session := range []bool{false, true} {required, forced := capabilityConfirmRequirement(registration, action, nil, session, map[string]bool{"*": true})diff --git a/kernel/agent/stream_timeout_test.go b/kernel/agent/stream_timeout_test.goindex 5c07730528..ebf4bdf171 100644--- a/kernel/agent/stream_timeout_test.go+++ b/kernel/agent/stream_timeout_test.go@@ -306,10 +306,10 @@ func TestAgentChatPartialStreamTimeoutSavesInterruptedWithoutRetry(t *testing.T)useTestDataDir(t)originalConf := kernelModel.ConfkernelModel.Conf = kernelModel.NewAppConf()- kernelModel.Conf.AI = kernelConf.NewAI()- kernelModel.Conf.AI.MCP = nil- kernelModel.Conf.AI.Agent.MaxToolCallRounds = 1- kernelModel.Conf.Variables = kernelConf.NewVariables()+ kernelModel.Conf.AI.Store(kernelConf.NewAI())+ kernelModel.Conf.AI.Load().MCP = nil+ kernelModel.Conf.AI.Load().Agent.MaxToolCallRounds = 1+ kernelModel.Conf.Variables.Store(kernelConf.NewVariables())t.Cleanup(func() {kernelModel.Conf = originalConf})diff --git a/kernel/agent/variables_test.go b/kernel/agent/variables_test.goindex 6edfff767e..a8bb7af876 100644--- a/kernel/agent/variables_test.go+++ b/kernel/agent/variables_test.go@@ -25,7 +25,7 @@ func TestAgentChatResolvesSavedUserVariables(t *testing.T) {} {t.Run(tc.name, func(t *testing.T) {setupCompactionAgentTest(t)- kernelModel.Conf.Variables.Items = []*kernelConf.Variable{{Name: "WORKSPACE", Value: "resolved workspace"}}+ kernelModel.Conf.Variables.Load().Items = []*kernelConf.Variable{{Name: "WORKSPACE", Value: "resolved workspace"}}const raw = "Inspect {{vars.WORKSPACE}} and $WORKSPACE"const resolved = "Inspect resolved workspace and resolved workspace"session := map[string]any{diff --git a/kernel/api/agent.go b/kernel/api/agent.goindex c1b4693fc8..b68945f9dd 100644--- a/kernel/api/agent.go+++ b/kernel/api/agent.go@@ -63,6 +63,8 @@ var runningSessions = map[string]*runningSession{}var agentChat = contractHandler(apicontract.AIAgentChat, agentChatContract, aiProviderAdmission)func agentChatContract(c *gin.Context, request apicontract.AIAgentChatRequest) apicontract.Response[apicontract.Null] {+ confAISnapshot := model.Conf.LoadAI()+req, err := aiAgentRequest(request)if err != nil {return apicontract.Failure[apicontract.Null](-1, err.Error())@@ -71,9 +73,9 @@ func agentChatContract(c *gin.Context, request apicontract.AIAgentChatRequest) avar selectedProvider *conf.Providervar selectedModel *conf.Modelif modelID != "" {- selectedProvider, selectedModel = model.Conf.AI.GetModel(modelID)+ selectedProvider, selectedModel = confAISnapshot.GetModel(modelID)} else {- selectedProvider, selectedModel = model.Conf.AI.GetAgentModel()+ selectedProvider, selectedModel = confAISnapshot.GetAgentModel()}if nil == selectedProvider || nil == selectedModel {ret := gulu.Ret.NewResult()@@ -83,8 +85,8 @@ func agentChatContract(c *gin.Context, request apicontract.AIAgentChatRequest) a}client := model.NewAIProviderClient(selectedProvider, selectedModel.Name)- confirmTimeout := resolveAgentConfirmTimeout(model.Conf.AI.Agent.ConfirmTimeout)- maxRetries := model.Conf.AI.Agent.MaxRetries+ confirmTimeout := resolveAgentConfirmTimeout(confAISnapshot.Agent.ConfirmTimeout)+ maxRetries := confAISnapshot.Agent.MaxRetriesif maxRetries < 0 {maxRetries = 0}@@ -94,7 +96,7 @@ func agentChatContract(c *gin.Context, request apicontract.AIAgentChatRequest) aif requestTimeout <= 0 {requestTimeout = 30 * time.Second}- streamIdleTimeout := time.Duration(model.Conf.AI.Agent.StreamIdleTimeout) * time.Second+ streamIdleTimeout := time.Duration(confAISnapshot.Agent.StreamIdleTimeout) * time.Secondif streamIdleTimeout <= 0 {streamIdleTimeout = 120 * time.Second}@@ -152,7 +154,7 @@ func agentChatContract(c *gin.Context, request apicontract.AIAgentChatRequest) areturn}- deadlineTimer, deadline := newAgentSessionDeadline(model.Conf.AI.Agent.SessionTimeout)+ deadlineTimer, deadline := newAgentSessionDeadline(model.Conf.AI.Load().Agent.SessionTimeout)if deadlineTimer != nil {defer deadlineTimer.Stop()}@@ -313,14 +315,15 @@ func lsCapabilitiesContract(c *gin.Context, req apicontract.EmptyRequest) apiconvar agentChatTitle = contractHandler(apicontract.AIAgentTitle, agentChatTitleContract)func agentChatTitleContract(c *gin.Context, req apicontract.AITitleRequest) apicontract.Response[string] {+ confAISnapshot := model.Conf.LoadAI()modelID := req.Modelvar selectedProvider *conf.Providervar selectedModel *conf.Modelif modelID != "" {- selectedProvider, selectedModel = model.Conf.AI.GetModel(modelID)+ selectedProvider, selectedModel = confAISnapshot.GetModel(modelID)} else {- selectedProvider, selectedModel = model.Conf.AI.GetAgentModel()+ selectedProvider, selectedModel = confAISnapshot.GetAgentModel()}if nil == selectedProvider || nil == selectedModel {ret := gulu.Ret.NewResult()diff --git a/kernel/api/ai.go b/kernel/api/ai.goindex dfe489fe9f..fb13768991 100644--- a/kernel/api/ai.go+++ b/kernel/api/ai.go@@ -83,7 +83,7 @@ func resolveAIProvider(request apicontract.AIProviderRequest) (*conf.Provider, e}providerID := request.Provider- for _, provider := range model.Conf.AI.Providers {+ for _, provider := range model.Conf.AI.Load().Providers {if provider != nil && provider.ID == providerID {return provider, nil}@@ -269,7 +269,7 @@ var testEmbeddingModel = contractHandler(apicontract.AITestEmbeddingModel, testEfunc testEmbeddingModelContract(c *gin.Context, req apicontract.EmptyRequest) apicontract.Response[apicontract.AIEmbeddingTestData] {- embedding := model.Conf.AI.Embedding+ embedding := model.Conf.AI.Load().Embeddingif nil == embedding || "" == embedding.APIKey || "" == embedding.BaseURL || "" == embedding.Name {// 配置不完整时统一以 code=0 返回,把信息放在 data 中由前端控制展示,// 避免返回 code=-1 触发统一错误提示且令前端按钮无法恢复@@ -295,7 +295,7 @@ var testRerankModel = contractHandler(apicontract.AITestRerankModel, testRerankMfunc testRerankModelContract(c *gin.Context, req apicontract.EmptyRequest) apicontract.Response[apicontract.AIRerankTestData] {- rerank := model.Conf.AI.Rerank+ rerank := model.Conf.AI.Load().Rerankif nil == rerank || "" == rerank.APIKey || "" == rerank.Endpoint || "" == rerank.Name {// 配置不完整时统一以 code=0 返回,把信息放在 data 中由前端控制展示,// 避免返回 code=-1 触发统一错误提示且令前端按钮无法恢复@@ -391,17 +391,19 @@ func mcpEnvironmentVariablesContract(c *gin.Context, req apicontract.EmptyRequesvar mcpOAuthAuthorize = contractHandler(apicontract.AIMCPOAuthAuthorize, mcpOAuthAuthorizeContract)func mcpOAuthAuthorizeContract(c *gin.Context, req apicontract.AIMCPIDRequest) apicontract.Response[apicontract.Null] {+ confAISnapshot := model.Conf.LoadAI()+ret := gulu.Ret.NewResult()serverID := req.ID- if model.Conf.AI == nil || model.Conf.AI.MCP == nil {+ if confAISnapshot == nil || confAISnapshot.MCP == nil {ret.Code = -1ret.Msg = "MCP server not found"return contractFailure[apicontract.Null](ret)}- for _, server := range model.Conf.AI.MCP.Servers {+ for _, server := range confAISnapshot.MCP.Servers {if server.ID == serverID && server.Enabled && server.Type == "http" {- mcpclient.ReconnectMCPAsync(model.Conf.AI.MCP.Servers, []string{serverID}, []string{serverID})+ mcpclient.ReconnectMCPAsync(confAISnapshot.MCP.Servers, []string{serverID}, []string{serverID})return contractFailure[apicontract.Null](ret)}}@@ -413,6 +415,8 @@ func mcpOAuthAuthorizeContract(c *gin.Context, req apicontract.AIMCPIDRequest) avar mcpOAuthDisconnect = contractHandler(apicontract.AIMCPOAuthDisconnect, mcpOAuthDisconnectContract)func mcpOAuthDisconnectContract(c *gin.Context, req apicontract.AIMCPIDRequest) apicontract.Response[apicontract.Null] {+ confAISnapshot := model.Conf.LoadAI()+ret := gulu.Ret.NewResult()serverID := req.ID@@ -420,8 +424,8 @@ func mcpOAuthDisconnectContract(c *gin.Context, req apicontract.AIMCPIDRequest)ret.Code = -1ret.Msg = err.Error()}- if model.Conf.AI != nil && model.Conf.AI.MCP != nil {- mcpclient.ReconnectMCPAsync(model.Conf.AI.MCP.Servers, []string{serverID}, nil)+ if confAISnapshot != nil && confAISnapshot.MCP != nil {+ mcpclient.ReconnectMCPAsync(confAISnapshot.MCP.Servers, []string{serverID}, nil)}return contractFailure[apicontract.Null](ret)}diff --git a/kernel/api/ai_contract.go b/kernel/api/ai_contract.goindex 18aba11343..a47eb5138b 100644--- a/kernel/api/ai_contract.go+++ b/kernel/api/ai_contract.go@@ -12,7 +12,7 @@ import ()func aiProviderAdmission(c *gin.Context) *apicontract.Response[apicontract.Null] {- if model.Conf.AI.HasAnyProvider() {+ if model.Conf.AI.Load().HasAnyProvider() {return nil}response := apicontract.Failure[apicontract.Null](-1, model.Conf.Language(193))diff --git a/kernel/api/ai_decision.go b/kernel/api/ai_decision.goindex c9a7a8a834..2f1b79bc88 100644--- a/kernel/api/ai_decision.go+++ b/kernel/api/ai_decision.go@@ -13,6 +13,8 @@ var testDecisionModel = contractHandler(apicontract.AITestDecisionModel, testDec// testDecisionModelContract 使用固定样例测试,不读取笔记或保存草稿。func testDecisionModelContract(c *gin.Context, request apicontract.AIDecisionTestRequest) apicontract.Response[apicontract.AIDecisionTestData] {+ confAISnapshot := model.Conf.LoadAI()+var decision *conf.Decisionif request.HasDraft() {if request.Provider == "" || request.Profile == nil {@@ -23,8 +25,8 @@ func testDecisionModelContract(c *gin.Context, request apicontract.AIDecisionTesdecision = &conf.Decision{Provider: request.Provider, Profiles: map[string]*conf.DecisionProfile{request.Provider: {Endpoint: profile.Endpoint, APIKey: profile.APIKey, Name: profile.Name, Timeout: profile.Timeout}}}} else {settingMutationMu.Lock()- if model.Conf.AI != nil {- decision = model.Conf.AI.Decision.Clone()+ if confAISnapshot != nil {+ decision = confAISnapshot.Decision.Clone()}settingMutationMu.Unlock()}diff --git a/kernel/api/ai_decision_test.go b/kernel/api/ai_decision_test.goindex 8daabebd5d..f505a45028 100644--- a/kernel/api/ai_decision_test.go+++ b/kernel/api/ai_decision_test.go@@ -31,8 +31,8 @@ func TestAPIContractAIDecisionConnection(t *testing.T) {}}))defer server.Close()- model.Conf.AI.Decision.Profiles["typesafe"].Endpoint = server.URL- model.Conf.AI.Decision.Profiles["typesafe"].APIKey = "test-key"+ model.Conf.AI.Load().Decision.Profiles["typesafe"].Endpoint = server.URL+ model.Conf.AI.Load().Decision.Profiles["typesafe"].APIKey = "test-key"engine := gin.New()engine.POST("/api/ai/testDecisionModel", testDecisionModel)bundle, err := apicontract.BuildBundle()@@ -56,7 +56,7 @@ func TestAPIContractAIDecisionConnection(t *testing.T) {t.Fatalf("incorrect connection result: %s", recorder.Body.String())}}- if model.Conf.AI.Decision.Enabled || calls.Load() != 2 {+ if model.Conf.AI.Load().Decision.Enabled || calls.Load() != 2 {t.Fatal("test requires enabled model or retries requests")}}@@ -72,7 +72,7 @@ func TestAPIContractAIDecisionDraftIsolation(t *testing.T) {io.WriteString(w, `{"answers":{}}`)}))defer server.Close()- saved := model.Conf.AI.Decision+ saved := model.Conf.AI.Load().Decisionsaved.Profiles["typesafe"].APIKey = "saved-secret"before, _ := json.Marshal(saved)engine := gin.New()@@ -92,7 +92,7 @@ func TestAPIContractAIDecisionDraftIsolation(t *testing.T) {t.Fatalf("incomplete draft fell back to saved configuration: %s", recorder.Body.String())}}- after, _ := json.Marshal(model.Conf.AI.Decision)+ after, _ := json.Marshal(model.Conf.AI.Load().Decision)if string(before) != string(after) || calls.Load() != 1 {t.Fatal("draft saved state or missing draft key borrowed saved key")}@@ -104,7 +104,7 @@ func TestAPIContractSettingDecisionLegacyProjection(t *testing.T) {"openai": {Endpoint: "https://openai.example", APIKey: "openai-key", Name: "openai", Timeout: 60},}}payload := settingDecisionPayload(decision)- system, err := systemConfPayload(&model.AppConf{AI: &conf.AI{Decision: decision}})+ system, err := systemConfPayload(&model.AppConf{AI: model.NewConfSection(&conf.AI{Decision: decision})})if err != nil || system.AI.Decision.APIKey != "typesafe-key" || system.AI.Decision.Provider != "openai" {t.Fatal("initial configuration lost legacy projection")}@@ -118,7 +118,7 @@ func TestAPIContractSettingDecisionPartialSave(t *testing.T) {previousReadOnly := util.ReadOnlyutil.ReadOnly = truet.Cleanup(func() { util.ReadOnly = previousReadOnly })- decision := model.Conf.AI.Decision+ decision := model.Conf.AI.Load().Decisiondecision.Provider = "openai"decision.Profiles["openai"].APIKey = "openai-key"decision.Profiles["typesafe"].APIKey = "typesafe-key"@@ -131,12 +131,12 @@ func TestAPIContractSettingDecisionPartialSave(t *testing.T) {if code != 0 {t.Fatalf("save failed: %s", message)}- current := model.Conf.AI.Decision+ current := model.Conf.AI.Load().Decisionif current.Provider != "openai" || current.Profiles["openai"].APIKey != "openai-key" {t.Fatal("partial save lost provider or unrelated credentials")}}- if model.Conf.AI.Decision.Profiles["typesafe"].APIKey != "new-key" {+ if model.Conf.AI.Load().Decision.Profiles["typesafe"].APIKey != "new-key" {t.Fatal("partial profile was not saved")}}@@ -146,7 +146,7 @@ func TestAPIContractSettingDecisionLegacyPatch(t *testing.T) {previousReadOnly := util.ReadOnlyutil.ReadOnly = truet.Cleanup(func() { util.ReadOnly = previousReadOnly })- decision := model.Conf.AI.Decision+ decision := model.Conf.AI.Load().Decisiondecision.Provider = "openai"decision.Profiles["openai"].APIKey = "openai-key"for _, body := range []string{@@ -158,13 +158,13 @@ func TestAPIContractSettingDecisionLegacyPatch(t *testing.T) {t.Fatalf("legacy patch failed: %s", message)}}- decision = model.Conf.AI.Decision+ decision = model.Conf.AI.Load().Decisionprofile := decision.Profiles["typesafe"]if decision.Provider != "openai" || decision.Profiles["openai"].APIKey != "openai-key" || profile.APIKey != "changed-typesafe-key" || profile.Endpoint != "https://typesafe.example/decision" || profile.Name != "changed-model" || profile.Timeout != 45 {t.Fatal("legacy patch was lost or changed the active provider")}code, message, _ := settingContractRequest(t, "patch", patchSetting, `{"ai":{"decision":{"apiKey":"stale-projection","profiles":{"typesafe":{"apiKey":"modern-key"}}}}}`)- if code != 0 || model.Conf.AI.Decision.Profiles["typesafe"].APIKey != "modern-key" {+ if code != 0 || model.Conf.AI.Load().Decision.Profiles["typesafe"].APIKey != "modern-key" {t.Fatalf("legacy projection overwrote modern patch: %s", message)}}diff --git a/kernel/api/asset_authorization_test.go b/kernel/api/asset_authorization_test.goindex f9c405bc7a..f36606fa94 100644--- a/kernel/api/asset_authorization_test.go+++ b/kernel/api/asset_authorization_test.go@@ -38,7 +38,7 @@ func TestInsertLocalAssetsWithoutBlockID(t *testing.T) {util.WorkspaceDir = workspaceDirutil.DataDir = filepath.Join(workspaceDir, "data")model.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())t.Cleanup(func() {model.Conf = originalConfutil.WorkspaceDir = originalWorkspaceDirdiff --git a/kernel/api/asset_download_authorization_test.go b/kernel/api/asset_download_authorization_test.goindex c589f0b418..f252a3622c 100644--- a/kernel/api/asset_download_authorization_test.go+++ b/kernel/api/asset_download_authorization_test.go@@ -37,12 +37,12 @@ func testDeferredAssetAPIAuthorizationAndMetadata(t *testing.T, symlinkWorkspaceoriginalConf := model.ConforiginalWorkspace, originalData, originalRepo := util.WorkspaceDir, util.DataDir, util.RepoDiroriginalHistory, originalTemp, originalConfDir := util.HistoryDir, util.TempDir, util.ConfDir- originalStatusBar := util.StatusBarCfg+ originalStatusBar := util.StatusBarCfg.Load()t.Cleanup(func() {model.Conf = originalConfutil.WorkspaceDir, util.DataDir, util.RepoDir = originalWorkspace, originalData, originalRepoutil.HistoryDir, util.TempDir, util.ConfDir = originalHistory, originalTemp, originalConfDir- util.StatusBarCfg = originalStatusBar+ util.StatusBarCfg.Store(originalStatusBar)})base := t.TempDir()if symlinkWorkspace {@@ -55,13 +55,22 @@ func testDeferredAssetAPIAuthorizationAndMetadata(t *testing.T, symlinkWorkspaceremote := filepath.Join(base, "cloud")key := []byte("0123456789abcdef0123456789abcdef")model.Conf = model.NewAppConf()- model.Conf.Sync, model.Conf.Repo, model.Conf.System = conf.NewSync(), conf.NewRepo(), conf.NewSystem()- model.Conf.Search, model.Conf.FileTree = conf.NewSearch(), conf.NewFileTree()- model.Conf.Sync.Provider, model.Conf.Sync.CloudName, model.Conf.Sync.Enabled = conf.ProviderLocal, "main", true- model.Conf.Sync.Local = &conf.Local{Endpoint: remote}- model.Conf.Sync.AssetDownloadMode, model.Conf.Repo.Key = 1, key+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewSync(), conf.NewRepo(), conf.NewSystem()+ model.Conf.Sync.Store(confSectionValue0)+ model.Conf.Repo.Store(confSectionValue1)+ model.Conf.System.Store(confSectionValue2)+ }+ {+ confSectionValue0, confSectionValue1 := conf.NewSearch(), conf.NewFileTree()+ model.Conf.Search.Store(confSectionValue0)+ model.Conf.FileTree.Store(confSectionValue1)+ }+ model.Conf.Sync.Load().Provider, model.Conf.Sync.Load().CloudName, model.Conf.Sync.Load().Enabled = conf.ProviderLocal, "main", true+ model.Conf.Sync.Load().Local = &conf.Local{Endpoint: remote}+ model.Conf.Sync.Load().AssetDownloadMode, model.Conf.Repo.Load().Key = 1, keymodel.Conf.SetUser(&conf.User{UserId: "asset-api-test", UserSiYuanOneTimePayStatus: 1})- util.StatusBarCfg = &util.StatusBar{MsgDataSyncDisabled: true}+ util.StatusBarCfg.Store(&util.StatusBar{MsgDataSyncDisabled: true})util.WorkspaceDir = filepath.Join(base, "partial")util.DataDir, util.RepoDir = filepath.Join(util.WorkspaceDir, "data"), filepath.Join(util.WorkspaceDir, "repo")util.HistoryDir, util.TempDir = filepath.Join(util.WorkspaceDir, "history"), filepath.Join(util.WorkspaceDir, "temp")@@ -248,7 +257,7 @@ func testDeferredAssetAPIAuthorizationAndMetadata(t *testing.T, symlinkWorkspaceif recorder.Code != http.StatusOK || !bytes.Equal(recorder.Body.Bytes(), files["assets/plain.bin"]) {t.Fatalf("authorized request failed to retrieve content: %d %s", recorder.Code, recorder.Body.String())}- model.Conf.Sync.Enabled = false+ model.Conf.Sync.Load().Enabled = falsemodel.Conf.SetUser(nil)recorder = request(model.RoleAdministrator, "/api/file/getFile", map[string]string{"path": "data/assets/plain.bin"})if recorder.Code != http.StatusOK || !bytes.Equal(recorder.Body.Bytes(), files["assets/plain.bin"]) {diff --git a/kernel/api/asset_html_paste_test.go b/kernel/api/asset_html_paste_test.goindex 6d912cdfc4..9a1f0f0a09 100644--- a/kernel/api/asset_html_paste_test.go+++ b/kernel/api/asset_html_paste_test.go@@ -24,7 +24,7 @@ func TestAPIContractHTMLLocalAssets(t *testing.T) {util.WorkspaceDir, util.HomeDir = t.TempDir(), t.TempDir()util.DataDir = filepath.Join(util.WorkspaceDir, "data")model.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())boxID := "20261002120000-htmlenc"t.Cleanup(func() {model.Conf, util.WorkspaceDir, util.DataDir, util.HomeDir = previousConf, previousWorkspace, previousData, previousHomediff --git a/kernel/api/asset_notification_test.go b/kernel/api/asset_notification_test.goindex 5cfdf546d4..499bd85914 100644--- a/kernel/api/asset_notification_test.go+++ b/kernel/api/asset_notification_test.go@@ -49,7 +49,7 @@ func testAPIContractUnusedNotificationScope(t *testing.T, attributeViews bool) {} {t.Run(test.name, func(t *testing.T) {assets := setupAssetContractWorkspace(t)- model.Conf.FileTree = conf.NewFileTree()+ model.Conf.FileTree.Store(conf.NewFileTree())if attributeViews {assets = filepath.Join(util.DataDir, "storage", "av")if err := os.MkdirAll(assets, 0755); err != nil {diff --git a/kernel/api/asset_rename_test.go b/kernel/api/asset_rename_test.goindex a1a48f2167..a41b4ca68f 100644--- a/kernel/api/asset_rename_test.go+++ b/kernel/api/asset_rename_test.go@@ -13,7 +13,7 @@ import (func TestRenameAssetMissingSourceContract(t *testing.T) {setupAssetContractWorkspace(t)- model.Conf.FileTree = conf.NewFileTree()+ model.Conf.FileTree.Store(conf.NewFileTree())engine := gin.New()engine.POST("/api/asset/renameAsset", renameAsset)recorder := httptest.NewRecorder()diff --git a/kernel/api/attr_test.go b/kernel/api/attr_test.goindex b643f2a00b..eab88a24c0 100644--- a/kernel/api/attr_test.go+++ b/kernel/api/attr_test.go@@ -49,7 +49,7 @@ func TestBlockAttrsRespectPublishAccess(t *testing.T) {previousDataDir := util.DataDirpreviousLangs := util.Langsmodel.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())util.DataDir = t.TempDir()util.BlockTreeDBPath = filepath.Join(util.DataDir, "blocktree.db")util.Langs = map[string]map[int]string{diff --git a/kernel/api/av_context_filter_test.go b/kernel/api/av_context_filter_test.goindex 21a3c34782..2797f1ce91 100644--- a/kernel/api/av_context_filter_test.go+++ b/kernel/api/av_context_filter_test.go@@ -207,8 +207,8 @@ func setupAttributeViewContextFilterAPITest(t *testing.T) *attributeViewContextF}model.Conf = model.NewAppConf()model.Conf.Lang = "en"- model.Conf.FileTree = conf.NewFileTree()- model.Conf.Sync = conf.NewSync()+ model.Conf.FileTree.Store(conf.NewFileTree())+ model.Conf.Sync.Store(conf.NewSync())cache.ClearAVCache()treenode.InitBlockTree(true)t.Cleanup(func() {diff --git a/kernel/api/backlink_ref_filter_test.go b/kernel/api/backlink_ref_filter_test.goindex bee3fefa37..46875cb8c3 100644--- a/kernel/api/backlink_ref_filter_test.go+++ b/kernel/api/backlink_ref_filter_test.go@@ -28,7 +28,7 @@ func TestParseBacklinkRefFilter(t *testing.T) {func TestPublishReaderBacklinkRefCandidates(t *testing.T) {oldConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.Editor = conf.NewEditor()+ model.Conf.Editor.Store(conf.NewEditor())t.Cleanup(func() { model.Conf = oldConf })gin.SetMode(gin.TestMode)engine := gin.New()diff --git a/kernel/api/bazaar.go b/kernel/api/bazaar.goindex 35086f5ebb..ba25e39765 100644--- a/kernel/api/bazaar.go+++ b/kernel/api/bazaar.go@@ -327,7 +327,7 @@ var installBazaarIcon = contractHandler(apicontract.InstallBazaarIcon, func(c *g}util.PushMsgWithApp(resolveRequestAppID(c, ""), model.Conf.Language(69), 3000)- data := apicontract.BazaarAppearancePackagesData{Packages: bazaarPackages(model.GetBazaarPackages("icons", "", request.Keyword)), Appearance: bazaarAppearance(model.Conf.Appearance)}+ data := apicontract.BazaarAppearancePackagesData{Packages: bazaarPackages(model.GetBazaarPackages("icons", "", request.Keyword)), Appearance: bazaarAppearance(model.Conf.Appearance.Load())}return apicontract.Success(data)})@@ -338,7 +338,7 @@ var uninstallBazaarIcon = contractHandler(apicontract.UninstallBazaarIcon, func(return apicontract.Failure[apicontract.BazaarAppearancePackagesData](-1, err.Error())}- data := apicontract.BazaarAppearancePackagesData{Packages: bazaarPackages(model.GetBazaarPackages("icons", "", request.Keyword)), Appearance: bazaarAppearance(model.Conf.Appearance)}+ data := apicontract.BazaarAppearancePackagesData{Packages: bazaarPackages(model.GetBazaarPackages("icons", "", request.Keyword)), Appearance: bazaarAppearance(model.Conf.Appearance.Load())}return apicontract.Success(data)})@@ -403,7 +403,7 @@ var installBazaarTheme = contractHandler(apicontract.InstallBazaarTheme, func(c}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)}+ data := apicontract.BazaarAppearancePackagesData{Packages: bazaarPackages(model.GetBazaarPackages("themes", request.Frontend, request.Keyword)), Appearance: bazaarAppearance(model.Conf.Appearance.Load())}return apicontract.Success(data)})@@ -414,7 +414,7 @@ var uninstallBazaarTheme = contractHandler(apicontract.UninstallBazaarTheme, funreturn apicontract.Failure[apicontract.BazaarAppearancePackagesData](-1, err.Error())}- data := apicontract.BazaarAppearancePackagesData{Packages: bazaarPackages(model.GetBazaarPackages("themes", request.Frontend, request.Keyword)), Appearance: bazaarAppearance(model.Conf.Appearance)}+ data := apicontract.BazaarAppearancePackagesData{Packages: bazaarPackages(model.GetBazaarPackages("themes", request.Frontend, request.Keyword)), Appearance: bazaarAppearance(model.Conf.Appearance.Load())}return apicontract.Success(data)})diff --git a/kernel/api/block_doc_info_publish_test.go b/kernel/api/block_doc_info_publish_test.goindex d6500f32b4..feb5fc13cf 100644--- a/kernel/api/block_doc_info_publish_test.go+++ b/kernel/api/block_doc_info_publish_test.go@@ -102,12 +102,12 @@ func TestGetDocInfoRefIDsPublishAccess(t *testing.T) {model.Conf = model.NewAppConf()model.Conf.Lang = "en"- model.Conf.FileTree = conf.NewFileTree()- model.Conf.Editor = conf.NewEditor()- model.Conf.Export = conf.NewExport()- model.Conf.Search = conf.NewSearch()+ model.Conf.FileTree.Store(conf.NewFileTree())+ model.Conf.Editor.Store(conf.NewEditor())+ model.Conf.Export.Store(conf.NewExport())+ model.Conf.Search.Store(conf.NewSearch())model.Conf.NotebookCrypto = conf.NewNotebookCrypto()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())const (boxID = "20260919000000-boxid01"diff --git a/kernel/api/block_test.go b/kernel/api/block_test.goindex 15d0b5ad76..d45bd6c083 100644--- a/kernel/api/block_test.go+++ b/kernel/api/block_test.go@@ -70,9 +70,18 @@ func testGetBlockInfoRecovery(t *testing.T, name string) {util.AssetContentDBPath = filepath.Join(root, "asset_content.db")util.BlockTreeDBPath = filepath.Join(root, "blocktree.db")model.Conf = model.NewAppConf()- model.Conf.FileTree, model.Conf.Sync = conf.NewFileTree(), conf.NewSync()+ {+ confSectionValue0, confSectionValue1 := conf.NewFileTree(), conf.NewSync()+ model.Conf.FileTree.Store(confSectionValue0)+ model.Conf.Sync.Store(confSectionValue1)+ }model.Conf.NotebookCrypto = conf.NewNotebookCrypto()- model.Conf.Search, model.Conf.Editor, model.Conf.Export = conf.NewSearch(), conf.NewEditor(), conf.NewExport()+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewSearch(), conf.NewEditor(), conf.NewExport()+ model.Conf.Search.Store(confSectionValue0)+ model.Conf.Editor.Store(confSectionValue1)+ model.Conf.Export.Store(confSectionValue2)+ }box := &model.Box{ID: ast.NewNodeID()}boxConf := conf.NewBoxConf()boxConf.Name, boxConf.Closed = "Recovery", false@@ -182,7 +191,7 @@ func TestCheckBlockRefRejectsDeletedIDsOutsideIDs(t *testing.T) {func TestFilterBlockAndRefIDsByPublishAccess(t *testing.T) {previousConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())t.Cleanup(func() { model.Conf = previousConf })const (boxID = "20260724000000-boxid01"@@ -255,7 +264,7 @@ func TestFilterBlockAndRefIDsByPublishAccess(t *testing.T) {func TestGetBlockInfoPublishAccess(t *testing.T) {previousConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())t.Cleanup(func() { model.Conf = previousConf })const (boxID = "20260806000020-box0020"@@ -372,7 +381,7 @@ type docBlocksOrdersResponse struct {func TestBlockPublishAccessGuards(t *testing.T) {previousConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())t.Cleanup(func() { model.Conf = previousConf })const (boxID = "20260724000000-boxid03"diff --git a/kernel/api/box_lease_test.go b/kernel/api/box_lease_test.goindex 1461b75342..e7477bb5a0 100644--- a/kernel/api/box_lease_test.go+++ b/kernel/api/box_lease_test.go@@ -199,8 +199,18 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {}}model.Conf = model.NewAppConf()- model.Conf.NotebookCrypto, model.Conf.Sync, model.Conf.FileTree = conf.NewNotebookCrypto(), conf.NewSync(), conf.NewFileTree()- model.Conf.Editor, model.Conf.Export, model.Conf.Search = conf.NewEditor(), conf.NewExport(), conf.NewSearch()+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewNotebookCrypto(), conf.NewSync(), conf.NewFileTree()+ model.Conf.NotebookCrypto = confSectionValue0+ model.Conf.Sync.Store(confSectionValue1)+ model.Conf.FileTree.Store(confSectionValue2)+ }+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewEditor(), conf.NewExport(), conf.NewSearch()+ model.Conf.Editor.Store(confSectionValue0)+ model.Conf.Export.Store(confSectionValue1)+ model.Conf.Search.Store(confSectionValue2)+ }if t.Name() == "TestContractDailyNoteNotebookResponseLease" || t.Name() == "TestContractDailyNoteInfoNotebookResponseLease" {content, err := os.ReadFile(filepath.Join("..", "..", "app", "appearance", "langs", "en.json"))if err != nil {@@ -215,7 +225,7 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {model.Conf.Lang = "en"util.TimeLangs = map[string]map[string]any{"en": language.Time}}- *model.Conf.FileTree.BoxDocEnabled = true+ *model.Conf.FileTree.Load().BoxDocEnabled = truesql.InitDatabase(true)sql.InitHistoryDatabase(true)sql.InitAssetContentDatabase(true)diff --git a/kernel/api/contract.go b/kernel/api/contract.goindex 1cb8071514..9cb4194965 100644--- a/kernel/api/contract.go+++ b/kernel/api/contract.go@@ -42,15 +42,19 @@ func notebookConfContract(value *conf.BoxConf) *apicontract.NotebookConf {// contractHandler 将请求绑定和响应类型与注册契约关联,业务入口继续使用现有中间件。func contractHandler[Request, Data any](endpoint apicontract.Endpoint[Request, Data],handler func(*gin.Context, Request) apicontract.Response[Data], beforeDecode ...func(*gin.Context) *apicontract.Response[Data]) gin.HandlerFunc {- if namespace := additionalSettingNamespace(endpoint.Definition().Path); namespace != "" {- handler = serializeSetting(namespace, handler)- }- if endpoint.Definition().Path == "/api/system/getConf" || settingsResetWritePath(endpoint.Definition().Path) {- read := handler+ // 写配置端点按契约声明串行化并通知;读取完整配置与写入共用互斥,保证读到已提交的配置+ if setting := endpoint.Definition().Setting; setting.Declared() && setting.Mode == apicontract.SettingNotify {+ handler = serializeSetting(setting.Namespace, handler)+ } else if setting.Declared() && setting.Mode == apicontract.SettingSilent || endpoint.Definition().Path == "/api/system/getConf" {+ serialized := handlerhandler = func(c *gin.Context, request Request) apicontract.Response[Data] {- settingMutationMu.Lock()- defer settingMutationMu.Unlock()- return read(c, request)+ namespace := setting.Namespace+ if namespace == "" {+ namespace = "*"+ }+ release := lockSetting(namespace)+ defer release()+ return serialized(c, request)}}return func(c *gin.Context) {@@ -136,18 +140,6 @@ func contractHandler[Request, Data any](endpoint apicontract.Endpoint[Request, D}}-// settingsResetWritePath 让重置事务与布局、本地偏好及关系图配置写入互斥,不改变这些接口的通知语义。-func settingsResetWritePath(path string) bool {- switch path {- case "/api/system/setUILayout", "/api/storage/setLocalStorage", "/api/storage/setLocalStorageVal",- "/api/storage/setLocalStorageVals", "/api/storage/removeLocalStorageVal", "/api/storage/removeLocalStorageVals",- "/api/setting/setBootAppearance", "/api/graph/setGraphConf", "/api/graph/resetGraph", "/api/graph/resetLocalGraph",- "/api/graph/getGraph", "/api/graph/getLocalGraph":- return true- }- return false-}-// contractFailure 保留既有业务校验的错误码和消息,并限制其错误载荷形态。func contractFailure[Data any](result *gulu.Result) apicontract.Response[Data] {switch data := result.Data.(type) {diff --git a/kernel/api/contract_agent_instructions_test.go b/kernel/api/contract_agent_instructions_test.goindex 515ab20dc9..edeb9d1799 100644--- a/kernel/api/contract_agent_instructions_test.go+++ b/kernel/api/contract_agent_instructions_test.go@@ -17,7 +17,7 @@ import (func TestAPIContractAIAgentInstructions(t *testing.T) {aiContractConfiguration(t)- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())engine := gin.New()engine.POST("/api/ai/agent/getInstructions", getAgentInstructions)engine.POST("/api/ai/agent/setInstructions", setAgentInstructions)diff --git a/kernel/api/contract_ai_test.go b/kernel/api/contract_ai_test.goindex ce15be39cc..681f789813 100644--- a/kernel/api/contract_ai_test.go+++ b/kernel/api/contract_ai_test.go@@ -24,9 +24,9 @@ func aiContractConfiguration(t *testing.T) {t.Helper()previous, dir := model.Conf, util.DataDirmodel.Conf = model.NewAppConf()- model.Conf.AI = conf.NewAI()- model.Conf.AI.Embedding = nil- model.Conf.AI.Rerank = nil+ model.Conf.AI.Store(conf.NewAI())+ model.Conf.AI.Load().Embedding = nil+ model.Conf.AI.Load().Rerank = nilutil.DataDir = t.TempDir()t.Cleanup(func() { model.Conf = previous; util.DataDir = dir })}@@ -41,7 +41,7 @@ func (body aiUnreadBody) Close() error { return nil }func TestAPIContractAIProviderAdmissionBeforeBody(t *testing.T) {aiContractConfiguration(t)- model.Conf.AI.Providers = nil+ model.Conf.AI.Load().Providers = nilengine := gin.New()engine.POST("/api/ai/editor/chat", aiEditorChat)engine.POST("/api/ai/agent/chat", agentChat)@@ -209,8 +209,8 @@ func TestAPIContractAIEditorSSE(t *testing.T) {fmt.Fprint(w, "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"hello\",\"reasoning_content\":\"reason\"},\"finish_reason\":\"length\"}]}\n\ndata: [DONE]\n\n")}))defer upstream.Close()- model.Conf.AI.Providers = []*conf.Provider{{ID: "provider", Enabled: true, BaseURL: upstream.URL + "/v1", Protocol: "openai", APIKey: "test", Models: []*conf.Model{{ID: "model", Name: "model", Enabled: true}}}}- model.Conf.AI.Editing.ModelID = "model"+ model.Conf.AI.Load().Providers = []*conf.Provider{{ID: "provider", Enabled: true, BaseURL: upstream.URL + "/v1", Protocol: "openai", APIKey: "test", Models: []*conf.Model{{ID: "model", Name: "model", Enabled: true}}}}+ model.Conf.AI.Load().Editing.ModelID = "model"engine := gin.New()engine.POST("/api/ai/editor/chat", aiEditorChat)recorder := httptest.NewRecorder()@@ -281,8 +281,8 @@ func TestAPIContractAIEditorStreamCancellation(t *testing.T) {close(closed)}))defer upstream.Close()- model.Conf.AI.Providers = []*conf.Provider{{ID: "provider", Enabled: true, BaseURL: upstream.URL + "/v1", Protocol: "openai", APIKey: "test", Models: []*conf.Model{{ID: "model", Name: "model", Enabled: true}}}}- model.Conf.AI.Editing.ModelID = "model"+ model.Conf.AI.Load().Providers = []*conf.Provider{{ID: "provider", Enabled: true, BaseURL: upstream.URL + "/v1", Protocol: "openai", APIKey: "test", Models: []*conf.Model{{ID: "model", Name: "model", Enabled: true}}}}+ model.Conf.AI.Load().Editing.ModelID = "model"engine := gin.New()engine.POST("/api/ai/editor/chat", aiEditorChat)server := httptest.NewServer(engine)diff --git a/kernel/api/contract_anthropic_test.go b/kernel/api/contract_anthropic_test.goindex 8df2291ca7..43fa3532b0 100644--- a/kernel/api/contract_anthropic_test.go+++ b/kernel/api/contract_anthropic_test.go@@ -55,8 +55,8 @@ func TestAPIContractAnthropicGenerationAndModels(t *testing.T) {provider := &conf.Provider{ID: "provider", Enabled: true, BaseURL: upstream.URL + "/v1",Protocol: util.AnthropicProtocolMessages, APIKey: "key", RequestTimeout: 5,Headers: map[string]string{"X-Custom": "configured"}, Models: []*conf.Model{{ID: "model", Name: "test", Enabled: true}}}- model.Conf.AI.Providers = []*conf.Provider{provider}- model.Conf.AI.Editing.ModelID = "model"+ model.Conf.AI.Load().Providers = []*conf.Provider{provider}+ model.Conf.AI.Load().Editing.ModelID = "model"engine := gin.New()engine.POST("/api/ai/editor/chat", aiEditorChat)engine.POST("/api/ai/chatGPT", chatGPT)diff --git a/kernel/api/contract_asset_test.go b/kernel/api/contract_asset_test.goindex e25b57399a..aa2c144b1d 100644--- a/kernel/api/contract_asset_test.go+++ b/kernel/api/contract_asset_test.go@@ -26,7 +26,7 @@ func setupAssetContractWorkspace(t *testing.T) string {t.Helper()previousConf, previousData, previousWorkspace := model.Conf, util.DataDir, util.WorkspaceDirmodel.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())util.WorkspaceDir = t.TempDir()util.DataDir = filepath.Join(util.WorkspaceDir, "data")t.Cleanup(func() { model.Conf, util.DataDir, util.WorkspaceDir = previousConf, previousData, previousWorkspace })@@ -217,7 +217,7 @@ func TestAssetUploadResultContractNullability(t *testing.T) {func TestAssetUnusedScanFailureContract(t *testing.T) {assets := setupAssetContractWorkspace(t)- model.Conf.FileTree = conf.NewFileTree()+ model.Conf.FileTree.Store(conf.NewFileTree())box := &model.Box{ID: "20260918000000-abcdefg"}if err := box.SaveConf(conf.NewBoxConf()); err != nil {t.Fatal(err)@@ -278,7 +278,11 @@ func TestAndroidNotificationAssetDeletionContract(t *testing.T) {return}assets := setupAssetContractWorkspace(t)- model.Conf.FileTree, model.Conf.Search = conf.NewFileTree(), conf.NewSearch()+ {+ confSectionValue0, confSectionValue1 := conf.NewFileTree(), conf.NewSearch()+ model.Conf.FileTree.Store(confSectionValue0)+ model.Conf.Search.Store(confSectionValue1)+ }util.HistoryDir, util.TempDir, util.ConfDir = t.TempDir(), t.TempDir(), t.TempDir()util.QueueDir = t.TempDir()util.DBPath, util.HistoryDBPath = filepath.Join(util.TempDir, "siyuan.db"), filepath.Join(util.TempDir, "history.db")diff --git a/kernel/api/contract_av_automation_test.go b/kernel/api/contract_av_automation_test.goindex fedda51c8d..8f51755059 100644--- a/kernel/api/contract_av_automation_test.go+++ b/kernel/api/contract_av_automation_test.go@@ -45,7 +45,12 @@ func TestAVContractAutomationWrites(t *testing.T) {t.Fatal(err)}util.TimeLangs["en"] = language.Time- model.Conf.Search, model.Conf.Editor, model.Conf.Export = conf.NewSearch(), conf.NewEditor(), conf.NewExport()+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewSearch(), conf.NewEditor(), conf.NewExport()+ model.Conf.Search.Store(confSectionValue0)+ model.Conf.Editor.Store(confSectionValue1)+ model.Conf.Export.Store(confSectionValue2)+ }tree, err := model.LoadTreeByBlockID(fixture.databaseID)if err != nil {t.Fatal(err)diff --git a/kernel/api/contract_av_test.go b/kernel/api/contract_av_test.goindex 7c3f376023..989d56dd49 100644--- a/kernel/api/contract_av_test.go+++ b/kernel/api/contract_av_test.go@@ -33,7 +33,7 @@ func TestUnusedAttributeViewScanFailureContract(t *testing.T) {util.Lang = "en"util.AttrViewLangs = map[string]map[string]any{"en": {"key": "Key", "select": "Select", "table": "Table"}}t.Cleanup(func() { util.Lang, util.AttrViewLangs = previousLang, previousLangs })- model.Conf.FileTree = conf.NewFileTree()+ model.Conf.FileTree.Store(conf.NewFileTree())box := &model.Box{ID: "20260918000000-abcdefg"}if err := box.SaveConf(conf.NewBoxConf()); err != nil {t.Fatal(err)@@ -114,7 +114,12 @@ func TestAVContractDetachedItemIcon(t *testing.T) {t.Fatal(err)}util.TimeLangs["en"] = language.Time- model.Conf.Search, model.Conf.Editor, model.Conf.Export = conf.NewSearch(), conf.NewEditor(), conf.NewExport()+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewSearch(), conf.NewEditor(), conf.NewExport()+ model.Conf.Search.Store(confSectionValue0)+ model.Conf.Editor.Store(confSectionValue1)+ model.Conf.Export.Store(confSectionValue2)+ }tree, err := model.LoadTreeByBlockID(fixture.databaseID)if err != nil {t.Fatal(err)diff --git a/kernel/api/contract_block_existence_test.go b/kernel/api/contract_block_existence_test.goindex 4a818c0b9c..083ad0f213 100644--- a/kernel/api/contract_block_existence_test.go+++ b/kernel/api/contract_block_existence_test.go@@ -48,8 +48,18 @@ func TestAPIContractCheckBlocksExist(t *testing.T) {}}model.Conf = model.NewAppConf()- model.Conf.NotebookCrypto, model.Conf.Sync, model.Conf.FileTree = conf.NewNotebookCrypto(), conf.NewSync(), conf.NewFileTree()- model.Conf.Editor, model.Conf.Export, model.Conf.Search = conf.NewEditor(), conf.NewExport(), conf.NewSearch()+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewNotebookCrypto(), conf.NewSync(), conf.NewFileTree()+ model.Conf.NotebookCrypto = confSectionValue0+ model.Conf.Sync.Store(confSectionValue1)+ model.Conf.FileTree.Store(confSectionValue2)+ }+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewEditor(), conf.NewExport(), conf.NewSearch()+ model.Conf.Editor.Store(confSectionValue0)+ model.Conf.Export.Store(confSectionValue1)+ model.Conf.Search.Store(confSectionValue2)+ }sql.InitDatabase(true)sql.InitHistoryDatabase(true)sql.InitAssetContentDatabase(true)diff --git a/kernel/api/contract_block_transaction_test.go b/kernel/api/contract_block_transaction_test.goindex 60805a903c..3d75b5189a 100644--- a/kernel/api/contract_block_transaction_test.go+++ b/kernel/api/contract_block_transaction_test.go@@ -81,8 +81,18 @@ func TestAPIContractHeadingTransactions(t *testing.T) {t.Fatal(err)}util.TimeLangs[model.Conf.Lang] = language.Time- model.Conf.FileTree, model.Conf.Sync, model.Conf.NotebookCrypto = conf.NewFileTree(), conf.NewSync(), conf.NewNotebookCrypto()- model.Conf.Search, model.Conf.Editor, model.Conf.Export = conf.NewSearch(), conf.NewEditor(), conf.NewExport()+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewFileTree(), conf.NewSync(), conf.NewNotebookCrypto()+ model.Conf.FileTree.Store(confSectionValue0)+ model.Conf.Sync.Store(confSectionValue1)+ model.Conf.NotebookCrypto = confSectionValue2+ }+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewSearch(), conf.NewEditor(), conf.NewExport()+ model.Conf.Search.Store(confSectionValue0)+ model.Conf.Editor.Store(confSectionValue1)+ model.Conf.Export.Store(confSectionValue2)+ }box := &model.Box{ID: ast.NewNodeID()}boxConf := conf.NewBoxConf()boxConf.Closed = falsediff --git a/kernel/api/contract_builtin_skill_test.go b/kernel/api/contract_builtin_skill_test.goindex f0e13a91cb..28fbb997b3 100644--- a/kernel/api/contract_builtin_skill_test.go+++ b/kernel/api/contract_builtin_skill_test.go@@ -20,7 +20,7 @@ func TestAPIContractAIBuiltinSkills(t *testing.T) {engine.POST("/api/ai/agent/lsSkills", lsSkills)for _, disabled := range []bool{false, true} {if disabled {- model.Conf.AI.Agent.Skills.BuiltinDisabled = []string{util.BuiltinPluginSkillID, "builtin:future"}+ model.Conf.AI.Load().Agent.Skills.BuiltinDisabled = []string{util.BuiltinPluginSkillID, "builtin:future"}}response := httptest.NewRecorder()engine.ServeHTTP(response, httptest.NewRequest("POST", "/api/ai/agent/lsBuiltinSkills", strings.NewReader("{}")))diff --git a/kernel/api/contract_clipboard_paste_test.go b/kernel/api/contract_clipboard_paste_test.goindex f3fbd5c1e5..c3af11ec22 100644--- a/kernel/api/contract_clipboard_paste_test.go+++ b/kernel/api/contract_clipboard_paste_test.go@@ -44,10 +44,23 @@ func TestAPIContractPasteAssets(t *testing.T) {}}model.Conf = model.NewAppConf()- model.Conf.NotebookCrypto, model.Conf.FileTree = conf.NewNotebookCrypto(), conf.NewFileTree()- model.Conf.Sync, model.Conf.System = conf.NewSync(), conf.NewSystem()- model.Conf.Editor, model.Conf.Search, model.Conf.Export = conf.NewEditor(), conf.NewSearch(), conf.NewExport()- model.Conf.Api = &conf.API{Token: "paste-assets-test"}+ {+ confSectionValue0, confSectionValue1 := conf.NewNotebookCrypto(), conf.NewFileTree()+ model.Conf.NotebookCrypto = confSectionValue0+ model.Conf.FileTree.Store(confSectionValue1)+ }+ {+ confSectionValue0, confSectionValue1 := conf.NewSync(), conf.NewSystem()+ model.Conf.Sync.Store(confSectionValue0)+ model.Conf.System.Store(confSectionValue1)+ }+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewEditor(), conf.NewSearch(), conf.NewExport()+ model.Conf.Editor.Store(confSectionValue0)+ model.Conf.Search.Store(confSectionValue1)+ model.Conf.Export.Store(confSectionValue2)+ }+ model.Conf.Api.Store(&conf.API{Token: "paste-assets-test"})sql.InitDatabase(true)sql.InitHistoryDatabase(true)sql.InitAssetContentDatabase(true)diff --git a/kernel/api/contract_duplicate_doc_tree_test.go b/kernel/api/contract_duplicate_doc_tree_test.goindex 252c9fb2ca..0c37320ba9 100644--- a/kernel/api/contract_duplicate_doc_tree_test.go+++ b/kernel/api/contract_duplicate_doc_tree_test.go@@ -58,9 +58,19 @@ func TestAPIContractDuplicateDocTree(t *testing.T) {}model.Conf = model.NewAppConf()model.Conf.Lang = "en"- model.Conf.NotebookCrypto, model.Conf.Sync, model.Conf.FileTree = conf.NewNotebookCrypto(), conf.NewSync(), conf.NewFileTree()- model.Conf.Editor, model.Conf.Export, model.Conf.Search = conf.NewEditor(), conf.NewExport(), conf.NewSearch()- model.Conf.Api = &conf.API{Token: "duplicate-tree-test"}+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewNotebookCrypto(), conf.NewSync(), conf.NewFileTree()+ model.Conf.NotebookCrypto = confSectionValue0+ model.Conf.Sync.Store(confSectionValue1)+ model.Conf.FileTree.Store(confSectionValue2)+ }+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewEditor(), conf.NewExport(), conf.NewSearch()+ model.Conf.Editor.Store(confSectionValue0)+ model.Conf.Export.Store(confSectionValue1)+ model.Conf.Search.Store(confSectionValue2)+ }+ model.Conf.Api.Store(&conf.API{Token: "duplicate-tree-test"})model.Conf.AccessAuthCode = "application-password"langData, err := os.ReadFile(filepath.Join("..", "..", "app", "appearance", "langs", "en.json"))if err != nil {diff --git a/kernel/api/contract_entry_visibility_defaults_test.go b/kernel/api/contract_entry_visibility_defaults_test.goindex c88c3fbf3f..e6ab401d97 100644--- a/kernel/api/contract_entry_visibility_defaults_test.go+++ b/kernel/api/contract_entry_visibility_defaults_test.go@@ -16,7 +16,7 @@ func TestAPIContractEntryVisibilityDefaults(t *testing.T) {t.Cleanup(func() { model.Conf, util.ReadOnly = previous, readOnly })for _, version := range []int{6, 7} {model.Conf = model.NewAppConf()- model.Conf.Appearance = conf.NewAppearance()+ model.Conf.Appearance.Store(conf.NewAppearance())body := fmt.Sprintf(`{"version":%d,"active":"custom","profiles":[{"id":"custom","name":"Custom","defaults":"simple","entries":{"editor.toolbar.strong":false},"orders":{"dock":["plugin:unavailable:dock"]}}]}`, version)code, message, data := settingContractRequest(t, "setEntryVisibility", setEntryVisibility, body)if code != 0 {diff --git a/kernel/api/contract_export_heading_numbers_test.go b/kernel/api/contract_export_heading_numbers_test.goindex e763fe77b3..024b537ce7 100644--- a/kernel/api/contract_export_heading_numbers_test.go+++ b/kernel/api/contract_export_heading_numbers_test.go@@ -44,11 +44,20 @@ func TestAPIContractExportHeadingNumbers(t *testing.T) {util.DBPath, util.HistoryDBPath = filepath.Join(root, "siyuan.db"), filepath.Join(root, "history.db")util.AssetContentDBPath, util.BlockTreeDBPath = filepath.Join(root, "asset_content.db"), filepath.Join(root, "blocktree.db")model.Conf = model.NewAppConf()- model.Conf.FileTree, model.Conf.Sync = conf.NewFileTree(), conf.NewSync()- model.Conf.Search, model.Conf.Editor, model.Conf.Export = conf.NewSearch(), conf.NewEditor(), conf.NewExport()+ {+ confSectionValue0, confSectionValue1 := conf.NewFileTree(), conf.NewSync()+ model.Conf.FileTree.Store(confSectionValue0)+ model.Conf.Sync.Store(confSectionValue1)+ }+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewSearch(), conf.NewEditor(), conf.NewExport()+ model.Conf.Search.Store(confSectionValue0)+ model.Conf.Editor.Store(confSectionValue1)+ model.Conf.Export.Store(confSectionValue2)+ }model.Conf.NotebookCrypto = conf.NewNotebookCrypto()- model.Conf.Appearance = conf.NewAppearance()- model.Conf.Export.AddTitle = false+ model.Conf.Appearance.Store(conf.NewAppearance())+ model.Conf.Export.Load().AddTitle = falseboxID, docID := ast.NewNodeID(), ast.NewNodeID()box := &model.Box{ID: boxID}boxConf := conf.NewBoxConf()@@ -90,8 +99,8 @@ func TestAPIContractExportHeadingNumbers(t *testing.T) {{"full width punctuation", "true", "chinese-document", "一、**First**", "(二)Last", false},} {t.Run(test.name, func(t *testing.T) {- model.Conf.Editor.HeadingNumber = test.defaultEnabled- model.Conf.Editor.HeadingNumberFormat = test.format+ model.Conf.Editor.Load().HeadingNumber = test.defaultEnabled+ model.Conf.Editor.Load().HeadingNumberFormat = test.formattree.Root.SetIALAttr("custom-sy-heading-number", test.documentSetting)if _, err := filesys.WriteTree(tree); err != nil {t.Fatal(err)diff --git a/kernel/api/contract_export_lease_test.go b/kernel/api/contract_export_lease_test.goindex faa3fce6c1..30d5a834da 100644--- a/kernel/api/contract_export_lease_test.go+++ b/kernel/api/contract_export_lease_test.go@@ -47,9 +47,19 @@ func TestAPIContractExportNotebookResponseLease(t *testing.T) {}}model.Conf = model.NewAppConf()- model.Conf.NotebookCrypto, model.Conf.Sync, model.Conf.FileTree = conf.NewNotebookCrypto(), conf.NewSync(), conf.NewFileTree()- model.Conf.Editor, model.Conf.Export, model.Conf.Search = conf.NewEditor(), conf.NewExport(), conf.NewSearch()- *model.Conf.FileTree.BoxDocEnabled = true+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewNotebookCrypto(), conf.NewSync(), conf.NewFileTree()+ model.Conf.NotebookCrypto = confSectionValue0+ model.Conf.Sync.Store(confSectionValue1)+ model.Conf.FileTree.Store(confSectionValue2)+ }+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewEditor(), conf.NewExport(), conf.NewSearch()+ model.Conf.Editor.Store(confSectionValue0)+ model.Conf.Export.Store(confSectionValue1)+ model.Conf.Search.Store(confSectionValue2)+ }+ *model.Conf.FileTree.Load().BoxDocEnabled = truesql.InitDatabase(true)sql.InitHistoryDatabase(true)sql.InitAssetContentDatabase(true)diff --git a/kernel/api/contract_export_task_markers_test.go b/kernel/api/contract_export_task_markers_test.goindex b558cda3dd..4bd8a23e21 100644--- a/kernel/api/contract_export_task_markers_test.go+++ b/kernel/api/contract_export_task_markers_test.go@@ -39,8 +39,17 @@ func TestAPIContractExportTaskMarkers(t *testing.T) {util.DBPath, util.HistoryDBPath = filepath.Join(root, "siyuan.db"), filepath.Join(root, "history.db")util.AssetContentDBPath, util.BlockTreeDBPath = filepath.Join(root, "asset_content.db"), filepath.Join(root, "blocktree.db")model.Conf = model.NewAppConf()- model.Conf.FileTree, model.Conf.Sync = conf.NewFileTree(), conf.NewSync()- model.Conf.Search, model.Conf.Editor, model.Conf.Export = conf.NewSearch(), conf.NewEditor(), conf.NewExport()+ {+ confSectionValue0, confSectionValue1 := conf.NewFileTree(), conf.NewSync()+ model.Conf.FileTree.Store(confSectionValue0)+ model.Conf.Sync.Store(confSectionValue1)+ }+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewSearch(), conf.NewEditor(), conf.NewExport()+ model.Conf.Search.Store(confSectionValue0)+ model.Conf.Editor.Store(confSectionValue1)+ model.Conf.Export.Store(confSectionValue2)+ }model.Conf.NotebookCrypto = conf.NewNotebookCrypto()boxID, docID := ast.NewNodeID(), ast.NewNodeID()box := &model.Box{ID: boxID}diff --git a/kernel/api/contract_export_test.go b/kernel/api/contract_export_test.goindex 0f79d72793..08e9d93a5d 100644--- a/kernel/api/contract_export_test.go+++ b/kernel/api/contract_export_test.go@@ -122,8 +122,8 @@ func TestAPIContractExportMarkdownOptions(t *testing.T) {}previous := model.Confmodel.Conf = model.NewAppConf()- model.Conf.Export = conf.NewExport()- model.Conf.Export.AddTitle = true+ model.Conf.Export.Store(conf.NewExport())+ model.Conf.Export.Load().AddTitle = truet.Cleanup(func() { model.Conf = previous })addTitle, title := exportTitleOptions(apicontract.ExportTitleOptions{CustomTitle: " custom "})if !addTitle || title != "custom" {diff --git a/kernel/api/contract_filetree_test.go b/kernel/api/contract_filetree_test.goindex b307e7b135..a808dfb9db 100644--- a/kernel/api/contract_filetree_test.go+++ b/kernel/api/contract_filetree_test.go@@ -210,7 +210,7 @@ func TestAPIContractFileTreeEncryptedAdmission(t *testing.T) {util.WorkspaceDir = t.TempDir()util.DataDir = filepath.Join(util.WorkspaceDir, "data")model.Conf = model.NewAppConf()- model.Conf.FileTree = conf.NewFileTree()+ model.Conf.FileTree.Store(conf.NewFileTree())model.Conf.NotebookCrypto = conf.NewNotebookCrypto()t.Cleanup(func() { model.Conf, util.DataDir, util.WorkspaceDir = previousConf, previousData, previousWorkspace })boxConf := conf.NewBoxConf()diff --git a/kernel/api/contract_graph_test.go b/kernel/api/contract_graph_test.goindex ed029429eb..7ed91952b7 100644--- a/kernel/api/contract_graph_test.go+++ b/kernel/api/contract_graph_test.go@@ -140,9 +140,9 @@ func TestAPIContractLocalGraphEncryptedNotebook(t *testing.T) {func testGraphQueryContracts(t *testing.T, id string) {t.Helper()- previous := model.Conf.Graph- model.Conf.Graph = conf.NewGraph()- defer func() { model.Conf.Graph = previous }()+ previous := model.Conf.Graph.Load()+ model.Conf.Graph.Store(conf.NewGraph())+ defer func() { model.Conf.Graph.Store(previous) }()for _, role := range []model.Role{model.RoleAdministrator, model.RoleReader} {engine := gin.New()engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, role) })@@ -171,11 +171,11 @@ func testGraphQueryContracts(t *testing.T, id string) {// testGraphResetContracts 使用契约测试进程的临时配置目录验证重置后的持久化状态。func testGraphResetContracts(t *testing.T) {t.Helper()- previous := model.Conf.Graph- model.Conf.Graph = conf.NewGraph()- defer func() { model.Conf.Graph = previous }()- model.Conf.Graph.Global.MinRefs = 12- model.Conf.Graph.Local.DailyNote = true+ previous := model.Conf.Graph.Load()+ model.Conf.Graph.Store(conf.NewGraph())+ defer func() { model.Conf.Graph.Store(previous) }()+ model.Conf.Graph.Load().Global.MinRefs = 12+ model.Conf.Graph.Load().Local.DailyNote = trueengine := gin.New()engine.POST("/api/graph/resetGraph", resetGraph)engine.POST("/api/graph/resetLocalGraph", resetLocalGraph)@@ -200,7 +200,7 @@ func testGraphResetContracts(t *testing.T) {t.Fatalf("graph reset changed: %s, %v", recorder.Body.String(), err)}}- if model.Conf.Graph.Global.MinRefs != 0 || model.Conf.Graph.Local.DailyNote {+ if model.Conf.Graph.Load().Global.MinRefs != 0 || model.Conf.Graph.Load().Local.DailyNote {t.Fatal("graph configuration was not reset")}data, err := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))diff --git a/kernel/api/contract_history_snapshots_test.go b/kernel/api/contract_history_snapshots_test.goindex 2dd1c6fc9f..f901bf92c7 100644--- a/kernel/api/contract_history_snapshots_test.go+++ b/kernel/api/contract_history_snapshots_test.go@@ -44,12 +44,12 @@ func TestAPIContractDocHistorySnapshots(t *testing.T) {util.AssetContentDBPath = filepath.Join(root, "assets.db")util.BlockTreeDBPath = filepath.Join(root, "blocktree.db")model.Conf = model.NewAppConf()- model.Conf.Repo = conf.NewRepo()- model.Conf.Repo.Key = bytes.Repeat([]byte{1}, 32)- model.Conf.Sync = conf.NewSync()- model.Conf.System = conf.NewSystem()- model.Conf.Editor = conf.NewEditor()- model.Conf.Export = conf.NewExport()+ model.Conf.Repo.Store(conf.NewRepo())+ model.Conf.Repo.Load().Key = bytes.Repeat([]byte{1}, 32)+ model.Conf.Sync.Store(conf.NewSync())+ model.Conf.System.Store(conf.NewSystem())+ model.Conf.Editor.Store(conf.NewEditor())+ model.Conf.Export.Store(conf.NewExport())sql.InitDatabase(true)sql.InitHistoryDatabase(true)sql.InitAssetContentDatabase(true)@@ -72,7 +72,7 @@ func TestAPIContractDocHistorySnapshots(t *testing.T) {{ID: "20260928100000-locked1", Type: model.HistoryTypeDoc, Op: "update", Title: "Locked", Path: "2026-09-28-100000-update/" + lockedBoxID + "/20260928100000-locked1.sy", Created: created},})sql.FlushHistoryQueue()- repo, err := dejavu.NewRepo(util.DataDir, util.RepoDir, util.HistoryDir, util.TempDir, "test", "test", "test", model.Conf.Repo.Key, nil, nil)+ repo, err := dejavu.NewRepo(util.DataDir, util.RepoDir, util.HistoryDir, util.TempDir, "test", "test", "test", model.Conf.Repo.Load().Key, nil, nil)if err != nil {t.Fatal(err)}diff --git a/kernel/api/contract_import_footnotes_test.go b/kernel/api/contract_import_footnotes_test.goindex 799a5c47b0..b212efb998 100644--- a/kernel/api/contract_import_footnotes_test.go+++ b/kernel/api/contract_import_footnotes_test.go@@ -59,10 +59,23 @@ func TestAPIContractMarkdownFootnotes(t *testing.T) {"xd": "%d days %s", "1w": "1 week %s", "xw": "%d weeks %s", "1M": "1 month %s", "xM": "%d months %s","1y": "1 year %s", "2y": "2 years %s", "xy": "%d years %s", "max": "a long while %s",}- model.Conf.NotebookCrypto, model.Conf.FileTree = conf.NewNotebookCrypto(), conf.NewFileTree()- model.Conf.Sync, model.Conf.System = conf.NewSync(), conf.NewSystem()- model.Conf.Editor, model.Conf.Search, model.Conf.Export = conf.NewEditor(), conf.NewSearch(), conf.NewExport()- model.Conf.Api = &conf.API{Token: "footnotes-test"}+ {+ confSectionValue0, confSectionValue1 := conf.NewNotebookCrypto(), conf.NewFileTree()+ model.Conf.NotebookCrypto = confSectionValue0+ model.Conf.FileTree.Store(confSectionValue1)+ }+ {+ confSectionValue0, confSectionValue1 := conf.NewSync(), conf.NewSystem()+ model.Conf.Sync.Store(confSectionValue0)+ model.Conf.System.Store(confSectionValue1)+ }+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewEditor(), conf.NewSearch(), conf.NewExport()+ model.Conf.Editor.Store(confSectionValue0)+ model.Conf.Search.Store(confSectionValue1)+ model.Conf.Export.Store(confSectionValue2)+ }+ model.Conf.Api.Store(&conf.API{Token: "footnotes-test"})sql.InitDatabase(true)sql.InitHistoryDatabase(true)sql.InitAssetContentDatabase(true)diff --git a/kernel/api/contract_mcp_oauth_test.go b/kernel/api/contract_mcp_oauth_test.goindex 342bbda5a9..447b2cba0b 100644--- a/kernel/api/contract_mcp_oauth_test.go+++ b/kernel/api/contract_mcp_oauth_test.go@@ -25,7 +25,13 @@ func oauthTestRouter(t *testing.T) *gin.Engine {previousConf, previousDir, previousReadonly := model.Conf, util.ConfDir, util.ReadOnlygin.SetMode(gin.TestMode)model.Conf = model.NewAppConf()- model.Conf.AccessAuthCode, model.Conf.CookieKey, model.Conf.Lang, model.Conf.Api = "password", "cookie-key", "en", &conf.API{Token: "api-token"}+ {+ confSectionValue0, confSectionValue1, confSectionValue2, confSectionValue3 := "password", "cookie-key", "en", &conf.API{Token: "api-token"}+ model.Conf.AccessAuthCode = confSectionValue0+ model.Conf.CookieKey = confSectionValue1+ model.Conf.Lang = confSectionValue2+ model.Conf.Api.Store(confSectionValue3)+ }util.ConfDir, util.ReadOnly = t.TempDir(), falset.Cleanup(func() { model.Conf, util.ConfDir, util.ReadOnly = previousConf, previousDir, previousReadonly })r := gin.New()diff --git a/kernel/api/contract_notebook_system_lock_test.go b/kernel/api/contract_notebook_system_lock_test.goindex 2f5fc24e35..e9bf24cace 100644--- a/kernel/api/contract_notebook_system_lock_test.go+++ b/kernel/api/contract_notebook_system_lock_test.go@@ -47,10 +47,23 @@ func TestAPIContractNotebookSystemLock(t *testing.T) {}}model.Conf = model.NewAppConf()- model.Conf.NotebookCrypto, model.Conf.FileTree = conf.NewNotebookCrypto(), conf.NewFileTree()- model.Conf.Sync, model.Conf.System = conf.NewSync(), conf.NewSystem()- model.Conf.Editor, model.Conf.Search, model.Conf.Export = conf.NewEditor(), conf.NewSearch(), conf.NewExport()- model.Conf.Api = &conf.API{Token: "system-lock-test"}+ {+ confSectionValue0, confSectionValue1 := conf.NewNotebookCrypto(), conf.NewFileTree()+ model.Conf.NotebookCrypto = confSectionValue0+ model.Conf.FileTree.Store(confSectionValue1)+ }+ {+ confSectionValue0, confSectionValue1 := conf.NewSync(), conf.NewSystem()+ model.Conf.Sync.Store(confSectionValue0)+ model.Conf.System.Store(confSectionValue1)+ }+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewEditor(), conf.NewSearch(), conf.NewExport()+ model.Conf.Editor.Store(confSectionValue0)+ model.Conf.Search.Store(confSectionValue1)+ model.Conf.Export.Store(confSectionValue2)+ }+ model.Conf.Api.Store(&conf.API{Token: "system-lock-test"})model.Conf.AccessAuthCode = "application-lock-password"sql.InitDatabase(true)sql.InitHistoryDatabase(true)@@ -190,7 +203,7 @@ func TestAPIContractNotebookSystemLock(t *testing.T) {func TestAPIContractNotebookSystemLockNotifications(t *testing.T) {setupAssetContractWorkspace(t)- model.Conf.System = conf.NewSystem()+ model.Conf.System.Store(conf.NewSystem())previousConfDir := util.ConfDirutil.ConfDir = t.TempDir()t.Cleanup(func() { util.ConfDir = previousConfDir })@@ -203,7 +216,7 @@ func TestAPIContractNotebookSystemLockNotifications(t *testing.T) {engine.ServeHTTP(recorder, httptest.NewRequest("POST", path, strings.NewReader(fmt.Sprintf(`{"enabled":%t}`, enabled))))requireAPIContract(t, "POST", path, recorder)var response struct{ Code int }- if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != 0 || model.Conf.System.EncryptedNotebookFollowSystemLock != enabled {+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != 0 || model.Conf.System.Load().EncryptedNotebookFollowSystemLock != enabled {t.Fatalf("system lock update failed: %s, %v", recorder.Body.String(), err)}if err := connection.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {diff --git a/kernel/api/contract_ocr_ai_test.go b/kernel/api/contract_ocr_ai_test.goindex f0066a7ec1..0d624396ad 100644--- a/kernel/api/contract_ocr_ai_test.go+++ b/kernel/api/contract_ocr_ai_test.go@@ -36,13 +36,13 @@ func setupAIOCRContract(t *testing.T, handler http.HandlerFunc) *gin.Engine {util.WorkingDir = filepath.Join("..", "..", "app")t.Cleanup(func() { util.WorkingDir = previousWorking })model.Conf.Lang = "en"- model.Conf.FileTree = conf.NewFileTree()- model.Conf.AI = conf.NewAI()+ model.Conf.FileTree.Store(conf.NewFileTree())+ model.Conf.AI.Store(conf.NewAI())server := httptest.NewServer(handler)t.Cleanup(server.Close)- model.Conf.AI.Providers = []*conf.Provider{{ID: "provider", Enabled: true, APIKey: "test-key", BaseURL: server.URL + "/v1",+ model.Conf.AI.Load().Providers = []*conf.Provider{{ID: "provider", Enabled: true, APIKey: "test-key", BaseURL: server.URL + "/v1",Headers: map[string]string{"X-OCR-Test": "custom"}, Models: []*conf.Model{{ID: "vision", Enabled: true, Name: "vision-test"}}}}- model.Conf.AI.Agent.ModelID = "vision"+ model.Conf.AI.Load().Agent.ModelID = "vision"writeAIOCRImage(t, filepath.Join(assets, "ai-ocr.png"), 1)engine := gin.New()engine.POST("/api/ai/ocr", aiOCR)@@ -103,7 +103,7 @@ func TestAPIContractAIOCRProtocols(t *testing.T) {w.Header().Set("Content-Type", "application/json")_, _ = io.WriteString(w, test.body)})- model.Conf.AI.Providers[0].Protocol = test.protocol+ model.Conf.AI.Load().Providers[0].Protocol = test.protocolconst path = "assets/ai-ocr.png"t.Cleanup(func() { util.RemoveAssetText(path) })response := requestAIOCR(t, engine, path+"#preview")@@ -211,7 +211,7 @@ func TestAPIContractAIOCRAdmissionAndCancellation(t *testing.T) {case <-time.After(2 * time.Second):}})- provider := model.Conf.AI.Providers[0]+ provider := model.Conf.AI.Load().Providers[0]if err := os.WriteFile(filepath.Join(util.DataDir, "assets", "invalid.png"), []byte("invalid image"), 0600); err != nil {t.Fatal(err)}diff --git a/kernel/api/contract_ocr_provider_test.go b/kernel/api/contract_ocr_provider_test.goindex 3a195b7ffa..7fcb0a8eb0 100644--- a/kernel/api/contract_ocr_provider_test.go+++ b/kernel/api/contract_ocr_provider_test.go@@ -45,8 +45,8 @@ func TestAPIContractOCRAIProviderSettings(t *testing.T) {t.Cleanup(func() { util.ConfDir, util.DisabledFeatures = previousConfDir, previousDisabled })engine.POST("/api/asset/getOCRConfig", getOCRConfig)engine.POST("/api/asset/setOCRConfig", setOCRConfig)- model.Conf.OCR = &conf.OCR{Provider: "tesseract", Model: "tiny", Auto: true}- provider := model.Conf.AI.Providers[0]+ model.Conf.OCR.Store(&conf.OCR{Provider: "tesseract", Model: "tiny", Auto: true})+ provider := model.Conf.AI.Load().Providers[0]provider.DisplayName = "Images"provider.Models = append(provider.Models, &conf.Model{ID: "disabled", Name: "hidden", Enabled: false})get := func() apicontract.OCRConfigData {@@ -99,9 +99,9 @@ func TestAPIContractOCRUsesIndependentAIModel(t *testing.T) {w.Header().Set("Content-Type", "application/json")_, _ = io.WriteString(w, aiOCRSuccess)})- model.Conf.AI.Providers[0].Models = append(model.Conf.AI.Providers[0].Models,+ model.Conf.AI.Load().Providers[0].Models = append(model.Conf.AI.Load().Providers[0].Models,&conf.Model{ID: "ocr-model", Enabled: true, Name: "independent"})- model.Conf.OCR = &conf.OCR{Provider: "ai", Model: "tiny", AIModelID: "ocr-model"}+ model.Conf.OCR.Store(&conf.OCR{Provider: "ai", Model: "tiny", AIModelID: "ocr-model"})engine.POST("/api/asset/ocr", ocr)const path = "assets/ai-ocr.png"t.Cleanup(func() { util.RemoveAssetText(path) })@@ -110,15 +110,15 @@ func TestAPIContractOCRUsesIndependentAIModel(t *testing.T) {result.Text != "first column\nsecond line" || result.OCRJSON == nil || len(result.OCRJSON) != 0 || calls != 1 {t.Fatalf("unified AI OCR response: %+v, calls=%d", result, calls)}- model.Conf.OCR.Provider = "tesseract"+ model.Conf.OCR.Load().Provider = "tesseract"if response := requestAIOCR(t, engine, path); response.Code != 0 || calls != 2 {t.Fatal("manual AI OCR ignored independent model")}- model.Conf.OCR.AIModelID = "missing"+ model.Conf.OCR.Load().AIModelID = "missing"if response := requestAIOCR(t, engine, path); response.Code == 0 || calls != 2 || util.GetAssetText(path) != result.Text {t.Fatal("invalid OCR model fell back to agent or changed text")}- model.Conf.OCR.Provider, model.Conf.OCR.AIModelID = "ai", ""+ model.Conf.OCR.Load().Provider, model.Conf.OCR.Load().AIModelID = "ai", ""if response := requestAIOCR(t, engine, path); response.Code == 0 || calls != 2 {t.Fatal("AI provider without a selected model fell back to agent")}@@ -129,7 +129,7 @@ func TestAPIContractOCRReasoningSettingsCompatibility(t *testing.T) {previousConfDir := util.ConfDirutil.ConfDir = t.TempDir()t.Cleanup(func() { util.ConfDir = previousConfDir })- model.Conf.OCR = &conf.OCR{Provider: "ai", Model: "tiny", AIModelID: "vision"}+ model.Conf.OCR.Store(&conf.OCR{Provider: "ai", Model: "tiny", AIModelID: "vision"})engine.POST("/api/asset/setOCRConfig", setOCRConfig)for _, test := range []struct {field, expected string@@ -202,11 +202,11 @@ func TestAPIContractOCRReasoningProtocols(t *testing.T) {_, _ = io.WriteString(w, `{"choices":[{"finish_reason":"stop","message":{"content":"text"}}]}`)}})- model.Conf.AI.Providers[0].Protocol = protocol+ model.Conf.AI.Load().Providers[0].Protocol = protocolif protocol == "anthropic-messages" {- model.Conf.AI.Providers[0].Models[0].Name = "claude-sonnet-4"+ model.Conf.AI.Load().Providers[0].Models[0].Name = "claude-sonnet-4"}- model.Conf.OCR = &conf.OCR{Provider: "ai", Model: "tiny", AIModelID: "vision", ReasoningEffort: effort}+ model.Conf.OCR.Store(&conf.OCR{Provider: "ai", Model: "tiny", AIModelID: "vision", ReasoningEffort: effort})const path = "assets/ai-ocr.png"t.Cleanup(func() { util.RemoveAssetText(path) })if response := requestAIOCR(t, engine, path); response.Code != 0 || response.Data.Text != "text" || calls != 1 {@@ -229,8 +229,8 @@ func TestAPIContractOCRRejectedReasoningPreservesResult(t *testing.T) {w.WriteHeader(http.StatusBadRequest)_, _ = io.WriteString(w, `{"error":{"message":"unsupported reasoning effort","type":"invalid_request_error","param":"reasoning.effort"}}`)})- model.Conf.AI.Providers[0].Protocol = "openai-responses"- model.Conf.OCR = &conf.OCR{Provider: "ai", Model: "tiny", AIModelID: "vision", ReasoningEffort: "none"}+ model.Conf.AI.Load().Providers[0].Protocol = "openai-responses"+ model.Conf.OCR.Store(&conf.OCR{Provider: "ai", Model: "tiny", AIModelID: "vision", ReasoningEffort: "none"})const path = "assets/ai-ocr.png"util.SetAssetText(path, "previous text")t.Cleanup(func() { util.RemoveAssetText(path) })diff --git a/kernel/api/contract_ocr_test.go b/kernel/api/contract_ocr_test.goindex aa8bd33b2d..18c93fafef 100644--- a/kernel/api/contract_ocr_test.go+++ b/kernel/api/contract_ocr_test.go@@ -168,7 +168,7 @@ func TestAPIContractOCRNativeImportAndHeadlessRecognition(t *testing.T) {util.WorkingDir = filepath.Dir(filepath.Dir(filepath.Dir(models)))util.TempDir, util.ConfDir = t.TempDir(), t.TempDir()t.Cleanup(func() { util.WorkingDir, util.TempDir, util.ConfDir = previousWorking, previousTemp, previousConf })- model.Conf.OCR = &conf.OCR{Provider: "paddleocr", Model: "tiny", Auto: true}+ model.Conf.OCR.Store(&conf.OCR{Provider: "paddleocr", Model: "tiny", Auto: true})engine := gin.New()engine.POST("/api/asset/importOCRModels", importOCRModels)engine.POST("/api/asset/ocr", ocr)@@ -301,7 +301,7 @@ func TestAPIContractOCRSettings(t *testing.T) {{`{"provider":"tesseract","model":"tiny","auto":"false"}`, false},{`{"provider":"tesseract","model":"tiny"}`, false},} {- previousRevision := settingRevision+ previousRevision := model.ConfSettingRevision.Load()recorder := httptest.NewRecorder()engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/asset/setOCRConfig", strings.NewReader(test.body)))requireAPIContract(t, "POST", "/api/asset/setOCRConfig", recorder)@@ -322,8 +322,8 @@ func TestAPIContractOCRSettings(t *testing.T) {if test.success {expectedRevision++}- if settingRevision != expectedRevision {- t.Fatalf("OCR setting revision: got %d, want %d", settingRevision, expectedRevision)+ if model.ConfSettingRevision.Load() != expectedRevision {+ t.Fatalf("OCR setting revision: got %d, want %d", model.ConfSettingRevision.Load(), expectedRevision)}if util.GetAssetText(path) != "existing text" {t.Fatal("configuration update changed existing OCR text")@@ -480,7 +480,7 @@ func TestAPIContractOCRFailurePreservesText(t *testing.T) {if err := os.WriteFile(filepath.Join(assets, "failure.png"), []byte("invalid image"), 0644); err != nil {t.Fatal(err)}- model.Conf.OCR = &conf.OCR{Provider: "paddleocr", Model: "tiny"}+ model.Conf.OCR.Store(&conf.OCR{Provider: "paddleocr", Model: "tiny"})util.SetAssetText(path, "previous result")t.Cleanup(func() { util.RemoveAssetText(path) })engine := gin.New()diff --git a/kernel/api/contract_petal_test.go b/kernel/api/contract_petal_test.goindex 36b8b41614..1338aa8f61 100644--- a/kernel/api/contract_petal_test.go+++ b/kernel/api/contract_petal_test.go@@ -45,8 +45,8 @@ func TestAPIContractPetalInvalidRequests(t *testing.T) {func TestAPIContractPetalSettingsWindow(t *testing.T) {originalConf, originalDataDir := model.Conf, util.DataDirmodel.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()- model.Conf.Bazaar = &conf.Bazaar{Trust: true}+ model.Conf.Sync.Store(conf.NewSync())+ model.Conf.Bazaar.Store(&conf.Bazaar{Trust: true})util.DataDir = t.TempDir()t.Cleanup(func() { model.Conf, util.DataDir = originalConf, originalDataDir })for _, name := range []string{"opted", "legacy"} {diff --git a/kernel/api/contract_query_test.go b/kernel/api/contract_query_test.goindex e19b01f6db..526a0c4dd2 100644--- a/kernel/api/contract_query_test.go+++ b/kernel/api/contract_query_test.go@@ -13,9 +13,9 @@ import (// testSQLContractQueries 使用契约测试进程的独立数据库,避免修改运行中的工作空间。func testSQLContractQueries(t *testing.T) {t.Helper()- limit := model.Conf.Search.Limit- model.Conf.Search.Limit = 2- defer func() { model.Conf.Search.Limit = limit }()+ limit := model.Conf.Search.Load().Limit+ model.Conf.Search.Load().Limit = 2+ defer func() { model.Conf.Search.Load().Limit = limit }()engine := gin.New()engine.POST("/api/query/sql", SQL)for _, entry := range []struct {diff --git a/kernel/api/contract_ref_global_test.go b/kernel/api/contract_ref_global_test.goindex 0d8fcb5223..e3df2bedb1 100644--- a/kernel/api/contract_ref_global_test.go+++ b/kernel/api/contract_ref_global_test.go@@ -15,7 +15,7 @@ import (func TestAPIContractGlobalBacklink(t *testing.T) {previousConf, previousData := model.Conf, util.DataDirmodel.Conf, util.DataDir = model.NewAppConf(), t.TempDir()- model.Conf.Editor = conf.NewEditor()+ model.Conf.Editor.Store(conf.NewEditor())t.Cleanup(func() { model.Conf, util.DataDir = previousConf, previousData })const boxID = "20260726000003-encrypt"boxConf := conf.NewBoxConf()diff --git a/kernel/api/contract_ref_test.go b/kernel/api/contract_ref_test.goindex c2095d12bb..e94e7bf744 100644--- a/kernel/api/contract_ref_test.go+++ b/kernel/api/contract_ref_test.go@@ -39,7 +39,7 @@ func testBacklinkContextPublishedEncryptedNotebook(t *testing.T, path string) {t.Helper()previousConf, previousData := model.Conf, util.DataDirmodel.Conf, util.DataDir = model.NewAppConf(), t.TempDir()- model.Conf.Editor = conf.NewEditor()+ model.Conf.Editor.Store(conf.NewEditor())t.Cleanup(func() { model.Conf, util.DataDir = previousConf, previousData })boxID := "20260726000003-encrypt"boxConf := conf.NewBoxConf()diff --git a/kernel/api/contract_repo_test.go b/kernel/api/contract_repo_test.goindex 4da42b19e2..308494f389 100644--- a/kernel/api/contract_repo_test.go+++ b/kernel/api/contract_repo_test.go@@ -625,13 +625,13 @@ func TestRepoSnapshotIDContractHTTP(t *testing.T) {root, _ := setupArchiveWorkspace(t)previousConf, previousRepo, previousTemp := model.Conf, util.RepoDir, util.TempDirmodel.Conf = model.NewAppConf()- model.Conf.Repo = conf.NewRepo()- model.Conf.Sync = conf.NewSync()- model.Conf.System = &conf.System{ID: "contract-device", Name: "contract-device", OS: "test"}- model.Conf.Repo.Key = bytes.Repeat([]byte{1}, 32)+ model.Conf.Repo.Store(conf.NewRepo())+ model.Conf.Sync.Store(conf.NewSync())+ model.Conf.System.Store(&conf.System{ID: "contract-device", Name: "contract-device", OS: "test"})+ model.Conf.Repo.Load().Key = bytes.Repeat([]byte{1}, 32)util.RepoDir, util.TempDir = filepath.Join(root, "repo"), filepath.Join(root, "temp")t.Cleanup(func() { model.Conf, util.RepoDir, util.TempDir = previousConf, previousRepo, previousTemp })- store, err := dejavu.NewStore(util.RepoDir, model.Conf.Repo.Key)+ store, err := dejavu.NewStore(util.RepoDir, model.Conf.Repo.Load().Key)if err != nil {t.Fatal(err)}@@ -699,13 +699,13 @@ func TestRepoContractLockedFileAdmission(t *testing.T) {root, boxID := setupArchiveWorkspace(t)previousConf, previousRepo, previousTemp := model.Conf, util.RepoDir, util.TempDirmodel.Conf = model.NewAppConf()- model.Conf.Repo = conf.NewRepo()- model.Conf.Sync = conf.NewSync()- model.Conf.System = &conf.System{ID: "contract-device", Name: "contract-device", OS: "test"}- model.Conf.Repo.Key = bytes.Repeat([]byte{1}, 32)+ model.Conf.Repo.Store(conf.NewRepo())+ model.Conf.Sync.Store(conf.NewSync())+ model.Conf.System.Store(&conf.System{ID: "contract-device", Name: "contract-device", OS: "test"})+ model.Conf.Repo.Load().Key = bytes.Repeat([]byte{1}, 32)util.RepoDir, util.TempDir = filepath.Join(root, "repo"), filepath.Join(root, "temp")t.Cleanup(func() { model.Conf, util.RepoDir, util.TempDir = previousConf, previousRepo, previousTemp })- store, err := dejavu.NewStore(util.RepoDir, model.Conf.Repo.Key)+ store, err := dejavu.NewStore(util.RepoDir, model.Conf.Repo.Load().Key)if err != nil {t.Fatal(err)}diff --git a/kernel/api/contract_riff_test.go b/kernel/api/contract_riff_test.goindex 50976fa0c8..0702a623d0 100644--- a/kernel/api/contract_riff_test.go+++ b/kernel/api/contract_riff_test.go@@ -91,8 +91,8 @@ func TestAPIContractRiffEmptyAndMissing(t *testing.T) {func TestAPIContractRiffDeckLifecycle(t *testing.T) {previousConf, previousDecks, previousData := model.Conf, model.Decks, util.DataDirmodel.Conf, model.Decks, util.DataDir = model.NewAppConf(), map[string]*riff.Deck{}, t.TempDir()- model.Conf.Flashcard = conf.NewFlashcard()- model.Conf.Sync = conf.NewSync()+ model.Conf.Flashcard.Store(conf.NewFlashcard())+ model.Conf.Sync.Store(conf.NewSync())t.Cleanup(func() { model.Conf, model.Decks, util.DataDir = previousConf, previousDecks, previousData })if err := os.MkdirAll(filepath.Join(util.DataDir, "storage", "riff"), 0755); err != nil {t.Fatal(err)diff --git a/kernel/api/contract_search_test.go b/kernel/api/contract_search_test.goindex 9cc86b0e9b..0fb7ed1998 100644--- a/kernel/api/contract_search_test.go+++ b/kernel/api/contract_search_test.go@@ -59,7 +59,7 @@ func TestAPIContractSearchPermissions(t *testing.T) {func TestAPIContractSearchAssetFilters(t *testing.T) {assetsDir := setupAssetContractWorkspace(t)- model.Conf.Search = conf.NewSearch()+ model.Conf.Search.Store(conf.NewSearch())files := []string{"alpha-cover.png", "alpha-note.txt", "beta-cover.PNG", "covers/gamma-cover.webp"}for _, name := range files {path := filepath.Join(assetsDir, filepath.FromSlash(name))diff --git a/kernel/api/contract_setting_export_test.go b/kernel/api/contract_setting_export_test.goindex ef1d2db507..13468be921 100644--- a/kernel/api/contract_setting_export_test.go+++ b/kernel/api/contract_setting_export_test.go@@ -37,9 +37,9 @@ func TestAPIContractSettingExportNormalization(t *testing.T) {} {t.Run(route.name+"/"+entry.body, func(t *testing.T) {model.Conf = model.NewAppConf()- model.Conf.Export = conf.NewExport()- model.Conf.Export.BlockRefMode = 3- model.Conf.Export.BlockRefTextLeft = "["+ model.Conf.Export.Store(conf.NewExport())+ model.Conf.Export.Load().BlockRefMode = 3+ model.Conf.Export.Load().BlockRefTextLeft = "["body, want := entry.body, entry.wantif route.name == "patch" {body = `{"export":` + body + `}`@@ -48,18 +48,18 @@ func TestAPIContractSettingExportNormalization(t *testing.T) {}}code, message, data := settingContractRequest(t, route.name, route.handler, body)- if code != 0 || model.Conf.Export.BlockRefMode != want {- t.Fatalf("save failed: code=%d message=%s config=%+v", code, message, model.Conf.Export)+ if code != 0 || model.Conf.Export.Load().BlockRefMode != want {+ t.Fatalf("save failed: code=%d message=%s config=%+v", code, message, model.Conf.Export.Load())}if route.name == "setExport" {var response conf.Exportif err := json.Unmarshal(data, &response); err != nil {t.Fatal(err)}- if !reflect.DeepEqual(&response, model.Conf.Export) || response.BlockRefTextLeft != "" {+ if !reflect.DeepEqual(&response, model.Conf.Export.Load()) || response.BlockRefTextLeft != "" {t.Fatal("replacement response differs from the applied export settings")}- } else if model.Conf.Export.BlockRefTextLeft != "[" {+ } else if model.Conf.Export.Load().BlockRefTextLeft != "[" {t.Fatal("patch lost an omitted export setting")}persisted, err := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))@@ -70,8 +70,8 @@ func TestAPIContractSettingExportNormalization(t *testing.T) {if err = json.Unmarshal(persisted, &reloaded); err != nil {t.Fatal(err)}- if !reflect.DeepEqual(reloaded.Export, model.Conf.Export) ||- !reflect.DeepEqual(conf.NormalizeExport(reloaded.Export), model.Conf.Export) {+ if !reflect.DeepEqual(reloaded.Export.Load(), model.Conf.Export.Load()) ||+ !reflect.DeepEqual(conf.NormalizeExport(reloaded.Export.Load()), model.Conf.Export.Load()) {t.Fatal("persisted export settings differ from the applied or startup settings")}})diff --git a/kernel/api/contract_setting_file_tree_click_test.go b/kernel/api/contract_setting_file_tree_click_test.goindex 9b3697fd4c..428b6fa8da 100644--- a/kernel/api/contract_setting_file_tree_click_test.go+++ b/kernel/api/contract_setting_file_tree_click_test.go@@ -39,8 +39,8 @@ func TestAPIContractSettingFileTreeClickMode(t *testing.T) {{"/api/setting/patch", `{"fileTree":{"parentDocTitleClickMode":9}}`, 0, 0, false},} {model.Conf = model.NewAppConf()- model.Conf.FileTree = conf.NewFileTree()- model.Conf.FileTree.ParentDocTitleClickMode = 1+ model.Conf.FileTree.Store(conf.NewFileTree())+ model.Conf.FileTree.Load().ParentDocTitleClickMode = 1recorder := httptest.NewRecorder()request := httptest.NewRequest("POST", entry.path, strings.NewReader(entry.body))request.Header.Set("Content-Type", "application/json")@@ -61,10 +61,10 @@ func TestAPIContractSettingFileTreeClickMode(t *testing.T) {response.Data.ParentDocTitleClickMode != entry.title) {t.Fatalf("response lost the click modes: %s", recorder.Body.String())}- if model.Conf.FileTree.DocIconClickMode != entry.docIcon ||- model.Conf.FileTree.ParentDocTitleClickMode != entry.title {+ if model.Conf.FileTree.Load().DocIconClickMode != entry.docIcon ||+ model.Conf.FileTree.Load().ParentDocTitleClickMode != entry.title {t.Fatalf("%s %s: want %d/%d, got %d/%d", entry.path, entry.body, entry.docIcon, entry.title,- model.Conf.FileTree.DocIconClickMode, model.Conf.FileTree.ParentDocTitleClickMode)+ model.Conf.FileTree.Load().DocIconClickMode, model.Conf.FileTree.Load().ParentDocTitleClickMode)}}}@@ -85,7 +85,7 @@ func TestAPIContractSettingFileTreeClickModeRejectsWrongTypes(t *testing.T) {} {for _, path := range []string{"/api/setting/setFiletree", "/api/setting/patch"} {model.Conf = model.NewAppConf()- model.Conf.FileTree = conf.NewFileTree()+ model.Conf.FileTree.Store(conf.NewFileTree())body := entryif path == "/api/setting/patch" {body = `{"fileTree":` + entry + `}`@@ -104,7 +104,7 @@ func TestAPIContractSettingFileTreeClickModeRejectsWrongTypes(t *testing.T) {if response.Code == 0 {t.Fatalf("%s %s: invalid value accepted", path, body)}- if 0 != model.Conf.FileTree.DocIconClickMode || 0 != model.Conf.FileTree.ParentDocTitleClickMode {+ if 0 != model.Conf.FileTree.Load().DocIconClickMode || 0 != model.Conf.FileTree.Load().ParentDocTitleClickMode {t.Fatalf("%s %s: configuration changed on rejection", path, body)}}diff --git a/kernel/api/contract_setting_funnel_test.go b/kernel/api/contract_setting_funnel_test.gonew file mode 100644index 0000000000..6613035080--- /dev/null+++ b/kernel/api/contract_setting_funnel_test.go@@ -0,0 +1,55 @@+package api++import (+ "encoding/json"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAPIContractSettingPatchDiagnosticsAndAdditionalSections(t *testing.T) {+ previous, readonly, directory := model.Conf, util.ReadOnly, util.ConfDir+ t.Cleanup(func() { model.Conf, util.ReadOnly, util.ConfDir = previous, readonly, directory })+ model.Conf = model.NewAppConf()+ util.ConfDir, util.ReadOnly = t.TempDir(), false+ model.NormalizeAppConf(model.Conf)+ code, message, data := settingContractRequest(t, "patch", patchSetting, `{"flashcard":{"weights":"invalid"}}`)+ if code != 0 {+ t.Fatalf("warning blocked valid normalized configuration: %s", message)+ }+ var diagnostics apicontract.SettingPatchData+ if err := json.Unmarshal(data, &diagnostics); err != nil {+ t.Fatal(err)+ }+ if len(diagnostics.Issues) != 1 || diagnostics.Issues[0].Field != "flashcard.weights" || diagnostics.Issues[0].Severity != "warning" ||+ model.Conf.Flashcard.Load().Weights != conf.DefaultFSRSWeights() {+ t.Fatal("normalization warning was not returned")+ }+ before := model.ConfNamespaceRevision("publish")+ previousPublish := model.Conf.Publish.Load()+ code, _, data = settingContractRequest(t, "patch", patchSetting, `{"publish":{"auth":{"enable":true,"accounts":[{"username":"test","password":"weak"}]}}}`)+ if code == 0 || model.Conf.Publish.Load() != previousPublish || before != model.ConfNamespaceRevision("publish") {+ t.Fatal("invalid publish credentials were committed")+ }+ if err := json.Unmarshal(data, &diagnostics); err != nil || len(diagnostics.Issues) != 1 || diagnostics.Issues[0].Severity != "error" {+ t.Fatal("field error was not returned")+ }+ for _, body := range []string{`{"system":{"settingsWindow":true}}`, `{"repo":{"indexRetentionDays":42}}`, `{"sync":{"interval":80}}`, `{"snippet":{"enabledCSS":false}}`} {+ code, message, data := settingContractRequest(t, "patch", patchSetting, body)+ if code != 0 || string(data) != "null" {+ t.Fatalf("additional patch failed or changed the null response: %s %d %s %s", body, code, message, data)+ }+ }+ if !model.Conf.System.Load().SettingsWindow || model.Conf.Repo.Load().IndexRetentionDays != 42 || model.Conf.Sync.Load().Interval != 80 || model.Conf.Snippet.Load().EnabledCSS {+ t.Fatal("additional patch did not apply")+ }+ for _, body := range []string{`{"system":{"id":"replacement"}}`, `{"sync":{"provider":2}}`, `{"repo":{"key":"replacement"}}`} {+ code, _, _ := settingContractRequest(t, "patch", patchSetting, body)+ if code == 0 {+ t.Fatalf("restricted field accepted: %s", body)+ }+ }+}diff --git a/kernel/api/contract_setting_normalize_test.go b/kernel/api/contract_setting_normalize_test.goindex e358b924d9..0c3c1a0cfb 100644--- a/kernel/api/contract_setting_normalize_test.go+++ b/kernel/api/contract_setting_normalize_test.go@@ -15,26 +15,35 @@ import ()func TestAPIContractSettingNormalization(t *testing.T) {- previous, readOnly, markdown := model.Conf, util.ReadOnly, util.MarkdownSettings- singleLine, largeFile := util.UseSingleLineSave, util.LargeFileWarningSize+ previous, readOnly, markdown := model.Conf, util.ReadOnly, util.MarkdownSettings.Load()+ singleLine, largeFile := util.UseSingleLineSave.Load(), util.LargeFileWarningSize.Load()util.ReadOnly = truet.Cleanup(func() {- model.Conf, util.ReadOnly, util.MarkdownSettings = previous, readOnly, markdown- util.UseSingleLineSave, util.LargeFileWarningSize = singleLine, largeFile+ {+ derivedValue0, derivedValue1, derivedValue2 := previous, readOnly, markdown+ model.Conf = derivedValue0+ util.ReadOnly = derivedValue1+ util.MarkdownSettings.Store(derivedValue2)+ }+ {+ derivedValue0, derivedValue1 := singleLine, largeFile+ util.UseSingleLineSave.Store(derivedValue0)+ util.LargeFileWarningSize.Store(derivedValue1)+ }})model.Conf = model.NewAppConf()- model.Conf.Editor = conf.NewEditor()- model.Conf.Editor.DisplayImgName = true- model.Conf.FileTree = conf.NewFileTree()- model.Conf.Flashcard = conf.NewFlashcard()+ model.Conf.Editor.Store(conf.NewEditor())+ model.Conf.Editor.Load().DisplayImgName = true+ model.Conf.FileTree.Store(conf.NewFileTree())+ model.Conf.Flashcard.Store(conf.NewFlashcard())for _, length := range []int{0, 1, 63, 95, 5120, 6000} {body, _ := json.Marshal(map[string]int{"blockRefDynamicAnchorTextMaxLen": length, "fontSize": 100})code, message, _ := settingContractRequest(t, "setEditor", setEditor, string(body))if code != 0 {t.Fatal(message)}- editor := *model.Conf.Editor- if !reflect.DeepEqual(&editor, conf.NormalizeEditor(model.Conf.Editor)) || !editor.DisplayImgName || editor.FontSize != 16 {+ editor := *model.Conf.Editor.Load()+ if !reflect.DeepEqual(&editor, conf.NormalizeEditor(model.Conf.Editor.Load())) || !editor.DisplayImgName || editor.FontSize != 16 {t.Fatal("saved editor differs from startup normalization or lost omitted fields")}want := length@@ -49,11 +58,11 @@ func TestAPIContractSettingNormalization(t *testing.T) {}}code, message, _ := settingContractRequest(t, "setFlashcard", setFlashcard, `{"weights":"invalid","requestRetention":2,"maximumInterval":-1}`)- if code != 0 || model.Conf.Flashcard.Weights != conf.DefaultFSRSWeights() || model.Conf.Flashcard.NewCardLimit != 0 {+ if code != 0 || model.Conf.Flashcard.Load().Weights != conf.DefaultFSRSWeights() || model.Conf.Flashcard.Load().NewCardLimit != 0 {t.Fatalf("flashcard normalization failed: %s", message)}code, message, _ = settingContractRequest(t, "setFiletree", setFiletree, `{"maxListCount":0,"largeFileWarningSize":1,"shorthandSavePath":"notes"}`)- if code != 0 || model.Conf.FileTree.MaxListCount != 512 || util.LargeFileWarningSize != 8 || model.Conf.FileTree.ShorthandSavePath != "/notes" {+ if code != 0 || model.Conf.FileTree.Load().MaxListCount != 512 || util.LargeFileWarningSize.Load() != 8 || model.Conf.FileTree.Load().ShorthandSavePath != "/notes" {t.Fatalf("file tree normalization failed: %s", message)}}@@ -69,7 +78,7 @@ func TestAPIContractImportedSettingsNormalization(t *testing.T) {`{"export":{"blockRefMode":5}}`,} {model.Conf = model.NewAppConf()- originalSync := model.Conf.Sync+ originalSync := model.Conf.Sync.Load()var body bytes.Bufferwriter := multipart.NewWriter(&body)part, err := writer.CreateFormFile("file", "settings.json")@@ -94,10 +103,10 @@ func TestAPIContractImportedSettingsNormalization(t *testing.T) {if err = json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != 0 {t.Fatalf("import failed: %s (%v)", recorder.Body.String(), err)}- if model.Conf.Editor == nil || model.Conf.Editor.FontSize != 16 || model.Conf.Editor.BlockRefDynamicAnchorTextMaxLen < 1 ||- model.Conf.Export == nil || model.Conf.Export.BlockRefMode != 4 ||- model.Conf.FileTree.MaxListCount != 512 || model.Conf.Search.Limit != 64 ||- model.Conf.Flashcard.Weights != conf.DefaultFSRSWeights() || model.Conf.Sync != originalSync {+ if model.Conf.Editor.Load() == nil || model.Conf.Editor.Load().FontSize != 16 || model.Conf.Editor.Load().BlockRefDynamicAnchorTextMaxLen < 1 ||+ model.Conf.Export.Load() == nil || model.Conf.Export.Load().BlockRefMode != 4 ||+ model.Conf.FileTree.Load().MaxListCount != 512 || model.Conf.Search.Load().Limit != 64 ||+ model.Conf.Flashcard.Load().Weights != conf.DefaultFSRSWeights() || model.Conf.Sync.Load() != originalSync {t.Fatal("import did not normalize preferences or replaced sync configuration")}}diff --git a/kernel/api/contract_setting_test.go b/kernel/api/contract_setting_test.goindex 865c961bf7..8a85f21f69 100644--- a/kernel/api/contract_setting_test.go+++ b/kernel/api/contract_setting_test.go@@ -115,12 +115,17 @@ func TestAPIContractSettingImageDisplayCompatibility(t *testing.T) {}func TestAPIContractSettingImageDisplayUpdates(t *testing.T) {- previousConf, previousReadOnly, previousMarkdown := model.Conf, util.ReadOnly, util.MarkdownSettings+ previousConf, previousReadOnly, previousMarkdown := model.Conf, util.ReadOnly, util.MarkdownSettings.Load()model.Conf = model.NewAppConf()- model.Conf.Editor = conf.NewEditor()+ model.Conf.Editor.Store(conf.NewEditor())util.ReadOnly = truet.Cleanup(func() {- model.Conf, util.ReadOnly, util.MarkdownSettings = previousConf, previousReadOnly, previousMarkdown+ {+ derivedValue0, derivedValue1, derivedValue2 := previousConf, previousReadOnly, previousMarkdown+ model.Conf = derivedValue0+ util.ReadOnly = derivedValue1+ util.MarkdownSettings.Store(derivedValue2)+ }})for _, entry := range []struct {body string@@ -137,7 +142,7 @@ func TestAPIContractSettingImageDisplayUpdates(t *testing.T) {if err := json.Unmarshal(data, &response); err != nil {t.Fatal(err)}- if code != 0 || model.Conf.Editor.DisplayImgName != entry.want || response.DisplayImgName != entry.want {+ if code != 0 || model.Conf.Editor.Load().DisplayImgName != entry.want || response.DisplayImgName != entry.want {t.Fatalf("image display update %s: code=%d message=%s data=%s", entry.body, code, message, data)}}@@ -153,7 +158,7 @@ func TestAPIContractSettingImageDisplayUpdates(t *testing.T) {if err := json.Unmarshal(data, &response); err != nil {t.Fatal(err)}- if code != 0 || model.Conf.Editor.DisplayImgAlt != entry.want || response.DisplayImgAlt != entry.want {+ if code != 0 || model.Conf.Editor.Load().DisplayImgAlt != entry.want || response.DisplayImgAlt != entry.want {t.Fatalf("image tooltip text update %s: code=%d message=%s data=%s", entry.body, code, message, data)}}@@ -218,17 +223,17 @@ func TestAPIContractSettingErrorsAndAdmission(t *testing.T) {func TestAPIContractSettingEmojiAndPublishValidation(t *testing.T) {previous := model.Confmodel.Conf = model.NewAppConf()- model.Conf.Editor = conf.NewEditor()- model.Conf.Publish = conf.NewPublish()+ model.Conf.Editor.Store(conf.NewEditor())+ model.Conf.Publish.Store(conf.NewPublish())t.Cleanup(func() { model.Conf = previous })code, _, data := settingContractRequest(t, "setEmoji", setEmoji, `{"emoji":[]}`)- if code != 0 || string(data) != "null" || model.Conf.Editor.Emoji == nil || len(model.Conf.Editor.Emoji) != 0 {+ if code != 0 || string(data) != "null" || model.Conf.Editor.Load().Emoji == nil || len(model.Conf.Editor.Load().Emoji) != 0 {t.Fatal("empty emoji list changed")}- priorPublish := model.Conf.Publish+ priorPublish := model.Conf.Publish.Load()for _, body := range []string{`{"auth":{"enable":true,"accounts":[null]}}`, `{"auth":{"enable":true,"accounts":[{"username":"u","password":"short"}]}}`, `{"auth":{"enable":true,"accounts":[{"username":"u","password":"12345678"},{"username":"u","password":"12345678"}]}}`} {code, _, _ = settingContractRequest(t, "setPublish", setPublish, body)- if code != -1 || model.Conf.Publish != priorPublish {+ if code != -1 || model.Conf.Publish.Load() != priorPublish {t.Fatal("invalid publish credentials changed configuration")}}diff --git a/kernel/api/contract_skill_manage_test.go b/kernel/api/contract_skill_manage_test.goindex 0623d666e4..c509d2a287 100644--- a/kernel/api/contract_skill_manage_test.go+++ b/kernel/api/contract_skill_manage_test.go@@ -18,7 +18,7 @@ import (func TestAPIContractAISkillManagement(t *testing.T) {aiContractConfiguration(t)- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())engine := gin.New()engine.POST("/api/ai/agent/manageSkills", manageSkills)call := func(body string, code int) apicontract.AISkillFileData {diff --git a/kernel/api/contract_sync_clear_test.go b/kernel/api/contract_sync_clear_test.goindex 7eea40308b..c51cf007d6 100644--- a/kernel/api/contract_sync_clear_test.go+++ b/kernel/api/contract_sync_clear_test.go@@ -25,8 +25,8 @@ func TestAPIContractSyncClearConfiguration(t *testing.T) {const path = "/api/sync/clearSyncProviderConfig"engine.POST(path, clearSyncProviderConfig)for _, body := range []string{`{}`, `{"provider":null}`, `{"provider":"2"}`, `{"provider":2.5}`, `{"provider":0}`, `{"provider":5}`, `{"provider":2}`} {- model.Conf.Sync.Provider, model.Conf.Sync.Enabled = conf.ProviderS3, true- model.Conf.Sync.S3 = &conf.S3{Endpoint: "https://s3.example", SecretKey: "secret"}+ model.Conf.Sync.Load().Provider, model.Conf.Sync.Load().Enabled = conf.ProviderS3, true+ model.Conf.Sync.Load().S3 = &conf.S3{Endpoint: "https://s3.example", SecretKey: "secret"}recorder := httptest.NewRecorder()engine.ServeHTTP(recorder, httptest.NewRequest("POST", path, strings.NewReader(body)))requireAPIContract(t, "POST", path, recorder)@@ -41,7 +41,7 @@ func TestAPIContractSyncClearConfiguration(t *testing.T) {if response.Code != 0 || response.Data == nil || response.Data.Enabled || response.Data.S3 == nil || response.Data.S3.SecretKey != "" {t.Fatalf("clear response: %s", recorder.Body.String())}- } else if response.Code == 0 || model.Conf.Sync.S3.SecretKey != "secret" || !model.Conf.Sync.Enabled {+ } else if response.Code == 0 || model.Conf.Sync.Load().S3.SecretKey != "secret" || !model.Conf.Sync.Load().Enabled {t.Fatalf("invalid clear changed configuration: %s", recorder.Body.String())}}diff --git a/kernel/api/contract_sync_test.go b/kernel/api/contract_sync_test.goindex bb89541102..7dc22572c5 100644--- a/kernel/api/contract_sync_test.go+++ b/kernel/api/contract_sync_test.go@@ -26,9 +26,9 @@ func syncTestConfiguration(t *testing.T) {t.Helper()previous, previousReadonly, previousTemp := model.Conf, util.ReadOnly, util.TempDirmodel.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()- model.Conf.Sync.S3 = &conf.S3{}- model.Conf.Sync.WebDAV = &conf.WebDAV{}+ model.Conf.Sync.Store(conf.NewSync())+ model.Conf.Sync.Load().S3 = &conf.S3{}+ model.Conf.Sync.Load().WebDAV = &conf.WebDAV{}util.ReadOnly = trueutil.TempDir = t.TempDir()t.Cleanup(func() { model.Conf, util.ReadOnly, util.TempDir = previous, previousReadonly, previousTemp })@@ -87,7 +87,7 @@ func TestAPIContractSyncProviderConfigCompatibility(t *testing.T) {func TestAPIContractSyncHTTPResponses(t *testing.T) {syncTestConfiguration(t)- model.Conf.Sync.Mode = 3+ model.Conf.Sync.Load().Mode = 3engine := gin.New()for path, handler := range map[string]gin.HandlerFunc{"getBootSync": getBootSync, "getSyncInfo": getSyncInfo, "getSyncLANStatus": getSyncLANStatus,@@ -138,8 +138,8 @@ func TestAPIContractSyncHTTPResponses(t *testing.T) {t.Fatalf("response changed for %s: %s (%v)", path, recorder.Body.String(), err)}}- if model.Conf.Sync.Mode != 3 || model.Conf.Sync.Interval != 31 {- t.Fatalf("numeric truncation changed: %+v", model.Conf.Sync)+ if model.Conf.Sync.Load().Mode != 3 || model.Conf.Sync.Load().Interval != 31 {+ t.Fatalf("numeric truncation changed: %+v", model.Conf.Sync.Load())}}@@ -148,7 +148,7 @@ func TestAPIContractSyncBootRole(t *testing.T) {previous := model.BootSyncSucc.Load()model.BootSyncSucc.Store(1)t.Cleanup(func() { model.BootSyncSucc.Store(previous) })- model.Conf.Sync.Enabled = true+ model.Conf.Sync.Load().Enabled = truefor _, role := range []model.Role{model.RoleAdministrator, model.RoleReader} {engine := gin.New()engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, role) })@@ -252,16 +252,17 @@ func TestAPIContractSyncProviderMultipart(t *testing.T) {func TestAPIContractSyncProviderExportContents(t *testing.T) {syncTestConfiguration(t)- model.Conf.Sync.S3 = &conf.S3{Endpoint: " endpoint ", AccessKey: "key", SecretKey: " secret ", Bucket: "bucket", Region: "auto", Timeout: 35}- model.Conf.Sync.WebDAV = &conf.WebDAV{Endpoint: " endpoint ", Password: " password ", Timeout: 36}+ model.Conf.Sync.Load().S3 = &conf.S3{Endpoint: " endpoint ", AccessKey: "key", SecretKey: " secret ", Bucket: "bucket", Region: "auto", Timeout: 35}+ model.Conf.Sync.Load().WebDAV = &conf.WebDAV{Endpoint: " endpoint ", Password: " password ", Timeout: 36}for _, entry := range []struct {name stringhandler gin.HandlerFunc- expected []byte+ expected func() []byte}{- {"exportSyncProviderS3", exportSyncProviderS3, syncMarshal(t, model.Conf.Sync.S3)},- {"exportSyncProviderWebDAV", exportSyncProviderWebDAV, syncMarshal(t, model.Conf.Sync.WebDAV)},+ {"exportSyncProviderS3", exportSyncProviderS3, func() []byte { return syncMarshal(t, model.Conf.Sync.Load().S3) }},+ {"exportSyncProviderWebDAV", exportSyncProviderWebDAV, func() []byte { return syncMarshal(t, model.Conf.Sync.Load().WebDAV) }},} {+ expected := entry.expected()engine := gin.New()path := "/api/sync/" + entry.nameengine.POST(path, entry.handler)@@ -295,8 +296,8 @@ func TestAPIContractSyncProviderExportContents(t *testing.T) {t.Fatal(err)}plain, err := hex.DecodeString(string(util.AESDecrypt(string(encrypted))))- if err != nil || !bytes.Equal(plain, entry.expected) {- t.Fatalf("export encryption or JSON changed: %s != %s (%v)", plain, entry.expected, err)+ if err != nil || !bytes.Equal(plain, expected) {+ t.Fatalf("export encryption or JSON changed: %s != %s (%v)", plain, expected, err)}archiveData, err := os.ReadFile(filepath.Join(util.TempDir, filepath.FromSlash(strings.TrimPrefix(response.Data.Zip, "/"))))if err != nil {diff --git a/kernel/api/contract_system_test.go b/kernel/api/contract_system_test.goindex abedc1d2ef..eb2689bdad 100644--- a/kernel/api/contract_system_test.go+++ b/kernel/api/contract_system_test.go@@ -65,6 +65,10 @@ func TestAPIContractSystemCompleteConfiguration(t *testing.T) {if err := decoder.Decode(&payloadJSON); err != nil {t.Fatal(err)}+ delete(sourceJSON.(map[string]any), "confVersion")+ if _, exposed := payloadJSON.(map[string]any)["confVersion"]; exposed {+ t.Fatal("internal configuration version was exposed")+ }if !reflect.DeepEqual(sourceJSON, payloadJSON) {t.Fatalf("complete configuration changed:\n%s\n%s", before, after)}diff --git a/kernel/api/contract_test.go b/kernel/api/contract_test.goindex 5fbcd17ca6..936bfa686d 100644--- a/kernel/api/contract_test.go+++ b/kernel/api/contract_test.go@@ -120,8 +120,17 @@ func TestAPIContractHandlers(t *testing.T) {for _, key := range []string{"albl", "blbl", "now", "1s", "xs", "1m", "xm", "1h", "xh", "1d", "xd", "1w", "xw", "1M", "xM", "1y", "2y", "xy", "max"} {util.TimeLangs["en"][key] = "time"}- model.Conf.FileTree, model.Conf.Sync = conf.NewFileTree(), conf.NewSync()- model.Conf.Search, model.Conf.Editor, model.Conf.Export = conf.NewSearch(), conf.NewEditor(), conf.NewExport()+ {+ confSectionValue0, confSectionValue1 := conf.NewFileTree(), conf.NewSync()+ model.Conf.FileTree.Store(confSectionValue0)+ model.Conf.Sync.Store(confSectionValue1)+ }+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewSearch(), conf.NewEditor(), conf.NewExport()+ model.Conf.Search.Store(confSectionValue0)+ model.Conf.Editor.Store(confSectionValue1)+ model.Conf.Export.Store(confSectionValue2)+ }model.Conf.NotebookCrypto = conf.NewNotebookCrypto()const boxID, docID = "20260912000000-boxapi1", "20260912000001-docapi1"box := &model.Box{ID: boxID}diff --git a/kernel/api/export.go b/kernel/api/export.goindex 27cb2701a1..7063c49692 100644--- a/kernel/api/export.go+++ b/kernel/api/export.go@@ -370,6 +370,8 @@ var exportSY = contractHandler(apicontract.ExportSY, func(c *gin.Context, reques})var exportMdContent = contractHandler(apicontract.ExportMdContent, func(c *gin.Context, request apicontract.ExportMarkdownContentRequest) apicontract.Response[apicontract.ExportMarkdownContentData] {+ confExportSnapshot := model.Conf.LoadExport()+ret := gulu.Ret.NewResult()id := request.ID@@ -385,7 +387,7 @@ var exportMdContent = contractHandler(apicontract.ExportMdContent, func(c *gin.Cret.Msg = err.Error()return contractFailure[apicontract.ExportMarkdownContentData](ret)}- refMode, embedMode, yfm := model.Conf.Export.BlockRefMode, model.Conf.Export.BlockEmbedMode, true+ refMode, embedMode, yfm := confExportSnapshot.BlockRefMode, confExportSnapshot.BlockEmbedMode, trueif request.RefMode != nil {refMode = int(*request.RefMode)}@@ -396,7 +398,7 @@ var exportMdContent = contractHandler(apicontract.ExportMdContent, func(c *gin.Cyfm = *request.YFM}fillCSSVar, adjustHeadingLevel, imgTag := request.FillCSSVar, request.AdjustHeadingLevel, request.ImgTag- addTitle := model.Conf.Export.AddTitle+ addTitle := confExportSnapshot.AddTitleif request.AddTitle != nil {addTitle = *request.AddTitle}@@ -676,7 +678,7 @@ var exportHTML = contractHandler(apicontract.ExportHTML, func(c *gin.Context, re})func exportTitleOptions(options apicontract.ExportTitleOptions) (addTitle bool, customTitle string) {- addTitle = model.Conf.Export.AddTitle+ addTitle = model.Conf.Export.Load().AddTitleif options.AddTitle != nil {addTitle = *options.AddTitle}diff --git a/kernel/api/file_test.go b/kernel/api/file_test.goindex 40e413f83c..a118b67621 100644--- a/kernel/api/file_test.go+++ b/kernel/api/file_test.go@@ -169,7 +169,7 @@ func TestGetFileAdminCanFollowAssetsSymlinkOutsideWorkspace(t *testing.T) {func TestGetFileReaderCanReadHiddenNotebookFile(t *testing.T) {previousConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())t.Cleanup(func() { model.Conf = previousConf })workspaceDir := testutil.PublicDataDir(t)origWorkspaceDir, origDataDir := util.WorkspaceDir, util.DataDir@@ -223,7 +223,7 @@ func TestGetFileReaderCanReadHiddenNotebookFile(t *testing.T) {func TestGetFileReaderCanReadVisibleNotebookFile(t *testing.T) {previousConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())t.Cleanup(func() { model.Conf = previousConf })workspaceDir := testutil.PublicDataDir(t)origWorkspaceDir, origDataDir := util.WorkspaceDir, util.DataDir@@ -272,7 +272,7 @@ func TestGetFileReaderCanReadVisibleNotebookFile(t *testing.T) {func TestGetFileEditorCanReadHiddenNotebookFile(t *testing.T) {previousConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())t.Cleanup(func() { model.Conf = previousConf })workspaceDir := testutil.PublicDataDir(t)origWorkspaceDir, origDataDir := util.WorkspaceDir, util.DataDir@@ -321,7 +321,7 @@ func TestGetFileEditorCanReadHiddenNotebookFile(t *testing.T) {func TestGetFileDeniesNotebookSiyuanConf(t *testing.T) {previousConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())t.Cleanup(func() { model.Conf = previousConf })workspaceDir := testutil.PublicDataDir(t)origWorkspaceDir, origDataDir := util.WorkspaceDir, util.DataDirdiff --git a/kernel/api/filetree.go b/kernel/api/filetree.goindex e0459b6f8b..c3891ceea8 100644--- a/kernel/api/filetree.go+++ b/kernel/api/filetree.go@@ -867,7 +867,7 @@ func getDocCreateSavePathContract(c *gin.Context, request apicontract.FileTreeNonotebook := request.NotebookdocCreateSaveBox, docCreateSavePathTpl := model.ResolveDocCreateSaveLocation(notebook)- docCreateTemplatePath := model.Conf.FileTree.DocCreateTemplatePath+ docCreateTemplatePath := model.Conf.FileTree.Load().DocCreateTemplatePathif box := model.Conf.Box(notebook); nil != box {boxConf := box.GetConf()if "" != boxConf.DocCreateTemplatePath {@@ -896,19 +896,21 @@ func getDocCreateSavePathContract(c *gin.Context, request apicontract.FileTreeNovar getRefCreateSavePath = contractHandler(apicontract.GetRefCreateSavePath, getRefCreateSavePathContract)func getRefCreateSavePathContract(c *gin.Context, request apicontract.FileTreeNotebookRequest) apicontract.Response[apicontract.FileTreeSavePathData] {+ confFileTreeSnapshot := model.Conf.LoadFileTree()+ret := gulu.Ret.NewResult()notebook := request.Notebookbox := model.Conf.Box(notebook)var refCreateSaveBox string- refCreateSavePathTpl := model.Conf.FileTree.RefCreateSavePath+ refCreateSavePathTpl := confFileTreeSnapshot.RefCreateSavePathif nil != box {boxConf := box.GetConf()refCreateSaveBox = boxConf.RefCreateSaveBoxrefCreateSavePathTpl = boxConf.RefCreateSavePath}if "" == refCreateSaveBox && "" == refCreateSavePathTpl {- refCreateSaveBox = model.Conf.FileTree.RefCreateSaveBox+ refCreateSaveBox = confFileTreeSnapshot.RefCreateSaveBox}if "" != refCreateSaveBox {if nil == model.Conf.Box(refCreateSaveBox) {@@ -920,7 +922,7 @@ func getRefCreateSavePathContract(c *gin.Context, request apicontract.FileTreeNorefCreateSaveBox = notebook}if "" == refCreateSavePathTpl {- refCreateSavePathTpl = model.Conf.FileTree.RefCreateSavePath+ refCreateSavePathTpl = confFileTreeSnapshot.RefCreateSavePath}if refCreateSaveBox != notebook {@@ -942,12 +944,14 @@ func getRefCreateSavePathContract(c *gin.Context, request apicontract.FileTreeNovar getShorthandSavePath = contractHandler(apicontract.GetShorthandSavePath, getShorthandSavePathContract)func getShorthandSavePathContract(c *gin.Context, request apicontract.FileTreeNotebookRequest) apicontract.Response[apicontract.FileTreeSavePathData] {+ confFileTreeSnapshot := model.Conf.LoadFileTree()+ret := gulu.Ret.NewResult()notebook := request.Notebook- shorthandSaveBox := model.Conf.FileTree.ShorthandSaveBox- shorthandSavePathTpl := model.Conf.FileTree.ShorthandSavePath+ shorthandSaveBox := confFileTreeSnapshot.ShorthandSaveBox+ shorthandSavePathTpl := confFileTreeSnapshot.ShorthandSavePathif "" == shorthandSaveBox {shorthandSaveBox = notebook@@ -1142,6 +1146,8 @@ func searchDocsContract(c *gin.Context, request apicontract.FileTreeSearchRequesvar listDocsByPath = contractHandler(apicontract.ListDocsByPath, listDocsByPathContract)func listDocsByPathContract(c *gin.Context, request apicontract.FileTreeListRequest) apicontract.Response[apicontract.FileTreeListData] {+ confFileTreeSnapshot := model.Conf.LoadFileTree()+ret := gulu.Ret.NewResult()notebook := request.Notebook@@ -1155,7 +1161,7 @@ func listDocsByPathContract(c *gin.Context, request apicontract.FileTreeListRequ}if isEncryptedNotebookDeniedForPublish(c, notebook) {- return apicontract.Success(apicontract.FileTreeListData{Box: notebook, Path: p, Files: []*apicontract.FileTreeFile{}, EffectiveSortMode: model.Conf.FileTree.Sort})+ return apicontract.Success(apicontract.FileTreeListData{Box: notebook, Path: p, Files: []*apicontract.FileTreeFile{}, EffectiveSortMode: confFileTreeSnapshot.Sort})}options, decodeErr := request.Options()@@ -1178,7 +1184,7 @@ func listDocsByPathContract(c *gin.Context, request apicontract.FileTreeListRequ}}flashcard := options.Flashcard- maxListCount := model.Conf.FileTree.MaxListCount+ maxListCount := confFileTreeSnapshot.MaxListCountif options.MaxListCount != nil {// API `listDocsByPath` add an optional parameter `maxListCount` https://github.com/siyuan-note/siyuan/issues/7993maxListCount = int(*options.MaxListCount)@@ -1219,7 +1225,7 @@ func listDocsByPathContract(c *gin.Context, request apicontract.FileTreeListRequreturn apicontract.Failure[apicontract.FileTreeListData](-1, hintErr.Error())}if !ignoreHint {- if nil == util.NotificationsCfg || util.NotificationsCfg.DocTreeMaxList {+ if nil == util.NotificationsCfg.Load() || util.NotificationsCfg.Load().DocTreeMaxList {util.PushMsgWithApp(app, fmt.Sprintf(model.Conf.Language(48), len(files)), 7000)}}@@ -1266,7 +1272,7 @@ func getDocContract(c *gin.Context, request apicontract.FileTreeGetDocRequest) astartID, endID := "", ""if options.StartID != nil && options.EndID != nil {startID, endID = *options.StartID, *options.EndID- size = model.Conf.Editor.DynamicLoadBlocks+ size = model.Conf.Editor.Load().DynamicLoadBlocks}isBacklink := options.IsBacklinkoriginalRefBlockIDs := options.OriginalRefBlockIDsdiff --git a/kernel/api/filetree_test.go b/kernel/api/filetree_test.goindex db69df0437..3835463f07 100644--- a/kernel/api/filetree_test.go+++ b/kernel/api/filetree_test.go@@ -172,7 +172,7 @@ func TestAuthFilePublishAccessReturnsUniformFailure(t *testing.T) {oldLangs := util.Langsutil.DataDir = t.TempDir()model.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())model.Conf.Lang = "test"util.Langs = map[string]map[int]string{"test": {285: passwordIncorrect},@@ -307,7 +307,7 @@ func TestAuthFilePublishAccessThrottlesBruteForce(t *testing.T) {oldLangs := util.Langsutil.DataDir = t.TempDir()model.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())model.Conf.Lang = "test"util.Langs = map[string]map[int]string{"test": {285: "Password is incorrect", 354: passwordLocked},@@ -433,7 +433,7 @@ func TestPublishAccessConfigurationRejectsEncryptedNotebook(t *testing.T) {oldLangs := util.Langsutil.DataDir = t.TempDir()model.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())model.Conf.Lang = "test"util.Langs = map[string]map[int]string{"test": {313: "Encrypted notebooks do not support this operation"},@@ -531,7 +531,7 @@ func TestPublishReaderCannotBrowseEncryptedNotebook(t *testing.T) {oldConf := model.Confutil.DataDir = t.TempDir()model.Conf = model.NewAppConf()- model.Conf.FileTree = conf.NewFileTree()+ model.Conf.FileTree.Store(conf.NewFileTree())t.Cleanup(func() {util.DataDir = oldDataDirmodel.Conf = oldConf@@ -608,11 +608,11 @@ func TestGetDocOptionallyReturnsEmbeddedDocInfo(t *testing.T) {util.DataDir = filepath.Join(tempDir, "data")util.BlockTreeDBPath = filepath.Join(tempDir, "blocktree.db")model.Conf = model.NewAppConf()- model.Conf.Editor = conf.NewEditor()- model.Conf.Export = conf.NewExport()- model.Conf.FileTree = conf.NewFileTree()+ model.Conf.Editor.Store(conf.NewEditor())+ model.Conf.Export.Store(conf.NewExport())+ model.Conf.FileTree.Store(conf.NewFileTree())model.Conf.NotebookCrypto = conf.NewNotebookCrypto()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())box := &model.Box{ID: boxID}boxConf := conf.NewBoxConf()@@ -683,7 +683,7 @@ func TestGetDocOptionallyReturnsEmbeddedDocInfo(t *testing.T) {func TestFilterFileTreePublishAccess(t *testing.T) {previousConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())t.Cleanup(func() { model.Conf = previousConf })const (boxID = "20260725000000-boxid01"@@ -788,8 +788,8 @@ func TestListDocsByPathFiltersSubFileCountForPublishReader(t *testing.T) {oldPublishAccess := model.GetPublishAccess()util.DataDir = t.TempDir()model.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()- model.Conf.FileTree = conf.NewFileTree()+ model.Conf.Sync.Store(conf.NewSync())+ model.Conf.FileTree.Store(conf.NewFileTree())const testLang = "filetree-subfile-count-test"installAPITestTimeLangs(t, testLang)model.Conf.Lang = testLangdiff --git a/kernel/api/graph.go b/kernel/api/graph.goindex 3d90fa5a9d..d8a3de3a2b 100644--- a/kernel/api/graph.go+++ b/kernel/api/graph.go@@ -27,15 +27,13 @@ import (var resetGraph = contractHandler(apicontract.ResetGraph, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.ResetGraphData] {graph := conf.NewGlobalGraph()- model.Conf.Graph.Global = graph- model.Conf.Save()+ model.UpdateGraphConf(func(g *conf.Graph) bool { g.Global = graph; return true })return apicontract.Success(apicontract.ResetGraphData{Conf: globalGraphContract(graph)})})var resetLocalGraph = contractHandler(apicontract.ResetLocalGraph, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.ResetLocalGraphData] {graph := conf.NewLocalGraph()- model.Conf.Graph.Local = graph- model.Conf.Save()+ model.UpdateGraphConf(func(g *conf.Graph) bool { g.Local = graph; return true })return apicontract.Success(apicontract.ResetLocalGraphData{Conf: localGraphContract(graph)})})@@ -60,8 +58,7 @@ var setGraphConf = contractHandler(apicontract.SetGraphConf, func(c *gin.Contextreturn apicontract.Failure[apicontract.GraphConfigurationData](-1, err.Error())}if model.IsAdminRoleContext(c) && !model.IsReadOnlyRoleContext(c) {- model.Conf.Graph.Global = global- model.Conf.Save()+ model.UpdateGraphConf(func(g *conf.Graph) bool { g.Global = global; return true })}return apicontract.Success(apicontract.GlobalGraphConfiguration(globalGraphContract(global)))case "local":@@ -70,8 +67,7 @@ var setGraphConf = contractHandler(apicontract.SetGraphConf, func(c *gin.Contextreturn apicontract.Failure[apicontract.GraphConfigurationData](-1, err.Error())}if model.IsAdminRoleContext(c) && !model.IsReadOnlyRoleContext(c) {- model.Conf.Graph.Local = local- model.Conf.Save()+ model.UpdateGraphConf(func(g *conf.Graph) bool { g.Local = local; return true })}return apicontract.Success(apicontract.LocalGraphConfiguration(localGraphContract(local)))default:diff --git a/kernel/api/icon.go b/kernel/api/icon.goindex 95f0eb11bd..c1ab3fc997 100644--- a/kernel/api/icon.go+++ b/kernel/api/icon.go@@ -118,6 +118,8 @@ func darkenColor(hexColor string, factor float64) string {}var getDynamicIcon = contractHandler(apicontract.GetDynamicIcon, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.BinaryContent] {+ confAppearanceSnapshot := model.Conf.LoadAppearance()+// Add internal kernel API `/api/icon/getDynamicIcon` https://github.com/siyuan-note/siyuan/pull/12939iconType := c.Query("type")@@ -183,12 +185,12 @@ var getDynamicIcon = contractHandler(apicontract.GetDynamicIcon, func(c *gin.Con}var fonts []*conf.EditorFont- if "8" == iconType && nil != model.Conf.Appearance {- fonts = model.Conf.Appearance.GlobalFontFamilies+ if "8" == iconType && nil != confAppearanceSnapshot {+ fonts = confAppearanceSnapshot.GlobalFontFamilies}svg = applyDynamicIconFont(svg, fonts)- if !model.Conf.Editor.AllowSVGScript {+ if !model.Conf.Editor.Load().AllowSVGScript {var err errorsvg, err = util.SanitizeSVG(svg)if err != nil {diff --git a/kernel/api/icon_publish_access_test.go b/kernel/api/icon_publish_access_test.goindex 00c874fa79..ec70bad9b1 100644--- a/kernel/api/icon_publish_access_test.go+++ b/kernel/api/icon_publish_access_test.go@@ -75,9 +75,9 @@ func TestGetDynamicIconEnforcesPublishAccess(t *testing.T) {}model.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())model.Conf.Lang = "en"- model.Conf.Editor = conf.NewEditor()+ model.Conf.Editor.Store(conf.NewEditor())boxConf := conf.NewBoxConf()boxConf.Name = "Dynamic icon publish access"diff --git a/kernel/api/icon_test.go b/kernel/api/icon_test.goindex eeeea49d5e..40aba1e535 100644--- a/kernel/api/icon_test.go+++ b/kernel/api/icon_test.go@@ -24,8 +24,8 @@ import (func TestAPIContractDynamicIconGlobalFonts(t *testing.T) {oldConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.Editor = conf.NewEditor()- model.Conf.Appearance = conf.NewAppearance()+ model.Conf.Editor.Store(conf.NewEditor())+ model.Conf.Appearance.Store(conf.NewAppearance())t.Cleanup(func() { model.Conf = oldConf })const fallback = "-apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'"for _, test := range []struct {@@ -42,8 +42,8 @@ func TestAPIContractDynamicIconGlobalFonts(t *testing.T) {for _, allowScript := range []bool{false, true} {for _, iconType := range []string{"1", "2", "3", "4", "5", "6", "7", "8", "", "unknown"} {t.Run(fmt.Sprintf("%s/type%s/script%t", test.name, iconType, allowScript), func(t *testing.T) {- model.Conf.Appearance.GlobalFontFamilies = test.fonts- model.Conf.Editor.AllowSVGScript = allowScript+ model.Conf.Appearance.Load().GlobalFontFamilies = test.fonts+ model.Conf.Editor.Load().AllowSVGScript = allowScriptrecorder := httptest.NewRecorder()context, _ := gin.CreateTestContext(recorder)context.Request = httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/icon/getDynamicIcon?type=%s&content=Text&date=2026-09-29&lang=en", iconType), nil)@@ -115,7 +115,7 @@ func TestGenerateTypeEightSVGHandlesEmptyContent(t *testing.T) {func TestGetDynamicIconSetsSecurityHeaders(t *testing.T) {oldConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.Editor = conf.NewEditor()+ model.Conf.Editor.Store(conf.NewEditor())t.Cleanup(func() {model.Conf = oldConf})diff --git a/kernel/api/inline_style_test.go b/kernel/api/inline_style_test.goindex 3ba8129ce9..f826acef92 100644--- a/kernel/api/inline_style_test.go+++ b/kernel/api/inline_style_test.go@@ -208,7 +208,7 @@ func setupInlineStylesAPITest(t *testing.T) {t.Helper()oldDataDir, oldConf, oldReadOnly := util.DataDir, model.Conf, util.ReadOnlyutil.DataDir, model.Conf, util.ReadOnly = t.TempDir(), model.NewAppConf(), false- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())t.Cleanup(func() {util.DataDir, model.Conf, util.ReadOnly = oldDataDir, oldConf, oldReadOnly})diff --git a/kernel/api/lute.go b/kernel/api/lute.goindex db1ff8ae93..d5b8cca2ca 100644--- a/kernel/api/lute.go+++ b/kernel/api/lute.go@@ -177,7 +177,7 @@ var html2BlockDOM = contractHandler(apicontract.HTML2BlockDOM, func(c *gin.Conte}}- if util.ContainerStd == model.Conf.System.Container && !skipLocalAssets {+ if util.ContainerStd == model.Conf.System.Load().Container && !skipLocalAssets {// 处理本地资源文件复制ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering || ast.NodeLinkDest != n.Type {diff --git a/kernel/api/lute_authorization_test.go b/kernel/api/lute_authorization_test.goindex c1da27574e..1805e62e0f 100644--- a/kernel/api/lute_authorization_test.go+++ b/kernel/api/lute_authorization_test.go@@ -34,8 +34,8 @@ func TestSpinBlockDOMAuthorization(t *testing.T) {previousConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.Editor = &conf.Editor{}- model.Conf.Export = &conf.Export{}+ model.Conf.Editor.Store(&conf.Editor{})+ model.Conf.Export.Store(&conf.Export{})t.Cleanup(func() {model.Conf = previousConf})@@ -93,8 +93,8 @@ func TestSpinBlockDOMInputSizeLimit(t *testing.T) {previousConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.Editor = &conf.Editor{}- model.Conf.Export = &conf.Export{}+ model.Conf.Editor.Store(&conf.Editor{})+ model.Conf.Export.Store(&conf.Export{})t.Cleanup(func() {model.Conf = previousConf})diff --git a/kernel/api/lute_escape_test.go b/kernel/api/lute_escape_test.goindex c68e2b3e96..45c9beaa79 100644--- a/kernel/api/lute_escape_test.go+++ b/kernel/api/lute_escape_test.go@@ -18,11 +18,15 @@ import ()func TestHTML2BlockDOMContractEscapedText(t *testing.T) {- originalConf, originalMarkdown := model.Conf, util.MarkdownSettings+ originalConf, originalMarkdown := model.Conf, util.MarkdownSettings.Load()model.Conf = model.NewAppConf()- model.Conf.System = &conf.System{}+ model.Conf.System.Store(&conf.System{})t.Cleanup(func() {- model.Conf, util.MarkdownSettings = originalConf, originalMarkdown+ {+ derivedValue0, derivedValue1 := originalConf, originalMarkdown+ model.Conf = derivedValue0+ util.MarkdownSettings.Store(derivedValue1)+ }})gin.SetMode(gin.TestMode)router := gin.New()@@ -56,7 +60,7 @@ func TestHTML2BlockDOMContractEscapedText(t *testing.T) {settings.InlineAsterisk, settings.InlineUnderscore = syntax, syntaxsettings.InlineStrikethrough, settings.InlineMark = syntax, syntaxsettings.InlineSup, settings.InlineSub, settings.InlineMath = syntax, syntax, syntax- util.MarkdownSettings = &settings+ util.MarkdownSettings.Store(&settings)for _, preserve := range []bool{false, true} {for _, test := range tests {t.Run(test.name+"/syntax="+strconv.FormatBool(syntax)+"/preserve="+strconv.FormatBool(preserve), func(t *testing.T) {diff --git a/kernel/api/lute_iframe_test.go b/kernel/api/lute_iframe_test.goindex ed2015ed0a..c173889994 100644--- a/kernel/api/lute_iframe_test.go+++ b/kernel/api/lute_iframe_test.go@@ -32,7 +32,7 @@ import (func TestHTML2BlockDOMNormalizesIFramePosition(t *testing.T) {originalConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.System = &conf.System{}+ model.Conf.System.Store(&conf.System{})t.Cleanup(func() { model.Conf = originalConf })tests := []struct {diff --git a/kernel/api/lute_request_limit_test.go b/kernel/api/lute_request_limit_test.goindex 70b51de8d9..5c45225637 100644--- a/kernel/api/lute_request_limit_test.go+++ b/kernel/api/lute_request_limit_test.go@@ -46,7 +46,7 @@ func TestLimitHTML2BlockDOMRequestBody(t *testing.T) {func TestHTML2BlockDOMPreflightOmitsConvertedDOM(t *testing.T) {originalConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.System = &conf.System{}+ model.Conf.System.Store(&conf.System{})t.Cleanup(func() { model.Conf = originalConf })gin.SetMode(gin.TestMode)diff --git a/kernel/api/lute_text_style_test.go b/kernel/api/lute_text_style_test.goindex 1d79c0a835..2402be06da 100644--- a/kernel/api/lute_text_style_test.go+++ b/kernel/api/lute_text_style_test.go@@ -33,7 +33,7 @@ import (func TestHTML2BlockDOMQuotedFontFamily(t *testing.T) {originalConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.System = &conf.System{}+ model.Conf.System.Store(&conf.System{})t.Cleanup(func() { model.Conf = originalConf })gin.SetMode(gin.TestMode)for _, tag := range []string{"p", "h2", "td"} {@@ -95,7 +95,7 @@ func TestHTML2BlockDOMQuotedFontFamily(t *testing.T) {func TestHTML2BlockDOMMatchesElementsByDefault(t *testing.T) {originalConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.System = &conf.System{}+ model.Conf.System.Store(&conf.System{})t.Cleanup(func() { model.Conf = originalConf })gin.SetMode(gin.TestMode)input := `<h2 style="color:gray;font-family:Arial;font-size:20px"><span style="font-weight:bold">heading</span></h2>` +@@ -131,7 +131,7 @@ func TestHTML2BlockDOMMatchesElementsByDefault(t *testing.T) {func TestHTML2BlockDOMDoesNotLeakWhitespaceTextMarkStyles(t *testing.T) {originalConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.System = &conf.System{}+ model.Conf.System.Store(&conf.System{})t.Cleanup(func() { model.Conf = originalConf })gin.SetMode(gin.TestMode)input := `<h3 style="color: rgb(31, 35, 40); font-family: Arial; font-size: 20px; font-weight: 600">` +diff --git a/kernel/api/mcp_oauth.go b/kernel/api/mcp_oauth.goindex d1108bcb1d..cd105d5088 100644--- a/kernel/api/mcp_oauth.go+++ b/kernel/api/mcp_oauth.go@@ -266,6 +266,8 @@ var mcpOAuthPage = template.Must(template.New("mcp-oauth").Parse(`<!doctype html</form>{{end}}</main></body></html>`))func mcpOAuthHTML(c *gin.Context, status int, ticket string, client apicontract.MCPOAuthClient) apicontract.Response[apicontract.BinaryContent] {+ confAppearanceSnapshot := model.Conf.LoadAppearance()+mcpOAuthHeaders(c)if ticket != "" {// 同源表单提交需要保留 Origin;跨站导航不发送 Referer。@@ -275,7 +277,7 @@ func mcpOAuthHTML(c *gin.Context, status int, ticket string, client apicontract.c.Header("X-Frame-Options", "DENY")data := map[string]string{"Title": mcpOAuthLanguage("mcpOAuthServer"), "Workspace": util.WorkspaceName, "Name": client.Name, "Redirect": client.RedirectURI,"Ticket": ticket, "Tip": mcpOAuthLanguage("mcpOAuthConsentTip"), "Approve": mcpOAuthLanguage("confirm"), "Cancel": mcpOAuthLanguage("cancel"), "Theme": "/appearance/themes/daylight/theme.css", "Lang": model.Conf.Lang, "Mode": "light"}- if model.Conf.Appearance != nil && model.Conf.Appearance.Mode == 1 {+ if confAppearanceSnapshot != nil && confAppearanceSnapshot.Mode == 1 {data["Theme"] = "/appearance/themes/midnight/theme.css"data["Mode"] = "dark"}diff --git a/kernel/api/notebook.go b/kernel/api/notebook.goindex 519c5c6372..4e211d0089 100644--- a/kernel/api/notebook.go+++ b/kernel/api/notebook.go@@ -426,7 +426,7 @@ var lsNotebooks = contractHandler(apicontract.ListNotebooks, func(c *gin.Context}}}- sortNotebooksBySubFileCount(notebooks, model.Conf.FileTree.Sort)+ sortNotebooksBySubFileCount(notebooks, model.Conf.FileTree.Load().Sort)}var values []*apicontract.Notebookdiff --git a/kernel/api/notebook_patch_test.go b/kernel/api/notebook_patch_test.goindex 04aeb70c0a..2ecea4d1a7 100644--- a/kernel/api/notebook_patch_test.go+++ b/kernel/api/notebook_patch_test.go@@ -20,8 +20,8 @@ func TestAPIContractNotebookConfPatchPersistence(t *testing.T) {oldConf, oldDataDir := model.Conf, util.DataDirutil.DataDir = t.TempDir()model.Conf = model.NewAppConf()- model.Conf.FileTree = conf.NewFileTree()- model.Conf.Sync = conf.NewSync()+ model.Conf.FileTree.Store(conf.NewFileTree())+ model.Conf.Sync.Store(conf.NewSync())t.Cleanup(func() { model.Conf, util.DataDir = oldConf, oldDataDir })const id = "20260101000000-abcdefg"path := filepath.Join(util.DataDir, id, ".siyuan", "conf.json")diff --git a/kernel/api/notebook_security_test.go b/kernel/api/notebook_security_test.goindex b34e392816..32c6af97d8 100644--- a/kernel/api/notebook_security_test.go+++ b/kernel/api/notebook_security_test.go@@ -78,8 +78,8 @@ func TestGetNotebookInfoHidesInvisibleNotebookFromReader(t *testing.T) {oldConf, oldDataDir := model.Conf, util.DataDirutil.DataDir = t.TempDir()model.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()- model.Conf.FileTree = conf.NewFileTree()+ model.Conf.Sync.Store(conf.NewSync())+ model.Conf.FileTree.Store(conf.NewFileTree())const testLang = "notebook-security-test"oldTimeLang, hadTimeLang := util.TimeLangs[testLang]util.TimeLangs[testLang] = map[string]any{@@ -218,8 +218,8 @@ func TestGetNotebookInfoExcludesPublishExcludedDocumentsForReader(t *testing.T)oldPublishAccess := model.GetPublishAccess()util.DataDir = t.TempDir()model.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()- model.Conf.FileTree = conf.NewFileTree()+ model.Conf.Sync.Store(conf.NewSync())+ model.Conf.FileTree.Store(conf.NewFileTree())const testLang = "notebook-info-publish-test"installAPITestTimeLangs(t, testLang)model.Conf.Lang = testLang@@ -348,7 +348,7 @@ func TestSetNotebookIconRejectsPathTraversal(t *testing.T) {oldConf, oldDataDir := model.Conf, util.DataDirutil.DataDir = t.TempDir()model.Conf = model.NewAppConf()- model.Conf.FileTree = conf.NewFileTree()+ model.Conf.FileTree.Store(conf.NewFileTree())t.Cleanup(func() {model.Conf, util.DataDir = oldConf, oldDataDir})@@ -391,7 +391,7 @@ func TestGetNotebookConfHidesEncryptedNotebookFromReader(t *testing.T) {oldConf, oldDataDir := model.Conf, util.DataDirutil.DataDir = t.TempDir()model.Conf = model.NewAppConf()- model.Conf.FileTree = conf.NewFileTree()+ model.Conf.FileTree.Store(conf.NewFileTree())t.Cleanup(func() {model.Conf, util.DataDir = oldConf, oldDataDir})@@ -492,7 +492,7 @@ func TestGetEncryptedNotebookStatusAuthorization(t *testing.T) {t.Fatal(err)}model.Conf = model.NewAppConf()- model.Conf.FileTree = conf.NewFileTree()+ model.Conf.FileTree.Store(conf.NewFileTree())model.Conf.NotebookCrypto = conf.NewNotebookCrypto()t.Cleanup(func() {model.Conf, util.DataDir, util.HistoryDir = oldConf, oldDataDir, oldHistoryDirdiff --git a/kernel/api/notebook_test.go b/kernel/api/notebook_test.goindex 746d6c9836..bd94a0db26 100644--- a/kernel/api/notebook_test.go+++ b/kernel/api/notebook_test.go@@ -40,10 +40,10 @@ func TestListNotebooksSortsBySubDocCount(t *testing.T) {oldPublishAccess := model.GetPublishAccess()util.DataDir = t.TempDir()model.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()- model.Conf.FileTree = conf.NewFileTree()+ model.Conf.Sync.Store(conf.NewSync())+ model.Conf.FileTree.Store(conf.NewFileTree())model.Conf.NotebookCrypto = conf.NewNotebookCrypto()- *model.Conf.FileTree.BoxDocEnabled = true+ *model.Conf.FileTree.Load().BoxDocEnabled = truet.Cleanup(func() {if err := model.SetPublishAccess(oldPublishAccess); err != nil {t.Errorf("restore publish access failed: %v", err)@@ -85,7 +85,7 @@ func TestListNotebooksSortsBySubDocCount(t *testing.T) {}for _, test := range tests {t.Run(test.name, func(t *testing.T) {- model.Conf.FileTree.Sort = test.sortMode+ model.Conf.FileTree.Load().Sort = test.sortModenotebooks := requestNotebookList(t, model.RoleAdministrator)if actual := notebookIDs(notebooks); !slices.Equal(actual, test.expected) {t.Fatalf("unexpected notebook order: %v", actual)@@ -100,7 +100,7 @@ func TestListNotebooksSortsBySubDocCount(t *testing.T) {if err := model.SetPublishAccess(publishAccess); err != nil {t.Fatal(err)}- model.Conf.FileTree.Sort = util.SortModeSubDocCountDESC+ model.Conf.FileTree.Load().Sort = util.SortModeSubDocCountDESCnotebooks := requestNotebookList(t, model.RoleReader)expected := []string{boxIDs[1], boxIDs[2], boxIDs[4], boxIDs[0], boxIDs[3]}if actual := notebookIDs(notebooks); !slices.Equal(actual, expected) {diff --git a/kernel/api/ocr.go b/kernel/api/ocr.goindex 8edd04b118..d7a392968e 100644--- a/kernel/api/ocr.go+++ b/kernel/api/ocr.go@@ -57,7 +57,9 @@ func ocrModelPayload(id string) apicontract.OCRModel {return apicontract.OCRModel{ID: id, Name: name, BuiltIn: id == "tiny"}}-var setOCRConfig = contractHandler(apicontract.SetOCRConfig, serializeSetting("ocr", func(c *gin.Context, request apicontract.SettingOCR) apicontract.Response[apicontract.SettingOCR] {+var setOCRConfig = contractHandler(apicontract.SetOCRConfig, applyOCRSetting)++func applyOCRSetting(c *gin.Context, request apicontract.SettingOCR) apicontract.Response[apicontract.SettingOCR] {value := model.Conf.GetOCR()value.Provider, value.Model, value.Auto = request.Provider, request.Model, request.Autoif request.AIModelID != nil {@@ -73,7 +75,7 @@ var setOCRConfig = contractHandler(apicontract.SetOCRConfig, serializeSetting("oreturn apicontract.Failure[apicontract.SettingOCR](-1, err.Error())}return apicontract.Success(ocrConfigPayload(model.Conf.GetOCR()))-}))+}var importOCRModels = contractHandler(apicontract.ImportOCRModels, func(c *gin.Context, request apicontract.ImportOCRModelsRequest) apicontract.Response[apicontract.OCRModel] {ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Minute)diff --git a/kernel/api/petal_test.go b/kernel/api/petal_test.goindex 4dbf1602b0..f16ccdc0e6 100644--- a/kernel/api/petal_test.go+++ b/kernel/api/petal_test.go@@ -36,8 +36,8 @@ func TestSetPetalPublishEnabledAuthorization(t *testing.T) {originalConf := model.ConforiginalDataDir := util.DataDirmodel.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()- model.Conf.Bazaar = &conf.Bazaar{Trust: true}+ model.Conf.Sync.Store(conf.NewSync())+ model.Conf.Bazaar.Store(&conf.Bazaar{Trust: true})util.DataDir = t.TempDir()t.Cleanup(func() {model.Conf = originalConfdiff --git a/kernel/api/plugin_publish_test.go b/kernel/api/plugin_publish_test.goindex c1f3e05c1d..f24a1fa9a5 100644--- a/kernel/api/plugin_publish_test.go+++ b/kernel/api/plugin_publish_test.go@@ -21,8 +21,8 @@ func TestAPIContractPluginPublish(t *testing.T) {util.WorkspaceDir = t.TempDir()util.DataDir, util.ConfDir = filepath.Join(util.WorkspaceDir, "data"), filepath.Join(util.WorkspaceDir, "conf")model.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()- model.Conf.Bazaar = &conf.Bazaar{Trust: true}+ model.Conf.Sync.Store(conf.NewSync())+ model.Conf.Bazaar.Store(&conf.Bazaar{Trust: true})t.Cleanup(func() {util.WorkspaceDir, util.DataDir, util.ConfDir, model.Conf = oldWorkspace, oldData, oldConfDir, oldConf})diff --git a/kernel/api/publish_encrypted_test.go b/kernel/api/publish_encrypted_test.goindex 3d98701cf4..05405f1318 100644--- a/kernel/api/publish_encrypted_test.go+++ b/kernel/api/publish_encrypted_test.go@@ -36,7 +36,7 @@ func TestPublishReaderSearchAndBacklinkEncryptedNotebook(t *testing.T) {oldConf, oldDataDir := model.Conf, util.DataDirutil.DataDir = t.TempDir()model.Conf = model.NewAppConf()- model.Conf.Editor = conf.NewEditor()+ model.Conf.Editor.Store(conf.NewEditor())t.Cleanup(func() {model.Conf, util.DataDir = oldConf, oldDataDir})diff --git a/kernel/api/ref.go b/kernel/api/ref.goindex f4192c3066..3767e98979 100644--- a/kernel/api/ref.go+++ b/kernel/api/ref.go@@ -68,7 +68,7 @@ var getBackmentionDoc = contractHandler(apicontract.GetBackmentionDoc, func(c *greturn apicontract.Failure[apicontract.BacklinkContextData](1, err.Error())}}- containChildren := model.Conf.Editor.BacklinkContainChildren+ containChildren := model.Conf.Editor.Load().BacklinkContainChildrenif request.ContainChildren != nil {containChildren = *request.ContainChildren}@@ -148,7 +148,7 @@ var getBacklinkDoc = contractHandler(apicontract.GetBacklinkDoc, func(c *gin.Conreturn apicontract.Failure[apicontract.BacklinkContextData](1, err.Error())}}- containChildren := model.Conf.Editor.BacklinkContainChildren+ containChildren := model.Conf.Editor.Load().BacklinkContainChildrenif request.ContainChildren != nil {containChildren = *request.ContainChildren}@@ -213,7 +213,7 @@ var getBacklink2 = contractHandler(apicontract.GetBacklink2, func(c *gin.Contextif request.MentionSort != nil {mentionSort, _ = strconv.Atoi(*request.MentionSort)}- containChildren := model.Conf.Editor.BacklinkContainChildren+ containChildren := model.Conf.Editor.Load().BacklinkContainChildrenif request.ContainChildren != nil {containChildren = *request.ContainChildren}diff --git a/kernel/api/repo.go b/kernel/api/repo.goindex 46b9b591c1..152111bc83 100644--- a/kernel/api/repo.go+++ b/kernel/api/repo.go@@ -30,6 +30,7 @@ import ("github.com/siyuan-note/dejavu""github.com/siyuan-note/dejavu/entity""github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util"@@ -41,8 +42,7 @@ var setRepoIndexRetentionDays = contractHandler(apicontract.SetRepoIndexRetentiodaysInt = 180}- model.Conf.Repo.IndexRetentionDays = daysInt- model.Conf.Save()+ model.UpdateRepoConf(func(s *conf.Repo) { s.IndexRetentionDays = daysInt })return apicontract.Success(apicontract.Null{})})@@ -53,8 +53,7 @@ var setRetentionIndexesDaily = contractHandler(apicontract.SetRetentionIndexesDaindexesInt = 180}- model.Conf.Repo.RetentionIndexesDaily = indexesInt- model.Conf.Save()+ model.UpdateRepoConf(func(s *conf.Repo) { s.RetentionIndexesDaily = indexesInt })return apicontract.Success(apicontract.Null{})})@@ -344,7 +343,7 @@ var initRepoKeyFromPassphrase = contractHandler(apicontract.InitRepoKeyFromPasspreturn apicontract.FailureWithTimeout[apicontract.RepoKeyData](-1, fmt.Sprintf(model.Conf.Language(137), err), 5000)}- return apicontract.Success(apicontract.RepoKeyData{Key: base64.StdEncoding.EncodeToString(model.Conf.Repo.Key)})+ return apicontract.Success(apicontract.RepoKeyData{Key: base64.StdEncoding.EncodeToString(model.Conf.Repo.Load().Key)})})var initRepoKey = contractHandler(apicontract.InitRepoKey, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.RepoKeyData] {@@ -352,7 +351,7 @@ var initRepoKey = contractHandler(apicontract.InitRepoKey, func(c *gin.Context,return apicontract.FailureWithTimeout[apicontract.RepoKeyData](-1, fmt.Sprintf(model.Conf.Language(137), err), 5000)}- return apicontract.Success(apicontract.RepoKeyData{Key: base64.StdEncoding.EncodeToString(model.Conf.Repo.Key)})+ return apicontract.Success(apicontract.RepoKeyData{Key: base64.StdEncoding.EncodeToString(model.Conf.Repo.Load().Key)})})var resetRepo = contractHandler(apicontract.ResetRepo, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.Null] {diff --git a/kernel/api/repo_snapshot_test.go b/kernel/api/repo_snapshot_test.goindex 0ee17308a4..a4fb675404 100644--- a/kernel/api/repo_snapshot_test.go+++ b/kernel/api/repo_snapshot_test.go@@ -16,7 +16,7 @@ func TestSnapshotAPIErrors(t *testing.T) {original := model.Conft.Cleanup(func() { model.Conf = original })model.Conf = model.NewAppConf()- model.Conf.Repo = conf.NewRepo()+ model.Conf.Repo.Store(conf.NewRepo())gin.SetMode(gin.TestMode)engine := gin.New()engine.POST("/api/repo/createSnapshot", createSnapshot)diff --git a/kernel/api/search.go b/kernel/api/search.goindex b6f3da64f3..e048bdcaf4 100644--- a/kernel/api/search.go+++ b/kernel/api/search.go@@ -86,7 +86,7 @@ var fullTextSearchAssetContent = contractHandler(apicontract.FullTextSearchAssetsearchPage, searchPageSize := page, pageSizeif isReadOnlyRole {searchPage = 1- searchPageSize = model.Conf.Search.Limit+ searchPageSize = model.Conf.Search.Load().Limit}assetContents, matchedAssetCount, pageCount, err := model.FullTextSearchAssetContent(query, types, method, orderBy, searchPage, searchPageSize)if err != nil {@@ -141,7 +141,7 @@ var findReplace = contractHandler(apicontract.FindReplace, func(c *gin.Context,})var searchAsset = contractHandler(apicontract.SearchAssetByName, func(c *gin.Context, request apicontract.SearchAssetRequest) apicontract.Response[[]*apicontract.SearchAsset] {- page, pageSize := 1, model.Conf.Search.Limit+ page, pageSize := 1, model.Conf.Search.Load().Limitif request.Page != nil {page = *request.Page}diff --git a/kernel/api/search_fts_injection_test.go b/kernel/api/search_fts_injection_test.goindex 335206bfcd..b247ba9f9d 100644--- a/kernel/api/search_fts_injection_test.go+++ b/kernel/api/search_fts_injection_test.go@@ -90,12 +90,12 @@ func TestFullTextSearchBlockFTSMatchInjection(t *testing.T) {model.Conf = model.NewAppConf()model.Conf.Lang = "en"- model.Conf.FileTree = conf.NewFileTree()- model.Conf.Editor = conf.NewEditor()- model.Conf.Export = conf.NewExport()- model.Conf.Search = conf.NewSearch()+ model.Conf.FileTree.Store(conf.NewFileTree())+ model.Conf.Editor.Store(conf.NewEditor())+ model.Conf.Export.Store(conf.NewExport())+ model.Conf.Search.Store(conf.NewSearch())model.Conf.NotebookCrypto = conf.NewNotebookCrypto()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())const boxID = "20260826000000-b0xb0x1"const docID = "20260826000001-aabbccd"diff --git a/kernel/api/search_publish_exclusion_test.go b/kernel/api/search_publish_exclusion_test.goindex 3dfad0f7f7..f4b7b8529b 100644--- a/kernel/api/search_publish_exclusion_test.go+++ b/kernel/api/search_publish_exclusion_test.go@@ -90,12 +90,12 @@ func TestPublishSearchCountExclusion(t *testing.T) {model.Conf = model.NewAppConf()model.Conf.Lang = "en"- model.Conf.FileTree = conf.NewFileTree()- model.Conf.Editor = conf.NewEditor()- model.Conf.Export = conf.NewExport()- model.Conf.Search = conf.NewSearch()+ model.Conf.FileTree.Store(conf.NewFileTree())+ model.Conf.Editor.Store(conf.NewEditor())+ model.Conf.Export.Store(conf.NewExport())+ model.Conf.Search.Store(conf.NewSearch())model.Conf.NotebookCrypto = conf.NewNotebookCrypto()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())const boxID = "20260823000000-b0xb0x1"const publicID = "20260823000001-aabbccd"diff --git a/kernel/api/setting.go b/kernel/api/setting.goindex 9809df8a45..b57f9b8559 100644--- a/kernel/api/setting.go+++ b/kernel/api/setting.go@@ -30,28 +30,21 @@ import (mcpclient "github.com/siyuan-note/siyuan/kernel/mcp/client""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/server/proxy"- "github.com/siyuan-note/siyuan/kernel/sql"- "github.com/siyuan-note/siyuan/kernel/task""github.com/siyuan-note/siyuan/kernel/util")var (- bazaarPetalStateMu sync.Mutex- bazaarPetalStateRevision uint64+ bazaarPetalStateMu sync.Mutex)var setEditorReadOnly = contractHandler(apicontract.SetEditorReadOnly, func(c *gin.Context, request apicontract.EditorReadOnlyRequest) apicontract.Response[apicontract.Null] {- oldReadOnly := model.Conf.Editor.ReadOnly- model.Conf.Editor.ReadOnly = request.ReadOnly- model.Conf.Save()- if oldReadOnly != model.Conf.Editor.ReadOnly {- util.BroadcastByType("protyle", "readonly", 0, "", model.Conf.Editor.ReadOnly)- util.BroadcastByType("main", "readonly", 0, "", model.Conf.Editor.ReadOnly)- }+ model.UpdateEditorConf(func(s *conf.Editor) { s.ReadOnly = request.ReadOnly })return apicontract.Success(apicontract.Null{})})-var setConfSnippet = contractHandler(apicontract.SetConfSnippet, func(c *gin.Context, request apicontract.SetConfSnippetRequest) (ret apicontract.Response[*apicontract.SettingSnpt]) {+var setConfSnippet = contractHandler(apicontract.SetConfSnippet, applySnippetSetting)++func applySnippetSetting(c *gin.Context, request apicontract.SetConfSnippetRequest) (ret apicontract.Response[*apicontract.SettingSnpt]) {if err := request.ConfigError(); err != nil {return apicontract.Failure[*apicontract.SettingSnpt](-1, err.Error())}@@ -66,33 +59,35 @@ var setConfSnippet = contractHandler(apicontract.SetConfSnippet, func(c *gin.Conreturn}- model.Conf.Snippet = snippet- model.Conf.Save()+ issues, applyErr := model.ApplyConfSection("snippet", snippet)+ recordSettingIssues(c, issues)+ err = applyErr+ if err != nil {+ return apicontract.Failure[*apicontract.SettingSnpt](-1, err.Error())+ }- ret = apicontract.Success(settingSnptPayload(snippet))- model.PushReloadSnippet(snippet)+ ret = apicontract.Success(settingSnptPayload(model.Conf.Snippet.Load()))return-})+}var addVirtualBlockRefExclude = contractHandler(apicontract.AddVirtualBlockRefExclude, func(c *gin.Context, request apicontract.VirtualBlockRefRequest) apicontract.Response[apicontract.Null] {model.AddVirtualBlockRefExclude(request.Keywords)- util.BroadcastByType("main", "setConf", 0, "", model.Conf)return apicontract.Success(apicontract.Null{})})var addVirtualBlockRefInclude = contractHandler(apicontract.AddVirtualBlockRefInclude, func(c *gin.Context, request apicontract.VirtualBlockRefRequest) apicontract.Response[apicontract.Null] {model.AddVirtualBlockRefInclude(request.Keywords)- util.BroadcastByType("main", "setConf", 0, "", model.Conf)return apicontract.Success(apicontract.Null{})})var refreshVirtualBlockRef = contractHandler(apicontract.RefreshVirtualBlockRef, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.Null] {model.ResetVirtualBlockRefCache()- util.BroadcastByType("main", "setConf", 0, "", model.Conf)return apicontract.Success(apicontract.Null{})})-var setBazaar = contractHandler(apicontract.SetBazaar, func(c *gin.Context, request apicontract.SetBazaarRequest) (ret apicontract.Response[*apicontract.SettingBazaar]) {+var setBazaar = contractHandler(apicontract.SetBazaar, applyBazaarSetting)++func applyBazaarSetting(c *gin.Context, request apicontract.SetBazaarRequest) (ret apicontract.Response[*apicontract.SettingBazaar]) {if err := request.ConfigError(); err != nil {return apicontract.Failure[*apicontract.SettingBazaar](-1, err.Error())}@@ -110,41 +105,25 @@ var setBazaar = contractHandler(apicontract.SetBazaar, func(c *gin.Context, requbazaarPetalStateMu.Lock()defer bazaarPetalStateMu.Unlock()- petalsEnabled := model.IsPetalsEnabled()- petalDisabled := model.Conf.Bazaar.PetalDisabled- model.Conf.Bazaar = bazaar- model.Conf.Save()- newPetalsEnabled := model.IsPetalsEnabled()- if petalsEnabled != newPetalsEnabled {- setKernelPluginsEnabled(newPetalsEnabled)- }- util.BroadcastByType("main", "setConf", 0, "", model.Conf)- if petalsEnabled != newPetalsEnabled || petalDisabled != bazaar.PetalDisabled {- bazaarPetalStateRevision++- model.PushReloadAllEnabledPlugins(newPetalsEnabled, bazaar.PetalDisabled, bazaarPetalStateRevision, true)+ issues, applyErr := model.ApplyConfSection("bazaar", bazaar)+ recordSettingIssues(c, issues)+ err = applyErr+ if err != nil {+ return apicontract.Failure[*apicontract.SettingBazaar](-1, err.Error())}- ret = apicontract.Success(settingBazaarPayload(bazaar))+ ret = apicontract.Success(settingBazaarPayload(model.Conf.Bazaar.Load()))return-})+}var setBazaarPetalDisabled = contractHandler(apicontract.SetBazaarPetalDisabled, func(c *gin.Context, request apicontract.SettingPetalDisabledRequest) apicontract.Response[apicontract.SettingPetalDisabledData] {petalDisabled := request.PetalDisabledbazaarPetalStateMu.Lock()defer bazaarPetalStateMu.Unlock()- petalsEnabled := model.IsPetalsEnabled()- changed := model.Conf.Bazaar.PetalDisabled != petalDisabled- model.Conf.Bazaar.PetalDisabled = petalDisabled- model.Conf.Save()+ changed := model.Conf.Bazaar.Load().PetalDisabled != petalDisabled+ model.UpdateBazaarConf(func(s *conf.Bazaar) { s.PetalDisabled = petalDisabled })newPetalsEnabled := model.IsPetalsEnabled()- if petalsEnabled != newPetalsEnabled {- setKernelPluginsEnabled(newPetalsEnabled)- }- util.BroadcastByType("main", "setConf", 0, "", model.Conf)- if changed {- bazaarPetalStateRevision++- }- payload := model.PushReloadAllEnabledPlugins(newPetalsEnabled, petalDisabled, bazaarPetalStateRevision, changed)+ payload := model.PluginReloadPayload(newPetalsEnabled, petalDisabled, model.BazaarPetalStateRevision.Load(), changed)encoded, err := gulu.JSON.MarshalJSON(payload)if err != nil {return apicontract.Failure[apicontract.SettingPetalDisabledData](-1, err.Error())@@ -156,19 +135,7 @@ var setBazaarPetalDisabled = contractHandler(apicontract.SetBazaarPetalDisabled,return apicontract.Success(data)})-func setKernelPluginsEnabled(enabled bool) {- if enabled {- if model.OnKernelPluginsStart != nil {- model.OnKernelPluginsStart()- }- return- }- if model.OnKernelPluginsStop != nil {- model.OnKernelPluginsStop()- }-}--var setAI = contractHandler(apicontract.SetAI, serializeSetting("ai", applyAISetting))+var setAI = contractHandler(apicontract.SetAI, applyAISetting)func applyAISetting(c *gin.Context, request apicontract.SetAIRequest) (ret apicontract.Response[*apicontract.SettingAI]) {if err := request.ConfigError(); err != nil {@@ -184,11 +151,11 @@ func applyAISetting(c *gin.Context, request apicontract.SetAIRequest) (ret apicoret = apicontract.Failure[*apicontract.SettingAI](-1, err.Error())return}- if model.Conf.AI != nil {+ if model.Conf.AI.Load() != nil {if ai.Decision == nil {- ai.Decision = model.Conf.AI.Decision.Clone()+ ai.Decision = model.Conf.AI.Load().Decision.Clone()} else {- ai.Decision.MergePrevious(model.Conf.AI.Decision)+ ai.Decision.MergePrevious(model.Conf.AI.Load().Decision)}}if ai.MCP != nil {@@ -205,20 +172,19 @@ func applyAISetting(c *gin.Context, request apicontract.SetAIRequest) (ret apico}var oldServers []conf.MCPServer- if model.Conf.AI != nil && model.Conf.AI.MCP != nil {- oldServers = append(oldServers, model.Conf.AI.MCP.Servers...)+ if model.Conf.AI.Load() != nil && model.Conf.AI.Load().MCP != nil {+ oldServers = append(oldServers, model.Conf.AI.Load().MCP.Servers...)}if ai.MCP != nil {preserveMCPServerIDs(oldServers, ai.MCP.Servers)}- ai.Normalize()- ai.ReconcileModelIDs()+ ai = conf.NormalizeAI(ai)model.Conf.SetAI(ai)mcpserver.RefreshToolExposure()// MCP 配置可能变更(开关切换、编辑、增删 server),异步重连让连接立即跟上。- if model.Conf.AI.MCP != nil {- newServers := model.Conf.AI.MCP.Servers+ if model.Conf.AI.Load().MCP != nil {+ newServers := model.Conf.AI.Load().MCP.ServersoldByID := make(map[string]conf.MCPServer, len(oldServers))newByID := make(map[string]conf.MCPServer, len(newServers))for _, server := range oldServers {@@ -248,7 +214,7 @@ func applyAISetting(c *gin.Context, request apicontract.SetAIRequest) (ret apico}}- ret = apicontract.Success(settingAIPayload(model.Conf.AI))+ ret = apicontract.Success(settingAIPayload(model.Conf.AI.Load()))return}@@ -264,7 +230,7 @@ func preserveMCPServerIDs(oldServers, newServers []conf.MCPServer) {}}-var setSecrets = contractHandler(apicontract.SetSecrets, serializeSetting("secrets", applySecretsSetting))+var setSecrets = contractHandler(apicontract.SetSecrets, applySecretsSetting)func applySecretsSetting(c *gin.Context, request apicontract.SetSecretsRequest) (ret apicontract.Response[*apicontract.SettingSecrets]) {if err := request.ConfigError(); err != nil {@@ -281,15 +247,19 @@ func applySecretsSetting(c *gin.Context, request apicontract.SetSecretsRequest)return}- model.Conf.Secrets = secrets- model.Conf.Save()+ issues, applyErr := model.ApplyConfSection("secrets", secrets)+ recordSettingIssues(c, issues)+ err = applyErr+ if err != nil {+ return apicontract.Failure[*apicontract.SettingSecrets](-1, err.Error())+ }reconnectStdioMCPWithEnvironment()- ret = apicontract.Success(settingSecretsPayload(model.Conf.Secrets))+ ret = apicontract.Success(settingSecretsPayload(model.Conf.Secrets.Load()))return}-var setVariables = contractHandler(apicontract.SetVariables, serializeSetting("variables", applyVariablesSetting))+var setVariables = contractHandler(apicontract.SetVariables, applyVariablesSetting)func applyVariablesSetting(c *gin.Context, request apicontract.SetVariablesRequest) (ret apicontract.Response[*apicontract.SettingVariables]) {if err := request.ConfigError(); err != nil {@@ -306,21 +276,27 @@ func applyVariablesSetting(c *gin.Context, request apicontract.SetVariablesRequereturn}- model.Conf.Variables = variables- model.Conf.Save()+ issues, applyErr := model.ApplyConfSection("variables", variables)+ recordSettingIssues(c, issues)+ err = applyErr+ if err != nil {+ return apicontract.Failure[*apicontract.SettingVariables](-1, err.Error())+ }reconnectStdioMCPWithEnvironment()- ret = apicontract.Success(settingVariablesPayload(model.Conf.Variables))+ ret = apicontract.Success(settingVariablesPayload(model.Conf.Variables.Load()))return}func reconnectStdioMCPWithEnvironment() {- if model.Conf.AI == nil || model.Conf.AI.MCP == nil {+ confAISnapshot := model.Conf.LoadAI()++ if confAISnapshot == nil || confAISnapshot.MCP == nil {return}- serverIDs := stdioMCPServerIDsWithEnvironment(model.Conf.AI.MCP.Servers)+ serverIDs := stdioMCPServerIDsWithEnvironment(confAISnapshot.MCP.Servers)if len(serverIDs) > 0 {- mcpclient.ReconnectMCPAsync(model.Conf.AI.MCP.Servers, serverIDs, nil)+ mcpclient.ReconnectMCPAsync(confAISnapshot.MCP.Servers, serverIDs, nil)}}@@ -334,7 +310,7 @@ func stdioMCPServerIDsWithEnvironment(servers []conf.MCPServer) []string {return serverIDs}-var setFlashcard = contractHandler(apicontract.SetFlashcard, serializeSetting("flashcard", applyFlashcardSetting))+var setFlashcard = contractHandler(apicontract.SetFlashcard, applyFlashcardSetting)func applyFlashcardSetting(c *gin.Context, request apicontract.SetFlashcardRequest) (ret apicontract.Response[*apicontract.SettingFlashcard]) {if err := request.ConfigError(); err != nil {@@ -351,16 +327,18 @@ func applyFlashcardSetting(c *gin.Context, request apicontract.SetFlashcardRequereturn}- flashcard, _ = conf.NormalizeFlashcard(flashcard)-- model.Conf.Flashcard = flashcard- model.Conf.Save()+ issues, applyErr := model.ApplyConfSection("flashcard", flashcard)+ recordSettingIssues(c, issues)+ err = applyErr+ if err != nil {+ return apicontract.Failure[*apicontract.SettingFlashcard](-1, err.Error())+ }- ret = apicontract.Success(settingFlashcardPayload(flashcard))+ ret = apicontract.Success(settingFlashcardPayload(model.Conf.Flashcard.Load()))return}-var setEditor = contractHandler(apicontract.SetEditor, serializeSetting("editor", applyEditorSetting))+var setEditor = contractHandler(apicontract.SetEditor, applyEditorSetting)func applyEditorSetting(c *gin.Context, request apicontract.SetEditorRequest) (ret apicontract.Response[*apicontract.SettingEditor]) {if err := request.ConfigError(); err != nil {@@ -371,59 +349,37 @@ func applyEditorSetting(c *gin.Context, request apicontract.SetEditorRequest) (rparam := request.ConfigJSON()var err error- oldGenerateHistoryInterval := model.Conf.Editor.GenerateHistoryInterval-editor := conf.NewEditor()if err = gulu.JSON.UnmarshalJSON(param, editor); err != nil {ret = apicontract.Failure[*apicontract.SettingEditor](-1, err.Error())return}- if !request.HasField("fontFamilies") && editor.FontFamily == model.Conf.Editor.FontFamily &&- editor.FontWeight == model.Conf.Editor.FontWeight {- editor.FontFamilies = model.Conf.Editor.FontFamilies+ if !request.HasField("fontFamilies") && editor.FontFamily == model.Conf.Editor.Load().FontFamily &&+ editor.FontWeight == model.Conf.Editor.Load().FontWeight {+ editor.FontFamilies = model.Conf.Editor.Load().FontFamilies}if !request.HasField("codeFontFamilies") {- editor.CodeFontFamilies = model.Conf.Editor.CodeFontFamilies+ editor.CodeFontFamilies = model.Conf.Editor.Load().CodeFontFamilies}if !request.HasFieldFold("displayImgName") {- editor.DisplayImgName = model.Conf.Editor.DisplayImgName+ editor.DisplayImgName = model.Conf.Editor.Load().DisplayImgName}if !request.HasFieldFold("displayImgAlt") {- editor.DisplayImgAlt = model.Conf.Editor.DisplayImgAlt- }- editor = conf.NormalizeEditor(editor)-- oldVirtualBlockRef := model.Conf.Editor.VirtualBlockRef- oldVirtualBlockRefInclude := model.Conf.Editor.VirtualBlockRefInclude- oldVirtualBlockRefExclude := model.Conf.Editor.VirtualBlockRefExclude- oldReadOnly := model.Conf.Editor.ReadOnly-- model.Conf.Editor = editor- model.Conf.Save()-- if oldGenerateHistoryInterval != model.Conf.Editor.GenerateHistoryInterval {- model.GenerateFileHistory()- model.ChangeHistoryTick(editor.GenerateHistoryInterval)+ editor.DisplayImgAlt = model.Conf.Editor.Load().DisplayImgAlt}- if oldVirtualBlockRef != model.Conf.Editor.VirtualBlockRef ||- oldVirtualBlockRefInclude != model.Conf.Editor.VirtualBlockRefInclude ||- oldVirtualBlockRefExclude != model.Conf.Editor.VirtualBlockRefExclude {- model.ResetVirtualBlockRefCache()- }-- if oldReadOnly != model.Conf.Editor.ReadOnly {- util.BroadcastByType("protyle", "readonly", 0, "", model.Conf.Editor.ReadOnly)- util.BroadcastByType("main", "readonly", 0, "", model.Conf.Editor.ReadOnly)+ issues, applyErr := model.ApplyConfSection("editor", editor)+ recordSettingIssues(c, issues)+ err = applyErr+ if err != nil {+ return apicontract.Failure[*apicontract.SettingEditor](-1, err.Error())}- util.MarkdownSettings = model.Conf.Editor.Markdown-- ret = apicontract.Success(settingEditorPayload(model.Conf.Editor))+ ret = apicontract.Success(settingEditorPayload(model.Conf.Editor.Load()))return}-var setExport = contractHandler(apicontract.SetExport, serializeSetting("export", applyExportSetting))+var setExport = contractHandler(apicontract.SetExport, applyExportSetting)func applyExportSetting(c *gin.Context, request apicontract.SetExportRequest) (ret apicontract.Response[*apicontract.SettingExport]) {if err := request.ConfigError(); err != nil {@@ -440,8 +396,9 @@ func applyExportSetting(c *gin.Context, request apicontract.SetExportRequest) (rreturn}- export = conf.NormalizeExport(export)- previousPandocBin := model.Conf.Export.PandocBin+ // 整段旧接口保留废弃导出模式的转换行为+ conf.MigrateExportBlockRefMode(export)+ previousPandocBin := model.Conf.Export.Load().PandocBinif "" != export.PandocBin {if !util.IsValidPandocBin(export.PandocBin) {util.PushErrMsg(fmt.Sprintf(model.Conf.Language(117), export.PandocBin), 5000)@@ -449,20 +406,21 @@ func applyExportSetting(c *gin.Context, request apicontract.SetExportRequest) (r}}- model.Conf.Export = export- model.Conf.Save()- if previousPandocBin != export.PandocBin {- util.InitPandoc(export.PandocBin)+ issues, applyErr := model.ApplyConfSection("export", export)+ recordSettingIssues(c, issues)+ err = applyErr+ if err != nil {+ return apicontract.Failure[*apicontract.SettingExport](-1, err.Error())}- ret = apicontract.Success(settingExportPayload(model.Conf.Export))+ ret = apicontract.Success(settingExportPayload(model.Conf.Export.Load()))return}var getPandocBin = contractHandler(apicontract.GetPandocBin, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[string] {pandocRuntime := util.GetPandocRuntime()if !util.IsValidPandocBin(pandocRuntime.BinPath) {- util.InitPandoc(model.Conf.Export.PandocBin)+ util.InitPandoc(model.Conf.Export.Load().PandocBin)pandocRuntime = util.GetPandocRuntime()}if !util.IsValidPandocBin(pandocRuntime.BinPath) {@@ -471,7 +429,7 @@ var getPandocBin = contractHandler(apicontract.GetPandocBin, func(c *gin.Contextreturn apicontract.Success(pandocRuntime.BinPath)})-var setFiletree = contractHandler(apicontract.SetFiletree, serializeSetting("fileTree", applyFiletreeSetting))+var setFiletree = contractHandler(apicontract.SetFiletree, applyFiletreeSetting)func applyFiletreeSetting(c *gin.Context, request apicontract.SetFiletreeRequest) (ret apicontract.Response[*apicontract.SettingFileTree]) {if err := request.ConfigError(); err != nil {@@ -479,11 +437,13 @@ func applyFiletreeSetting(c *gin.Context, request apicontract.SetFiletreeRequest}ret = apicontract.Success((*apicontract.SettingFileTree)(nil))- oldSortMode := model.Conf.FileTree.Sortparam := request.ConfigJSON()var err errorfileTree := conf.NewFileTree()+ // 请求未携带的保存格式和大文件阈值沿用当前配置+ fileTree.UseSingleLineSave = model.Conf.FileTree.Load().UseSingleLineSave+ fileTree.LargeFileWarningSize = model.Conf.FileTree.Load().LargeFileWarningSizefileTree.BoxDocEnabled = nilfileTree.UseSVGDefaultIcon = nilif err = gulu.JSON.UnmarshalJSON(param, fileTree); err != nil {@@ -491,40 +451,32 @@ func applyFiletreeSetting(c *gin.Context, request apicontract.SetFiletreeRequestreturn}if nil == fileTree.BoxDocEnabled {- if nil != model.Conf.FileTree && nil != model.Conf.FileTree.BoxDocEnabled {- fileTree.BoxDocEnabled = model.Conf.FileTree.BoxDocEnabled+ if nil != model.Conf.FileTree.Load() && nil != model.Conf.FileTree.Load().BoxDocEnabled {+ fileTree.BoxDocEnabled = model.Conf.FileTree.Load().BoxDocEnabled} else {fileTree.BoxDocEnabled = new(bool)}}if nil == fileTree.UseSVGDefaultIcon {- if nil != model.Conf.FileTree && nil != model.Conf.FileTree.UseSVGDefaultIcon {- fileTree.UseSVGDefaultIcon = model.Conf.FileTree.UseSVGDefaultIcon+ if nil != model.Conf.FileTree.Load() && nil != model.Conf.FileTree.Load().UseSVGDefaultIcon {+ fileTree.UseSVGDefaultIcon = model.Conf.FileTree.Load().UseSVGDefaultIcon} else {fileTree.UseSVGDefaultIcon = new(bool)}}- oldBoxDocEnabled := model.IsBoxDocEnabled()- fileTree = conf.NormalizeFileTree(fileTree)-- model.Conf.FileTree = fileTree- model.Conf.Save()- if oldSortMode != fileTree.Sort {- model.PushDocSortModeChanged("global", "", "", "/", &fileTree.Sort)- }- if oldBoxDocEnabled != model.IsBoxDocEnabled() {- model.RefreshBoxDocFeature()+ issues, applyErr := model.ApplyConfSection("fileTree", fileTree)+ recordSettingIssues(c, issues)+ err = applyErr+ if err != nil {+ return apicontract.Failure[*apicontract.SettingFileTree](-1, err.Error())}- util.UseSingleLineSave = model.Conf.FileTree.UseSingleLineSave- util.LargeFileWarningSize = model.Conf.FileTree.LargeFileWarningSize-- ret = apicontract.Success(settingFileTreePayload(model.Conf.FileTree))+ ret = apicontract.Success(settingFileTreePayload(model.Conf.FileTree.Load()))return}-var setSearch = contractHandler(apicontract.SetSearch, serializeSetting("search", applySearchSetting))+var setSearch = contractHandler(apicontract.SetSearch, applySearchSetting)func applySearchSetting(c *gin.Context, request apicontract.SetSearchRequest) (ret apicontract.Response[*apicontract.SettingSearch]) {if err := request.ConfigError(); err != nil {@@ -543,50 +495,26 @@ func applySearchSetting(c *gin.Context, request apicontract.SetSearchRequest) (rif s.HanSensitive == nil {// 兼容未携带该字段的旧版前端/第三方调用:保持当前值,避免被零值意外关闭并触发重建索引- s.HanSensitive = model.Conf.Search.HanSensitive+ s.HanSensitive = model.Conf.Search.Load().HanSensitive}if s.CustomBlock == nil {- s.CustomBlock = new(model.Conf.Search.CustomBlockEnabled())+ s.CustomBlock = new(model.Conf.Search.Load().CustomBlockEnabled())}if s.Mindmap == nil {- s.Mindmap = new(model.Conf.Search.MindmapEnabled())+ s.Mindmap = new(model.Conf.Search.Load().MindmapEnabled())}if s.MindmapItem == nil {- s.MindmapItem = new(model.Conf.Search.MindmapItemEnabled())+ s.MindmapItem = new(model.Conf.Search.Load().MindmapItemEnabled())}- s = conf.NormalizeSearch(s)-- oldCaseSensitive := model.Conf.Search.CaseSensitive- oldHanSensitive := model.Conf.Search.HanSensitiveVal()- oldIndexAssetPath := model.Conf.Search.IndexAssetPath-- oldVirtualRefName := model.Conf.Search.VirtualRefName- oldVirtualRefAlias := model.Conf.Search.VirtualRefAlias- oldVirtualRefAnchor := model.Conf.Search.VirtualRefAnchor- oldVirtualRefDoc := model.Conf.Search.VirtualRefDoc-- model.Conf.Search = s- model.Conf.Save()-- sql.SetCaseSensitive(s.CaseSensitive)- sql.SetHanSensitive(s.HanSensitiveVal())- sql.SetIndexAssetPath(s.IndexAssetPath)-- ftsChanged := s.CaseSensitive != oldCaseSensitive || s.HanSensitiveVal() != oldHanSensitive- if ftsChanged && s.IndexAssetPath == oldIndexAssetPath {- task.AppendTask(task.DatabaseIndexFTS, model.ReindexFTS)- } else if ftsChanged || s.IndexAssetPath != oldIndexAssetPath {- model.FullReindex(false)+ issues, applyErr := model.ApplyConfSection("search", s)+ recordSettingIssues(c, issues)+ err = applyErr+ if err != nil {+ return apicontract.Failure[*apicontract.SettingSearch](-1, err.Error())}- if oldVirtualRefName != s.VirtualRefName ||- oldVirtualRefAlias != s.VirtualRefAlias ||- oldVirtualRefAnchor != s.VirtualRefAnchor ||- oldVirtualRefDoc != s.VirtualRefDoc {- model.ResetVirtualBlockRefCache()- }- ret = apicontract.Success(settingSearchPayload(s))+ ret = apicontract.Success(settingSearchPayload(model.Conf.Search.Load()))return}@@ -601,12 +529,16 @@ func applyKeymapSetting(c *gin.Context, request apicontract.SettingKeymapRequestif err = gulu.JSON.UnmarshalJSON(param, keymap); err != nil {return apicontract.Failure[apicontract.Null](-1, err.Error())}- model.Conf.Keymap = keymap- model.Conf.Save()+ issues, applyErr := model.ApplyConfSection("keymap", keymap)+ recordSettingIssues(c, issues)+ err = applyErr+ if err != nil {+ return apicontract.Failure[apicontract.Null](-1, err.Error())+ }return apicontract.Success(apicontract.Null{})}-var setAppearance = contractHandler(apicontract.SetAppearance, serializeSetting("appearance", applyAppearanceSetting))+var setAppearance = contractHandler(apicontract.SetAppearance, applyAppearanceSetting)func applyAppearanceSetting(c *gin.Context, request apicontract.SetAppearanceRequest) (ret apicontract.Response[*apicontract.SettingAppearance]) {if err := request.ConfigError(); err != nil {@@ -624,31 +556,22 @@ func applyAppearanceSetting(c *gin.Context, request apicontract.SetAppearanceReq}if nil == appearance.EntryVisibility {- appearance.EntryVisibility = model.Conf.Appearance.EntryVisibility+ appearance.EntryVisibility = model.Conf.Appearance.Load().EntryVisibility}if !request.HasField("bodyGradient") {- appearance.BodyGradient = model.Conf.Appearance.BodyGradient+ appearance.BodyGradient = model.Conf.Appearance.Load().BodyGradient}if !request.HasField("globalFontFamilies") {- appearance.GlobalFontFamilies = model.Conf.Appearance.GlobalFontFamilies- }- appearance.NormalizeGlobalFontFamilies()- appearance.StatusBar = util.NormalizeStatusBar(appearance.StatusBar, util.IsMobileContainer())- model.Conf.Appearance = appearance- util.StatusBarCfg = model.Conf.Appearance.StatusBar- if nil == model.Conf.Appearance.Notifications {- // 旧配置未迁移,按默认全部启用处理- model.Conf.Appearance.Notifications = util.NewNotifications()- }- util.NotificationsCfg = model.Conf.Appearance.Notifications- model.Conf.Lang = util.LangToBCP47(appearance.Lang) // 兼容历史下划线值,如 zh_CN → zh-CN- util.Lang = model.Conf.Lang- model.Conf.Save()- model.InitAppearance()- model.WatchThemes()+ appearance.GlobalFontFamilies = model.Conf.Appearance.Load().GlobalFontFamilies+ }+ issues, applyErr := model.ApplyConfSection("appearance", appearance)+ recordSettingIssues(c, issues)+ err = applyErr+ if err != nil {+ return apicontract.Failure[*apicontract.SettingAppearance](-1, err.Error())+ }- ret = apicontract.Success(settingAppearancePayload(model.Conf.Appearance))- util.BroadcastByType("main", "setAppearance", 0, "", model.Conf.Appearance)+ ret = apicontract.Success(settingAppearancePayload(model.Conf.Appearance.Load()))return}@@ -695,9 +618,9 @@ var setEntryVisibility = contractHandler(apicontract.SetEntryVisibility, func(cret = apicontract.Failure[*apicontract.SettingEntryVisibility](-1, err.Error())return}- entryVisibility = conf.NormalizeEntryVisibility(entryVisibility, conf.EntryVisibilityProfileFull)- model.Conf.Appearance.EntryVisibility = entryVisibility- model.Conf.Save()+ entryVisibility = model.UpdateAppearanceConf(func(appearance *conf.Appearance) {+ appearance.EntryVisibility = entryVisibility+ }).EntryVisibilityret = apicontract.Success(settingEntryVisibilityPayload(entryVisibility))util.BroadcastByType("main", "setEntryVisibility", 0, "", entryVisibility)return@@ -708,7 +631,7 @@ var setIcon = contractHandler(apicontract.SetIcon, func(c *gin.Context, requestreturn apicontract.Failure[apicontract.Null](-1, err.Error())}model.InitAppearance()- util.BroadcastByType("main", "setAppearance", 0, "", model.Conf.Appearance)+ util.BroadcastByType("main", "setAppearance", 0, "", model.Conf.Appearance.Load())return apicontract.Success(apicontract.Null{})})@@ -722,11 +645,13 @@ var setTheme = contractHandler(apicontract.SetTheme, func(c *gin.Context, reques}model.InitAppearance()model.WatchThemes()- util.BroadcastByType("main", "setAppearance", 0, "", model.Conf.Appearance)+ util.BroadcastByType("main", "setAppearance", 0, "", model.Conf.Appearance.Load())return apicontract.Success(apicontract.Null{})})-var setPublish = contractHandler(apicontract.SetPublish, func(c *gin.Context, request apicontract.SetPublishRequest) (ret apicontract.Response[apicontract.SettingPublishData]) {+var setPublish = contractHandler(apicontract.SetPublish, applyPublishSetting)++func applyPublishSetting(c *gin.Context, request apicontract.SetPublishRequest) (ret apicontract.Response[apicontract.SettingPublishData]) {if err := request.ConfigError(); err != nil {return apicontract.Failure[apicontract.SettingPublishData](-1, err.Error())}@@ -744,55 +669,33 @@ var setPublish = contractHandler(apicontract.SetPublish, func(c *gin.Context, reif nil == publish.Auth {// 请求体缺省 auth(如 null)时保留现有认证配置,避免把 null 写入 conf.json 导致下次启动崩溃// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-rp9f-c2fj-h648- if nil != model.Conf.Publish.Auth {- publish.Auth = model.Conf.Publish.Auth- } else {- publish.Auth = conf.NewPublish().Auth- }+ publish.Auth = model.Conf.Publish.Load().Auth}-- // 认证启用时校验发布服务账户:用户名非空且不重复、密码至少 8 位,- // 防止弱密码或无密码账户被暴力破解 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-phg7-xcr4-q5wg- if publish.Auth.Enable {- usernames := map[string]bool{}- for _, account := range publish.Auth.Accounts {- if nil == account || "" == account.Username {- ret = apicontract.Failure[apicontract.SettingPublishData](-1, model.Conf.Language(361))- return- }- if usernames[account.Username] {- ret = apicontract.Failure[apicontract.SettingPublishData](-1, model.Conf.Language(362))- return- }- usernames[account.Username] = true- if 8 > len(account.Password) {- ret = apicontract.Failure[apicontract.SettingPublishData](-1, model.Conf.Language(363))- return- }- }+ issues, applyErr := model.ApplyConfSection("publish", publish)+ recordSettingIssues(c, issues)+ err = applyErr+ if err != nil {+ return apicontract.Failure[apicontract.SettingPublishData](-1, err.Error())}- model.Conf.Publish = publish- model.Conf.Save()-port, err := proxy.InitPublishService()if err != nil {ret = apicontract.Failure[apicontract.SettingPublishData](-1, err.Error())return}- ret = apicontract.Success(apicontract.SettingPublishData{Port: port, Publish: settingPublishPayload(model.Conf.Publish)})+ ret = apicontract.Success(apicontract.SettingPublishData{Port: port, Publish: settingPublishPayload(model.Conf.Publish.Load())})- util.BroadcastByType("main", "setPublish", 0, "", model.Conf.Publish)+ util.BroadcastByType("main", "setPublish", 0, "", model.Conf.Publish.Load())return-})+}var getPublish = contractHandler(apicontract.GetPublish, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.SettingPublishData] {port, err := proxy.InitPublishService()if err != nil {return apicontract.Failure[apicontract.SettingPublishData](-1, err.Error())}- return apicontract.Success(apicontract.SettingPublishData{Port: port, Publish: settingPublishPayload(model.Conf.Publish)})+ return apicontract.Success(apicontract.SettingPublishData{Port: port, Publish: settingPublishPayload(model.Conf.Publish.Load())})})var getCloudUser = contractHandler(apicontract.GetCloudUser, func(c *gin.Context, request apicontract.SettingCloudUserRequest) apicontract.Response[*apicontract.SettingUser] {@@ -835,6 +738,6 @@ var login2faCloudUser = contractHandler(apicontract.Login2faCloudUser, func(c *g})var setEmoji = contractHandler(apicontract.SetEmoji, func(c *gin.Context, request apicontract.SettingEmojiRequest) apicontract.Response[apicontract.Null] {- model.Conf.Editor.Emoji = util.FilterRecentIconValues(request.Emoji)+ model.UpdateEditorConf(func(s *conf.Editor) { s.Emoji = util.FilterRecentIconValues(request.Emoji) })return apicontract.Success(apicontract.Null{})})diff --git a/kernel/api/setting_contract_fields_test.go b/kernel/api/setting_contract_fields_test.gonew file mode 100644index 0000000000..90b6983851--- /dev/null+++ b/kernel/api/setting_contract_fields_test.go@@ -0,0 +1,132 @@+package api++import (+ "reflect"+ "sort"+ "strings"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/conf"+)++// settingContractFieldExceptions 登记契约与配置字段不一致的位置及原因,键为「契约类型.字段路径」。+var settingContractFieldExceptions = map[string]string{}++// I2:契约类型的 json 键集合与配置段一致,新增配置字段漏抄到契约时测试失败。+func TestSettingContractFieldsMatchConf(t *testing.T) {+ pairs := []struct {+ contract, config any+ }{+ {apicontract.SettingEditor{}, conf.Editor{}},+ {apicontract.SettingFileTree{}, conf.FileTree{}},+ {apicontract.SettingExport{}, conf.Export{}},+ {apicontract.SettingSearch{}, conf.Search{}},+ {apicontract.SettingFlashcard{}, conf.Flashcard{}},+ {apicontract.SettingAppearance{}, conf.Appearance{}},+ {apicontract.SettingAI{}, conf.AI{}},+ {apicontract.SettingOCR{}, conf.OCR{}},+ {apicontract.SettingSecrets{}, conf.Secrets{}},+ {apicontract.SettingVariables{}, conf.Variables{}},+ {apicontract.SettingBazaar{}, conf.Bazaar{}},+ {apicontract.SettingPublish{}, conf.Publish{}},+ {apicontract.SettingSnpt{}, conf.Snpt{}},+ {apicontract.SettingEntryVisibility{}, conf.EntryVisibility{}},+ {apicontract.SystemSync{}, conf.Sync{}},+ {apicontract.SystemSystem{}, conf.System{}},+ {apicontract.SystemRepo{}, conf.Repo{}},+ {apicontract.SystemAPI{}, conf.API{}},+ {apicontract.SystemStat{}, conf.Stat{}},+ {apicontract.SystemTag{}, conf.Tag{}},+ {apicontract.SystemGraph{}, conf.Graph{}},+ {apicontract.SystemNotebookCrypto{}, conf.NotebookCrypto{}},+ {apicontract.SystemOIDC{}, conf.OIDC{}},+ {apicontract.SystemOnboarding{}, conf.Onboarding{}},+ }+ var problems []string+ used := map[string]bool{}+ for _, pair := range pairs {+ contractType := reflect.TypeOf(pair.contract)+ compareJSONFields(contractType.Name(), contractType, reflect.TypeOf(pair.config), map[reflect.Type]bool{}, func(path, problem string) {+ if _, ok := settingContractFieldExceptions[path]; ok {+ used[path] = true+ return+ }+ problems = append(problems, path+": "+problem)+ })+ }+ for path := range settingContractFieldExceptions {+ if !used[path] {+ problems = append(problems, path+": stale exception")+ }+ }+ sort.Strings(problems)+ if len(problems) > 0 {+ t.Fatalf("setting contracts differ from configuration:\n%s", strings.Join(problems, "\n"))+ }+}++func compareJSONFields(path string, contract, config reflect.Type, visited map[reflect.Type]bool, report func(path, problem string)) {+ contract, config = structType(contract), structType(config)+ if contract == nil || config == nil {+ return+ }+ if visited[contract] {+ return+ }+ visited[contract] = true+ contractFields, configFields := jsonFields(contract), jsonFields(config)+ for name, field := range configFields {+ other, ok := contractFields[name]+ if !ok {+ report(path+"."+name, "missing in contract")+ continue+ }+ compareJSONFields(path+"."+name, other, field, visited, report)+ }+ for name := range contractFields {+ if _, ok := configFields[name]; !ok {+ report(path+"."+name, "missing in configuration")+ }+ }+}++// structType 解开指针、切片、数组和映射值,返回结构体类型;其他类型返回 nil。+func structType(typ reflect.Type) reflect.Type {+ for typ != nil {+ switch typ.Kind() {+ case reflect.Pointer, reflect.Slice, reflect.Array, reflect.Map:+ typ = typ.Elem()+ case reflect.Struct:+ return typ+ default:+ return nil+ }+ }+ return nil+}++func jsonFields(typ reflect.Type) map[string]reflect.Type {+ ret := map[string]reflect.Type{}+ for i := 0; i < typ.NumField(); i++ {+ field := typ.Field(i)+ if !field.IsExported() {+ continue+ }+ name, _, _ := strings.Cut(field.Tag.Get("json"), ",")+ if name == "-" {+ continue+ }+ if field.Anonymous && name == "" {+ for embedded, embeddedType := range jsonFields(structType(field.Type)) {+ ret[embedded] = embeddedType+ }+ continue+ }+ if name == "" {+ name = field.Name+ }+ ret[name] = field.Type+ }+ return ret+}diff --git a/kernel/api/setting_patch.go b/kernel/api/setting_patch.goindex b13b920ce4..ea4f26fabc 100644--- a/kernel/api/setting_patch.go+++ b/kernel/api/setting_patch.go@@ -5,7 +5,6 @@ import ("encoding/json""fmt""sort"- "strings""sync""sync/atomic"@@ -17,8 +16,8 @@ import ()// 配置更新按内核接受顺序提交,旧接口与字段更新共用互斥,通知只携带配置域和顺序号。-var settingMutationMu sync.Mutex-var settingRevision uint64+var settingMutationMu sync.RWMutex+var settingNamespaceLocks sync.Mapvar settingTaskID atomic.Uint64var settingTasksMu sync.Mutexvar settingTasks = map[string]apicontract.SettingTask{}@@ -55,50 +54,31 @@ func beginSettingTask(messageKey string) func() {return func() { notify(false) }}-// 单项设置接口沿用原请求和返回值,成功后通知其他前端重新读取配置。-func additionalSettingNamespace(path string) string {- switch path {- case "/api/setting/setKeymap":- return "keymap"- case "/api/setting/setBazaar":- return "bazaar"- case "/api/setting/setPublish":- return "publish"- case "/api/system/importConf":- return "*"- case "/api/system/setAutoLaunch", "/api/system/setFollowSystemLockScreen",- "/api/notebook/setEncryptedNotebookFollowSystemLock",- "/api/system/setDownloadInstallPkg", "/api/system/setSettingsWindow", "/api/system/setUpdateChannel",- "/api/system/setNetworkProxy", "/api/system/setAPIToken", "/api/system/setAccessAuthCode", "/api/system/setOIDC":- return "system"- }- if strings.HasPrefix(path, "/api/sync/set") {- return "sync"- }- if strings.HasPrefix(path, "/api/repo/set") {- return "repo"- }- if strings.HasPrefix(path, "/api/sync/importSyncProvider") {- return "sync"- }- return ""+func notifySettingChanged(namespace string) {+ model.NotifyConfChanged(namespace)}-func notifySettingChanged(namespace string) {- settingRevision++- util.BroadcastByType("main", "settingChanged", 0, "", struct {- Namespace string `json:"namespace"`- Revision uint64 `json:"revision"`- }{namespace, settingRevision})+// 批量操作独占设置闸门,单段写入只串行化同一命名空间。+func lockSetting(namespace string) func() {+ if namespace == "*" {+ settingMutationMu.Lock()+ return settingMutationMu.Unlock+ }+ settingMutationMu.RLock()+ value, _ := settingNamespaceLocks.LoadOrStore(namespace, &sync.Mutex{})+ mu := value.(*sync.Mutex)+ mu.Lock()+ return func() { mu.Unlock(); settingMutationMu.RUnlock() }}func serializeSetting[Request, Data any](namespace string,apply func(*gin.Context, Request) apicontract.Response[Data]) func(*gin.Context, Request) apicontract.Response[Data] {return func(c *gin.Context, request Request) apicontract.Response[Data] {- settingMutationMu.Lock()- defer settingMutationMu.Unlock()+ release := lockSetting(namespace)+ defer release()+ previous := model.ConfNamespaceRevision(namespace)response := apply(c, request)- if response.Code() == 0 {+ if response.Code() == 0 && previous == model.ConfNamespaceRevision(namespace) {notifySettingChanged(namespace)}return response@@ -173,68 +153,118 @@ func migrateDecisionSettingPatch(patch []byte) ([]byte, error) {}func applySettingPatch[Request, Data, Config any](c *gin.Context, patch []byte, config Config,- endpoint apicontract.Endpoint[Request, Data], apply func(*gin.Context, Request) apicontract.Response[Data]) apicontract.Response[apicontract.Null] {+ endpoint apicontract.Endpoint[Request, Data], apply func(*gin.Context, Request) apicontract.Response[Data]) apicontract.Response[*apicontract.SettingPatchData] {base, err := json.Marshal(config)if err != nil {- return apicontract.Failure[apicontract.Null](-1, err.Error())+ return apicontract.Failure[*apicontract.SettingPatchData](-1, err.Error())}merged, err := mergeSettingJSON(base, patch)if err != nil {- return apicontract.Failure[apicontract.Null](-1, err.Error())+ return apicontract.Failure[*apicontract.SettingPatchData](-1, err.Error())}request, err := endpoint.Decode(bytes.NewReader(merged))if err != nil {- return apicontract.Failure[apicontract.Null](-1, err.Error())+ return apicontract.Failure[*apicontract.SettingPatchData](-1, err.Error())}response := apply(c, request)if response.Code() != 0 {- return apicontract.Failure[apicontract.Null](response.Code(), response.Message())+ return apicontract.PatchSetting.FailureWithData(response.Code(), response.Message(), settingPatchDiagnostics(c))}- return apicontract.Success(apicontract.Null{})+ return apicontract.Success((*apicontract.SettingPatchData)(nil))}-var patchSetting = contractHandler(apicontract.PatchSetting, func(c *gin.Context, request apicontract.PatchSettingRequest) apicontract.Response[apicontract.Null] {- settingMutationMu.Lock()- defer settingMutationMu.Unlock()+var patchSetting = contractHandler(apicontract.PatchSetting, func(c *gin.Context, request apicontract.PatchSettingRequest) apicontract.Response[*apicontract.SettingPatchData] {+ release := lockSetting(request.Namespace())+ defer release()+ previous := model.ConfNamespaceRevision(request.Namespace())patch := request.PatchJSON()- var response apicontract.Response[apicontract.Null]+ var response apicontract.Response[*apicontract.SettingPatchData]switch request.Namespace() {case "editor":- response = applySettingPatch(c, patch, model.Conf.Editor, apicontract.SetEditor, applyEditorSetting)+ response = applySettingPatch(c, patch, model.Conf.Editor.Load(), apicontract.SetEditor, applyEditorSetting)case "export":- response = applySettingPatch(c, patch, model.Conf.Export, apicontract.SetExport, applyExportSetting)+ response = applySettingPatch(c, patch, model.Conf.Export.Load(), apicontract.SetExport, applyExportSetting)case "fileTree":- response = applySettingPatch(c, patch, model.Conf.FileTree, apicontract.SetFiletree, applyFiletreeSetting)+ response = applySettingPatch(c, patch, model.Conf.FileTree.Load(), apicontract.SetFiletree, applyFiletreeSetting)case "search":- response = applySettingPatch(c, patch, model.Conf.Search, apicontract.SetSearch, applySearchSetting)+ response = applySettingPatch(c, patch, model.Conf.Search.Load(), apicontract.SetSearch, applySearchSetting)case "appearance":- response = applySettingPatch(c, patch, model.Conf.Appearance, apicontract.SetAppearance, applyAppearanceSetting)+ response = applySettingPatch(c, patch, model.Conf.Appearance.Load(), apicontract.SetAppearance, applyAppearanceSetting)case "flashcard":- response = applySettingPatch(c, patch, model.Conf.Flashcard, apicontract.SetFlashcard, applyFlashcardSetting)+ response = applySettingPatch(c, patch, model.Conf.Flashcard.Load(), apicontract.SetFlashcard, applyFlashcardSetting)case "secrets":- response = applySettingPatch(c, patch, model.Conf.Secrets, apicontract.SetSecrets, applySecretsSetting)+ response = applySettingPatch(c, patch, model.Conf.Secrets.Load(), apicontract.SetSecrets, applySecretsSetting)case "variables":- response = applySettingPatch(c, patch, model.Conf.Variables, apicontract.SetVariables, applyVariablesSetting)+ response = applySettingPatch(c, patch, model.Conf.Variables.Load(), apicontract.SetVariables, applyVariablesSetting)case "keymap":response = applySettingPatch(c, append(append([]byte(`{"data":`), patch...), '}'),struct {Data *conf.Keymap `json:"data"`- }{model.Conf.Keymap}, apicontract.SetKeymap, applyKeymapSetting)+ }{model.Conf.Keymap.Load()}, apicontract.SetKeymap, applyKeymapSetting)case "ai":if util.IsDisabledFeature("ai") {- return apicontract.Failure[apicontract.Null](-1, util.I18nTerm(model.Conf.Lang, "agentCapabilitiesUnavailable"))+ return apicontract.Failure[*apicontract.SettingPatchData](-1, util.I18nTerm(model.Conf.Lang, "agentCapabilitiesUnavailable"))}var err errorpatch, err = migrateDecisionSettingPatch(patch)if err != nil {- return apicontract.Failure[apicontract.Null](-1, err.Error())+ return apicontract.Failure[*apicontract.SettingPatchData](-1, err.Error())}- response = applySettingPatch(c, patch, model.Conf.AI, apicontract.SetAI, applyAISetting)+ response = applySettingPatch(c, patch, model.Conf.AI.Load(), apicontract.SetAI, applyAISetting)+ case "ocr":+ response = applySettingPatch(c, patch, model.Conf.OCR.Load(), apicontract.SetOCRConfig, applyOCRSetting)+ case "bazaar":+ response = applySettingPatch(c, patch, model.Conf.Bazaar.Load(), apicontract.SetBazaar, applyBazaarSetting)+ case "publish":+ response = applySettingPatch(c, patch, model.Conf.Publish.Load(), apicontract.SetPublish, applyPublishSetting)+ case "snippet":+ response = applySettingPatch(c, patch, model.Conf.Snippet.Load(), apicontract.SetConfSnippet, applySnippetSetting)+ case "system", "repo", "sync":+ var err error+ var issues []model.Issue+ if request.Namespace() == "sync" {+ issues, err = model.ApplySyncSettingPatch(patch)+ } else {+ issues, err = model.ApplyConfPatch(request.Namespace(), patch)+ }+ recordSettingIssues(c, issues)+ if err != nil {+ return apicontract.PatchSetting.FailureWithData(-1, err.Error(), settingPatchDiagnostics(c))+ }+ response = apicontract.Success((*apicontract.SettingPatchData)(nil))default:- return apicontract.Failure[apicontract.Null](-1, fmt.Sprintf("unsupported settings namespace: %s", request.Namespace()))+ return apicontract.Failure[*apicontract.SettingPatchData](-1, fmt.Sprintf("unsupported settings namespace: %s", request.Namespace()))}- if response.Code() == 0 {+ if response.Code() == 0 && previous == model.ConfNamespaceRevision(request.Namespace()) {notifySettingChanged(request.Namespace())}+ if response.Code() == 0 {+ return apicontract.Success(settingPatchDiagnostics(c))+ }return response})++func recordSettingIssues(c *gin.Context, issues []model.Issue) {+ if c != nil && len(issues) > 0 {+ c.Set("settingIssues", issues)+ }+}++func settingPatchDiagnostics(c *gin.Context) *apicontract.SettingPatchData {+ if c == nil {+ return nil+ }+ value, ok := c.Get("settingIssues")+ if !ok {+ return nil+ }+ issues, ok := value.([]model.Issue)+ if !ok || len(issues) == 0 {+ return nil+ }+ data := &apicontract.SettingPatchData{Issues: make([]apicontract.SettingIssue, len(issues))}+ for i, issue := range issues {+ data.Issues[i] = apicontract.SettingIssue{Field: issue.Field, Severity: issue.Severity, Message: issue.Message}+ }+ return data+}diff --git a/kernel/api/setting_patch_test.go b/kernel/api/setting_patch_test.goindex 4aec9f38c9..f7c13e1929 100644--- a/kernel/api/setting_patch_test.go+++ b/kernel/api/setting_patch_test.go@@ -12,14 +12,19 @@ import ()func TestAPIContractSettingPatchConcurrentFields(t *testing.T) {- previousConf, previousReadOnly, previousMarkdown := model.Conf, util.ReadOnly, util.MarkdownSettings+ previousConf, previousReadOnly, previousMarkdown := model.Conf, util.ReadOnly, util.MarkdownSettings.Load()model.Conf = model.NewAppConf()- model.Conf.Editor = conf.NewEditor()+ model.Conf.Editor.Store(conf.NewEditor())util.ReadOnly = truet.Cleanup(func() {- model.Conf, util.ReadOnly, util.MarkdownSettings = previousConf, previousReadOnly, previousMarkdown+ {+ derivedValue0, derivedValue1, derivedValue2 := previousConf, previousReadOnly, previousMarkdown+ model.Conf = derivedValue0+ util.ReadOnly = derivedValue1+ util.MarkdownSettings.Store(derivedValue2)+ }})- fontSize := model.Conf.Editor.FontSize+ fontSize := model.Conf.Editor.Load().FontSizevar group sync.WaitGroupfor _, body := range []string{`{"editor":{"displayImgName":true}}`, `{"editor":{"displayImgAlt":true}}`} {group.Add(1)@@ -32,12 +37,12 @@ func TestAPIContractSettingPatchConcurrentFields(t *testing.T) {}()}group.Wait()- if !model.Conf.Editor.DisplayImgName || !model.Conf.Editor.DisplayImgAlt || model.Conf.Editor.FontSize != fontSize {+ if !model.Conf.Editor.Load().DisplayImgName || !model.Conf.Editor.Load().DisplayImgAlt || model.Conf.Editor.Load().FontSize != fontSize {t.Fatal("independent settings updates must preserve each other and omitted fields")}- before := settingRevision+ before := model.ConfSettingRevision.Load()code, _, _ := settingContractRequest(t, "patch", patchSetting, `{"editor":{"fontSize":"bad"}}`)- if code == 0 || settingRevision != before || model.Conf.Editor.FontSize != fontSize {+ if code == 0 || model.ConfSettingRevision.Load() != before || model.Conf.Editor.Load().FontSize != fontSize {t.Fatal("failed patches must not modify configuration or publish a change")}}diff --git a/kernel/api/setting_test.go b/kernel/api/setting_test.goindex 8c998d800c..a716315018 100644--- a/kernel/api/setting_test.go+++ b/kernel/api/setting_test.go@@ -33,9 +33,9 @@ import (func TestSetAIRejectsInvalidProviderHeaders(t *testing.T) {previousConf := model.Conf- model.Conf = &model.AppConf{AI: &conf.AI{}}+ model.Conf = &model.AppConf{AI: model.NewConfSection(&conf.AI{})}t.Cleanup(func() { model.Conf = previousConf })- initialAI := model.Conf.AI+ initialAI := model.Conf.AI.Load()for _, headers := range []string{`{"Bad Name":"private-value"}`, `{"X-Key":"private-value\r\ninjected: yes"}`, `{"X-Key":"a","x-key":"b"}`,} {@@ -51,7 +51,7 @@ func TestSetAIRejectsInvalidProviderHeaders(t *testing.T) {if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil {t.Fatal(err)}- if result.Code != -1 || model.Conf.AI != initialAI || strings.Contains(recorder.Body.String(), "private-value") {+ if result.Code != -1 || model.Conf.AI.Load() != initialAI || strings.Contains(recorder.Body.String(), "private-value") {t.Fatal("invalid provider headers must be rejected without changing configuration or exposing values")}}@@ -67,13 +67,13 @@ func TestSetBazaarPetalDisabledSerializesTransitions(t *testing.T) {util.ReadOnly = trueutil.DataDir = t.TempDir()model.Conf = model.NewAppConf()- model.Conf.Bazaar = &conf.Bazaar{Trust: true}+ model.Conf.Bazaar.Store(&conf.Bazaar{Trust: true})bazaarPetalStateMu.Lock()- bazaarPetalStateRevision = 0+ model.BazaarPetalStateRevision.Store(0)bazaarPetalStateMu.Unlock()t.Cleanup(func() {bazaarPetalStateMu.Lock()- bazaarPetalStateRevision = 0+ model.BazaarPetalStateRevision.Store(0)bazaarPetalStateMu.Unlock()model.Conf = previousConfutil.ReadOnly = previousReadOnly@@ -153,7 +153,7 @@ func TestSetBazaarPetalDisabledSerializesTransitions(t *testing.T) {enabled.Data.Revision != 2 {t.Fatalf("unexpected enabled response: %#v", enabled)}- if model.Conf.Bazaar.PetalDisabled {+ if model.Conf.Bazaar.Load().PetalDisabled {t.Fatal("final bazaar plugin state is disabled")}_, unchanged := request(`{"petalDisabled":false}`)@@ -189,8 +189,8 @@ func TestSetFiletreePreservesUseSVGDefaultIconWhenMissing(t *testing.T) {} {t.Run(test.name, func(t *testing.T) {model.Conf = model.NewAppConf()- model.Conf.FileTree = conf.NewFileTree()- model.Conf.FileTree.UseSVGDefaultIcon = new(test.enabled)+ model.Conf.FileTree.Store(conf.NewFileTree())+ model.Conf.FileTree.Load().UseSVGDefaultIcon = new(test.enabled)recorder := httptest.NewRecorder()request := httptest.NewRequest(http.MethodPost, "/api/setting/setFiletree", strings.NewReader(`{}`))@@ -206,9 +206,9 @@ func TestSetFiletreePreservesUseSVGDefaultIconWhenMissing(t *testing.T) {if 0 != response.Code {t.Fatalf("setFiletree failed: %s", recorder.Body.String())}- if nil == model.Conf.FileTree.UseSVGDefaultIcon ||- test.enabled != *model.Conf.FileTree.UseSVGDefaultIcon {- t.Fatalf("missing setting changed the current value: %#v", model.Conf.FileTree.UseSVGDefaultIcon)+ if nil == model.Conf.FileTree.Load().UseSVGDefaultIcon ||+ test.enabled != *model.Conf.FileTree.Load().UseSVGDefaultIcon {+ t.Fatalf("missing setting changed the current value: %#v", model.Conf.FileTree.Load().UseSVGDefaultIcon)}})}diff --git a/kernel/api/setting_write_contract_test.go b/kernel/api/setting_write_contract_test.gonew file mode 100644index 0000000000..af3b7c05ec--- /dev/null+++ b/kernel/api/setting_write_contract_test.go@@ -0,0 +1,150 @@+package api++import (+ "go/ast"+ "go/parser"+ "go/token"+ "os"+ "path/filepath"+ "regexp"+ "strings"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/apicontract"+)++// settingWriteExemptions 登记命名约定上像写配置、但不写入应用配置或按事务单独处理的端点,必须注明原因。+var settingWriteExemptions = map[string]string{+ "/api/setting/getBootAppearances": "只读",+ "/api/setting/getCloudUser": "读取账号信息,缓存的用户数据由账号流程维护",+ "/api/setting/getPandocBin": "只读",+ "/api/setting/getPublish": "只读",+ "/api/setting/logoutCloudUser": "账号登出,用户数据不属于设置项",+ "/api/setting/login2faCloudUser": "账号登录,用户数据不属于设置项",+ "/api/setting/refreshVirtualBlockRef": "仅刷新运行时缓存",+ "/api/system/setWorkspaceDir": "写入全局工作空间列表,不属于工作空间配置",+ "/api/system/importCustomFont": "写入字体资源文件,不修改配置",+ "/api/system/importTLSCABundle": "写入证书文件,不修改配置",+ "/api/system/addCustomEmoji": "写入表情资源文件,不修改配置",+ "/api/system/removeWorkspaceDir": "写入全局工作空间列表,不属于工作空间配置",+ "/api/system/removeWorkspaceDirPhysically": "删除工作空间目录,不修改当前配置",+ "/api/repo/setSnapshotMemo": "写入快照备注,不修改配置",+ "/api/repo/importRepoKey": "数据仓库密钥事务,由密钥流程自行持久化和广播",+ "/api/repo/initRepoKey": "数据仓库密钥事务,由密钥流程自行持久化和广播",+ "/api/repo/initRepoKeyFromPassphrase": "数据仓库密钥事务,由密钥流程自行持久化和广播",+ "/api/repo/resetRepo": "数据仓库重置事务,由仓库流程自行持久化和广播",+ "/api/repo/removeRepoTagSnapshot": "删除快照标签,不修改配置",+ "/api/repo/removeCloudRepoTagSnapshot": "删除云端快照标签,不修改配置",+ "/api/system/clearTempFiles": "清理临时文件,不修改配置",+}++// 写配置端点的命名约定:这些前缀下以写入动词开头的端点默认视为写配置。+var settingWritePathPattern = regexp.MustCompile(`^/api/(setting|system|sync|repo|graph|storage)/(set|reset|import|clear|patch|add|remove|init|confirm)[A-Z0-9]`)++// 处理器中直接写配置的语句。+var directSettingWritePattern = regexp.MustCompile(`model\.Conf\.Save\(\)|model\.Update[A-Za-z]+Conf\(|model\.Conf\.(SetAI|SetOIDC|SetMCPOAuth|CompareAndSetOIDC|SaveGraphQueryConf|SetUILayout)\(|model\.Conf\.[A-Z][A-Za-z.]*\s*=[^=]`)++// I5:每个写配置端点都在契约中声明命名空间,由 contractHandler 统一持锁和通知。+func TestSettingWriteEndpointsAreDeclared(t *testing.T) {+ definitions := map[string]apicontract.Definition{}+ for _, definition := range apicontract.Definitions() {+ definitions[definition.Path] = definition+ }+ for path, definition := range definitions {+ if !settingWritePathPattern.MatchString(path) {+ continue+ }+ if _, exempt := settingWriteExemptions[path]; exempt {+ if definition.Setting.Declared() {+ t.Errorf("%s is both exempted and declared", path)+ }+ continue+ }+ if !definition.Setting.Declared() {+ t.Errorf("%s writes settings by naming convention but declares no setting namespace", path)+ }+ }+ for path := range settingWriteExemptions {+ if _, ok := definitions[path]; !ok {+ t.Errorf("exempted endpoint %s no longer exists", path)+ }+ }++ paths := contractVarPaths(t)+ fset := token.NewFileSet()+ files, err := filepath.Glob("*.go")+ if err != nil {+ t.Fatal(err)+ }+ for _, name := range files {+ if strings.HasSuffix(name, "_test.go") {+ continue+ }+ file, err := parser.ParseFile(fset, name, nil, 0)+ if err != nil {+ t.Fatal(err)+ }+ source, _ := os.ReadFile(name)+ funcs := map[string]string{}+ for _, decl := range file.Decls {+ if fn, ok := decl.(*ast.FuncDecl); ok && fn.Recv == nil {+ funcs[fn.Name.Name] = string(source[fset.Position(fn.Pos()).Offset:fset.Position(fn.End()).Offset])+ }+ }+ ast.Inspect(file, func(node ast.Node) bool {+ call, ok := node.(*ast.CallExpr)+ if !ok || len(call.Args) < 2 {+ return true+ }+ if ident, ok := call.Fun.(*ast.Ident); !ok || ident.Name != "contractHandler" {+ return true+ }+ selector, ok := call.Args[0].(*ast.SelectorExpr)+ if !ok {+ return true+ }+ body := string(source[fset.Position(call.Args[1].Pos()).Offset:fset.Position(call.Args[1].End()).Offset])+ if ident, ok := call.Args[1].(*ast.Ident); ok {+ body = funcs[ident.Name]+ }+ // 展开同文件中被直接调用的辅助函数一层+ expanded := body+ for fn, fnBody := range funcs {+ if strings.Contains(body, fn+"(") {+ expanded += fnBody+ }+ }+ path := paths[selector.Sel.Name]+ definition := definitions[path]+ if directSettingWritePattern.MatchString(expanded) && !definition.Setting.Declared() {+ t.Errorf("%s (%s) writes configuration directly but declares no setting namespace", path, name)+ }+ if definition.Setting.Declared() && definition.Setting.Mode != apicontract.SettingSelfManaged &&+ strings.Contains(expanded, "settingMutationMu.Lock()") {+ t.Errorf("%s locks the setting mutex itself; declare SettingSelfManaged instead", path)+ }+ return true+ })+ }+}++// contractVarPaths 从契约源码中解析变量名与路径的对应关系。+func contractVarPaths(t *testing.T) map[string]string {+ t.Helper()+ ret := map[string]string{}+ files, err := filepath.Glob(filepath.Join("..", "apicontract", "*.go"))+ if err != nil {+ t.Fatal(err)+ }+ pattern := regexp.MustCompile(`(?m)^\s*(?:var\s+)?([A-Z][A-Za-z0-9]*)\s*=\s*define\[[^\n]*?\("[^"]+",\s*"([^"]+)"`)+ for _, name := range files {+ data, err := os.ReadFile(name)+ if err != nil {+ t.Fatal(err)+ }+ for _, match := range pattern.FindAllStringSubmatch(string(data), -1) {+ ret[match[1]] = match[2]+ }+ }+ return ret+}diff --git a/kernel/api/settings_reset.go b/kernel/api/settings_reset.goindex 2c137f160e..dcddbd476c 100644--- a/kernel/api/settings_reset.go+++ b/kernel/api/settings_reset.go@@ -110,7 +110,7 @@ var resetSettings = contractHandler(apicontract.ResetSettings,}}model.FlushTxQueue()- previousSearch := model.Conf.Search+ previousSearch := model.Conf.Search.Load()if err := model.ResetSettings(); err != nil {return apicontract.Failure[apicontract.Null](-1, err.Error())}diff --git a/kernel/api/settings_reset_test.go b/kernel/api/settings_reset_test.goindex 2bcacfbc21..315266c8ae 100644--- a/kernel/api/settings_reset_test.go+++ b/kernel/api/settings_reset_test.go@@ -120,10 +120,10 @@ func TestAPIContractSettingsResetSerializesGraphWrites(t *testing.T) {{"/api/graph/getLocalGraph", getLocalGraph, `{"id":"missing","conf":{"d3":false}}`, false},} {t.Run(entry.path+entry.body, func(t *testing.T) {- model.Conf.Graph = conf.NewGraph()- model.Conf.Graph.Global.MinRefs = 7- model.Conf.Graph.Local.DailyNote = true- before := string(graphJSON(t, model.Conf.Graph))+ model.Conf.Graph.Store(conf.NewGraph())+ model.Conf.Graph.Load().Global.MinRefs = 7+ model.Conf.Graph.Load().Local.DailyNote = true+ before := string(graphJSON(t, model.Conf.Graph.Load()))recorder := httptest.NewRecorder()c, _ := gin.CreateTestContext(recorder)c.Set(model.RoleContextKey, model.RoleAdministrator)@@ -148,7 +148,7 @@ func TestAPIContractSettingsResetSerializesGraphWrites(t *testing.T) {t.Fatal("graph write did not resume after settings reset unlocked")}requireAPIContract(t, http.MethodPost, entry.path, recorder)- if changed := before != string(graphJSON(t, model.Conf.Graph)); changed != entry.changed {+ if changed := before != string(graphJSON(t, model.Conf.Graph.Load())); changed != entry.changed {t.Fatal("graph write or validation changed after unlocking")}})diff --git a/kernel/api/sql.go b/kernel/api/sql.goindex 3c9c0e3161..5106042bc3 100644--- a/kernel/api/sql.go+++ b/kernel/api/sql.go@@ -57,7 +57,7 @@ var SQL = contractHandler(apicontract.QuerySQL, func(c *gin.Context, request apireturn apicontract.Failure[apicontract.SQLRows](-1, "unknown [mode]")}- result, info, err := sql.QueryWithLimitInfo(stmt, model.Conf.Search.Limit)+ result, info, err := sql.QueryWithLimitInfo(stmt, model.Conf.Search.Load().Limit)if err != nil {return apicontract.Failure[apicontract.SQLRows](1, err.Error())}diff --git a/kernel/api/storage_test.go b/kernel/api/storage_test.goindex f461bf111a..77930af237 100644--- a/kernel/api/storage_test.go+++ b/kernel/api/storage_test.go@@ -34,7 +34,7 @@ func TestCriteriaCRUD(t *testing.T) {gin.SetMode(gin.TestMode)oldConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()+ model.Conf.Sync.Store(conf.NewSync())t.Cleanup(func() { model.Conf = oldConf })oldDataDir := util.DataDirdiff --git a/kernel/api/sync.go b/kernel/api/sync.goindex 3fad5cd41a..88285e873e 100644--- a/kernel/api/sync.go+++ b/kernel/api/sync.go@@ -146,7 +146,7 @@ func importSyncProviderWebDAVContract(c *gin.Context, request apicontract.SyncPrreturn}- result := apicontract.SyncWebDAVData{WebDAV: (*apicontract.SyncWebDAV)(model.Conf.Sync.WebDAV)}+ result := apicontract.SyncWebDAVData{WebDAV: (*apicontract.SyncWebDAV)(model.Conf.Sync.Load().WebDAV)}if copyError != nil {return apicontract.ImportSyncProviderWebDAV.FailureWithData(-1, copyError.Error(), result)}@@ -157,6 +157,7 @@ func importSyncProviderWebDAVContract(c *gin.Context, request apicontract.SyncPrvar exportSyncProviderWebDAV = contractHandler(apicontract.ExportSyncProviderWebDAV, exportSyncProviderWebDAVContract)func exportSyncProviderWebDAVContract(c *gin.Context, request apicontract.EmptyRequest) (ret apicontract.Response[apicontract.SyncProviderExportData]) {+ confSyncSnapshot := model.Conf.LoadSync()name := "siyuan-webdav-" + time.Now().Format("20060102150405") + ".json"tmpDir := filepath.Join(util.TempDir, "export")@@ -166,12 +167,12 @@ func exportSyncProviderWebDAVContract(c *gin.Context, request apicontract.EmptyRreturn}- webdav := model.Conf.Sync.WebDAV+ webdav := confSyncSnapshot.WebDAVif nil == webdav {webdav = &conf.WebDAV{}}- data, err := gulu.JSON.MarshalJSON(model.Conf.Sync.WebDAV)+ data, err := gulu.JSON.MarshalJSON(confSyncSnapshot.WebDAV)if err != nil {logging.LogErrorf("export WebDAV provider failed: %s", err)ret = apicontract.Failure[apicontract.SyncProviderExportData](-1, err.Error())@@ -307,7 +308,7 @@ func importSyncProviderS3Contract(c *gin.Context, request apicontract.SyncProvidreturn}- result := apicontract.SyncS3Data{S3: (*apicontract.SyncS3)(model.Conf.Sync.S3)}+ result := apicontract.SyncS3Data{S3: (*apicontract.SyncS3)(model.Conf.Sync.Load().S3)}if copyError != nil {return apicontract.ImportSyncProviderS3.FailureWithData(-1, copyError.Error(), result)}@@ -318,6 +319,7 @@ func importSyncProviderS3Contract(c *gin.Context, request apicontract.SyncProvidvar exportSyncProviderS3 = contractHandler(apicontract.ExportSyncProviderS3, exportSyncProviderS3Contract)func exportSyncProviderS3Contract(c *gin.Context, request apicontract.EmptyRequest) (ret apicontract.Response[apicontract.SyncProviderExportData]) {+ confSyncSnapshot := model.Conf.LoadSync()name := "siyuan-s3-" + time.Now().Format("20060102150405") + ".json"tmpDir := filepath.Join(util.TempDir, "export")@@ -327,12 +329,12 @@ func exportSyncProviderS3Contract(c *gin.Context, request apicontract.EmptyRequereturn}- s3 := model.Conf.Sync.S3+ s3 := confSyncSnapshot.S3if nil == s3 {s3 = &conf.S3{}}- data, err := gulu.JSON.MarshalJSON(model.Conf.Sync.S3)+ data, err := gulu.JSON.MarshalJSON(confSyncSnapshot.S3)if err != nil {logging.LogErrorf("export S3 provider failed: %s", err)ret = apicontract.Failure[apicontract.SyncProviderExportData](-1, err.Error())@@ -374,9 +376,10 @@ func exportSyncProviderS3Contract(c *gin.Context, request apicontract.EmptyRequevar getSyncInfo = contractHandler(apicontract.GetSyncInfo, getSyncInfoContract)func getSyncInfoContract(c *gin.Context, request apicontract.EmptyRequest) (ret apicontract.Response[apicontract.SyncInfoData]) {+ confSyncSnapshot := model.Conf.LoadSync()- stat := model.Conf.Sync.Stat- if !model.Conf.Sync.Enabled {+ stat := confSyncSnapshot.Stat+ if !confSyncSnapshot.Enabled {stat = model.Conf.Language(53)}@@ -385,7 +388,7 @@ func getSyncInfoContract(c *gin.Context, request apicontract.EmptyRequest) (retfor i, item := range kernels {items[i] = (*apicontract.SyncOnlineKernel)(item)}- ret = apicontract.Success(apicontract.SyncInfoData{Synced: model.Conf.Sync.Synced, Stat: stat, Kernels: items, Kernel: model.KernelID})+ ret = apicontract.Success(apicontract.SyncInfoData{Synced: confSyncSnapshot.Synced, Stat: stat, Kernels: items, Kernel: model.KernelID})return}@@ -398,7 +401,7 @@ func getBootSyncContract(c *gin.Context, request apicontract.EmptyRequest) (retreturn}- if model.Conf.Sync.Enabled && 1 == model.BootSyncSucc.Load() {+ if model.Conf.Sync.Load().Enabled && 1 == model.BootSyncSucc.Load() {ret = apicontract.Failure[apicontract.Null](1, model.Conf.Language(17))return}@@ -408,6 +411,8 @@ func getBootSyncContract(c *gin.Context, request apicontract.EmptyRequest) (retvar performSync = contractHandler(apicontract.PerformSync, performSyncContract)func performSyncContract(c *gin.Context, request apicontract.PerformSyncRequest) (ret apicontract.Response[apicontract.Null]) {+ confSyncSnapshot := model.Conf.LoadSync()+ret = apicontract.Success(apicontract.Null{})// Android 端前后台切换时自动触发同步 https://github.com/siyuan-note/siyuan/issues/7122@@ -416,12 +421,12 @@ func performSyncContract(c *gin.Context, request apicontract.PerformSyncRequest)if !util.IsBooted() {return}- if nil == model.Conf.GetUser() || !model.Conf.Sync.Enabled {+ if nil == model.Conf.GetUser() || !confSyncSnapshot.Enabled {return}}- if 3 != model.Conf.Sync.Mode {+ if 3 != confSyncSnapshot.Mode {model.SyncData(true)return}@@ -453,6 +458,7 @@ func performBootSyncContract(c *gin.Context, request apicontract.EmptyRequest) (var listCloudSyncDir = contractHandler(apicontract.ListCloudSyncDir, listCloudSyncDirContract)func listCloudSyncDirContract(c *gin.Context, request apicontract.EmptyRequest) (ret apicontract.Response[apicontract.CloudSyncDirsData]) {+ confSyncSnapshot := model.Conf.LoadSync()syncDirs, hSize, err := model.ListCloudSyncDir()if err != nil {@@ -460,8 +466,8 @@ func listCloudSyncDirContract(c *gin.Context, request apicontract.EmptyRequest)return}- checkedSyncDir := model.Conf.Sync.CloudName- if conf.ProviderS3 == model.Conf.Sync.Provider {+ checkedSyncDir := confSyncSnapshot.CloudName+ if conf.ProviderS3 == confSyncSnapshot.Provider {checkedSyncDir = ""}var items []*apicontract.CloudSyncDir@@ -480,13 +486,17 @@ var removeCloudSyncDir = contractHandler(apicontract.RemoveCloudSyncDir, removeCfunc removeCloudSyncDirContract(c *gin.Context, request apicontract.SyncNameRequest) (ret apicontract.Response[string]) {name := request.Name+ // 删除云端目录是网络操作,不持有配置互斥锁;删除当前目录时回退的目录名在完成后统一通知err := model.RemoveCloudSyncDir(name)if err != nil {ret = apicontract.FailureWithTimeout[string](-1, err.Error(), 5000)return}+ settingMutationMu.Lock()+ notifySettingChanged("sync")+ settingMutationMu.Unlock()- ret = apicontract.Success(model.Conf.Sync.CloudName)+ ret = apicontract.Success(model.Conf.Sync.Load().CloudName)return}@@ -603,22 +613,25 @@ func setSyncProviderContract(c *gin.Context, request apicontract.SyncProviderReqvar setSyncProviderS3 = contractHandler(apicontract.SetSyncProviderS3, setSyncProviderS3Contract)var clearSyncProviderConfig = contractHandler(apicontract.ClearSyncProviderConfig, func(c *gin.Context, request apicontract.ClearSyncProviderConfigRequest) apicontract.Response[apicontract.ClearSyncProviderConfigData] {+if err := model.ClearSyncProviderConfig(request.Provider); err != nil {return apicontract.Failure[apicontract.ClearSyncProviderConfigData](-1, err.Error())}- data := apicontract.ClearSyncProviderConfigData{Enabled: model.Conf.Sync.Enabled}+ confSyncSnapshot := model.Conf.LoadSync()+ data := apicontract.ClearSyncProviderConfigData{Enabled: confSyncSnapshot.Enabled}switch request.Provider {case conf.ProviderS3:- data.S3 = (*apicontract.SyncS3)(model.Conf.Sync.S3)+ data.S3 = (*apicontract.SyncS3)(confSyncSnapshot.S3)case conf.ProviderWebDAV:- data.WebDAV = (*apicontract.SyncWebDAV)(model.Conf.Sync.WebDAV)+ data.WebDAV = (*apicontract.SyncWebDAV)(confSyncSnapshot.WebDAV)case conf.ProviderLocal:- data.Local = (*apicontract.SyncLocal)(model.Conf.Sync.Local)+ data.Local = (*apicontract.SyncLocal)(confSyncSnapshot.Local)}return apicontract.Success(data)})func setSyncProviderS3Contract(c *gin.Context, request apicontract.SetSyncS3Request) (ret apicontract.Response[apicontract.SyncS3Data]) {+ confSyncSnapshot := model.Conf.LoadSync()if err := request.ConfigError(); err != nil {return apicontract.FailureWithTimeout[apicontract.SyncS3Data](-1, err.Error(), 5000)@@ -626,7 +639,7 @@ func setSyncProviderS3Contract(c *gin.Context, request apicontract.SetSyncS3Requs3 := (*conf.S3)(&request.S3)newBucket := strings.TrimSpace(s3.Bucket)- prevBucket := strings.TrimSpace(model.Conf.Sync.S3.Bucket)+ prevBucket := strings.TrimSpace(confSyncSnapshot.S3.Bucket)if newBucket != prevBucket && !cloud.IsValidCloudDirName(newBucket) {ret = apicontract.FailureWithTimeout[apicontract.SyncS3Data](-1, model.Conf.Language(37), 5000)return@@ -638,7 +651,7 @@ func setSyncProviderS3Contract(c *gin.Context, request apicontract.SetSyncS3Requreturn}- ret = apicontract.Success(apicontract.SyncS3Data{S3: (*apicontract.SyncS3)(model.Conf.Sync.S3)})+ ret = apicontract.Success(apicontract.SyncS3Data{S3: (*apicontract.SyncS3)(model.Conf.LoadSync().S3)})return}@@ -657,7 +670,7 @@ func setSyncProviderWebDAVContract(c *gin.Context, request apicontract.SetSyncWereturn}- ret = apicontract.Success(apicontract.SyncWebDAVData{WebDAV: (*apicontract.SyncWebDAV)(model.Conf.Sync.WebDAV)})+ ret = apicontract.Success(apicontract.SyncWebDAVData{WebDAV: (*apicontract.SyncWebDAV)(model.Conf.Sync.Load().WebDAV)})return}@@ -676,7 +689,7 @@ func setSyncProviderLocalContract(c *gin.Context, request apicontract.SetSyncLocreturn}- ret = apicontract.Success(apicontract.SyncLocalData{Local: (*apicontract.SyncLocal)(model.Conf.Sync.Local)})+ ret = apicontract.Success(apicontract.SyncLocalData{Local: (*apicontract.SyncLocal)(model.Conf.Sync.Load().Local)})return}diff --git a/kernel/api/system.go b/kernel/api/system.goindex 9f6bc7f4ef..a374633c23 100644--- a/kernel/api/system.go+++ b/kernel/api/system.go@@ -70,8 +70,7 @@ var addMicrosoftDefenderExclusion = contractHandler(apicontract.AddMicrosoftDefevar ignoreAddMicrosoftDefenderExclusion = contractHandler(apicontract.IgnoreAddMicrosoftDefenderExclusion, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.Null] {if gulu.OS.IsWindows() {- model.Conf.System.MicrosoftDefenderExcluded = true- model.Conf.Save()+ model.UpdateSystemConf(func(s *conf.System) { s.MicrosoftDefenderExcluded = true })}return apicontract.Success(apicontract.Null{})})@@ -90,7 +89,7 @@ var getNetwork = contractHandler(apicontract.GetNetwork, func(c *gin.Context, rereturn apicontract.Failure[apicontract.NetworkData](-1, "get conf failed: "+err.Error())}var proxy *apicontract.NetworkProxy- if value := maskedConf.System.NetworkProxy; value != nil {+ if value := maskedConf.System.Load().NetworkProxy; value != nil {proxy = &apicontract.NetworkProxy{Scheme: value.Scheme, Host: value.Host, Port: value.Port}}return apicontract.Success(apicontract.NetworkData{Proxy: proxy})@@ -459,90 +458,90 @@ var exportConf = contractHandler(apicontract.SystemExportConf, func(c *gin.Contereturn}- if nil != clonedConf.Appearance {- clonedConf.Appearance.DarkThemes = nil- clonedConf.Appearance.LightThemes = nil- clonedConf.Appearance.Icons = nil- fonts := make([]*conf.EditorFont, 0, len(clonedConf.Appearance.GlobalFontFamilies))- for _, font := range clonedConf.Appearance.GlobalFontFamilies {+ if nil != clonedConf.Appearance.Load() {+ clonedConf.Appearance.Load().DarkThemes = nil+ clonedConf.Appearance.Load().LightThemes = nil+ clonedConf.Appearance.Load().Icons = nil+ fonts := make([]*conf.EditorFont, 0, len(clonedConf.Appearance.Load().GlobalFontFamilies))+ for _, font := range clonedConf.Appearance.Load().GlobalFontFamilies {if nil != font && !strings.HasPrefix(font.Family, util.CustomFontFamilyPrefix) {fonts = append(fonts, font)}}- clonedConf.Appearance.GlobalFontFamilies = fonts+ clonedConf.Appearance.Load().GlobalFontFamilies = fonts}- if nil != clonedConf.Editor {- clonedConf.Editor.Emoji = []string{}- fonts := make([]*conf.EditorFont, 0, len(clonedConf.Editor.FontFamilies))- for _, font := range clonedConf.Editor.FontFamilies {+ if nil != clonedConf.Editor.Load() {+ clonedConf.Editor.Load().Emoji = []string{}+ fonts := make([]*conf.EditorFont, 0, len(clonedConf.Editor.Load().FontFamilies))+ for _, font := range clonedConf.Editor.Load().FontFamilies {if nil != font && !strings.HasPrefix(font.Family, util.CustomFontFamilyPrefix) {fonts = append(fonts, font)}}- clonedConf.Editor.FontFamilies = fonts- codeFonts := make([]*conf.EditorFont, 0, len(clonedConf.Editor.CodeFontFamilies))- for _, font := range clonedConf.Editor.CodeFontFamilies {+ clonedConf.Editor.Load().FontFamilies = fonts+ codeFonts := make([]*conf.EditorFont, 0, len(clonedConf.Editor.Load().CodeFontFamilies))+ for _, font := range clonedConf.Editor.Load().CodeFontFamilies {if nil != font && !strings.HasPrefix(font.Family, util.CustomFontFamilyPrefix) {codeFonts = append(codeFonts, font)}}- clonedConf.Editor.CodeFontFamilies = codeFonts- clonedConf.Editor.FontFamily = ""- clonedConf.Editor.FontWeight = 400- clonedConf.Editor.FontFamilyDisplay = ""- clonedConf.Editor.NormalizeFontFamilies()+ clonedConf.Editor.Load().CodeFontFamilies = codeFonts+ clonedConf.Editor.Load().FontFamily = ""+ clonedConf.Editor.Load().FontWeight = 400+ clonedConf.Editor.Load().FontFamilyDisplay = ""+ clonedConf.Editor.Load().NormalizeFontFamilies()}- if nil != clonedConf.Export {- clonedConf.Export.PandocBin = ""+ if nil != clonedConf.Export.Load() {+ clonedConf.Export.Load().PandocBin = ""}clonedConf.UserData = ""clonedConf.AccessAuthCode = ""- if nil != clonedConf.System {- clonedConf.System.NetworkProxy = &conf.NetworkProxy{}- clonedConf.System.ID = ""- clonedConf.System.Name = ""- clonedConf.System.OSPlatform = ""- clonedConf.System.Container = ""- clonedConf.System.IsMicrosoftStore = false- clonedConf.System.UpdateChannel = ""- clonedConf.System.MicrosoftDefenderExcluded = false- }- clonedConf.Sync = nil- clonedConf.Stat = nil- clonedConf.Api = nil- clonedConf.Repo = nil- clonedConf.Secrets = nil+ if nil != clonedConf.System.Load() {+ clonedConf.System.Load().NetworkProxy = &conf.NetworkProxy{}+ clonedConf.System.Load().ID = ""+ clonedConf.System.Load().Name = ""+ clonedConf.System.Load().OSPlatform = ""+ clonedConf.System.Load().Container = ""+ clonedConf.System.Load().IsMicrosoftStore = false+ clonedConf.System.Load().UpdateChannel = ""+ clonedConf.System.Load().MicrosoftDefenderExcluded = false+ }+ clonedConf.Sync.Store(nil)+ clonedConf.Stat.Store(nil)+ clonedConf.Api.Store(nil)+ clonedConf.Repo.Store(nil)+ clonedConf.Secrets.Store(nil)clonedConf.NotebookCrypto = nil- clonedConf.Onboarding = nil- clonedConf.Publish = nil+ clonedConf.Onboarding.Store(nil)+ clonedConf.Publish.Store(nil)clonedConf.CookieKey = ""clonedConf.MCPOAuth = ""clonedConf.CloudRegion = 0if nil != clonedConf.OIDC {clonedConf.OIDC.ClientSecret = ""}- if nil != clonedConf.AI {- for _, provider := range clonedConf.AI.Providers {+ if nil != clonedConf.AI.Load() {+ for _, provider := range clonedConf.AI.Load().Providers {if nil != provider {provider.APIKey = ""provider.Headers = nil}}- if nil != clonedConf.AI.Embedding {- clonedConf.AI.Embedding.APIKey = ""+ if nil != clonedConf.AI.Load().Embedding {+ clonedConf.AI.Load().Embedding.APIKey = ""}- if nil != clonedConf.AI.Rerank {- clonedConf.AI.Rerank.APIKey = ""+ if nil != clonedConf.AI.Load().Rerank {+ clonedConf.AI.Load().Rerank.APIKey = ""}- if nil != clonedConf.AI.Decision {- clonedConf.AI.Decision.APIKey = ""- for _, profile := range clonedConf.AI.Decision.Profiles {+ if nil != clonedConf.AI.Load().Decision {+ clonedConf.AI.Load().Decision.APIKey = ""+ for _, profile := range clonedConf.AI.Load().Decision.Profiles {if profile != nil {profile.APIKey = ""}}}- clonedConf.AI.MCP = nil+ clonedConf.AI.Load().MCP = nil}data, err := gulu.JSON.MarshalIndentJSON(clonedConf, "", " ")@@ -679,36 +678,37 @@ var importConf = contractHandler(apicontract.SystemImportConf, func(c *gin.Conteret = apicontract.Failure[apicontract.Null](-1, err.Error())return}- preserveImportedAISecrets(importedConf.AI, model.Conf.AI)- if err = validateAIProviderHeaders(importedConf.AI); err != nil {+ // 导入的旧版配置与启动加载执行相同的格式迁移+ model.ApplyImportedConfMigrations(importedConf, data)+ preserveImportedAISecrets(importedConf.AI.Load(), model.Conf.AI.Load())+ if err = validateAIProviderHeaders(importedConf.AI.Load()); err != nil {ret = apicontract.Failure[apicontract.Null](-1, err.Error())return}- if nil != importedConf.System && nil != model.Conf.System {- // 更新通道是应用级全局设置,导入工作空间配置时保持不变。- importedConf.System.UpdateChannel = model.Conf.System.UpdateChannel+ if nil != importedConf.System.Load() && nil != model.Conf.System.Load(+ // 更新通道是应用级全局设置,导入工作空间配置时保持不变。+ ) {++ importedConf.System.Load().UpdateChannel = model.Conf.System.Load().UpdateChannel// 网络代理依赖本机环境,导入设置时保持不变。- importedConf.System.NetworkProxy = model.Conf.System.NetworkProxy- }-- importedConf.FileTree = conf.NormalizeFileTree(importedConf.FileTree)- importedConf.Editor = conf.NormalizeEditor(importedConf.Editor)- importedConf.Export = conf.NormalizeExport(importedConf.Export)- importedConf.Search = conf.NormalizeSearch(importedConf.Search)- importedConf.Flashcard, _ = conf.NormalizeFlashcard(importedConf.Flashcard)- model.Conf.FileTree = importedConf.FileTree- model.Conf.Tag = importedConf.Tag- model.Conf.Editor = importedConf.Editor- model.Conf.Export = importedConf.Export- model.Conf.Graph = importedConf.Graph- model.Conf.UILayout = importedConf.UILayout- model.Conf.System = importedConf.System- model.Conf.Keymap = importedConf.Keymap- model.Conf.Search = importedConf.Search- model.Conf.Flashcard = importedConf.Flashcard- model.Conf.AI = importedConf.AI- model.Conf.Bazaar = importedConf.Bazaar+ importedConf.System.Load().NetworkProxy = model.Conf.System.Load().NetworkProxy+ }++ model.NormalizeAppConf(importedConf)+ model.Conf.FileTree.Store(importedConf.FileTree.Load())+ model.Conf.Tag.Store(importedConf.Tag.Load())+ model.Conf.Editor.Store(importedConf.Editor.Load())+ model.Conf.Export.Store(importedConf.Export.Load())+ model.Conf.Graph.Store(importedConf.Graph.Load())+ model.Conf.UILayout.Store(importedConf.UILayout.Load())+ model.Conf.System.Store(importedConf.System.Load())+ model.Conf.Keymap.Store(importedConf.Keymap.Load())+ model.Conf.Search.Store(importedConf.Search.Load())+ model.Conf.Flashcard.Store(importedConf.Flashcard.Load())+ model.Conf.AI.Store(importedConf.AI.Load())+ model.Conf.Bazaar.Store(importedConf.Bazaar.Load())model.Conf.Save()+ model.ApplyConfRuntime()logging.LogInfof("imported conf")return@@ -763,8 +763,8 @@ var getConf = contractHandler(apicontract.SystemGetConf, func(c *gin.Context, rereturn}- if !maskedConf.Sync.Enabled || (0 == maskedConf.Sync.Provider && !model.IsSubscriber()) {- maskedConf.Sync.Stat = model.Conf.Language(53)+ if !maskedConf.Sync.Load().Enabled || (0 == maskedConf.Sync.Load().Provider && !model.IsSubscriber()) {+ maskedConf.Sync.Load().Stat = model.Conf.Language(53)}// REF: https://github.com/siyuan-note/siyuan/issues/11364@@ -780,18 +780,18 @@ var getConf = contractHandler(apicontract.SystemGetConf, func(c *gin.Context, re}if model.IsReadOnlyRoleContext(c) {- maskedConf.UILayout = &conf.UILayout{}+ maskedConf.UILayout.Store(&conf.UILayout{})}// 浏览器环境下不返回工作空间绝对路径,避免泄露用户名等敏感信息// 原生客户端(桌面 Electron、移动端)UA 以 "SiYuan/" 开头,照常返回真实路径// REF: https://github.com/siyuan-note/siyuan/issues/17410if util.IsBrowserRequest(c) {- maskedConf.System.WorkspaceDir = ""- maskedConf.System.AppDir = ""- maskedConf.System.ConfDir = ""- maskedConf.System.DataDir = ""- maskedConf.System.HomeDir = ""+ maskedConf.System.Load().WorkspaceDir = ""+ maskedConf.System.Load().AppDir = ""+ maskedConf.System.Load().ConfDir = ""+ maskedConf.System.Load().DataDir = ""+ maskedConf.System.Load().HomeDir = ""}config, err := systemConfPayload(maskedConf)@@ -865,8 +865,7 @@ var setAPIToken = contractHandler(apicontract.SystemSetAPIToken, func(c *gin.Conreturn}- model.Conf.Api.Token = token- model.Conf.Save()+ model.UpdateAPIConf(func(s *conf.API) { s.Token = token })return})@@ -963,8 +962,7 @@ var setOIDC = contractHandler(apicontract.SystemSetOIDC, func(c *gin.Context, re})var setFollowSystemLockScreen = contractHandler(apicontract.SetFollowSystemLockScreen, func(c *gin.Context, request apicontract.LockScreenRequest) apicontract.Response[apicontract.Null] {- model.Conf.System.LockScreenMode = int(request.LockScreenMode)- model.Conf.Save()+ model.UpdateSystemConf(func(s *conf.System) { s.LockScreenMode = int(request.LockScreenMode) })return apicontract.Success(apicontract.Null{})})@@ -1050,40 +1048,36 @@ var removeCustomFont = contractHandler(apicontract.SystemRemoveCustomFont, func(var editor *conf.Editorvar appearance *conf.Appearance- globalFonts := make([]*conf.EditorFont, 0, len(model.Conf.Appearance.GlobalFontFamilies))- for _, selectedFont := range model.Conf.Appearance.GlobalFontFamilies {+ globalFonts := make([]*conf.EditorFont, 0, len(model.Conf.Appearance.Load().GlobalFontFamilies))+ for _, selectedFont := range model.Conf.Appearance.Load().GlobalFontFamilies {if nil != selectedFont && selectedFont.Family != font.Family {globalFonts = append(globalFonts, selectedFont)}}- if len(globalFonts) != len(model.Conf.Appearance.GlobalFontFamilies) {- model.Conf.Appearance.GlobalFontFamilies = globalFonts- appearance = model.Conf.Appearance+ if len(globalFonts) != len(model.Conf.Appearance.Load().GlobalFontFamilies) {+ appearance = model.UpdateAppearanceConf(func(a *conf.Appearance) { a.GlobalFontFamilies = globalFonts })}- fonts := make([]*conf.EditorFont, 0, len(model.Conf.Editor.FontFamilies))- for _, selectedFont := range model.Conf.Editor.FontFamilies {+ fonts := make([]*conf.EditorFont, 0, len(model.Conf.Editor.Load().FontFamilies))+ for _, selectedFont := range model.Conf.Editor.Load().FontFamilies {if nil != selectedFont && selectedFont.Family != font.Family {fonts = append(fonts, selectedFont)}}- codeFonts := make([]*conf.EditorFont, 0, len(model.Conf.Editor.CodeFontFamilies))- for _, selectedFont := range model.Conf.Editor.CodeFontFamilies {+ codeFonts := make([]*conf.EditorFont, 0, len(model.Conf.Editor.Load().CodeFontFamilies))+ for _, selectedFont := range model.Conf.Editor.Load().CodeFontFamilies {if nil != selectedFont && selectedFont.Family != font.Family {codeFonts = append(codeFonts, selectedFont)}}- if len(fonts) != len(model.Conf.Editor.FontFamilies) ||- len(codeFonts) != len(model.Conf.Editor.CodeFontFamilies) {- model.Conf.Editor.FontFamilies = fonts- model.Conf.Editor.CodeFontFamilies = codeFonts- model.Conf.Editor.FontFamily = ""- model.Conf.Editor.FontWeight = 400- model.Conf.Editor.FontFamilyDisplay = ""- model.Conf.Editor.NormalizeFontFamilies()- editor = model.Conf.Editor- }- if nil != editor || nil != appearance {- model.Conf.Save()+ if len(fonts) != len(model.Conf.Editor.Load().FontFamilies) ||+ len(codeFonts) != len(model.Conf.Editor.Load().CodeFontFamilies) {+ editor = model.UpdateEditorConf(func(e *conf.Editor) {+ e.FontFamilies = fonts+ e.CodeFontFamilies = codeFonts+ e.FontFamily = ""+ e.FontWeight = 400+ e.FontFamilyDisplay = ""+ })}if nil != appearance {util.BroadcastByType("main", "setAppearance", 0, "", appearance)@@ -1174,26 +1168,24 @@ var setAppearanceMode = contractHandler(apicontract.SystemSetAppearanceMode, funret = apicontract.Success(apicontract.SystemAppearanceData{})mode := int(request.Mode)- model.Conf.Appearance.Mode = mode+ model.UpdateAppearanceConf(func(s *conf.Appearance) { s.Mode = mode })model.LoadThemes()model.WatchThemes()model.Conf.Save()- ret = apicontract.Success(apicontract.SystemAppearanceData{Appearance: settingAppearancePayload(model.Conf.Appearance)})+ ret = apicontract.Success(apicontract.SystemAppearanceData{Appearance: settingAppearancePayload(model.Conf.Appearance.Load())})return})var setNetworkServe = contractHandler(apicontract.SetNetworkServe, func(c *gin.Context, request apicontract.NetworkServeRequest) apicontract.Response[apicontract.Null] {- model.Conf.System.NetworkServe = request.NetworkServe- model.Conf.Save()+ model.UpdateSystemConf(func(s *conf.System) { s.NetworkServe = request.NetworkServe })util.PushMsg(model.Conf.Language(42), 1000*15)time.Sleep(time.Second * 3)return apicontract.Success(apicontract.Null{})})var setNetworkServeTLS = contractHandler(apicontract.SetNetworkServeTLS, func(c *gin.Context, request apicontract.NetworkServeTLSRequest) apicontract.Response[apicontract.Null] {- model.Conf.System.NetworkServeTLS = request.NetworkServeTLS- model.Conf.Save()+ model.UpdateSystemConf(func(s *conf.System) { s.NetworkServeTLS = request.NetworkServeTLS })util.PushMsg(model.Conf.Language(42), 1000*15)time.Sleep(time.Second * 3)return apicontract.Success(apicontract.Null{})@@ -1326,20 +1318,18 @@ var importTLSCABundle = contractHandler(apicontract.SystemImportTLSCABundle, fun})var setAutoLaunch = contractHandler(apicontract.SetAutoLaunch, func(c *gin.Context, request apicontract.AutoLaunchRequest) apicontract.Response[apicontract.Null] {- model.Conf.System.AutoLaunch2 = int(request.AutoLaunch)+ model.UpdateSystemConf(func(value *conf.System) { value.AutoLaunch2 = int(request.AutoLaunch) })model.Conf.Save()return apicontract.Success(apicontract.Null{})})var setDownloadInstallPkg = contractHandler(apicontract.SetDownloadInstallPkg, func(c *gin.Context, request apicontract.DownloadInstallPkgRequest) apicontract.Response[apicontract.Null] {- model.Conf.System.DownloadInstallPkg = request.DownloadInstallPkg- model.Conf.Save()+ model.UpdateSystemConf(func(s *conf.System) { s.DownloadInstallPkg = request.DownloadInstallPkg })return apicontract.Success(apicontract.Null{})})var setSettingsWindow = contractHandler(apicontract.SetSettingsWindow, func(c *gin.Context, request apicontract.SettingsWindowRequest) apicontract.Response[apicontract.Null] {- model.Conf.System.SettingsWindow = request.SettingsWindow- model.Conf.Save()+ model.UpdateSystemConf(func(s *conf.System) { s.SettingsWindow = request.SettingsWindow })return apicontract.Success(apicontract.Null{})})@@ -1351,10 +1341,9 @@ var setUpdateChannel = contractHandler(apicontract.SetUpdateChannel, func(c *gin})var setNetworkProxy = contractHandler(apicontract.SetNetworkProxy, func(c *gin.Context, request apicontract.NetworkProxy) apicontract.Response[apicontract.Null] {- model.Conf.System.NetworkProxy = &conf.NetworkProxy{Scheme: request.Scheme, Host: request.Host, Port: request.Port}- model.Conf.Save()- proxyURL := model.Conf.System.NetworkProxy.String()- util.SetNetworkProxy(proxyURL, model.Conf.System.NetworkProxy.IsSystem())+ model.UpdateSystemConf(func(s *conf.System) {+ s.NetworkProxy = &conf.NetworkProxy{Scheme: request.Scheme, Host: request.Host, Port: request.Port}+ })util.PushMsg(model.Conf.Language(102), 3000)return apicontract.Success(apicontract.Null{})})diff --git a/kernel/api/system_contract.go b/kernel/api/system_contract.goindex 90d264121f..e66c6f058c 100644--- a/kernel/api/system_contract.go+++ b/kernel/api/system_contract.go@@ -17,8 +17,8 @@ func systemConfPayload(value *model.AppConf) (result *apicontract.SystemAppConf,if err == nil {err = json.Unmarshal(encoded, &result)}- if err == nil && result != nil && value.AI != nil && result.AI != nil {- result.AI.Decision = settingDecisionPayload(value.AI.Decision)+ if err == nil && result != nil && value.AI.Load() != nil && result.AI != nil {+ result.AI.Decision = settingDecisionPayload(value.AI.Load().Decision)}return}diff --git a/kernel/api/system_export_secrets_test.go b/kernel/api/system_export_secrets_test.goindex 2aa2c37540..5e93e7e955 100644--- a/kernel/api/system_export_secrets_test.go+++ b/kernel/api/system_export_secrets_test.go@@ -22,14 +22,14 @@ func TestAPIContractSystemExportSecrets(t *testing.T) {for _, populated := range []bool{true, false} {model.Conf = model.NewAppConf()if populated {- model.Conf.AI = conf.NewAI()- model.Conf.AI.Decision.Profiles["typesafe"].APIKey = "export-test-decision-secret"- model.Conf.AI.Decision.Profiles["openai"].APIKey = "export-test-openai-secret"+ model.Conf.AI.Store(conf.NewAI())+ model.Conf.AI.Load().Decision.Profiles["typesafe"].APIKey = "export-test-decision-secret"+ model.Conf.AI.Load().Decision.Profiles["openai"].APIKey = "export-test-openai-secret"model.Conf.OIDC = conf.NewOIDC()model.Conf.OIDC.ClientID = "test-client"model.Conf.OIDC.ClientSecret = "export-test-oidc-secret"} else {- model.Conf.AI = &conf.AI{}+ model.Conf.AI.Store(&conf.AI{})model.Conf.OIDC = nil}before, err := json.Marshal(model.Conf)@@ -66,11 +66,11 @@ func TestAPIContractSystemExportSecrets(t *testing.T) {t.Fatal(err)}if populated {- if exported.AI.Decision.APIKey != "" || exported.AI.Decision.Profiles["typesafe"].APIKey != "" || exported.AI.Decision.Profiles["openai"].APIKey != "" || exported.OIDC.ClientSecret != "" ||+ if exported.AI.Load().Decision.APIKey != "" || exported.AI.Load().Decision.Profiles["typesafe"].APIKey != "" || exported.AI.Load().Decision.Profiles["openai"].APIKey != "" || exported.OIDC.ClientSecret != "" ||bytes.Contains(data, []byte("export-test-")) {t.Fatal("export retained secrets")}- if exported.AI.Decision.Profiles["typesafe"].Name != model.Conf.AI.Decision.Profiles["typesafe"].Name || exported.OIDC.ClientID != "test-client" {+ if exported.AI.Load().Decision.Profiles["typesafe"].Name != model.Conf.AI.Load().Decision.Profiles["typesafe"].Name || exported.OIDC.ClientID != "test-client" {t.Fatal("export lost non-secret settings")}}diff --git a/kernel/api/system_proxy_import_test.go b/kernel/api/system_proxy_import_test.goindex c108dce14d..ba8801054c 100644--- a/kernel/api/system_proxy_import_test.go+++ b/kernel/api/system_proxy_import_test.go@@ -34,7 +34,7 @@ func TestConfTransferPreservesLocalNetworkProxy(t *testing.T) {} {t.Run("local-"+proxy.Scheme, func(t *testing.T) {model.Conf = model.NewAppConf()- model.Conf.System = &conf.System{NetworkProxy: &proxy}+ model.Conf.System.Store(&conf.System{NetworkProxy: &proxy})recorder := httptest.NewRecorder()engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/export", nil))response := struct {@@ -54,10 +54,10 @@ func TestConfTransferPreservesLocalNetworkProxy(t *testing.T) {if err = json.Unmarshal(data, exported); err != nil {t.Fatal(err)}- if exported.System.NetworkProxy == nil || *exported.System.NetworkProxy != (conf.NetworkProxy{}) {- t.Fatalf("export retained network proxy: %+v", exported.System.NetworkProxy)+ if exported.System.Load().NetworkProxy == nil || *exported.System.Load().NetworkProxy != (conf.NetworkProxy{}) {+ t.Fatalf("export retained network proxy: %+v", exported.System.Load().NetworkProxy)}- if *model.Conf.System.NetworkProxy != proxy {+ if *model.Conf.System.Load().NetworkProxy != proxy {t.Fatal("export changed local proxy")}for _, payload := range []string{@@ -89,8 +89,8 @@ func TestConfTransferPreservesLocalNetworkProxy(t *testing.T) {if err = json.Unmarshal(recorder.Body.Bytes(), &result); err != nil || result.Code != 0 {t.Fatalf("import failed: %s (%v)", recorder.Body.String(), err)}- if !reflect.DeepEqual(model.Conf.System.NetworkProxy, &proxy) {- t.Fatalf("import changed local proxy: %+v", model.Conf.System.NetworkProxy)+ if !reflect.DeepEqual(model.Conf.System.Load().NetworkProxy, &proxy) {+ t.Fatalf("import changed local proxy: %+v", model.Conf.System.Load().NetworkProxy)}}})diff --git a/kernel/api/system_test.go b/kernel/api/system_test.goindex 5422697710..c397ae12fc 100644--- a/kernel/api/system_test.go+++ b/kernel/api/system_test.go@@ -193,10 +193,10 @@ func TestGetConfUILayoutByRole(t *testing.T) {oldConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()- model.Conf.Sync.Enabled = true- model.Conf.Sync.Provider = 1- model.Conf.System = &conf.System{}+ model.Conf.Sync.Store(conf.NewSync())+ model.Conf.Sync.Load().Enabled = true+ model.Conf.Sync.Load().Provider = 1+ model.Conf.System.Store(&conf.System{})uiLayout := conf.UILayout{"layout": map[string]any{"instance": "Layout",@@ -217,7 +217,7 @@ func TestGetConfUILayoutByRole(t *testing.T) {"data": []any{map[string]any{"title": "private-dock-title"}},},}- model.Conf.UILayout = &uiLayout+ model.Conf.UILayout.Store(&uiLayout)t.Cleanup(func() {model.Conf = oldConf})diff --git a/kernel/api/tag.go b/kernel/api/tag.goindex 5bd6886882..6655ac64c6 100644--- a/kernel/api/tag.go+++ b/kernel/api/tag.go@@ -19,6 +19,7 @@ package apiimport ("github.com/gin-gonic/gin""github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/util")@@ -40,8 +41,7 @@ func tagContracts(tags model.Tags) []*apicontract.TagData {var getTag = contractHandler(apicontract.GetTag, func(c *gin.Context, request apicontract.GetTagRequest) apicontract.Response[[]*apicontract.TagData] {if model.IsAdminRoleContext(c) && !model.IsReadOnlyRoleContext(c) {- model.Conf.Tag.Sort = int(request.Sort)- model.Conf.Save()+ model.UpdateTagConf(func(s *conf.Tag) { s.Sort = int(request.Sort) })}tags := model.BuildTags(request.IgnoreMaxListHint, request.App, int(request.Sort))if model.IsReadOnlyRoleContext(c) {diff --git a/kernel/api/ui.go b/kernel/api/ui.goindex 4f0f6c1bf0..5955a82e89 100644--- a/kernel/api/ui.go+++ b/kernel/api/ui.go@@ -64,7 +64,7 @@ var reloadUI = contractHandler(apicontract.ReloadUI, func(c *gin.Context, requesvar reloadIcon = contractHandler(apicontract.ReloadIcon, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.Null] {model.LoadIcons()- util.BroadcastByType("main", "setAppearance", 0, "", model.Conf.Appearance)+ util.BroadcastByType("main", "setAppearance", 0, "", model.Conf.Appearance.Load())return apicontract.Success(apicontract.Null{})})@@ -72,7 +72,7 @@ var reloadIcon = contractHandler(apicontract.ReloadIcon, func(c *gin.Context, revar reloadTheme = contractHandler(apicontract.ReloadTheme, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.Null] {model.LoadThemes()- util.BroadcastByType("main", "setAppearance", 0, "", model.Conf.Appearance)+ util.BroadcastByType("main", "setAppearance", 0, "", model.Conf.Appearance.Load())return apicontract.Success(apicontract.Null{})})diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex 0a19094dfb..6788196863 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -48,6 +48,7 @@ type Definition struct {FastJSON boolEmptyResponseStatuses []intAdditionalErrorStatuses []int+ Setting SettingWrite}type Endpoint[Request, Data any] struct {@@ -72,6 +73,7 @@ type ResponseOptions struct {FastJSON boolEmptyResponseStatuses []intAdditionalErrorStatuses []int+ Setting SettingWrite}var definitions []Definition@@ -160,7 +162,7 @@ func define[Request, Data any](name, path string, authorization Authorization, bErrorCodes: append([]int{-1}, response.AdditionalCodes...), ErrorText: response.Text, DataNonNullable: response.NonNullable, DataOnError: response.DataOnError,Output: response.Output, ErrorStatus: response.ErrorStatus, NoContent: response.NoContent, WebSocket: response.WebSocket, SSE: response.SSE, Proxy: response.Proxy, PluginService: response.PluginService,AdditionalErrorStatuses: append([]int(nil), response.AdditionalErrorStatuses...), ContentVariants: append([]HTTPContentVariant(nil), response.ContentVariants...), FastJSON: response.FastJSON,- EmptyResponseStatuses: append([]int(nil), response.EmptyResponseStatuses...)}+ EmptyResponseStatuses: append([]int(nil), response.EmptyResponseStatuses...), Setting: response.Setting}definitions = append(definitions, d)return Endpoint[Request, Data]{definition: d}}@@ -281,8 +283,8 @@ var (ClearTempFiles = define[EmptyRequest, Null]("clearTempFiles", "/api/system/clearTempFiles", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")VacuumDataIndex = define[EmptyRequest, Null]("vacuumDataIndex", "/api/system/vacuumDataIndex", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")RebuildDataIndex = define[EmptyRequest, Null]("rebuildDataIndex", "/api/system/rebuildDataIndex", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")- IgnoreAddMicrosoftDefenderExclusion = define[EmptyRequest, Null]("ignoreAddMicrosoftDefenderExclusion", "/api/system/ignoreAddMicrosoftDefenderExclusion", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")- AddMicrosoftDefenderExclusion = define[EmptyRequest, Null]("addMicrosoftDefenderExclusion", "/api/system/addMicrosoftDefenderExclusion", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")+ IgnoreAddMicrosoftDefenderExclusion = define[EmptyRequest, Null]("ignoreAddMicrosoftDefenderExclusion", "/api/system/ignoreAddMicrosoftDefenderExclusion", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{Setting: SettingWrite{Namespace: "system"}}, "POST")+ AddMicrosoftDefenderExclusion = define[EmptyRequest, Null]("addMicrosoftDefenderExclusion", "/api/system/addMicrosoftDefenderExclusion", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{Setting: SettingWrite{Namespace: "system"}}, "POST")GetWorkspaceInfo = define[EmptyRequest, WorkspaceInfoData]("getWorkspaceInfo", "/api/system/getWorkspaceInfo", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")// 无需参数,要求管理员权限并允许只读模式,统计当前内核工作空间的本地文件大小。// totalSize 为普通文件字节数之和,assetsSize 是 data 的子集,不能重复累加;不含目录分配空间或链接目标。@@ -295,15 +297,15 @@ var (GetRuntimeInfo = define[EmptyRequest, SystemRuntimeInfoData]("getRuntimeInfo", "/api/system/getRuntimeInfo", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")CurrentTime = define[EmptyRequest, int64]("currentTime", "/api/system/currentTime", PublicAccess, NoBody, ResponseOptions{}, "POST")BootProgress = define[EmptyRequest, BootProgressData]("bootProgress", "/api/system/bootProgress", PublicAccess, NoBody, ResponseOptions{}, "GET", "POST")- SetFollowSystemLockScreen = define[LockScreenRequest, Null]("setFollowSystemLockScreen", "/api/system/setFollowSystemLockScreen", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")- SetAutoLaunch = define[AutoLaunchRequest, Null]("setAutoLaunch", "/api/system/setAutoLaunch", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")- SetDownloadInstallPkg = define[DownloadInstallPkgRequest, Null]("setDownloadInstallPkg", "/api/system/setDownloadInstallPkg", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+ SetFollowSystemLockScreen = define[LockScreenRequest, Null]("setFollowSystemLockScreen", "/api/system/setFollowSystemLockScreen", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "system"}}, "POST")+ SetAutoLaunch = define[AutoLaunchRequest, Null]("setAutoLaunch", "/api/system/setAutoLaunch", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "system"}}, "POST")+ SetDownloadInstallPkg = define[DownloadInstallPkgRequest, Null]("setDownloadInstallPkg", "/api/system/setDownloadInstallPkg", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "system"}}, "POST")// 更新工作空间的独立设置窗口开关,仅桌面 Electron 客户端使用。- SetSettingsWindow = define[SettingsWindowRequest, Null]("setSettingsWindow", "/api/system/setSettingsWindow", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")- SetNetworkServe = define[NetworkServeRequest, Null]("setNetworkServe", "/api/system/setNetworkServe", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")- SetNetworkServeTLS = define[NetworkServeTLSRequest, Null]("setNetworkServeTLS", "/api/system/setNetworkServeTLS", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")- SetUpdateChannel = define[UpdateChannelRequest, Null]("setUpdateChannel", "/api/system/setUpdateChannel", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")- SetNetworkProxy = define[NetworkProxy, Null]("setNetworkProxy", "/api/system/setNetworkProxy", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+ SetSettingsWindow = define[SettingsWindowRequest, Null]("setSettingsWindow", "/api/system/setSettingsWindow", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "system"}}, "POST")+ SetNetworkServe = define[NetworkServeRequest, Null]("setNetworkServe", "/api/system/setNetworkServe", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "system"}}, "POST")+ SetNetworkServeTLS = define[NetworkServeTLSRequest, Null]("setNetworkServeTLS", "/api/system/setNetworkServeTLS", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "system"}}, "POST")+ SetUpdateChannel = define[UpdateChannelRequest, Null]("setUpdateChannel", "/api/system/setUpdateChannel", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "system"}}, "POST")+ SetNetworkProxy = define[NetworkProxy, Null]("setNetworkProxy", "/api/system/setNetworkProxy", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "system"}}, "POST")GetBookmarkLabels = define[EmptyRequest, []string]("getBookmarkLabels", "/api/attr/getBookmarkLabels", AuthenticatedAccess, NoBody, ResponseOptions{}, "POST")BatchGetBlockAttrs = define[BlockIDsRequest, map[string]map[string]string]("batchGetBlockAttrs", "/api/attr/batchGetBlockAttrs", AuthenticatedAccess, JSONBody, ResponseOptions{NonNullable: true}, "POST")GetDOMText = define[DOMTextRequest, string]("getDOMText", "/api/block/getDOMText", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")@@ -314,15 +316,15 @@ var ()var (- SetEditorReadOnly = define[EditorReadOnlyRequest, Null]("setEditorReadOnly", "/api/setting/setEditorReadOnly", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")- AddVirtualBlockRefExclude = define[VirtualBlockRefRequest, Null]("addVirtualBlockRefExclude", "/api/setting/addVirtualBlockRefExclude", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")- AddVirtualBlockRefInclude = define[VirtualBlockRefRequest, Null]("addVirtualBlockRefInclude", "/api/setting/addVirtualBlockRefInclude", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+ SetEditorReadOnly = define[EditorReadOnlyRequest, Null]("setEditorReadOnly", "/api/setting/setEditorReadOnly", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "editor"}}, "POST")+ AddVirtualBlockRefExclude = define[VirtualBlockRefRequest, Null]("addVirtualBlockRefExclude", "/api/setting/addVirtualBlockRefExclude", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "editor"}}, "POST")+ AddVirtualBlockRefInclude = define[VirtualBlockRefRequest, Null]("addVirtualBlockRefInclude", "/api/setting/addVirtualBlockRefInclude", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "editor"}}, "POST")RefreshVirtualBlockRef = define[EmptyRequest, Null]("refreshVirtualBlockRef", "/api/setting/refreshVirtualBlockRef", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")GetPandocBin = define[EmptyRequest, string]("getPandocBin", "/api/setting/getPandocBin", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")ReindexHistory = define[EmptyRequest, Null]("reindexHistory", "/api/history/reindexHistory", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")ClearWorkspaceHistory = define[EmptyRequest, Null]("clearWorkspaceHistory", "/api/history/clearWorkspaceHistory", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")BatchSetBlockAttrs = define[BatchSetBlockAttrsRequest, Null]("batchSetBlockAttrs", "/api/attr/batchSetBlockAttrs", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")- GetTag = define[GetTagRequest, []*TagData]("getTag", "/api/tag/getTag", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")+ GetTag = define[GetTagRequest, []*TagData]("getTag", "/api/tag/getTag", AuthenticatedAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "tag"}}, "POST"))var (@@ -347,9 +349,9 @@ var (UnlockAndOpenNotebook = define[UnlockNotebookRequest, Null]("unlockAndOpenNotebook", "/api/notebook/unlockAndOpenNotebook", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")LockNotebook = define[NotebookIDRequest, Null]("lockNotebook", "/api/notebook/lockNotebook", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")// 保存本机加密笔记本锁屏策略,成功后广播 system 设置变更通知,供其他客户端重新读取配置。- SetEncryptedNotebookFollowSystemLock = define[EncryptedNotebookFollowSystemLockRequest, Null]("setEncryptedNotebookFollowSystemLock", "/api/notebook/setEncryptedNotebookFollowSystemLock", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+ SetEncryptedNotebookFollowSystemLock = define[EncryptedNotebookFollowSystemLockRequest, Null]("setEncryptedNotebookFollowSystemLock", "/api/notebook/setEncryptedNotebookFollowSystemLock", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "system"}}, "POST")LockEncryptedNotebooksOnSystemLock = define[EmptyRequest, Null]("lockEncryptedNotebooksOnSystemLock", "/api/notebook/lockEncryptedNotebooksOnSystemLock", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")- SetNotebookCryptoAutoLock = define[NotebookCryptoAutoLockRequest, Null]("setNotebookCryptoAutoLock", "/api/notebook/setNotebookCryptoAutoLock", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+ SetNotebookCryptoAutoLock = define[NotebookCryptoAutoLockRequest, Null]("setNotebookCryptoAutoLock", "/api/notebook/setNotebookCryptoAutoLock", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "notebookCrypto"}}, "POST")ChangeMasterPassword = define[ChangeMasterPasswordRequest, Null]("changeMasterPassword", "/api/notebook/changeMasterPassword", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")ExportNotebookCryptoBackup = define[EmptyRequest, NotebookCryptoBackupData]("exportNotebookCryptoBackup", "/api/notebook/exportNotebookCryptoBackup", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")TouchEncryptedNotebooks = define[EmptyRequest, Null]("touchEncryptedNotebooks", "/api/notebook/touchEncryptedNotebooks", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")@@ -511,26 +513,26 @@ var ReloadTheme = define[EmptyRequest, Null]("reloadTheme", "/api/ui/reloadThemevar GetLocalStorage = define[EmptyRequest, map[string]JSONValue]("getLocalStorage", "/api/storage/getLocalStorage", AuthenticatedAccess, NoBody, ResponseOptions{}, "POST")var GetLocalStorageVal = define[StorageKeyRequest, JSONValue]("getLocalStorageVal", "/api/storage/getLocalStorageVal", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")var GetLocalStorageVals = define[StorageKeysRequest, map[string]JSONValue]("getLocalStorageVals", "/api/storage/getLocalStorageVals", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")-var SetLocalStorageVal = define[StorageSetRequest, Null]("setLocalStorageVal", "/api/storage/setLocalStorageVal", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SetLocalStorageVals = define[StorageSetKeysRequest, Null]("setLocalStorageVals", "/api/storage/setLocalStorageVals", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var RemoveLocalStorageVal = define[StorageRemoveRequest, Null]("removeLocalStorageVal", "/api/storage/removeLocalStorageVal", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var RemoveLocalStorageVals = define[StorageRemoveKeysRequest, Null]("removeLocalStorageVals", "/api/storage/removeLocalStorageVals", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetLocalStorageVal = define[StorageSetRequest, Null]("setLocalStorageVal", "/api/storage/setLocalStorageVal", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "localStorage", Mode: SettingSilent}}, "POST")+var SetLocalStorageVals = define[StorageSetKeysRequest, Null]("setLocalStorageVals", "/api/storage/setLocalStorageVals", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "localStorage", Mode: SettingSilent}}, "POST")+var RemoveLocalStorageVal = define[StorageRemoveRequest, Null]("removeLocalStorageVal", "/api/storage/removeLocalStorageVal", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "localStorage", Mode: SettingSilent}}, "POST")+var RemoveLocalStorageVals = define[StorageRemoveKeysRequest, Null]("removeLocalStorageVals", "/api/storage/removeLocalStorageVals", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "localStorage", Mode: SettingSilent}}, "POST")var GetOutlineStorage = define[OutlineStorageRequest, map[string]JSONValue]("getOutlineStorage", "/api/storage/getOutlineStorage", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")-var SetOutlineStorage = define[OutlineStorageSetRequest, Null]("setOutlineStorage", "/api/storage/setOutlineStorage", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var RemoveOutlineStorage = define[OutlineStorageRequest, Null]("removeOutlineStorage", "/api/storage/removeOutlineStorage", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetOutlineStorage = define[OutlineStorageSetRequest, Null]("setOutlineStorage", "/api/storage/setOutlineStorage", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "storage"}}, "POST")+var RemoveOutlineStorage = define[OutlineStorageRequest, Null]("removeOutlineStorage", "/api/storage/removeOutlineStorage", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "storage"}}, "POST")var GetViewState = define[StorageKeyRequest, map[string]JSONValue]("getViewState", "/api/storage/getViewState", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")-var PatchViewState = define[ViewStatePatchRequest, map[string]JSONValue]("patchViewState", "/api/storage/patchViewState", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var RemoveViewState = define[StorageKeyRequest, Null]("removeViewState", "/api/storage/removeViewState", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var PatchViewState = define[ViewStatePatchRequest, map[string]JSONValue]("patchViewState", "/api/storage/patchViewState", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "storage"}}, "POST")+var RemoveViewState = define[StorageKeyRequest, Null]("removeViewState", "/api/storage/removeViewState", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "storage"}}, "POST")var GetRecentDocs = define[RecentDocsRequest, []*RecentDoc]("getRecentDocs", "/api/storage/getRecentDocs", AuthenticatedAccess, LegacyOptionalBody, ResponseOptions{}, "POST")var ResetBlockAttrs = define[EmptyRequest, Null]("resetBlockAttrs", "/api/attr/resetBlockAttrs", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")var SearchAttributeViewNonRelationKey = define[EmptyRequest, Null]("searchAttributeViewNonRelationKey", "/api/av/searchAttributeViewNonRelationKey", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")-var SetLocalStorage = define[EmptyRequest, Null]("setLocalStorage", "/api/storage/setLocalStorage", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")+var SetLocalStorage = define[EmptyRequest, Null]("setLocalStorage", "/api/storage/setLocalStorage", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{Setting: SettingWrite{Namespace: "localStorage", Mode: SettingSilent}}, "POST")var DeprecatedReloadUI = define[EmptyRequest, Null]("deprecatedReloadUI", "/api/system/reloadUI", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")var GetCriteria = define[EmptyRequest, []*Criterion]("getCriteria", "/api/storage/getCriteria", AuthenticatedAccess, NoBody, ResponseOptions{}, "POST")-var SetCriterion = define[SetCriterionRequest, Null]("setCriterion", "/api/storage/setCriterion", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var RemoveCriterion = define[RemoveCriterionRequest, Null]("removeCriterion", "/api/storage/removeCriterion", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetCriterion = define[SetCriterionRequest, Null]("setCriterion", "/api/storage/setCriterion", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "storage"}}, "POST")+var RemoveCriterion = define[RemoveCriterionRequest, Null]("removeCriterion", "/api/storage/removeCriterion", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "storage"}}, "POST")var UpdateRecentDocOpenTime = define[RecentDocUpdateRequest, Null]("updateRecentDocOpenTime", "/api/storage/updateRecentDocOpenTime", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")var UpdateRecentDocViewTime = define[RecentDocUpdateRequest, Null]("updateRecentDocViewTime", "/api/storage/updateRecentDocViewTime", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")@@ -541,8 +543,8 @@ var GetDocOutline = define[OutlineRequest, []*SearchPath]("getDocOutline", "/apivar GetDocHeadingNumbers = define[HeadingNumbersRequest, map[string]string]("getDocHeadingNumbers", "/api/outline/getDocHeadingNumbers", AuthenticatedAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var GetInlineStyles = define[EmptyRequest, *InlineStyles]("getInlineStyles", "/api/storage/getInlineStyles", AuthenticatedAccess, NoBody, ResponseOptions{}, "POST")-var SetInlineStyles = define[SetInlineStylesRequest, *InlineStyles]("setInlineStyles", "/api/storage/setInlineStyles", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SetWorkspaceAVPalette = define[WorkspaceAVPaletteRequest, *InlineStyles]("setWorkspaceAVPalette", "/api/storage/setWorkspaceAVPalette", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetInlineStyles = define[SetInlineStylesRequest, *InlineStyles]("setInlineStyles", "/api/storage/setInlineStyles", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "storage"}}, "POST")+var SetWorkspaceAVPalette = define[WorkspaceAVPaletteRequest, *InlineStyles]("setWorkspaceAVPalette", "/api/storage/setWorkspaceAVPalette", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "storage"}}, "POST")var HTML2BlockDOM = define[HTMLClipboardRequest, HTMLClipboardData]("html2BlockDOM", "/api/lute/html2BlockDOM", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")@@ -632,15 +634,15 @@ var RenderTemplate = define[RenderTemplateRequest, RenderTemplateData]("renderTe// 打开来源时需按当前工作空间的文档访问规则处理失败;该字段不是预览上下文,也不保证模板与源文档保持同步。var ManageTemplateFiles = define[TemplateFileRequest, TemplateManagementData]("manageTemplateFiles", "/api/template/manage", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{}, "POST")-var ResetGraph = define[EmptyRequest, ResetGraphData]("resetGraph", "/api/graph/resetGraph", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")+var ResetGraph = define[EmptyRequest, ResetGraphData]("resetGraph", "/api/graph/resetGraph", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{Setting: SettingWrite{Namespace: "graph"}}, "POST")-var ResetLocalGraph = define[EmptyRequest, ResetLocalGraphData]("resetLocalGraph", "/api/graph/resetLocalGraph", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")+var ResetLocalGraph = define[EmptyRequest, ResetLocalGraphData]("resetLocalGraph", "/api/graph/resetLocalGraph", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{Setting: SettingWrite{Namespace: "graph"}}, "POST")-var SetGraphConf = define[SetGraphConfRequest, GraphConfigurationData]("setGraphConf", "/api/graph/setGraphConf", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")+var SetGraphConf = define[SetGraphConfRequest, GraphConfigurationData]("setGraphConf", "/api/graph/setGraphConf", AuthenticatedAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "graph"}}, "POST")-var GetGraph = define[GlobalGraphRequest, GlobalGraphData]("getGraph", "/api/graph/getGraph", AuthenticatedAccess, JSONBody, ResponseOptions{DataOnError: true}, "POST")+var GetGraph = define[GlobalGraphRequest, GlobalGraphData]("getGraph", "/api/graph/getGraph", AuthenticatedAccess, JSONBody, ResponseOptions{DataOnError: true, Setting: SettingWrite{Namespace: "graph"}}, "POST")-var GetLocalGraph = define[LocalGraphRequest, LocalGraphData]("getLocalGraph", "/api/graph/getLocalGraph", AuthenticatedAccess, JSONBody, ResponseOptions{DataOnError: true}, "POST")+var GetLocalGraph = define[LocalGraphRequest, LocalGraphData]("getLocalGraph", "/api/graph/getLocalGraph", AuthenticatedAccess, JSONBody, ResponseOptions{DataOnError: true, Setting: SettingWrite{Namespace: "graph"}}, "POST")var RefreshBacklink = define[RefreshBacklinkRequest, Null]("refreshBacklink", "/api/ref/refreshBacklink", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")@@ -816,44 +818,44 @@ var GetInstalledTheme = define[GetInstalledThemeRequest, BazaarPackagesData]("gevar InstallBazaarTheme = define[InstallBazaarThemeRequest, BazaarAppearancePackagesData]("installBazaarTheme", "/api/bazaar/installBazaarTheme", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var UninstallBazaarTheme = define[UninstallBazaarThemeRequest, BazaarAppearancePackagesData]("uninstallBazaarTheme", "/api/bazaar/uninstallBazaarTheme", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")-var SetSyncEnable = define[SyncEnabledRequest, Null]("setSyncEnable", "/api/sync/setSyncEnable", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SetSyncInterval = define[SyncIntervalRequest, Null]("setSyncInterval", "/api/sync/setSyncInterval", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SetSyncPerception = define[SyncEnabledRequest, Null]("setSyncPerception", "/api/sync/setSyncPerception", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SetSyncLAN = define[SyncLANRequest, SyncLANStatus]("setSyncLAN", "/api/sync/setSyncLAN", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetSyncEnable = define[SyncEnabledRequest, Null]("setSyncEnable", "/api/sync/setSyncEnable", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "sync"}}, "POST")+var SetSyncInterval = define[SyncIntervalRequest, Null]("setSyncInterval", "/api/sync/setSyncInterval", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "sync"}}, "POST")+var SetSyncPerception = define[SyncEnabledRequest, Null]("setSyncPerception", "/api/sync/setSyncPerception", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "sync"}}, "POST")+var SetSyncLAN = define[SyncLANRequest, SyncLANStatus]("setSyncLAN", "/api/sync/setSyncLAN", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "sync"}}, "POST")var GetSyncLANStatus = define[EmptyRequest, SyncLANStatus]("getSyncLANStatus", "/api/sync/getSyncLANStatus", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")-var SetSyncGenerateConflictDoc = define[SyncEnabledRequest, Null]("setSyncGenerateConflictDoc", "/api/sync/setSyncGenerateConflictDoc", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SetSyncMode = define[SyncModeRequest, Null]("setSyncMode", "/api/sync/setSyncMode", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SetSyncProvider = define[SyncProviderRequest, Null]("setSyncProvider", "/api/sync/setSyncProvider", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SetSyncProviderS3 = define[SetSyncS3Request, SyncS3Data]("setSyncProviderS3", "/api/sync/setSyncProviderS3", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetSyncGenerateConflictDoc = define[SyncEnabledRequest, Null]("setSyncGenerateConflictDoc", "/api/sync/setSyncGenerateConflictDoc", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "sync"}}, "POST")+var SetSyncMode = define[SyncModeRequest, Null]("setSyncMode", "/api/sync/setSyncMode", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "sync"}}, "POST")+var SetSyncProvider = define[SyncProviderRequest, Null]("setSyncProvider", "/api/sync/setSyncProvider", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "sync"}}, "POST")+var SetSyncProviderS3 = define[SetSyncS3Request, SyncS3Data]("setSyncProviderS3", "/api/sync/setSyncProviderS3", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "sync"}}, "POST")// SetSyncProviderWebDAV 保存有效的 HTTP(S) 地址;地址不能为空,省略协议时补为 HTTPS,保留协议占位符兼容。// 用户名和密码允许为空以支持匿名访问;校验失败保留原配置,更换来源仍须补齐资源和历史快照。-var SetSyncProviderWebDAV = define[SetSyncWebDAVRequest, SyncWebDAVData]("setSyncProviderWebDAV", "/api/sync/setSyncProviderWebDAV", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetSyncProviderWebDAV = define[SetSyncWebDAVRequest, SyncWebDAVData]("setSyncProviderWebDAV", "/api/sync/setSyncProviderWebDAV", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "sync"}}, "POST")// SetSyncProviderLocal 在解析绝对路径前拒绝空白地址,避免将其当作内核工作目录保存。// 保留现有路径存在性及工作空间边界校验;失败不覆盖原配置,更换来源仍须补齐资源和历史快照。-var SetSyncProviderLocal = define[SetSyncLocalRequest, SyncLocalData]("setSyncProviderLocal", "/api/sync/setSyncProviderLocal", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetSyncProviderLocal = define[SetSyncLocalRequest, SyncLocalData]("setSyncProviderLocal", "/api/sync/setSyncProviderLocal", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "sync"}}, "POST")// ClearSyncProviderConfig 清除 provider 为 2(S3)、3(WebDAV)或 4(本地文件系统)的配置并同步落盘。// 清除当前服务时先验证资源及历史快照完整性,再关闭同步;失败时保留原配置,不删除本地或云端数据。// 响应包含当前同步开关及被清除服务的默认配置;其他服务配置、仓库密钥和下载模式保持不变。-var ClearSyncProviderConfig = define[ClearSyncProviderConfigRequest, ClearSyncProviderConfigData]("clearSyncProviderConfig", "/api/sync/clearSyncProviderConfig", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var ClearSyncProviderConfig = define[ClearSyncProviderConfigRequest, ClearSyncProviderConfigData]("clearSyncProviderConfig", "/api/sync/clearSyncProviderConfig", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "sync"}}, "POST")-var SetCloudSyncDir = define[SyncNameRequest, Null]("setCloudSyncDir", "/api/sync/setCloudSyncDir", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SetSyncAssetDownloadMode = define[SyncModeRequest, SyncAssetDownloadModeData]("setSyncAssetDownloadMode", "/api/sync/setSyncAssetDownloadMode", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetCloudSyncDir = define[SyncNameRequest, Null]("setCloudSyncDir", "/api/sync/setCloudSyncDir", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "sync"}}, "POST")+var SetSyncAssetDownloadMode = define[SyncModeRequest, SyncAssetDownloadModeData]("setSyncAssetDownloadMode", "/api/sync/setSyncAssetDownloadMode", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "sync"}}, "POST")var CreateCloudSyncDir = define[SyncNameRequest, Null]("createCloudSyncDir", "/api/sync/createCloudSyncDir", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var RemoveCloudSyncDir = define[SyncNameRequest, string]("removeCloudSyncDir", "/api/sync/removeCloudSyncDir", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var RemoveCloudSyncDir = define[SyncNameRequest, string]("removeCloudSyncDir", "/api/sync/removeCloudSyncDir", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "sync", Mode: SettingSelfManaged}}, "POST")var ListCloudSyncDir = define[EmptyRequest, CloudSyncDirsData]("listCloudSyncDir", "/api/sync/listCloudSyncDir", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var PerformSync = define[PerformSyncRequest, Null]("performSync", "/api/sync/performSync", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var PerformBootSync = define[EmptyRequest, Null]("performBootSync", "/api/sync/performBootSync", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var GetBootSync = define[EmptyRequest, Null]("getBootSync", "/api/sync/getBootSync", AuthenticatedAccess, NoBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var GetSyncInfo = define[EmptyRequest, SyncInfoData]("getSyncInfo", "/api/sync/getSyncInfo", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")var ExportSyncProviderS3 = define[EmptyRequest, SyncProviderExportData]("exportSyncProviderS3", "/api/sync/exportSyncProviderS3", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")-var ImportSyncProviderS3 = define[SyncProviderImportRequest, SyncS3Data]("importSyncProviderS3", "/api/sync/importSyncProviderS3", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{DataOnError: true}, "POST")+var ImportSyncProviderS3 = define[SyncProviderImportRequest, SyncS3Data]("importSyncProviderS3", "/api/sync/importSyncProviderS3", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{DataOnError: true, Setting: SettingWrite{Namespace: "sync"}}, "POST")var ExportSyncProviderWebDAV = define[EmptyRequest, SyncProviderExportData]("exportSyncProviderWebDAV", "/api/sync/exportSyncProviderWebDAV", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")// ImportSyncProviderWebDAV 导入后使用与保存接口相同的地址校验;空白或无效地址不覆盖原配置。-var ImportSyncProviderWebDAV = define[SyncProviderImportRequest, SyncWebDAVData]("importSyncProviderWebDAV", "/api/sync/importSyncProviderWebDAV", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{DataOnError: true}, "POST")+var ImportSyncProviderWebDAV = define[SyncProviderImportRequest, SyncWebDAVData]("importSyncProviderWebDAV", "/api/sync/importSyncProviderWebDAV", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{DataOnError: true, Setting: SettingWrite{Namespace: "sync"}}, "POST")var GetRiffCardsByBlockIDs = define[RiffBlockIDsRequest, RiffBlocksData]("getRiffCardsByBlockIDs", "/api/riff/getRiffCardsByBlockIDs", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var BatchSetRiffCardsDueTime = define[SetRiffCardsDueRequest, Null]("batchSetRiffCardsDueTime", "/api/riff/batchSetRiffCardsDueTime", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")@@ -875,8 +877,8 @@ var RemoveRiffDeck = define[RiffDeckRequest, Null]("removeRiffDeck", "/api/riff/var CreateRiffDeck = define[CreateRiffDeckRequest, *RiffDeck]("createRiffDeck", "/api/riff/createRiffDeck", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var GetRiffDecks = define[EmptyRequest, []*RiffDeck]("getRiffDecks", "/api/riff/getRiffDecks", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{NonNullable: true}, "POST")-var SetRepoIndexRetentionDays = define[SetRepoIndexRetentionDaysRequest, Null]("setRepoIndexRetentionDays", "/api/repo/setRepoIndexRetentionDays", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")-var SetRetentionIndexesDaily = define[SetRetentionIndexesDailyRequest, Null]("setRetentionIndexesDaily", "/api/repo/setRetentionIndexesDaily", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")+var SetRepoIndexRetentionDays = define[SetRepoIndexRetentionDaysRequest, Null]("setRepoIndexRetentionDays", "/api/repo/setRepoIndexRetentionDays", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "repo"}}, "POST")+var SetRetentionIndexesDaily = define[SetRetentionIndexesDailyRequest, Null]("setRetentionIndexesDaily", "/api/repo/setRetentionIndexesDaily", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "repo"}}, "POST")var GetRepoFile = define[GetRepoFileRequest, BinaryContent]("getRepoFile", "/api/repo/getRepoFile", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{Output: BinaryOutput, ErrorStatus: 200}, "POST")var RollbackRepoSnapshotFile = define[RollbackRepoSnapshotFileRequest, Null]("rollbackRepoSnapshotFile", "/api/repo/rollbackRepoSnapshotFile", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var OpenRepoSnapshotFile = define[OpenRepoSnapshotFileRequest, RepoOpenFileData]("openRepoSnapshotFile", "/api/repo/openRepoSnapshotFile", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")@@ -1034,7 +1036,7 @@ var AssetOCR = define[AssetPathRequest, AssetOCRData]("ocr", "/api/asset/ocr", Avar AIOCR = define[AssetPathRequest, AssetTextData]("aiOCR", "/api/ai/ocr", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var GetOCRConfig = define[EmptyRequest, OCRConfigData]("getOCRConfig", "/api/asset/getOCRConfig", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")-var SetOCRConfig = define[SettingOCR, SettingOCR]("setOCRConfig", "/api/asset/setOCRConfig", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetOCRConfig = define[SettingOCR, SettingOCR]("setOCRConfig", "/api/asset/setOCRConfig", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "ocr"}}, "POST")var ImportOCRModels = define[ImportOCRModelsRequest, OCRModel]("importOCRModels", "/api/asset/importOCRModels", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{}, "POST")// 重命名普通笔记本资源,并同步字面量及百分号编码的文档、数据库引用。@@ -1076,43 +1078,43 @@ var InsertLocalAssets = define[InsertLocalAssetsRequest, AssetUploadData]("inservar InsertCover = define[InsertCoverRequest, AssetInsertCoverData]("insertCover", "/api/asset/insertCover", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var UploadAsset = define[UploadAssetRequest, AssetUploadData]("uploadAsset", "/api/asset/upload", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{}, "POST")-var SetConfSnippet = define[SetConfSnippetRequest, *SettingSnpt]("setConfSnippet", "/api/setting/setSnippet", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SetBazaar = define[SetBazaarRequest, *SettingBazaar]("setBazaar", "/api/setting/setBazaar", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SetAI = define[SetAIRequest, *SettingAI]("setAI", "/api/setting/setAI", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SetSecrets = define[SetSecretsRequest, *SettingSecrets]("setSecrets", "/api/setting/setSecrets", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SetVariables = define[SetVariablesRequest, *SettingVariables]("setVariables", "/api/setting/setVariables", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetConfSnippet = define[SetConfSnippetRequest, *SettingSnpt]("setConfSnippet", "/api/setting/setSnippet", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "snippet"}}, "POST")+var SetBazaar = define[SetBazaarRequest, *SettingBazaar]("setBazaar", "/api/setting/setBazaar", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "bazaar"}}, "POST")+var SetAI = define[SetAIRequest, *SettingAI]("setAI", "/api/setting/setAI", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "ai"}}, "POST")+var SetSecrets = define[SetSecretsRequest, *SettingSecrets]("setSecrets", "/api/setting/setSecrets", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "secrets"}}, "POST")+var SetVariables = define[SetVariablesRequest, *SettingVariables]("setVariables", "/api/setting/setVariables", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "variables"}}, "POST")// SetFlashcard 使用与启动、导入相同的规范化规则;保留零张上限,非法记忆参数和权重恢复默认值。-var SetFlashcard = define[SetFlashcardRequest, *SettingFlashcard]("setFlashcard", "/api/setting/setFlashcard", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetFlashcard = define[SetFlashcardRequest, *SettingFlashcard]("setFlashcard", "/api/setting/setFlashcard", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "flashcard"}}, "POST")// SetEditor 使用与启动、导入相同的规范化规则并同步保存。锚文本长度 1–5120 保持不变,小于 1 回退 64。// 字体大小超出 9–72 回退 16;省略字体列表和图片标题字段时继续保留原有兼容行为。-var SetEditor = define[SetEditorRequest, *SettingEditor]("setEditor", "/api/setting/setEditor", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetEditor = define[SetEditorRequest, *SettingEditor]("setEditor", "/api/setting/setEditor", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "editor"}}, "POST")// PatchSetting 保留省略字段,成功后客户端重新读取配置;通知不包含密码或密钥。// export.blockRefMode 的废弃值 0、1、5 在保存前转换为 4,与启动时的转换规则一致。-var PatchSetting = define[PatchSettingRequest, Null]("patchSetting", "/api/setting/patch", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var PatchSetting = define[PatchSettingRequest, *SettingPatchData]("patchSetting", "/api/setting/patch", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{DataOnError: true, Setting: SettingWrite{Namespace: "*", Mode: SettingSelfManaged}}, "POST")// SetExport 整体替换导出配置,将 blockRefMode 的废弃值 0、1、5 转换为 4 后同步保存并回显。// 其他取值及字段省略、null 的解析行为保持不变。-var SetExport = define[SetExportRequest, *SettingExport]("setExport", "/api/setting/setExport", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetExport = define[SetExportRequest, *SettingExport]("setExport", "/api/setting/setExport", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "export"}}, "POST")// SetFiletree 使用与启动、导入相同的路径和数值规范化规则;省略顶层笔记本文档和默认图标选项时保留当前值。-var SetFiletree = define[SetFiletreeRequest, *SettingFileTree]("setFiletree", "/api/setting/setFiletree", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetFiletree = define[SetFiletreeRequest, *SettingFileTree]("setFiletree", "/api/setting/setFiletree", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "fileTree"}}, "POST")// SetSearch 使用与启动、导入相同的规范化规则;limit 小于 1 回退 64,1–31 提升至 32。// 省略汉字敏感、自定义块和脑图选项时保留当前值;反链提及关键词上限小于 1 回退 512。-var SetSearch = define[SetSearchRequest, *SettingSearch]("setSearch", "/api/setting/setSearch", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SetAppearance = define[SetAppearanceRequest, *SettingAppearance]("setAppearance", "/api/setting/setAppearance", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetSearch = define[SetSearchRequest, *SettingSearch]("setSearch", "/api/setting/setSearch", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "search"}}, "POST")+var SetAppearance = define[SetAppearanceRequest, *SettingAppearance]("setAppearance", "/api/setting/setAppearance", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "appearance"}}, "POST")// SetEntryVisibility 的版本 7 方案可用 defaults 指定 simple 或 full,未覆盖的显隐跟随该内置方案。// 省略 defaults 的方案及旧版本方案保留独立显隐语义;entries 中的布尔值始终优先,未知入口和插件排序保留。-var SetEntryVisibility = define[SetEntryVisibilityRequest, *SettingEntryVisibility]("setEntryVisibility", "/api/setting/setEntryVisibility", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SetPublish = define[SetPublishRequest, SettingPublishData]("setPublish", "/api/setting/setPublish", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetEntryVisibility = define[SetEntryVisibilityRequest, *SettingEntryVisibility]("setEntryVisibility", "/api/setting/setEntryVisibility", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "appearance"}}, "POST")+var SetPublish = define[SetPublishRequest, SettingPublishData]("setPublish", "/api/setting/setPublish", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "publish"}}, "POST")var GetBootAppearances = define[EmptyRequest, SettingBootAppearancesData]("getBootAppearances", "/api/setting/getBootAppearances", AuthenticatedAccess, NoBody, ResponseOptions{}, "POST")-var SetBootAppearance = define[SettingBootAppearanceRequest, *SettingBootAppearanceSelection]("setBootAppearance", "/api/setting/setBootAppearance", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SetBazaarPetalDisabled = define[SettingPetalDisabledRequest, SettingPetalDisabledData]("setBazaarPetalDisabled", "/api/setting/setBazaarPetalDisabled", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SetKeymap = define[SettingKeymapRequest, Null]("setKeymap", "/api/setting/setKeymap", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetBootAppearance = define[SettingBootAppearanceRequest, *SettingBootAppearanceSelection]("setBootAppearance", "/api/setting/setBootAppearance", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "appearance", Mode: SettingSilent}}, "POST")+var SetBazaarPetalDisabled = define[SettingPetalDisabledRequest, SettingPetalDisabledData]("setBazaarPetalDisabled", "/api/setting/setBazaarPetalDisabled", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "bazaar"}}, "POST")+var SetKeymap = define[SettingKeymapRequest, Null]("setKeymap", "/api/setting/setKeymap", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "keymap"}}, "POST")// 接收可选的 exit(默认 false),要求管理员权限并禁止只读写入。// 仅重置当前工作空间的普通偏好、内置快捷键和当前布局;保留笔记、历史、历史保留天数、学习进度、@@ -1122,14 +1124,14 @@ var SetKeymap = define[SettingKeymapRequest, Null]("setKeymap", "/api/setting/se// 成功后 settingsReset 通知所有主客户端直接重载;exit: true 仅让管理本地内核的桌面主窗口重载后正常退出,// 不直接停止远程内核;失败时 cancelSettingsReset 携带此次操作 ID,客户端应恢复正常保存。// 插件调用前应先取得用户确认,并确保未保存内容已经提交;重复调用恢复同一组默认值。-var ResetSettings = define[ResetSettingsRequest, Null]("resetSettings", "/api/setting/resetSettings", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var ResetSettings = define[ResetSettingsRequest, Null]("resetSettings", "/api/setting/resetSettings", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "*", Mode: SettingSelfManaged}}, "POST")// 确认 `/api/setting/resetSettings` 发起的重置,要求管理员权限并禁止只读写入。// 接收 prepareSettingsReset 通知中的一次性 token;已保存待提交内容时传入 saved: true,保存失败传 false。// 主客户端在确认前暂停布局保存;15 秒未确认则取消,收到 cancelSettingsReset 后恢复正常保存。-var ConfirmSettingsReset = define[ConfirmSettingsResetRequest, Null]("confirmSettingsReset", "/api/setting/confirmSettingsReset", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SetTheme = define[SettingThemeRequest, Null]("setTheme", "/api/setting/setTheme", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SetIcon = define[SettingIconRequest, Null]("setIcon", "/api/setting/setIcon", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var ConfirmSettingsReset = define[ConfirmSettingsResetRequest, Null]("confirmSettingsReset", "/api/setting/confirmSettingsReset", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "*", Mode: SettingSelfManaged}}, "POST")+var SetTheme = define[SettingThemeRequest, Null]("setTheme", "/api/setting/setTheme", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "appearance"}}, "POST")+var SetIcon = define[SettingIconRequest, Null]("setIcon", "/api/setting/setIcon", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "appearance"}}, "POST")var GetPublish = define[EmptyRequest, SettingPublishData]("getPublish", "/api/setting/getPublish", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")// `cached: true` 仅返回内存中的账户,未登录时返回 null。@@ -1139,7 +1141,7 @@ var GetPublish = define[EmptyRequest, SettingPublishData]("getPublish", "/api/sevar GetCloudUser = define[SettingCloudUserRequest, *SettingUser]("getCloudUser", "/api/setting/getCloudUser", AuthenticatedAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1, 255}, DataOnError: true}, "POST")var LogoutCloudUser = define[EmptyRequest, Null]("logoutCloudUser", "/api/setting/logoutCloudUser", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")var Login2faCloudUser = define[SettingLogin2faRequest, Login2faEnvelope]("login2faCloudUser", "/api/setting/login2faCloudUser", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Output: DirectJSONOutput}, "POST")-var SetEmoji = define[SettingEmojiRequest, Null]("setEmoji", "/api/setting/setEmoji", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetEmoji = define[SettingEmojiRequest, Null]("setEmoji", "/api/setting/setEmoji", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "editor"}}, "POST")// 先完整扫描普通笔记本的引用关系;扫描失败返回 code=-1,不创建清理历史或删除数据库。// 加密笔记本及笔记本级数据库不参与全局未引用清理。@@ -1319,7 +1321,7 @@ var SystemExportConf = define[EmptyRequest, SystemExportConfData]("exportConf",var SystemExportLog = define[EmptyRequest, SystemZipData]("exportLog", "/api/system/exportLog", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")var SystemExportTLSCABundle = define[EmptyRequest, SystemPathData]("exportTLSCABundle", "/api/system/exportTLSCABundle", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")var SystemExportTLSCACert = define[EmptyRequest, SystemPathData]("exportTLSCACert", "/api/system/exportTLSCACert", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")-var SystemGetChangelog = define[SystemChangelogRequest, SystemChangelogData]("getChangelog", "/api/system/getChangelog", AuthenticatedAccess, LegacyOptionalBody, ResponseOptions{}, "POST")+var SystemGetChangelog = define[SystemChangelogRequest, SystemChangelogData]("getChangelog", "/api/system/getChangelog", AuthenticatedAccess, LegacyOptionalBody, ResponseOptions{Setting: SettingWrite{Namespace: "system", Mode: SettingSilent}}, "POST")var SystemGetConf = define[EmptyRequest, SystemConfData]("getConf", "/api/system/getConf", AuthenticatedAccess, NoBody, ResponseOptions{}, "POST")var SystemGetCustomFonts = define[EmptyRequest, []*SystemCustomFont]("getCustomFonts", "/api/system/getCustomFonts", AuthenticatedAccess, NoBody, ResponseOptions{}, "POST")var SystemGetEmojiConf = define[EmptyRequest, []*SystemEmojiGroup]("getEmojiConf", "/api/system/getEmojiConf", AuthenticatedAccess, NoBody, ResponseOptions{}, "POST")@@ -1328,7 +1330,7 @@ var SystemGetSysFonts = define[EmptyRequest, []*SystemFont]("getSysFonts", "/apivar SystemGetWorkspaces = define[EmptyRequest, []*SystemWorkspace]("getWorkspaces", "/api/system/getWorkspaces", AuthenticatedAccess, NoBody, ResponseOptions{}, "POST")// SystemImportConf 导入前按启动和设置接口的相同规则规范化编辑器、导出、文档树、搜索和闪卡偏好,并同步保存。-var SystemImportConf = define[SystemImportConfRequest, Null]("importConf", "/api/system/importConf", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{}, "POST")+var SystemImportConf = define[SystemImportConfRequest, Null]("importConf", "/api/system/importConf", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{Setting: SettingWrite{Namespace: "*"}}, "POST")var SystemImportCustomFont = define[SystemImportFileRequest, *SystemCustomFont]("importCustomFont", "/api/system/importCustomFont", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{AdditionalCodes: []int{400, 413}}, "POST")var SystemImportTLSCABundle = define[SystemImportFileRequest, SystemMessageData]("importTLSCABundle", "/api/system/importTLSCABundle", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{}, "POST")var SystemLoginAuth = define[SystemLoginAuthRequest, Null]("loginAuth", "/api/system/loginAuth", PublicAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")@@ -1340,14 +1342,14 @@ var SystemOIDCValidateStart = define[SystemOIDCRequest, SystemOIDCStartData]("oivar SystemOIDCValidateActivate = define[SystemOIDCPollRequest, SystemOIDCActivateData]("oidcValidateActivate", "/api/system/oidc/validateActivate", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{}, "POST")var SystemOIDCValidateCancel = define[SystemOIDCPollRequest, Null]("oidcValidateCancel", "/api/system/oidc/validateCancel", AuthenticatedAccess|AdminAccess, StructJSONBody, ResponseOptions{}, "POST")var SystemOIDCValidatePoll = define[SystemOIDCPollRequest, SystemOIDCValidatePollData]("oidcValidatePoll", "/api/system/oidc/validatePoll", PublicAccess, StructJSONBody, ResponseOptions{}, "POST")-var SystemRemoveCustomFont = define[SystemRemoveCustomFontRequest, SystemRemoveCustomFontData]("removeCustomFont", "/api/system/removeCustomFont", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{400, 404}}, "POST")+var SystemRemoveCustomFont = define[SystemRemoveCustomFontRequest, SystemRemoveCustomFontData]("removeCustomFont", "/api/system/removeCustomFont", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{400, 404}, Setting: SettingWrite{Namespace: "*"}}, "POST")var SystemRemoveWorkspaceDir = define[SystemPathRequest, Null]("removeWorkspaceDir", "/api/system/removeWorkspaceDir", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var SystemRemoveWorkspaceDirPhysically = define[SystemPathRequest, Null]("removeWorkspaceDirPhysically", "/api/system/removeWorkspaceDirPhysically", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SystemSetAPIToken = define[SystemAPITokenRequest, Null]("setAPIToken", "/api/system/setAPIToken", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SystemSetAccessAuthCode = define[SystemAccessAuthCodeRequest, Null]("setAccessAuthCode", "/api/system/setAccessAuthCode", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SystemSetAppearanceMode = define[SystemAppearanceModeRequest, SystemAppearanceData]("setAppearanceMode", "/api/system/setAppearanceMode", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var SystemSetOIDC = define[SystemOIDCRequest, *SystemOIDC]("setOIDC", "/api/system/setOIDC", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{}, "POST")-var SystemSetUILayout = define[SystemUILayoutRequest, Null]("setUILayout", "/api/system/setUILayout", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SystemSetAPIToken = define[SystemAPITokenRequest, Null]("setAPIToken", "/api/system/setAPIToken", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "system"}}, "POST")+var SystemSetAccessAuthCode = define[SystemAccessAuthCodeRequest, Null]("setAccessAuthCode", "/api/system/setAccessAuthCode", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "system"}}, "POST")+var SystemSetAppearanceMode = define[SystemAppearanceModeRequest, SystemAppearanceData]("setAppearanceMode", "/api/system/setAppearanceMode", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "appearance"}}, "POST")+var SystemSetOIDC = define[SystemOIDCRequest, *SystemOIDC]("setOIDC", "/api/system/setOIDC", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "system"}}, "POST")+var SystemSetUILayout = define[SystemUILayoutRequest, Null]("setUILayout", "/api/system/setUILayout", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "uiLayout", Mode: SettingSilent}}, "POST")var SystemSetWorkspaceDir = define[SystemPathRequest, Null]("setWorkspaceDir", "/api/system/setWorkspaceDir", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")// SystemAddUIProcess 从 URL 查询参数读取正整数 pid,不读取请求体;无效 pid 或注册表已满时返回空 200。diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex 16e8b70b9f..023d0fc0fd 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -34464,6 +34464,32 @@],"additionalProperties": false},+ "PatchRepoSettingInput": {+ "type": "object",+ "properties": {+ "indexRetentionDays": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ]+ },+ "retentionIndexesDaily": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "additionalProperties": false+ },"PatchSettingRequestInput": {"type": "object","properties": {@@ -34487,6 +34513,16 @@}]},+ "bazaar": {+ "anyOf": [+ {+ "$ref": "#/$defs/SettingBazaarInput"+ },+ {+ "type": "null"+ }+ ]+ },"editor": {"anyOf": [{@@ -34533,6 +34569,36 @@"$ref": "#/$defs/JSONValue"}},+ "ocr": {+ "anyOf": [+ {+ "$ref": "#/$defs/SettingOCRInput"+ },+ {+ "type": "null"+ }+ ]+ },+ "publish": {+ "anyOf": [+ {+ "$ref": "#/$defs/SettingPublishInput"+ },+ {+ "type": "null"+ }+ ]+ },+ "repo": {+ "anyOf": [+ {+ "$ref": "#/$defs/PatchRepoSettingInput"+ },+ {+ "type": "null"+ }+ ]+ },"search": {"anyOf": [{@@ -34553,6 +34619,36 @@}]},+ "snippet": {+ "anyOf": [+ {+ "$ref": "#/$defs/SettingSnptInput"+ },+ {+ "type": "null"+ }+ ]+ },+ "sync": {+ "anyOf": [+ {+ "$ref": "#/$defs/PatchSyncSettingInput"+ },+ {+ "type": "null"+ }+ ]+ },+ "system": {+ "anyOf": [+ {+ "$ref": "#/$defs/PatchSystemSettingInput"+ },+ {+ "type": "null"+ }+ ]+ },"variables": {"anyOf": [{@@ -34566,6 +34662,198 @@},"additionalProperties": false},+ "PatchSyncSettingInput": {+ "type": "object",+ "properties": {+ "assetDownloadMode": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ]+ },+ "cloudName": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "enabled": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "generateConflictDoc": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "interval": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ]+ },+ "lan": {+ "anyOf": [+ {+ "$ref": "#/$defs/SyncLANRequestInput"+ },+ {+ "type": "null"+ }+ ]+ },+ "local": {+ "anyOf": [+ {+ "$ref": "#/$defs/SyncLocalInput"+ },+ {+ "type": "null"+ }+ ]+ },+ "mode": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ]+ },+ "perception": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "s3": {+ "anyOf": [+ {+ "$ref": "#/$defs/SyncS3Input"+ },+ {+ "type": "null"+ }+ ]+ },+ "webdav": {+ "anyOf": [+ {+ "$ref": "#/$defs/SyncWebDAVInput"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "additionalProperties": false+ },+ "PatchSystemSettingInput": {+ "type": "object",+ "properties": {+ "autoLaunch2": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ]+ },+ "encryptedNotebookFollowSystemLock": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "lockScreenMode": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ]+ },+ "networkProxy": {+ "anyOf": [+ {+ "$ref": "#/$defs/NetworkProxyInput"+ },+ {+ "type": "null"+ }+ ]+ },+ "networkServe": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "networkServeTLS": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "settingsWindow": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "additionalProperties": false+ },"PerformSyncRequestInput": {"type": "object","properties": {@@ -43055,6 +43343,32 @@],"additionalProperties": false},+ "SettingBazaarInput": {+ "type": "object",+ "properties": {+ "petalDisabled": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "trust": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "additionalProperties": false+ },"SettingBodyGradient": {"type": "object","properties": {@@ -46241,6 +46555,26 @@},"additionalProperties": false},+ "SettingIssue": {+ "type": "object",+ "properties": {+ "field": {+ "type": "string"+ },+ "message": {+ "type": "string"+ },+ "severity": {+ "type": "string"+ }+ },+ "required": [+ "field",+ "message",+ "severity"+ ],+ "additionalProperties": false+ },"SettingKeymapRequestInput": {"type": "object","properties": {@@ -47038,6 +47372,28 @@],"additionalProperties": false},+ "SettingPatchData": {+ "type": "object",+ "properties": {+ "issues": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "$ref": "#/$defs/SettingIssue"+ }+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": [+ "issues"+ ],+ "additionalProperties": false+ },"SettingPetalDisabledData": {"type": "object","properties": {@@ -47376,6 +47732,42 @@],"additionalProperties": false},+ "SettingPublishInput": {+ "type": "object",+ "properties": {+ "auth": {+ "anyOf": [+ {+ "$ref": "#/$defs/SettingBasicAuthInput"+ },+ {+ "type": "null"+ }+ ]+ },+ "enable": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "port": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "additionalProperties": false+ },"SettingRerank": {"type": "object","properties": {@@ -48244,6 +48636,32 @@],"additionalProperties": false},+ "SettingSnptInput": {+ "type": "object",+ "properties": {+ "enabledCSS": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "enabledJS": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "additionalProperties": false+ },"SettingStatusBar": {"type": "object","properties": {@@ -159511,7 +159929,14 @@]},"data": {- "type": "null"+ "anyOf": [+ {+ "$ref": "#/$defs/SettingPatchData"+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -159549,6 +159974,16 @@},{"type": "null"+ },+ {+ "anyOf": [+ {+ "$ref": "#/$defs/SettingPatchData"+ },+ {+ "type": "null"+ }+ ]}]},diff --git a/kernel/apicontract/setting_patch.go b/kernel/apicontract/setting_patch.goindex 23385ca2b0..232d2ff4f8 100644--- a/kernel/apicontract/setting_patch.go+++ b/kernel/apicontract/setting_patch.go@@ -4,8 +4,22 @@ import ("encoding/json""errors""io"+ "reflect"+ "strings")+// SettingIssue 指出配置字段的诊断,error 阻断提交,warning 表示已采用兼容默认值。+type SettingIssue struct {+ Field string `json:"field"`+ Severity string `json:"severity"`+ Message string `json:"message"`+}++// SettingPatchData 仅在存在诊断时返回;无诊断的成功响应继续使用 data: null。+type SettingPatchData struct {+ Issues []SettingIssue `json:"issues"`+}+// PatchSettingRequest 每次仅更新一个配置域。对象递归合并,数组和 null 整体替换,省略字段保留当前值。// 旧设置接口的整份配置提交和默认值语义不变;失败不发出配置变更通知。type PatchSettingRequest struct {@@ -19,6 +33,13 @@ type PatchSettingRequest struct {Secrets *SettingSecrets `json:"secrets" api:"optional"`Variables *SettingVariables `json:"variables" api:"optional"`Keymap map[string]JSONValue `json:"keymap" api:"optional"`+ System *PatchSystemSetting `json:"system" api:"optional"`+ Sync *PatchSyncSetting `json:"sync" api:"optional"`+ Repo *PatchRepoSetting `json:"repo" api:"optional"`+ OCR *SettingOCR `json:"ocr" api:"optional"`+ Bazaar *SettingBazaar `json:"bazaar" api:"optional"`+ Publish *SettingPublish `json:"publish" api:"optional"`+ Snippet *SettingSnpt `json:"snippet" api:"optional"`namespace stringpatch json.RawMessage}@@ -45,7 +66,7 @@ func init() {}for namespace, patch := range fields {switch namespace {- case "editor", "export", "fileTree", "search", "appearance", "flashcard", "ai", "secrets", "variables", "keymap":+ case "editor", "export", "fileTree", "search", "appearance", "flashcard", "ai", "secrets", "variables", "keymap", "system", "sync", "repo", "ocr", "bazaar", "publish", "snippet":default:return r, errors.New("unsupported settings namespace")}@@ -56,8 +77,60 @@ func init() {if len(object) == 0 {return r, errors.New("settings patch must be a nonempty object")}+ var restricted any+ switch namespace {+ case "system":+ restricted = PatchSystemSetting{}+ case "sync":+ restricted = PatchSyncSetting{}+ case "repo":+ restricted = PatchRepoSetting{}+ }+ if restricted != nil {+ allowed := map[string]bool{}+ typ := reflect.TypeOf(restricted)+ for i := 0; i < typ.NumField(); i++ {+ allowed[strings.Split(typ.Field(i).Tag.Get("json"), ",")[0]] = true+ }+ for field := range object {+ if !allowed[field] {+ return r, errors.New("unsupported settings field: " + namespace + "." + field)+ }+ }+ }r.namespace, r.patch = namespace, patch}return}}++// PatchSystemSetting 仅允许写用户偏好,宿主信息、访问凭据和全局更新通道保留专用接口。+type PatchSystemSetting struct {+ AutoLaunch2 *int `json:"autoLaunch2" api:"optional"`+ LockScreenMode *int `json:"lockScreenMode" api:"optional"`+ NetworkServe *bool `json:"networkServe" api:"optional"`+ NetworkServeTLS *bool `json:"networkServeTLS" api:"optional"`+ NetworkProxy *NetworkProxy `json:"networkProxy" api:"optional"`+ SettingsWindow *bool `json:"settingsWindow" api:"optional"`+ EncryptedNotebookFollowSystemLock *bool `json:"encryptedNotebookFollowSystemLock" api:"optional"`+}++// PatchSyncSetting 不切换提供商,来源切换仍需 setSyncProvider 的完整资源检查。+type PatchSyncSetting struct {+ Enabled *bool `json:"enabled" api:"optional"`+ Interval *int `json:"interval" api:"optional"`+ Mode *int `json:"mode" api:"optional"`+ Perception *bool `json:"perception" api:"optional"`+ GenerateConflictDoc *bool `json:"generateConflictDoc" api:"optional"`+ AssetDownloadMode *int `json:"assetDownloadMode" api:"optional"`+ CloudName *string `json:"cloudName" api:"optional"`+ S3 *SyncS3 `json:"s3" api:"optional"`+ WebDAV *SyncWebDAV `json:"webdav" api:"optional"`+ Local *SyncLocal `json:"local" api:"optional"`+ LAN *SyncLANRequest `json:"lan" api:"optional"`+}++type PatchRepoSetting struct {+ IndexRetentionDays *int `json:"indexRetentionDays" api:"optional"`+ RetentionIndexesDaily *int `json:"retentionIndexesDaily" api:"optional"`+}diff --git a/kernel/apicontract/setting_write.go b/kernel/apicontract/setting_write.gonew file mode 100644index 0000000000..8dfffd485e--- /dev/null+++ b/kernel/apicontract/setting_write.go@@ -0,0 +1,24 @@+package apicontract++// SettingWriteMode 决定写配置端点的串行化与通知方式。+type SettingWriteMode int++const (+ // SettingNotify 在配置互斥锁内执行处理器,成功后向全部主界面广播 settingChanged 和命名空间。+ SettingNotify SettingWriteMode = iota+ // SettingSilent 仅在配置互斥锁内执行,用于独立存储的布局、本地偏好和启动外观选择。+ // conf.json 的普通配置段使用 SettingNotify,由提交漏斗发布变更。+ SettingSilent+ // SettingSelfManaged 由处理器自行加锁和广播:命名空间取决于请求内容,或加锁前需要等待外部条件。+ SettingSelfManaged+)++// SettingWrite 声明端点写入的配置命名空间。零值表示端点不写入应用配置。+// 写入 conf.json、本地偏好或启动外观等配置文件的端点必须声明,契约测试按路径约定和处理器内容检查遗漏。+type SettingWrite struct {+ Namespace string // 变更通知中的配置命名空间,"*" 表示可能涉及多个配置段+ Mode SettingWriteMode+}++// Declared 报告端点是否声明了配置写入。+func (setting SettingWrite) Declared() bool { return setting.Namespace != "" }diff --git a/kernel/av/av.go b/kernel/av/av.goindex 17651f0396..e9e7f60134 100644--- a/kernel/av/av.go+++ b/kernel/av/av.go@@ -1058,7 +1058,7 @@ func saveAttributeView(av *AttributeView, original []byte) (err error) {var data []byterestoreRenderedContents := av.suspendRenderedContents()restoreResolvedColors := av.suspendResolvedColors()- if util.UseSingleLineSave {+ if util.UseSingleLineSave.Load() {data, err = gulu.JSON.MarshalJSON(av)} else {data, err = gulu.JSON.MarshalIndentJSON(av, "", "\t")@@ -1142,7 +1142,7 @@ func saveAttributeView(av *AttributeView, original []byte) (err error) {}if util.ExceedLargeFileWarningSize(len(data)) {- msg := fmt.Sprintf(util.Langs[util.Lang][268], av.Name+" "+filepath.Base(avJSONPath), util.LargeFileWarningSize)+ msg := fmt.Sprintf(util.Langs[util.Lang][268], av.Name+" "+filepath.Base(avJSONPath), util.LargeFileWarningSize.Load())util.PushErrMsg(msg, 7000)}returndiff --git a/kernel/av/filter.go b/kernel/av/filter.goindex 4dcc22cbe4..7ff7bb6fae 100644--- a/kernel/av/filter.go+++ b/kernel/av/filter.go@@ -1367,7 +1367,7 @@ func filterTextContent(operator FilterOperator, valueContent, otherValueContentif "" == strings.TrimSpace(otherValueContent) {return true}- if util.SearchCaseSensitive {+ if util.SearchCaseSensitive.Load() {return valueContent == otherValueContent}return strings.EqualFold(valueContent, otherValueContent)@@ -1375,7 +1375,7 @@ func filterTextContent(operator FilterOperator, valueContent, otherValueContentif "" == strings.TrimSpace(otherValueContent) {return true}- if util.SearchCaseSensitive {+ if util.SearchCaseSensitive.Load() {return valueContent != otherValueContent}return !strings.EqualFold(valueContent, otherValueContent)@@ -1383,7 +1383,7 @@ func filterTextContent(operator FilterOperator, valueContent, otherValueContentif "" == strings.TrimSpace(otherValueContent) {return true}- if util.SearchCaseSensitive {+ if util.SearchCaseSensitive.Load() {return strings.Contains(valueContent, otherValueContent)}return strings.Contains(strings.ToLower(valueContent), strings.ToLower(otherValueContent))@@ -1391,7 +1391,7 @@ func filterTextContent(operator FilterOperator, valueContent, otherValueContentif "" == strings.TrimSpace(otherValueContent) {return true}- if util.SearchCaseSensitive {+ if util.SearchCaseSensitive.Load() {return !strings.Contains(valueContent, otherValueContent)}return !strings.Contains(strings.ToLower(valueContent), strings.ToLower(otherValueContent))@@ -1399,7 +1399,7 @@ func filterTextContent(operator FilterOperator, valueContent, otherValueContentif "" == strings.TrimSpace(otherValueContent) {return true}- if util.SearchCaseSensitive {+ if util.SearchCaseSensitive.Load() {return strings.HasPrefix(valueContent, otherValueContent)}return strings.HasPrefix(strings.ToLower(valueContent), strings.ToLower(otherValueContent))@@ -1407,7 +1407,7 @@ func filterTextContent(operator FilterOperator, valueContent, otherValueContentif "" == strings.TrimSpace(otherValueContent) {return true}- if util.SearchCaseSensitive {+ if util.SearchCaseSensitive.Load() {return strings.HasSuffix(valueContent, otherValueContent)}return strings.HasSuffix(strings.ToLower(valueContent), strings.ToLower(otherValueContent))diff --git a/kernel/av/value_text_test.go b/kernel/av/value_text_test.goindex 553d814808..70c6e5561f 100644--- a/kernel/av/value_text_test.go+++ b/kernel/av/value_text_test.go@@ -851,9 +851,9 @@ func TestValueTextRichInlineRoundTrip(t *testing.T) {}func TestValueTextRichParserIgnoresEditorMarkdownSettings(t *testing.T) {- original := *util.MarkdownSettings+ original := *util.MarkdownSettings.Load()defer func() {- *util.MarkdownSettings = original+ *util.MarkdownSettings.Load() = original}()rich := &ValueTextRich{@@ -865,18 +865,18 @@ func TestValueTextRichParserIgnoresEditorMarkdownSettings(t *testing.T) {t.Fatal(err)}- util.MarkdownSettings.InlineAsterisk = false- util.MarkdownSettings.InlineUnderscore = false- util.MarkdownSettings.InlineSup = false- util.MarkdownSettings.InlineSub = false- util.MarkdownSettings.InlineTag = false- util.MarkdownSettings.InlineMath = false- util.MarkdownSettings.InlineStrikethrough = false- util.MarkdownSettings.InlineFullWidthStrikethrough = false- util.MarkdownSettings.InlineMark = false+ util.MarkdownSettings.Load().InlineAsterisk = false+ util.MarkdownSettings.Load().InlineUnderscore = false+ util.MarkdownSettings.Load().InlineSup = false+ util.MarkdownSettings.Load().InlineSub = false+ util.MarkdownSettings.Load().InlineTag = false+ util.MarkdownSettings.Load().InlineMath = false+ util.MarkdownSettings.Load().InlineStrikethrough = false+ util.MarkdownSettings.Load().InlineFullWidthStrikethrough = false+ util.MarkdownSettings.Load().InlineMark = falsedisabled := false- util.MarkdownSettings.BlockFullWidthTaskList = &disabled- util.MarkdownSettings.CodeBlockMiddleDot = &disabled+ util.MarkdownSettings.Load().BlockFullWidthTaskList = &disabled+ util.MarkdownSettings.Load().CodeBlockMiddleDot = &disableddisabledSettingsRich := &ValueTextRich{Spec: ValueTextRichSpec,diff --git a/kernel/cli/cmd/database_unused_test.go b/kernel/cli/cmd/database_unused_test.goindex 3d681c8f15..db95a01d84 100644--- a/kernel/cli/cmd/database_unused_test.go+++ b/kernel/cli/cmd/database_unused_test.go@@ -15,7 +15,7 @@ import (func TestDatabaseCommandsRejectIncompleteUnusedScan(t *testing.T) {previousConf, previousData, previousWorkspace, previousDryRun := model.Conf, util.DataDir, util.WorkspaceDir, dryRunmodel.Conf = model.NewAppConf()- model.Conf.FileTree = conf.NewFileTree()+ model.Conf.FileTree.Store(conf.NewFileTree())util.WorkspaceDir = t.TempDir()util.DataDir = filepath.Join(util.WorkspaceDir, "data")t.Cleanup(func() {diff --git a/kernel/cli/cmd/ref.go b/kernel/cli/cmd/ref.goindex 39657626f5..64c53c930b 100644--- a/kernel/cli/cmd/ref.go+++ b/kernel/cli/cmd/ref.go@@ -44,7 +44,7 @@ var refBacklinksCmd = &cobra.Command{keyword, _ := cmd.Flags().GetString("keyword")sortMode, _ := cmd.Flags().GetInt("sort")- _, backlinks, _, count, _ := model.GetBacklink2(id, keyword, "", sortMode, 0, model.Conf.Editor.BacklinkContainChildren)+ _, backlinks, _, count, _ := model.GetBacklink2(id, keyword, "", sortMode, 0, model.Conf.Editor.Load().BacklinkContainChildren)switch outputFormat {case "json":@@ -71,7 +71,7 @@ var refMentionsCmd = &cobra.Command{keyword, _ := cmd.Flags().GetString("keyword")sortMode, _ := cmd.Flags().GetInt("sort")- _, _, backmentions, _, count := model.GetBacklink2(id, "", keyword, 0, sortMode, model.Conf.Editor.BacklinkContainChildren)+ _, _, backmentions, _, count := model.GetBacklink2(id, "", keyword, 0, sortMode, model.Conf.Editor.Load().BacklinkContainChildren)switch outputFormat {case "json":diff --git a/kernel/cli/cmd/repo_failure_test.go b/kernel/cli/cmd/repo_failure_test.goindex e9020f3cb4..f29f4d39b0 100644--- a/kernel/cli/cmd/repo_failure_test.go+++ b/kernel/cli/cmd/repo_failure_test.go@@ -10,8 +10,8 @@ import (func TestRepoAndSyncCommandsReportUnavailableOperations(t *testing.T) {previousConf, previousDryRun := model.Conf, dryRun- model.Conf = &model.AppConf{Lang: "en", Repo: conf.NewRepo(), Sync: conf.NewSync()}- model.Conf.Sync.Enabled = false+ model.Conf = &model.AppConf{Lang: "en", Repo: model.NewConfSection(conf.NewRepo()), Sync: model.NewConfSection(conf.NewSync())}+ model.Conf.Sync.Load().Enabled = falsedryRun = falset.Cleanup(func() { model.Conf, dryRun = previousConf, previousDryRun })for _, command := range []*cobra.Command{repoCheckoutCmd, syncPushCmd, syncPullCmd} {diff --git a/kernel/cli/cmd/root.go b/kernel/cli/cmd/root.goindex a4a1cc14e8..f87ddff98c 100644--- a/kernel/cli/cmd/root.go+++ b/kernel/cli/cmd/root.go@@ -114,8 +114,8 @@ var rootCmd = &cobra.Command{sql.InitDatabase(false)sql.InitHistoryDatabase(false)sql.InitAssetContentDatabase(false)- sql.SetCaseSensitive(model.Conf.Search.CaseSensitive)- sql.SetIndexAssetPath(model.Conf.Search.IndexAssetPath)+ // 数据库打开后重新应用搜索配置,使 PRAGMA case_sensitive_like 对新连接生效+ model.ApplySearchRuntime()// 让 CLI 一次性命令(如 search -m 4)也能命中语义搜索:StartEmbeddingIndexer 是死循环不能用于会立即退出的进程,这里只把开关置真model.PrepareEmbeddingSearch()if err := rejectEncryptedNotebookCLI(cmd, args); err != nil {diff --git a/kernel/cli/cmd/serve.go b/kernel/cli/cmd/serve.goindex 02b4c7df04..1e2f67b8b8 100644--- a/kernel/cli/cmd/serve.go+++ b/kernel/cli/cmd/serve.go@@ -73,8 +73,8 @@ var serveCmd = &cobra.Command{sql.InitDatabase(false)sql.InitHistoryDatabase(false)sql.InitAssetContentDatabase(false)- sql.SetCaseSensitive(model.Conf.Search.CaseSensitive)- sql.SetIndexAssetPath(model.Conf.Search.IndexAssetPath)+ // 数据库打开后重新应用搜索配置,使 PRAGMA case_sensitive_like 对新连接生效+ model.ApplySearchRuntime()model.BootSyncData()model.CleanupEmptyPluginStorageDirs()diff --git a/kernel/cli/cmd/sync.go b/kernel/cli/cmd/sync.goindex fecb91424f..552239c295 100644--- a/kernel/cli/cmd/sync.go+++ b/kernel/cli/cmd/sync.go@@ -31,7 +31,7 @@ var syncCmd = &cobra.Command{Use: "sync",Short: "Sync data with cloud",RunE: func(cmd *cobra.Command, args []string) error {- if model.Conf.Sync.Mode == 3 {+ if model.Conf.Sync.Load().Mode == 3 {return fmt.Errorf("full-manual mode requires 'push' or 'pull' subcommand")}@@ -84,7 +84,7 @@ var syncStatusCmd = &cobra.Command{Use: "status",Short: "Show sync status",RunE: func(cmd *cobra.Command, args []string) error {- s := model.Conf.Sync+ s := model.Conf.Sync.Load()switch outputFormat {case "json":data, _ := json.MarshalIndent(map[string]any{diff --git a/kernel/conf/ai.go b/kernel/conf/ai.goindex 88dbe521a4..a1adb536ef 100644--- a/kernel/conf/ai.go+++ b/kernel/conf/ai.go@@ -422,6 +422,11 @@ func NewAI() *AI {ImageGeneration: defaultImageGeneration(),}+ return ai+}++// ApplyAIEnvironment 仅由启动适配器调用,环境变量不参与默认值或日常规范化。+func ApplyAIEnvironment(ai *AI) {apiKey := os.Getenv("SIYUAN_OPENAI_API_KEY")apiModel := os.Getenv("SIYUAN_OPENAI_API_MODEL")apiBaseURL := os.Getenv("SIYUAN_OPENAI_API_BASE_URL")@@ -511,7 +516,6 @@ func NewAI() *AI {}}- return ai}func (ai *AI) HasAnyProvider() bool {@@ -652,7 +656,8 @@ func (ai *AI) Normalize() {serverIDs := map[string]bool{}for i := range ai.MCP.Servers {if ai.MCP.Servers[i].ID == "" || serverIDs[ai.MCP.Servers[i].ID] {- ai.MCP.Servers[i].ID = uuid.New().String()+ data := []byte(fmt.Sprintf("mcp:%d:%s:%s", i, ai.MCP.Servers[i].Name, ai.MCP.Servers[i].Type))+ ai.MCP.Servers[i].ID = uuid.NewSHA1(uuid.NameSpaceOID, data).String()}serverIDs[ai.MCP.Servers[i].ID] = true}@@ -754,7 +759,7 @@ func (ai *AI) Normalize() {ai.ImageGeneration.OutputFormat = "png"}providers := make([]*Provider, 0, len(ai.Providers))- for _, p := range ai.Providers {+ for providerIndex, p := range ai.Providers {if p == nil {continue}@@ -783,10 +788,10 @@ func (ai *AI) Normalize() {p.RequestTimeout = 600}if !ast.IsNodeIDPattern(p.ID) {- p.ID = ast.NewNodeID()+ p.ID = normalizedAIID(fmt.Sprintf("provider:%d:%s", providerIndex, p.DisplayName))}models := make([]*Model, 0, len(p.Models))- for _, m := range p.Models {+ for modelIndex, m := range p.Models {if m == nil {continue}@@ -799,7 +804,7 @@ func (ai *AI) Normalize() {m.ContextLength = 0}if !ast.IsNodeIDPattern(m.ID) {- m.ID = ast.NewNodeID()+ m.ID = normalizedAIID(fmt.Sprintf("model:%s:%d:%s", p.ID, modelIndex, m.Name))}models = append(models, m)}@@ -817,7 +822,7 @@ func (ai *AI) Normalize() {ai.Embedding.Dimensions = 0 // 负值非法,归零表示用模型默认维度}if !ast.IsNodeIDPattern(ai.Embedding.ID) {- ai.Embedding.ID = ast.NewNodeID()+ ai.Embedding.ID = normalizedAIID("embedding")}if ai.Rerank == nil {ai.Rerank = defaultRerank()@@ -839,10 +844,16 @@ func (ai *AI) Normalize() {ai.Rerank.CandidateCount = 100}if !ast.IsNodeIDPattern(ai.Rerank.ID) {- ai.Rerank.ID = ast.NewNodeID()+ ai.Rerank.ID = normalizedAIID("rerank")}}+// normalizedAIID 补全缺失标识时仅依赖公开配置位置,保持区块 ID 形态且不包含凭据。+func normalizedAIID(seed string) string {+ id := uuid.NewSHA1(uuid.NameSpaceOID, []byte(seed))+ return "20000101000000-" + hex.EncodeToString(id[:])[:7]+}+func (ai *AI) pruneOrphanedMCPCapabilityPolicies() {configuredServerIDs := make(map[string]bool, len(ai.MCP.Servers))for _, server := range ai.MCP.Servers {diff --git a/kernel/conf/ai_provider_test.go b/kernel/conf/ai_provider_test.goindex 525eed4c20..3851e82163 100644--- a/kernel/conf/ai_provider_test.go+++ b/kernel/conf/ai_provider_test.go@@ -16,6 +16,7 @@ func TestNewAIAddsKeylessProviderFromEnvironment(t *testing.T) {t.Setenv("SIYUAN_OPENAI_API_BASE_URL", "http://127.0.0.1:8080/v1")ai := NewAI()+ ApplyAIEnvironment(ai)if len(ai.Providers) != 1 {t.Fatalf("provider count = %d, want 1", len(ai.Providers))}diff --git a/kernel/conf/ai_timeout_test.go b/kernel/conf/ai_timeout_test.goindex e43afc16f9..30605cc132 100644--- a/kernel/conf/ai_timeout_test.go+++ b/kernel/conf/ai_timeout_test.go@@ -58,7 +58,9 @@ func TestAINormalizeAgentTimeoutsAndRetries(t *testing.T) {func TestNewAIReadsAgentStreamIdleTimeoutFromEnvironment(t *testing.T) {t.Setenv("SIYUAN_OPENAI_AGENT_STREAM_IDLE_TIMEOUT", "240")- if got := NewAI().Agent.StreamIdleTimeout; got != 240 {+ ai := NewAI()+ ApplyAIEnvironment(ai)+ if got := ai.Agent.StreamIdleTimeout; got != 240 {t.Fatalf("stream idle timeout = %d, want 240", got)}}@@ -79,6 +81,7 @@ func TestNewAIDefaultProviderRequestTimeout(t *testing.T) {t.Setenv("SIYUAN_OPENAI_API_MODEL", "test-model")t.Setenv("SIYUAN_OPENAI_API_BASE_URL", "https://example.com/v1")ai := NewAI()+ ApplyAIEnvironment(ai)if len(ai.Providers) != 1 || ai.Providers[0].RequestTimeout != 120 {t.Fatalf("unexpected default provider request timeout: %#v", ai.Providers)}diff --git a/kernel/conf/api.go b/kernel/conf/api.goindex 6b334498aa..cb748559e7 100644--- a/kernel/conf/api.go+++ b/kernel/conf/api.go@@ -16,14 +16,10 @@package conf-import "github.com/88250/gulu"-type API struct {Token string `json:"token"`}func NewAPI() *API {- return &API{- Token: gulu.Rand.String(16),- }+ return &API{}}diff --git a/kernel/conf/appearance.go b/kernel/conf/appearance.goindex ab4bb88487..a941a562cd 100644--- a/kernel/conf/appearance.go+++ b/kernel/conf/appearance.go@@ -55,6 +55,11 @@ type BodyGradientColor struct {}func NewAppearance() *Appearance {+ return NewAppearanceForContainer(false)+}++// NewAppearanceForContainer 使用显式容器参数选择状态栏默认项。+func NewAppearanceForContainer(mobile bool) *Appearance {return &Appearance{GlobalFontFamilies: []*EditorFont{},Mode: 0,@@ -68,7 +73,7 @@ func NewAppearance() *Appearance {CloseButtonBehavior: 0,HideToolbar: true,HideStatusBar: false,- StatusBar: util.NewStatusBar(util.IsMobileContainer()),+ StatusBar: util.NewStatusBar(mobile),Notifications: util.NewNotifications(),EntryVisibility: NewEntryVisibility(EntryVisibilityProfileSimple),}diff --git a/kernel/conf/defaults_purity_test.go b/kernel/conf/defaults_purity_test.gonew file mode 100644index 0000000000..1dd4b199ed--- /dev/null+++ b/kernel/conf/defaults_purity_test.go@@ -0,0 +1,58 @@+package conf++import (+ "encoding/json"+ "reflect"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestConfigurationDefaultsAndNormalizationArePure(t *testing.T) {+ previous := util.MarkdownSettings.Load()+ previousSingle, previousLarge := util.UseSingleLineSave.Load(), util.LargeFileWarningSize.Load()+ t.Cleanup(func() {+ util.MarkdownSettings.Store(previous)+ util.UseSingleLineSave.Store(previousSingle)+ util.LargeFileWarningSize.Store(previousLarge)+ })+ construct := func() []any {+ return []any{NewEditor(), NewFileTree(), NewAPI(), NewAI(), NewSystem(), NewAppearance(), NewSync(),+ NewExport(), NewSearch(), NewFlashcard(), NewRepo(), NewOCR(), NewPublish(), NewBazaar(), NewSnpt(),+ NewSecrets(), NewVariables(), NewOIDC(), NewGraph(), NewStat(), NewTag(), NewNotebookCrypto()}+ }+ before, err := json.Marshal(construct())+ if err != nil {+ t.Fatal(err)+ }+ t.Setenv("SIYUAN_OPENAI_API_KEY", "environment-key")+ t.Setenv("SIYUAN_OPENAI_API_MODEL", "environment-model")+ t.Setenv("SIYUAN_OPENAI_AGENT_TIMEOUT", "150")+ markdown := util.NewMarkdown()+ markdown.InlineMath = false+ util.MarkdownSettings.Store(markdown)+ util.UseSingleLineSave.Store(!util.DefaultUseSingleLineSave)+ util.LargeFileWarningSize.Store(999)+ after, err := json.Marshal(construct())+ if err != nil || string(before) != string(after) {+ t.Fatal("defaults depend on mutable globals, environment or randomness")+ }+ first := &AI{MCP: &MCP{Servers: []MCPServer{{Name: "fixture", Type: "stdio", Command: "fixture"}}}}+ second := &AI{MCP: &MCP{Servers: []MCPServer{{Name: "fixture", Type: "stdio", Command: "fixture"}}}}+ if !reflect.DeepEqual(NormalizeAI(first), NormalizeAI(second)) {+ t.Fatal("normalization depends on randomness")+ }+}++func TestExportModeMigrationIsSeparateFromNormalization(t *testing.T) {+ for _, mode := range []int{0, 1, 5} {+ export := NewExport()+ export.BlockRefMode = mode+ if NormalizeExport(export).BlockRefMode != mode {+ t.Fatal("daily normalization ran a version migration")+ }+ if !MigrateExportBlockRefMode(export) || export.BlockRefMode != 4 || MigrateExportBlockRefMode(export) {+ t.Fatal("mode migration is not idempotent")+ }+ }+}diff --git a/kernel/conf/editor.go b/kernel/conf/editor.goindex bdd9568e8d..282b8886e6 100644--- a/kernel/conf/editor.go+++ b/kernel/conf/editor.go@@ -247,6 +247,6 @@ func NewEditor() *Editor {HeadingEmbedMode: 0,PasteURLAutoConvert: false,DragHTMLFileToIframe: false,- Markdown: util.MarkdownSettings,+ Markdown: util.NewMarkdown(),}}diff --git a/kernel/conf/filetree.go b/kernel/conf/filetree.goindex d3db8b77ee..3560dfdb91 100644--- a/kernel/conf/filetree.go+++ b/kernel/conf/filetree.go@@ -64,8 +64,8 @@ func NewFileTree() *FileTree {AllowCreateDeeper: false,CloseTabsOnStart: false,TabStartupMode: new(int),- UseSingleLineSave: util.UseSingleLineSave,- LargeFileWarningSize: util.LargeFileWarningSize,+ UseSingleLineSave: util.DefaultUseSingleLineSave,+ LargeFileWarningSize: util.DefaultLargeFileWarningSize,CreateDocAtTop: new(bool),NoSplitScreenWhenOpenTab: false,}diff --git a/kernel/conf/settings_normalize.go b/kernel/conf/settings_normalize.goindex 2bfb5b5ddd..4552a71c5c 100644--- a/kernel/conf/settings_normalize.go+++ b/kernel/conf/settings_normalize.go@@ -128,15 +128,21 @@ func NormalizeEditor(editor *Editor) *Editor {return editor}-// NormalizeExport 将已废弃的块引用导出模式统一转换为脚注与锚点哈希模式。+// NormalizeExport 补全缺失的导出配置,不推断配置格式版本。func NormalizeExport(export *Export) *Export {if export == nil {export = NewExport()}- if export.BlockRefMode == 0 || export.BlockRefMode == 1 || export.BlockRefMode == 5 {+ return export+}++// MigrateExportBlockRefMode 转换旧格式的块引用导出模式,保留其余模式。+func MigrateExportBlockRefMode(export *Export) bool {+ if export != nil && (export.BlockRefMode == 0 || export.BlockRefMode == 1 || export.BlockRefMode == 5) {export.BlockRefMode = 4+ return true}- return export+ return false}// NormalizeSearch 保留非空布尔指针表示的用户选择。@@ -205,3 +211,234 @@ func NormalizeFlashcard(flashcard *Flashcard) (*Flashcard, string) {}return flashcard, message}++// NormalizeAppearance 补全外观缺失字段,并将已移除的图标包和越界的状态栏配置转换为当前可用值。+// mobile 表示是否为移动端容器,决定状态栏默认项。+func NormalizeAppearance(appearance *Appearance, mobile bool) *Appearance {+ if appearance == nil {+ appearance = NewAppearanceForContainer(mobile)+ }+ if "ant" == appearance.Icon || "material" == appearance.Icon {+ // v3.7.0 移除了 ant/material 图标包 https://github.com/siyuan-note/siyuan/issues/7976+ appearance.Icon = "litheness"+ }+ if "" == appearance.CodeBlockThemeDark {+ appearance.CodeBlockThemeDark = "dracula"+ }+ if "" == appearance.CodeBlockThemeLight {+ appearance.CodeBlockThemeLight = "github"+ }+ appearance.StatusBar = util.NormalizeStatusBar(appearance.StatusBar, mobile)+ if nil == appearance.Notifications {+ appearance.Notifications = util.NewNotifications()+ }+ appearance.EntryVisibility = NormalizeEntryVisibility(appearance.EntryVisibility, EntryVisibilityProfileFull)+ appearance.NormalizeGlobalFontFamilies()+ return appearance+}++// NormalizeSync 限定同步间隔和并发数范围,并补全各存储服务的连接参数。+func NormalizeSync(sync *Sync) *Sync {+ if sync == nil {+ sync = NewSync()+ }+ if 0 == sync.Mode {+ sync.Mode = 1+ }+ sync.Interval = max(30, min(60*60*12, sync.Interval))+ if nil == sync.S3 {+ sync.S3 = &S3{PathStyle: true, SkipTlsVerify: true}+ }+ sync.S3.Endpoint = util.NormalizeEndpoint(sync.S3.Endpoint)+ sync.S3.Timeout = util.NormalizeTimeout(sync.S3.Timeout)+ sync.S3.ConcurrentReqs = util.NormalizeConcurrentReqs(sync.S3.ConcurrentReqs, ProviderS3)+ if nil == sync.WebDAV {+ sync.WebDAV = &WebDAV{SkipTlsVerify: true}+ }+ sync.WebDAV.Endpoint = util.NormalizeEndpoint(sync.WebDAV.Endpoint)+ sync.WebDAV.Timeout = util.NormalizeTimeout(sync.WebDAV.Timeout)+ sync.WebDAV.ConcurrentReqs = util.NormalizeConcurrentReqs(sync.WebDAV.ConcurrentReqs, ProviderWebDAV)+ if nil == sync.Local {+ sync.Local = &Local{}+ }+ sync.Local.Endpoint = util.NormalizeLocalPath(sync.Local.Endpoint)+ sync.Local.Timeout = util.NormalizeTimeout(sync.Local.Timeout)+ sync.Local.ConcurrentReqs = util.NormalizeConcurrentReqs(sync.Local.ConcurrentReqs, ProviderLocal)+ if nil == sync.LAN {+ sync.LAN = &LANSync{MaxConcurrentReqs: 16}+ }+ if 1 > sync.LAN.MaxConcurrentReqs {+ sync.LAN.MaxConcurrentReqs = 16+ }+ sync.LAN.MaxConcurrentReqs = min(128, sync.LAN.MaxConcurrentReqs)+ return sync+}++// NormalizeSystem 补全系统配置的设备标识和网络代理;运行环境信息由加载入口按当前进程投影。+func NormalizeSystem(system *System) *System {+ if system == nil {+ system = NewSystem()+ }+ if nil == system.NetworkProxy {+ system.NetworkProxy = &NetworkProxy{}+ }+ if nil == system.DisabledFeatures {+ system.DisabledFeatures = []string{}+ }+ return system+}++// NormalizeRepo 限定数据仓库索引提示阈值和自动清理保留策略的下限。+func NormalizeRepo(repo *Repo) *Repo {+ defaults := NewRepo()+ if repo == nil {+ repo = defaults+ }+ repo.SyncIndexTiming = max(defaults.SyncIndexTiming, repo.SyncIndexTiming)+ if 1 > repo.IndexRetentionDays {+ repo.IndexRetentionDays = defaults.IndexRetentionDays+ }+ if 1 > repo.RetentionIndexesDaily {+ repo.RetentionIndexesDaily = defaults.RetentionIndexesDaily+ }+ return repo+}++// NormalizeGraph 在全局或局部关系图配置缺失时整体恢复默认值,否则仅限定最大块数。+func NormalizeGraph(graph *Graph) *Graph {+ if graph == nil || graph.Local == nil || graph.Global == nil {+ return NewGraph()+ }+ graph.NormalizeMaxBlocks()+ return graph+}++// NormalizeOCR 将已合并的内置模型名称转换为当前名称;缺失配置的默认来源由加载入口决定。+func NormalizeOCR(ocr *OCR) *OCR {+ if ocr == nil {+ ocr = NewOCR()+ }+ if "small" == ocr.Model {+ // 内置模型统一为 Tiny,自行导入的模型仍保留内容摘要标识。+ ocr.Model = "tiny"+ }+ return ocr+}++// NormalizeAI 补全人工智能配置并对齐模型标识;密钥解密由加载入口负责。+func NormalizeAI(ai *AI) *AI {+ if ai == nil {+ ai = NewAI()+ }+ ai.Normalize()+ ai.ReconcileModelIDs()+ return ai+}++// NormalizeOIDC 补全 OpenID Connect 配置;环境变量覆盖和密钥解密由加载入口负责。+func NormalizeOIDC(oidc *OIDC) *OIDC {+ if oidc == nil {+ oidc = NewOIDC()+ }+ oidc.Normalize()+ return oidc+}++// NormalizePublish 保证发布服务始终带有认证配置,避免空认证配置写入后导致启动失败。+func NormalizePublish(publish *Publish) *Publish {+ if publish == nil {+ publish = NewPublish()+ }+ if nil == publish.Auth {+ publish.Auth = NewPublish().Auth+ }+ return publish+}++// NormalizeSnippet 在代码片段配置缺失时使用默认值。+func NormalizeSnippet(snippet *Snpt) *Snpt {+ if snippet == nil {+ snippet = NewSnpt()+ }+ return snippet+}++// NormalizeTag 在标签面板配置缺失时使用默认值。+func NormalizeTag(tag *Tag) *Tag {+ if tag == nil {+ tag = NewTag()+ }+ return tag+}++// NormalizeStat 在统计配置缺失时使用默认值。+func NormalizeStat(stat *Stat) *Stat {+ if stat == nil {+ stat = NewStat()+ }+ return stat+}++// NormalizeBazaar 在集市配置缺失时使用默认值。+func NormalizeBazaar(bazaar *Bazaar) *Bazaar {+ if bazaar == nil {+ bazaar = NewBazaar()+ }+ return bazaar+}++// NormalizeAPI 在 API 配置缺失时使用默认值。+func NormalizeAPI(api *API) *API {+ if api == nil {+ api = NewAPI()+ }+ return api+}++// NormalizeNotebookCrypto 在加密笔记本密钥管理配置缺失时使用默认值,已有配置原样保留。+func NormalizeNotebookCrypto(notebookCrypto *NotebookCrypto) *NotebookCrypto {+ if notebookCrypto == nil {+ notebookCrypto = NewNotebookCrypto()+ }+ return notebookCrypto+}++// NormalizeSecrets 在密钥库缺失时使用默认值;解密由加载入口负责。+func NormalizeSecrets(secrets *Secrets) *Secrets {+ if secrets == nil {+ secrets = NewSecrets()+ }+ return secrets+}++// NormalizeVariables 在变量库缺失时使用默认值。+func NormalizeVariables(variables *Variables) *Variables {+ if variables == nil {+ variables = NewVariables()+ }+ return variables+}++// NormalizeKeymap 在快捷键配置缺失时使用空配置,内置快捷键由前端按平台补全。+func NormalizeKeymap(keymap *Keymap) *Keymap {+ if keymap == nil {+ keymap = &Keymap{}+ }+ return keymap+}++// NormalizeUILayout 在界面布局缺失时使用空布局。+func NormalizeUILayout(uiLayout *UILayout) *UILayout {+ if uiLayout == nil {+ uiLayout = &UILayout{}+ }+ return uiLayout+}++// NormalizeOnboarding 在首次使用引导状态缺失时视为已完成,避免已有工作空间重复引导。+func NormalizeOnboarding(onboarding *Onboarding) *Onboarding {+ if onboarding == nil {+ onboarding = &Onboarding{State: OnboardingCompleted}+ }+ return onboarding+}diff --git a/kernel/conf/system.go b/kernel/conf/system.goindex 0f00b4a2c7..c1f30b5438 100644--- a/kernel/conf/system.go+++ b/kernel/conf/system.go@@ -16,10 +16,6 @@package conf-import (- "github.com/siyuan-note/siyuan/kernel/util"-)-type System struct {ID string `json:"id"`Name string `json:"name"`@@ -76,9 +72,6 @@ type Onboarding struct {func NewSystem() *System {return &System{- ID: util.GetDeviceID(),- Name: util.GetDeviceName(),- KernelVersion: util.Ver,NetworkProxy: &NetworkProxy{},DownloadInstallPkg: true,UpdateChannel: UpdateChannelStable,diff --git a/kernel/filesys/tree.go b/kernel/filesys/tree.goindex c1ac53f1c1..3053896efe 100644--- a/kernel/filesys/tree.go+++ b/kernel/filesys/tree.go@@ -534,7 +534,7 @@ func WriteTree(tree *parse.Tree) (size uint64, err error) {}if util.ExceedLargeFileWarningSize(len(data)) {- msg := fmt.Sprintf(util.Langs[util.Lang][268], tree.Root.IALAttr("title")+" "+filepath.Base(filePath), util.LargeFileWarningSize)+ msg := fmt.Sprintf(util.Langs[util.Lang][268], tree.Root.IALAttr("title")+" "+filepath.Base(filePath), util.LargeFileWarningSize.Load())util.PushErrMsg(msg, 7000)}@@ -583,7 +583,7 @@ func prepareWriteTree(tree *parse.Tree) (data []byte, filePath string, err errorrenderer := render.NewJSONRenderer(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)data = renderer.Render()data, _ = removeUnescapedUnicodeNull(data)- if !util.UseSingleLineSave {+ if !util.UseSingleLineSave.Load() {buf := bytes.Buffer{}buf.Grow(1024 * 1024 * 2)if err = json.Indent(&buf, data, "", "\t"); err != nil {@@ -721,7 +721,7 @@ func fixTreeJSONData(boxID, p string, jsonData []byte, luteEngine *lute.Lute, derenderer := render.NewJSONRenderer(ret, luteEngine.RenderOptions, luteEngine.ParseOptions)data = renderer.Render()- if !util.UseSingleLineSave {+ if !util.UseSingleLineSave.Load() {buf := bytes.Buffer{}buf.Grow(1024 * 1024 * 2)if err = json.Indent(&buf, data, "", "\t"); err != nil {diff --git a/kernel/harmony/kernel.go b/kernel/harmony/kernel.goindex 3218a859c1..9de96b98f4 100644--- a/kernel/harmony/kernel.go+++ b/kernel/harmony/kernel.go@@ -141,8 +141,8 @@ func StartKernel(container, appDir, workspaceBaseDir, timezoneID, localIPs, langsql.InitDatabase(false)sql.InitHistoryDatabase(false)sql.InitAssetContentDatabase(false)- sql.SetCaseSensitive(model.Conf.Search.CaseSensitive)- sql.SetIndexAssetPath(model.Conf.Search.IndexAssetPath)+ // 数据库打开后重新应用搜索配置,使 PRAGMA case_sensitive_like 对新连接生效+ model.ApplySearchRuntime()model.BootSyncData()model.CleanupEmptyPluginStorageDirs()diff --git a/kernel/mcp/bazaar_test.go b/kernel/mcp/bazaar_test.goindex 2d732733d9..d6b8f69ea4 100644--- a/kernel/mcp/bazaar_test.go+++ b/kernel/mcp/bazaar_test.go@@ -18,7 +18,7 @@ import (func TestBazaarMCPPagination(t *testing.T) {oldConf, oldDataDir := model.Conf, util.DataDirmodel.Conf = model.NewAppConf()- model.Conf.Bazaar = &conf.Bazaar{}+ model.Conf.Bazaar.Store(&conf.Bazaar{})util.DataDir = t.TempDir()t.Cleanup(func() { model.Conf, util.DataDir = oldConf, oldDataDir })for i := 0; i < 23; i++ {diff --git a/kernel/mcp/client/mcp.go b/kernel/mcp/client/mcp.goindex 18c004df25..0bf8f4d9e1 100644--- a/kernel/mcp/client/mcp.go+++ b/kernel/mcp/client/mcp.go@@ -199,7 +199,7 @@ func (h *headerRoundTripper) RoundTrip(req *http.Request) (*http.Response, error// 对每个 header 值里的 {{secrets.NAME}}、{{vars.NAME}} 占位符插值,// 使 MCP 服务的 Authorization 等头部可引用密钥/变量而无需明文存储。// 密钥插值限定目标主机为该 MCP 服务的出站地址,防止密钥被转发到其他主机。- clone.Header.Set(k, conf.ResolveSecretsVarsForHost(model.Conf.Secrets, model.Conf.Variables, req.URL.Hostname(), v))+ clone.Header.Set(k, conf.ResolveSecretsVarsForHost(model.Conf.Secrets.Load(), model.Conf.Variables.Load(), req.URL.Hostname(), v))}return h.base.RoundTrip(clone)}@@ -469,7 +469,7 @@ func connectStdio(ctx context.Context, client *mcp.Client, server conf.MCPServerif model.Conf == nil {return value}- return conf.ResolveSecretsVars(model.Conf.Secrets, model.Conf.Variables, value)+ return conf.ResolveSecretsVars(model.Conf.Secrets.Load(), model.Conf.Variables.Load(), value)}, runtime.GOOS)if err != nil {return nil, nil, fmt.Errorf("environment: %w", err)diff --git a/kernel/mcp/client/oauth_test.go b/kernel/mcp/client/oauth_test.goindex fed3bae385..319ac5f4d3 100644--- a/kernel/mcp/client/oauth_test.go+++ b/kernel/mcp/client/oauth_test.go@@ -546,7 +546,7 @@ func useOAuthTestConf(t *testing.T) {t.Helper()oldConf, oldConfDir, oldReadOnly := model.Conf, util.ConfDir, util.ReadOnlymodel.Conf = model.NewAppConf()- model.Conf.System = &conf.System{}+ model.Conf.System.Store(&conf.System{})util.ConfDir = t.TempDir()util.ReadOnly = falseresetOAuthCredentialStore()diff --git a/kernel/mcp/server.go b/kernel/mcp/server.goindex 05248550cd..5d581ece14 100644--- a/kernel/mcp/server.go+++ b/kernel/mcp/server.go@@ -143,10 +143,10 @@ func externalMCPToolAllowed(tool *tools.Tool) bool {if tool == nil || tool.AgentOnly || tool.Source == "mcp" || tool.Runtime == "mcp" {return false}- if model.Conf == nil || model.Conf.AI == nil || model.Conf.AI.MCP == nil {+ if model.Conf == nil || model.Conf.AI.Load() == nil || model.Conf.AI.Load().MCP == nil {return true}- return model.Conf.AI.MCP.ExposurePolicy.Allows(tools.CapabilityIDForTool(tool))+ return model.Conf.AI.Load().MCP.ExposurePolicy.Allows(tools.CapabilityIDForTool(tool))}func newServer() *mcpsdk.Server {diff --git a/kernel/mcp/tools/bazaar.go b/kernel/mcp/tools/bazaar.goindex 4b6d8a83eb..22412139b4 100644--- a/kernel/mcp/tools/bazaar.go+++ b/kernel/mcp/tools/bazaar.go@@ -114,7 +114,7 @@ func bazaarHandler(ctx context.Context, args map[string]any) (CallToolResult, erif err := ctx.Err(); err != nil {return blockToolError(err.Error())}- if model.Conf == nil || model.Conf.Bazaar == nil {+ if model.Conf == nil || model.Conf.Bazaar.Load() == nil {return blockToolError("Bazaar configuration is unavailable")}// 请求入口负责管理员鉴权;执行前再次检查只读模式与集市开关。@@ -125,10 +125,10 @@ func bazaarHandler(ctx context.Context, args map[string]any) (CallToolResult, erif isPluginProjectAction(action) {return bazaarPluginProjectAction(ctx, action, args)}- if action != "installed" && !model.Conf.Bazaar.Trust {+ if action != "installed" && !model.Conf.Bazaar.Load().Trust {return blockToolError("Bazaar is not trusted; enable Bazaar access in SiYuan settings first")}- if effects.LocalWrite && pkgType == "plugins" && model.Conf.Bazaar.PetalDisabled {+ if effects.LocalWrite && pkgType == "plugins" && model.Conf.Bazaar.Load().PetalDisabled {return blockToolError("plugins are globally disabled")}var summaries []bazaarPackageSummary@@ -251,7 +251,7 @@ func bazaarHandler(ctx context.Context, args map[string]any) (CallToolResult, erif err != nil {return bazaarProjectError(err, nil)}- if model.Conf.Bazaar.PetalDisabled {+ if model.Conf.Bazaar.Load().PetalDisabled {// 插件全局禁用时先识别归档,其他类型仍可正常安装。localType, _, _, cleanup, err := bazaar.ExtractLocalPackage(archive)if cleanup != nil {@@ -313,7 +313,7 @@ func bazaarUpdateAll(ctx context.Context, args map[string]any, frontend string)return blockToolError("update targets must have valid names and repoHash and must not repeat")}seen[key] = true- if target.PkgType == "plugins" && model.Conf.Bazaar.PetalDisabled {+ if target.PkgType == "plugins" && model.Conf.Bazaar.Load().PetalDisabled {return blockToolError("plugins are globally disabled")}}diff --git a/kernel/mcp/tools/bazaar_project_test.go b/kernel/mcp/tools/bazaar_project_test.goindex 31597e2915..4e13b1b736 100644--- a/kernel/mcp/tools/bazaar_project_test.go+++ b/kernel/mcp/tools/bazaar_project_test.go@@ -23,8 +23,8 @@ func bazaarProjectGrant(t *testing.T) (context.Context, *util.PluginDevelopmentGfunc TestBazaarProjectOfflineGuardsAndEffects(t *testing.T) {ctx, grant := bazaarProjectGrant(t)- model.Conf.Bazaar.Trust = false- model.Conf.Bazaar.PetalDisabled = true+ model.Conf.Bazaar.Load().Trust = false+ model.Conf.Bazaar.Load().PetalDisabled = trueresult, err := bazaarHandler(ctx, map[string]any{"action": "prepare_project", "taskId": grant.TaskID})if err != nil || result.IsError {t.Fatal("offline project incorrectly requires trust, frontend or pkgType", probeText(result), err)@@ -61,7 +61,7 @@ func TestBazaarProjectCandidateInspectionBeforePlan(t *testing.T) {return grant, nil})writeProbeFile(t, filepath.Join(util.WorkspaceDir, "source", "index.js"), "candidate")- model.Conf.Bazaar.Trust = false+ model.Conf.Bazaar.Load().Trust = falseresult, err := bazaarHandler(ctx, map[string]any{"action": "project_status", "taskId": grant.TaskID, "sourcePath": "source"})if err != nil || result.IsError {t.Fatal(probeText(result), err)diff --git a/kernel/mcp/tools/bazaar_test.go b/kernel/mcp/tools/bazaar_test.goindex c967f3cf9f..fe172be48c 100644--- a/kernel/mcp/tools/bazaar_test.go+++ b/kernel/mcp/tools/bazaar_test.go@@ -22,9 +22,9 @@ func setupBazaarToolTest(t *testing.T) string {root := setupProbeWorkspace(t)oldConf, oldReadonly := model.Conf, util.ReadOnlymodel.Conf = model.NewAppConf()- model.Conf.Bazaar = &conf.Bazaar{Trust: true}- model.Conf.Sync = conf.NewSync()- model.Conf.Sync.Enabled = false+ model.Conf.Bazaar.Store(&conf.Bazaar{Trust: true})+ model.Conf.Sync.Store(conf.NewSync())+ model.Conf.Sync.Load().Enabled = falseutil.ReadOnly = falset.Cleanup(func() { model.Conf, util.ReadOnly = oldConf, oldReadonly })return root@@ -61,7 +61,7 @@ func TestBazaarToolGuards(t *testing.T) {}}util.ReadOnly = false- model.Conf.Bazaar.Trust = false+ model.Conf.Bazaar.Load().Trust = falsefor _, action := range []string{"list", "updates", "readme", "install", "enable"} {result, _ := bazaarHandler(context.Background(), map[string]any{"action": action, "pkgType": "plugins", "packageName": "sample", "frontend": "desktop",@@ -75,8 +75,8 @@ func TestBazaarToolGuards(t *testing.T) {if result.IsError || json.Unmarshal([]byte(probeText(result)), &page) != nil || page.Total != 0 || page.Packages == nil {t.Fatalf("local listing should remain available: %+v", result)}- model.Conf.Bazaar.Trust = true- model.Conf.Bazaar.PetalDisabled = true+ model.Conf.Bazaar.Load().Trust = true+ model.Conf.Bazaar.Load().PetalDisabled = truefor _, action := range []string{"install", "update", "uninstall", "enable", "disable"} {result, _ = bazaarHandler(context.Background(), map[string]any{"action": action, "pkgType": "plugins", "packageName": "sample", "frontend": "mobile",@@ -179,12 +179,12 @@ func TestBazaarToolUpdateAllTargetsAndFailures(t *testing.T) {t.Fatal("blocked targets must prevent all writes")}broken.Available.DisallowUpdate = false- model.Conf.Bazaar.PetalDisabled = true+ model.Conf.Bazaar.Load().PetalDisabled = trueresult, _ = bazaarHandler(context.Background(), args)if !result.IsError || len(calls) != 0 {t.Fatal("all targets must be checked before any package is updated")}- model.Conf.Bazaar.PetalDisabled = false+ model.Conf.Bazaar.Load().PetalDisabled = falseduplicate := target("widgets", "one").(map[string]any)duplicate["repoHash"] = "different-hash"args["packages"] = []any{target("widgets", "one"), duplicate}@@ -207,12 +207,12 @@ func TestBazaarToolLocalPluginLifecycle(t *testing.T) {{name: "index.js", body: "export default {};"},})args := map[string]any{"action": "install_local", "path": "sample.zip", "frontend": "mobile"}- model.Conf.Bazaar.PetalDisabled = true+ model.Conf.Bazaar.Load().PetalDisabled = trueresult, _ := bazaarHandler(context.Background(), args)if !result.IsError || !strings.Contains(probeText(result), "globally disabled") {t.Fatalf("local install bypassed global plugin switch: %+v", result)}- model.Conf.Bazaar.PetalDisabled = false+ model.Conf.Bazaar.Load().PetalDisabled = falseresult, err := bazaarHandler(context.Background(), args)if err != nil || result.IsError {t.Fatalf("local install failed: %+v, %v", result, err)@@ -350,7 +350,7 @@ func TestBazaarToolInstalledEnabledFilter(t *testing.T) {t.Fatal("invalid manifests must retain the reason")}}- model.Conf.Bazaar.PetalDisabled = true+ model.Conf.Bazaar.Load().PetalDisabled = trueargs["enabled"] = truepage = readBazaarPage(t, args)if page.Total != 2 || page.Packages[0].Name != "broken" || page.Packages[1].Name != "enabled" {diff --git a/kernel/mcp/tools/database_test.go b/kernel/mcp/tools/database_test.goindex 1b50de5ef0..db42e98dad 100644--- a/kernel/mcp/tools/database_test.go+++ b/kernel/mcp/tools/database_test.go@@ -25,7 +25,7 @@ import (func TestDatabaseToolsRejectIncompleteUnusedScan(t *testing.T) {previousConf, previousData, previousWorkspace := model.Conf, util.DataDir, util.WorkspaceDirmodel.Conf = model.NewAppConf()- model.Conf.FileTree = conf.NewFileTree()+ model.Conf.FileTree.Store(conf.NewFileTree())util.WorkspaceDir = t.TempDir()util.DataDir = filepath.Join(util.WorkspaceDir, "data")t.Cleanup(func() { model.Conf, util.DataDir, util.WorkspaceDir = previousConf, previousData, previousWorkspace })diff --git a/kernel/mcp/tools/decision.go b/kernel/mcp/tools/decision.goindex ba1d7e001c..eee46fbfeb 100644--- a/kernel/mcp/tools/decision.go+++ b/kernel/mcp/tools/decision.go@@ -86,14 +86,16 @@ func init() {}func decisionAvailable() bool {- return decisionEnabled() && model.Conf.AI.Decision.Configured()+ return decisionEnabled() && model.Conf.AI.Load().Decision.Configured()}// decisionEnabled 不读取活动供应商配置,已开始的批次使用独立的配置快照。func decisionEnabled() bool {- return !util.IsDisabledFeature("ai") && model.Conf != nil && model.Conf.AI != nil &&- model.Conf.AI.Decision != nil && model.Conf.AI.Decision.Enabled &&- (model.Conf.AI.Agent == nil || model.Conf.AI.Agent.CapabilityPolicy.Allows("native/backend/decision"))+ confAISnapshot := model.Conf.LoadAI()++ return !util.IsDisabledFeature("ai") && model.Conf != nil && confAISnapshot != nil &&+ confAISnapshot.Decision != nil && confAISnapshot.Decision.Enabled &&+ (confAISnapshot.Agent == nil || confAISnapshot.Agent.CapabilityPolicy.Allows("native/backend/decision"))}func decisionBoxLeases(args map[string]any) []string {@@ -132,7 +134,7 @@ func decisionHandler(ctx context.Context, args map[string]any) (CallToolResult,return blockToolError("encrypted notebook is locked, please unlock it first")}defer release()- options, err := model.Conf.AI.Decision.ActiveOptions()+ options, err := model.Conf.AI.Load().Decision.ActiveOptions()if err != nil {return blockToolError(err.Error())}diff --git a/kernel/mcp/tools/decision_test.go b/kernel/mcp/tools/decision_test.goindex 4f052eebdf..d4e191bfc0 100644--- a/kernel/mcp/tools/decision_test.go+++ b/kernel/mcp/tools/decision_test.go@@ -24,10 +24,10 @@ func configureDecisionTest(t *testing.T, endpoint string) {t.Helper()original := model.Confmodel.Conf = model.NewAppConf()- model.Conf.AI = conf.NewAI()- model.Conf.Editor = conf.NewEditor()- model.Conf.Export = conf.NewExport()- model.Conf.AI.Decision = &conf.Decision{Enabled: true, Endpoint: endpoint, APIKey: "test-key", Name: "jev-test", Timeout: 1}+ model.Conf.AI.Store(conf.NewAI())+ model.Conf.Editor.Store(conf.NewEditor())+ model.Conf.Export.Store(conf.NewExport())+ model.Conf.AI.Load().Decision = &conf.Decision{Enabled: true, Endpoint: endpoint, APIKey: "test-key", Name: "jev-test", Timeout: 1}t.Cleanup(func() { model.Conf = original })}@@ -76,7 +76,7 @@ func TestDecisionSequentialPartialResults(t *testing.T) {if len(batch.Items) != 3 || batch.Items[0].Status != "completed" || batch.Items[1].Status != "error" || batch.Items[2].Status != "not_run" || batch.Items[1].Result != nil {t.Fatalf("successful or failed results confused: %+v", batch)}- model.Conf.AI.Decision.Enabled = false+ model.Conf.AI.Load().Decision.Enabled = falseresult, _ = decisionHandler(context.Background(), args)if !result.IsError || calls.Load() != 2 {t.Fatal("disabled decision performed requests")@@ -114,21 +114,21 @@ func TestDecisionBatchProviderSnapshotAndDisable(t *testing.T) {if calls.Add(1) == 1 {switch change {case "switch":- model.Conf.AI.Decision.Provider = "openai"+ model.Conf.AI.Load().Decision.Provider = "openai"case "edit":- model.Conf.AI.Decision.Profiles["typesafe"].APIKey = "changed-key"- model.Conf.AI.Decision.Profiles["typesafe"].Endpoint = "http://unused.invalid"+ model.Conf.AI.Load().Decision.Profiles["typesafe"].APIKey = "changed-key"+ model.Conf.AI.Load().Decision.Profiles["typesafe"].Endpoint = "http://unused.invalid"case "disable":- model.Conf.AI.Decision.Enabled = false+ model.Conf.AI.Load().Decision.Enabled = falsecase "deny":- model.Conf.AI.Agent.CapabilityPolicy.Overrides["native/backend/decision"] = "deny"+ model.Conf.AI.Load().Agent.CapabilityPolicy.Overrides["native/backend/decision"] = "deny"}}io.WriteString(w, `{"model":"jev-test","answers":{"q":{"type":"noul","noul":0.1}}}`)}))defer server.Close()configureDecisionTest(t, server.URL)- model.Conf.AI.Decision.Normalize()+ model.Conf.AI.Load().Decision.Normalize()result, err := decisionHandler(context.Background(), decisionArgs(t, `{"action":"evaluate","items":[{"id":"a","text":"first"},{"id":"b","text":"second"},{"id":"c","text":"third"}],"questions":[{"id":"q","type":"noul","instructions":"Relevant?"}]}`))if err != nil {t.Fatal(err)@@ -161,7 +161,7 @@ func TestDecisionOpenAIRefusalStopsBatch(t *testing.T) {}))defer server.Close()configureDecisionTest(t, server.URL)- model.Conf.AI.Decision = &conf.Decision{Enabled: true, Provider: "openai", Profiles: map[string]*conf.DecisionProfile{"openai": {Endpoint: server.URL, APIKey: "key", Name: "gpt-6-luna", Timeout: 1}}}+ model.Conf.AI.Load().Decision = &conf.Decision{Enabled: true, Provider: "openai", Profiles: map[string]*conf.DecisionProfile{"openai": {Endpoint: server.URL, APIKey: "key", Name: "gpt-6-luna", Timeout: 1}}}result, err := decisionHandler(context.Background(), decisionArgs(t, `{"action":"evaluate","items":[{"id":"a","text":"first"},{"id":"b","text":"second"},{"id":"c","text":"third"}],"questions":[{"id":"q","type":"noul","instructions":"Relevant?"}]}`))if err != nil || !result.IsError || calls.Load() != 2 {t.Fatalf("refusal was retried or ignored: %+v %v", result, err)diff --git a/kernel/mcp/tools/http_request.go b/kernel/mcp/tools/http_request.goindex c9ef5dc0e3..a3e6df651a 100644--- a/kernel/mcp/tools/http_request.go+++ b/kernel/mcp/tools/http_request.go@@ -74,13 +74,13 @@ func httpRequestHandler(args map[string]any) (CallToolResult, error) {// 智能体/MCP 客户端控制,插值密钥会让明文被发送到任意公网主机。// headers/body 中的密钥插值按目标主机限定(见 ResolveSecretsVarsForHost),// 只有目标主机在密钥的允许主机列表内才插值,密钥明文只进入出站请求,不进入 LLM 上下文。- rawURL = model.Conf.Variables.Resolve(rawURL)+ rawURL = model.Conf.Variables.Load().Resolve(rawURL)host := ""if u, err := url.Parse(rawURL); err == nil {host = u.Hostname()}resolve := func(s string) string {- return conf.ResolveSecretsVarsForHost(model.Conf.Secrets, model.Conf.Variables, host, s)+ return conf.ResolveSecretsVarsForHost(model.Conf.Secrets.Load(), model.Conf.Variables.Load(), host, s)}for k, v := range headers {headers[k] = resolve(v)diff --git a/kernel/mcp/tools/log.go b/kernel/mcp/tools/log.goindex 35aa7c1cda..3880450ee9 100644--- a/kernel/mcp/tools/log.go+++ b/kernel/mcp/tools/log.go@@ -322,6 +322,12 @@ func collectAgentLogSecrets(value reflect.Value, ownerType string, secrets map[sif !value.IsValid() {return}+ if value.CanInterface() {+ if section, ok := value.Interface().(interface{ SnapshotValue() any }); ok {+ collectAgentLogSecrets(reflect.ValueOf(section.SnapshotValue()), ownerType, secrets)+ return+ }+ }for value.Kind() == reflect.Pointer || value.Kind() == reflect.Interface {if value.IsNil() {returndiff --git a/kernel/mcp/tools/log_test.go b/kernel/mcp/tools/log_test.goindex 763652499e..d592558c4a 100644--- a/kernel/mcp/tools/log_test.go+++ b/kernel/mcp/tools/log_test.go@@ -38,7 +38,7 @@ func TestAgentLogToolReadsSearchesAndRedacts(t *testing.T) {util.ConfDir = filepath.Join(workspace, "conf")util.LogPath = filepath.Join(workspace, "temp", "siyuan.log")model.Conf = model.NewAppConf()- model.Conf.Api = &kernelConf.API{Token: "api-token-123456"}+ model.Conf.Api.Store(&kernelConf.API{Token: "api-token-123456"})t.Cleanup(func() {util.WorkspaceDir, util.DataDir, util.ConfDir, util.LogPath =originalWorkspace, originalData, originalConfDir, originalLogPathdiff --git a/kernel/mcp/tools/ref.go b/kernel/mcp/tools/ref.goindex aa1f53cb18..5cf876551b 100644--- a/kernel/mcp/tools/ref.go+++ b/kernel/mcp/tools/ref.go@@ -67,7 +67,7 @@ func refBacklinks(args map[string]any) (CallToolResult, error) {sortMode = int(v)}- _, backlinks, _, _, _ := model.GetBacklink2(id, keyword, "", sortMode, 0, model.Conf.Editor.BacklinkContainChildren)+ _, backlinks, _, _, _ := model.GetBacklink2(id, keyword, "", sortMode, 0, model.Conf.Editor.Load().BacklinkContainChildren)if len(backlinks) == 0 {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "no backlinks found"}}}, nil}@@ -88,7 +88,7 @@ func refMentions(args map[string]any) (CallToolResult, error) {sortMode = int(v)}- _, _, mentions, _, _ := model.GetBacklink2(id, "", keyword, 0, sortMode, model.Conf.Editor.BacklinkContainChildren)+ _, _, mentions, _, _ := model.GetBacklink2(id, "", keyword, 0, sortMode, model.Conf.Editor.Load().BacklinkContainChildren)if len(mentions) == 0 {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "no mentions found"}}}, nil}diff --git a/kernel/mcp/tools/repo_test.go b/kernel/mcp/tools/repo_test.goindex 46d7c2aa34..88c66d35fe 100644--- a/kernel/mcp/tools/repo_test.go+++ b/kernel/mcp/tools/repo_test.go@@ -14,7 +14,7 @@ func TestRepoCheckoutFailure(t *testing.T) {previousLangs := util.LangspreviousReadOnly := util.ReadOnlymodel.Conf = model.NewAppConf()- model.Conf.Repo = &conf.Repo{}+ model.Conf.Repo.Store(&conf.Repo{})model.Conf.Lang = "en"util.Langs = map[string]map[int]string{"en": {26: "repository key is not configured"}}util.ReadOnly = falsediff --git a/kernel/mcp/tools/skill.go b/kernel/mcp/tools/skill.goindex 18cfa5712a..b5361bacbd 100644--- a/kernel/mcp/tools/skill.go+++ b/kernel/mcp/tools/skill.go@@ -172,7 +172,7 @@ func skillLoad(args map[string]any) (CallToolResult, error) {if loaded.ResourcePath == "" {// Variables.Resolve 还会匹配 $NAME 和 ${NAME}。// 资源可能包含脚本或模板,因此只解析技能正文,避免误改资源内容。- loaded.Content = model.Conf.Variables.Resolve(loaded.Content)+ loaded.Content = model.Conf.Variables.Load().Resolve(loaded.Content)result = formatSkillContent(loaded)} else {result = formatSkillResource(loaded)diff --git a/kernel/mcp/tools/skill_test.go b/kernel/mcp/tools/skill_test.goindex 876bb6431b..532d34d445 100644--- a/kernel/mcp/tools/skill_test.go+++ b/kernel/mcp/tools/skill_test.go@@ -50,7 +50,7 @@ func TestBuiltinSkillRejectsForgedContextAndMutations(t *testing.T) {func TestBuiltinSkillTrustedActivationAndResourceReads(t *testing.T) {setSkillToolTestEnvironment(t)- model.Conf.Variables = &kernelConf.Variables{Items: []*kernelConf.Variable{{Name: "PLUGIN_NAME", Value: "modified-by-user-variable"}}}+ model.Conf.Variables.Store(&kernelConf.Variables{Items: []*kernelConf.Variable{{Name: "PLUGIN_NAME", Value: "modified-by-user-variable"}}})operations := []string{}ctx := util.WithPluginDevelopmentAccess(context.Background(), func(operation string) (*util.PluginDevelopmentGrant, error) {operations = append(operations, operation)@@ -75,12 +75,12 @@ func TestBuiltinSkillTrustedActivationAndResourceReads(t *testing.T) {t.Fatalf("resource read activated skill: %+v, %v, %v", result, err, operations)}operations = nil- model.Conf.AI.Agent.Skills.BuiltinDisabled = []string{util.BuiltinPluginSkillID}+ model.Conf.AI.Load().Agent.Skills.BuiltinDisabled = []string{util.BuiltinPluginSkillID}result, err = skillContextHandler(ctx, map[string]any{"source": "builtin", "name": util.PluginDevelopmentSkillName})if err != nil || !result.IsError || strings.Join(operations, ",") != "load" {t.Fatalf("disabled load activated skill: %+v, %v, %v", result, err, operations)}- model.Conf.AI.Agent.Skills.BuiltinDisabled = nil+ model.Conf.AI.Load().Agent.Skills.BuiltinDisabled = nilctx = util.WithPluginDevelopmentAccess(context.Background(), func(operation string) (*util.PluginDevelopmentGrant, error) {if operation == "loaded" {return nil, errors.New("choice revoked")@@ -105,8 +105,8 @@ func setSkillToolTestEnvironment(t *testing.T) string {util.HomeDir = filepath.Join(root, "home")util.ConfDir = filepath.Join(util.WorkspaceDir, "conf")model.Conf = model.NewAppConf()- model.Conf.AI = kernelConf.NewAI()- model.Conf.Variables = &kernelConf.Variables{Items: []*kernelConf.Variable{{Name: "VALUE", Value: "resolved"}}}+ model.Conf.AI.Store(kernelConf.NewAI())+ model.Conf.Variables.Store(&kernelConf.Variables{Items: []*kernelConf.Variable{{Name: "VALUE", Value: "resolved"}}})t.Cleanup(func() {util.WorkspaceDir, util.DataDir = originalWorkspaceDir, originalDataDirutil.HomeDir, util.ConfDir = originalHomeDir, originalConfDirdiff --git a/kernel/mcp/tools/snippet.go b/kernel/mcp/tools/snippet.goindex f269183d6f..ba9caa9fe2 100644--- a/kernel/mcp/tools/snippet.go+++ b/kernel/mcp/tools/snippet.go@@ -85,7 +85,7 @@ func AgentSnippetPreview(args map[string]any) (map[string]any, error) {preview["truncated"] = len(content) > 65536_, contentSet := args["content"]preview["mayExecuteJS"] = snippet.Type == "js" && (action == "enable" || (action == "replace" || action == "update" && contentSet) && snippet.Enabled)- preview["global"] = model.Conf.Snippet+ preview["global"] = model.Conf.Snippet.Load()return preview, nil}return nil, fmt.Errorf("snippet not found")@@ -96,6 +96,8 @@ func snippetAvailable() bool {}func snippetHandler(args map[string]any) (CallToolResult, error) {+ confSnippetSnapshot := model.Conf.LoadSnippet()+if !snippetAvailable() {return blockToolError("snippet capability is unavailable")}@@ -109,7 +111,7 @@ func snippetHandler(args map[string]any) (CallToolResult, error) {if action == "get" && offset > 0 && revision == "" {return blockToolError("revision is required for subsequent content pages")}- result := map[string]any{"global": model.Conf.Snippet}+ result := map[string]any{"global": confSnippetSnapshot}if action == "list" || action == "get" {snippets, err := model.LoadSnippets()if err != nil {@@ -170,7 +172,7 @@ func snippetHandler(args map[string]any) (CallToolResult, error) {if err != nil {return blockToolError(err.Error())}- model.PushReloadSnippet(model.Conf.Snippet)+ model.PushReloadSnippet(confSnippetSnapshot)result["snippet"], result["action"] = snippetSummary(snippet), action}data, err := json.Marshal(result)diff --git a/kernel/mcp/tools/snippet_test.go b/kernel/mcp/tools/snippet_test.goindex 6e5629cc15..2bd9823886 100644--- a/kernel/mcp/tools/snippet_test.go+++ b/kernel/mcp/tools/snippet_test.go@@ -17,7 +17,7 @@ func setupSnippetToolTest(t *testing.T, snippets []*conf.Snippet) {t.Helper()oldConf, oldPath := model.Conf, util.SnippetsPathmodel.Conf = model.NewAppConf()- model.Conf.Snippet = conf.NewSnpt()+ model.Conf.Snippet.Store(conf.NewSnpt())util.SnippetsPath = t.TempDir()t.Cleanup(func() { model.Conf, util.SnippetsPath = oldConf, oldPath })data, err := json.Marshal(snippets)diff --git a/kernel/mcp/tools/sync.go b/kernel/mcp/tools/sync.goindex 627c285af3..bf19cc93bc 100644--- a/kernel/mcp/tools/sync.go+++ b/kernel/mcp/tools/sync.go@@ -59,21 +59,21 @@ func syncHandler(args map[string]any) (CallToolResult, error) {func syncPerform(args map[string]any) (CallToolResult, error) {model.SyncData(true)- return CallToolResult{Content: []ContentItem{{Type: "text", Text: "sync done: " + model.Conf.Sync.Stat}}}, nil+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "sync done: " + model.Conf.Sync.Load().Stat}}}, nil}func syncUpload(args map[string]any) (CallToolResult, error) {model.SyncDataUpload()- return CallToolResult{Content: []ContentItem{{Type: "text", Text: "sync upload done: " + model.Conf.Sync.Stat}}}, nil+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "sync upload done: " + model.Conf.Sync.Load().Stat}}}, nil}func syncDownload(args map[string]any) (CallToolResult, error) {model.SyncDataDownload()- return CallToolResult{Content: []ContentItem{{Type: "text", Text: "sync download done: " + model.Conf.Sync.Stat}}}, nil+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "sync download done: " + model.Conf.Sync.Load().Stat}}}, nil}func syncStatus(args map[string]any) (CallToolResult, error) {- s := model.Conf.Sync+ s := model.Conf.Sync.Load()return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("Sync Status:\n Enabled: %v\n Mode: %d (0/1=auto, 2=manual, 3=full-manual)\n Provider: %d\n Cloud: %s\n Perception: %v\n Interval: %ds\n Synced: %d\n Stat: %s",s.Enabled, s.Mode, s.Provider, s.CloudName, s.Perception, s.Interval, s.Synced, s.Stat,diff --git a/kernel/mobile/kernel.go b/kernel/mobile/kernel.goindex c6c001b8be..99ebfc92b5 100644--- a/kernel/mobile/kernel.go+++ b/kernel/mobile/kernel.go@@ -301,8 +301,8 @@ func StartKernel(container, appDir, workspaceBaseDir, timezoneID, localIPs, langsql.InitDatabase(false)sql.InitHistoryDatabase(false)sql.InitAssetContentDatabase(false)- sql.SetCaseSensitive(model.Conf.Search.CaseSensitive)- sql.SetIndexAssetPath(model.Conf.Search.IndexAssetPath)+ // 数据库打开后重新应用搜索配置,使 PRAGMA case_sensitive_like 对新连接生效+ model.ApplySearchRuntime()finishMobileStartup(util.Container, model.BootSyncData, func() {model.CleanupEmptyPluginStorageDirs()diff --git a/kernel/model/ai.go b/kernel/model/ai.goindex 2cc260013e..85fed0ca73 100644--- a/kernel/model/ai.go+++ b/kernel/model/ai.go@@ -33,17 +33,17 @@ import ()func EnabledUserSkills() []string {- if Conf == nil || Conf.AI == nil || Conf.AI.Agent == nil || Conf.AI.Agent.Skills == nil {+ if Conf == nil || Conf.AI.Load() == nil || Conf.AI.Load().Agent == nil || Conf.AI.Load().Agent.Skills == nil {return nil}- return append([]string(nil), Conf.AI.Agent.Skills.UserEnabled...)+ return append([]string(nil), Conf.AI.Load().Agent.Skills.UserEnabled...)}func DisabledBuiltinSkills() []string {- if Conf == nil || Conf.AI == nil || Conf.AI.Agent == nil || Conf.AI.Agent.Skills == nil {+ if Conf == nil || Conf.AI.Load() == nil || Conf.AI.Load().Agent == nil || Conf.AI.Load().Agent.Skills == nil {return nil}- return append([]string(nil), Conf.AI.Agent.Skills.BuiltinDisabled...)+ return append([]string(nil), Conf.AI.Load().Agent.Skills.BuiltinDisabled...)}func ChatGPT(msg string) (ret string) {@@ -160,15 +160,17 @@ func (stream *AIEditorChatStream) Close() {// NewAIEditorChatStream 创建绑定到编辑器请求生命周期的模型流。func NewAIEditorChatStream(ctx context.Context, ids []string, input, action string, history []AIEditorMessage) (*AIEditorChatStream, error) {- if !Conf.AI.HasAnyProvider() {+ confAISnapshot := Conf.LoadAI()++ if !confAISnapshot.HasAnyProvider() {return nil, errors.New("no AI provider configured")}- prov, m := Conf.AI.GetEditingModel()+ prov, m := confAISnapshot.GetEditingModel()if nil == prov || nil == m {return nil, errors.New("no AI editing model configured")}- editing := Conf.AI.Editing+ editing := confAISnapshot.Editingif nil == editing {return nil, errors.New("no AI editing config")}@@ -243,16 +245,18 @@ func IsAIEditorStreamDone(err error) bool {}func chatGPTComplete(msg string, contextMsgs []string, cloud bool) (ret string, retContextMsgs []string, err error) {+ confAISnapshot := Conf.LoadAI()+util.PushEndlessProgress("Requesting...")defer util.ClearPushProgress(100)- prov, m := Conf.AI.GetEditingModel()+ prov, m := confAISnapshot.GetEditingModel()if nil == prov || nil == m {err = errors.New("no AI provider configured")return}- editing := Conf.AI.Editing+ editing := confAISnapshot.Editingif nil == editing {err = errors.New("no AI editing config")return@@ -299,7 +303,7 @@ func chatGPTComplete(msg string, contextMsgs []string, cloud bool) (ret string,}func isOpenAIAPIEnabled() bool {- if !Conf.AI.HasAnyProvider() {+ if !Conf.AI.Load().HasAnyProvider() {util.PushMsg(Conf.Language(193), 5000)return false}diff --git a/kernel/model/ai_disabled_test.go b/kernel/model/ai_disabled_test.goindex b5437c6b4c..b63d215826 100644--- a/kernel/model/ai_disabled_test.go+++ b/kernel/model/ai_disabled_test.go@@ -11,16 +11,16 @@ func TestAIDisabledBackgroundFeatures(t *testing.T) {previousConf, previousFeatures := Conf, util.DisabledFeaturest.Cleanup(func() { Conf, util.DisabledFeatures = previousConf, previousFeatures })Conf = NewAppConf()- Conf.AI = conf.NewAI()- Conf.AI.Embedding = &conf.Embedding{Enabled: true, APIKey: "embedding-key"}- Conf.AI.Rerank = &conf.Rerank{Enabled: true, APIKey: "rerank-key"}+ Conf.AI.Store(conf.NewAI())+ Conf.AI.Load().Embedding = &conf.Embedding{Enabled: true, APIKey: "embedding-key"}+ Conf.AI.Load().Rerank = &conf.Rerank{Enabled: true, APIKey: "rerank-key"}util.DisabledFeatures = []string{"ai"}if isEmbeddingEnabled() || isRerankEnabled() {t.Fatal("AI background features are enabled")}fullReindexEmbedding()retryFailedEmbedding()- if !Conf.AI.Embedding.Enabled || !Conf.AI.Rerank.Enabled || Conf.AI.Embedding.APIKey != "embedding-key" {+ if !Conf.AI.Load().Embedding.Enabled || !Conf.AI.Load().Rerank.Enabled || Conf.AI.Load().Embedding.APIKey != "embedding-key" {t.Fatal("disabling AI modified stored configuration")}util.DisabledFeatures = nildiff --git a/kernel/model/ai_headers.go b/kernel/model/ai_headers.goindex 08113c167f..a47f741045 100644--- a/kernel/model/ai_headers.go+++ b/kernel/model/ai_headers.go@@ -19,7 +19,7 @@ func ResolveAIProviderHeaders(provider *conf.Provider) map[string]string {headers := make(map[string]string, len(provider.Headers))for name, value := range provider.Headers {if Conf != nil {- value = conf.ResolveSecretsVarsForHost(Conf.Secrets, Conf.Variables, host, value)+ value = conf.ResolveSecretsVarsForHost(Conf.Secrets.Load(), Conf.Variables.Load(), host, value)}headers[name] = value}diff --git a/kernel/model/ai_headers_test.go b/kernel/model/ai_headers_test.goindex 88cdce7bb1..04fbe2ab2d 100644--- a/kernel/model/ai_headers_test.go+++ b/kernel/model/ai_headers_test.go@@ -17,8 +17,8 @@ func TestResolveAIProviderHeaders(t *testing.T) {previousConf := Conft.Cleanup(func() { Conf = previousConf })Conf = &AppConf{- Secrets: &conf.Secrets{Items: []*conf.Secret{{Name: "TOKEN", Value: "private-token", AllowedHosts: []string{"127.0.0.1"}}}},- Variables: &conf.Variables{Items: []*conf.Variable{{Name: "ROUTE", Value: "route-a"}}},+ Secrets: NewConfSection(&conf.Secrets{Items: []*conf.Secret{{Name: "TOKEN", Value: "private-token", AllowedHosts: []string{"127.0.0.1"}}}}),+ Variables: NewConfSection(&conf.Variables{Items: []*conf.Variable{{Name: "ROUTE", Value: "route-a"}}}),}requests := 0server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {@@ -48,8 +48,8 @@ func TestResolveAIProviderHeaders(t *testing.T) {}provider.BaseURL = server.URL + "/v1"endpoint, _ := url.Parse(server.URL)- Conf.Secrets.Items[0].AllowedHosts = []string{endpoint.Hostname()}- Conf.Secrets.Items[0].Value = "private-token\r\ninjected: true"+ Conf.Secrets.Load().Items[0].AllowedHosts = []string{endpoint.Hostname()}+ Conf.Secrets.Load().Items[0].Value = "private-token\r\ninjected: true"client = util.NewOpenAIClient("", provider.BaseURL, ResolveAIProviderHeaders(provider))if _, err := client.ListModels(context.Background()); err == nil || strings.Contains(err.Error(), "private-token") {t.Fatal("invalid resolved header must fail without exposing its value")diff --git a/kernel/model/appearance.go b/kernel/model/appearance.goindex 505c4eb660..a157216c3b 100644--- a/kernel/model/appearance.go+++ b/kernel/model/appearance.go@@ -66,18 +66,21 @@ func refreshAppearanceConfig() {var reloadThemes, reloadIcons boolConf.m.Lock()- if !containTheme(Conf.Appearance.ThemeDark, Conf.Appearance.DarkThemes) {- Conf.Appearance.ThemeDark = "midnight"- reloadThemes = true- }- if !containTheme(Conf.Appearance.ThemeLight, Conf.Appearance.LightThemes) {- Conf.Appearance.ThemeLight = "daylight"- reloadThemes = true- }- if !containIcon(Conf.Appearance.Icon, Conf.Appearance.Icons) {- Conf.Appearance.Icon = "litheness"- reloadIcons = true- }+ replaceConfSectionLocked(&Conf.Appearance, func(appearance *conf.Appearance) bool {+ if !containTheme(appearance.ThemeDark, appearance.DarkThemes) {+ appearance.ThemeDark = "midnight"+ reloadThemes = true+ }+ if !containTheme(appearance.ThemeLight, appearance.LightThemes) {+ appearance.ThemeLight = "daylight"+ reloadThemes = true+ }+ if !containIcon(appearance.Icon, appearance.Icons) {+ appearance.Icon = "litheness"+ reloadIcons = true+ }+ return reloadThemes || reloadIcons+ })Conf.m.Unlock()if reloadThemes {LoadThemes()@@ -92,49 +95,59 @@ func SetIcon(icon string) error {Conf.m.Lock()defer Conf.m.Unlock()- if !containIcon(icon, Conf.Appearance.Icons) {+ if !containIcon(icon, Conf.Appearance.Load().Icons) {return fmt.Errorf("icon [%s] not exists or not available", icon)}- Conf.Appearance.Icon = icon+ replaceConfSectionLocked(&Conf.Appearance, func(appearance *conf.Appearance) bool {+ appearance.Icon = icon+ return true+ })return nil}-func SetTheme(theme string, modes []int, appearanceMode string) error {+// SetTheme 校验全部参数后一次性替换外观配置段,任一参数无效时保持原配置不变。+func SetTheme(theme string, modes []int, appearanceMode string) (err error) {Conf.m.Lock()defer Conf.m.Unlock()- if theme != "" {- for _, mode := range modes {- switch mode {- case 0:- if !containTheme(theme, Conf.Appearance.LightThemes) {- return fmt.Errorf("theme [%s] not exists or not available for light mode", theme)- }- Conf.Appearance.ThemeLight = theme- case 1:- if !containTheme(theme, Conf.Appearance.DarkThemes) {- return fmt.Errorf("theme [%s] not exists or not available for dark mode", theme)+ replaceConfSectionLocked(&Conf.Appearance, func(appearance *conf.Appearance) bool {+ if theme != "" {+ for _, mode := range modes {+ switch mode {+ case 0:+ if !containTheme(theme, appearance.LightThemes) {+ err = fmt.Errorf("theme [%s] not exists or not available for light mode", theme)+ return false+ }+ appearance.ThemeLight = theme+ case 1:+ if !containTheme(theme, appearance.DarkThemes) {+ err = fmt.Errorf("theme [%s] not exists or not available for dark mode", theme)+ return false+ }+ appearance.ThemeDark = theme}- Conf.Appearance.ThemeDark = theme}}- }- if appearanceMode != "" {- switch appearanceMode {- case "light":- Conf.Appearance.ModeOS = false- Conf.Appearance.Mode = 0- case "dark":- Conf.Appearance.ModeOS = false- Conf.Appearance.Mode = 1- case "system":- Conf.Appearance.ModeOS = true- default:- return fmt.Errorf("invalid appearance mode: %s", appearanceMode)+ if appearanceMode != "" {+ switch appearanceMode {+ case "light":+ appearance.ModeOS = false+ appearance.Mode = 0+ case "dark":+ appearance.ModeOS = false+ appearance.Mode = 1+ case "system":+ appearance.ModeOS = true+ default:+ err = fmt.Errorf("invalid appearance mode: %s", appearanceMode)+ return false+ }}- }- return nil+ return true+ })+ return}func containTheme(name string, themes []*conf.AppearanceTheme) bool {@@ -180,6 +193,8 @@ func appearancePackageNames(kind string) ([]string, error) {}func LoadThemes() {+ confAppearanceSnapshot := Conf.LoadAppearance()+themeNames, err := appearancePackageNames("themes")if err != nil {logging.LogErrorf("read appearance themes folder failed: %s", err)@@ -191,9 +206,9 @@ func LoadThemes() {var daylightTheme, midnightTheme *conf.AppearanceThemevar themeVer stringvar themeJS bool- mode := Conf.Appearance.Mode- themeLight := Conf.Appearance.ThemeLight- themeDark := Conf.Appearance.ThemeDark+ mode := confAppearanceSnapshot.Mode+ themeLight := confAppearanceSnapshot.ThemeLight+ themeDark := confAppearanceSnapshot.ThemeDarkfor _, name := range themeNames {themePath := util.AppearancePackagePath("themes", name)themeConf, parseErr := bazaar.ParsePackageJSON(filepath.Join(themePath, "theme.json"))@@ -259,10 +274,13 @@ func LoadThemes() {}Conf.m.Lock()- Conf.Appearance.DarkThemes = darkThemes- Conf.Appearance.LightThemes = lightThemes- Conf.Appearance.ThemeVer = themeVer- Conf.Appearance.ThemeJS = themeJS+ replaceConfSectionLocked(&Conf.Appearance, func(appearance *conf.Appearance) bool {+ appearance.DarkThemes = darkThemes+ appearance.LightThemes = lightThemes+ appearance.ThemeVer = themeVer+ appearance.ThemeJS = themeJS+ return true+ })Conf.m.Unlock()}@@ -276,7 +294,7 @@ func LoadIcons() {var icons []*conf.AppearanceIconvar iconVer string- currentIcon := Conf.Appearance.Icon+ currentIcon := Conf.Appearance.Load().Iconfor _, name := range iconNames {iconPath := util.AppearancePackagePath("icons", name)iconConf, err := bazaar.ParsePackageJSON(filepath.Join(iconPath, "icon.json"))@@ -305,19 +323,24 @@ func LoadIcons() {}}Conf.m.Lock()- Conf.Appearance.Icons = icons- Conf.Appearance.IconVer = iconVer+ replaceConfSectionLocked(&Conf.Appearance, func(appearance *conf.Appearance) bool {+ appearance.Icons = icons+ appearance.IconVer = iconVer+ return true+ })Conf.m.Unlock()}func isCurrentUseTheme(themePath string) string {+ confAppearanceSnapshot := Conf.LoadAppearance()+themeName := filepath.Base(filepath.Dir(themePath))- if 0 == Conf.Appearance.Mode { // 明亮- if Conf.Appearance.ThemeLight == themeName {+ if 0 == confAppearanceSnapshot.Mode { // 明亮+ if confAppearanceSnapshot.ThemeLight == themeName {return themeName}- } else if 1 == Conf.Appearance.Mode { // 暗黑- if Conf.Appearance.ThemeDark == themeName {+ } else if 1 == confAppearanceSnapshot.Mode { // 暗黑+ if confAppearanceSnapshot.ThemeDark == themeName {return themeName}}@@ -331,16 +354,16 @@ func currentThemeDir() string {Conf.m.RLock()defer Conf.m.RUnlock()- if nil == Conf.Appearance {+ if nil == Conf.Appearance.Load() {return ""}var themeName string- switch Conf.Appearance.Mode {+ switch Conf.Appearance.Load().Mode {case 0:- themeName = Conf.Appearance.ThemeLight+ themeName = Conf.Appearance.Load().ThemeLightcase 1:- themeName = Conf.Appearance.ThemeDark+ themeName = Conf.Appearance.Load().ThemeDarkdefault:return ""}diff --git a/kernel/model/appearance_packages_test.go b/kernel/model/appearance_packages_test.goindex 6e81713d3b..70920a1558 100644--- a/kernel/model/appearance_packages_test.go+++ b/kernel/model/appearance_packages_test.go@@ -38,7 +38,7 @@ func setupAppearancePackagesTest(t *testing.T) {util.ThemesPath, util.IconsPath = filepath.Join(root, "data", "themes"), filepath.Join(root, "data", "icons")util.Mode = "prod"Conf = NewAppConf()- Conf.Appearance = conf.NewAppearance()+ Conf.Appearance.Store(conf.NewAppearance())for _, name := range []string{"daylight", "midnight", "custom"} {writeAppearanceTestPackage(t, "themes", name, "1.0.0", "")}@@ -87,28 +87,28 @@ func TestLoadAppearancePackagesPreservesBuiltInsAndChecksVersion(t *testing.T) {writeAppearanceTestPackage(t, "icons", "future", "2.0.0", "999.0.0")writeAppearanceTestFile(t, filepath.Join(util.ThemesPath, "daylight", "theme.json"), `{"name":"daylight","version":"99.0.0"}`)writeAppearanceTestFile(t, filepath.Join(util.IconsPath, "litheness", "icon.json"), `{"name":"litheness","version":"99.0.0"}`)- Conf.Appearance.ThemeLight, Conf.Appearance.Icon = "custom", "custom"+ Conf.Appearance.Load().ThemeLight, Conf.Appearance.Load().Icon = "custom", "custom"LoadThemes()LoadIcons()- if !containTheme("daylight", Conf.Appearance.LightThemes) || !containTheme("midnight", Conf.Appearance.DarkThemes) ||- !containIcon("litheness", Conf.Appearance.Icons) {+ if !containTheme("daylight", Conf.Appearance.Load().LightThemes) || !containTheme("midnight", Conf.Appearance.Load().DarkThemes) ||+ !containIcon("litheness", Conf.Appearance.Load().Icons) {t.Fatal("built-in packages were not retained")}- if !containTheme("custom", Conf.Appearance.LightThemes) || !containIcon("custom", Conf.Appearance.Icons) {+ if !containTheme("custom", Conf.Appearance.Load().LightThemes) || !containIcon("custom", Conf.Appearance.Load().Icons) {t.Fatal("data packages were not loaded")}- if containTheme("future", Conf.Appearance.LightThemes) || containIcon("future", Conf.Appearance.Icons) {+ if containTheme("future", Conf.Appearance.Load().LightThemes) || containIcon("future", Conf.Appearance.Load().Icons) {t.Fatal("packages requiring a newer application were loaded")}- if Conf.Appearance.ThemeLight != "custom" || Conf.Appearance.Icon != "custom" ||- Conf.Appearance.ThemeVer != "1.0.0" || Conf.Appearance.IconVer != "1.0.0" {+ if Conf.Appearance.Load().ThemeLight != "custom" || Conf.Appearance.Load().Icon != "custom" ||+ Conf.Appearance.Load().ThemeVer != "1.0.0" || Conf.Appearance.Load().IconVer != "1.0.0" {t.Fatal("local selection or package version changed unexpectedly")}if err := os.Remove(filepath.Join(util.IconsPath, "custom", "icon.js")); err != nil {t.Fatal(err)}LoadIcons()- if containIcon("custom", Conf.Appearance.Icons) {+ if containIcon("custom", Conf.Appearance.Load().Icons) {t.Fatal("incomplete icon package was loaded")}}@@ -162,10 +162,10 @@ func TestExportAppearanceReportsMissingEmojiFont(t *testing.T) {func TestRefreshAppearanceConfigFallsBackAfterRemoval(t *testing.T) {setupAppearancePackagesTest(t)writeAppearanceTestFile(t, filepath.Join(util.ThemesPath, "custom", "theme.js"), "script")- Conf.Appearance.ThemeLight, Conf.Appearance.Icon = "custom", "custom"- Conf.Appearance.ThemeDark = "missing"+ Conf.Appearance.Load().ThemeLight, Conf.Appearance.Load().Icon = "custom", "custom"+ Conf.Appearance.Load().ThemeDark = "missing"refreshAppearanceConfig()- if !Conf.Appearance.ThemeJS || Conf.Appearance.ThemeLight != "custom" || Conf.Appearance.ThemeDark != "midnight" {+ if !Conf.Appearance.Load().ThemeJS || Conf.Appearance.Load().ThemeLight != "custom" || Conf.Appearance.Load().ThemeDark != "midnight" {t.Fatal("fallback for an unused mode changed the current theme script")}if err := os.Remove(filepath.Join(util.ThemesPath, "custom", "theme.json")); err != nil {@@ -173,8 +173,8 @@ func TestRefreshAppearanceConfigFallsBackAfterRemoval(t *testing.T) {}writeAppearanceTestPackage(t, "icons", "custom", "2.0.0", "999.0.0")refreshAppearanceConfig()- if Conf.Appearance.ThemeLight != "daylight" || Conf.Appearance.Icon != "litheness" || Conf.Appearance.ThemeJS ||- Conf.Appearance.ThemeVer != "1.0.0" || Conf.Appearance.IconVer != "1.0.0" {- t.Fatalf("appearance fallback retained stale package state: %+v", Conf.Appearance)+ if Conf.Appearance.Load().ThemeLight != "daylight" || Conf.Appearance.Load().Icon != "litheness" || Conf.Appearance.Load().ThemeJS ||+ Conf.Appearance.Load().ThemeVer != "1.0.0" || Conf.Appearance.Load().IconVer != "1.0.0" {+ t.Fatalf("appearance fallback retained stale package state: %+v", Conf.Appearance.Load())}}diff --git a/kernel/model/appearance_sync.go b/kernel/model/appearance_sync.goindex 3cccf978ac..977b6461e4 100644--- a/kernel/model/appearance_sync.go+++ b/kernel/model/appearance_sync.go@@ -52,7 +52,7 @@ func refreshAppearancePackages(themes, icons []string) {}refreshAppearanceConfig()util.BroadcastByType("main", "refreshAppearance", 0, "", map[string]any{- "appearance": Conf.Appearance, "themes": themes, "icons": icons,+ "appearance": Conf.Appearance.Load(), "themes": themes, "icons": icons,"revision": time.Now().UTC().Format("20060102150405.000000000"),})}diff --git a/kernel/model/asset_content.go b/kernel/model/asset_content.goindex b2504eb0a0..1cff98fb9a 100644--- a/kernel/model/asset_content.go+++ b/kernel/model/asset_content.go@@ -161,7 +161,7 @@ func fullTextSearchAssetContentByRegexp(exp, typeFilter string, typeArgs []any,stmt := "SELECT * FROM `asset_contents_fts_case_insensitive` WHERE " + fieldFilter + typeFilterstmt += " " + orderBystmt += " LIMIT " + strconv.Itoa(pageSize) + " OFFSET " + strconv.Itoa((page-1)*pageSize)- assetContents := sql.SelectAssetContentsRawStmtNoParseArgs(stmt, args, Conf.Search.Limit)+ assetContents := sql.SelectAssetContentsRawStmtNoParseArgs(stmt, args, Conf.Search.Load().Limit)ret = fromSQLAssetContents(&assetContents)if 1 > len(ret) {ret = []*AssetContent{}@@ -199,7 +199,7 @@ func fullTextSearchAssetContentByFTS(query, typeFilter string, typeArgs []any, ostmt += " LIMIT " + strconv.Itoa(pageSize) + " OFFSET " + strconv.Itoa((page-1)*pageSize)args := []any{buildAssetContentColumnFilter() + ":(" + query + ")"}args = append(args, typeArgs...)- assetContents := sql.SelectAssetContentsRawStmtNoParseArgs(stmt, args, Conf.Search.Limit)+ assetContents := sql.SelectAssetContentsRawStmtNoParseArgs(stmt, args, Conf.Search.Load().Limit)ret = fromSQLAssetContents(&assetContents)if 1 > len(ret) {ret = []*AssetContent{}diff --git a/kernel/model/asset_download.go b/kernel/model/asset_download.goindex 0024b7ba6f..e8b03da4c9 100644--- a/kernel/model/asset_download.go+++ b/kernel/model/asset_download.go@@ -70,26 +70,30 @@ func DeferredSyncAssets() ([]*entity.File, error) {}func deferredSyncAssets() ([]*entity.File, error) {+ confRepoSnapshot := Conf.LoadRepo()+exists, err := assetDownloadStateExists()if err != nil || !exists {return nil, err}- if Conf.Repo == nil || len(Conf.Repo.Key) == 0 {+ if confRepoSnapshot == nil || len(confRepoSnapshot.Key) == 0 {return nil, errors.New(Conf.Language(377))}- return dejavu.ReadDeferredAssets(assetDownloadStatePath(), Conf.Repo.Key)+ return dejavu.ReadDeferredAssets(assetDownloadStatePath(), confRepoSnapshot.Key)}// validateAssetDownloadSourceScope 在公布新的账号身份前保留未完成的资源与历史恢复来源。func validateAssetDownloadSourceScope(scope string) error {+ confRepoSnapshot := Conf.LoadRepo()+exists, err := assetDownloadStateExists()if err != nil || !exists {return err}- if Conf.Repo == nil || len(Conf.Repo.Key) == 0 {+ if confRepoSnapshot == nil || len(confRepoSnapshot.Key) == 0 {return errors.New(Conf.Language(377))}- stored, err := dejavu.ReadAssetDownloadScope(assetDownloadStatePath(), Conf.Repo.Key)+ stored, err := dejavu.ReadAssetDownloadScope(assetDownloadStatePath(), confRepoSnapshot.Key)if err != nil || stored == scope {return err}@@ -97,10 +101,12 @@ func validateAssetDownloadSourceScope(scope string) error {}func checkAssetDownloadAccess() error {- if Conf.Sync == nil || !Conf.Sync.Enabled || Conf.GetUser() == nil {+ confSyncSnapshot := Conf.LoadSync()++ if confSyncSnapshot == nil || !confSyncSnapshot.Enabled || Conf.GetUser() == nil {return errors.New(Conf.Language(376))}- switch Conf.Sync.Provider {+ switch confSyncSnapshot.Provider {case conf.ProviderSiYuan:if !IsSubscriber() {return errors.New(Conf.Language(376))@@ -383,8 +389,7 @@ func SetSyncAssetDownloadMode(mode int) error {return err}}- Conf.Sync.AssetDownloadMode = mode- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.AssetDownloadMode = mode })return nil}@@ -419,9 +424,11 @@ func openRepoFileWithAssets(repo *dejavu.Repo, file *entity.File) ([]byte, error// readRepoFileWithAssets 将仓库实例的创建和历史分块补齐纳入来源读锁。func readRepoFileWithAssets(fileID string) ([]byte, *entity.File, error) {+ confRepoSnapshot := Conf.LoadRepo()+assetDownloadSourceMu.RLock()defer assetDownloadSourceMu.RUnlock()- if Conf.Repo == nil || len(Conf.Repo.Key) == 0 {+ if confRepoSnapshot == nil || len(confRepoSnapshot.Key) == 0 {return nil, nil, errors.New(Conf.Language(26))}repo, err := newRepositoryWithAssetSourceLocked()diff --git a/kernel/model/asset_download_read.go b/kernel/model/asset_download_read.goindex b57df0d023..8a318b61b7 100644--- a/kernel/model/asset_download_read.go+++ b/kernel/model/asset_download_read.go@@ -145,6 +145,8 @@ func prepareExportAssets(boxID string, docPaths []string, includeFootnotes ...bo// prepareExportAssetsInScope 在单块导出时按块范围收集依赖,文档导出仍按文档路径收集。func prepareExportAssetsInScope(boxID string, docPaths []string, includeFootnotes bool, blockID string) error {+ confExportSnapshot := Conf.LoadExport()+if boxID != "" && IsEncryptedBox(boxID) && !IsBoxUnlocked(boxID) {return errors.New(Conf.Language(314))}@@ -214,14 +216,14 @@ func prepareExportAssetsInScope(boxID string, docPaths []string, includeFootnote}defer treenode.MaterializeTabTitles(tree.Root)()}- if includeFootnotes && Conf.Export.BlockRefMode == 4 && tree.Root.Type == ast.NodeDocument {+ if includeFootnotes && confExportSnapshot.BlockRefMode == 4 && tree.Root.Type == ast.NodeDocument {// 按单文件导出的脚注展开规则收集资源,不受是否另行导出关联文档影响order := []string{}footnotes := map[string]*refAsFootnotes{}depth := 0collectFootnotesDefs0(tree, tree.Root, &order, footnotes, &depth, nil)defs, defsErr := resolveFootnotesDefs(&order, footnotes, tree, map[string]bool{},- Conf.Export.BlockRefTextLeft, Conf.Export.BlockRefTextRight, false)+ confExportSnapshot.BlockRefTextLeft, confExportSnapshot.BlockRefTextRight, false)if defsErr != nil {return defsErr}@@ -233,15 +235,17 @@ func prepareExportAssetsInScope(boxID string, docPaths []string, includeFootnote}}treenode.WalkWithTabTitles(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ confSearchSnapshot := Conf.LoadSearch()+if !entering || node.Type != ast.NodeBlockQueryEmbedScript {return ast.WalkContinue}stmt := strings.ReplaceAll(html.UnescapeString(node.TokensStr()), editor.IALValEscNewLine, "\n")var blocks []*sql.Blockif IsEncryptedBox(tree.Box) {- blocks = sql.SelectBlocksRawStmtInBox(stmt, 1, Conf.Search.Limit, tree.Box)+ blocks = sql.SelectBlocksRawStmtInBox(stmt, 1, confSearchSnapshot.Limit, tree.Box)} else {- blocks = sql.SelectBlocksRawStmt(stmt, 1, Conf.Search.Limit)+ blocks = sql.SelectBlocksRawStmt(stmt, 1, confSearchSnapshot.Limit)}for _, block := range blocks {if embedded, loadErr := loadExportRelatedTree(block.ID, tree.Box); loadErr == nil {diff --git a/kernel/model/asset_download_read_test.go b/kernel/model/asset_download_read_test.goindex bb68f13de8..95dcae95f0 100644--- a/kernel/model/asset_download_read_test.go+++ b/kernel/model/asset_download_read_test.go@@ -72,12 +72,12 @@ func TestDeferredAssetReadAndDirectoryExport(t *testing.T) {originalConf := ConforiginalWorkspace, originalData, originalRepo := util.WorkspaceDir, util.DataDir, util.RepoDiroriginalHistory, originalTemp, originalConfDir := util.HistoryDir, util.TempDir, util.ConfDir- originalStatusBar := util.StatusBarCfg+ originalStatusBar := util.StatusBarCfg.Load()t.Cleanup(func() {Conf = originalConfutil.WorkspaceDir, util.DataDir, util.RepoDir = originalWorkspace, originalData, originalRepoutil.HistoryDir, util.TempDir, util.ConfDir = originalHistory, originalTemp, originalConfDir- util.StatusBarCfg = originalStatusBar+ util.StatusBarCfg.Store(originalStatusBar)})base := t.TempDir()remote := filepath.Join(base, "cloud")@@ -104,14 +104,20 @@ func TestDeferredAssetReadAndDirectoryExport(t *testing.T) {}}Conf = NewAppConf()- util.StatusBarCfg = &util.StatusBar{MsgDataSyncDisabled: true}- Conf.Sync, Conf.Repo, Conf.System, Conf.Search = conf.NewSync(), conf.NewRepo(), conf.NewSystem(), conf.NewSearch()- Conf.FileTree = conf.NewFileTree()- Conf.Sync.Local = &conf.Local{Endpoint: remote}+ util.StatusBarCfg.Store(&util.StatusBar{MsgDataSyncDisabled: true})+ {+ confSectionValue0, confSectionValue1, confSectionValue2, confSectionValue3 := conf.NewSync(), conf.NewRepo(), conf.NewSystem(), conf.NewSearch()+ Conf.Sync.Store(confSectionValue0)+ Conf.Repo.Store(confSectionValue1)+ Conf.System.Store(confSectionValue2)+ Conf.Search.Store(confSectionValue3)+ }+ Conf.FileTree.Store(conf.NewFileTree())+ Conf.Sync.Load().Local = &conf.Local{Endpoint: remote}Conf.User = &conf.User{UserId: "asset-test", UserSiYuanOneTimePayStatus: 1}- Conf.Sync.Provider, Conf.Sync.CloudName, Conf.Sync.Enabled = conf.ProviderLocal, "main", true- Conf.Sync.Local.Endpoint, Conf.Sync.AssetDownloadMode = remote, 1- Conf.Repo.Key = key+ Conf.Sync.Load().Provider, Conf.Sync.Load().CloudName, Conf.Sync.Load().Enabled = conf.ProviderLocal, "main", true+ Conf.Sync.Load().Local.Endpoint, Conf.Sync.Load().AssetDownloadMode = remote, 1+ Conf.Repo.Load().Key = keyutil.WorkspaceDir = filepath.Join(base, "partial")util.DataDir, util.RepoDir = filepath.Join(util.WorkspaceDir, "data"), filepath.Join(util.WorkspaceDir, "repo")util.HistoryDir, util.TempDir = filepath.Join(util.WorkspaceDir, "history"), filepath.Join(util.WorkspaceDir, "temp")@@ -151,14 +157,14 @@ func TestDeferredAssetReadAndDirectoryExport(t *testing.T) {if err != nil || !bytes.Equal(data, []byte("image bytes")) {t.Fatalf("on-demand read: %q, %v", data, err)}- Conf.Sync.Enabled = false+ Conf.Sync.Load().Enabled = falseif _, err = ReadAssetBytesInBox("", "assets/image.png"); err != nil {t.Fatalf("cached asset unavailable with sync disabled: %v", err)}if uri, exportErr := ExportResources([]string{"data/assets/site"}, "site"); exportErr == nil || uri != "" {t.Fatalf("offline incomplete directory export succeeded: %q, %v", uri, exportErr)}- Conf.Sync.Enabled = true+ Conf.Sync.Load().Enabled = trueuri, err := ExportResources([]string{"data/assets/site"}, "site")if err != nil {t.Fatal(err)diff --git a/kernel/model/asset_download_recovery_fts5_test.go b/kernel/model/asset_download_recovery_fts5_test.goindex b270848f1e..78167a895e 100644--- a/kernel/model/asset_download_recovery_fts5_test.go+++ b/kernel/model/asset_download_recovery_fts5_test.go@@ -113,7 +113,7 @@ func TestAssetDownloadRecoveryUpdatesDocumentCache(t *testing.T) {if err != nil {t.Fatal(err)}- scope, err := dejavu.ReadAssetDownloadScope(assetDownloadStatePath(), Conf.Repo.Key)+ scope, err := dejavu.ReadAssetDownloadScope(assetDownloadStatePath(), Conf.Repo.Load().Key)if err != nil {t.Fatal(err)}@@ -127,7 +127,7 @@ func TestAssetDownloadRecoveryUpdatesDocumentCache(t *testing.T) {if err != nil {t.Fatal(err)}- store, err := dejavu.NewStore(t.TempDir(), Conf.Repo.Key)+ store, err := dejavu.NewStore(t.TempDir(), Conf.Repo.Load().Key)if err != nil {t.Fatal(err)}diff --git a/kernel/model/asset_download_regression_test.go b/kernel/model/asset_download_regression_test.goindex b007971b22..277b236ab9 100644--- a/kernel/model/asset_download_regression_test.go+++ b/kernel/model/asset_download_regression_test.go@@ -18,8 +18,13 @@ import (func prepareAssetDownloadDocumentTest(t *testing.T) (*fileOperationTestFixture, *dejavu.Repo, *dejavu.Repo, string) {fixture := setupFileOperationTest(t)full, partial, fullData := prepareAssetDownloadRepoTest(t)- Conf.Export, Conf.Editor, Conf.Appearance = conf.NewExport(), conf.NewEditor(), conf.NewAppearance()- Conf.FileTree = conf.NewFileTree()+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewExport(), conf.NewEditor(), conf.NewAppearance()+ Conf.Export.Store(confSectionValue0)+ Conf.Editor.Store(confSectionValue1)+ Conf.Appearance.Store(confSectionValue2)+ }+ Conf.FileTree.Store(conf.NewFileTree())Conf.NotebookCrypto = conf.NewNotebookCrypto()for i := 0; i < 3; i++ {writeAssetDownloadDocumentTest(t, treenode.NewTree(fixture.box.ID, "/"+ast.NewNodeID()+".sy", "/Seed", "Seed"))@@ -50,7 +55,7 @@ func TestAssetDownloadCrossNotebookExport(t *testing.T) {source := treenode.NewTree(fixture.box.ID, "/20260905210002-abcdefg.sy", "/Source", "Source")source.Root.FirstChild.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkBlockRefID: other.Root.FirstChild.ID, TextMarkBlockRefSubtype: "d", TextMarkTextContent: "Other"})writeAssetDownloadDocumentTest(t, source)- Conf.Export.IncludeRelatedDocs = true+ Conf.Export.Load().IncludeRelatedDocs = true_, paths := prepareExportTreesWithConfig([]string{source.Path}, resolveExportOptions(nil), source.Box)if len(paths) != 2 {t.Fatalf("expected two export documents, got %v", paths)@@ -69,22 +74,22 @@ func TestAssetDownloadFootnoteExport(t *testing.T) {source := treenode.NewTree(fixture.box.ID, "/20260905210004-abcdefg.sy", "/Source", "Source")source.Root.FirstChild.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkBlockRefID: target.Root.FirstChild.ID, TextMarkBlockRefSubtype: "d", TextMarkTextContent: "Target"})writeAssetDownloadDocumentTest(t, source)- Conf.Export.IncludeRelatedDocs = false- Conf.Export.BlockRefMode = 4+ Conf.Export.Load().IncludeRelatedDocs = false+ Conf.Export.Load().BlockRefMode = 4if err := prepareExportBlockAssets(source.ID, false); err != nil {t.Fatal(err)}exported, prepareErr := exportTree(prepareExportTree(getExportBlockTree(source.ID)), treeExportOptions{Config: conf.Export{- BlockRefMode: Conf.Export.BlockRefMode,- BlockEmbedMode: Conf.Export.BlockEmbedMode,- FileAnnotationRefMode: Conf.Export.FileAnnotationRefMode,- TagOpenMarker: Conf.Export.TagOpenMarker,- TagCloseMarker: Conf.Export.TagCloseMarker,- BlockRefTextLeft: Conf.Export.BlockRefTextLeft,- BlockRefTextRight: Conf.Export.BlockRefTextRight,- AddTitle: Conf.Export.AddTitle,- InlineMemo: Conf.Export.InlineMemo,+ BlockRefMode: Conf.Export.Load().BlockRefMode,+ BlockEmbedMode: Conf.Export.Load().BlockEmbedMode,+ FileAnnotationRefMode: Conf.Export.Load().FileAnnotationRefMode,+ TagOpenMarker: Conf.Export.Load().TagOpenMarker,+ TagCloseMarker: Conf.Export.Load().TagCloseMarker,+ BlockRefTextLeft: Conf.Export.Load().BlockRefTextLeft,+ BlockRefTextRight: Conf.Export.Load().BlockRefTextRight,+ AddTitle: Conf.Export.Load().AddTitle,+ InlineMemo: Conf.Export.Load().InlineMemo,},WYSIWYG: true,RichTableCells: true,@@ -112,12 +117,12 @@ func TestAssetDownloadFootnoteExport(t *testing.T) {t.Cleanup(func() { util.AppearancePath = appearancePath })util.AppearancePath = t.TempDir()writeAppearanceTestEmojiFont(t)- for _, theme := range []string{Conf.Appearance.ThemeLight, Conf.Appearance.ThemeDark} {+ for _, theme := range []string{Conf.Appearance.Load().ThemeLight, Conf.Appearance.Load().ThemeDark} {if err := os.MkdirAll(filepath.Join(util.AppearancePath, "themes", theme), 0755); err != nil {t.Fatal(err)}}- if err := os.MkdirAll(filepath.Join(util.AppearancePath, "icons", Conf.Appearance.Icon), 0755); err != nil {+ if err := os.MkdirAll(filepath.Join(util.AppearancePath, "icons", Conf.Appearance.Load().Icon), 0755); err != nil {t.Fatal(err)}_, _, exportErr := exportMarkdownHTML(source.ID, exportDir, false, false)diff --git a/kernel/model/asset_download_source_test.go b/kernel/model/asset_download_source_test.goindex 8e6c7a4322..7a080bced6 100644--- a/kernel/model/asset_download_source_test.go+++ b/kernel/model/asset_download_source_test.go@@ -44,7 +44,7 @@ func TestAssetRepositoryCreationWaitsForSourceChange(t *testing.T) {if _, err := os.Stat(assetDownloadStatePath()); !os.IsNotExist(err) {t.Fatalf("old source state was recreated: %v", err)}- Conf.Repo.Key = []byte("abcdef0123456789abcdef0123456789")+ Conf.Repo.Load().Key = []byte("abcdef0123456789abcdef0123456789")assetDownloadSourceMu.Unlock()locked = falseselect {@@ -55,7 +55,7 @@ func TestAssetRepositoryCreationWaitsForSourceChange(t *testing.T) {case <-time.After(10 * time.Second):t.Fatal("repository creation did not resume")}- if _, err := dejavu.ReadAssetDownloadScope(assetDownloadStatePath(), Conf.Repo.Key); err != nil {+ if _, err := dejavu.ReadAssetDownloadScope(assetDownloadStatePath(), Conf.Repo.Load().Key); err != nil {t.Fatalf("new source state does not authenticate: %v", err)}}@@ -73,7 +73,7 @@ func TestAssetDownloadIndexIgnoreRequiresAccess(t *testing.T) {if err = os.WriteFile(ignorePath, []byte("/assets/file.bin"), 0644); err != nil {t.Fatal(err)}- Conf.Sync.Enabled = false+ Conf.Sync.Load().Enabled = falseif _, err = IndexRepo("offline ignore change"); err == nil {t.Fatal("local snapshot downloaded an ignored resource without access")}diff --git a/kernel/model/asset_download_test.go b/kernel/model/asset_download_test.goindex c34d49543b..233ce1646b 100644--- a/kernel/model/asset_download_test.go+++ b/kernel/model/asset_download_test.go@@ -19,9 +19,9 @@ func prepareAssetDownloadRepoTest(t *testing.T) (*dejavu.Repo, *dejavu.Repo, stroriginalConf := ConforiginalWorkspace, originalData, originalRepo := util.WorkspaceDir, util.DataDir, util.RepoDiroriginalHistory, originalTemp, originalConfDir := util.HistoryDir, util.TempDir, util.ConfDir- originalStatusBar := util.StatusBarCfg+ originalStatusBar := util.StatusBarCfg.Load()t.Cleanup(func() {- util.StatusBarCfg = originalStatusBar+ util.StatusBarCfg.Store(originalStatusBar)Conf = originalConfutil.WorkspaceDir, util.DataDir, util.RepoDir = originalWorkspace, originalData, originalRepoutil.HistoryDir, util.TempDir, util.ConfDir = originalHistory, originalTemp, originalConfDir@@ -47,13 +47,19 @@ func prepareAssetDownloadRepoTest(t *testing.T) (*dejavu.Repo, *dejavu.Repo, str}}Conf = NewAppConf()- util.StatusBarCfg = &util.StatusBar{MsgDataSyncDisabled: true}- Conf.Sync, Conf.Repo, Conf.System, Conf.Search = conf.NewSync(), conf.NewRepo(), conf.NewSystem(), conf.NewSearch()- Conf.Sync.Local = &conf.Local{Endpoint: remote}+ util.StatusBarCfg.Store(&util.StatusBar{MsgDataSyncDisabled: true})+ {+ confSectionValue0, confSectionValue1, confSectionValue2, confSectionValue3 := conf.NewSync(), conf.NewRepo(), conf.NewSystem(), conf.NewSearch()+ Conf.Sync.Store(confSectionValue0)+ Conf.Repo.Store(confSectionValue1)+ Conf.System.Store(confSectionValue2)+ Conf.Search.Store(confSectionValue3)+ }+ Conf.Sync.Load().Local = &conf.Local{Endpoint: remote}Conf.SetUser(&conf.User{UserId: "asset-test", UserSiYuanOneTimePayStatus: 1})- Conf.Sync.Provider, Conf.Sync.CloudName, Conf.Sync.Enabled = conf.ProviderLocal, "main", true- Conf.Sync.Local.Endpoint, Conf.Sync.AssetDownloadMode = remote, 1- Conf.Repo.Key = key+ Conf.Sync.Load().Provider, Conf.Sync.Load().CloudName, Conf.Sync.Load().Enabled = conf.ProviderLocal, "main", true+ Conf.Sync.Load().Local.Endpoint, Conf.Sync.Load().AssetDownloadMode = remote, 1+ Conf.Repo.Load().Key = keyutil.WorkspaceDir = filepath.Join(base, "partial")util.DataDir, util.RepoDir = filepath.Join(util.WorkspaceDir, "data"), filepath.Join(util.WorkspaceDir, "repo")util.HistoryDir, util.TempDir = filepath.Join(util.WorkspaceDir, "history"), filepath.Join(util.WorkspaceDir, "temp")@@ -100,7 +106,7 @@ func TestAssetDownloadModePreservesHistoricalRecovery(t *testing.T) {if err = requireCompleteAssetDownloads(); err == nil {t.Fatal("source change allowed with missing current content")}- if err = ClearSyncProviderConfig(conf.ProviderLocal); err == nil || !Conf.Sync.Enabled || Conf.Sync.Local.Endpoint == "" {+ if err = ClearSyncProviderConfig(conf.ProviderLocal); err == nil || !Conf.Sync.Load().Enabled || Conf.Sync.Load().Local.Endpoint == "" {t.Fatal("clear discarded the source of missing current assets")}assetPath := filepath.Join(fullData, "assets", "file.bin")@@ -130,21 +136,21 @@ func TestAssetDownloadModePreservesHistoricalRecovery(t *testing.T) {if err = requireCompleteAssetDownloads(); err == nil {t.Fatal("source change allowed with missing historical content")}- if err = ClearSyncProviderConfig(conf.ProviderLocal); err == nil || !Conf.Sync.Enabled || Conf.Sync.Local.Endpoint == "" {+ if err = ClearSyncProviderConfig(conf.ProviderLocal); err == nil || !Conf.Sync.Load().Enabled || Conf.Sync.Load().Local.Endpoint == "" {t.Fatal("clear discarded the source of missing historical assets")}- Conf.Sync.Enabled = false- if err = SetSyncAssetDownloadMode(0); err == nil || Conf.Sync.AssetDownloadMode != 1 {+ Conf.Sync.Load().Enabled = false+ if err = SetSyncAssetDownloadMode(0); err == nil || Conf.Sync.Load().AssetDownloadMode != 1 {t.Fatalf("offline mode switch discarded the previous mode: %v", err)}if err = EnsureAssetLocal(localAsset); err != nil {t.Fatalf("cached resource unavailable offline: %v", err)}- Conf.Sync.Enabled = true+ Conf.Sync.Load().Enabled = trueif err = SetSyncAssetDownloadMode(0); err != nil {t.Fatal(err)}- if Conf.Sync.AssetDownloadMode != 0 || repoFileNeedsDownload(oldFile) {+ if Conf.Sync.Load().AssetDownloadMode != 0 || repoFileNeedsDownload(oldFile) {t.Fatal("full mode did not complete historical assets")}if err = requireCompleteAssetDownloads(); err != nil {@@ -160,13 +166,13 @@ func TestAssetDownloadModePreservesHistoricalRecovery(t *testing.T) {if err = ClearSyncProviderConfig(conf.ProviderLocal); err != nil {t.Fatal(err)}- if Conf.Sync.Enabled || Conf.Sync.Local.Endpoint != "" {+ if Conf.Sync.Load().Enabled || Conf.Sync.Load().Local.Endpoint != "" {t.Fatal("complete source was not cleared and disabled")}if exists, err := assetDownloadStateExists(); err != nil || exists {t.Fatalf("authenticated complete state was not cleared: %v", err)}- Conf.Repo.Key = nil+ Conf.Repo.Load().Key = nilif err = requireCompleteAssetDownloads(); err != nil {t.Fatalf("reset state prevents initializing another key: %v", err)}@@ -183,18 +189,18 @@ func TestAssetDownloadStateCorruptionPreservesSource(t *testing.T) {if err = os.WriteFile(statePath, data, 0600); err != nil {t.Fatal(err)}- key := append([]byte(nil), Conf.Repo.Key...)+ key := append([]byte(nil), Conf.Repo.Load().Key...)if err = requireCompleteAssetDownloads(); err == nil {t.Fatal("corrupt state accepted for a source change")}- if err = SetSyncAssetDownloadMode(0); err == nil || Conf.Sync.AssetDownloadMode != 1 {+ if err = SetSyncAssetDownloadMode(0); err == nil || Conf.Sync.Load().AssetDownloadMode != 1 {t.Fatal("corrupt state was discarded during a mode change")}if err = clearAssetDownloadState(); err == nil {t.Fatal("corrupt state was discarded before changing the key")}remaining, err := os.ReadFile(statePath)- if err != nil || !bytes.Equal(data, remaining) || !bytes.Equal(key, Conf.Repo.Key) {+ if err != nil || !bytes.Equal(data, remaining) || !bytes.Equal(key, Conf.Repo.Load().Key) {t.Fatal("failure changed source state or recovery key")}}@@ -212,7 +218,7 @@ func TestAssetDownloadUsesLocalSnapshotChunksWhileLoggedOut(t *testing.T) {if _, err = os.Stat(assetPath); !os.IsNotExist(err) {t.Fatal("snapshot chunk download unexpectedly materialized workspace content")}- Conf.Sync.Enabled = false+ Conf.Sync.Load().Enabled = falseConf.SetUser(nil)if err = EnsureAssetLocal(assetPath); err != nil {t.Fatalf("offline local chunks were not reused: %v", err)diff --git a/kernel/model/asset_reference.go b/kernel/model/asset_reference.goindex 4a54e94c9d..7769936945 100644--- a/kernel/model/asset_reference.go+++ b/kernel/model/asset_reference.go@@ -315,7 +315,7 @@ func rewriteAttributeViewDataAssetReferences(data []byte, options assetReferenceif !rewriteAttributeViewAssetReferences(attrView, options) {return data, nil}- if util.UseSingleLineSave {+ if util.UseSingleLineSave.Load() {return gulu.JSON.MarshalJSON(attrView)}return gulu.JSON.MarshalIndentJSON(attrView, "", "\t")diff --git a/kernel/model/assets.go b/kernel/model/assets.goindex f8878f0993..667a11bfd0 100644--- a/kernel/model/assets.go+++ b/kernel/model/assets.go@@ -516,10 +516,10 @@ func PrepareAgentMessageImage(assetPath string) (PreparedDocumentImage, error) {// GenerateImage 使用全局图片生成配置创建图片字节,可供文档资源、编辑器和其他图片入口复用。func GenerateImage(ctx context.Context, request GenerateImageRequest) (GenerateImageResult, error) {- if Conf == nil || Conf.AI == nil {+ if Conf == nil || Conf.AI.Load() == nil {return GenerateImageResult{}, errors.New("AI configuration is unavailable")}- provider, generationModel := Conf.AI.GetImageGenerationModel()+ provider, generationModel := Conf.AI.Load().GetImageGenerationModel()if err := validateImageModel(provider, generationModel); err != nil {return GenerateImageResult{}, err}@@ -527,14 +527,14 @@ func GenerateImage(ctx context.Context, request GenerateImageRequest) (GenerateIif prompt == "" {return GenerateImageResult{}, errors.New("prompt is required for image generation")}- size := multimodalValueOrDefault(request.Size, Conf.AI.ImageGeneration.Size)- quality := multimodalValueOrDefault(request.Quality, Conf.AI.ImageGeneration.Quality)- outputFormat := strings.ToLower(multimodalValueOrDefault(request.OutputFormat, Conf.AI.ImageGeneration.OutputFormat))+ size := multimodalValueOrDefault(request.Size, Conf.AI.Load().ImageGeneration.Size)+ quality := multimodalValueOrDefault(request.Quality, Conf.AI.Load().ImageGeneration.Quality)+ outputFormat := strings.ToLower(multimodalValueOrDefault(request.OutputFormat, Conf.AI.Load().ImageGeneration.OutputFormat))if outputFormat != "png" && outputFormat != "jpeg" && outputFormat != "webp" {return GenerateImageResult{}, errors.New("unsupported image output format")}generated, err := util.NewOpenAIImageAdapter(- provider.APIKey, provider.BaseURL, generationModel.Name, Conf.AI.ImageGeneration.RequestTimeout, ResolveAIProviderHeaders(provider),+ provider.APIKey, provider.BaseURL, generationModel.Name, Conf.AI.Load().ImageGeneration.RequestTimeout, ResolveAIProviderHeaders(provider),).Generate(ctx, util.GenerateImageRequest{Prompt: prompt, Size: size, Quality: quality, OutputFormat: outputFormat,})@@ -915,14 +915,16 @@ type AssetSearchMatch struct {}func SearchAssetsByName(keyword string, exts []string) (ret []*cache.Asset) {- ret, _ = SearchAssetsByNamePage(keyword, exts, nil, 1, Conf.Search.Limit, false)+ ret, _ = SearchAssetsByNamePage(keyword, exts, nil, 1, Conf.Search.Load().Limit, false)return}// SearchAssetsByNamePage 筛选资源,可合并图片元数据命中,并按稳定顺序返回指定页。func SearchAssetsByNamePage(keyword string, exts []string, match *AssetSearchMatch, page, pageSize int, includeMetadata bool) (ret []*cache.Asset, err error) {+ confSearchSnapshot := Conf.LoadSearch()+ret = []*cache.Asset{}- if page < 1 || pageSize < 1 || pageSize > Conf.Search.Limit {+ if page < 1 || pageSize < 1 || pageSize > confSearchSnapshot.Limit {return nil, errors.New("invalid asset search page")}allowedExts := map[string]bool{}@@ -1092,7 +1094,7 @@ func SearchAssetsByNamePage(keyword string, exts []string, match *AssetSearchMathighlightKeyword := strings.Join(keywords, search.TermSep)for _, asset := range ret {if pathHitCount[asset.Path] > 0 {- _, asset.HName = search.MarkText(asset.HName, highlightKeyword, 64, Conf.Search.CaseSensitive)+ _, asset.HName = search.MarkText(asset.HName, highlightKeyword, 64, confSearchSnapshot.CaseSensitive)}}return@@ -2586,7 +2588,7 @@ func getQueryEmbedNodesAssetsLinkDests(node *ast.Node) (ret []string) {stmt := n.TokensStr()stmt = html.UnescapeString(stmt)stmt = strings.ReplaceAll(stmt, editor.IALValEscNewLine, "\n")- sqlBlocks := sql.SelectBlocksRawStmt(stmt, 1, Conf.Search.Limit)+ sqlBlocks := sql.SelectBlocksRawStmt(stmt, 1, Conf.Search.Load().Limit)for _, sqlBlock := range sqlBlocks {subtree, _ := LoadTreeByBlockID(sqlBlock.ID)if nil == subtree {diff --git a/kernel/model/assets_cleanup_test.go b/kernel/model/assets_cleanup_test.goindex 0299c1b299..876e33e899 100644--- a/kernel/model/assets_cleanup_test.go+++ b/kernel/model/assets_cleanup_test.go@@ -99,8 +99,8 @@ func setupUnusedAssetWorkspace(t *testing.T) (boxID, docPath string) {t.Helper()originalConf, originalData, originalWorkspace := Conf, util.DataDir, util.WorkspaceDirConf = NewAppConf()- Conf.FileTree = conf.NewFileTree()- Conf.Sync = conf.NewSync()+ Conf.FileTree.Store(conf.NewFileTree())+ Conf.Sync.Store(conf.NewSync())util.WorkspaceDir = t.TempDir()util.DataDir = filepath.Join(util.WorkspaceDir, "data")t.Cleanup(func() { Conf, util.DataDir, util.WorkspaceDir = originalConf, originalData, originalWorkspace })@@ -180,7 +180,7 @@ func TestUnusedAssetsTemplatePaths(t *testing.T) {for _, mode := range []string{"uppercase extension", "symlink root"} {t.Run(mode, func(t *testing.T) {setupUnusedAssetWorkspace(t)- Conf.Search = conf.NewSearch()+ Conf.Search.Store(conf.NewSearch())templateDir := filepath.Join(util.DataDir, "templates")name := "example.MD"if mode == "symlink root" {diff --git a/kernel/model/assets_test.go b/kernel/model/assets_test.goindex b91d1c8a70..d4d6f7ca69 100644--- a/kernel/model/assets_test.go+++ b/kernel/model/assets_test.go@@ -105,7 +105,7 @@ func TestGenerateImageDoesNotRequireDocument(t *testing.T) {}}ai.ImageGeneration.ModelID = modelIDConf = NewAppConf()- Conf.AI = ai+ Conf.AI.Store(ai)result, err := GenerateImage(context.Background(), GenerateImageRequest{Prompt: "draw", OutputFormat: "png"})if err != nil {@@ -132,7 +132,7 @@ func TestImageGenerationProviderErrorsPreventAutomaticRetry(t *testing.T) {}}ai.ImageGeneration.ModelID = generationModelIDConf = NewAppConf()- Conf.AI = ai+ Conf.AI.Store(ai)if _, err := GenerateImage(context.Background(), GenerateImageRequest{Prompt: "draw", OutputFormat: "png"}); !IsImageExecutionUnknown(err) {t.Fatalf("image provider error should prevent automatic retry: %v", err)@@ -253,7 +253,7 @@ func TestUnusedAssetsExcludesAgentSessionImages(t *testing.T) {util.WorkspaceDir = workspaceDirutil.DataDir = filepath.Join(workspaceDir, "data")Conf = NewAppConf()- Conf.FileTree = conf.NewFileTree()+ Conf.FileTree.Store(conf.NewFileTree())assetsDir := filepath.Join(util.DataDir, "assets")if err := os.MkdirAll(assetsDir, 0755); err != nil {t.Fatal(err)@@ -660,7 +660,7 @@ func TestAllAssetAbsPathsWithAssetsInWorkspacePath(t *testing.T) {util.DataDir = filepath.Join(t.TempDir(), "assets", "workspace", "data")Conf = NewAppConf()- Conf.FileTree = conf.NewFileTree()+ Conf.FileTree.Store(conf.NewFileTree())globalAssetPath := filepath.Join(util.DataDir, "assets", "nested", "assets", "image.png")if err := os.MkdirAll(filepath.Dir(globalAssetPath), 0755); err != nil {t.Fatal(err)diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.goindex 890b3f8a77..3cf34b0440 100644--- a/kernel/model/attribute_view.go+++ b/kernel/model/attribute_view.go@@ -2888,7 +2888,7 @@ func relationCandidateMatches(row *av.TableRow, keyword string) bool {content := cell.Value.String(true)allKeywordsHit := truefor _, currentKeyword := range keywords {- if util.SearchCaseSensitive {+ if util.SearchCaseSensitive.Load() {if !strings.Contains(content, currentKeyword) {allKeywordsHit = falsebreakdiff --git a/kernel/model/attribute_view_location_export_test.go b/kernel/model/attribute_view_location_export_test.goindex cfc3c74865..9c435ecd70 100644--- a/kernel/model/attribute_view_location_export_test.go+++ b/kernel/model/attribute_view_location_export_test.go@@ -20,8 +20,8 @@ import (func TestAttributeViewLocationCSVAndMarkdownExport(t *testing.T) {const boxID, avID, docID, blockID, rowID = "20261009010000-box0001", "20261009010001-av00001", "20261009010002-doc0001", "20261009010003-avnode1", "20261009010004-row0001"setupExportRelatedTest(t, boxID)- Conf.Editor = conf.NewEditor()- Conf.Search = conf.NewSearch()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Search.Store(conf.NewSearch())oldLang, oldLangs := util.Lang, util.AttrViewLangsutil.Lang = "en"util.AttrViewLangs = map[string]map[string]any{"en": {"key": "Key", "select": "Select", "table": "Table"}}@@ -86,7 +86,7 @@ func TestAttributeViewLocationCSVAndMarkdownExport(t *testing.T) {if !found {t.Fatal("CSV file missing from export")}- exported, err := exportTree(tree, treeExportOptions{Config: *Conf.Export, WYSIWYG: false})+ exported, err := exportTree(tree, treeExportOptions{Config: *Conf.Export.Load(), WYSIWYG: false})if err != nil {t.Fatal(err)}diff --git a/kernel/model/attribute_view_new_item_test.go b/kernel/model/attribute_view_new_item_test.goindex cf26f1785a..99f3de7d84 100644--- a/kernel/model/attribute_view_new_item_test.go+++ b/kernel/model/attribute_view_new_item_test.go@@ -210,9 +210,9 @@ func TestResolveDocCreateSaveLocation(t *testing.T) {originalConf, originalDataDir := Conf, util.DataDirutil.DataDir = t.TempDir()Conf = NewAppConf()- Conf.FileTree = conf.NewFileTree()+ Conf.FileTree.Store(conf.NewFileTree())Conf.NotebookCrypto = conf.NewNotebookCrypto()- Conf.Sync = conf.NewSync()+ Conf.Sync.Store(conf.NewSync())t.Cleanup(func() {Conf = originalConfutil.DataDir = originalDataDir@@ -232,8 +232,8 @@ func TestResolveDocCreateSaveLocation(t *testing.T) {t.Fatalf("save notebook config failed: %s", err)}}- Conf.FileTree.DocCreateSaveBox = globalBoxID- Conf.FileTree.DocCreateSavePath = "/Global/{{now | date \"200601\"}}"+ Conf.FileTree.Load().DocCreateSaveBox = globalBoxID+ Conf.FileTree.Load().DocCreateSavePath = "/Global/{{now | date \"200601\"}}"assertLocation := func(expectedBoxID, expectedPath string) {t.Helper()@@ -242,7 +242,7 @@ func TestResolveDocCreateSaveLocation(t *testing.T) {t.Fatalf("unexpected save location: box=%q path=%q", boxID, pathTemplate)}}- assertLocation(globalBoxID, Conf.FileTree.DocCreateSavePath)+ assertLocation(globalBoxID, Conf.FileTree.Load().DocCreateSavePath)currentBoxConf.DocCreateSavePath = "Local/{{now | date \"200601\"}}"if err := (&Box{ID: currentBoxID}).SaveConf(currentBoxConf); nil != err {@@ -255,7 +255,7 @@ func TestResolveDocCreateSaveLocation(t *testing.T) {if err := (&Box{ID: currentBoxID}).SaveConf(currentBoxConf); nil != err {t.Fatal(err)}- assertLocation(localBoxID, Conf.FileTree.DocCreateSavePath)+ assertLocation(localBoxID, Conf.FileTree.Load().DocCreateSavePath)currentBoxConf.DocCreateSavePath = "/Local"if err := (&Box{ID: currentBoxID}).SaveConf(currentBoxConf); nil != err {diff --git a/kernel/model/attribute_view_ref_dynamic_test.go b/kernel/model/attribute_view_ref_dynamic_test.goindex a556814bae..d1c199a9b8 100644--- a/kernel/model/attribute_view_ref_dynamic_test.go+++ b/kernel/model/attribute_view_ref_dynamic_test.go@@ -28,7 +28,7 @@ import (func TestUpdateAttributeViewDynamicRefTextsKeepsStaticAnchors(t *testing.T) {originalConf := Conf- Conf = &AppConf{Editor: conf.NewEditor()}+ Conf = &AppConf{Editor: NewConfSection(conf.NewEditor())}t.Cleanup(func() { Conf = originalConf })const defID = "20260904040000-def0001"diff --git a/kernel/model/attribute_view_validation_test.go b/kernel/model/attribute_view_validation_test.goindex 7054dc8cc4..9687123e74 100644--- a/kernel/model/attribute_view_validation_test.go+++ b/kernel/model/attribute_view_validation_test.go@@ -49,8 +49,8 @@ func setupAttributeViewValidationTest(t *testing.T) {}Conf = NewAppConf()Conf.Lang = "en"- Conf.FileTree = conf.NewFileTree()- Conf.Sync = conf.NewSync()+ Conf.FileTree.Store(conf.NewFileTree())+ Conf.Sync.Store(conf.NewSync())cache.ClearAVCache()t.Cleanup(func() {cache.ClearAVCache()diff --git a/kernel/model/auth.go b/kernel/model/auth.goindex e6a0443244..02d7bede97 100644--- a/kernel/model/auth.go+++ b/kernel/model/auth.go@@ -244,18 +244,18 @@ func countPublishSessionsByUsername(username string) int {}func InitPublishAccounts() {- if nil == Conf.Publish {- Conf.Publish = conf.NewPublish()+ if nil == Conf.Publish.Load() {+ Conf.Publish.Store(conf.NewPublish())}- if nil == Conf.Publish.Auth {+ if nil == Conf.Publish.Load().Auth {// 防御 conf.json 中 auth 为 null 的历史坏配置,避免启动时解引用空指针崩溃// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-rp9f-c2fj-h648- Conf.Publish.Auth = conf.NewPublish().Auth+ UpdatePublishConf(func(s *conf.Publish) { s.Auth = conf.NewPublish().Auth })}accounts := AccountsMap{"": &Account{}, // 匿名用户}- for _, account := range Conf.Publish.Auth.Accounts {+ for _, account := range Conf.Publish.Load().Auth.Accounts {accounts[account.Username] = &Account{Username: account.Username,Password: account.Password,diff --git a/kernel/model/auth_test.go b/kernel/model/auth_test.goindex 2fe02da59b..3a5a3bb80f 100644--- a/kernel/model/auth_test.go+++ b/kernel/model/auth_test.go@@ -176,8 +176,8 @@ func TestPublishSessionInvalidatedAfterPasswordChange(t *testing.T) {resetPublishSessions(t)Conf = NewAppConf()- Conf.Publish = conf.NewPublish()- Conf.Publish.Auth.Accounts = []*conf.BasicAuthAccount{+ Conf.Publish.Store(conf.NewPublish())+ Conf.Publish.Load().Auth.Accounts = []*conf.BasicAuthAccount{{Username: "alice", Password: "old-password"},{Username: "bob", Password: "bob-password"},}@@ -188,7 +188,7 @@ func TestPublishSessionInvalidatedAfterPasswordChange(t *testing.T) {aliceSessionID := AddSession(alice.Username, alice.CredentialVersion)bobSessionID := AddSession(bob.Username, bob.CredentialVersion)- Conf.Publish.Auth.Accounts[0].Password = "new-password"+ Conf.Publish.Load().Auth.Accounts[0].Password = "new-password"InitPublishAccounts()if sessionID := AddSession(alice.Username, alice.CredentialVersion); "" != sessionID {@@ -208,8 +208,8 @@ func TestPublishSessionPreservedWhenCredentialsUnchanged(t *testing.T) {resetPublishSessions(t)Conf = NewAppConf()- Conf.Publish = conf.NewPublish()- Conf.Publish.Auth.Accounts = []*conf.BasicAuthAccount{+ Conf.Publish.Store(conf.NewPublish())+ Conf.Publish.Load().Auth.Accounts = []*conf.BasicAuthAccount{{Username: "alice", Password: "same-password"},}InitPublishAccounts()@@ -282,7 +282,7 @@ func TestInitPublishAccountsWithNilAuth(t *testing.T) {preserveAuthState(t)Conf = NewAppConf()- Conf.Publish = &conf.Publish{Enable: true, Port: 6808}+ Conf.Publish.Store(&conf.Publish{Enable: true, Port: 6808})defer func() {if e := recover(); nil != e {@@ -291,7 +291,7 @@ func TestInitPublishAccountsWithNilAuth(t *testing.T) {}()InitPublishAccounts()- if nil == Conf.Publish.Auth {+ if nil == Conf.Publish.Load().Auth {t.Fatal("InitPublishAccounts should default Publish.Auth when it is nil")}}diff --git a/kernel/model/backlink.go b/kernel/model/backlink.goindex b4099644be..e6c3429e0d 100644--- a/kernel/model/backlink.go+++ b/kernel/model/backlink.go@@ -1019,28 +1019,30 @@ func buildTreeBackmention(defSQLBlock *sql.Block, refBlocks []*Block, keyword st// buildTreeBackmentionInBox 与 buildTreeBackmention 一致,但按 boxID 路由到加密 db 或全局 db。func buildTreeBackmentionInBox(defSQLBlock *sql.Block, refBlocks []*Block, keyword string, excludeBacklinkIDs *hashset.Set, beforeLen int, boxID string, notifiers ...BackmentionNotifier) (ret []*Block, mentionKeywords []string) {+ confSearchSnapshot := Conf.LoadSearch()+ret = []*Block{}var names, aliases []stringvar fName, rootID stringif "d" == defSQLBlock.Type {- if Conf.Search.BacklinkMentionName {+ if confSearchSnapshot.BacklinkMentionName {names = sql.QueryBlockNamesByRootIDInBox(defSQLBlock.ID, boxID)}- if Conf.Search.BacklinkMentionAlias {+ if confSearchSnapshot.BacklinkMentionAlias {aliases = sql.QueryBlockAliasesInBox(defSQLBlock.ID, boxID)}- if Conf.Search.BacklinkMentionDoc {+ if confSearchSnapshot.BacklinkMentionDoc {fName = path.Base(defSQLBlock.HPath)}rootID = defSQLBlock.ID} else {- if Conf.Search.BacklinkMentionName {+ if confSearchSnapshot.BacklinkMentionName {if "" != defSQLBlock.Name {names = append(names, defSQLBlock.Name)}}- if Conf.Search.BacklinkMentionAlias {+ if confSearchSnapshot.BacklinkMentionAlias {if "" != defSQLBlock.Alias {aliases = strings.Split(defSQLBlock.Alias, ",")}@@ -1063,7 +1065,7 @@ func buildTreeBackmentionInBox(defSQLBlock *sql.Block, refBlocks []*Block, keywoset.Add(fName)}- if Conf.Search.BacklinkMentionAnchor {+ if confSearchSnapshot.BacklinkMentionAnchor {for _, refBlock := range refBlocks {refs := sql.QueryRefsByDefIDRefIDInBox(refBlock.DefID, refBlock.ID, boxID)for _, ref := range refs {@@ -1075,7 +1077,7 @@ func buildTreeBackmentionInBox(defSQLBlock *sql.Block, refBlocks []*Block, keywofor _, v := range set.Values() {mentionKeywords = append(mentionKeywords, v.(string))}- mentionKeywords = excludeKeywords(mentionKeywords, Conf.Editor.BacklinkMentionExclude)+ mentionKeywords = excludeKeywords(mentionKeywords, Conf.Editor.Load().BacklinkMentionExclude)mentionKeywords = prepareMarkKeywords(mentionKeywords)mentionKeywords, ret = searchBackmentionInBox(mentionKeywords, keyword, excludeBacklinkIDs, rootID, beforeLen, boxID, notifiers...)return@@ -1104,6 +1106,8 @@ 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, notifiers ...BackmentionNotifier) (retMentionKeywords []string, ret []*Block) {+ confSearchSnapshot := Conf.LoadSearch()+ret = []*Block{}if 1 > len(mentionKeywords) {return@@ -1112,7 +1116,7 @@ func searchBackmentionInBox(mentionKeywords []string, keyword string, excludeBacbuf := bytes.Buffer{}buf.WriteString(columnFilter() + ":(")for i, mentionKeyword := range mentionKeywords {- if Conf.Search.BacklinkMentionKeywordsLimit < i {+ if confSearchSnapshot.BacklinkMentionKeywordsLimit < i {if notify := backmentionNotifier(notifiers); notify != nil {notify(fmt.Sprintf(Conf.Language(38), len(mentionKeywords)), 5000)}@@ -1134,7 +1138,7 @@ func searchBackmentionInBox(mentionKeywords []string, keyword string, excludeBacterms = append(terms, keyword)}luteEngine := util.NewLute()- limit := Conf.Search.Limit+ limit := confSearchSnapshot.LimitbeforeID := ""// 按块 ID 分批补取候选,正文校验和反链排除后的有效提及才占用结果额度。for len(ret) < limit {@@ -1233,7 +1237,7 @@ func buildFullLinks(condition string) (forwardlinks, backlinks []*Block) {func buildDefsAndRefs(condition string) (defBlocks []*Block) {defBlockMap := map[string]*Block{}refBlockMap := map[string]*Block{}- defRefs := sql.DefRefs(condition, Conf.Graph.MaxBlocks)+ defRefs := sql.DefRefs(condition, Conf.Graph.Load().MaxBlocks)// 将 sql block 转为 blockfor _, row := range defRefs {diff --git a/kernel/model/backlink_global_fts5_test.go b/kernel/model/backlink_global_fts5_test.goindex 515305732a..0329057b6d 100644--- a/kernel/model/backlink_global_fts5_test.go+++ b/kernel/model/backlink_global_fts5_test.go@@ -18,7 +18,7 @@ import (func TestGlobalBacklinkPagination(t *testing.T) {fixture := setupStructureTransactionTest(t)setupFoldTransactionDatabase(t, fixture)- Conf.Search = conf.NewSearch()+ Conf.Search.Store(conf.NewSearch())t.Cleanup(func() { ClearGlobalBacklinkSnapshots("") })ids := map[int]string{}for index, rootID := range []string{fixture.sourceID, fixture.targetID} {@@ -122,7 +122,7 @@ func TestGlobalBacklinkPagination(t *testing.T) {func TestGlobalBacklinkTransitiveContextsAndContentSort(t *testing.T) {fixture := setupStructureTransactionTest(t)setupFoldTransactionDatabase(t, fixture)- Conf.Search = conf.NewSearch()+ Conf.Search.Store(conf.NewSearch())t.Cleanup(func() { ClearGlobalBacklinkSnapshots("") })definition, err := LoadTreeByBlockID(fixture.sourceID)if err != nil {@@ -246,7 +246,7 @@ func TestGlobalBacklinkSnapshotBounds(t *testing.T) {func TestGlobalBacklinkLargeDataset(t *testing.T) {fixture := setupStructureTransactionTest(t)setupFoldTransactionDatabase(t, fixture)- Conf.Search = conf.NewSearch()+ Conf.Search.Store(conf.NewSearch())t.Cleanup(func() { ClearGlobalBacklinkSnapshots("") })const documents, perDocument = 100, 100definition, err := LoadTreeByBlockID(fixture.sourceID)diff --git a/kernel/model/backlink_mention_fts5_test.go b/kernel/model/backlink_mention_fts5_test.goindex 19dc8f5b22..c484793cd9 100644--- a/kernel/model/backlink_mention_fts5_test.go+++ b/kernel/model/backlink_mention_fts5_test.go@@ -29,7 +29,7 @@ func TestBacklinkMentionFilteredPagination(t *testing.T) {t.Run(name, func(t *testing.T) {fixture := setupStructureTransactionTest(t)setupFoldTransactionDatabase(t, fixture)- Conf.Search = conf.NewSearch()+ Conf.Search.Store(conf.NewSearch())var trees []*parse.Treefor _, id := range []string{fixture.sourceID, fixture.targetID} {tree, err := LoadTreeByBlockID(id)@@ -139,7 +139,7 @@ func TestBacklinkMentionFilteredPagination(t *testing.T) {}excluded := hashset.New(ids[4], ids[5], ids[7])for _, limit := range []int{1, 2, 3, 4, 5, 64} {- Conf.Search.Limit = limit+ Conf.Search.Load().Limit = limitwant := []string{ids[3], ids[2], ids[1], ids[0]}if limit < len(want) {want = want[:limit]@@ -165,7 +165,7 @@ func TestBacklinkMentionFilteredPagination(t *testing.T) {}}}- Conf.Search.Limit = 2+ Conf.Search.Load().Limit = 2_, blocks := searchBackmentionInBox([]string{"needle", "broad"}, "", hashset.New(ids[0], ids[1], ids[2], ids[3], ids[4], ids[5], ids[7]), fixture.sourceID, 12, boxID)if len(blocks) != 0 {t.Fatal("fully filtered candidates returned mentions")diff --git a/kernel/model/backlink_notification_fts5_test.go b/kernel/model/backlink_notification_fts5_test.goindex a6634b6f9c..fdef9d90a3 100644--- a/kernel/model/backlink_notification_fts5_test.go+++ b/kernel/model/backlink_notification_fts5_test.go@@ -27,10 +27,10 @@ func TestBackmentionNotificationPlainAndEncrypted(t *testing.T) {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+ Conf.Search.Store(conf.NewSearch())+ Conf.Search.Load().BacklinkMentionDoc = true+ Conf.Search.Load().BacklinkMentionName = true+ Conf.Search.Load().BacklinkMentionKeywordsLimit = 0var trees []*parse.Treefor _, id := range []string{fixture.sourceID, fixture.targetID} {tree, err := LoadTreeByBlockID(id)diff --git a/kernel/model/backlink_notification_test.go b/kernel/model/backlink_notification_test.goindex 72773324eb..812d767c21 100644--- a/kernel/model/backlink_notification_test.go+++ b/kernel/model/backlink_notification_test.go@@ -21,9 +21,9 @@ func TestBackmentionNotifierLegacyAndSuppressed(t *testing.T) {func TestBackmentionKeywordWarningNotifier(t *testing.T) {previous := ConfConf = NewAppConf()- Conf.Search = conf.NewSearch()- Conf.Search.BacklinkMentionKeywordsLimit = 0- Conf.Search.Limit = 0+ Conf.Search.Store(conf.NewSearch())+ Conf.Search.Load().BacklinkMentionKeywordsLimit = 0+ Conf.Search.Load().Limit = 0t.Cleanup(func() { Conf = previous })calls := 0notify := func(msg string, timeout int) string {diff --git a/kernel/model/backlink_options_fts5_test.go b/kernel/model/backlink_options_fts5_test.goindex f9816143a3..9a80de862e 100644--- a/kernel/model/backlink_options_fts5_test.go+++ b/kernel/model/backlink_options_fts5_test.go@@ -16,8 +16,8 @@ import (func TestBacklink2OptionalMentions(t *testing.T) {fixture := setupStructureTransactionTest(t)setupFoldTransactionDatabase(t, fixture)- Conf.Search = conf.NewSearch()- Conf.Search.BacklinkMentionDoc = true+ Conf.Search.Store(conf.NewSearch())+ Conf.Search.Load().BacklinkMentionDoc = truefor _, id := range []string{fixture.sourceID, fixture.targetID} {tree, err := LoadTreeByBlockID(id)if err != nil {diff --git a/kernel/model/backlink_ref_filter_fts5_test.go b/kernel/model/backlink_ref_filter_fts5_test.goindex b124dc4040..6008d6d889 100644--- a/kernel/model/backlink_ref_filter_fts5_test.go+++ b/kernel/model/backlink_ref_filter_fts5_test.go@@ -16,8 +16,8 @@ import (func TestBacklinkRefFilterListContextAndCandidates(t *testing.T) {fixture := setupStructureTransactionTest(t)setupFoldTransactionDatabase(t, fixture)- Conf.Search = conf.NewSearch()- Conf.Search.BacklinkMentionDoc = true+ Conf.Search.Store(conf.NewSearch())+ Conf.Search.Load().BacklinkMentionDoc = trueconst archiveID = "20260909160000-archive"const sameNameID = "20260909160001-sameref"const itemID = "20260909160002-listitm"diff --git a/kernel/model/backlink_sort_fts5_test.go b/kernel/model/backlink_sort_fts5_test.goindex f3f282ac4f..36f4165e6d 100644--- a/kernel/model/backlink_sort_fts5_test.go+++ b/kernel/model/backlink_sort_fts5_test.go@@ -28,7 +28,7 @@ func TestBacklinkAnchorSortContext(t *testing.T) {t.Run(name, func(t *testing.T) {fixture := setupStructureTransactionTest(t)setupFoldTransactionDatabase(t, fixture)- Conf.Search = conf.NewSearch()+ Conf.Search.Store(conf.NewSearch())var trees []*parse.Treefor _, id := range []string{fixture.sourceID, fixture.targetID} {tree, err := LoadTreeByBlockID(id)diff --git a/kernel/model/bazaar.go b/kernel/model/bazaar.goindex 944ab46405..1f58c1f0ad 100644--- a/kernel/model/bazaar.go+++ b/kernel/model/bazaar.go@@ -30,6 +30,7 @@ import ("github.com/emirpasic/gods/sets/hashset""github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/bazaar"+ "github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/util""golang.org/x/mod/semver""golang.org/x/sync/semaphore"@@ -367,6 +368,8 @@ func installedPackageBaseURLPath(prefix, packageName string) string {}func getInstalledPackages0(pkgType, frontend, keyword string) (installedPackages []*bazaar.Package) {+ confAppearanceSnapshot := Conf.LoadAppearance()+installedPackages = []*bazaar.Package{}installedInfos, basePath, baseURLPathPrefix, err := GetInstalledPackageInfos(pkgType)@@ -413,9 +416,9 @@ func getInstalledPackages0(pkgType, frontend, keyword string) (installedPackages}case "themes":pkg.InstalledIncompatible = new(bazaar.IsIncompatibleTheme(pkg, frontend))- pkg.Current = pkg.Name == Conf.Appearance.ThemeDark || pkg.Name == Conf.Appearance.ThemeLight+ pkg.Current = pkg.Name == confAppearanceSnapshot.ThemeDark || pkg.Name == confAppearanceSnapshot.ThemeLightcase "icons":- pkg.Current = pkg.Name == Conf.Appearance.Icon+ pkg.Current = pkg.Name == confAppearanceSnapshot.Icon}}return@@ -507,6 +510,8 @@ func GetBazaarPackagesWithError(pkgType, frontend, keyword string) ([]*bazaar.Pa}func enrichBazaarPackages(bazaarPackages []*bazaar.Package, pkgType, keyword string) []*bazaar.Package {+ confAppearanceSnapshot := Conf.LoadAppearance()+bazaarPackages = bazaar.FilterPackages(bazaarPackages, keyword)installedInfos, _, _, err := GetInstalledPackageInfos(pkgType)if err != nil {@@ -528,9 +533,9 @@ func enrichBazaarPackages(bazaarPackages []*bazaar.Package, pkgType, keyword strpkg.Outdated = 0 > semver.Compare("v"+installedPkg.Version, "v"+pkg.Version)switch pkgType {case "themes":- pkg.Current = pkg.Name == Conf.Appearance.ThemeDark || pkg.Name == Conf.Appearance.ThemeLight+ pkg.Current = pkg.Name == confAppearanceSnapshot.ThemeDark || pkg.Name == confAppearanceSnapshot.ThemeLightcase "icons":- pkg.Current = pkg.Name == Conf.Appearance.Icon+ pkg.Current = pkg.Name == confAppearanceSnapshot.Icon}}return bazaarPackages@@ -552,7 +557,7 @@ func installBazaarPackage(pkgType, repoURL, repoHash, repoRef, packageName strinmeta.update = parseErr == nil && installedPkg != nil && installedPkg.Name == packageNameoptions := bazaar.PackageInstallOptions{PrivateTemp: pkgType == "plugins"}- _, err = bazaar.InstallPackageWithOptions(repoURL, repoHash, repoRef, installPath, Conf.System.ID, pkgType, packageName, meta.update, options)+ _, err = bazaar.InstallPackageWithOptions(repoURL, repoHash, repoRef, installPath, Conf.System.Load().ID, pkgType, packageName, meta.update, options)if err != nil {err = fmt.Errorf(Conf.Language(46), packageName, err)} else {@@ -595,31 +600,33 @@ func finishInstall(pkgType string, items []batchInstallItem, themeOptions *Themefor _, item := range items {if !item.meta.update && nil != themeOptions {// 新安装主题时才自动切换 https://github.com/siyuan-note/siyuan/issues/4966- applied := falsetheme, err := bazaar.ParsePackageJSON(filepath.Join(util.AppearancePackagePath("themes", item.name), "theme.json"))- if nil == err && nil != theme && nil != theme.Modes {- for _, mode := range *theme.Modes {- switch mode {- case "light":- Conf.Appearance.ThemeLight = item.name- applied = true- case "dark":- Conf.Appearance.ThemeDark = item.name- applied = true+ themeJS := gulu.File.IsExist(filepath.Join(util.AppearancePackagePath("themes", item.name), "theme.js"))+ UpdateAppearanceConf(func(appearance *conf.Appearance) {+ applied := false+ if nil == err && nil != theme && nil != theme.Modes {+ for _, mode := range *theme.Modes {+ switch mode {+ case "light":+ appearance.ThemeLight = item.name+ applied = true+ case "dark":+ appearance.ThemeDark = item.name+ applied = true+ }}}- }- if !applied {- if 0 == themeOptions.Mode {- Conf.Appearance.ThemeLight = item.name- } else {- Conf.Appearance.ThemeDark = item.name+ if !applied {+ if 0 == themeOptions.Mode {+ appearance.ThemeLight = item.name+ } else {+ appearance.ThemeDark = item.name+ }}- }- Conf.Appearance.Mode = themeOptions.Mode- Conf.Appearance.ModeOS = themeOptions.ModeOS- Conf.Appearance.ThemeJS = gulu.File.IsExist(filepath.Join(util.AppearancePackagePath("themes", item.name), "theme.js"))- Conf.Save()+ appearance.Mode = themeOptions.Mode+ appearance.ModeOS = themeOptions.ModeOS+ appearance.ThemeJS = themeJS+ })}}var names []string@@ -631,8 +638,7 @@ func finishInstall(pkgType string, items []batchInstallItem, themeOptions *Themefor _, item := range items {if !item.meta.update && applyNewAppearance {// 新安装图标时才自动切换- Conf.Appearance.Icon = item.name- Conf.Save()+ UpdateAppearanceConf(func(appearance *conf.Appearance) { appearance.Icon = item.name })}}var names []stringdiff --git a/kernel/model/block.go b/kernel/model/block.goindex e34b2a541e..44976fdf7f 100644--- a/kernel/model/block.go+++ b/kernel/model/block.go@@ -1363,7 +1363,7 @@ func resolveEmbedContentInBox(n *ast.Node, luteEngine *lute.Lute, boxID string,stmt = strings.ReplaceAll(stmt, editor.IALValEscNewLine, "\n")// 执行查询获取嵌入的块- sqlBlocks := sql.SelectBlocksRawStmtInBox(stmt, 1, Conf.Search.Limit, boxID)+ sqlBlocks := sql.SelectBlocksRawStmtInBox(stmt, 1, Conf.Search.Load().Limit, boxID)sqlBlocks = filterEmbedBlocksByAccess(sqlBlocks, accessChecker)// 收集所有嵌入块的内容 HTMLdiff --git a/kernel/model/blockinfo.go b/kernel/model/blockinfo.goindex 336c7547b9..30abc83315 100644--- a/kernel/model/blockinfo.go+++ b/kernel/model/blockinfo.go@@ -336,7 +336,7 @@ func getBlockRefText(id string, tree *parse.Tree) (ret string) {}ret = getNodeRefText(node)- ret = maxContent(ret, Conf.Editor.BlockRefDynamicAnchorTextMaxLen)+ ret = maxContent(ret, Conf.Editor.Load().BlockRefDynamicAnchorTextMaxLen)return}@@ -350,7 +350,7 @@ func getNodeRefText(node *ast.Node) string {ret = util.EscapeHTML(ret)return ret}- return getNodeRefText0(node, Conf.Editor.BlockRefDynamicAnchorTextMaxLen, true)+ return getNodeRefText0(node, Conf.Editor.Load().BlockRefDynamicAnchorTextMaxLen, true)}func getNodeAvBlockText(node *ast.Node, avID string) (icon, content string) {diff --git a/kernel/model/boot_sync_test.go b/kernel/model/boot_sync_test.goindex d559c7e5d7..32341fcfdb 100644--- a/kernel/model/boot_sync_test.go+++ b/kernel/model/boot_sync_test.go@@ -31,7 +31,7 @@ func TestIOSBootSyncPerception(t *testing.T) {util.SetBooted()util.IsUILoaded.Store(true)lastAutoPurgeRepo = time.Now()- Conf.Sync.Perception = true+ Conf.Sync.Load().Perception = truegetPetals()// 使用本地仓库和独立感知连接,验证完整启动同步流程而不访问云服务。@@ -87,7 +87,7 @@ func TestIOSBootSyncPerception(t *testing.T) {}return}- if msg.Cmd != "synced" || msg.Synced != Conf.Sync.Synced {+ if msg.Cmd != "synced" || msg.Synced != Conf.Sync.Load().Synced {t.Fatalf("unexpected sync notification: %+v", msg)}count++@@ -105,7 +105,7 @@ func TestIOSBootSyncPerception(t *testing.T) {assertResult := func(want int32) {t.Helper()if result := BootSyncSucc.Load(); result != want {- t.Fatalf("boot sync result = %d, want %d: %s", result, want, Conf.Sync.Stat)+ t.Fatalf("boot sync result = %d, want %d: %s", result, want, Conf.Sync.Load().Stat)}}assertPublished := func(name string) {@@ -120,23 +120,23 @@ func TestIOSBootSyncPerception(t *testing.T) {}writeLocal("ios-local-edit.txt")- Conf.Sync.Enabled = false+ Conf.Sync.Load().Enabled = falseBootSyncData()assertResult(-1)assertNotifications(0)- Conf.Sync.Enabled = true- Conf.Sync.Mode = 3+ Conf.Sync.Load().Enabled = true+ Conf.Sync.Load().Mode = 3BootSyncData()assertResult(-1)assertNotifications(0)- Conf.Sync.Mode = 1+ Conf.Sync.Load().Mode = 1- key := Conf.Repo.Key- Conf.Repo.Key = nil+ key := Conf.Repo.Load().Key+ Conf.Repo.Load().Key = nilBootSyncData()assertResult(1)assertNotifications(0)- Conf.Repo.Key = key+ Conf.Repo.Load().Key = keyBootSyncData()assertResult(0)assertNotifications(1)@@ -146,14 +146,14 @@ func TestIOSBootSyncPerception(t *testing.T) {assertResult(0)assertNotifications(0)- Conf.Sync.Mode = 2+ Conf.Sync.Load().Mode = 2writeLocal("manual-mode-edit.txt")BootSyncData()assertResult(0)assertNotifications(0)assertPublished("manual-mode-edit.txt")- Conf.Sync.Mode = 1+ Conf.Sync.Load().Mode = 1writeLocal("normal-sync-edit.txt")BootSyncSucc.Store(1)SyncData(false)diff --git a/kernel/model/box.go b/kernel/model/box.goindex 84a208977f..7dc782344e 100644--- a/kernel/model/box.go+++ b/kernel/model/box.go@@ -70,32 +70,35 @@ type Box struct {func StatJob() {- Conf.m.Lock()- Conf.Stat.TreeCount = treenode.CountTrees()- Conf.Stat.CTreeCount = treenode.CeilTreeCount(Conf.Stat.TreeCount)- Conf.Stat.BlockCount = treenode.CountBlocks()- Conf.Stat.CBlockCount = treenode.CeilBlockCount(Conf.Stat.BlockCount)- Conf.Stat.DataSize, Conf.Stat.AssetsSize = util.DataSize()- Conf.Stat.CDataSize = util.CeilSize(Conf.Stat.DataSize)- Conf.Stat.CAssetsSize = util.CeilSize(Conf.Stat.AssetsSize)- Conf.m.Unlock()- Conf.Save()-- logging.LogInfof("auto stat [trees=%d, blocks=%d, dataSize=%s, assetsSize=%s]", Conf.Stat.TreeCount, Conf.Stat.BlockCount, humanize.BytesCustomCeil(uint64(Conf.Stat.DataSize), 2), humanize.BytesCustomCeil(uint64(Conf.Stat.AssetsSize), 2))+ treeCount, blockCount := treenode.CountTrees(), treenode.CountBlocks()+ dataSize, assetsSize := util.DataSize()+ stat := UpdateStatConf(func(stat *conf.Stat) {+ stat.TreeCount = treeCount+ stat.CTreeCount = treenode.CeilTreeCount(treeCount)+ stat.BlockCount = blockCount+ stat.CBlockCount = treenode.CeilBlockCount(blockCount)+ stat.DataSize, stat.AssetsSize = dataSize, assetsSize+ stat.CDataSize = util.CeilSize(dataSize)+ stat.CAssetsSize = util.CeilSize(assetsSize)+ })++ logging.LogInfof("auto stat [trees=%d, blocks=%d, dataSize=%s, assetsSize=%s]", stat.TreeCount, stat.BlockCount, humanize.BytesCustomCeil(uint64(stat.DataSize), 2), humanize.BytesCustomCeil(uint64(stat.AssetsSize), 2))// 桌面端检查磁盘可用空间 https://github.com/siyuan-note/siyuan/issues/6873if util.ContainerStd != util.Container {return}- if util.NeedWarnDiskUsage(Conf.Stat.DataSize) {+ if util.NeedWarnDiskUsage(Conf.Stat.Load().DataSize) {util.PushMsg(Conf.Language(179), 7000)}}func ListNotebooks() (ret []*Box, err error) {+ confSyncSnapshot := Conf.LoadSync()+// 启用数据同步时,缺失配置可能表示其他设备已删除笔记本,不能在列表读取过程中自动重建。- repairMissingConf := nil != Conf && nil != Conf.Sync && !Conf.Sync.Enabled+ repairMissingConf := nil != Conf && nil != confSyncSnapshot && !confSyncSnapshot.Enabledret, err = listNotebooks(repairMissingConf)return}@@ -246,7 +249,7 @@ func listNotebooks(repairMissingConf bool) (ret []*Box, err error) {ret = append(ret, box)}- switch Conf.FileTree.Sort {+ switch Conf.FileTree.Load().Sort {case util.SortModeNameASC:sort.Slice(ret, func(i, j int) bool {return util.PinYinCompare4FileTree(ret[i].Name, ret[j].Name)diff --git a/kernel/model/box_doc.go b/kernel/model/box_doc.goindex 3f179c25fe..7608843cfd 100644--- a/kernel/model/box_doc.go+++ b/kernel/model/box_doc.go@@ -92,7 +92,9 @@ func writeBoxDocID(boxID string) error {}func IsBoxDocEnabled() bool {- return nil != Conf && nil != Conf.FileTree && nil != Conf.FileTree.BoxDocEnabled && *Conf.FileTree.BoxDocEnabled+ confFileTreeSnapshot := Conf.LoadFileTree()++ return nil != Conf && nil != confFileTreeSnapshot && nil != confFileTreeSnapshot.BoxDocEnabled && *confFileTreeSnapshot.BoxDocEnabled}func hiddenBoxDocRootIDs() (ret []string) {diff --git a/kernel/model/box_doc_test.go b/kernel/model/box_doc_test.goindex f21bef7242..c894713308 100644--- a/kernel/model/box_doc_test.go+++ b/kernel/model/box_doc_test.go@@ -93,9 +93,9 @@ func TestFindUnindexedTreePathIgnoresTextMatch(t *testing.T) {util.DataDir = filepath.Join(tempDir, "data")util.BlockTreeDBPath = filepath.Join(tempDir, "blocktree.db")Conf = NewAppConf()- Conf.FileTree = conf.NewFileTree()+ Conf.FileTree.Store(conf.NewFileTree())Conf.NotebookCrypto = conf.NewNotebookCrypto()- Conf.Sync = conf.NewSync()+ Conf.Sync.Store(conf.NewSync())box := &Box{ID: "20260716120010-abcdefg"}boxConf := conf.NewBoxConf()diff --git a/kernel/model/box_list_test.go b/kernel/model/box_list_test.goindex c0f56a9c38..2a5794c048 100644--- a/kernel/model/box_list_test.go+++ b/kernel/model/box_list_test.go@@ -29,10 +29,10 @@ func TestListNotebooksIgnoresBoxWithoutConfAndDocuments(t *testing.T) {oldConf, oldDataDir := Conf, util.DataDirutil.DataDir = t.TempDir()Conf = NewAppConf()- Conf.FileTree = conf.NewFileTree()+ Conf.FileTree.Store(conf.NewFileTree())Conf.NotebookCrypto = conf.NewNotebookCrypto()- Conf.Sync = conf.NewSync()- Conf.Sync.Enabled = true+ Conf.Sync.Store(conf.NewSync())+ Conf.Sync.Load().Enabled = truet.Cleanup(func() {Conf, util.DataDir = oldConf, oldDataDir})@@ -71,10 +71,10 @@ func TestListNotebooksDoesNotRepairBoxWithDocuments(t *testing.T) {oldConf, oldDataDir := Conf, util.DataDirutil.DataDir = t.TempDir()Conf = NewAppConf()- Conf.FileTree = conf.NewFileTree()+ Conf.FileTree.Store(conf.NewFileTree())Conf.NotebookCrypto = conf.NewNotebookCrypto()- Conf.Sync = conf.NewSync()- Conf.Sync.Enabled = true+ Conf.Sync.Store(conf.NewSync())+ Conf.Sync.Load().Enabled = truet.Cleanup(func() {Conf, util.DataDir = oldConf, oldDataDir})diff --git a/kernel/model/clipboard_paste_test.go b/kernel/model/clipboard_paste_test.goindex 44e9e55767..4981827cec 100644--- a/kernel/model/clipboard_paste_test.go+++ b/kernel/model/clipboard_paste_test.go@@ -18,10 +18,10 @@ func TestPrepareClipboardPasteAssets(t *testing.T) {util.WorkspaceDir = t.TempDir()util.DataDir = filepath.Join(util.WorkspaceDir, "data")Conf = NewAppConf()- Conf.Sync = conf.NewSync()- Conf.FileTree = conf.NewFileTree()- Conf.Editor = conf.NewEditor()- Conf.Editor.VirtualBlockRef = false+ Conf.Sync.Store(conf.NewSync())+ Conf.FileTree.Store(conf.NewFileTree())+ Conf.Editor.Store(conf.NewEditor())+ Conf.Editor.Load().VirtualBlockRef = falseboxID, otherBox := "20260928120000-abcdefg", "20260928120000-hijklmn"t.Cleanup(func() {LockBox(boxID)diff --git a/kernel/model/cloud_account_auth.go b/kernel/model/cloud_account_auth.goindex 8c5330cd34..48ce468384 100644--- a/kernel/model/cloud_account_auth.go+++ b/kernel/model/cloud_account_auth.go@@ -44,7 +44,7 @@ func cloudAccountAuthFailureHandler(token string) func() {// 调用方在来源锁或同步锁内捕获凭据,第三方存储错误不影响思源账号。func cloudRepoErrorHandler() func(error) {user := Conf.GetUser()- if Conf.Sync.Provider != conf.ProviderSiYuan || user == nil {+ if Conf.Sync.Load().Provider != conf.ProviderSiYuan || user == nil {return func(error) {}}invalid := cloudAccountAuthFailureHandler(user.UserToken)diff --git a/kernel/model/cloud_account_auth_test.go b/kernel/model/cloud_account_auth_test.goindex d1b5d400db..6a1e2f2525 100644--- a/kernel/model/cloud_account_auth_test.go+++ b/kernel/model/cloud_account_auth_test.go@@ -31,9 +31,14 @@ func setupCloudAccountAuthTest(t *testing.T) *conf.User {util.DataDir, util.RepoDir, util.HistoryDir, util.TempDir = oldData, oldRepo, oldHistory, oldTemp})Conf = NewAppConf()- Conf.Sync, Conf.Repo, Conf.System = conf.NewSync(), conf.NewRepo(), conf.NewSystem()- Conf.Sync.Enabled, Conf.Sync.Provider, Conf.Sync.CloudName = true, conf.ProviderSiYuan, "main"- Conf.Repo.Key = []byte("0123456789abcdef0123456789abcdef")+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewSync(), conf.NewRepo(), conf.NewSystem()+ Conf.Sync.Store(confSectionValue0)+ Conf.Repo.Store(confSectionValue1)+ Conf.System.Store(confSectionValue2)+ }+ Conf.Sync.Load().Enabled, Conf.Sync.Load().Provider, Conf.Sync.Load().CloudName = true, conf.ProviderSiYuan, "main"+ Conf.Repo.Load().Key = []byte("0123456789abcdef0123456789abcdef")util.ConfDir, util.CurrentCloudRegion, util.ReadOnly = t.TempDir(), 0, falseutil.DataDir, util.RepoDir = filepath.Join(util.ConfDir, "data"), filepath.Join(util.ConfDir, "repo")util.HistoryDir, util.TempDir = filepath.Join(util.ConfDir, "history"), filepath.Join(util.ConfDir, "temp")@@ -59,7 +64,7 @@ func assertCloudAccountLoggedOut(t *testing.T) {if err = json.Unmarshal(data, &saved); err != nil || saved.UserData != "" {t.Fatalf("authentication failure retained persisted credentials: %v", err)}- if !Conf.Sync.Enabled || Conf.Sync.CloudName != "main" || string(Conf.Repo.Key) != "0123456789abcdef0123456789abcdef" {+ if !Conf.Sync.Load().Enabled || Conf.Sync.Load().CloudName != "main" || string(Conf.Repo.Load().Key) != "0123456789abcdef0123456789abcdef" {t.Fatal("logout changed sync configuration or recovery key")}}@@ -93,10 +98,10 @@ func TestCloudRepoAuthFailurePreservesOtherSessions(t *testing.T) {t.Run(name, func(t *testing.T) {user := setupCloudAccountAuthTest(t)if name == "s3" {- Conf.Sync.Provider = conf.ProviderS3+ Conf.Sync.Load().Provider = conf.ProviderS3}if name == "webdav" {- Conf.Sync.Provider = conf.ProviderWebDAV+ Conf.Sync.Load().Provider = conf.ProviderWebDAV}handle := cloudRepoErrorHandler()err := cloud.ErrCloudAuthFaileddiff --git a/kernel/model/cloud_service.go b/kernel/model/cloud_service.goindex b7d91101d6..ac787200dd 100644--- a/kernel/model/cloud_service.go+++ b/kernel/model/cloud_service.go@@ -150,7 +150,7 @@ func StartFreeTrial() (err error) {func DeactivateUser() (err error) {release := lockAssetSourceChange()defer release()- if Conf.Sync.Provider == conf.ProviderSiYuan {+ if Conf.Sync.Load().Provider == conf.ProviderSiYuan {if err = requireCompleteAssetDownloads(); err != nil {return}@@ -504,7 +504,9 @@ func IsCloudAssetSourceChange(err error) bool {// 使用服务端返回的账号标识验证来源,允许过期登出后重新认证原账号。func validateCloudUserAssetSource(user *conf.User) error {- if Conf.Sync.Provider != conf.ProviderSiYuan {+ confSyncSnapshot := Conf.LoadSync()++ if confSyncSnapshot.Provider != conf.ProviderSiYuan {return nil}cloudConf, err := buildCloudConf()@@ -512,7 +514,7 @@ func validateCloudUserAssetSource(user *conf.User) error {return &cloudAssetSourceError{cause: err}}cloudConf.UserID = user.UserId- if err = validateAssetDownloadSourceScope(assetDownloadScope(Conf.Sync.Provider, cloudConf, Conf.Repo.Key)); err != nil {+ if err = validateAssetDownloadSourceScope(assetDownloadScope(confSyncSnapshot.Provider, cloudConf, Conf.Repo.Load().Key)); err != nil {return &cloudAssetSourceError{cause: err}}return nil@@ -828,7 +830,7 @@ func Login(userName, password, captcha string, cloudRegion int) (ret *gulu.Resulrelease := lockAssetSourceChange()defer release()previousCloudRegion := util.CurrentCloudRegion- if Conf.Sync.Provider == conf.ProviderSiYuan && previousCloudRegion != cloudRegion {+ if Conf.Sync.Load().Provider == conf.ProviderSiYuan && previousCloudRegion != cloudRegion {if err := requireCompleteAssetDownloads(); err != nil {ret = gulu.Ret.NewResult()ret.Code = -1diff --git a/kernel/model/cloud_service_asset_source_test.go b/kernel/model/cloud_service_asset_source_test.goindex f262361bba..32b30692e0 100644--- a/kernel/model/cloud_service_asset_source_test.go+++ b/kernel/model/cloud_service_asset_source_test.go@@ -35,10 +35,15 @@ func testCloudAssetSourceAllowsOriginalAccountAfterLogout(t *testing.T, logout fkey := []byte("0123456789abcdef0123456789abcdef")owner := &conf.User{UserId: "asset-owner", UserName: "owner", UserToken: "asset-token"}Conf = NewAppConf()- Conf.Sync, Conf.Repo, Conf.System = conf.NewSync(), conf.NewRepo(), conf.NewSystem()- Conf.Sync.Provider, Conf.Sync.CloudName, Conf.Sync.Enabled = conf.ProviderSiYuan, "main", true- Conf.Sync.AssetDownloadMode = 1- Conf.Repo.Key = key+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewSync(), conf.NewRepo(), conf.NewSystem()+ Conf.Sync.Store(confSectionValue0)+ Conf.Repo.Store(confSectionValue1)+ Conf.System.Store(confSectionValue2)+ }+ Conf.Sync.Load().Provider, Conf.Sync.Load().CloudName, Conf.Sync.Load().Enabled = conf.ProviderSiYuan, "main", true+ Conf.Sync.Load().AssetDownloadMode = 1+ Conf.Repo.Load().Key = keyConf.SetUser(owner)Conf.CloudRegion, util.CurrentCloudRegion = 0, 0deviceDir := filepath.Join(base, "partial")diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex 302d82026e..d99858aa0b 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -24,7 +24,6 @@ import ("os""path/filepath""reflect"- "runtime""sort""strconv""strings"@@ -51,43 +50,44 @@ var Conf *AppConf// AppConf 维护应用元数据,保存在 ~/.siyuan/conf.json。type AppConf struct {- LogLevel string `json:"logLevel"` // 日志级别:off, trace, debug, info, warn, error, fatal- Appearance *conf.Appearance `json:"appearance"` // 外观- Langs []*conf.Lang `json:"langs"` // 界面语言列表- Lang string `json:"lang"` // 选择的界面语言,同 Appearance.Lang- FileTree *conf.FileTree `json:"fileTree"` // 文档面板- Tag *conf.Tag `json:"tag"` // 标签面板- Editor *conf.Editor `json:"editor"` // 编辑器配置- Export *conf.Export `json:"export"` // 导出配置- Graph *conf.Graph `json:"graph"` // 关系图配置- UILayout *conf.UILayout `json:"uiLayout"` // 界面布局,通过 SetUILayout 更新- UserData string `json:"userData"` // 社区用户信息,对 User 加密存储- User *conf.User `json:"-"` // 社区用户内存结构,不持久化。不要直接使用,使用 GetUser() 和 SetUser() 方法- ReadOnly bool `json:"readonly"` // 是否是以只读模式运行- ServerAddrs []string `json:"serverAddrs"` // 本地服务器地址列表- AccessAuthCode string `json:"accessAuthCode"` // 锁屏密码- OIDC *conf.OIDC `json:"oidc"` // OpenID Connect 登录- System *conf.System `json:"system"` // 系统配置- Keymap *conf.Keymap `json:"keymap"` // 快捷键配置- Sync *conf.Sync `json:"sync"` // 同步配置- Search *conf.Search `json:"search"` // 搜索配置- Flashcard *conf.Flashcard `json:"flashcard"` // 闪卡配置- AI *conf.AI `json:"ai"` // 人工智能配置- OCR *conf.OCR `json:"ocr"` // 本地图片文字识别- Secrets *conf.Secrets `json:"secrets"` // 全局密钥库- Variables *conf.Variables `json:"variables"` // 全局变量库- Bazaar *conf.Bazaar `json:"bazaar"` // 集市配置- Stat *conf.Stat `json:"stat"` // 统计- Api *conf.API `json:"api"` // API- Repo *conf.Repo `json:"repo"` // 数据仓库- NotebookCrypto *conf.NotebookCrypto `json:"notebookCrypto"` // 加密笔记本密钥管理- Publish *conf.Publish `json:"publish"` // 发布服务- Onboarding *conf.Onboarding `json:"onboarding"` // 首次使用引导- ShowChangelog bool `json:"showChangelog"` // 是否显示版本更新日志- CloudRegion int `json:"cloudRegion"` // 云端区域,0:中国大陆,1:北美- Snippet *conf.Snpt `json:"snippet"` // 代码片段- DataIndexState int `json:"dataIndexState"` // 数据索引状态,0:已索引,1:未索引- CookieKey string `json:"cookieKey"` // 用于加密 Cookie 的密钥+ LogLevel string `json:"logLevel"` // 日志级别:off, trace, debug, info, warn, error, fatal+ Appearance ConfSection[conf.Appearance] `json:"appearance"` // 外观+ Langs []*conf.Lang `json:"langs"` // 界面语言列表+ Lang string `json:"lang"` // 选择的界面语言,同 Appearance.Lang+ FileTree ConfSection[conf.FileTree] `json:"fileTree"` // 文档面板+ Tag ConfSection[conf.Tag] `json:"tag"` // 标签面板+ Editor ConfSection[conf.Editor] `json:"editor"` // 编辑器配置+ Export ConfSection[conf.Export] `json:"export"` // 导出配置+ Graph ConfSection[conf.Graph] `json:"graph"` // 关系图配置+ UILayout ConfSection[conf.UILayout] `json:"uiLayout"` // 界面布局,通过 SetUILayout 更新+ UserData string `json:"userData"` // 社区用户信息,对 User 加密存储+ User *conf.User `json:"-"` // 社区用户内存结构,不持久化。不要直接使用,使用 GetUser() 和 SetUser() 方法+ ReadOnly bool `json:"readonly"` // 是否是以只读模式运行+ ServerAddrs []string `json:"serverAddrs"` // 本地服务器地址列表+ AccessAuthCode string `json:"accessAuthCode"` // 锁屏密码+ OIDC *conf.OIDC `json:"oidc"` // OpenID Connect 登录+ System ConfSection[conf.System] `json:"system"` // 系统配置+ Keymap ConfSection[conf.Keymap] `json:"keymap"` // 快捷键配置+ Sync ConfSection[conf.Sync] `json:"sync"` // 同步配置+ Search ConfSection[conf.Search] `json:"search"` // 搜索配置+ Flashcard ConfSection[conf.Flashcard] `json:"flashcard"` // 闪卡配置+ AI ConfSection[conf.AI] `json:"ai"` // 人工智能配置+ OCR ConfSection[conf.OCR] `json:"ocr"` // 本地图片文字识别+ Secrets ConfSection[conf.Secrets] `json:"secrets"` // 全局密钥库+ Variables ConfSection[conf.Variables] `json:"variables"` // 全局变量库+ Bazaar ConfSection[conf.Bazaar] `json:"bazaar"` // 集市配置+ Stat ConfSection[conf.Stat] `json:"stat"` // 统计+ Api ConfSection[conf.API] `json:"api"` // API+ Repo ConfSection[conf.Repo] `json:"repo"` // 数据仓库+ NotebookCrypto *conf.NotebookCrypto `json:"notebookCrypto"` // 加密笔记本密钥管理+ Publish ConfSection[conf.Publish] `json:"publish"` // 发布服务+ Onboarding ConfSection[conf.Onboarding] `json:"onboarding"` // 首次使用引导+ ShowChangelog bool `json:"showChangelog"` // 是否显示版本更新日志+ CloudRegion int `json:"cloudRegion"` // 云端区域,0:中国大陆,1:北美+ Snippet ConfSection[conf.Snpt] `json:"snippet"` // 代码片段+ DataIndexState int `json:"dataIndexState"` // 数据索引状态,0:已索引,1:未索引+ CookieKey string `json:"cookieKey"` // 用于加密 Cookie 的密钥+ ConfVersion int `json:"confVersion"` // 配置格式版本,用于判定需要执行的迁移MCPOAuth string `json:"mcpOAuth"` // MCP OAuth 凭据密文@@ -97,10 +97,33 @@ type AppConf struct {func NewAppConf() *AppConf {return &AppConf{- LogLevel: "debug",- OIDC: conf.NewOIDC(),- m: &sync.RWMutex{},- userLock: &sync.RWMutex{},+ LogLevel: "debug",+ Appearance: NewConfSection[conf.Appearance](nil),+ FileTree: NewConfSection[conf.FileTree](nil),+ Tag: NewConfSection[conf.Tag](nil),+ Editor: NewConfSection[conf.Editor](nil),+ Export: NewConfSection[conf.Export](nil),+ Graph: NewConfSection[conf.Graph](nil),+ UILayout: NewConfSection[conf.UILayout](nil),+ System: NewConfSection[conf.System](nil),+ Keymap: NewConfSection[conf.Keymap](nil),+ Sync: NewConfSection[conf.Sync](nil),+ Search: NewConfSection[conf.Search](nil),+ Flashcard: NewConfSection[conf.Flashcard](nil),+ AI: NewConfSection[conf.AI](nil),+ OCR: NewConfSection[conf.OCR](nil),+ Secrets: NewConfSection[conf.Secrets](nil),+ Variables: NewConfSection[conf.Variables](nil),+ Bazaar: NewConfSection[conf.Bazaar](nil),+ Stat: NewConfSection[conf.Stat](nil),+ Api: NewConfSection[conf.API](nil),+ Repo: NewConfSection[conf.Repo](nil),+ Publish: NewConfSection[conf.Publish](nil),+ Onboarding: NewConfSection[conf.Onboarding](nil),+ Snippet: NewConfSection[conf.Snpt](nil),+ OIDC: conf.NewOIDC(),+ m: &sync.RWMutex{},+ userLock: &sync.RWMutex{},}}@@ -208,7 +231,7 @@ func (appConf *AppConf) CompareAndSetOIDC(expectedVersion string, config *conf.Ofunc (conf *AppConf) SetAI(ai *conf.AI) {conf.m.Lock()- conf.AI = ai+ conf.AI.Store(ai)conf.m.Unlock()conf.Save()}@@ -216,7 +239,7 @@ func (conf *AppConf) SetAI(ai *conf.AI) {func (conf *AppConf) SetUILayout(uiLayout *conf.UILayout) {conf.m.Lock()defer conf.m.Unlock()- conf.UILayout = uiLayout+ conf.UILayout.Store(uiLayout)}func (conf *AppConf) GetUser() *conf.User {@@ -251,12 +274,12 @@ func InitConf() {clearOldInstallPackages("")confPath := filepath.Join(util.ConfDir, "conf.json")confFileExists := gulu.File.IsExist(confPath)- entryVisibilityConfigured := false+ var confData []byteif confFileExists {if data, err := os.ReadFile(confPath); err != nil {logging.LogErrorf("load conf [%s] failed: %s", confPath, err)} else {- entryVisibilityConfigured = bytes.Contains(data, []byte(`"entryVisibility"`))+ recordPersistedConf(data)// 解析失败时保留已成功写入的字段;未导出字段(m、userLock)与未触及的导出字段保持 NewAppConf() 初值。if err = gulu.JSON.UnmarshalJSON(data, Conf); err != nil {logging.LogWarnf("parse conf failed, parsed fields retained: %s", err)@@ -266,12 +289,7 @@ func InitConf() {// 启动时检测并完成中断的改密迁移recoverMasterPasswordMigration()-- if conf.NeedsAIMigration(data) {- Conf.AI = conf.MigrateAI(data)- Conf.Save()- logging.LogInfof("migrated AI config [%s]", confPath)- }+ confData = data}}@@ -338,18 +356,56 @@ func InitConf() {}Conf.Langs = loadLangs()- if nil == Conf.Appearance {- Conf.Appearance = conf.NewAppearance()- }- entryVisibilityFallback := conf.EntryVisibilityProfileSimpleif confFileExists {- entryVisibilityFallback = conf.EntryVisibilityProfileFull+ applyConfMigrations(Conf, confData)+ } else {+ // 新工作空间直接使用当前格式,无需迁移+ Conf.ConfVersion = CurrentConfVersion+ }+ // 已有工作空间缺失的配置段按升级前的行为补全,其余规则由 normalizeAppConf 统一处理。+ Conf.FileTree.Store(normalizeFileTreeDefaultIcon(Conf.FileTree.Load(), confFileExists))+ Conf.OCR.Store(normalizeOCRConfig(Conf.OCR.Load(), confFileExists))+ isNewWorkspace := nil == Conf.System.Load()+ if Conf.Api.Load() == nil {+ api := conf.NewAPI()+ api.Token = gulu.Rand.String(16)+ Conf.Api.Store(api)+ }+ if Conf.AI.Load() == nil {+ ai := conf.NewAI()+ conf.ApplyAIEnvironment(ai)+ Conf.AI.Store(ai)+ }+ if nil != Conf.AI.Load() {+ Conf.AI.Load().DecryptAPIKeys()+ }+ if nil == Conf.OIDC {+ Conf.OIDC = conf.NewOIDC()+ } else {+ Conf.OIDC.DecryptClientSecret()+ }+ applyOIDCEnvironment(Conf.OIDC)+ if nil != Conf.Secrets.Load() {+ Conf.Secrets.Load().Decrypt()+ }+ if timingEnv := os.Getenv("SIYUAN_SYNC_INDEX_TIMING"); "" != timingEnv {+ if val, err := strconv.Atoi(timingEnv); err == nil {+ if nil == Conf.Repo.Load() {+ Conf.Repo.Store(conf.NewRepo())+ }+ Conf.Repo.Load().SyncIndexTiming = int64(val)+ }}- if confFileExists && !entryVisibilityConfigured {- Conf.Appearance.EntryVisibility = nil++ flashcardWarning := normalizeAppConf(Conf)+ if flashcardWarning != "" {+ logging.LogWarnf("%s, reset to default weights [%s]", flashcardWarning, Conf.Flashcard.Load().Weights)+ go func() {+ util.WaitForUILoaded()+ task.AppendAsyncTaskWithDelay(task.PushMsg, 2*time.Second, util.PushErrMsg, flashcardWarning, 15000)+ }()}- Conf.Appearance.EntryVisibility = conf.NormalizeEntryVisibility(Conf.Appearance.EntryVisibility, entryVisibilityFallback)- migrateSlashFrequent(Conf.Appearance.EntryVisibility, getLocalStorageWithError)+var langOK boolfor _, l := range Conf.Langs {if Conf.Lang == l.Name {@@ -361,7 +417,7 @@ func InitConf() {Conf.Lang = "en"util.Lang = Conf.Lang}- Conf.Appearance.Lang = Conf.Lang+ Conf.Appearance.Load().Lang = Conf.Lang// 历史下划线命名的 i18n 文件(zh_CN.json 等)已重命名为 BCP 47(zh-CN.json 等),// 清理 ConfDir/appearance/langs/ 下的旧名残留,避免僵尸文件。@@ -380,208 +436,36 @@ func InitConf() {}}}- if "ant" == Conf.Appearance.Icon || "material" == Conf.Appearance.Icon {- // v3.7.0 移除了 ant/material 图标包,如果用户之前选择了这两个其中之一,升级后改为 litheness 图标包,避免图标显示异常 https://github.com/siyuan-note/siyuan/issues/7976- Conf.Appearance.Icon = "litheness"- }os.RemoveAll(filepath.Join(util.AppearancePath, "icons", "ant"))os.RemoveAll(filepath.Join(util.AppearancePath, "icons", "material"))- if nil == Conf.UILayout {- Conf.UILayout = &conf.UILayout{}- }- if nil == Conf.Keymap {- Conf.Keymap = &conf.Keymap{}- }- if "" == Conf.Appearance.CodeBlockThemeDark {- Conf.Appearance.CodeBlockThemeDark = "dracula"- }- if "" == Conf.Appearance.CodeBlockThemeLight {- Conf.Appearance.CodeBlockThemeLight = "github"- }- Conf.Appearance.StatusBar = util.NormalizeStatusBar(Conf.Appearance.StatusBar, util.IsMobileContainer())- util.StatusBarCfg = Conf.Appearance.StatusBar- if nil == Conf.Appearance.Notifications {- Conf.Appearance.Notifications = util.NewNotifications()- }- util.NotificationsCfg = Conf.Appearance.Notifications- Conf.FileTree = normalizeFileTreeDefaultIcon(Conf.FileTree, confFileExists)- Conf.FileTree = conf.NormalizeFileTree(Conf.FileTree)- util.UseSingleLineSave = Conf.FileTree.UseSingleLineSave- util.LargeFileWarningSize = Conf.FileTree.LargeFileWarningSizeutil.CurrentCloudRegion = Conf.CloudRegion- if nil == Conf.Tag {- Conf.Tag = conf.NewTag()- }-- Conf.Editor = conf.NormalizeEditor(Conf.Editor)- Conf.Appearance.NormalizeGlobalFontFamilies()- util.MarkdownSettings = Conf.Editor.Markdown-- Conf.Export = conf.NormalizeExport(Conf.Export)- if nil == Conf.Graph || nil == Conf.Graph.Local || nil == Conf.Graph.Global {- Conf.Graph = conf.NewGraph()- } else {- Conf.Graph.NormalizeMaxBlocks()- }-- isNewWorkspace := nil == Conf.System- if isNewWorkspace {- Conf.System = conf.NewSystem()- } else {- cmp := semver.Compare("v"+util.Ver, "v"+Conf.System.KernelVersion)+ if !isNewWorkspace {+ cmp := semver.Compare("v"+util.Ver, "v"+Conf.System.Load().KernelVersion)if 0 < cmp {- logging.LogInfof("upgraded from version [%s] to [%s]", Conf.System.KernelVersion, util.Ver)+ logging.LogInfof("upgraded from version [%s] to [%s]", Conf.System.Load().KernelVersion, util.Ver)Conf.ShowChangelog = true} else if 0 > cmp {- logging.LogInfof("downgraded from version [%s] to [%s]", Conf.System.KernelVersion, util.Ver)+ logging.LogInfof("downgraded from version [%s] to [%s]", Conf.System.Load().KernelVersion, util.Ver)}-- Conf.System.KernelVersion = util.Ver- }- Conf.System.UpdateChannel = loadGlobalUpdateChannel()- if nil == Conf.Onboarding {- Conf.Onboarding = &conf.Onboarding{State: conf.OnboardingCompleted}- }- if nil == Conf.System.NetworkProxy {- Conf.System.NetworkProxy = &conf.NetworkProxy{}- }- if "" == Conf.System.ID {- Conf.System.ID = util.GetDeviceID()- }- if "" == Conf.System.Name {- Conf.System.Name = util.GetDeviceName()- }- if util.ContainerStd == util.Container {- Conf.System.ID = util.GetDeviceID()- Conf.System.Name = util.GetDeviceName()- }- Conf.System.DisabledFeatures = util.DisabledFeatures- if 1 > len(Conf.System.DisabledFeatures) {- Conf.System.DisabledFeatures = []string{}- }-- Conf.System.AppDir = util.WorkingDir- Conf.System.ConfDir = util.ConfDir- Conf.System.HomeDir = util.HomeDir- Conf.System.WorkspaceDir = util.WorkspaceDir- Conf.System.DataDir = util.DataDir- Conf.System.Container = util.Container- Conf.System.IsMicrosoftStore = util.ISMicrosoftStore- if util.ISMicrosoftStore {- logging.LogInfof("using Microsoft Store edition")- }- Conf.System.OS = runtime.GOOS- Conf.System.OSPlatform = util.GetOSPlatform()-- docxTemplate := util.RemoveInvalid(Conf.Export.DocxTemplate)- if "" != docxTemplate {- params := util.RemoveInvalid(Conf.Export.PandocParams)- if gulu.File.IsExist(docxTemplate) && !strings.Contains(params, "--reference-doc") && !Conf.System.IsMicrosoftStore {- if !strings.HasPrefix(docxTemplate, "\"") {- docxTemplate = "\"" + docxTemplate + "\""- }- params += " --reference-doc " + docxTemplate- Conf.Export.PandocParams = strings.TrimSpace(params)- }- Conf.Export.DocxTemplate = ""- Conf.Save()- }- if migratePandocConfig(Conf.Export) {- Conf.Save()- }-- if nil == Conf.Snippet {- Conf.Snippet = conf.NewSnpt()+ Conf.System.Load().KernelVersion = util.Ver}+ projectSystemEnvironment(Conf.System.Load())if "" != Conf.UserData {Conf.SetUser(loadUserFromConf())}- if nil == Conf.Sync {- Conf.Sync = conf.NewSync()- }- if 0 == Conf.Sync.Mode {- Conf.Sync.Mode = 1- }- if 30 > Conf.Sync.Interval {- Conf.Sync.Interval = 30- }- if 60*60*12 < Conf.Sync.Interval {- Conf.Sync.Interval = 60 * 60 * 12- }- if nil == Conf.Sync.S3 {- Conf.Sync.S3 = &conf.S3{PathStyle: true, SkipTlsVerify: true}- }- Conf.Sync.S3.Endpoint = util.NormalizeEndpoint(Conf.Sync.S3.Endpoint)- Conf.Sync.S3.Timeout = util.NormalizeTimeout(Conf.Sync.S3.Timeout)- Conf.Sync.S3.ConcurrentReqs = util.NormalizeConcurrentReqs(Conf.Sync.S3.ConcurrentReqs, conf.ProviderS3)- if nil == Conf.Sync.WebDAV {- Conf.Sync.WebDAV = &conf.WebDAV{SkipTlsVerify: true}- }- Conf.Sync.WebDAV.Endpoint = util.NormalizeEndpoint(Conf.Sync.WebDAV.Endpoint)- Conf.Sync.WebDAV.Timeout = util.NormalizeTimeout(Conf.Sync.WebDAV.Timeout)- Conf.Sync.WebDAV.ConcurrentReqs = util.NormalizeConcurrentReqs(Conf.Sync.WebDAV.ConcurrentReqs, conf.ProviderWebDAV)- if nil == Conf.Sync.Local {- Conf.Sync.Local = &conf.Local{}- }- Conf.Sync.Local.Endpoint = util.NormalizeLocalPath(Conf.Sync.Local.Endpoint)- Conf.Sync.Local.Timeout = util.NormalizeTimeout(Conf.Sync.Local.Timeout)- Conf.Sync.Local.ConcurrentReqs = util.NormalizeConcurrentReqs(Conf.Sync.Local.ConcurrentReqs, conf.ProviderLocal)- if nil == Conf.Sync.LAN {- Conf.Sync.LAN = &conf.LANSync{MaxConcurrentReqs: 16}- }- if 1 > Conf.Sync.LAN.MaxConcurrentReqs {- Conf.Sync.LAN.MaxConcurrentReqs = 16- }- if 128 < Conf.Sync.LAN.MaxConcurrentReqs {- Conf.Sync.LAN.MaxConcurrentReqs = 128- }-if util.ContainerDocker == util.Container {- Conf.Sync.Perception = false+ Conf.Sync.Load().Perception = false}if boxes, listErr := ListNotebooks(); listErr == nil {- prepareOnboardingForEmptyWorkspace(Conf.Onboarding, util.ReadOnly, len(boxes))- }-- if nil == Conf.Api {- Conf.Api = conf.NewAPI()+ prepareOnboardingForEmptyWorkspace(Conf.Onboarding.Load(), util.ReadOnly, len(boxes))}- if nil == Conf.Bazaar {- Conf.Bazaar = conf.NewBazaar()- }-- if nil == Conf.Publish {- Conf.Publish = conf.NewPublish()- }- if nil == Conf.Repo {- Conf.Repo = conf.NewRepo()- }- if timingEnv := os.Getenv("SIYUAN_SYNC_INDEX_TIMING"); "" != timingEnv {- val, err := strconv.Atoi(timingEnv)- if err == nil {- Conf.Repo.SyncIndexTiming = int64(val)- }- }- if 12000 > Conf.Repo.SyncIndexTiming {- Conf.Repo.SyncIndexTiming = 12 * 1000- }- if 1 > Conf.Repo.IndexRetentionDays {- Conf.Repo.IndexRetentionDays = 180- }- if 1 > Conf.Repo.RetentionIndexesDaily {- Conf.Repo.RetentionIndexesDaily = 2- }- if 0 < len(Conf.Repo.Key) {- logging.LogInfof("repo key [%x]", sha1.Sum(Conf.Repo.Key))- }-- if nil == Conf.NotebookCrypto {- Conf.NotebookCrypto = conf.NewNotebookCrypto()+ if 0 < len(Conf.Repo.Load().Key) {+ logging.LogInfof("repo key [%x]", sha1.Sum(Conf.Repo.Load().Key))}// 注意:此处不在启动时为已启用但备份缺失的情形回填密钥备份。无 KEK 生成的备份 KEKMAC 必为空,@@ -590,53 +474,9 @@ func InitConf() {// Enabled=true 但备份缺失/无效属配置不完整,解锁时由 deriveKEK 返回恢复提示(Language 315),// 引导用户导入匹配的备份文件后重新验证主密码。- Conf.Search = conf.NormalizeSearch(Conf.Search)- sql.SetCaseSensitive(Conf.Search.CaseSensitive)- sql.SetHanSensitive(Conf.Search.HanSensitiveVal())- sql.SetIndexAssetPath(Conf.Search.IndexAssetPath)-- if nil == Conf.Stat {- Conf.Stat = conf.NewStat()- }-- var flashcardWarning string- Conf.Flashcard, flashcardWarning = conf.NormalizeFlashcard(Conf.Flashcard)- if flashcardWarning != "" {- logging.LogWarnf("%s, reset to default weights [%s]", flashcardWarning, Conf.Flashcard.Weights)- go func() {- util.WaitForUILoaded()- task.AppendAsyncTaskWithDelay(task.PushMsg, 2*time.Second, util.PushErrMsg, flashcardWarning, 15000)- }()- }-- Conf.OCR = normalizeOCRConfig(Conf.OCR, confFileExists)- if nil == Conf.AI {- Conf.AI = conf.NewAI()- } else {- Conf.AI.DecryptAPIKeys()- }- Conf.AI.Normalize()- Conf.AI.ReconcileModelIDs()+ applyConfRuntime()- if nil == Conf.OIDC {- Conf.OIDC = conf.NewOIDC()- } else {- Conf.OIDC.DecryptClientSecret()- }- applyOIDCEnvironment(Conf.OIDC)- Conf.OIDC.Normalize()-- if nil == Conf.Secrets {- Conf.Secrets = conf.NewSecrets()- } else {- Conf.Secrets.Decrypt()- }-- if nil == Conf.Variables {- Conf.Variables = conf.NewVariables()- }-- for _, p := range Conf.AI.Providers {+ for _, p := range Conf.AI.Load().Providers {if p == nil || !p.Enabled {continue}@@ -654,18 +494,18 @@ func InitConf() {p.BaseURL,p.RequestTimeout,m.Name,- Conf.AI.Editing.MaxCompletionTokens,- Conf.AI.Editing.Temperature,- Conf.AI.Editing.MaxHistoryMessages)+ Conf.AI.Load().Editing.MaxCompletionTokens,+ Conf.AI.Load().Editing.Temperature,+ Conf.AI.Load().Editing.MaxHistoryMessages)}}- if Conf.AI.Embedding != nil && len(Conf.AI.Embedding.APIKey) > 0 {+ if Conf.AI.Load().Embedding != nil && len(Conf.AI.Load().Embedding.APIKey) > 0 {logging.LogInfof("embedding API enabled\n"+" baseURL=%s\n"+" model=%s",- Conf.AI.Embedding.BaseURL,- Conf.AI.Embedding.Name)+ Conf.AI.Load().Embedding.BaseURL,+ Conf.AI.Load().Embedding.Name)}Conf.ReadOnly = util.ReadOnly@@ -705,17 +545,17 @@ func InitConf() {// 安全模式:渲染进程崩溃恢复后由桌面端主进程通过 --safe-mode 注入。// safeMode 是纯运行时状态,不随 conf.json 持久化(Save 时会被排除),故每次启动都按 util.SafeMode 重新赋值。- Conf.System.SafeMode = util.SafeMode+ Conf.System.Load().SafeMode = util.SafeModeif util.SafeMode {// 直接覆盖外观、集市、代码片段相关配置并持久化,禁用代码片段、插件、自定义主题与图标,以排除扩展导致再次崩溃的可能。// 注意:这是破坏性操作,会覆盖用户原有配置,后续不会自动恢复。- Conf.Appearance.ThemeLight = "daylight"- Conf.Appearance.ThemeDark = "midnight"- Conf.Appearance.Icon = "litheness"- Conf.Appearance.ThemeJS = false- Conf.Bazaar.PetalDisabled = true- Conf.Snippet.EnabledCSS = false- Conf.Snippet.EnabledJS = false+ Conf.Appearance.Load().ThemeLight = "daylight"+ Conf.Appearance.Load().ThemeDark = "midnight"+ Conf.Appearance.Load().Icon = "litheness"+ Conf.Appearance.Load().ThemeJS = false+ Conf.Bazaar.Load().PetalDisabled = true+ Conf.Snippet.Load().EnabledCSS = false+ Conf.Snippet.Load().EnabledJS = falseConf.Save()logging.LogInfof("booted in safe mode")}@@ -726,9 +566,9 @@ func InitConf() {logging.SetLogLevel(Conf.LogLevel)}- util.SetNetworkProxy(Conf.System.NetworkProxy.String(), Conf.System.NetworkProxy.IsSystem())+ util.SetNetworkProxy(Conf.System.Load().NetworkProxy.String(), Conf.System.Load().NetworkProxy.IsSystem())- go util.InitPandoc(Conf.Export.PandocBin)+ go util.InitPandoc(Conf.Export.Load().PandocBin)go util.InitTesseract()InitOCR()}@@ -862,6 +702,8 @@ var exitLock = sync.Mutex{}// 当 force 为 true(强制退出)并且 execInstallPkg 为 0(默认检查更新)并且新版本安装包已经准备就绪时,将安装包路径返回给桌面宿主// https://github.com/siyuan-note/siyuan/issues/10288func Close(force, setCurrentWorkspace bool, execInstallPkg int) (exitCode int, installPkgPath string) {+ confSyncSnapshot := Conf.LoadSync()+diagnostic := util.WatchOperationWithTiming("exit kernel", "wait for exit lock")defer diagnostic.Finish()exitLock.Lock()@@ -886,8 +728,8 @@ func Close(force, setCurrentWorkspace bool, execInstallPkg int) (exitCode int, iOnKernelPluginsStop()}- if Conf.Sync.Enabled && 3 != Conf.Sync.Mode &&- ((IsSubscriber() && conf.ProviderSiYuan == Conf.Sync.Provider) || conf.ProviderSiYuan != Conf.Sync.Provider) {+ if confSyncSnapshot.Enabled && 3 != confSyncSnapshot.Mode &&+ ((IsSubscriber() && conf.ProviderSiYuan == confSyncSnapshot.Provider) || conf.ProviderSiYuan != confSyncSnapshot.Provider) {diagnostic.Stage("exit sync")syncData(true, false)if 0 != ExitSyncSucc {@@ -1009,11 +851,13 @@ func ClearCustomEmojis() {}func NewLute() (ret *lute.Lute) {+ confEditorSnapshot := Conf.LoadEditor()+ret = util.NewLute()- ret.SetCodeSyntaxHighlightLineNum(Conf.Editor.CodeSyntaxHighlightLineNum)- ret.SetChineseParagraphBeginningSpace(Conf.Export.ParagraphBeginningSpace)- ret.SetProtyleMarkNetImg(Conf.Editor.DisplayNetImgMark)- ret.SetSpellcheck(Conf.Editor.Spellcheck)+ ret.SetCodeSyntaxHighlightLineNum(confEditorSnapshot.CodeSyntaxHighlightLineNum)+ ret.SetChineseParagraphBeginningSpace(Conf.Export.Load().ParagraphBeginningSpace)+ ret.SetProtyleMarkNetImg(confEditorSnapshot.DisplayNetImgMark)+ ret.SetSpellcheck(confEditorSnapshot.Spellcheck)customEmojiMap := map[string]string{}customEmojis.Range(func(key, value any) bool {@@ -1047,31 +891,43 @@ func (conf *AppConf) Save() {// SaveGraphQueryConf 仅在查询携带的图配置变化时更新并保存,比较、赋值和序列化共用配置锁。func (appConf *AppConf) SaveGraphQueryConf(global *conf.GlobalGraph, local *conf.LocalGraph) {- appConf.m.Lock()- defer appConf.m.Unlock()- changed := false- if global != nil && !reflect.DeepEqual(appConf.Graph.Global, global) {- appConf.Graph.Global = global- changed = true+ mutate := func(graph *conf.Graph) bool {+ changed := false+ if global != nil && !reflect.DeepEqual(graph.Global, global) {+ graph.Global = cloneConfSection(global)+ changed = true+ }+ if local != nil && !reflect.DeepEqual(graph.Local, local) {+ graph.Local = cloneConfSection(local)+ changed = true+ }+ return changed}- if local != nil && !reflect.DeepEqual(appConf.Graph.Local, local) {- appConf.Graph.Local = local- changed = true+ if appConf == Conf {+ UpdateGraphConf(mutate)+ return}- if changed && !util.ReadOnly {- appConf.saveLocked()+ spec := newSectionSpecFor(appConf, "graph", &appConf.Graph, conf.NormalizeGraph)+ spec.WriteLock.Lock()+ defer spec.WriteLock.Unlock()+ next := cloneConfSection(spec.Load())+ if mutate(next) {+ _, _ = applySectionLocked(spec, next)}}func (conf *AppConf) saveLocked() {+ applyConfRuntime(conf)newData, err := conf.marshalForSave()if err != nil {logging.LogErrorf("marshal conf failed: %s", err)return}+ recordPersistedConf(newData)confPath := filepath.Join(util.ConfDir, "conf.json")oldData, err := filelock.ReadFile(confPath)if err == nil && bytes.Equal(newData, oldData) {+ recordPersistedConf(oldData)return}conf.save0(newData)@@ -1087,20 +943,20 @@ func (conf *AppConf) marshalForSave() ([]byte, error) {if err = gulu.JSON.UnmarshalJSON(plainData, snapshot); err != nil {return nil, err}- if snapshot.AI != nil {- snapshot.AI.EncryptAPIKeys()+ if snapshot.AI.Load() != nil {+ snapshot.AI.Load().EncryptAPIKeys()}if snapshot.OIDC != nil {snapshot.OIDC.EncryptClientSecret()}- if snapshot.Secrets != nil {- snapshot.Secrets.Encrypt()+ if snapshot.Secrets.Load() != nil {+ snapshot.Secrets.Load().Encrypt()}// safeMode 是纯运行时状态(由 --safe-mode 注入),不随 conf.json 持久化,避免跨启动残留。- if snapshot.System != nil {- snapshot.System.SafeMode = false+ if snapshot.System.Load() != nil {+ snapshot.System.Load().SafeMode = false// 更新通道由用户目录下的全局配置持久化,不写入工作空间配置。- snapshot.System.UpdateChannel = ""+ snapshot.System.Load().UpdateChannel = ""}return gulu.JSON.MarshalIndentJSON(snapshot, "", " ")@@ -1113,6 +969,7 @@ func (conf *AppConf) save0(data []byte) {util.ReportFileSysFatalError(err)return}+ recordPersistedConf(data)}func (conf *AppConf) Close() {@@ -1297,21 +1154,21 @@ func UpdateServerAddrs(serverAddrs []string) bool {// HideConfSecret 隐藏设置中的秘密信息// REF: https://github.com/siyuan-note/siyuan/issues/11364func HideConfSecret(c *AppConf) {- c.AI = &conf.AI{}+ c.AI.Store(&conf.AI{})c.OIDC = &conf.OIDC{}c.MCPOAuth = ""c.CookieKey = ""- c.Api = &conf.API{}- if nil != c.Export {- c.Export.PandocBin = ""+ c.Api.Store(&conf.API{})+ if nil != c.Export.Load() {+ c.Export.Load().PandocBin = ""}- c.Flashcard = &conf.Flashcard{}+ c.Flashcard.Store(&conf.Flashcard{})c.ServerAddrs = []string{}- c.Publish = &conf.Publish{}- c.Repo = &conf.Repo{}- c.Sync = &conf.Sync{}- c.Secrets = &conf.Secrets{}- c.Variables = &conf.Variables{}+ c.Publish.Store(&conf.Publish{})+ c.Repo.Store(&conf.Repo{})+ c.Sync.Store(&conf.Sync{})+ c.Secrets.Store(&conf.Secrets{})+ c.Variables.Store(&conf.Variables{})if nil != c.NotebookCrypto {enabled := c.NotebookCrypto.Enabled && notebookCryptoConfigurationComplete(c.NotebookCrypto)c.NotebookCrypto = &conf.NotebookCrypto{@@ -1319,13 +1176,13 @@ func HideConfSecret(c *AppConf) {AutoLockMinutes: c.NotebookCrypto.AutoLockMinutes,}}- c.System.AppDir = ""- c.System.ConfDir = ""- c.System.DataDir = ""- c.System.HomeDir = ""- c.System.WorkspaceDir = ""- c.System.Name = ""- c.System.NetworkProxy = &conf.NetworkProxy{}+ c.System.Load().AppDir = ""+ c.System.Load().ConfDir = ""+ c.System.Load().DataDir = ""+ c.System.Load().HomeDir = ""+ c.System.Load().WorkspaceDir = ""+ c.System.Load().Name = ""+ c.System.Load().NetworkProxy = &conf.NetworkProxy{}}// HideBoxConfSecret 隐藏笔记本配置中的密钥材料。diff --git a/kernel/model/conf_archive_regression_test.go b/kernel/model/conf_archive_regression_test.gonew file mode 100644index 0000000000..fd5185ffa2--- /dev/null+++ b/kernel/model/conf_archive_regression_test.go@@ -0,0 +1,104 @@+package model++import (+ "bytes"+ "errors"+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestNotebookArchivePasswordChangePreservesArchiveGenerations(t *testing.T) {+ notebookArchiveTestWorkspace(t)+ if err := EnableEncryptedNotebook("old-archive-password"); err != nil {+ t.Fatal(err)+ }+ kek, err := deriveKEK("old-archive-password")+ if err != nil {+ t.Fatal(err)+ }+ defer zeroAndClear(kek)+ id := "20261011120000-archive"+ ciphertext := notebookArchiveTestBox(t, id, kek)+ oldID, _, err := PrepareNotebookArchive([]string{id})+ if err != nil {+ t.Fatal(err)+ }+ oldDirectory, _ := notebookArchiveDirectory(oldID)+ oldArchive := filepath.Join(oldDirectory, "archive.zip")+ if err = CommitNotebookArchive(oldID, true); err != nil {+ t.Fatal(err)+ }+ // 将归档移出的测试笔记本放回,继续验证同一份密文的包络改密。+ source := filepath.Join(oldDirectory, "removed", "data", id)+ err = archiveWalk(source, func(name, path string) error {+ return archiveCopyFile(path, filepath.Join(util.DataDir, id, filepath.FromSlash(name)))+ })+ if err != nil {+ t.Fatal(err)+ }+ if err = ChangeMasterPassword("old-archive-password", "new-archive-password"); err != nil {+ t.Fatal(err)+ }+ if _, err = deriveKEK("old-archive-password"); err == nil {+ t.Fatal("password change retained the old password")+ }+ // 打包不读取配置文件,即使磁盘内容过时也使用已生成的持久化形态。+ if err = os.WriteFile(filepath.Join(util.ConfDir, "conf.json"), []byte(`{"notebookCrypto":null}`), 0600); err != nil {+ t.Fatal(err)+ }+ newID, _, err := PrepareNotebookArchive([]string{id})+ if err != nil {+ t.Fatal(err)+ }+ newDirectory, _ := notebookArchiveDirectory(newID)+ newArchive := filepath.Join(newDirectory, "archive.zip")+ legacyDirectory := t.TempDir()+ manifest, err := readNotebookArchive(oldArchive, filepath.Join(legacyDirectory, "payload"))+ if err != nil {+ t.Fatal(err)+ }+ for _, name := range []string{"conf.json", "backup.json"} {+ if err = os.Remove(filepath.Join(legacyDirectory, "payload", "keys", name)); err != nil && !os.IsNotExist(err) {+ t.Fatal(err)+ }+ }+ if err = writeNotebookArchive(legacyDirectory, manifest); err != nil {+ t.Fatal(err)+ }+ for _, entry := range []struct{ name, archive, password string }{+ {"old", oldArchive, "old-archive-password"},+ {"new", newArchive, "new-archive-password"},+ {"legacy-persisted-key", filepath.Join(legacyDirectory, "archive.zip"), "old-archive-password"},+ } {+ t.Run(entry.name, func(t *testing.T) {+ notebookArchiveTestWorkspace(t)+ if err := ImportNotebookArchive(entry.archive, "invalid-password", nil); !errors.Is(err, ErrNotebookArchiveAuthentication) {+ t.Fatalf("wrong password accepted: %v", err)+ }+ if err := ImportNotebookArchive(entry.archive, entry.password, nil); err != nil {+ t.Fatal(err)+ }+ restored, err := os.ReadFile(filepath.Join(util.DataDir, id, id+".sy"))+ if err != nil || !bytes.Equal(restored, ciphertext) {+ t.Fatal("recovery changed authenticated ciphertext")+ }+ key, err := deriveKEK(entry.password)+ if err != nil {+ t.Fatal(err)+ }+ defer zeroAndClear(key)+ if _, _, err := decryptBoxCrypt(id, key); err != nil {+ t.Fatal(err)+ }+ })+ }+ t.Run("new archive rejects revoked password", func(t *testing.T) {+ notebookArchiveTestWorkspace(t)+ if err := ImportNotebookArchive(newArchive, "old-archive-password", nil); !errors.Is(err, ErrNotebookArchiveAuthentication) {+ t.Fatalf("revoked password accepted: %v", err)+ }+ })+}diff --git a/kernel/model/conf_consistency_test.go b/kernel/model/conf_consistency_test.gonew file mode 100644index 0000000000..2efee696eb--- /dev/null+++ b/kernel/model/conf_consistency_test.go@@ -0,0 +1,250 @@+package model++import (+ "encoding/json"+ "path/filepath"+ "reflect"+ "sync"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// legacyConfFixture 覆盖旧版字段、越界值和缺失配置段。+const legacyConfFixture = `{+ "ai": {"openAI": {"apiKey": "", "apiModel": "gpt-4o"}},+ "appearance": {"icon": "ant", "codeBlockThemeDark": "", "statusBar": null},+ "editor": {"fontSize": 200, "blockRefDynamicAnchorTextMaxLen": 0},+ "export": {"blockRefMode": 1, "pandocParams": "--wrap=none"},+ "fileTree": {"maxListCount": 0, "maxOpenTabCount": 99},+ "sync": {"mode": 0, "interval": 5, "lan": {"maxConcurrentReqs": 999}},+ "repo": {"syncIndexTiming": 1, "indexRetentionDays": 0},+ "graph": {"local": null},+ "search": {"limit": 1},+ "publish": {"auth": null},+ "system": {"id": "fixture-device", "name": "fixture-host", "networkProxy": null}+}`++func prepareConfConsistencyTest(t *testing.T) {+ t.Helper()+ previous, readOnly, confDir, dataDir := Conf, util.ReadOnly, util.ConfDir, util.DataDir+ lang := util.Lang+ markdown, singleLine, largeFile := util.MarkdownSettings.Load(), util.UseSingleLineSave.Load(), util.LargeFileWarningSize.Load()+ statusBar, notifications := util.StatusBarCfg.Load(), util.NotificationsCfg.Load()+ persisted := lastPersistedConf()+ t.Cleanup(func() {+ Conf, util.ReadOnly, util.ConfDir, util.DataDir = previous, readOnly, confDir, dataDir+ util.Lang = lang+ {+ derivedValue0, derivedValue1, derivedValue2 := markdown, singleLine, largeFile+ util.MarkdownSettings.Store(derivedValue0)+ util.UseSingleLineSave.Store(derivedValue1)+ util.LargeFileWarningSize.Store(derivedValue2)+ }+ {+ derivedValue0, derivedValue1 := statusBar, notifications+ util.StatusBarCfg.Store(derivedValue0)+ util.NotificationsCfg.Store(derivedValue1)+ }+ recordPersistedConf(persisted)+ if previous != nil && previous.Search.Load() != nil {+ ApplySearchRuntime()+ }+ })+ root := t.TempDir()+ util.ReadOnly, util.ConfDir, util.DataDir = false, root, filepath.Join(root, "data")+ Conf = NewAppConf()+}++func loadConfFixture(t *testing.T, raw string) *AppConf {+ t.Helper()+ c := NewAppConf()+ if err := json.Unmarshal([]byte(raw), c); err != nil {+ t.Fatal(err)+ }+ return c+}++// I1:启动路径与写入路径对同一配置段产出相同结果;I6:规范化只依赖输入,构造函数不读可变全局状态。+func TestConfNormalizeIsSharedAndIdempotent(t *testing.T) {+ prepareConfConsistencyTest(t)+ c := loadConfFixture(t, legacyConfFixture)+ normalizeAppConf(c)+ first, err := json.Marshal(c)+ if err != nil {+ t.Fatal(err)+ }+ normalizeAppConf(c)+ second, _ := json.Marshal(c)+ if string(first) != string(second) {+ t.Fatal("normalization is not idempotent")+ }+ if c.Appearance.Load().Icon != "litheness" || c.Appearance.Load().CodeBlockThemeDark == "" || c.Appearance.Load().StatusBar == nil ||+ c.Editor.Load().FontSize != 16 || c.Export.Load().BlockRefMode != 1 || c.FileTree.Load().MaxListCount != 512 ||+ c.FileTree.Load().MaxOpenTabCount != 32 || c.Sync.Load().Mode != 1 || c.Sync.Load().Interval != 30 || c.Sync.Load().LAN.MaxConcurrentReqs != 128 ||+ c.Repo.Load().SyncIndexTiming != 12000 || c.Repo.Load().IndexRetentionDays != 180 || c.Graph.Load().Local == nil ||+ c.Search.Load().Limit != 32 || c.Publish.Load().Auth == nil {+ t.Fatalf("legacy values were not normalized: %s", first)+ }+ for name, value := range map[string]any{+ "tag": c.Tag.Load(), "snippet": c.Snippet.Load(), "api": c.Api.Load(), "bazaar": c.Bazaar.Load(), "notebookCrypto": c.NotebookCrypto,+ "stat": c.Stat.Load(), "ocr": c.OCR.Load(), "oidc": c.OIDC, "secrets": c.Secrets.Load(), "variables": c.Variables.Load(),+ "keymap": c.Keymap.Load(), "uiLayout": c.UILayout.Load(), "onboarding": c.Onboarding.Load(), "system": c.System.Load(),+ } {+ if reflect.ValueOf(value).IsNil() {+ t.Fatalf("section %s was not filled", name)+ }+ }++ // 写入路径以段为单位规范化,结果必须与整体规范化一致+ sections := []struct {+ name string+ normalize func(*AppConf)+ }{+ {"sync", func(c *AppConf) { c.Sync.Store(conf.NormalizeSync(c.Sync.Load())) }},+ {"system", func(c *AppConf) { c.System.Store(conf.NormalizeSystem(c.System.Load())) }},+ {"repo", func(c *AppConf) { c.Repo.Store(conf.NormalizeRepo(c.Repo.Load())) }},+ {"editor", func(c *AppConf) { c.Editor.Store(conf.NormalizeEditor(c.Editor.Load())) }},+ {"appearance", func(c *AppConf) {+ c.Appearance.Store(conf.NormalizeAppearance(c.Appearance.Load(), util.IsMobileContainer()))+ }},+ {"graph", func(c *AppConf) { c.Graph.Store(conf.NormalizeGraph(c.Graph.Load())) }},+ {"publish", func(c *AppConf) { c.Publish.Store(conf.NormalizePublish(c.Publish.Load())) }},+ }+ for _, section := range sections {+ whole, single := loadConfFixture(t, legacyConfFixture), loadConfFixture(t, legacyConfFixture)+ normalizeAppConf(whole)+ section.normalize(single)+ a, _ := json.Marshal(reflect.ValueOf(whole).Elem().FieldByNameFunc(func(name string) bool {+ return jsonFieldName(reflect.TypeOf(*whole), name) == section.name+ }).Interface())+ b, _ := json.Marshal(reflect.ValueOf(single).Elem().FieldByNameFunc(func(name string) bool {+ return jsonFieldName(reflect.TypeOf(*single), name) == section.name+ }).Interface())+ if string(a) != string(b) {+ t.Fatalf("section %s differs between startup and write normalization:\n%s\n%s", section.name, a, b)+ }+ }+ {+ derivedValue0,++ // 构造函数不继承运行时状态+ derivedValue1 := !util.DefaultUseSingleLineSave, 99+ util.UseSingleLineSave.Store(derivedValue0)+ util.LargeFileWarningSize.Store(derivedValue1)+ }+ if fileTree := conf.NewFileTree(); fileTree.UseSingleLineSave != util.DefaultUseSingleLineSave ||+ fileTree.LargeFileWarningSize != util.DefaultLargeFileWarningSize {+ t.Fatal("NewFileTree inherits mutable runtime state")+ }+}++func jsonFieldName(typ reflect.Type, fieldName string) string {+ field, ok := typ.FieldByName(fieldName)+ if !ok {+ return ""+ }+ tag := field.Tag.Get("json")+ for i, ch := range tag {+ if ch == ',' {+ return tag[:i]+ }+ }+ return tag+}++// I3:迁移全量应用两次,第二次无修改;I7:配置版本高于本内核时不执行迁移、不改写版本。+func TestConfMigrationsAreVersioned(t *testing.T) {+ prepareConfConsistencyTest(t)+ raw := []byte(legacyConfFixture)+ c := loadConfFixture(t, legacyConfFixture)+ if !applyConfMigrations(c, raw) || c.ConfVersion != CurrentConfVersion {+ t.Fatal("legacy configuration was not migrated")+ }+ if c.AI.Load() == nil || c.Appearance.Load() == nil || c.Appearance.Load().EntryVisibility == nil ||+ c.Appearance.Load().EntryVisibility.Active != conf.EntryVisibilityProfileFull {+ t.Fatal("legacy AI or entry visibility migration was not applied")+ }+ before, _ := json.Marshal(c)+ if applyConfMigrations(c, raw) {+ t.Fatal("second migration pass changed the configuration")+ }+ after, _ := json.Marshal(c)+ if string(before) != string(after) {+ t.Fatal("second migration pass rewrote the configuration")+ }++ for i := 1; i < len(confMigrations); i++ {+ if confMigrations[i].version <= confMigrations[i-1].version {+ t.Fatal("migration versions must increase strictly")+ }+ }++ future := loadConfFixture(t, legacyConfFixture)+ future.ConfVersion = CurrentConfVersion + 1+ if applyConfMigrations(future, raw) || future.ConfVersion != CurrentConfVersion+1 || future.Export.Load().BlockRefMode != 1 {+ t.Fatal("configuration written by a newer kernel was migrated or downgraded")+ }+ normalizeAppConf(future)+ if future.ConfVersion != CurrentConfVersion+1 {+ t.Fatal("normalization changed the configuration version")+ }+}++// I4:配置写入后派生运行时状态由唯一函数重新投影。+func TestApplyConfRuntimeProjectsDerivedState(t *testing.T) {+ prepareConfConsistencyTest(t)+ normalizeAppConf(Conf)+ Conf.FileTree.Load().UseSingleLineSave = !util.DefaultUseSingleLineSave+ Conf.FileTree.Load().LargeFileWarningSize = 42+ Conf.Search.Load().CaseSensitive = true+ applyConfRuntime()+ if util.UseSingleLineSave.Load() != Conf.FileTree.Load().UseSingleLineSave || util.LargeFileWarningSize.Load() != 42 ||+ util.MarkdownSettings.Load() != Conf.Editor.Load().Markdown || util.StatusBarCfg.Load() != Conf.Appearance.Load().StatusBar ||+ util.NotificationsCfg.Load() != Conf.Appearance.Load().Notifications || !util.SearchCaseSensitive.Load() ||+ util.SearchHanSensitive.Load() != Conf.Search.Load().HanSensitiveVal() {+ t.Fatal("derived runtime state was not projected from the configuration")+ }+ sql.SetCaseSensitive(false)+}++// I10:段快照更新期间,读方取得的段在其生命周期内保持字段间自洽。+func TestConfSectionSnapshotsAreConsistent(t *testing.T) {+ prepareConfConsistencyTest(t)+ normalizeAppConf(Conf)+ held := Conf.Sync.Load()+ heldInterval, heldMode := held.Interval, held.Mode+ var wg sync.WaitGroup+ for i := 0; i < 20; i++ {+ wg.Add(1)+ go func(i int) {+ defer wg.Done()+ UpdateSyncConf(func(s *conf.Sync) {+ s.Interval = 60 + i+ s.Mode = 2 + i%2+ })+ }(i)+ }+ wg.Wait()+ if held.Interval != heldInterval || held.Mode != heldMode {+ t.Fatal("a section held by a reader was mutated in place")+ }+ if Conf.Sync.Load() == held || Conf.Sync.Load().Interval < 60 {+ t.Fatal("section update did not replace the section")+ }+ for _, section := range []any{Conf.Sync.Load(), Conf.System.Load(), Conf.Repo.Load(), Conf.Editor.Load(), Conf.Appearance.Load(), Conf.Bazaar.Load(), Conf.Graph.Load(),+ Conf.Tag.Load(), Conf.Api.Load(), Conf.Publish.Load(), Conf.Onboarding.Load(), Conf.Stat.Load()} {+ // 按实际类型执行与 cloneConfSection 相同的 JSON 往返,确认配置段没有不可序列化的状态+ value := reflect.ValueOf(section)+ data, _ := json.Marshal(section)+ copied := reflect.New(value.Elem().Type())+ if err := json.Unmarshal(data, copied.Interface()); err != nil || !reflect.DeepEqual(copied.Interface(), section) {+ t.Fatalf("section %T cannot be copied losslessly", section)+ }+ }+ if !reflect.DeepEqual(cloneConfSection(Conf.Search.Load()), Conf.Search.Load()) || !reflect.DeepEqual(cloneConfSection(Conf.AI.Load()), Conf.AI.Load()) {+ t.Fatal("search or AI section cannot be copied losslessly")+ }+}diff --git a/kernel/model/conf_migration.go b/kernel/model/conf_migration.gonew file mode 100644index 0000000000..fbfe8326b2--- /dev/null+++ b/kernel/model/conf_migration.go@@ -0,0 +1,130 @@+// 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 (+ "bytes"+ "strings"++ "github.com/88250/gulu"+ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// confMigration 描述一次配置格式迁移。version 单调递增,配置的 confVersion 低于该值时才执行;+// apply 接收配置文件原始字节,返回是否修改了配置。+type confMigration struct {+ version int+ name string+ apply func(c *AppConf, raw []byte) (bool, error)+}++// confMigrations 按版本升序登记全部配置迁移。新增迁移只能追加在末尾并使用更大的版本号。+var confMigrations = []confMigration{+ {1, "ai", func(c *AppConf, raw []byte) (bool, error) {+ // 旧版人工智能配置使用 openAI 字段 https://github.com/siyuan-note/siyuan/issues/14591+ if !conf.NeedsAIMigration(raw) {+ return false, nil+ }+ c.AI.Store(conf.MigrateAI(raw))+ return true, nil+ }},+ {2, "entryVisibility", func(c *AppConf, raw []byte) (bool, error) {+ // 入口可见性引入前的已有工作空间按完整方案显示全部入口+ if bytes.Contains(raw, []byte(`"entryVisibility"`)) {+ return false, nil+ }+ if nil == c.Appearance.Load() {+ c.Appearance.Store(conf.NewAppearanceForContainer(util.IsMobileContainer()))+ }+ c.Appearance.Load().EntryVisibility = conf.NewEntryVisibility(conf.EntryVisibilityProfileFull)+ return true, nil+ }},+ {3, "slashFrequent", func(c *AppConf, raw []byte) (bool, error) {+ // 斜杠菜单常用项开关从本地存储迁移到自定义入口方案+ if nil == c.Appearance.Load() || nil == c.Appearance.Load().EntryVisibility {+ return false, nil+ }+ before, _ := gulu.JSON.MarshalJSON(c.Appearance.Load().EntryVisibility)+ if err := migrateSlashFrequent(c.Appearance.Load().EntryVisibility, getLocalStorageWithError); err != nil {+ return false, err+ }+ after, _ := gulu.JSON.MarshalJSON(c.Appearance.Load().EntryVisibility)+ return !bytes.Equal(before, after), nil+ }},+ {4, "docxTemplate", func(c *AppConf, raw []byte) (bool, error) {+ // Word 导出模板并入 Pandoc 参数+ if nil == c.Export.Load() {+ return false, nil+ }+ docxTemplate := util.RemoveInvalid(c.Export.Load().DocxTemplate)+ if "" == docxTemplate {+ return false, nil+ }+ params := util.RemoveInvalid(c.Export.Load().PandocParams)+ if gulu.File.IsExist(docxTemplate) && !strings.Contains(params, "--reference-doc") && !util.ISMicrosoftStore {+ if !strings.HasPrefix(docxTemplate, "\"") {+ docxTemplate = "\"" + docxTemplate + "\""+ }+ params += " --reference-doc " + docxTemplate+ c.Export.Load().PandocParams = strings.TrimSpace(params)+ }+ c.Export.Load().DocxTemplate = ""+ return true, nil+ }},+ {5, "pandoc", func(c *AppConf, raw []byte) (bool, error) {+ // 移除指向临时目录的 Pandoc 路径和内置模板参数+ return migratePandocConfig(c.Export.Load()), nil+ }},+ {6, "exportBlockRefMode", func(c *AppConf, raw []byte) (bool, error) {+ return conf.MigrateExportBlockRefMode(c.Export.Load()), nil+ }},+}++// CurrentConfVersion 是本内核支持的最高配置版本。+var CurrentConfVersion = confMigrations[len(confMigrations)-1].version++// applyConfMigrations 执行配置版本之后登记的迁移并更新版本号,返回是否修改了配置。+// 配置版本高于本内核时视为由更新的内核写入:不执行迁移、不降低版本号,也不拒绝该配置。+func applyConfMigrations(c *AppConf, raw []byte) (changed bool) {+ if c.ConfVersion > CurrentConfVersion {+ logging.LogWarnf("conf version [%d] is newer than kernel supported version [%d], skip migrations", c.ConfVersion, CurrentConfVersion)+ return false+ }+ for _, migration := range confMigrations {+ if migration.version <= c.ConfVersion {+ continue+ }+ applied, err := migration.apply(c, raw)+ if err != nil {+ logging.LogWarnf("migrate conf [%s] failed, retry on next load: %s", migration.name, err)+ return changed+ }+ c.ConfVersion = migration.version+ changed = true+ if applied {+ logging.LogInfof("migrated conf [%s] to version [%d]", migration.name, migration.version)+ }+ }+ return+}++// ApplyImportedConfMigrations 对导入的配置执行与启动加载相同的迁移。+func ApplyImportedConfMigrations(c *AppConf, raw []byte) {+ applyConfMigrations(c, raw)+}diff --git a/kernel/model/conf_normalize.go b/kernel/model/conf_normalize.gonew file mode 100644index 0000000000..f9143ec11f--- /dev/null+++ b/kernel/model/conf_normalize.go@@ -0,0 +1,62 @@+// 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 (+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// NormalizeAppConf 对全部持久化配置段执行规范化,导入设置等整体写入路径使用。+func NormalizeAppConf(c *AppConf) {+ normalizeAppConf(c)+}++// normalizeAppConf 对全部持久化配置段执行规范化,启动加载、设置重置和写入路径共用同一组规则。+// 返回闪卡权重修复原因,由调用方决定是否提示用户。+func normalizeAppConf(c *AppConf) (flashcardWarning string) {+ c.Appearance.Store(conf.NormalizeAppearance(c.Appearance.Load(), util.IsMobileContainer()))+ c.UILayout.Store(conf.NormalizeUILayout(c.UILayout.Load()))+ c.Keymap.Store(conf.NormalizeKeymap(c.Keymap.Load()))+ c.FileTree.Store(conf.NormalizeFileTree(c.FileTree.Load()))+ c.Tag.Store(conf.NormalizeTag(c.Tag.Load()))+ c.Editor.Store(conf.NormalizeEditor(c.Editor.Load()))+ c.Export.Store(conf.NormalizeExport(c.Export.Load()))+ c.Graph.Store(conf.NormalizeGraph(c.Graph.Load()))+ c.System.Store(conf.NormalizeSystem(c.System.Load()))+ c.Onboarding.Store(conf.NormalizeOnboarding(c.Onboarding.Load()))+ c.Snippet.Store(conf.NormalizeSnippet(c.Snippet.Load()))+ c.Sync.Store(conf.NormalizeSync(c.Sync.Load()))+ c.Api.Store(conf.NormalizeAPI(c.Api.Load()))+ c.Bazaar.Store(conf.NormalizeBazaar(c.Bazaar.Load()))+ c.Publish.Store(conf.NormalizePublish(c.Publish.Load()))+ c.Repo.Store(conf.NormalizeRepo(c.Repo.Load()))+ c.NotebookCrypto = conf.NormalizeNotebookCrypto(c.NotebookCrypto)+ c.Search.Store(conf.NormalizeSearch(c.Search.Load()))+ c.Stat.Store(conf.NormalizeStat(c.Stat.Load()))+ {+ confSectionValue0, confSectionValue1 := conf.NormalizeFlashcard(c.Flashcard.Load())+ c.Flashcard.Store(confSectionValue0)+ flashcardWarning = confSectionValue1+ }+ c.OCR.Store(conf.NormalizeOCR(c.OCR.Load()))+ c.AI.Store(conf.NormalizeAI(c.AI.Load()))+ c.OIDC = conf.NormalizeOIDC(c.OIDC)+ c.Secrets.Store(conf.NormalizeSecrets(c.Secrets.Load()))+ c.Variables.Store(conf.NormalizeVariables(c.Variables.Load()))+ return+}diff --git a/kernel/model/conf_notify.go b/kernel/model/conf_notify.gonew file mode 100644index 0000000000..f37e277b0f--- /dev/null+++ b/kernel/model/conf_notify.go@@ -0,0 +1,30 @@+package model++import (+ "sync"+ "sync/atomic"++ "github.com/siyuan-note/siyuan/kernel/util"+)++var ConfSettingRevision atomic.Uint64+var confNamespaceRevisions sync.Map++func ConfNamespaceRevision(namespace string) uint64 {+ value, ok := confNamespaceRevisions.Load(namespace)+ if !ok {+ return 0+ }+ return value.(*atomic.Uint64).Load()+}++// NotifyConfChanged 统一发布配置提交通知,不在事件中携带配置或凭据。+func NotifyConfChanged(namespace string) {+ revision := ConfSettingRevision.Add(1)+ value, _ := confNamespaceRevisions.LoadOrStore(namespace, &atomic.Uint64{})+ value.(*atomic.Uint64).Store(revision)+ util.BroadcastByType("main", "settingChanged", 0, "", struct {+ Namespace string `json:"namespace"`+ Revision uint64 `json:"revision"`+ }{namespace, revision})+}diff --git a/kernel/model/conf_patch.go b/kernel/model/conf_patch.gonew file mode 100644index 0000000000..99402b9bfd--- /dev/null+++ b/kernel/model/conf_patch.go@@ -0,0 +1,170 @@+package model++import (+ "bytes"+ "encoding/json"+ "errors"+ "fmt"+ "path/filepath"+ "reflect"+ "strings"+ "time"++ "github.com/88250/gulu"+ "github.com/siyuan-note/dejavu/cloud"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// MergeConfJSON 对象递归合并,数组和 null 整体替换,未知字段由入站契约决定是否接受。+func MergeConfJSON(base, patch []byte) ([]byte, error) {+ var current, changes map[string]json.RawMessage+ if err := json.Unmarshal(base, ¤t); err != nil {+ return nil, err+ }+ if err := json.Unmarshal(patch, &changes); err != nil {+ return nil, err+ }+ if current == nil {+ current = map[string]json.RawMessage{}+ }+ for key, value := range changes {+ if bytes.HasPrefix(bytes.TrimSpace(value), []byte("{")) && bytes.HasPrefix(bytes.TrimSpace(current[key]), []byte("{")) {+ merged, err := MergeConfJSON(current[key], value)+ if err != nil {+ return nil, err+ }+ current[key] = merged+ } else {+ current[key] = value+ }+ }+ return json.Marshal(current)+}++func (spec *SectionSpec[C]) patch(patch []byte) ([]Issue, error) {+ spec.WriteLock.Lock()+ defer spec.WriteLock.Unlock()+ next, err := mergeConfSection(spec.Load(), patch)+ if err != nil {+ return nil, err+ }+ return applySectionLocked(spec, next)+}++func mergeConfSection[C any](current C, patch []byte) (next C, err error) {+ data, err := json.Marshal(current)+ if err != nil {+ return next, err+ }+ data, err = MergeConfJSON(data, patch)+ if err != nil {+ return next, err+ }+ err = json.Unmarshal(data, &next)+ return+}++func ApplyConfPatch(namespace string, patch []byte) ([]Issue, error) {+ spec, ok := SectionSpecByNamespace(namespace)+ if !ok {+ return nil, fmt.Errorf("unsupported configuration section: %s", namespace)+ }+ return spec.patch(patch)+}++// ApplySyncSettingPatch 在来源锁与段写锁内合并,先验证全部改动,再一次性发布配置。+func ApplySyncSettingPatch(patch []byte) ([]Issue, error) {+ release := lockAssetSourceChange()+ defer release()+ spec := newSectionSpec("sync", &Conf.Sync, conf.NormalizeSync)+ spec.WriteLock.Lock()+ defer spec.WriteLock.Unlock()+ old := spec.Load()+ next, err := mergeConfSection(old, patch)+ if err != nil {+ return nil, err+ }+ if next.Provider != old.Provider {+ return nil, errors.New("use setSyncProvider to change the sync provider")+ }+ if util.ContainerDocker == util.Container {+ next.Perception = false+ }+ if !reflect.DeepEqual(old.S3, next.S3) {+ if err = validateSyncS3(next.S3); err != nil {+ return nil, err+ }+ }+ if !reflect.DeepEqual(old.WebDAV, next.WebDAV) {+ if next.WebDAV == nil {+ return nil, errors.New("invalid WebDAV configuration")+ }+ if strings.Contains(strings.ToLower(next.WebDAV.Endpoint), "dav.jianguoyun.com") {+ return nil, errors.New(Conf.Language(194))+ }+ }+ if !reflect.DeepEqual(old.Local, next.Local) {+ if err = validateSyncLocal(next.Local); err != nil {+ return nil, err+ }+ }+ if old.CloudName != next.CloudName {+ if old.Provider == conf.ProviderS3 {+ return nil, errors.New(Conf.Language(131))+ }+ if !cloud.IsValidCloudDirName(next.CloudName) {+ return nil, errors.New(Conf.Language(37))+ }+ }+ if next.AssetDownloadMode != 0 && next.AssetDownloadMode != 1 {+ return nil, errors.New("invalid asset download mode")+ }+ if old.AssetDownloadMode != next.AssetDownloadMode && next.AssetDownloadMode == 0 {+ if err = ensureCompleteSyncAssets(nil); err != nil {+ return nil, err+ }+ }+ sourceChanged := old.CloudName != next.CloudName ||+ (old.Provider == conf.ProviderS3 && (next.S3.Endpoint != old.S3.Endpoint || next.S3.Bucket != old.S3.Bucket)) ||+ (old.Provider == conf.ProviderWebDAV && (next.WebDAV.Endpoint != old.WebDAV.Endpoint || next.WebDAV.Username != old.WebDAV.Username)) ||+ (old.Provider == conf.ProviderLocal && filepath.Clean(next.Local.Endpoint) != filepath.Clean(old.Local.Endpoint))+ if sourceChanged {+ if err = requireCompleteAssetDownloads(); err != nil {+ return nil, err+ }+ }+ issues, err := applySectionLocked(spec, next)+ if err != nil {+ return issues, err+ }+ refreshLANSyncManager()+ if old.Interval != next.Interval {+ planSyncAfter(time.Duration(next.Interval) * time.Second)+ }+ if old.Perception != next.Perception {+ if next.Perception {+ connectSyncWebSocket()+ } else {+ closeSyncWebSocket()+ }+ }+ return issues, nil+}++func validateSyncLocal(local *conf.Local) error {+ if local == nil {+ return errors.New("invalid local sync configuration")+ }+ absPath, err := filepath.Abs(util.NormalizeLocalPath(local.Endpoint))+ if err != nil {+ return fmt.Errorf(Conf.Language(77), err.Error())+ }+ if !gulu.File.IsExist(absPath) {+ return fmt.Errorf(Conf.Language(77), fmt.Sprintf("endpoint [%s] not exist", local.Endpoint))+ }+ if util.IsAbsPathInWorkspace(absPath) || filepath.Clean(absPath) == filepath.Clean(util.WorkspaceDir) || gulu.File.IsSubPath(absPath, util.WorkspaceDir) {+ return fmt.Errorf(Conf.Language(77), fmt.Sprintf("endpoint [%s] overlaps workspace", local.Endpoint))+ }+ return nil+}diff --git a/kernel/model/conf_regression_test.go b/kernel/model/conf_regression_test.gonew file mode 100644index 0000000000..6170abb0a1--- /dev/null+++ b/kernel/model/conf_regression_test.go@@ -0,0 +1,183 @@+package model++import (+ "bytes"+ "encoding/json"+ "os"+ "path/filepath"+ "reflect"+ "sync"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestConfAllSectionsShareStartupAndWriteNormalization(t *testing.T) {+ prepareConfConsistencyTest(t)+ raw := []byte(`{"editor":{"fontSize":200},"sync":{"interval":1},"repo":{"indexRetentionDays":0},"ocr":{"provider":"tesseract","model":"tiny"}}`)+ startup := NewAppConf()+ if err := json.Unmarshal(raw, startup); err != nil {+ t.Fatal(err)+ }+ normalizeAppConf(startup)+ for namespace := range confSectionSpecs() {+ t.Run(namespace, func(t *testing.T) {+ Conf = NewAppConf()+ normalizeAppConf(Conf)+ input := NewAppConf()+ if err := json.Unmarshal(raw, input); err != nil {+ t.Fatal(err)+ }+ var value any+ typ := reflect.TypeOf(*input)+ for i := 0; i < typ.NumField(); i++ {+ if jsonFieldName(typ, typ.Field(i).Name) == namespace {+ data, _ := json.Marshal(reflect.ValueOf(input).Elem().Field(i).Interface())+ if err := json.Unmarshal(data, &value); err != nil {+ t.Fatal(err)+ }+ break+ }+ }+ spec, _ := SectionSpecByNamespace(namespace)+ // 路径一致性检查只运行提交规则,领域动作由各功能回归测试覆盖。+ reflect.ValueOf(spec).Elem().FieldByName("Reactions").SetZero()+ if _, err := spec.apply(value); err != nil {+ t.Fatal(err)+ }+ actual, _ := json.Marshal(spec.load())+ var expected []byte+ for i := 0; i < typ.NumField(); i++ {+ if jsonFieldName(typ, typ.Field(i).Name) == namespace {+ expected, _ = json.Marshal(reflect.ValueOf(startup).Elem().Field(i).Interface())+ break+ }+ }+ if !bytes.Equal(actual, expected) {+ t.Fatalf("startup and write differ: %s\n%s", expected, actual)+ }+ })+ }+}++func TestConfMigrationRetriesFailedStorageAndLostVersion(t *testing.T) {+ prepareConfConsistencyTest(t)+ normalizeAppConf(Conf)+ Conf.ConfVersion = 2+ profile := &conf.EntryVisibilityProfile{ID: "custom", Name: "Custom", Entries: map[string]bool{}}+ Conf.Appearance.Load().EntryVisibility.Profiles = append(Conf.Appearance.Load().EntryVisibility.Profiles, profile)+ storage := filepath.Join(util.DataDir, "storage", "local.json")+ if err := os.MkdirAll(filepath.Dir(storage), 0700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(storage, []byte(`{`), 0600); err != nil {+ t.Fatal(err)+ }+ applyConfMigrations(Conf, nil)+ if Conf.ConfVersion != 2 {+ t.Fatal("failed storage migration was marked complete")+ }+ if err := os.WriteFile(storage, []byte(`{"local-slash-frequent-enabled":false}`), 0600); err != nil {+ t.Fatal(err)+ }+ applyConfMigrations(Conf, nil)+ if Conf.ConfVersion != CurrentConfVersion || profile.Entries["editor.slash.menu.frequent"] {+ t.Fatal("storage migration did not retry successfully")+ }+ first, _ := json.Marshal(Conf)+ Conf.ConfVersion = 0+ applyConfMigrations(Conf, first)+ second, _ := json.Marshal(Conf)+ if !bytes.Equal(first, second) {+ t.Fatal("rerunning migrations after losing confVersion changed settings")+ }+}++func TestConfConcurrentReadersHoldCoherentSnapshots(t *testing.T) {+ prepareConfConsistencyTest(t)+ normalizeAppConf(Conf)+ util.ReadOnly = true+ UpdateSyncConf(func(value *conf.Sync) { value.Interval = 100; value.CloudName = "100" })+ var group sync.WaitGroup+ group.Add(2)+ go func() {+ defer group.Done()+ for i := 0; i < 100; i++ {+ UpdateSyncConf(func(value *conf.Sync) { value.Interval = 200; value.CloudName = "200" })+ UpdateSyncConf(func(value *conf.Sync) { value.Interval = 100; value.CloudName = "100" })+ }+ }()+ go func() {+ defer group.Done()+ for i := 0; i < 100000; i++ {+ snapshot := Conf.Sync.Load()+ if snapshot.Interval == 100 && snapshot.CloudName != "100" || snapshot.Interval == 200 && snapshot.CloudName != "200" {+ t.Error("reader observed fields from different commits")+ return+ }+ }+ }()+ group.Wait()+}++func TestConfWritesProjectDerivedStateAndKeepInputsImmutable(t *testing.T) {+ prepareConfConsistencyTest(t)+ normalizeAppConf(Conf)+ previous := Conf.Editor.Load()+ input := cloneConfSection(previous)+ input.Markdown.InlineMath = !previous.Markdown.InlineMath+ input.FontSize = 200+ before := ConfNamespaceRevision("editor")+ if _, err := ApplyConfSection("editor", input); err != nil {+ t.Fatal(err)+ }+ if input.FontSize != 200 || previous.Markdown.InlineMath == input.Markdown.InlineMath && Conf.Editor.Load() == previous {+ t.Fatal("submission changed its input or held snapshot")+ }+ if util.MarkdownSettings.Load() != Conf.Editor.Load().Markdown ||+ util.UseSingleLineSave.Load() != Conf.FileTree.Load().UseSingleLineSave ||+ util.LargeFileWarningSize.Load() != Conf.FileTree.Load().LargeFileWarningSize ||+ util.StatusBarCfg.Load() != Conf.Appearance.Load().StatusBar ||+ util.NotificationsCfg.Load() != Conf.Appearance.Load().Notifications ||+ util.SearchCaseSensitive.Load() != Conf.Search.Load().CaseSensitive ||+ util.SearchHanSensitive.Load() != Conf.Search.Load().HanSensitiveVal() ||+ ConfNamespaceRevision("editor") <= before {+ t.Fatal("configuration commit omitted projection or notification")+ }+}++func TestConfGraphQueryDoesNotMutateHeldSnapshot(t *testing.T) {+ prepareConfConsistencyTest(t)+ normalizeAppConf(Conf)+ held := Conf.Graph.Load()+ before, _ := json.Marshal(held)+ global := cloneConfSection(held.Global)+ global.DailyNote = !global.DailyNote+ Conf.SaveGraphQueryConf(global, nil)+ after, _ := json.Marshal(held)+ if !bytes.Equal(before, after) {+ t.Fatal("graph query changed a held snapshot")+ }+}++func TestConfDirectApplyClonesNestedInputs(t *testing.T) {+ prepareConfConsistencyTest(t)+ normalizeAppConf(Conf)+ util.ReadOnly = true+ input := cloneConfSection(Conf.Editor.Load())+ input.FontSize = 200+ spec := newSectionSpec("editor", &Conf.Editor, conf.NormalizeEditor)+ if _, err := Apply(spec, input); err != nil {+ t.Fatal(err)+ }+ stored := Conf.Editor.Load()+ if input.FontSize != 200 || stored.FontSize == 200 || stored == input || stored.Markdown == input.Markdown {+ t.Fatal("direct submission reused its input during normalization")+ }+ inlineMath := stored.Markdown.InlineMath+ input.Markdown.InlineMath = !inlineMath+ if stored.Markdown.InlineMath != inlineMath {+ t.Fatal("published snapshot still shares nested input data")+ }+}diff --git a/kernel/model/conf_runtime.go b/kernel/model/conf_runtime.gonew file mode 100644index 0000000000..5d4675e8ac--- /dev/null+++ b/kernel/model/conf_runtime.go@@ -0,0 +1,129 @@+// 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 (+ "bytes"+ "runtime"+ "sync/atomic"++ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// persistedConf 记录本进程最近一次生成的配置持久化字节;加密归档据此打包持久化形态,+// 不依赖打包时磁盘上的配置文件。nil 表示本进程尚无已知的持久化配置。+var persistedConf atomic.Pointer[[]byte]++// recordPersistedConf 在生成持久化字节后调用,事务路径在确认提交后发布。+func recordPersistedConf(data []byte) {+ if data == nil {+ persistedConf.Store(nil)+ return+ }+ cloned := bytes.Clone(data)+ persistedConf.Store(&cloned)+}++// lastPersistedConf 返回本进程最近一次生成的持久化形态副本。+func lastPersistedConf() []byte {+ if data := persistedConf.Load(); data != nil {+ return bytes.Clone(*data)+ }+ return nil+}++// applyConfRuntime 是派生运行时状态的唯一投影入口:任一配置写入后都由它从当前配置重新计算全部派生值。+// 缺失的配置段保持对应派生值不变。+func applyConfRuntime(configs ...*AppConf) {+ current := Conf+ if len(configs) > 0 {+ current = configs[0]+ }+ if current == nil {+ return+ }+ confAppearanceSnapshot := current.LoadAppearance()++ confEditorSnapshot := current.LoadEditor()++ confFileTreeSnapshot := current.LoadFileTree()++ if nil != confEditorSnapshot {+ util.MarkdownSettings.Store(confEditorSnapshot.Markdown)+ }+ if nil != confFileTreeSnapshot {+ util.UseSingleLineSave.Store(confFileTreeSnapshot.UseSingleLineSave)+ util.LargeFileWarningSize.Store(confFileTreeSnapshot.LargeFileWarningSize)+ }+ if nil != confAppearanceSnapshot {+ util.StatusBarCfg.Store(confAppearanceSnapshot.StatusBar)+ util.NotificationsCfg.Store(confAppearanceSnapshot.Notifications)+ }+ applySearchRuntime(current)+}++// ApplyConfRuntime 供设置接口在替换配置段后重新投影派生运行时状态。+func ApplyConfRuntime() {+ applyConfRuntime()+}++// ApplySearchRuntime 将搜索配置投影到数据库层。数据库打开前设置的 PRAGMA 不会生效,+// 因此各入口在打开数据库后需要再调用一次。+func ApplySearchRuntime() {+ applySearchRuntime(Conf)+}++func applySearchRuntime(current *AppConf) {+ search := current.LoadSearch()+ if nil == search {+ return+ }+ sql.SetCaseSensitive(search.CaseSensitive)+ sql.SetHanSensitive(search.HanSensitiveVal())+ sql.SetIndexAssetPath(search.IndexAssetPath)+}++// projectSystemEnvironment 将当前进程的运行环境投影到系统配置,这些字段每次启动都按运行环境重新赋值。+func projectSystemEnvironment(system *conf.System) {+ system.KernelVersion = util.Ver+ system.UpdateChannel = loadGlobalUpdateChannel()+ if system.ID == "" || util.ContainerStd == util.Container {+ system.ID = util.GetDeviceID()+ }+ if system.Name == "" || util.ContainerStd == util.Container {+ system.Name = util.GetDeviceName()+ }+ system.DisabledFeatures = util.DisabledFeatures+ if 1 > len(system.DisabledFeatures) {+ system.DisabledFeatures = []string{}+ }+ system.AppDir = util.WorkingDir+ system.ConfDir = util.ConfDir+ system.HomeDir = util.HomeDir+ system.WorkspaceDir = util.WorkspaceDir+ system.DataDir = util.DataDir+ system.Container = util.Container+ system.IsMicrosoftStore = util.ISMicrosoftStore+ if util.ISMicrosoftStore {+ logging.LogInfof("using Microsoft Store edition")+ }+ system.OS = runtime.GOOS+ system.OSPlatform = util.GetOSPlatform()+}diff --git a/kernel/model/conf_save_test.go b/kernel/model/conf_save_test.goindex 6192550ebd..e4d4d9be6e 100644--- a/kernel/model/conf_save_test.go+++ b/kernel/model/conf_save_test.go@@ -37,14 +37,14 @@ func TestSaveUsesEncryptedSnapshot(t *testing.T) {})app := NewAppConf()- app.System = &appconf.System{SafeMode: true}- app.AI = appconf.NewAI()- app.AI.Providers = []*appconf.Provider{{APIKey: "plain-api-key"}}- app.Secrets = &appconf.Secrets{Items: []*appconf.Secret{{Name: "token", Value: "plain-secret"}}}+ app.System.Store(&appconf.System{SafeMode: true})+ app.AI.Store(appconf.NewAI())+ app.AI.Load().Providers = []*appconf.Provider{{APIKey: "plain-api-key"}}+ app.Secrets.Store(&appconf.Secrets{Items: []*appconf.Secret{{Name: "token", Value: "plain-secret"}}})app.MCPOAuth = "encrypted-oauth-data"app.Save()- if app.AI.Providers[0].APIKey != "plain-api-key" || app.Secrets.Items[0].Value != "plain-secret" || !app.System.SafeMode {+ if app.AI.Load().Providers[0].APIKey != "plain-api-key" || app.Secrets.Load().Items[0].Value != "plain-secret" || !app.System.Load().SafeMode {t.Fatalf("live configuration was mutated: %#v", app)}data, err := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))@@ -55,7 +55,7 @@ func TestSaveUsesEncryptedSnapshot(t *testing.T) {if err = gulu.JSON.UnmarshalJSON(data, stored); err != nil {t.Fatal(err)}- if stored.AI.Providers[0].APIKey == "plain-api-key" || stored.Secrets.Items[0].Value == "plain-secret" || stored.System.SafeMode {+ if stored.AI.Load().Providers[0].APIKey == "plain-api-key" || stored.Secrets.Load().Items[0].Value == "plain-secret" || stored.System.Load().SafeMode {t.Fatalf("stored configuration was not sanitized: %#v", stored)}if stored.MCPOAuth != app.MCPOAuth {@@ -93,8 +93,8 @@ func TestGraphQuerySavesOnlyChangedConfiguration(t *testing.T) {util.ConfDir, util.ReadOnly = t.TempDir(), falset.Cleanup(func() { util.ConfDir, util.ReadOnly = oldConfDir, oldReadOnly })app := NewAppConf()- app.Graph = appconf.NewGraph()- global, local := app.Graph.Global, app.Graph.Local+ app.Graph.Store(appconf.NewGraph())+ global, local := app.Graph.Load().Global, app.Graph.Load().Localpath := filepath.Join(util.ConfDir, "conf.json")marker := []byte("unchanged graph query must not serialize configuration")if err := os.WriteFile(path, marker, 0600); err != nil {@@ -102,7 +102,7 @@ func TestGraphQuerySavesOnlyChangedConfiguration(t *testing.T) {}app.SaveGraphQueryConf(appconf.NewGlobalGraph(), appconf.NewLocalGraph())data, err := os.ReadFile(path)- if err != nil || !bytes.Equal(data, marker) || app.Graph.Global != global || app.Graph.Local != local {+ if err != nil || !bytes.Equal(data, marker) || app.Graph.Load().Global != global || app.Graph.Load().Local != local {t.Fatalf("unchanged query saved or replaced configuration: %s, %v", data, err)}for _, globalQuery := range []bool{true, false} {@@ -123,8 +123,8 @@ func TestGraphQuerySavesOnlyChangedConfiguration(t *testing.T) {if err = gulu.JSON.UnmarshalJSON(data, stored); err != nil {t.Fatal(err)}- if stored.Graph.Global.MinRefs != 7 || stored.Graph.Local.DailyNote != !globalQuery {- t.Fatalf("graph change was not persisted: %+v", stored.Graph)+ if stored.Graph.Load().Global.MinRefs != 7 || stored.Graph.Load().Local.DailyNote != !globalQuery {+ t.Fatalf("graph change was not persisted: %+v", stored.Graph.Load())}}}diff --git a/kernel/model/conf_secret_test.go b/kernel/model/conf_secret_test.goindex 725266d263..dacde30d88 100644--- a/kernel/model/conf_secret_test.go+++ b/kernel/model/conf_secret_test.go@@ -57,7 +57,7 @@ func TestGetMaskedConfHidesCookieKeyAndPreservesOIDCSecret(t *testing.T) {func TestHideConfSecretPreservesNotebookCryptoSettings(t *testing.T) {appConf := NewAppConf()appConf.CookieKey = "session-cookie-signing-key"- appConf.System = &conf.System{}+ appConf.System.Store(&conf.System{})kek := bytes.Repeat([]byte{1}, 32)verifier, err := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:kek-verifier"))if err != nil {@@ -105,7 +105,7 @@ func TestHideConfSecretPreservesNotebookCryptoSettings(t *testing.T) {func TestHideConfSecretMasksIncompleteNotebookCryptoAsDisabled(t *testing.T) {appConf := NewAppConf()- appConf.System = &conf.System{}+ appConf.System.Store(&conf.System{})appConf.NotebookCrypto = conf.NewNotebookCrypto()appConf.NotebookCrypto.Enabled = true@@ -118,36 +118,36 @@ func TestHideConfSecretMasksIncompleteNotebookCryptoAsDisabled(t *testing.T) {func TestHideConfSecretHidesAbsolutePaths(t *testing.T) {appConf := NewAppConf()- appConf.Export = &conf.Export{+ appConf.Export.Store(&conf.Export{AddTitle: true,PandocBin: `C:\Users\alice\SiYuan\temp\pandoc\bin\pandoc.exe`,- }- appConf.System = &conf.System{+ })+ appConf.System.Store(&conf.System{KernelVersion: "3.3.0",HomeDir: `C:\Users\alice`,WorkspaceDir: `C:\Users\alice\SiYuan`,AppDir: `C:\Program Files\SiYuan`,ConfDir: `C:\Users\alice\SiYuan\conf`,DataDir: `C:\Users\alice\SiYuan\data`,- }+ })HideConfSecret(appConf)- if "" != appConf.Export.PandocBin {- t.Fatalf("pandoc path was not hidden: %q", appConf.Export.PandocBin)+ if "" != appConf.Export.Load().PandocBin {+ t.Fatalf("pandoc path was not hidden: %q", appConf.Export.Load().PandocBin)}- if !appConf.Export.AddTitle {+ if !appConf.Export.Load().AddTitle {t.Fatal("functional export settings should be preserved")}- if "" != appConf.System.HomeDir ||- "" != appConf.System.WorkspaceDir ||- "" != appConf.System.AppDir ||- "" != appConf.System.ConfDir ||- "" != appConf.System.DataDir {- t.Fatalf("system paths were not hidden: %#v", appConf.System)+ if "" != appConf.System.Load().HomeDir ||+ "" != appConf.System.Load().WorkspaceDir ||+ "" != appConf.System.Load().AppDir ||+ "" != appConf.System.Load().ConfDir ||+ "" != appConf.System.Load().DataDir {+ t.Fatalf("system paths were not hidden: %#v", appConf.System.Load())}- if "3.3.0" != appConf.System.KernelVersion {- t.Fatalf("functional system settings were changed: %#v", appConf.System)+ if "3.3.0" != appConf.System.Load().KernelVersion {+ t.Fatalf("functional system settings were changed: %#v", appConf.System.Load())}}diff --git a/kernel/model/conf_section.go b/kernel/model/conf_section.gonew file mode 100644index 0000000000..e7d8c33ccc--- /dev/null+++ b/kernel/model/conf_section.go@@ -0,0 +1,154 @@+// 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 (+ "encoding/json"++ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// 配置段按快照更新:写入方在配置锁内复制当前段、在副本上修改并规范化后整体替换指针,+// 读方一次取得的段指针在其生命周期内不会被改写,因此同一段内多个字段的读取总是自洽的。++// cloneConfSection 通过 JSON 往返深复制配置段,配置段的全部状态均为可序列化的导出字段。+func cloneConfSection[T any](section *T) *T {+ if section == nil {+ return nil+ }+ data, err := json.Marshal(section)+ if err != nil {+ logging.LogErrorf("clone conf section failed: %s", err)+ return nil+ }+ ret := new(T)+ if err = json.Unmarshal(data, ret); err != nil {+ logging.LogErrorf("clone conf section failed: %s", err)+ return nil+ }+ return ret+}++// updateConfSection 在配置锁内基于 field 当前值的副本执行 mutate,规范化后整体替换并持久化,返回替换后的段。+// mutate 返回 false 时放弃本次修改,不替换也不持久化。+func updateConfSection[T any](field *ConfSection[T], normalize func(*T) *T, mutate func(*T) bool) *T {+ spec := newSectionSpec("", field, normalize)+ // 从注册表取得同一配置段的反应声明。+ for _, registered := range confSectionSpecs() {+ if candidate, ok := registered.(*SectionSpec[*T]); ok && candidate.WriteLock == spec.WriteLock {+ spec = candidate+ break+ }+ }+ spec.WriteLock.Lock()+ defer spec.WriteLock.Unlock()+ next := cloneConfSection(field.Load())+ if next == nil {+ next = normalize(nil)+ }+ if !mutate(next) {+ return field.Load()+ }+ if _, err := applySectionLocked(spec, next); err != nil {+ logging.LogWarnf("update conf section [%s] failed: %s", spec.Namespace, err)+ return field.Load()+ }+ next = field.Load()+ return next+}++func always[T any](mutate func(*T)) func(*T) bool {+ return func(section *T) bool {+ mutate(section)+ return true+ }+}++// UpdateSyncConf 以快照方式更新同步配置段。+func UpdateSyncConf(mutate func(*conf.Sync)) *conf.Sync {+ return updateConfSection(&Conf.Sync, conf.NormalizeSync, always(mutate))+}++// UpdateSystemConf 以快照方式更新系统配置段。+func UpdateSystemConf(mutate func(*conf.System)) *conf.System {+ return updateConfSection(&Conf.System, conf.NormalizeSystem, always(mutate))+}++// UpdateRepoConf 以快照方式更新数据仓库配置段。+func UpdateRepoConf(mutate func(*conf.Repo)) *conf.Repo {+ return updateConfSection(&Conf.Repo, conf.NormalizeRepo, always(mutate))+}++// UpdateEditorConf 以快照方式更新编辑器配置段。+func UpdateEditorConf(mutate func(*conf.Editor)) *conf.Editor {+ return updateConfSection(&Conf.Editor, conf.NormalizeEditor, always(mutate))+}++// UpdateAppearanceConf 以快照方式更新外观配置段。+func UpdateAppearanceConf(mutate func(*conf.Appearance)) *conf.Appearance {+ return updateConfSection(&Conf.Appearance, func(appearance *conf.Appearance) *conf.Appearance {+ return conf.NormalizeAppearance(appearance, util.IsMobileContainer())+ }, always(mutate))+}++// UpdateBazaarConf 以快照方式更新集市配置段。+func UpdateBazaarConf(mutate func(*conf.Bazaar)) *conf.Bazaar {+ return updateConfSection(&Conf.Bazaar, conf.NormalizeBazaar, always(mutate))+}++// UpdateGraphConf 以快照方式更新关系图配置段;mutate 返回 false 表示没有变化。+func UpdateGraphConf(mutate func(*conf.Graph) bool) *conf.Graph {+ return updateConfSection(&Conf.Graph, conf.NormalizeGraph, mutate)+}++// UpdateTagConf 以快照方式更新标签面板配置段。+func UpdateTagConf(mutate func(*conf.Tag)) *conf.Tag {+ return updateConfSection(&Conf.Tag, conf.NormalizeTag, always(mutate))+}++// UpdateAPIConf 以快照方式更新 API 配置段。+func UpdateAPIConf(mutate func(*conf.API)) *conf.API {+ return updateConfSection(&Conf.Api, conf.NormalizeAPI, always(mutate))+}++// UpdatePublishConf 以快照方式更新发布服务配置段。+func UpdatePublishConf(mutate func(*conf.Publish)) *conf.Publish {+ return updateConfSection(&Conf.Publish, conf.NormalizePublish, always(mutate))+}++// UpdateOnboardingConf 以快照方式更新首次使用引导状态。+func UpdateOnboardingConf(mutate func(*conf.Onboarding)) *conf.Onboarding {+ return updateConfSection(&Conf.Onboarding, conf.NormalizeOnboarding, always(mutate))+}++// UpdateStatConf 以快照方式更新统计配置段。+func UpdateStatConf(mutate func(*conf.Stat)) *conf.Stat {+ return updateConfSection(&Conf.Stat, conf.NormalizeStat, always(mutate))+}++// replaceConfSectionLocked 要求调用方已持有配置锁:在 field 当前值的副本上执行 mutate 后整体替换,+// 不做规范化也不持久化。mutate 返回 false 时保持原段不变。+func replaceConfSectionLocked[T any](field *ConfSection[T], mutate func(*T) bool) bool {+ next := cloneConfSection(field.Load())+ if next == nil || !mutate(next) {+ return false+ }+ field.Store(next)+ return true+}diff --git a/kernel/model/conf_snapshot.go b/kernel/model/conf_snapshot.gonew file mode 100644index 0000000000..4d4f065e4c--- /dev/null+++ b/kernel/model/conf_snapshot.go@@ -0,0 +1,254 @@+package model++import (+ "encoding/json"+ "sync"+ "sync/atomic"++ "github.com/siyuan-note/siyuan/kernel/conf"+)++// ConfSection 原子发布不可变配置段,复制容器时不会复制原子变量或写锁。+type ConfSection[T any] struct {+ cell *confSectionCell[T]+}++type confSectionCell[T any] struct {+ value atomic.Pointer[T]+ mu sync.Mutex+}++func NewConfSection[T any](value *T) ConfSection[T] {+ section := ConfSection[T]{cell: &confSectionCell[T]{}}+ section.cell.value.Store(value)+ return section+}++func (section ConfSection[T]) Load() *T {+ if section.cell == nil {+ return nil+ }+ return section.cell.value.Load()+}++// Store 在初始化阶段允许补建容器,发布配置后只原子替换段快照。+func (section *ConfSection[T]) Store(value *T) {+ if section.cell == nil {+ *section = NewConfSection(value)+ return+ }+ section.cell.value.Store(value)+}++func (section ConfSection[T]) MarshalJSON() ([]byte, error) {+ return json.Marshal(section.Load())+}++// SnapshotValue 供配置检查器遍历段内容,不暴露原子容器或互斥实现。+func (section ConfSection[T]) SnapshotValue() any {+ return section.Load()+}++func (section *ConfSection[T]) UnmarshalJSON(data []byte) error {+ var value *T+ if err := json.Unmarshal(data, &value); err != nil {+ return err+ }+ section.Store(value)+ return nil+}++func (section ConfSection[T]) Clone() ConfSection[T] {+ return NewConfSection(cloneConfSection(section.Load()))+}++// cloneSettings 复制配置容器和段内容,保证重置或事务回滚不改写当前快照。+func (c *AppConf) cloneSettings() AppConf {+ next := *c+ next.Appearance = c.Appearance.Clone()+ next.FileTree = c.FileTree.Clone()+ next.Tag = c.Tag.Clone()+ next.Editor = c.Editor.Clone()+ next.Export = c.Export.Clone()+ next.Graph = c.Graph.Clone()+ next.UILayout = c.UILayout.Clone()+ next.System = c.System.Clone()+ next.Keymap = c.Keymap.Clone()+ next.Sync = c.Sync.Clone()+ next.Search = c.Search.Clone()+ next.Flashcard = c.Flashcard.Clone()+ next.AI = c.AI.Clone()+ next.OCR = c.OCR.Clone()+ next.Secrets = c.Secrets.Clone()+ next.Variables = c.Variables.Clone()+ next.Bazaar = c.Bazaar.Clone()+ next.Stat = c.Stat.Clone()+ next.Api = c.Api.Clone()+ next.Repo = c.Repo.Clone()+ next.Publish = c.Publish.Clone()+ next.Onboarding = c.Onboarding.Clone()+ next.Snippet = c.Snippet.Clone()+ return next+}++// 段读取方法允许尚未初始化的配置,调用方在自己的有效性判断之后使用取得的快照。+func (c *AppConf) LoadAppearance() *conf.Appearance {+ if c == nil {+ return nil+ }+ return c.Appearance.Load()+}++func (c *AppConf) LoadFileTree() *conf.FileTree {+ if c == nil {+ return nil+ }+ return c.FileTree.Load()+}++func (c *AppConf) LoadTag() *conf.Tag {+ if c == nil {+ return nil+ }+ return c.Tag.Load()+}++func (c *AppConf) LoadEditor() *conf.Editor {+ if c == nil {+ return nil+ }+ return c.Editor.Load()+}++func (c *AppConf) LoadExport() *conf.Export {+ if c == nil {+ return nil+ }+ return c.Export.Load()+}++func (c *AppConf) LoadGraph() *conf.Graph {+ if c == nil {+ return nil+ }+ return c.Graph.Load()+}++func (c *AppConf) LoadUILayout() *conf.UILayout {+ if c == nil {+ return nil+ }+ return c.UILayout.Load()+}++func (c *AppConf) LoadSystem() *conf.System {+ if c == nil {+ return nil+ }+ return c.System.Load()+}++func (c *AppConf) LoadKeymap() *conf.Keymap {+ if c == nil {+ return nil+ }+ return c.Keymap.Load()+}++func (c *AppConf) LoadSync() *conf.Sync {+ if c == nil {+ return nil+ }+ return c.Sync.Load()+}++func (c *AppConf) LoadSearch() *conf.Search {+ if c == nil {+ return nil+ }+ return c.Search.Load()+}++func (c *AppConf) LoadFlashcard() *conf.Flashcard {+ if c == nil {+ return nil+ }+ return c.Flashcard.Load()+}++func (c *AppConf) LoadAI() *conf.AI {+ if c == nil {+ return nil+ }+ return c.AI.Load()+}++func (c *AppConf) LoadOCR() *conf.OCR {+ if c == nil {+ return nil+ }+ return c.OCR.Load()+}++func (c *AppConf) LoadSecrets() *conf.Secrets {+ if c == nil {+ return nil+ }+ return c.Secrets.Load()+}++func (c *AppConf) LoadVariables() *conf.Variables {+ if c == nil {+ return nil+ }+ return c.Variables.Load()+}++func (c *AppConf) LoadBazaar() *conf.Bazaar {+ if c == nil {+ return nil+ }+ return c.Bazaar.Load()+}++func (c *AppConf) LoadStat() *conf.Stat {+ if c == nil {+ return nil+ }+ return c.Stat.Load()+}++func (c *AppConf) LoadApi() *conf.API {+ if c == nil {+ return nil+ }+ return c.Api.Load()+}++func (c *AppConf) LoadRepo() *conf.Repo {+ if c == nil {+ return nil+ }+ return c.Repo.Load()+}++func (c *AppConf) LoadPublish() *conf.Publish {+ if c == nil {+ return nil+ }+ return c.Publish.Load()+}++func (c *AppConf) LoadOnboarding() *conf.Onboarding {+ if c == nil {+ return nil+ }+ return c.Onboarding.Load()+}++func (c *AppConf) LoadSnippet() *conf.Snpt {+ if c == nil {+ return nil+ }+ return c.Snippet.Load()+}diff --git a/kernel/model/conf_spec.go b/kernel/model/conf_spec.gonew file mode 100644index 0000000000..1c07fb7629--- /dev/null+++ b/kernel/model/conf_spec.go@@ -0,0 +1,145 @@+package model++import (+ "encoding/json"+ "fmt"+ "reflect"+ "sync"++ "github.com/siyuan-note/siyuan/kernel/util"+)++// Issue 描述配置字段诊断,error 阻断提交,warning 随成功结果返回。+type Issue struct {+ Field string `json:"field"`+ Severity string `json:"severity"`+ Message string `json:"message"`+}++type ValidationError struct{ Issues []Issue }++func (err *ValidationError) Error() string {+ for _, issue := range err.Issues {+ if issue.Severity == "error" {+ return issue.Message+ }+ }+ return "invalid configuration"+}++type Reaction[C any] struct {+ Name string+ Changed func(old, next C) bool+ Apply func(old, next C)+}++// SectionSpec 集中描述配置段规范化、诊断和反应,写锁仅属于该配置段。+type SectionSpec[C any] struct {+ Config *AppConf+ Namespace string+ Load func() C+ Store func(C)+ Normalize func(C) C+ Validate func(C) []Issue+ WriteLock *sync.Mutex+ Reactions []Reaction[C]+}++type registeredSection interface {+ apply(any) ([]Issue, error)+ patch([]byte) ([]Issue, error)+ load() any+}++func (spec *SectionSpec[C]) load() any { return spec.Load() }++func (spec *SectionSpec[C]) apply(value any) ([]Issue, error) {+ data, err := json.Marshal(value)+ if err != nil {+ return nil, err+ }+ var next C+ if err = json.Unmarshal(data, &next); err != nil {+ return nil, err+ }+ return Apply(spec, next)+}++// Apply 在段写锁下完成规范化和诊断,再持配置锁发布并同步落盘。+// 反应在配置锁外执行,允许动作读取配置或更新领域状态。+func Apply[C any](spec *SectionSpec[C], next C) ([]Issue, error) {+ spec.WriteLock.Lock()+ defer spec.WriteLock.Unlock()+ return applySectionLocked(spec, next)+}++func applySectionLocked[C any](spec *SectionSpec[C], next C) ([]Issue, error) {+ old := spec.Load()+ data, err := json.Marshal(next)+ if err != nil {+ return nil, err+ }+ var cloned C+ if err = json.Unmarshal(data, &cloned); err != nil {+ return nil, err+ }+ next = cloned+ next = spec.Normalize(next)+ var issues []Issue+ if spec.Validate != nil {+ issues = spec.Validate(next)+ for _, issue := range issues {+ if issue.Severity == "error" {+ return issues, &ValidationError{issues}+ }+ }+ }+ current := spec.Config+ if current == nil {+ current = Conf+ }+ current.m.Lock()+ spec.Store(next)+ applyConfRuntime(current)+ if !util.ReadOnly {+ current.saveLocked()+ }+ current.m.Unlock()+ for _, reaction := range spec.Reactions {+ if !reflect.ValueOf(old).IsZero() && reaction.Changed(old, next) {+ reaction.Apply(old, next)+ }+ }+ if current == Conf {+ NotifyConfChanged(spec.Namespace)+ }+ return issues, nil+}++func newSectionSpec[T any](namespace string, field *ConfSection[T], normalize func(*T) *T,+ reactions ...Reaction[*T]) *SectionSpec[*T] {+ return newSectionSpecFor(Conf, namespace, field, normalize, reactions...)+}++func newSectionSpecFor[T any](current *AppConf, namespace string, field *ConfSection[T], normalize func(*T) *T,+ reactions ...Reaction[*T]) *SectionSpec[*T] {+ if field.cell == nil {+ field.Store(nil)+ }+ return &SectionSpec[*T]{Config: current, Namespace: namespace, Load: field.Load, Store: field.Store,+ Normalize: normalize, WriteLock: &field.cell.mu, Reactions: reactions}+}++// SectionSpecByNamespace 返回当前工作空间的注册项,不缓存可替换的 AppConf 地址。+func SectionSpecByNamespace(namespace string) (registeredSection, bool) {+ spec, ok := confSectionSpecs()[namespace]+ return spec, ok+}++func ApplyConfSection(namespace string, value any) ([]Issue, error) {+ spec, ok := SectionSpecByNamespace(namespace)+ if !ok {+ return nil, fmt.Errorf("unsupported configuration section: %s", namespace)+ }+ return spec.apply(value)+}diff --git a/kernel/model/conf_specs.go b/kernel/model/conf_specs.gonew file mode 100644index 0000000000..0a1e3d3a96--- /dev/null+++ b/kernel/model/conf_specs.go@@ -0,0 +1,170 @@+package model++import (+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/task"+ "github.com/siyuan-note/siyuan/kernel/util"+ "sync/atomic"+)++func confSectionSpecs() map[string]registeredSection {+ return map[string]registeredSection{+ "appearance": appearanceSectionSpec(),+ "fileTree": newSectionSpec("fileTree", &Conf.FileTree, conf.NormalizeFileTree, fileTreeReactions()...),+ "tag": newSectionSpec("tag", &Conf.Tag, conf.NormalizeTag),+ "editor": newSectionSpec("editor", &Conf.Editor, conf.NormalizeEditor, editorReactions()...),+ "export": newSectionSpec("export", &Conf.Export, conf.NormalizeExport, exportReactions()...),+ "graph": newSectionSpec("graph", &Conf.Graph, conf.NormalizeGraph),+ "uiLayout": newSectionSpec("uiLayout", &Conf.UILayout, conf.NormalizeUILayout),+ "system": newSectionSpec("system", &Conf.System, conf.NormalizeSystem, systemReactions()...),+ "keymap": newSectionSpec("keymap", &Conf.Keymap, conf.NormalizeKeymap),+ "sync": newSectionSpec("sync", &Conf.Sync, conf.NormalizeSync),+ "search": newSectionSpec("search", &Conf.Search, conf.NormalizeSearch, searchReactions()...),+ "flashcard": flashcardSectionSpec(),+ "ai": newSectionSpec("ai", &Conf.AI, conf.NormalizeAI),+ "ocr": ocrSectionSpec(),+ "secrets": newSectionSpec("secrets", &Conf.Secrets, conf.NormalizeSecrets),+ "variables": newSectionSpec("variables", &Conf.Variables, conf.NormalizeVariables),+ "bazaar": newSectionSpec("bazaar", &Conf.Bazaar, conf.NormalizeBazaar, bazaarReactions()...),+ "stat": newSectionSpec("stat", &Conf.Stat, conf.NormalizeStat),+ "api": newSectionSpec("api", &Conf.Api, conf.NormalizeAPI),+ "repo": newSectionSpec("repo", &Conf.Repo, conf.NormalizeRepo),+ "publish": publishSectionSpec(),+ "onboarding": newSectionSpec("onboarding", &Conf.Onboarding, conf.NormalizeOnboarding),+ "snippet": newSectionSpec("snippet", &Conf.Snippet, conf.NormalizeSnippet, Reaction[*conf.Snpt]{Name: "reload-snippet", Changed: func(old, next *conf.Snpt) bool { return true }, Apply: func(old, next *conf.Snpt) { PushReloadSnippet(next) }}),+ }+}++var BazaarPetalStateRevision atomic.Uint64++func bazaarReactions() []Reaction[*conf.Bazaar] {+ return []Reaction[*conf.Bazaar]{{Name: "petal-state", Changed: func(old, next *conf.Bazaar) bool {+ return petalsEnabled(old) != petalsEnabled(next) || old.PetalDisabled != next.PetalDisabled+ }, Apply: func(old, next *conf.Bazaar) {+ enabled := petalsEnabled(next)+ if petalsEnabled(old) != enabled {+ if enabled && OnKernelPluginsStart != nil {+ OnKernelPluginsStart()+ }+ if !enabled && OnKernelPluginsStop != nil {+ OnKernelPluginsStop()+ }+ }+ PushReloadAllEnabledPlugins(enabled, next.PetalDisabled, BazaarPetalStateRevision.Add(1), true)+ }}}+}++func appearanceSectionSpec() *SectionSpec[*conf.Appearance] {+ spec := newSectionSpec("appearance", &Conf.Appearance, func(value *conf.Appearance) *conf.Appearance {+ return conf.NormalizeAppearance(value, util.IsMobileContainer())+ }, Reaction[*conf.Appearance]{Name: "appearance-resources", Changed: func(old, next *conf.Appearance) bool {+ return old.Lang != next.Lang || old.Icon != next.Icon || old.ThemeLight != next.ThemeLight ||+ old.ThemeDark != next.ThemeDark || old.Mode != next.Mode || old.ModeOS != next.ModeOS+ }, Apply: func(old, next *conf.Appearance) {+ InitAppearance()+ WatchThemes()+ util.BroadcastByType("main", "setAppearance", 0, "", Conf.Appearance.Load())+ }})+ spec.Store = func(value *conf.Appearance) {+ Conf.Appearance.Store(value)+ Conf.Lang = util.LangToBCP47(value.Lang)+ util.Lang = Conf.Lang+ }+ return spec+}++func systemReactions() []Reaction[*conf.System] {+ return []Reaction[*conf.System]{{Name: "network-proxy", Changed: func(old, next *conf.System) bool {+ return old.NetworkProxy == nil || old.NetworkProxy.String() != next.NetworkProxy.String() ||+ old.NetworkProxy.IsSystem() != next.NetworkProxy.IsSystem()+ }, Apply: func(old, next *conf.System) {+ util.SetNetworkProxy(next.NetworkProxy.String(), next.NetworkProxy.IsSystem())+ }}}+}++func flashcardSectionSpec() *SectionSpec[*conf.Flashcard] {+ var warning string+ spec := newSectionSpec("flashcard", &Conf.Flashcard, func(value *conf.Flashcard) *conf.Flashcard {+ value, warning = conf.NormalizeFlashcard(value)+ return value+ })+ spec.Validate = func(value *conf.Flashcard) []Issue {+ if warning != "" {+ return []Issue{{Field: "flashcard.weights", Severity: "warning", Message: warning}}+ }+ return nil+ }+ return spec+}++// publishSectionSpec 在所有写入路径校验启用的认证账户,失败时保留现有凭据。+func publishSectionSpec() *SectionSpec[*conf.Publish] {+ spec := newSectionSpec("publish", &Conf.Publish, conf.NormalizePublish)+ spec.Validate = func(value *conf.Publish) []Issue {+ if !value.Auth.Enable {+ return nil+ }+ usernames := map[string]bool{}+ for _, account := range value.Auth.Accounts {+ key := 0+ if account == nil || account.Username == "" {+ key = 361+ } else if usernames[account.Username] {+ key = 362+ } else if len(account.Password) < 8 {+ key = 363+ }+ if key != 0 {+ return []Issue{{Field: "publish.auth.accounts", Severity: "error", Message: Conf.Language(key)}}+ }+ usernames[account.Username] = true+ }+ return nil+ }+ return spec+}++func editorReactions() []Reaction[*conf.Editor] {+ return []Reaction[*conf.Editor]{+ {Name: "history-interval", Changed: func(old, next *conf.Editor) bool { return old.GenerateHistoryInterval != next.GenerateHistoryInterval }, Apply: func(old, next *conf.Editor) { GenerateFileHistory(); ChangeHistoryTick(next.GenerateHistoryInterval) }},+ {Name: "virtual-block-ref", Changed: func(old, next *conf.Editor) bool {+ return old.VirtualBlockRef != next.VirtualBlockRef || old.VirtualBlockRefInclude != next.VirtualBlockRefInclude || old.VirtualBlockRefExclude != next.VirtualBlockRefExclude+ }, Apply: func(old, next *conf.Editor) { ResetVirtualBlockRefCache() }},+ {Name: "readonly", Changed: func(old, next *conf.Editor) bool { return old.ReadOnly != next.ReadOnly }, Apply: func(old, next *conf.Editor) {+ util.BroadcastByType("protyle", "readonly", 0, "", next.ReadOnly)+ util.BroadcastByType("main", "readonly", 0, "", next.ReadOnly)+ }},+ }+}++func fileTreeReactions() []Reaction[*conf.FileTree] {+ return []Reaction[*conf.FileTree]{+ {Name: "sort", Changed: func(old, next *conf.FileTree) bool { return old.Sort != next.Sort }, Apply: func(old, next *conf.FileTree) { PushDocSortModeChanged("global", "", "", "/", &next.Sort) }},+ {Name: "box-document", Changed: func(old, next *conf.FileTree) bool {+ return (old.BoxDocEnabled != nil && *old.BoxDocEnabled) != (next.BoxDocEnabled != nil && *next.BoxDocEnabled)+ }, Apply: func(old, next *conf.FileTree) { RefreshBoxDocFeature() }},+ }+}++func searchReactions() []Reaction[*conf.Search] {+ return []Reaction[*conf.Search]{+ {Name: "index", Changed: func(old, next *conf.Search) bool {+ return old.CaseSensitive != next.CaseSensitive || old.HanSensitiveVal() != next.HanSensitiveVal() || old.IndexAssetPath != next.IndexAssetPath+ }, Apply: func(old, next *conf.Search) {+ if old.IndexAssetPath == next.IndexAssetPath {+ task.AppendTask(task.DatabaseIndexFTS, ReindexFTS)+ } else {+ FullReindex(false)+ }+ }},+ {Name: "virtual-block-ref", Changed: func(old, next *conf.Search) bool {+ return old.VirtualRefName != next.VirtualRefName || old.VirtualRefAlias != next.VirtualRefAlias || old.VirtualRefAnchor != next.VirtualRefAnchor || old.VirtualRefDoc != next.VirtualRefDoc+ }, Apply: func(old, next *conf.Search) { ResetVirtualBlockRefCache() }},+ }+}++func exportReactions() []Reaction[*conf.Export] {+ return []Reaction[*conf.Export]{+ {Name: "pandoc", Changed: func(old, next *conf.Export) bool { return old.PandocBin != next.PandocBin }, Apply: func(old, next *conf.Export) { util.InitPandoc(next.PandocBin) }},+ }+}diff --git a/kernel/model/crypto.go b/kernel/model/crypto.goindex cc210fc181..b338dc2621 100644--- a/kernel/model/crypto.go+++ b/kernel/model/crypto.go@@ -1884,7 +1884,11 @@ func finishMasterPasswordMigration(kek []byte) error {if err != nil {return err}- return atomicWriteFile(filepath.Join(util.ConfDir, "conf.json"), data)+ if err = atomicWriteFile(filepath.Join(util.ConfDir, "conf.json"), data); err != nil {+ return err+ }+ recordPersistedConf(data)+ return nil}()if err != nil {return fmt.Errorf("save notebook crypto configuration failed: %w", err)diff --git a/kernel/model/crypto_create_sqlcipher_test.go b/kernel/model/crypto_create_sqlcipher_test.goindex f942a9f36a..b73500d476 100644--- a/kernel/model/crypto_create_sqlcipher_test.go+++ b/kernel/model/crypto_create_sqlcipher_test.go@@ -73,10 +73,10 @@ func testCreateEncryptedBoxInitializesBoxDocument(t *testing.T) {}Conf = NewAppConf()- Conf.FileTree = conf.NewFileTree()- *Conf.FileTree.BoxDocEnabled = true+ Conf.FileTree.Store(conf.NewFileTree())+ *Conf.FileTree.Load().BoxDocEnabled = trueConf.NotebookCrypto = conf.NewNotebookCrypto()- Conf.Sync = conf.NewSync()+ Conf.Sync.Store(conf.NewSync())sql.InitDatabase(true)sql.InitHistoryDatabase(true)sql.InitAssetContentDatabase(true)diff --git a/kernel/model/crypto_lifecycle_test.go b/kernel/model/crypto_lifecycle_test.goindex 8d7fca0374..ecb710cfee 100644--- a/kernel/model/crypto_lifecycle_test.go+++ b/kernel/model/crypto_lifecycle_test.go@@ -331,7 +331,7 @@ func TestMissingEncryptedIdentityNeverFallsBackToNormalNotebook(t *testing.T) {oldConf := Confutil.DataDir = t.TempDir()Conf = NewAppConf()- Conf.FileTree = conf.NewFileTree()+ Conf.FileTree.Store(conf.NewFileTree())boxID := "20260731160100-abcdefg"defer func() {forgetRuntimeEncryptedBox(boxID)@@ -380,7 +380,7 @@ func TestMissingEncryptedIdentityNeverFallsBackToNormalNotebook(t *testing.T) {func TestNotebookBackupPreventsNormalIdentityDowngrade(t *testing.T) {oldConf := ConfConf = NewAppConf()- Conf.FileTree = conf.NewFileTree()+ Conf.FileTree.Store(conf.NewFileTree())defer func() {Conf = oldConf}()@@ -513,7 +513,7 @@ func TestEncryptedBoxMetadataIsNotStoredInPlaintext(t *testing.T) {func TestListNotebooksDoesNotInheritEncryptedOpenState(t *testing.T) {oldConf := ConfConf = NewAppConf()- Conf.FileTree = conf.NewFileTree()+ Conf.FileTree.Store(conf.NewFileTree())defer func() {Conf = oldConf}()diff --git a/kernel/model/crypto_regression_test.go b/kernel/model/crypto_regression_test.goindex 55e2f0fec5..04dd1b6c29 100644--- a/kernel/model/crypto_regression_test.go+++ b/kernel/model/crypto_regression_test.go@@ -145,7 +145,7 @@ func TestPasswordChangePreservesDeletedHistoryRecovery(t *testing.T) {}Conf = NewAppConf()Conf.NotebookCrypto = conf.NewNotebookCrypto()- Conf.Sync = conf.NewSync()+ Conf.Sync.Store(conf.NewSync())if err := EnableEncryptedNotebook("old-review-password"); err != nil {t.Fatal(err)}@@ -304,7 +304,11 @@ func TestMasterPasswordMigrationRetainsHistoryKeysAfterBoxRemoval(t *testing.T)}}Conf = NewAppConf()- Conf.NotebookCrypto, Conf.Sync = conf.NewNotebookCrypto(), conf.NewSync()+ {+ confSectionValue0, confSectionValue1 := conf.NewNotebookCrypto(), conf.NewSync()+ Conf.NotebookCrypto = confSectionValue0+ Conf.Sync.Store(confSectionValue1)+ }if err := EnableEncryptedNotebook("migration-old"); err != nil {t.Fatal(err)}diff --git a/kernel/model/crypto_system_lock.go b/kernel/model/crypto_system_lock.goindex 41250e594a..363e255a4e 100644--- a/kernel/model/crypto_system_lock.go+++ b/kernel/model/crypto_system_lock.go@@ -1,16 +1,16 @@package model+import "github.com/siyuan-note/siyuan/kernel/conf"+// SetEncryptedNotebookFollowSystemLock 将锁屏策略保存在本机系统配置中,不参与密钥备份认证。func SetEncryptedNotebookFollowSystemLock(enabled bool) {- Conf.m.Lock()- Conf.System.EncryptedNotebookFollowSystemLock = enabled- Conf.m.Unlock()+ UpdateSystemConf(func(s *conf.System) { s.EncryptedNotebookFollowSystemLock = enabled })}// LockEncryptedNotebooksOnSystemLock 等待正在解锁的笔记本完成,再复用卸载流程保存内容并清除密钥。func LockEncryptedNotebooksOnSystemLock() {Conf.m.RLock()- enabled := Conf.System.EncryptedNotebookFollowSystemLock+ enabled := Conf.System.Load().EncryptedNotebookFollowSystemLockConf.m.RUnlock()if !enabled {returndiff --git a/kernel/model/crypto_test.go b/kernel/model/crypto_test.goindex 3fe26a03e4..d8bd28f2fb 100644--- a/kernel/model/crypto_test.go+++ b/kernel/model/crypto_test.go@@ -389,7 +389,7 @@ func TestRestoreNotebookCryptoConfigFromExistingBackup(t *testing.T) {}Conf = NewAppConf()Conf.NotebookCrypto = conf.NewNotebookCrypto()- Conf.Sync = conf.NewSync()+ Conf.Sync.Store(conf.NewSync())defer func() {Conf = originalConfutil.DataDir = originalDataDir@@ -1122,7 +1122,7 @@ func TestEnableEncryptedNotebookRestoresConfigWhenBackupWriteFails(t *testing.T)}Conf = NewAppConf()Conf.NotebookCrypto = conf.NewNotebookCrypto()- Conf.FileTree = conf.NewFileTree()+ Conf.FileTree.Store(conf.NewFileTree())util.DataDir = dataDirutil.HistoryDir = filepath.Join(dataDir, "history")defer func() {diff --git a/kernel/model/delete_stress_fts5_test.go b/kernel/model/delete_stress_fts5_test.goindex f141a8416e..ee2d9759d7 100644--- a/kernel/model/delete_stress_fts5_test.go+++ b/kernel/model/delete_stress_fts5_test.go@@ -33,7 +33,7 @@ func TestRapidDeletionLargeIndex(t *testing.T) {}f := setupStructureTransactionTest(t)setupFoldTransactionDatabase(t, f)- Conf.Search = conf.NewSearch()+ Conf.Search.Store(conf.NewSearch())source, err := LoadTreeByBlockID(f.sourceID)if err != nil {t.Fatal(err)diff --git a/kernel/model/document_history_fts5_test.go b/kernel/model/document_history_fts5_test.goindex 34c9660878..1e38062abc 100644--- a/kernel/model/document_history_fts5_test.go+++ b/kernel/model/document_history_fts5_test.go@@ -42,7 +42,7 @@ func TestBatchDocumentWritesInvalidateHistory(t *testing.T) {t.Run(action, func(t *testing.T) {fixture := setupStructureTransactionTest(t)setupFoldTransactionDatabase(t, fixture)- Conf.Search = conf.NewSearch()+ Conf.Search.Store(conf.NewSearch())tree, err := LoadTreeByBlockID(fixture.sourceID)if err != nil {t.Fatal(err)diff --git a/kernel/model/document_stat.go b/kernel/model/document_stat.goindex 45a3316b3a..2973001b2f 100644--- a/kernel/model/document_stat.go+++ b/kernel/model/document_stat.go@@ -74,6 +74,8 @@ type documentEmbedStatResolver struct {// GetDocumentStat 统计文档,并按需解析查询嵌入块。func GetDocumentStat(ctx context.Context, id, boxID string, includeEmbed bool, accessChecker EmbedBlockAccessChecker) (ret *DocumentStat) {+ confSearchSnapshot := Conf.LoadSearch()+tree := loadDocumentStatTree(id, boxID)if nil == tree {return@@ -95,8 +97,8 @@ func GetDocumentStat(ctx context.Context, id, boxID string, includeEmbed bool, a}queryLimit := 64- if nil != Conf && nil != Conf.Search && 0 < Conf.Search.Limit {- queryLimit = Conf.Search.Limit+ if nil != Conf && nil != confSearchSnapshot && 0 < confSearchSnapshot.Limit {+ queryLimit = confSearchSnapshot.Limit}resolver := &documentEmbedStatResolver{ctx: ctx,@@ -300,8 +302,10 @@ func documentStatEmbedStatement(embed *ast.Node) (stmt string, ok bool) {}func documentStatHeadingMode(embed *ast.Node) (ret int) {- if nil != Conf && nil != Conf.Editor {- ret = Conf.Editor.HeadingEmbedMode+ confEditorSnapshot := Conf.LoadEditor()++ if nil != Conf && nil != confEditorSnapshot {+ ret = confEditorSnapshot.HeadingEmbedMode}if nil == embed {returndiff --git a/kernel/model/document_stat_test.go b/kernel/model/document_stat_test.goindex 5e95c46768..ae09499051 100644--- a/kernel/model/document_stat_test.go+++ b/kernel/model/document_stat_test.go@@ -220,8 +220,8 @@ func documentStatTestResolver(tree *parse.Tree, stat *util.BlockStatResult, infofunc setDocumentStatTestConf(t *testing.T) {previousConf := ConfConf = NewAppConf()- Conf.Editor = conf.NewEditor()- Conf.Search = conf.NewSearch()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Search.Store(conf.NewSearch())t.Cleanup(func() {Conf = previousConf})diff --git a/kernel/model/duplicate_doc_hpath_test.go b/kernel/model/duplicate_doc_hpath_test.goindex 0679411a88..df86abbe40 100644--- a/kernel/model/duplicate_doc_hpath_test.go+++ b/kernel/model/duplicate_doc_hpath_test.go@@ -37,7 +37,7 @@ func TestDuplicateDocHPath(t *testing.T) {return}prepareHPathRefreshTest(t)- Conf.Flashcard = conf.NewFlashcard()+ Conf.Flashcard.Store(conf.NewFlashcard())const password = "duplicate-hpath-test-password"if err := EnableEncryptedNotebook(password); err != nil {t.Fatal(err)diff --git a/kernel/model/elevator_windows.go b/kernel/model/elevator_windows.goindex b0670ce1a8..d3f8ae5eb2 100644--- a/kernel/model/elevator_windows.go+++ b/kernel/model/elevator_windows.go@@ -31,6 +31,7 @@ import ("github.com/88250/gulu""github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/internal/elevator""github.com/siyuan-note/siyuan/kernel/util")@@ -76,8 +77,7 @@ func AddMicrosoftDefenderExclusion() (err error) {return}- Conf.System.MicrosoftDefenderExcluded = true- Conf.Save()+ UpdateSystemConf(func(s *conf.System) { s.MicrosoftDefenderExcluded = true })logging.LogInfof("added Windows Defender exclusion path [%s, %s]", installPath, util.WorkspaceDir)util.PushMsg(Conf.language(102), 5000)@@ -89,7 +89,7 @@ func AutoCheckMicrosoftDefenderJob() {microsoftDefenderLock.Lock()defer microsoftDefenderLock.Unlock()- if !gulu.OS.IsWindows() || Conf.System.MicrosoftDefenderExcluded {+ if !gulu.OS.IsWindows() || Conf.System.Load().MicrosoftDefenderExcluded {return}diff --git a/kernel/model/embed_heading_export_test.go b/kernel/model/embed_heading_export_test.goindex 4e78290c9b..a33005b9b9 100644--- a/kernel/model/embed_heading_export_test.go+++ b/kernel/model/embed_heading_export_test.go@@ -40,8 +40,8 @@ func TestExportExplicitEmbedHeadingLevels(t *testing.T) {util.ConfDir = t.TempDir()t.Cleanup(func() { util.ConfDir = oldConfDir })setupExportRelatedTest(t, boxID)- Conf.Editor = conf.NewEditor()- Conf.Search = conf.NewSearch()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Search.Store(conf.NewSearch())oldDB, oldQueue := util.DBPath, util.QueueDiroldHistoryDB, oldAssetDB := util.HistoryDBPath, util.AssetContentDBPathutil.DBPath = filepath.Join(util.TempDir, "siyuan.db")diff --git a/kernel/model/embedding.go b/kernel/model/embedding.goindex f6e7126652..9834fa9cab 100644--- a/kernel/model/embedding.go+++ b/kernel/model/embedding.go@@ -622,7 +622,9 @@ func SemanticSearchBlock(query string, boxes, paths []string, types, subTypes ma}func isEmbeddingEnabled() bool {- return !util.IsDisabledFeature("ai") && nil != Conf.AI.Embedding && Conf.AI.Embedding.Enabled && len(Conf.AI.Embedding.APIKey) > 0+ confAISnapshot := Conf.LoadAI()++ return !util.IsDisabledFeature("ai") && nil != confAISnapshot.Embedding && confAISnapshot.Embedding.Enabled && len(confAISnapshot.Embedding.APIKey) > 0}// rerankSqlBlocks 用重排模型对候选块按 query 逐对精排。未启用或调用失败时原样返回(降级为向量相似度排序)。@@ -817,8 +819,10 @@ func GetEmbeddingStat() (ret *EmbeddingStat) {}func embeddingKey() string {- if nil != Conf.AI.Embedding && Conf.AI.Embedding.Enabled && "" != Conf.AI.Embedding.APIKey {- return Conf.AI.Embedding.APIKey+ confAISnapshot := Conf.LoadAI()++ if nil != confAISnapshot.Embedding && confAISnapshot.Embedding.Enabled && "" != confAISnapshot.Embedding.APIKey {+ return confAISnapshot.Embedding.APIKey}if v := os.Getenv("SIYUAN_OPENAI_EMBEDDING_API_KEY"); "" != v {return v@@ -827,8 +831,10 @@ func embeddingKey() string {}func embeddingBaseURL() string {- if nil != Conf.AI.Embedding && Conf.AI.Embedding.Enabled && "" != Conf.AI.Embedding.BaseURL {- return Conf.AI.Embedding.BaseURL+ confAISnapshot := Conf.LoadAI()++ if nil != confAISnapshot.Embedding && confAISnapshot.Embedding.Enabled && "" != confAISnapshot.Embedding.BaseURL {+ return confAISnapshot.Embedding.BaseURL}if v := os.Getenv("SIYUAN_OPENAI_EMBEDDING_BASE_URL"); "" != v {return v@@ -837,8 +843,10 @@ func embeddingBaseURL() string {}func embeddingTimeout() int {- if nil != Conf.AI.Embedding && Conf.AI.Embedding.Enabled && 0 < Conf.AI.Embedding.Timeout {- return Conf.AI.Embedding.Timeout+ confAISnapshot := Conf.LoadAI()++ if nil != confAISnapshot.Embedding && confAISnapshot.Embedding.Enabled && 0 < confAISnapshot.Embedding.Timeout {+ return confAISnapshot.Embedding.Timeout}return 30}@@ -846,15 +854,19 @@ func embeddingTimeout() int {// embeddingDimensions 返回配置的输出向量维度。0 表示用模型默认维度(不传 dimensions 参数给 API),// 仅 text-embedding-3 及以上模型支持自定义维度。文档向量与查询向量必须用相同维度,否则相似度计算会维度不匹配。func embeddingDimensions() int {- if nil != Conf.AI.Embedding && Conf.AI.Embedding.Enabled && 0 < Conf.AI.Embedding.Dimensions {- return Conf.AI.Embedding.Dimensions+ confAISnapshot := Conf.LoadAI()++ if nil != confAISnapshot.Embedding && confAISnapshot.Embedding.Enabled && 0 < confAISnapshot.Embedding.Dimensions {+ return confAISnapshot.Embedding.Dimensions}return 0}func embeddingModel() string {- if nil != Conf.AI.Embedding && Conf.AI.Embedding.Enabled && "" != Conf.AI.Embedding.Name {- return Conf.AI.Embedding.Name+ confAISnapshot := Conf.LoadAI()++ if nil != confAISnapshot.Embedding && confAISnapshot.Embedding.Enabled && "" != confAISnapshot.Embedding.Name {+ return confAISnapshot.Embedding.Name}if v := os.Getenv("SIYUAN_OPENAI_EMBEDDING_MODEL"); "" != v {return vdiff --git a/kernel/model/embedding_queue_test.go b/kernel/model/embedding_queue_test.goindex 38f7501d58..ecf2c97f91 100644--- a/kernel/model/embedding_queue_test.go+++ b/kernel/model/embedding_queue_test.go@@ -16,8 +16,8 @@ func prepareEmbeddingQueueTest(t *testing.T) {t.Helper()previousConf := ConfConf = NewAppConf()- Conf.AI = conf.NewAI()- Conf.AI.Embedding = &conf.Embedding{Enabled: true, APIKey: "test"}+ Conf.AI.Store(conf.NewAI())+ Conf.AI.Load().Embedding = &conf.Embedding{Enabled: true, APIKey: "test"}embeddingIgnoreLock.Lock()loaded, matcher := embeddingIgnoreLoaded, embeddingIgnoreMatcherembeddingIgnoreLoaded, embeddingIgnoreMatcher = true, nil@@ -122,8 +122,8 @@ func TestEmbeddingRebuildDiscardsInflightFailure(t *testing.T) {http.Error(w, `{"error":{"message":"failed"}}`, http.StatusInternalServerError)}))defer server.Close()- Conf.AI.Embedding.BaseURL = server.URL- Conf.AI.Embedding.Timeout = 5+ Conf.AI.Load().Embedding.BaseURL = server.URL+ Conf.AI.Load().Embedding.Timeout = 5embeddingResultMu.Lock()generation := embeddingGenerationembeddingResultMu.Unlock()diff --git a/kernel/model/encrypted_history_index_test.go b/kernel/model/encrypted_history_index_test.goindex d0f0ffd88d..b05a377598 100644--- a/kernel/model/encrypted_history_index_test.go+++ b/kernel/model/encrypted_history_index_test.go@@ -56,12 +56,12 @@ func TestEncryptedHistoryAndIndexRecovery(t *testing.T) {}}Conf = NewAppConf()- Conf.Editor = conf.NewEditor()- Conf.Export = conf.NewExport()- Conf.Search = conf.NewSearch()- Conf.FileTree = conf.NewFileTree()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Export.Store(conf.NewExport())+ Conf.Search.Store(conf.NewSearch())+ Conf.FileTree.Store(conf.NewFileTree())Conf.NotebookCrypto = conf.NewNotebookCrypto()- Conf.Sync = conf.NewSync()+ Conf.Sync.Store(conf.NewSync())sql.InitDatabase(true)sql.InitHistoryDatabase(true)sql.InitAssetContentDatabase(true)diff --git a/kernel/model/export.go b/kernel/model/export.goindex 86263b8677..6e5292f954 100644--- a/kernel/model/export.go+++ b/kernel/model/export.go@@ -649,7 +649,7 @@ func ExportNotebookSY(id string) (zipPath string) {logging.LogErrorf("export encrypted notebook [%s] failed: locked", id)return}- zipPath = exportBoxSYZip(id)+ zipPath = exportBoxSYZip(id, resolveExportOptions(nil))return}@@ -695,7 +695,7 @@ func ExportSYs(ids []string) (zipPath string) {for _, bt := range bts {docPaths = append(docPaths, bt.Path)- if Conf.Export.IncludeSubDocs {+ if Conf.Export.Load().IncludeSubDocs {listPath := strings.TrimSuffix(bt.Path, ".sy")if IsBoxDoc(bt.BoxID, bt.RootID) {listPath = "/"@@ -1043,7 +1043,9 @@ func exportResourcesEncryptedBox(resourcePaths []string) (encryptedBoxID string,func ExportPreview(id string, fillCSSVar bool, avPublishFilter AVExportPublishFilter,accessChecker ...EmbedBlockAccessChecker) (retStdHTML string) {if exportErr := withExportReadLockByBlockID(id, func() error {- blockRefMode := Conf.Export.BlockRefMode+ confExportSnapshot := Conf.LoadExport()++ blockRefMode := confExportSnapshot.BlockRefModebt := getExportBlockTree(id)if nil == bt {return nil@@ -1057,14 +1059,14 @@ func ExportPreview(id string, fillCSSVar bool, avPublishFilter AVExportPublishFi// 这里固定使用 # 包裹标签,否则无法正确解析标签 https://github.com/siyuan-note/siyuan/issues/13857Config: conf.Export{BlockRefMode: blockRefMode,- BlockEmbedMode: Conf.Export.BlockEmbedMode,- FileAnnotationRefMode: Conf.Export.FileAnnotationRefMode,+ BlockEmbedMode: confExportSnapshot.BlockEmbedMode,+ FileAnnotationRefMode: confExportSnapshot.FileAnnotationRefMode,TagOpenMarker: "#",TagCloseMarker: "#",- BlockRefTextLeft: Conf.Export.BlockRefTextLeft,- BlockRefTextRight: Conf.Export.BlockRefTextRight,- AddTitle: Conf.Export.AddTitle,- InlineMemo: Conf.Export.InlineMemo,+ BlockRefTextLeft: confExportSnapshot.BlockRefTextLeft,+ BlockRefTextRight: confExportSnapshot.BlockRefTextRight,+ AddTitle: confExportSnapshot.AddTitle,+ InlineMemo: confExportSnapshot.InlineMemo,},WYSIWYG: false,RichTableCells: true,@@ -1084,7 +1086,7 @@ func ExportPreview(id string, fillCSSVar bool, avPublishFilter AVExportPublishFiluteEngine.SetFootnotes(true)addBlockIALNodes(tree, false)- adjustHeadingLevel(bt, tree, Conf.Export.AddTitle)+ adjustHeadingLevel(bt, tree, confExportSnapshot.AddTitle)// 移除超级块的属性列表 https://github.com/siyuan-note/siyuan/issues/13451var unlinks []*ast.Node@@ -1137,9 +1139,11 @@ func ExportDocx(id, savePath string, removeAssets, merge bool, mergeHeadingOptioreturn}err = withExportReadLockByBlockID(id, func() error {+ confExportSnapshot := Conf.LoadExport()+pandocRuntime := util.GetPandocRuntime()if !util.IsValidPandocBin(pandocRuntime.BinPath) {- util.InitPandoc(Conf.Export.PandocBin)+ util.InitPandoc(confExportSnapshot.PandocBin)pandocRuntime = util.GetPandocRuntime()if !util.IsValidPandocBin(pandocRuntime.BinPath) {return errors.New(Conf.Language(115))@@ -1171,7 +1175,7 @@ func ExportDocx(id, savePath string, removeAssets, merge bool, mergeHeadingOptio"-o", tmpDocxPath,}- params := util.ReplaceNewline(Conf.Export.PandocParams, " ")+ params := util.ReplaceNewline(confExportSnapshot.PandocParams, " ")if "" != params {customArgs, parseErr := shellquote.Split(params)if nil != parseErr {@@ -1239,6 +1243,10 @@ func ExportMarkdownHTML(id, savePath string, docx, merge bool, mergeHeadingOptiofunc exportMarkdownHTML(id, savePath string, docx, merge bool, mergeHeadingOptions ...MergeHeadingOptions) (name, dom string, err error) {err = withExportReadLockByBlockID(id, func() error {+ confAppearanceSnapshot := Conf.LoadAppearance()++ confExportSnapshot := Conf.LoadExport()+bt := getExportBlockTree(id)if nil == bt {return ErrBlockNotFound@@ -1248,7 +1256,7 @@ func exportMarkdownHTML(id, savePath string, docx, merge bool, mergeHeadingOptioif merge {var mergeErr error- tree, mergeErr = mergeSubDocs(tree, mergeHeadingOptionsOrDefault(mergeHeadingOptions), Conf.Export.AddTitle)+ tree, mergeErr = mergeSubDocs(tree, mergeHeadingOptionsOrDefault(mergeHeadingOptions), confExportSnapshot.AddTitle)if nil != mergeErr {logging.LogErrorf("merge sub docs failed: %s", mergeErr)return mergeErr@@ -1259,18 +1267,18 @@ func exportMarkdownHTML(id, savePath string, docx, merge bool, mergeHeadingOptioreturn numberErr}- blockRefMode := Conf.Export.BlockRefMode+ blockRefMode := confExportSnapshot.BlockRefModetree, exportTreeErr := exportTree(tree, treeExportOptions{Config: conf.Export{BlockRefMode: blockRefMode,- BlockEmbedMode: Conf.Export.BlockEmbedMode,- FileAnnotationRefMode: Conf.Export.FileAnnotationRefMode,- TagOpenMarker: Conf.Export.TagOpenMarker,- TagCloseMarker: Conf.Export.TagCloseMarker,- BlockRefTextLeft: Conf.Export.BlockRefTextLeft,- BlockRefTextRight: Conf.Export.BlockRefTextRight,- AddTitle: Conf.Export.AddTitle,- InlineMemo: Conf.Export.InlineMemo,+ BlockEmbedMode: confExportSnapshot.BlockEmbedMode,+ FileAnnotationRefMode: confExportSnapshot.FileAnnotationRefMode,+ TagOpenMarker: confExportSnapshot.TagOpenMarker,+ TagCloseMarker: confExportSnapshot.TagCloseMarker,+ BlockRefTextLeft: confExportSnapshot.BlockRefTextLeft,+ BlockRefTextRight: confExportSnapshot.BlockRefTextRight,+ AddTitle: confExportSnapshot.AddTitle,+ InlineMemo: confExportSnapshot.InlineMemo,},WYSIWYG: true,RichTableCells: true,@@ -1324,11 +1332,11 @@ func exportMarkdownHTML(id, savePath string, docx, merge bool, mergeHeadingOptio}}- theme := Conf.Appearance.ThemeLight- if 1 == Conf.Appearance.Mode {- theme = Conf.Appearance.ThemeDark+ theme := confAppearanceSnapshot.ThemeLight+ if 1 == confAppearanceSnapshot.Mode {+ theme = confAppearanceSnapshot.ThemeDark}- if err := copyExportAppearance(savePath, theme, Conf.Appearance.Icon); err != nil {+ if err := copyExportAppearance(savePath, theme, confAppearanceSnapshot.Icon); err != nil {return err}@@ -1392,7 +1400,7 @@ func exportMarkdownHTML(id, savePath string, docx, merge bool, mergeHeadingOptio}func ExportHTML(id, savePath string, pdf, keepFold, merge bool, mergeHeadingOptions ...MergeHeadingOptions) (name, dom string, node *ast.Node) {- return ExportHTMLWithTitle(id, savePath, pdf, keepFold, merge, Conf.Export.AddTitle, "", mergeHeadingOptions...)+ return ExportHTMLWithTitle(id, savePath, pdf, keepFold, merge, Conf.Export.Load().AddTitle, "", mergeHeadingOptions...)}func ExportHTMLWithTitle(id, savePath string, pdf, keepFold, merge, addTitle bool, customTitle string,@@ -1412,6 +1420,10 @@ func exportHTMLWithTitle(id, savePath string, pdf, keepFold, merge, addTitle booreturn}if exportErr := withExportReadLockByBlockID(id, func() error {+ confAppearanceSnapshot := Conf.LoadAppearance()++ confExportSnapshot := Conf.LoadExport()+savePath = strings.TrimSpace(savePath)bt := getExportBlockTree(id)@@ -1438,7 +1450,7 @@ func exportHTMLWithTitle(id, savePath string, pdf, keepFold, merge, addTitle booreturn numberErr}- blockRefMode := Conf.Export.BlockRefMode+ blockRefMode := confExportSnapshot.BlockRefModevar headings []*ast.Nodeif pdf { // 导出 PDF 需要标记目录书签headings = collectOutlineHeadings(tree)@@ -1460,14 +1472,14 @@ func exportHTMLWithTitle(id, savePath string, pdf, keepFold, merge, addTitle bootree, exportTreeErr := exportTree(tree, treeExportOptions{Config: conf.Export{BlockRefMode: blockRefMode,- BlockEmbedMode: Conf.Export.BlockEmbedMode,- FileAnnotationRefMode: Conf.Export.FileAnnotationRefMode,- TagOpenMarker: Conf.Export.TagOpenMarker,- TagCloseMarker: Conf.Export.TagCloseMarker,- BlockRefTextLeft: Conf.Export.BlockRefTextLeft,- BlockRefTextRight: Conf.Export.BlockRefTextRight,+ BlockEmbedMode: confExportSnapshot.BlockEmbedMode,+ FileAnnotationRefMode: confExportSnapshot.FileAnnotationRefMode,+ TagOpenMarker: confExportSnapshot.TagOpenMarker,+ TagCloseMarker: confExportSnapshot.TagCloseMarker,+ BlockRefTextLeft: confExportSnapshot.BlockRefTextLeft,+ BlockRefTextRight: confExportSnapshot.BlockRefTextRight,AddTitle: addTitle,- InlineMemo: Conf.Export.InlineMemo,+ InlineMemo: confExportSnapshot.InlineMemo,},WYSIWYG: true,RichTableCells: true,@@ -1517,11 +1529,11 @@ func exportHTMLWithTitle(id, savePath string, pdf, keepFold, merge, addTitle boo}}- theme := Conf.Appearance.ThemeLight- if 1 == Conf.Appearance.Mode {- theme = Conf.Appearance.ThemeDark+ theme := confAppearanceSnapshot.ThemeLight+ if 1 == confAppearanceSnapshot.Mode {+ theme = confAppearanceSnapshot.ThemeDark}- if err := copyExportAppearance(savePath, theme, Conf.Appearance.Icon); err != nil {+ if err := copyExportAppearance(savePath, theme, confAppearanceSnapshot.Icon); err != nil {return err}@@ -1609,6 +1621,8 @@ func selectExportTree(tree *parse.Tree, bt *treenode.BlockTree) (ret *parse.Tree}func applyHeadingNumbersForExport(tree *parse.Tree, bt *treenode.BlockTree, merged bool) (err error) {+ confEditorSnapshot := Conf.LoadEditor()+if nil == tree || nil == tree.Root {return}@@ -1621,10 +1635,10 @@ func applyHeadingNumbersForExport(tree *parse.Tree, bt *treenode.BlockTree, merg}}- if !headingNumberEnabled(numberingTree, Conf.Editor.HeadingNumber) {+ if !headingNumberEnabled(numberingTree, confEditorSnapshot.HeadingNumber) {return}- materializeHeadingNumbers(tree, headingNumberLabels(numberingTree, Conf.Editor.HeadingNumberFormat))+ materializeHeadingNumbers(tree, headingNumberLabels(numberingTree, confEditorSnapshot.HeadingNumberFormat))return}@@ -1681,15 +1695,17 @@ func ProcessPDF(id, p string, merge, removeAssets, watermark bool, mergeHeadingOreturn}err = withExportReadLockByBlockID(id, func() error {+ confEditorSnapshot := Conf.LoadEditor()+tree, _ := LoadTreeByBlockID(id)if nil == tree {return nil}- numberHeadings := headingNumberEnabled(tree, Conf.Editor.HeadingNumber)+ numberHeadings := headingNumberEnabled(tree, confEditorSnapshot.HeadingNumber)if merge {var mergeErr error- tree, mergeErr = mergeSubDocs(tree, mergeHeadingOptionsOrDefault(mergeHeadingOptions), Conf.Export.AddTitle)+ tree, mergeErr = mergeSubDocs(tree, mergeHeadingOptionsOrDefault(mergeHeadingOptions), Conf.Export.Load().AddTitle)if nil != mergeErr {logging.LogErrorf("merge sub docs failed: %s", mergeErr)return nil@@ -1700,7 +1716,7 @@ func ProcessPDF(id, p string, merge, removeAssets, watermark bool, mergeHeadingOheadings := collectOutlineHeadings(tree)var headingNumbers map[string]stringif numberHeadings {- headingNumbers = headingNumberLabels(tree, Conf.Editor.HeadingNumberFormat)+ headingNumbers = headingNumberLabels(tree, confEditorSnapshot.HeadingNumberFormat)}api.DisableConfigDir()@@ -1735,6 +1751,8 @@ func ProcessPDF(id, p string, merge, removeAssets, watermark bool, mergeHeadingO}func processPDFWatermark(pdfCtx *model.Context, watermark bool) {+ confExportSnapshot := Conf.LoadExport()+// Support adding the watermark on export PDF https://github.com/siyuan-note/siyuan/issues/9961// https://pdfcpu.io/core/watermark@@ -1742,7 +1760,7 @@ func processPDFWatermark(pdfCtx *model.Context, watermark bool) {return}- str := Conf.Export.PDFWatermarkStr+ str := confExportSnapshot.PDFWatermarkStrif "" == str {return}@@ -1756,7 +1774,7 @@ func processPDFWatermark(pdfCtx *model.Context, watermark bool) {}}- desc := Conf.Export.PDFWatermarkDesc+ desc := confExportSnapshot.PDFWatermarkDescif "text" == mode && util.ContainsCJK(str) {// 中日韩文本水印需要安装字体文件descParts := strings.Split(desc, ",")@@ -2245,7 +2263,7 @@ type ExportOptions struct {// resolveExportOptions 解析单次导出的独立配置快照,缺省选项沿用当前配置,不写入全局配置。func resolveExportOptions(opts *ExportOptions) (ret conf.Export) {- ret = *Conf.Export+ ret = *Conf.Export.Load()if nil != opts {if nil != opts.AddTitle {ret.AddTitle = *opts.AddTitle@@ -2602,7 +2620,7 @@ func treeToSYJSON(tree *parse.Tree) (data []byte) {luteEngine := util.NewLute()renderer := render.NewJSONRenderer(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)data = renderer.Render()- if !util.UseSingleLineSave {+ if !util.UseSingleLineSave.Load() {buf := bytes.Buffer{}buf.Grow(1024 * 1024 * 2)if err := json.Indent(&buf, data, "", "\t"); err != nil {@@ -2614,7 +2632,8 @@ func treeToSYJSON(tree *parse.Tree) (data []byte) {return}-func exportBoxSYZip(boxID string) (zipPath string) {+// exportBoxSYZip 使用调用方给定的导出配置导出整个笔记本,不改写全局导出配置。+func exportBoxSYZip(boxID string, config conf.Export) (zipPath string) {util.PushEndlessProgress(Conf.Language(65))defer util.ClearPushProgress(100)@@ -2630,11 +2649,17 @@ func exportBoxSYZip(boxID string) (zipPath string) {for _, docFile := range docFiles {docPaths = append(docPaths, docFile.path)}- zipPath = exportSYZip(boxID, "/", baseFolderName, docPaths, true)+ zipPath = exportSYZipWithConfig(boxID, "/", baseFolderName, docPaths, true, config)return}func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string, includeBoxConf bool) (zipPath string) {+ return exportSYZipWithConfig(boxID, rootDirPath, baseFolderName, docPaths, includeBoxConf, resolveExportOptions(nil))+}++func exportSYZipWithConfig(boxID, rootDirPath, baseFolderName string, docPaths []string, includeBoxConf bool, config conf.Export) (zipPath string) {+ confFlashcardSnapshot := Conf.LoadFlashcard()+defer util.ClearPushProgress(100)if err := recoverSortConfAppend(filepath.Join(util.DataDir, boxID, ".siyuan", "sort.json")); err != nil {logging.LogErrorf("recover export sort conf failed: %s", err)@@ -2743,7 +2768,7 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string, iutil.PushEndlessProgress(Conf.language(65) + " " + fmt.Sprintf(Conf.language(70), fmt.Sprintf("%d/%d %s", count, len(docPaths), tree.Root.IALAttr("title"))))refs := map[string]*parse.Tree{}- exportRefTreesWithConfig(tree, &[]string{}, refs, resolveExportOptions(nil))+ exportRefTreesWithConfig(tree, &[]string{}, refs, config)for refTreeID, refTree := range refs {if nil == trees[refTreeID] {refTrees[refTreeID] = refTree@@ -2921,7 +2946,7 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string, iif !IsEncryptedBox(box.ID) {// 导出闪卡 Export related flashcard data when exporting .sy.zip https://github.com/siyuan-note/siyuan/issues/9372exportStorageRiffDir := filepath.Join(exportDir, "storage", "riff")- deck, loadErr := riff.LoadDeck(exportStorageRiffDir, builtinDeckID, Conf.Flashcard.RequestRetention, Conf.Flashcard.MaximumInterval, Conf.Flashcard.Weights)+ deck, loadErr := riff.LoadDeck(exportStorageRiffDir, builtinDeckID, confFlashcardSnapshot.RequestRetention, confFlashcardSnapshot.MaximumInterval, confFlashcardSnapshot.Weights)if nil != loadErr {logging.LogErrorf("load deck [%s] failed: %s", name, loadErr)} else {@@ -4193,6 +4218,8 @@ func resolveFootnotesDefs(refFootnoteOrder *[]string, refFootnotesByID map[strinvar unlinks []*ast.Nodeast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {+ confSearchSnapshot := Conf.LoadSearch()+if !entering {return ast.WalkContinue}@@ -4221,9 +4248,9 @@ func resolveFootnotesDefs(refFootnoteOrder *[]string, refFootnotesByID map[strinstmt = strings.ReplaceAll(stmt, editor.IALValEscNewLine, "\n")var sqlBlocks []*sql.Blockif IsEncryptedBox(currentTree.Box) {- sqlBlocks = sql.SelectBlocksRawStmtInBox(stmt, 1, Conf.Search.Limit, currentTree.Box)+ sqlBlocks = sql.SelectBlocksRawStmtInBox(stmt, 1, confSearchSnapshot.Limit, currentTree.Box)} else {- sqlBlocks = sql.SelectBlocksRawStmt(stmt, 1, Conf.Search.Limit)+ sqlBlocks = sql.SelectBlocksRawStmt(stmt, 1, confSearchSnapshot.Limit)}for _, b := range sqlBlocks {subNodes := renderBlockMarkdownR(b.ID, &rendered, currentTree.Box)@@ -4347,6 +4374,8 @@ func collectFootnotesDefs(currentTree *parse.Tree, id string, refFootnoteOrder *}func addRefFootnoteAndRecurse(currentTree *parse.Tree, defID, anchorText string, refFootnoteOrder *[]string, refFootnotesByID map[string]*refAsFootnotes, depth *int, references *markdownExportReferences) {+ confEditorSnapshot := Conf.LoadEditor()+if references.contains(defID, currentTree.Box) {references.anchorIDs[defID] = truereturn@@ -4361,8 +4390,8 @@ func addRefFootnoteAndRecurse(currentTree *parse.Tree, defID, anchorText string,// 当前文档内不转换脚注,直接使用锚点哈希 https://github.com/siyuan-note/siyuan/issues/13283return}- if Conf.Editor.BlockRefDynamicAnchorTextMaxLen < utf8.RuneCountInString(anchorText) {- anchorText = gulu.Str.SubStr(anchorText, Conf.Editor.BlockRefDynamicAnchorTextMaxLen) + "..."+ if confEditorSnapshot.BlockRefDynamicAnchorTextMaxLen < utf8.RuneCountInString(anchorText) {+ anchorText = gulu.Str.SubStr(anchorText, confEditorSnapshot.BlockRefDynamicAnchorTextMaxLen) + "..."}*refFootnoteOrder = append(*refFootnoteOrder, defID)refFootnotesByID[defID] = &refAsFootnotes{@@ -4844,6 +4873,8 @@ func removeAssetsID(tree *parse.Tree, assetsOldNew, assetsNewOld map[string]stri}func getExportBlockRefLinkText(blockRef *ast.Node, blockRefTextLeft, blockRefTextRight, boxID string) (defID, linkText string) {+ confEditorSnapshot := Conf.LoadEditor()+defID, linkText, _ = treenode.GetBlockRef(blockRef)if "" == linkText {if IsEncryptedBox(boxID) {@@ -4853,8 +4884,8 @@ func getExportBlockRefLinkText(blockRef *ast.Node, blockRefTextLeft, blockRefTex}}linkText = util.UnescapeHTML(linkText) // 块引锚文本导出时 `&` 变为实体 `&` https://github.com/siyuan-note/siyuan/issues/7659- if Conf.Editor.BlockRefDynamicAnchorTextMaxLen < utf8.RuneCountInString(linkText) {- linkText = gulu.Str.SubStr(linkText, Conf.Editor.BlockRefDynamicAnchorTextMaxLen) + "..."+ if confEditorSnapshot.BlockRefDynamicAnchorTextMaxLen < utf8.RuneCountInString(linkText) {+ linkText = gulu.Str.SubStr(linkText, confEditorSnapshot.BlockRefDynamicAnchorTextMaxLen) + "..."}linkText = blockRefTextLeft + linkText + blockRefTextRightreturndiff --git a/kernel/model/export_annotation_test.go b/kernel/model/export_annotation_test.goindex 401dc2b084..ad90c85ee9 100644--- a/kernel/model/export_annotation_test.go+++ b/kernel/model/export_annotation_test.go@@ -18,7 +18,11 @@ func TestExportTreeMissingFileAnnotationRef(t *testing.T) {originalWorkspaceDir := util.WorkspaceDirutil.WorkspaceDir = filepath.Dir(util.DataDir)t.Cleanup(func() { util.WorkspaceDir = originalWorkspaceDir })- Conf.Export, Conf.Editor = conf.NewExport(), conf.NewEditor()+ {+ confSectionValue0, confSectionValue1 := conf.NewExport(), conf.NewEditor()+ Conf.Export.Store(confSectionValue0)+ Conf.Editor.Store(confSectionValue1)+ }assetPath := filepath.Join(util.DataDir, "assets", "document.pdf")if err := os.MkdirAll(filepath.Dir(assetPath), 0755); err != nil {t.Fatal(err)diff --git a/kernel/model/export_asset_test.go b/kernel/model/export_asset_test.goindex efc2a4826f..0b27b6280e 100644--- a/kernel/model/export_asset_test.go+++ b/kernel/model/export_asset_test.go@@ -35,11 +35,11 @@ func TestExportAssetCopyFailureReturnsNoOutput(t *testing.T) {originalWorkspaceDir := util.WorkspaceDirutil.WorkspaceDir = filepath.Dir(util.DataDir)t.Cleanup(func() { util.WorkspaceDir = originalWorkspaceDir })- Conf.Editor = conf.NewEditor()- Conf.Export = conf.NewExport()- Conf.Appearance = conf.NewAppearance()- Conf.Search = conf.NewSearch()- Conf.System = conf.NewSystem()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Export.Store(conf.NewExport())+ Conf.Appearance.Store(conf.NewAppearance())+ Conf.Search.Store(conf.NewSearch())+ Conf.System.Store(conf.NewSystem())assetPath := "assets/export-20260905000000-abcdefg.html"absPath := filepath.Join(util.DataDir, assetPath)if err := os.MkdirAll(filepath.Dir(absPath), 0755); err != nil {@@ -121,8 +121,8 @@ func TestResolveExportAssetPaths(t *testing.T) {t.Run(test.name, func(t *testing.T) {originalConf := ConfConf = NewAppConf()- Conf.Export = conf.NewExport()- Conf.Export.RemoveAssetsID = test.removeID+ Conf.Export.Store(conf.NewExport())+ Conf.Export.Load().RemoveAssetsID = test.removeIDt.Cleanup(func() {Conf = originalConf})@@ -136,7 +136,7 @@ func TestResolveExportAssetPaths(t *testing.T) {assetsOldNew, assetsNewOld := map[string]string{}, map[string]string{}tree := &parse.Tree{Root: root}- removeAssetsID(tree, assetsOldNew, assetsNewOld, Conf.Export.RemoveAssetsID)+ removeAssetsID(tree, assetsOldNew, assetsNewOld, Conf.Export.Load().RemoveAssetsID)assets := getAssetsLinkDests(root, false)if len(assets) != len(test.expected) {@@ -169,11 +169,11 @@ func TestExportHTMLMultipleAssetReferences(t *testing.T) {originalWorkspaceDir := util.WorkspaceDirutil.WorkspaceDir = filepath.Dir(util.DataDir)t.Cleanup(func() { util.WorkspaceDir = originalWorkspaceDir })- Conf.Editor = conf.NewEditor()- Conf.Export = conf.NewExport()- Conf.Appearance = conf.NewAppearance()- Conf.Search = conf.NewSearch()- Conf.System = conf.NewSystem()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Export.Store(conf.NewExport())+ Conf.Appearance.Store(conf.NewAppearance())+ Conf.Search.Store(conf.NewSearch())+ Conf.System.Store(conf.NewSystem())assetsDir := filepath.Join(util.DataDir, "assets")if err := os.MkdirAll(assetsDir, 0755); err != nil {t.Fatal(err)@@ -204,16 +204,16 @@ func TestExportAssetEntityRename(t *testing.T) {originalConf := Conft.Cleanup(func() { Conf = originalConf })Conf = NewAppConf()- Conf.Export = conf.NewExport()+ Conf.Export.Store(conf.NewExport())for _, removeID := range []bool{false, true} {- Conf.Export.RemoveAssetsID = removeID+ Conf.Export.Load().RemoveAssetsID = removeIDfor _, typ := range []ast.NodeType{ast.NodeHTMLBlock, ast.NodeInlineHTML, ast.NodeIFrame, ast.NodeAudio, ast.NodeVideo} {markup := `<video src='assets/a&b-20260724150608-42z1qwz.webm?x=1&y=2#part' poster="assets/a&amp;b-20260724150608-42z1qwz.png"><source src=assets/second-20260724150608-42z1qwz.webm></video>`root := &ast.Node{Type: ast.NodeDocument}node := &ast.Node{Type: typ, Tokens: []byte(markup)}root.AppendChild(node)oldNew, newOld := map[string]string{}, map[string]string{}- removeAssetsID(&parse.Tree{Root: root}, oldNew, newOld, Conf.Export.RemoveAssetsID)+ removeAssetsID(&parse.Tree{Root: root}, oldNew, newOld, Conf.Export.Load().RemoveAssetsID)original := []string{"assets/a&b-20260724150608-42z1qwz.webm?x=1&y=2#part", "assets/a&b-20260724150608-42z1qwz.png", "assets/second-20260724150608-42z1qwz.webm"}want := append([]string(nil), original...)if removeID {diff --git a/kernel/model/export_attribute_view_test.go b/kernel/model/export_attribute_view_test.goindex 3d8415dd20..cc2f741da6 100644--- a/kernel/model/export_attribute_view_test.go+++ b/kernel/model/export_attribute_view_test.go@@ -35,7 +35,7 @@ import (func TestAttributeViewExportTablePresentation(t *testing.T) {const boxID = "20261004000000-box0001"setupExportRelatedTest(t, boxID)- Conf.Editor = conf.NewEditor()+ Conf.Editor.Store(conf.NewEditor())oldLang, oldAttrViewLangs := util.Lang, util.AttrViewLangsutil.Lang = "en"util.AttrViewLangs = map[string]map[string]any{@@ -195,7 +195,7 @@ func TestAttributeViewExportDoesNotCrossEncryptedBoundary(t *testing.T) {)setupExportRelatedTest(t, normalBoxID)- Conf.Editor = conf.NewEditor()+ Conf.Editor.Store(conf.NewEditor())oldLang, oldAttrViewLangs := util.Lang, util.AttrViewLangsutil.Lang = "en"util.AttrViewLangs = map[string]map[string]any{diff --git a/kernel/model/export_footnotes_fts5_test.go b/kernel/model/export_footnotes_fts5_test.goindex 3e29bff4e3..9a0c702b80 100644--- a/kernel/model/export_footnotes_fts5_test.go+++ b/kernel/model/export_footnotes_fts5_test.go@@ -18,7 +18,7 @@ import (func TestExportFootnotesAcrossNotebooksFormats(t *testing.T) {setupExportPublishTest(t)- Conf.Appearance = conf.NewAppearance()+ Conf.Appearance.Store(conf.NewAppearance())oldAppearance := util.AppearancePathutil.AppearancePath = t.TempDir()t.Cleanup(func() { util.AppearancePath = oldAppearance })@@ -81,8 +81,13 @@ func TestExportFootnotesAfterEmbedExpansion(t *testing.T) {func TestExportFootnotesAfterMerge(t *testing.T) {fixture := setupFileOperationTest(t)- Conf.Export, Conf.Editor, Conf.Appearance = conf.NewExport(), conf.NewEditor(), conf.NewAppearance()- Conf.Search = conf.NewSearch()+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewExport(), conf.NewEditor(), conf.NewAppearance()+ Conf.Export.Store(confSectionValue0)+ Conf.Editor.Store(confSectionValue1)+ Conf.Appearance.Store(confSectionValue2)+ }+ Conf.Search.Store(conf.NewSearch())oldAppearance := util.AppearancePathutil.AppearancePath = t.TempDir()t.Cleanup(func() { util.AppearancePath = oldAppearance })@@ -134,8 +139,12 @@ func TestExportFootnotesPruneAfterAbbreviation(t *testing.T) {func TestExportBlockAssetsEmbeddedScopes(t *testing.T) {setupExportPublishTest(t)prepareAssetDownloadRepoTest(t)- Conf.Export, Conf.Editor = conf.NewExport(), conf.NewEditor()- Conf.FileTree = conf.NewFileTree()+ {+ confSectionValue0, confSectionValue1 := conf.NewExport(), conf.NewEditor()+ Conf.Export.Store(confSectionValue0)+ Conf.Editor.Store(confSectionValue1)+ }+ Conf.FileTree.Store(conf.NewFileTree())Conf.NotebookCrypto = conf.NewNotebookCrypto()const boxID = "20260918000003-box0004"source := newFootnoteTestDoc(t, boxID, "source")diff --git a/kernel/model/export_footnotes_test.go b/kernel/model/export_footnotes_test.goindex ef9d41d1fc..9541bffdfd 100644--- a/kernel/model/export_footnotes_test.go+++ b/kernel/model/export_footnotes_test.go@@ -30,7 +30,7 @@ func TestExportFootnotesAcrossNotebooks(t *testing.T) {const sourceBox = "20260927000000-box0001"const targetBox = "20260927000001-box0002"setupExportRelatedTest(t, sourceBox, targetBox)- Conf.Editor = conf.NewEditor()+ Conf.Editor.Store(conf.NewEditor())source := newFootnoteTestDoc(t, sourceBox, "source")target := newFootnoteTestDoc(t, targetBox, "cross notebook content")nested := newFootnoteTestDoc(t, sourceBox, "nested content")@@ -79,7 +79,7 @@ func TestExportFootnotesRejectCrossCryptoBoundary(t *testing.T) {const sourceBox = "20260927000002-box0003"const targetBox = "20260927000003-box0004"setupExportRelatedTest(t, sourceBox, targetBox)- Conf.Editor = conf.NewEditor()+ Conf.Editor.Store(conf.NewEditor())source := newFootnoteTestDoc(t, sourceBox, "source")target := newFootnoteTestDoc(t, targetBox, "private content")nested := newFootnoteTestDoc(t, sourceBox, "unreachable content")@@ -108,7 +108,11 @@ func TestExportFootnotesRejectCrossCryptoBoundary(t *testing.T) {func TestExportFootnotesStayWithinBlockScope(t *testing.T) {fixture := setupFileOperationTest(t)- Conf.Export, Conf.Editor = conf.NewExport(), conf.NewEditor()+ {+ confSectionValue0, confSectionValue1 := conf.NewExport(), conf.NewEditor()+ Conf.Export.Store(confSectionValue0)+ Conf.Editor.Store(confSectionValue1)+ }a := newFootnoteTestDoc(t, fixture.box.ID, "selected paragraph")b := newFootnoteTestDoc(t, fixture.box.ID, "unrelated B")c := newFootnoteTestDoc(t, fixture.box.ID, "unrelated C")@@ -177,7 +181,7 @@ func TestExportBlockAssetsExcludeUnrelatedContent(t *testing.T) {for _, tree := range []*parse.Tree{a, b} {writeAssetDownloadDocumentTest(t, tree)}- Conf.Export.IncludeRelatedDocs = true+ Conf.Export.Load().IncludeRelatedDocs = trueif err := prepareExportBlockAssets(a.Root.FirstChild.ID, false); err != nil {t.Fatal(err)}@@ -237,7 +241,11 @@ func TestExportFootnotesPruneUnreachable(t *testing.T) {func TestExportFootnotesHeadingAndContainerScopes(t *testing.T) {fixture := setupFileOperationTest(t)- Conf.Export, Conf.Editor = conf.NewExport(), conf.NewEditor()+ {+ confSectionValue0, confSectionValue1 := conf.NewExport(), conf.NewEditor()+ Conf.Export.Store(confSectionValue0)+ Conf.Editor.Store(confSectionValue1)+ }source := newFootnoteTestDoc(t, fixture.box.ID, "source")target := newFootnoteTestDoc(t, fixture.box.ID, "target")heading := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeHeading, HeadingLevel: 1}@@ -307,7 +315,11 @@ func TestExportFootnotesHeadingAndContainerScopes(t *testing.T) {func TestExportFootnotesUseMaterializedTableContent(t *testing.T) {fixture := setupFileOperationTest(t)- Conf.Export, Conf.Editor = conf.NewExport(), conf.NewEditor()+ {+ confSectionValue0, confSectionValue1 := conf.NewExport(), conf.NewEditor()+ Conf.Export.Store(confSectionValue0)+ Conf.Editor.Store(confSectionValue1)+ }source := newFootnoteTestDoc(t, fixture.box.ID, "source")target := newFootnoteTestDoc(t, fixture.box.ID, "target")parsed := parse.Parse("", []byte("| Header |\n| --- |\n| value |"), util.NewLute().ParseOptions)diff --git a/kernel/model/export_js_embed_test.go b/kernel/model/export_js_embed_test.goindex c6a2572e02..1188013282 100644--- a/kernel/model/export_js_embed_test.go+++ b/kernel/model/export_js_embed_test.go@@ -13,8 +13,8 @@ func TestExportPreviewJSEmbed(t *testing.T) {const boxID = "20260924010000-box0001"const docID = "20260924010001-doc0001"setupExportRelatedTest(t, boxID)- Conf.Editor = conf.NewEditor()- Conf.Search = conf.NewSearch()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Search.Store(conf.NewSearch())tree := treenode.NewTree(boxID, "/"+docID+".sy", "/Export", "Export")script := "//!js\nitem.innerHTML = '<b>& content</b>';"for range 2 {diff --git a/kernel/model/export_markdown_refs_test.go b/kernel/model/export_markdown_refs_test.goindex ecfaa52bda..3a66d8638d 100644--- a/kernel/model/export_markdown_refs_test.go+++ b/kernel/model/export_markdown_refs_test.go@@ -22,8 +22,8 @@ import (func setupMarkdownReferencesTest(t *testing.T, boxIDs ...string) {t.Helper()setupExportPublishTest(t)- Conf.Export.IncludeSubDocs = false- Conf.Export.IncludeRelatedDocs = false+ Conf.Export.Load().IncludeSubDocs = false+ Conf.Export.Load().IncludeRelatedDocs = falsefor _, boxID := range boxIDs {boxConf := conf.NewBoxConf()boxConf.Name, boxConf.Closed = boxID, false@@ -81,7 +81,7 @@ func TestExportMarkdownReferenceScope(t *testing.T) {sql.IndexTreeQueue(tree)}sql.FlushQueue()- Conf.Export.IncludeSubDocs, Conf.Export.IncludeRelatedDocs = scenario.includeSubDocs, scenario.includeRelated+ Conf.Export.Load().IncludeSubDocs, Conf.Export.Load().IncludeRelatedDocs = scenario.includeSubDocs, scenario.includeRelatedids := []string{source.ID}if scenario.selectTarget {ids = append(ids, target.ID)@@ -178,8 +178,8 @@ func TestExportMarkdownFootnoteAssetsAndCrossNotebook(t *testing.T) {func TestExportMarkdownFootnoteDeferredAsset(t *testing.T) {setupExportPublishTest(t)fixture, _, _, _ := prepareAssetDownloadDocumentTest(t)- Conf.Search = conf.NewSearch()- Conf.Export.IncludeSubDocs, Conf.Export.IncludeRelatedDocs = false, false+ Conf.Search.Store(conf.NewSearch())+ Conf.Export.Load().IncludeSubDocs, Conf.Export.Load().IncludeRelatedDocs = false, falsesource := newFootnoteTestDoc(t, fixture.box.ID, "Source")target := newFootnoteTestDoc(t, fixture.box.ID, "Target")source.Root.FirstChild.AppendChild(newFootnoteTestRef(target.Root.FirstChild.ID))@@ -230,7 +230,7 @@ func TestExportMarkdownOtherReferenceModes(t *testing.T) {t.Run(strconv.Itoa(mode), func(t *testing.T) {const boxID = "20261003000006-box0007"setupMarkdownReferencesTest(t, boxID)- Conf.Export.BlockRefMode = mode+ Conf.Export.Load().BlockRefMode = modesource := newFootnoteTestDoc(t, boxID, "Source")target := newFootnoteTestDoc(t, boxID, "Target")source.Root.FirstChild.AppendChild(newFootnoteTestRef(target.Root.FirstChild.ID))diff --git a/kernel/model/export_markdown_table_test.go b/kernel/model/export_markdown_table_test.goindex a037ccc7d4..7dab2625a3 100644--- a/kernel/model/export_markdown_table_test.go+++ b/kernel/model/export_markdown_table_test.go@@ -12,8 +12,8 @@ import (func TestExportMarkdownContentOmitsTableCellIAL(t *testing.T) {oldConf := ConfConf = NewAppConf()- Conf.Editor = conf.NewEditor()- Conf.Export = conf.NewExport()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Export.Store(conf.NewExport())t.Cleanup(func() { Conf = oldConf })luteEngine := NewLute()tree := parse.Parse("", []byte("| Left | Center | Right |\n| :--- | :---: | ---: |\n| **bold** | middle | end |\n"), luteEngine.ParseOptions)diff --git a/kernel/model/export_merge.go b/kernel/model/export_merge.goindex ee387661b7..8a8bdfca6f 100644--- a/kernel/model/export_merge.go+++ b/kernel/model/export_merge.go@@ -191,7 +191,7 @@ func buildBlockChildren(block *Block) (err error) {if IsBoxDoc(block.Box, block.ID) {listPath = "/"}- files, _, err := ListDocTree(block.Box, listPath, util.SortModeUnassigned, false, false, Conf.FileTree.MaxListCount)+ files, _, err := ListDocTree(block.Box, listPath, util.SortModeUnassigned, false, false, Conf.FileTree.Load().MaxListCount)if err != nil {return}diff --git a/kernel/model/export_options_fts5_test.go b/kernel/model/export_options_fts5_test.goindex a37c9ce26b..71122cbef0 100644--- a/kernel/model/export_options_fts5_test.go+++ b/kernel/model/export_options_fts5_test.go@@ -17,8 +17,8 @@ import (func TestExportOptionsReachMarkdownArchiveStages(t *testing.T) {const boxID = "20261009000000-box0001"setupMarkdownReferencesTest(t, boxID)- Conf.Export.AddTitle, Conf.Export.MarkdownYFM, Conf.Export.RemoveAssetsID = false, false, false- baseline := *Conf.Export+ Conf.Export.Load().AddTitle, Conf.Export.Load().MarkdownYFM, Conf.Export.Load().RemoveAssetsID = false, false, false+ baseline := *Conf.Export.Load()source := newFootnoteTestDoc(t, boxID, "Source")child := newFootnoteTestDoc(t, boxID, "Child")child.Path, child.HPath = "/"+source.ID+"/"+child.ID+".sy", "/Source/Child"@@ -66,7 +66,7 @@ func TestExportOptionsReachMarkdownArchiveStages(t *testing.T) {if overridden {wantDocuments = 3}- if documents != wantDocuments || *Conf.Export != baseline {+ if documents != wantDocuments || *Conf.Export.Load() != baseline {t.Fatalf("document inclusion or global configuration changed: got %d want %d", documents, wantDocuments)}if err := archive.Close(); err != nil {diff --git a/kernel/model/export_options_test.go b/kernel/model/export_options_test.goindex 19e5a3be09..4f091aea65 100644--- a/kernel/model/export_options_test.go+++ b/kernel/model/export_options_test.go@@ -12,9 +12,9 @@ import (func TestExportOptionsSnapshot(t *testing.T) {previous := Conf- Conf = &AppConf{Export: conf.NewExport()}+ Conf = &AppConf{Export: NewConfSection(conf.NewExport())}t.Cleanup(func() { Conf = previous })- baseline := *Conf.Export+ baseline := *Conf.Export.Load()options := &ExportOptions{AddTitle: new(false), InlineMemo: new(true), BlockRefMode: new(3), BlockEmbedMode: new(0),FileAnnotationRefMode: new(1), BlockRefTextLeft: new("["), BlockRefTextRight: new("]"),@@ -34,11 +34,11 @@ func TestExportOptionsSnapshot(t *testing.T) {t.Fatalf("option %s was not resolved", name)}}- if *Conf.Export != baseline || resolveExportOptions(nil) != baseline || resolveExportOptions(&ExportOptions{}) != baseline {+ if *Conf.Export.Load() != baseline || resolveExportOptions(nil) != baseline || resolveExportOptions(&ExportOptions{}) != baseline {t.Fatal("single-export options changed defaults or the global configuration")}*options.AddTitle = true- Conf.Export.BlockRefMode = 2+ Conf.Export.Load().BlockRefMode = 2if resolved.AddTitle || resolved.BlockRefMode != 3 {t.Fatal("resolved configuration retains a mutable reference to input or defaults")}@@ -55,9 +55,9 @@ func TestExportOptionsSnapshot(t *testing.T) {func TestExportOptionsConcurrentSnapshots(t *testing.T) {previous := Conf- Conf = &AppConf{Export: conf.NewExport()}+ Conf = &AppConf{Export: NewConfSection(conf.NewExport())}t.Cleanup(func() { Conf = previous })- baseline := *Conf.Export+ baseline := *Conf.Export.Load()var workers sync.WaitGroupfor i := range 64 {workers.Go(func() {@@ -71,7 +71,7 @@ func TestExportOptionsConcurrentSnapshots(t *testing.T) {})}workers.Wait()- if *Conf.Export != baseline {+ if *Conf.Export.Load() != baseline {t.Fatal("resolving concurrent exports changed global configuration")}}diff --git a/kernel/model/export_publish_test.go b/kernel/model/export_publish_test.goindex 3430d54165..40a510da28 100644--- a/kernel/model/export_publish_test.go+++ b/kernel/model/export_publish_test.go@@ -70,10 +70,10 @@ func setupExportPublishTest(t *testing.T) {sql.InitHistoryDatabase(true)sql.InitAssetContentDatabase(true)Conf = NewAppConf()- Conf.Editor = conf.NewEditor()- Conf.FileTree = conf.NewFileTree()- Conf.Search = conf.NewSearch()- Conf.Export = conf.NewExport()+ Conf.Editor.Store(conf.NewEditor())+ Conf.FileTree.Store(conf.NewFileTree())+ Conf.Search.Store(conf.NewSearch())+ Conf.Export.Store(conf.NewExport())treenode.InitBlockTree(true)invalidateEncryptedPublishAccessCache()diff --git a/kernel/model/export_related_test.go b/kernel/model/export_related_test.goindex 1c775ef3a8..ca15facc0f 100644--- a/kernel/model/export_related_test.go+++ b/kernel/model/export_related_test.go@@ -110,13 +110,13 @@ func setupExportRelatedTest(t *testing.T, boxIDs ...string) {util.TempDir = filepath.Join(testRoot, "temp")util.BlockTreeDBPath = filepath.Join(testRoot, "blocktree.db")Conf = NewAppConf()- Conf.Export = conf.NewExport()- Conf.Export.IncludeSubDocs = false- Conf.Export.IncludeRelatedDocs = true- Conf.FileTree = conf.NewFileTree()- Conf.Flashcard = conf.NewFlashcard()+ Conf.Export.Store(conf.NewExport())+ Conf.Export.Load().IncludeSubDocs = false+ Conf.Export.Load().IncludeRelatedDocs = true+ Conf.FileTree.Store(conf.NewFileTree())+ Conf.Flashcard.Store(conf.NewFlashcard())Conf.NotebookCrypto = conf.NewNotebookCrypto()- Conf.Sync = conf.NewSync()+ Conf.Sync.Store(conf.NewSync())if err := os.MkdirAll(util.DataDir, 0755); err != nil {t.Fatal(err)}diff --git a/kernel/model/export_task_markers_test.go b/kernel/model/export_task_markers_test.goindex 149ce7c4eb..d08cbcd3e9 100644--- a/kernel/model/export_task_markers_test.go+++ b/kernel/model/export_task_markers_test.go@@ -12,7 +12,11 @@ import (func TestExportMarkdownTaskMarkers(t *testing.T) {previousConf := ConfConf = NewAppConf()- Conf.Editor, Conf.Export = conf.NewEditor(), conf.NewExport()+ {+ confSectionValue0, confSectionValue1 := conf.NewEditor(), conf.NewExport()+ Conf.Editor.Store(confSectionValue0)+ Conf.Export.Store(confSectionValue1)+ }t.Cleanup(func() { Conf = previousConf })config := *conf.NewExport()config.AddTitle = falsediff --git a/kernel/model/file.go b/kernel/model/file.goindex cfe288505d..1daae045b5 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -210,6 +210,8 @@ func (box *Box) moveCorruptedData(filePath string) {}func SearchDocs(keyword string, flashcard bool, excludeIDs []string) (ret []map[string]string) {+ confSearchSnapshot := Conf.LoadSearch()+ret = []map[string]string{}var results []searchDocResult@@ -275,7 +277,7 @@ func SearchDocs(keyword string, flashcard bool, excludeIDs []string) (ret []map[keywords := strings.Fields(keyword)if 0 < len(keywords) {for _, box := range boxes {- if containsSearchDocKeyword(box.Name, keywords, Conf.Search.CaseSensitive) {+ if containsSearchDocKeyword(box.Name, keywords, confSearchSnapshot.CaseSensitive) {data := map[string]string{"path": "/", "hPath": box.Name + "/", "box": box.ID, "boxIcon": box.Icon}if flashcard {newFlashcardCount, dueFlashcardCount, flashcardCount := countBoxFlashcard(box.ID, deck, deckBlockIDs)@@ -286,12 +288,12 @@ func SearchDocs(keyword string, flashcard bool, excludeIDs []string) (ret []map[data["dueFlashcardCount"] = strconv.Itoa(dueFlashcardCount)data["flashcardCount"] = strconv.Itoa(flashcardCount)}- results = append(results, searchDocResult{data: data, exact: isExactSearchDocMatch(box.Name, keyword, Conf.Search.CaseSensitive)})+ results = append(results, searchDocResult{data: data, exact: isExactSearchDocMatch(box.Name, keyword, confSearchSnapshot.CaseSensitive)})}}- condition, args := buildSearchDocsCondition(keywords, excludeIDs, Conf.Search.Name, Conf.Search.Alias, Conf.Search.Memo)- rootBlocks = queryRootBlocks(condition, keyword, Conf.Search.Limit, args...)+ condition, args := buildSearchDocsCondition(keywords, excludeIDs, confSearchSnapshot.Name, confSearchSnapshot.Alias, confSearchSnapshot.Memo)+ rootBlocks = queryRootBlocks(condition, keyword, confSearchSnapshot.Limit, args...)} else {for _, box := range boxes {data := map[string]string{"path": "/", "hPath": box.Name + "/", "box": box.ID, "boxIcon": box.Icon}@@ -329,7 +331,7 @@ func SearchDocs(keyword string, flashcard bool, excludeIDs []string) (ret []map[data["dueFlashcardCount"] = strconv.Itoa(dueFlashcardCount)data["flashcardCount"] = strconv.Itoa(flashcardCount)}- results = append(results, searchDocResult{data: data, exact: isExactSearchDocBlockMatch(rootBlock, keyword, Conf.Search.CaseSensitive)})+ results = append(results, searchDocResult{data: data, exact: isExactSearchDocBlockMatch(rootBlock, keyword, confSearchSnapshot.CaseSensitive)})}sortSearchDocResults(results)@@ -473,7 +475,7 @@ func ResolveDocTreeSortMode(boxID, listPath string) (sortMode int, err error) {}}- sortMode = Conf.FileTree.Sort+ sortMode = Conf.FileTree.Load().SortboxConf := box.GetConf()if util.SortModeFileTree != boxConf.SortMode {sortMode = boxConf.SortMode@@ -648,6 +650,8 @@ func GetDoc(startID, endID, id string, index int, query string, queryTypes, quer// 加密笔记本打开文档时传入 boxID,blocktree/content 查询走加密 db;boxID 为空时 fall-through 全局 db。func GetDocInBox(startID, endID, id string, index int, query string, queryTypes, querySubTypes map[string]bool, queryMethod, mode int, size int, isBacklink bool, originalRefBlockIDs map[string]string, highlight, includeDocInfo bool, boxID string) (blockCount int, dom, parentID, parent2ID, rootID, typ string, eof, scroll bool, boxIDOut, docPath string, isBacklinkExpand bool, keywords []string, headingNumbers map[string]string, docInfo *BlockInfo, err error) {+ confEditorSnapshot := Conf.LoadEditor()+//os.MkdirAll("pprof", 0755)//cpuProfile, _ := os.Create("pprof/GetDoc")//pprof.StartCPUProfile(cpuProfile)@@ -765,8 +769,8 @@ func GetDocInBox(startID, endID, id string, index int, query string, queryTypes,blockCount = tree.DocBlockCount()if shouldReturnHeadingNumbers(mode, isBacklink) {headingNumbers = map[string]string{}- if headingNumberEnabled(tree, Conf.Editor.HeadingNumber) {- headingNumbers = headingNumberLabels(tree, Conf.Editor.HeadingNumberFormat)+ if headingNumberEnabled(tree, confEditorSnapshot.HeadingNumber) {+ headingNumbers = headingNumberLabels(tree, confEditorSnapshot.HeadingNumberFormat)}}if ast.NodeDocument == node.Type {@@ -802,7 +806,7 @@ func GetDocInBox(startID, endID, id string, index int, query string, queryTypes,childCount += treenode.CountBlockNodes(n)}- if childCount > Conf.Editor.DynamicLoadBlocks {+ if childCount > Conf.Editor.Load().DynamicLoadBlocks {scroll = truereturn ast.WalkStop}@@ -935,7 +939,7 @@ func GetDocInBox(startID, endID, id string, index int, query string, queryTypes,if ast.NodeCodeBlockCode == n.Type && !treenode.IsChartCodeBlockCode(n) {// 支持代码块搜索定位 https://github.com/siyuan-note/siyuan/issues/5520code := string(n.Tokens)- markedCode, matched := search.EncloseHighlightingRaw(code, keywords, search.SearchMarkLeft, search.SearchMarkRight, Conf.Search.CaseSensitive, false)+ markedCode, matched := search.EncloseHighlightingRaw(code, keywords, search.SearchMarkLeft, search.SearchMarkRight, Conf.Search.Load().CaseSensitive, false)if matched {n.Tokens = gulu.Str.ToBytes(markedCode)return ast.WalkContinue@@ -1029,7 +1033,7 @@ func loadNodesByStartEnd(tree *parse.Tree, startID, endID string) (nodes []*ast.break}- if len(nodes) >= Conf.Editor.DynamicLoadBlocks {+ if len(nodes) >= Conf.Editor.Load().DynamicLoadBlocks {// 如果加载到指定数量的块则停止加载break}@@ -1422,14 +1426,14 @@ func applyRequestedDocCreateTemplate(arg map[string]any, markdown, docID string)// ResolveDocCreateSaveLocation 按笔记本配置和全局配置解析新建文档的存放位置。func ResolveDocCreateSaveLocation(currentBoxID string) (boxID, pathTemplate string) {- pathTemplate = Conf.FileTree.DocCreateSavePath+ pathTemplate = Conf.FileTree.Load().DocCreateSavePathif box := Conf.Box(currentBoxID); nil != box {boxConf := box.GetConf()boxID = boxConf.DocCreateSaveBoxpathTemplate = boxConf.DocCreateSavePath}if "" == boxID && "" == pathTemplate {- boxID = Conf.FileTree.DocCreateSaveBox+ boxID = Conf.FileTree.Load().DocCreateSaveBox}if "" != boxID && nil == Conf.Box(boxID) {boxID = currentBoxID@@ -1438,7 +1442,7 @@ func ResolveDocCreateSaveLocation(currentBoxID string) (boxID, pathTemplate striboxID = currentBoxID}if "" == pathTemplate {- pathTemplate = Conf.FileTree.DocCreateSavePath+ pathTemplate = Conf.FileTree.Load().DocCreateSavePath}return}@@ -1754,7 +1758,7 @@ func moveDocs(fromPaths []string, toBoxID, toPath string, callback any, placeByCfor _, fromPath := range fromPaths {fromBox := pathsBoxes[fromPath]childDepth := util.GetChildDocDepth(filepath.Join(util.DataDir, fromBox.ID, fromPath))- if depth := strings.Count(toPath, "/") + childDepth; 6 < depth && !Conf.FileTree.AllowCreateDeeper {+ if depth := strings.Count(toPath, "/") + childDepth; 6 < depth && !Conf.FileTree.Load().AllowCreateDeeper {err = errors.New(Conf.Language(118))return}@@ -1786,6 +1790,8 @@ func moveDocs(fromPaths []string, toBoxID, toPath string, callback any, placeByCrefresh := newMoveDocsRefresh()movedDocs := make([]moveDocResult, 0, len(fromPaths))defer func() {+ confFileTreeSnapshot := Conf.LoadFileTree()+if 0 < len(movedDocs) {// 部分移动失败时也保存已完成文档的整组顺序,再通知前端刷新。if placeByConf {@@ -1794,7 +1800,7 @@ func moveDocs(fromPaths []string, toBoxID, toPath string, callback any, placeByCids = append(ids, util.GetTreeID(moved.NewPath))}position := "after"- if Conf.FileTree.CreateDocAtTop != nil && *Conf.FileTree.CreateDocAtTop {+ if confFileTreeSnapshot.CreateDocAtTop != nil && *confFileTreeSnapshot.CreateDocAtTop {position = "before"}if sortErr := toBox.placeDocsInSiblingOrder(strings.TrimSuffix(toPath, ".sy"), ids, "", position); sortErr != nil {@@ -2412,7 +2418,7 @@ func validateCreateDoc(boxID, p, title string, titleEmpty bool) (ret *createDocVhPath = path.Join(parentTree.HPath, title)}- if depth := strings.Count(p, "/"); 7 < depth && !Conf.FileTree.AllowCreateDeeper {+ if depth := strings.Count(p, "/"); 7 < depth && !Conf.FileTree.Load().AllowCreateDeeper {return nil, errors.New(Conf.Language(118))}if box.Exist(p) {@@ -3165,7 +3171,7 @@ func (box *Box) removeSort(ids []string) {}func (box *Box) setSortByConf(parentPath, id string) {- if *Conf.FileTree.CreateDocAtTop {+ if *Conf.FileTree.Load().CreateDocAtTop {box.addMinSort(parentPath, id)} else {box.addMaxSort(parentPath, id)diff --git a/kernel/model/file_annotation_test.go b/kernel/model/file_annotation_test.goindex 3b78b1db65..a3edd426f3 100644--- a/kernel/model/file_annotation_test.go+++ b/kernel/model/file_annotation_test.go@@ -156,8 +156,8 @@ func TestFileAnnotationExportEncryptedCompatibility(t *testing.T) {func TestFileAnnotationExportRejectsInvalidData(t *testing.T) {originalConf := ConfConf = NewAppConf()- Conf.Editor = conf.NewEditor()- Conf.Export = conf.NewExport()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Export.Store(conf.NewExport())t.Cleanup(func() { Conf = originalConf })oldWorkspace, oldDataDir := util.WorkspaceDir, util.DataDirutil.WorkspaceDir = t.TempDir()diff --git a/kernel/model/file_doc_sort_test.go b/kernel/model/file_doc_sort_test.goindex 87d51511c6..612c7444c8 100644--- a/kernel/model/file_doc_sort_test.go+++ b/kernel/model/file_doc_sort_test.go@@ -131,7 +131,7 @@ func TestSetDocSortModeValidationAndPersistence(t *testing.T) {if nil != err {t.Fatalf("remove document sort mode failed: %v", err)}- if nil != clearResult.SortMode || Conf.FileTree.Sort != clearResult.EffectiveSortMode {+ if nil != clearResult.SortMode || Conf.FileTree.Load().Sort != clearResult.EffectiveSortMode {t.Fatalf("cleared document sort mode did not inherit the global mode: %#v", clearResult)}tree, err = LoadTreeByBlockID(fixture.sourceID)diff --git a/kernel/model/file_index_test.go b/kernel/model/file_index_test.goindex 9a7036ad83..914b2b8f36 100644--- a/kernel/model/file_index_test.go+++ b/kernel/model/file_index_test.go@@ -68,9 +68,9 @@ func TestRemoveDocFlushesDatabaseIndex(t *testing.T) {}Conf = NewAppConf()- Conf.FileTree = conf.NewFileTree()+ Conf.FileTree.Store(conf.NewFileTree())Conf.NotebookCrypto = conf.NewNotebookCrypto()- Conf.Sync = conf.NewSync()+ Conf.Sync.Store(conf.NewSync())box := &Box{ID: "20260726000000-abcdefg"}boxConf := conf.NewBoxConf()@@ -192,11 +192,11 @@ func TestDocumentTemplatesWaitForDatabaseIndex(t *testing.T) {}Conf = NewAppConf()- Conf.FileTree = conf.NewFileTree()- Conf.Editor = conf.NewEditor()- Conf.Export = conf.NewExport()+ Conf.FileTree.Store(conf.NewFileTree())+ Conf.Editor.Store(conf.NewEditor())+ Conf.Export.Store(conf.NewExport())Conf.NotebookCrypto = conf.NewNotebookCrypto()- Conf.Sync = conf.NewSync()+ Conf.Sync.Store(conf.NewSync())Conf.Lang = "en"util.WorkingDir = filepath.Clean(filepath.Join("..", "..", "app"))initLang()diff --git a/kernel/model/file_move_sort_test.go b/kernel/model/file_move_sort_test.goindex f5f96c3528..25109acaf6 100644--- a/kernel/model/file_move_sort_test.go+++ b/kernel/model/file_move_sort_test.go@@ -51,7 +51,7 @@ func TestMoveDocsBatchCustomOrder(t *testing.T) {}treenode.UpsertBlockTree(tree)}- Conf.FileTree.CreateDocAtTop = &atTop+ Conf.FileTree.Load().CreateDocAtTop = &atTopa := addFileOperationTestDoc(t, f, "20260718000003-abcdefg", "A", false)b := addFileOperationTestDoc(t, f, "20260718000004-abcdefg", "B", false)if err := MoveDocs([]string{a.Path, b.Path}, f.box.ID, f.sourcePath, nil); err != nil {@@ -102,7 +102,7 @@ func TestMoveDocsBatchCustomOrder(t *testing.T) {if atTop {position = "after"}- Conf.FileTree.Sort = util.SortModeCustom+ Conf.FileTree.Load().Sort = util.SortModeCustomif _, err := ReorderDocTree([]string{b.ID, a.ID}, f.targetID, position, false, true); err != nil {t.Fatal(err)}diff --git a/kernel/model/file_test.go b/kernel/model/file_test.goindex ec58f608ea..1fa2c570d9 100644--- a/kernel/model/file_test.go+++ b/kernel/model/file_test.go@@ -60,9 +60,9 @@ func setupFileOperationTest(t *testing.T) *fileOperationTestFixture {util.BlockTreeDBPath = filepath.Join(tempDir, "blocktree.db")Conf = NewAppConf()Conf.Lang = testLang- Conf.FileTree = conf.NewFileTree()+ Conf.FileTree.Store(conf.NewFileTree())Conf.NotebookCrypto = conf.NewNotebookCrypto()- Conf.Sync = conf.NewSync()+ Conf.Sync.Store(conf.NewSync())box := &Box{ID: "20260718000000-abcdefg"}boxConf := conf.NewBoxConf()@@ -181,7 +181,7 @@ func TestListDocTreeUsesPathIDForInvalidPropertiesID(t *testing.T) {func TestResolveDocTreeSortModeInheritance(t *testing.T) {fixture := setupFileOperationTest(t)- Conf.FileTree.Sort = util.SortModeSizeDESC+ Conf.FileTree.Load().Sort = util.SortModeSizeDESCboxConf := fixture.box.GetConf()boxConf.SortMode = util.SortModeCreatedASCif err := fixture.box.SaveConf(boxConf); nil != err {@@ -260,8 +260,8 @@ func TestResolveDocTreeSortModeInheritance(t *testing.T) {func TestCustomSortMaintenanceIgnoresEffectiveModeAndListLimit(t *testing.T) {fixture := setupFileOperationTest(t)- Conf.FileTree.Sort = util.SortModeNameASC- Conf.FileTree.MaxListCount = 1+ Conf.FileTree.Load().Sort = util.SortModeNameASC+ Conf.FileTree.Load().MaxListCount = 1boxConf := fixture.box.GetConf()boxConf.SortMode = util.SortModeFileTreeif err := fixture.box.SaveConf(boxConf); nil != err {@@ -327,7 +327,7 @@ func TestCustomSortMaintenanceIgnoresEffectiveModeAndListLimit(t *testing.T) {func TestReorderDocsUsesCompleteSiblingOrder(t *testing.T) {fixture := setupFileOperationTest(t)- Conf.FileTree.MaxListCount = 2+ Conf.FileTree.Load().MaxListCount = 2hiddenTree := addFileOperationTestDoc(t, fixture, "20260718000003-abcdefg", "Hidden", true)unlistedTree := addFileOperationTestDoc(t, fixture, "20260718000004-abcdefg", "Unlisted", false)confPath := filepath.Join(util.DataDir, fixture.box.ID, ".siyuan", "sort.json")@@ -467,8 +467,8 @@ func assertNotebookCustomOrder(t *testing.T, expected []string) {func TestGetDocOptionallyIncludesDocInfo(t *testing.T) {fixture := setupFileOperationTest(t)- Conf.Editor = conf.NewEditor()- Conf.Export = conf.NewExport()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Export.Store(conf.NewExport())expected, err := GetDocInfo(fixture.sourceID)if nil != err {t.Fatalf("get standalone document info failed: %v", err)diff --git a/kernel/model/file_tree_reorder.go b/kernel/model/file_tree_reorder.goindex f1bc138334..76bd0c65e4 100644--- a/kernel/model/file_tree_reorder.go+++ b/kernel/model/file_tree_reorder.go@@ -82,7 +82,7 @@ type DocTreeReorderResult struct {func resolveDraggedDocSortMode(boxID, listPath string) (*int, error) {mode := util.SortModeCustomif listPath == "/" {- if Conf.FileTree.Sort == util.SortModeCustom {+ if Conf.FileTree.Load().Sort == util.SortModeCustom {mode = util.SortModeFileTree}return &mode, nildiff --git a/kernel/model/file_tree_reorder_test.go b/kernel/model/file_tree_reorder_test.goindex 5d5384a95b..a7e67cb97b 100644--- a/kernel/model/file_tree_reorder_test.go+++ b/kernel/model/file_tree_reorder_test.go@@ -16,8 +16,8 @@ import (func TestDocTreeReorderConflictAndCompleteOrder(t *testing.T) {f := setupFileOperationTest(t)- Conf.FileTree.Sort = util.SortModeNameASC- Conf.FileTree.MaxListCount = 1+ Conf.FileTree.Load().Sort = util.SortModeNameASC+ Conf.FileTree.Load().MaxListCount = 1hidden := addFileOperationTestDoc(t, f, "20260718000003-abcdefg", "Hidden", true)unlisted := addFileOperationTestDoc(t, f, "20260718000004-abcdefg", "Unlisted", false)confPath := filepath.Join(util.DataDir, f.box.ID, ".siyuan", "sort.json")@@ -45,14 +45,14 @@ func TestDocTreeReorderConflictAndCompleteOrder(t *testing.T) {}assertSiblingCustomOrder(t, f.box.ID, "/", []string{hidden.ID, f.targetID, f.sourceID, unlisted.ID})mode, err := ResolveDocTreeSortMode(f.box.ID, "/")- if err != nil || mode != util.SortModeCustom || Conf.FileTree.Sort != util.SortModeNameASC {+ if err != nil || mode != util.SortModeCustom || Conf.FileTree.Load().Sort != util.SortModeNameASC {t.Fatalf("confirmation did not set only notebook mode: %d, %v", mode, err)}}func TestDocTreeReorderEqualValuesPersist(t *testing.T) {f := setupFileOperationTest(t)- Conf.FileTree.Sort = util.SortModeSubDocCountASC+ Conf.FileTree.Load().Sort = util.SortModeSubDocCountASCresult, err := ReorderDocTree([]string{f.sourceID}, f.targetID, "before", false, false)if err != nil || result.Conflict || !result.Changed {t.Fatalf("equal-value move failed: %+v, %v", result, err)@@ -90,7 +90,7 @@ func TestDocTreeReorderRecoversUnreadableSort(t *testing.T) {func TestDocTreeReorderRejectsDescendantTargetsWithLocalizedMessage(t *testing.T) {f := setupFileOperationTest(t)- Conf.FileTree.Sort = util.SortModeNameASC+ Conf.FileTree.Load().Sort = util.SortModeNameASCchildPath := strings.TrimSuffix(f.sourcePath, ".sy") + "/20260718000003-abcdefg.sy"grandchildPath := strings.TrimSuffix(childPath, ".sy") + "/20260718000004-abcdefg.sy"for _, docPath := range []string{childPath, grandchildPath} {@@ -136,7 +136,7 @@ func TestDocTreeSortAllModesRespectTies(t *testing.T) {func TestDocTreeReorderCrossParentPreviewDoesNotMove(t *testing.T) {f := setupFileOperationTest(t)- Conf.FileTree.Sort = util.SortModeNameASC+ Conf.FileTree.Load().Sort = util.SortModeNameASCchildPath := "/" + f.sourceID + "/20260718000003-abcdefg.sy"child := treenode.NewTree(f.box.ID, childPath, "/Source/A", "A")if _, err := filesys.WriteTree(child); err != nil {@@ -163,7 +163,7 @@ func TestDocTreeReorderCrossParentPreviewDoesNotMove(t *testing.T) {func TestDocTreeReorderMultipleSourcesKeepSelectionOrder(t *testing.T) {f := setupFileOperationTest(t)- Conf.FileTree.Sort = util.SortModeNameASC+ Conf.FileTree.Load().Sort = util.SortModeNameASCextra := addFileOperationTestDoc(t, f, "20260718000003-abcdefg", "Z", false)result, err := ReorderDocTree([]string{extra.ID, f.targetID}, f.sourceID, "before", false, true)if err != nil || !result.Conflict {@@ -174,7 +174,7 @@ func TestDocTreeReorderMultipleSourcesKeepSelectionOrder(t *testing.T) {func TestDocTreeReorderInheritsCustomPanelSort(t *testing.T) {f := setupFileOperationTest(t)- Conf.FileTree.Sort = util.SortModeCustom+ Conf.FileTree.Load().Sort = util.SortModeCustomboxConf := f.box.GetConf()boxConf.SortMode = util.SortModeNameASCif err := f.box.SaveConf(boxConf); err != nil {@@ -188,7 +188,7 @@ func TestDocTreeReorderInheritsCustomPanelSort(t *testing.T) {t.Fatalf("expected panel inheritance, got %d", mode)}assertSiblingCustomOrder(t, f.box.ID, "/", []string{f.targetID, f.sourceID})- Conf.FileTree.Sort = util.SortModeCreatedASC+ Conf.FileTree.Load().Sort = util.SortModeCreatedASCif mode, err := ResolveDocTreeSortMode(f.box.ID, "/"); err != nil || mode != util.SortModeCreatedASC {t.Fatalf("notebook did not follow later panel changes: %d, %v", mode, err)}@@ -196,7 +196,7 @@ func TestDocTreeReorderInheritsCustomPanelSort(t *testing.T) {func TestDraggedDocSortModeUsesParentInheritance(t *testing.T) {f := setupFileOperationTest(t)- Conf.FileTree.Sort = util.SortModeNameASC+ Conf.FileTree.Load().Sort = util.SortModeNameASCparent, err := LoadTreeByBlockID(f.sourceID)if err != nil {t.Fatal(err)diff --git a/kernel/model/flashcard.go b/kernel/model/flashcard.goindex 6d07e05ffe..4201c2aa8b 100644--- a/kernel/model/flashcard.go+++ b/kernel/model/flashcard.go@@ -747,6 +747,8 @@ func newFlashcard(card riff.Card, deckID string, now time.Time) *Flashcard {}func GetNotebookDueFlashcards(boxID string, reviewedCardIDs []string) (ret []*Flashcard, unreviewedCount, unreviewedNewCardCount, unreviewedOldCardCount int, err error) {+ confFlashcardSnapshot := Conf.LoadFlashcard()+if IsEncryptedBox(boxID) {err = errors.New(Conf.Language(393))return@@ -788,7 +790,7 @@ func GetNotebookDueFlashcards(boxID string, reviewedCardIDs []string) (ret []*Flreturn}- cards, unreviewedCnt, unreviewedNewCardCnt, unreviewedOldCardCnt := getDeckDueCards(deck, reviewedCardIDs, treeBlockIDs, Conf.Flashcard.NewCardLimit, Conf.Flashcard.ReviewCardLimit, Conf.Flashcard.ReviewMode)+ cards, unreviewedCnt, unreviewedNewCardCnt, unreviewedOldCardCnt := getDeckDueCards(deck, reviewedCardIDs, treeBlockIDs, confFlashcardSnapshot.NewCardLimit, confFlashcardSnapshot.ReviewCardLimit, confFlashcardSnapshot.ReviewMode)now := time.Now()for _, card := range cards {ret = append(ret, newFlashcard(card, builtinDeckID, now))@@ -803,6 +805,8 @@ func GetNotebookDueFlashcards(boxID string, reviewedCardIDs []string) (ret []*Fl}func GetTreeDueFlashcards(rootID string, reviewedCardIDs []string) (ret []*Flashcard, unreviewedCount, unreviewedNewCardCount, unreviewedOldCardCount int, err error) {+ confFlashcardSnapshot := Conf.LoadFlashcard()+if err = validateFlashcardTree(rootID); err != nil {return}@@ -817,8 +821,8 @@ func GetTreeDueFlashcards(rootID string, reviewedCardIDs []string) (ret []*Flash}_, treeBlockIDs := getTreeSubTreeChildBlocks(rootID)- newCardLimit := Conf.Flashcard.NewCardLimit- reviewCardLimit := Conf.Flashcard.ReviewCardLimit+ newCardLimit := confFlashcardSnapshot.NewCardLimit+ reviewCardLimit := confFlashcardSnapshot.ReviewCardLimit// 文档级新卡/复习卡上限控制 Document-level new card/review card limit control https://github.com/siyuan-note/siyuan/issues/9365ial := sql.GetBlockAttrs(rootID)if newCardLimitStr := ial["custom-riff-new-card-limit"]; "" != newCardLimitStr {@@ -836,7 +840,7 @@ func GetTreeDueFlashcards(rootID string, reviewedCardIDs []string) (ret []*Flash}}- cards, unreviewedCnt, unreviewedNewCardCnt, unreviewedOldCardCnt := getDeckDueCards(deck, reviewedCardIDs, treeBlockIDs, newCardLimit, reviewCardLimit, Conf.Flashcard.ReviewMode)+ cards, unreviewedCnt, unreviewedNewCardCnt, unreviewedOldCardCnt := getDeckDueCards(deck, reviewedCardIDs, treeBlockIDs, newCardLimit, reviewCardLimit, confFlashcardSnapshot.ReviewMode)now := time.Now()for _, card := range cards {ret = append(ret, newFlashcard(card, builtinDeckID, now))@@ -904,13 +908,15 @@ func GetDueFlashcards(deckID string, reviewedCardIDs []string) (ret []*Flashcard}func getDueFlashcards(deckID string, reviewedCardIDs []string) (ret []*Flashcard, unreviewedCount, unreviewedNewCardCount, unreviewedOldCardCount int) {+ confFlashcardSnapshot := Conf.LoadFlashcard()+deck := Decks[deckID]if nil == deck {logging.LogWarnf("deck not found [%s]", deckID)return}- cards, unreviewedCnt, unreviewedNewCardCnt, unreviewedOldCardCnt := getDeckDueCards(deck, reviewedCardIDs, nil, Conf.Flashcard.NewCardLimit, Conf.Flashcard.ReviewCardLimit, Conf.Flashcard.ReviewMode)+ cards, unreviewedCnt, unreviewedNewCardCnt, unreviewedOldCardCnt := getDeckDueCards(deck, reviewedCardIDs, nil, confFlashcardSnapshot.NewCardLimit, confFlashcardSnapshot.ReviewCardLimit, confFlashcardSnapshot.ReviewMode)now := time.Now()for _, card := range cards {ret = append(ret, newFlashcard(card, deckID, now))@@ -925,6 +931,8 @@ func getDueFlashcards(deckID string, reviewedCardIDs []string) (ret []*Flashcard}func getAllDueFlashcards(reviewedCardIDs []string) (ret []*Flashcard, unreviewedCount, unreviewedNewCardCount, unreviewedOldCardCount int) {+ confFlashcardSnapshot := Conf.LoadFlashcard()+now := time.Now()for _, deck := range Decks {if deck.ID != builtinDeckID {@@ -933,7 +941,7 @@ func getAllDueFlashcards(reviewedCardIDs []string) (ret []*Flashcard, unreviewedcontinue}- cards, unreviewedCnt, unreviewedNewCardCnt, unreviewedOldCardCnt := getDeckDueCards(deck, reviewedCardIDs, nil, Conf.Flashcard.NewCardLimit, Conf.Flashcard.ReviewCardLimit, Conf.Flashcard.ReviewMode)+ cards, unreviewedCnt, unreviewedNewCardCnt, unreviewedOldCardCnt := getDeckDueCards(deck, reviewedCardIDs, nil, confFlashcardSnapshot.NewCardLimit, confFlashcardSnapshot.ReviewCardLimit, confFlashcardSnapshot.ReviewMode)unreviewedCount += unreviewedCntunreviewedNewCardCount += unreviewedNewCardCntunreviewedOldCardCount += unreviewedOldCardCnt@@ -1168,6 +1176,8 @@ func (tx *Transaction) doAddFlashcards(operation *Operation) (ret *TxErr) {}func LoadFlashcards() {+ confFlashcardSnapshot := Conf.LoadFlashcard()+riffSavePath := getRiffDir()if err := os.MkdirAll(riffSavePath, 0755); err != nil {logging.LogErrorf("create riff dir [%s] failed: %s", riffSavePath, err)@@ -1185,7 +1195,7 @@ func LoadFlashcards() {name := entry.Name()if before, ok := strings.CutSuffix(name, ".deck"); ok {deckID := before- deck, loadErr := riff.LoadDeck(riffSavePath, deckID, Conf.Flashcard.RequestRetention, Conf.Flashcard.MaximumInterval, Conf.Flashcard.Weights)+ deck, loadErr := riff.LoadDeck(riffSavePath, deckID, confFlashcardSnapshot.RequestRetention, confFlashcardSnapshot.MaximumInterval, confFlashcardSnapshot.Weights)if nil != loadErr {logging.LogErrorf("load deck [%s] failed: %s", name, loadErr)continue@@ -1272,8 +1282,10 @@ func createDeck(name string) (deck *riff.Deck, err error) {}func createDeck0(name string, deckID string) (deck *riff.Deck, err error) {+ confFlashcardSnapshot := Conf.LoadFlashcard()+riffSavePath := getRiffDir()- deck, err = riff.LoadDeck(riffSavePath, deckID, Conf.Flashcard.RequestRetention, Conf.Flashcard.MaximumInterval, Conf.Flashcard.Weights)+ deck, err = riff.LoadDeck(riffSavePath, deckID, confFlashcardSnapshot.RequestRetention, confFlashcardSnapshot.MaximumInterval, confFlashcardSnapshot.Weights)if err != nil {logging.LogErrorf("load deck [%s] failed: %s", deckID, err)returndiff --git a/kernel/model/graph.go b/kernel/model/graph.goindex 62ac77b0a2..50037e8d5e 100644--- a/kernel/model/graph.go+++ b/kernel/model/graph.go@@ -61,6 +61,8 @@ type GraphArrowsTo struct {}func BuildTreeGraph(id, query string) (boxID string, nodes []*GraphNode, links []*GraphLink) {+ confGraphSnapshot := Conf.LoadGraph()+nodes = []*GraphNode{}links = []*GraphLink{}@@ -85,10 +87,10 @@ func BuildTreeGraph(id, query string) (boxID string, nodes []*GraphNode, links [var sqlBlocks []*sql.Blockvar rootID stringif ast.NodeDocument == node.Type {- sqlBlocks = sql.GetAllChildBlocks([]string{block.ID}, stmt, Conf.Graph.MaxBlocks)+ sqlBlocks = sql.GetAllChildBlocks([]string{block.ID}, stmt, confGraphSnapshot.MaxBlocks)rootID = block.ID} else {- sqlBlocks = sql.GetChildBlocks(block.ID, stmt, Conf.Graph.MaxBlocks)+ sqlBlocks = sql.GetChildBlocks(block.ID, stmt, confGraphSnapshot.MaxBlocks)}blocks := fromSQLBlocks(&sqlBlocks, "", 0)if "" != rootID {@@ -156,7 +158,7 @@ func BuildTreeGraph(id, query string) (boxID string, nodes []*GraphNode, links [blocks = append(blocks, forwardlinks...)blocks = append(blocks, backlinks...)buildLinks(&blocks, &links, true)- if Conf.Graph.Local.Tag {+ if confGraphSnapshot.Local.Tag {p := sqlBlock.PathlinkTagBlocks(&blocks, &nodes, &links, p)}@@ -166,6 +168,8 @@ func BuildTreeGraph(id, query string) (boxID string, nodes []*GraphNode, links [}func BuildGraph(query string) (boxID string, nodes []*GraphNode, links []*GraphLink) {+ confGraphSnapshot := Conf.LoadGraph()+nodes = []*GraphNode{}links = []*GraphLink{}@@ -187,7 +191,7 @@ func BuildGraph(query string) (boxID string, nodes []*GraphNode, links []*GraphL}rootIDs = gulu.Str.RemoveDuplicatedElem(rootIDs)- sqlBlocks := sql.GetAllChildBlocks(rootIDs, stmt, Conf.Graph.MaxBlocks)+ sqlBlocks := sql.GetAllChildBlocks(rootIDs, stmt, confGraphSnapshot.MaxBlocks)treeBlocks := fromSQLBlocks(&sqlBlocks, "", 0)treeBlocks = filterDailyNote(treeBlocks, false)genTreeNodes(treeBlocks, &nodes, &links, false)@@ -209,7 +213,7 @@ func BuildGraph(query string) (boxID string, nodes []*GraphNode, links []*GraphLblocks = append(blocks, forwardlinks...)blocks = append(blocks, backlinks...)buildLinks(&blocks, &links, false)- if Conf.Graph.Global.Tag {+ if confGraphSnapshot.Global.Tag {linkTagBlocks(&blocks, &nodes, &links, "")}markLinkedNodes(&nodes, &links, false)@@ -219,15 +223,17 @@ func BuildGraph(query string) (boxID string, nodes []*GraphNode, links []*GraphL}func linkTagBlocks(blocks *[]*Block, nodes *[]*GraphNode, links *[]*GraphLink, p string) {+ confGraphSnapshot := Conf.LoadGraph()+tagSpans := sql.QueryTagSpans(p)if 1 > len(tagSpans) {return}isGlobal := "" == p- nodeSize := Conf.Graph.Global.NodeSize+ nodeSize := confGraphSnapshot.Global.NodeSizeif !isGlobal {- nodeSize = Conf.Graph.Local.NodeSize+ nodeSize = confGraphSnapshot.Local.NodeSize}linkTagSpans(*blocks, nodes, links, tagSpans, isGlobal, nodeSize)}@@ -292,7 +298,7 @@ func linkTagSpans(blocks []*Block, nodes *[]*GraphNode, links *[]*GraphLink, tagfunc growTreeGraph(forwardlinks, backlinks *[]*Block, nodes *[]*GraphNode) {forwardDepth, backDepth := 0, 0visitedIDs := graphNodeIDs(*nodes)- growLinkedNodes(forwardlinks, backlinks, nodes, visitedIDs, Conf.Graph.Local.NodeSize, &forwardDepth, &backDepth)+ growLinkedNodes(forwardlinks, backlinks, nodes, visitedIDs, Conf.Graph.Load().Local.NodeSize, &forwardDepth, &backDepth)}func growLinkedNodes(forwardlinks, backlinks *[]*Block, nodes *[]*GraphNode, visitedIDs map[string]bool, nodeSize float64, forwardDepth, backDepth *int) {@@ -367,6 +373,8 @@ func graphNodeIDs(nodes []*GraphNode) map[string]bool {}func buildLinks(defs *[]*Block, links *[]*GraphLink, local bool) {+ confGraphSnapshot := Conf.LoadGraph()+for _, def := range *defs {for _, ref := range def.Refs {link := &GraphLink{@@ -375,11 +383,11 @@ func buildLinks(defs *[]*Block, links *[]*GraphLink, local bool) {Ref: true,}if local {- if Conf.Graph.Local.Arrow {+ if confGraphSnapshot.Local.Arrow {link.Arrows = &GraphArrows{To: &GraphArrowsTo{Enabled: true}}}} else {- if Conf.Graph.Global.Arrow {+ if confGraphSnapshot.Global.Arrow {link.Arrows = &GraphArrows{To: &GraphArrowsTo{Enabled: true}}}}@@ -389,9 +397,11 @@ func buildLinks(defs *[]*Block, links *[]*GraphLink, local bool) {}func genTreeNodes(blocks []*Block, nodes *[]*GraphNode, links *[]*GraphLink, local bool) {- nodeSize := Conf.Graph.Local.NodeSize+ confGraphSnapshot := Conf.LoadGraph()++ nodeSize := confGraphSnapshot.Local.NodeSizeif !local {- nodeSize = Conf.Graph.Global.NodeSize+ nodeSize = confGraphSnapshot.Global.NodeSize}for _, block := range blocks {@@ -414,9 +424,11 @@ func genTreeNodes(blocks []*Block, nodes *[]*GraphNode, links *[]*GraphLink, loc}func markLinkedNodes(nodes *[]*GraphNode, links *[]*GraphLink, local bool) {- nodeSize := Conf.Graph.Local.NodeSize+ confGraphSnapshot := Conf.LoadGraph()++ nodeSize := confGraphSnapshot.Local.NodeSizeif !local {- nodeSize = Conf.Graph.Global.NodeSize+ nodeSize = confGraphSnapshot.Global.NodeSize}markLinkedNodesWithSize(nodes, links, nodeSize)}@@ -462,7 +474,9 @@ func removeDuplicatedUnescape(nodes []*GraphNode) (ret []*GraphNode) {}func pruneUnref(nodes *[]*GraphNode, links *[]*GraphLink) {- pruneUnrefWithLimits(nodes, links, Conf.Graph.Global.MinRefs, Conf.Graph.MaxBlocks)+ confGraphSnapshot := Conf.LoadGraph()++ pruneUnrefWithLimits(nodes, links, confGraphSnapshot.Global.MinRefs, confGraphSnapshot.MaxBlocks)}func pruneUnrefWithLimits(nodes *[]*GraphNode, links *[]*GraphLink, minRefs, maxBlocks int) {@@ -504,83 +518,85 @@ func nodeContentByBlock(block *Block) (ret string) {}func graphTypeFilter(local bool) string {+ confGraphSnapshot := Conf.LoadGraph()+var inList []string- paragraph := Conf.Graph.Local.Paragraph+ paragraph := confGraphSnapshot.Local.Paragraphif !local {- paragraph = Conf.Graph.Global.Paragraph+ paragraph = confGraphSnapshot.Global.Paragraph}if paragraph {inList = append(inList, "'p'")}- heading := Conf.Graph.Local.Heading+ heading := confGraphSnapshot.Local.Headingif !local {- heading = Conf.Graph.Global.Heading+ heading = confGraphSnapshot.Global.Heading}if heading {inList = append(inList, "'h'")}- math := Conf.Graph.Local.Math+ math := confGraphSnapshot.Local.Mathif !local {- math = Conf.Graph.Global.Math+ math = confGraphSnapshot.Global.Math}if math {inList = append(inList, "'m'")}- code := Conf.Graph.Local.Code+ code := confGraphSnapshot.Local.Codeif !local {- code = Conf.Graph.Global.Code+ code = confGraphSnapshot.Global.Code}if code {inList = append(inList, "'c'")}- table := Conf.Graph.Local.Table+ table := confGraphSnapshot.Local.Tableif !local {- table = Conf.Graph.Global.Table+ table = confGraphSnapshot.Global.Table}if table {inList = append(inList, "'t'")}- list := Conf.Graph.Local.List+ list := confGraphSnapshot.Local.Listif !local {- list = Conf.Graph.Global.List+ list = confGraphSnapshot.Global.List}if list {inList = append(inList, "'l'")}- listItem := Conf.Graph.Local.ListItem+ listItem := confGraphSnapshot.Local.ListItemif !local {- listItem = Conf.Graph.Global.ListItem+ listItem = confGraphSnapshot.Global.ListItem}if listItem {inList = append(inList, "'i'")}- blockquote := Conf.Graph.Local.Blockquote+ blockquote := confGraphSnapshot.Local.Blockquoteif !local {- blockquote = Conf.Graph.Global.Blockquote+ blockquote = confGraphSnapshot.Global.Blockquote}if blockquote {inList = append(inList, "'b'")}- super := Conf.Graph.Local.Super+ super := confGraphSnapshot.Local.Superif !local {- super = Conf.Graph.Global.Super+ super = confGraphSnapshot.Global.Super}if super {inList = append(inList, "'s'")}- callout := Conf.Graph.Local.Callout+ callout := confGraphSnapshot.Local.Calloutif !local {- callout = Conf.Graph.Global.Callout+ callout = confGraphSnapshot.Global.Callout}if callout {inList = append(inList, "'callout'")@@ -591,11 +607,13 @@ func graphTypeFilter(local bool) string {}func filterDailyNote(blocks []*Block, local bool) (ret []*Block) {+ confGraphSnapshot := Conf.LoadGraph()+// Graph dailynote filtering not working https://github.com/siyuan-note/siyuan/issues/16463- dailyNote := Conf.Graph.Local.DailyNote+ dailyNote := confGraphSnapshot.Local.DailyNoteif !local {- dailyNote = Conf.Graph.Global.DailyNote+ dailyNote = confGraphSnapshot.Global.DailyNote}if dailyNote {@@ -634,9 +652,11 @@ func graphDailyNoteFilter(local bool) string {}func dailyNotePaths(local bool) (ret []string) {- dailyNote := Conf.Graph.Local.DailyNote+ confGraphSnapshot := Conf.LoadGraph()++ dailyNote := confGraphSnapshot.Local.DailyNoteif !local {- dailyNote = Conf.Graph.Global.DailyNote+ dailyNote = confGraphSnapshot.Global.DailyNote}if dailyNote {@@ -692,7 +712,7 @@ func query2Stmt(queryStr string) (ret string) {continue}buf.WriteString("(content LIKE " + conf.SearchLikePattern(part))- buf.WriteString(Conf.Search.NAMFilter(part))+ buf.WriteString(Conf.Search.Load().NAMFilter(part))buf.WriteString(")")if i < len(parts)-1 {buf.WriteString(" AND ")diff --git a/kernel/model/graph_test.go b/kernel/model/graph_test.goindex 1d43d84106..e3e11b7037 100644--- a/kernel/model/graph_test.go+++ b/kernel/model/graph_test.go@@ -59,8 +59,8 @@ func TestLinkTagSpansPreservesGraph(t *testing.T) {func TestGraphSearchLiteralWildcards(t *testing.T) {previous := Conf- Conf = &AppConf{Search: conf.NewSearch()}- Conf.Search.Name, Conf.Search.Alias, Conf.Search.Memo = true, true, true+ Conf = &AppConf{Search: NewConfSection(conf.NewSearch())}+ Conf.Search.Load().Name, Conf.Search.Load().Alias, Conf.Search.Load().Memo = true, true, truet.Cleanup(func() { Conf = previous })db, err := gosql.Open("sqlite3_extended", ":memory:")if err != nil {@@ -155,7 +155,7 @@ func TestGrowLinkedNodesUsesIndexesAndStopsCycles(t *testing.T) {// 防止标签内容闭合字符串字面量注入查询 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-5rwv-4j4c-f954func TestQuery2StmtEscapesTagQuote(t *testing.T) {oldConf := Conf- Conf = &AppConf{Search: conf.NewSearch()}+ Conf = &AppConf{Search: NewConfSection(conf.NewSearch())}t.Cleanup(func() {Conf = oldConf})diff --git a/kernel/model/heading.go b/kernel/model/heading.goindex b1222cab97..e4f215ed50 100644--- a/kernel/model/heading.go+++ b/kernel/model/heading.go@@ -366,7 +366,7 @@ func Heading2Doc(srcHeadingID, targetBoxID, targetPath, previousPath string, toT}box := Conf.Box(targetBoxID)- headingText := getNodeRefText0(headingNode, Conf.Editor.BlockRefDynamicAnchorTextMaxLen, true)+ headingText := getNodeRefText0(headingNode, Conf.Editor.Load().BlockRefDynamicAnchorTextMaxLen, true)if strings.Contains(headingText, "/") {headingText = strings.ReplaceAll(headingText, "/", "_")util.PushMsg(Conf.language(246), 7000)diff --git a/kernel/model/heading_number.go b/kernel/model/heading_number.goindex 1cdaae7fee..e339d4ff2e 100644--- a/kernel/model/heading_number.go+++ b/kernel/model/heading_number.go@@ -78,15 +78,17 @@ func headingNumberEnabled(tree *parse.Tree, defaultEnabled bool) bool {// GetHeadingNumbers 返回文档标题块 ID 到显示编号的映射。func GetHeadingNumbers(rootID, boxID string) (ret map[string]string, err error) {+ confEditorSnapshot := Conf.LoadEditor()+FlushTxQueue()tree, err := loadTreeByBlockIDInBox(rootID, boxID)if err != nil || nil == tree {return map[string]string{}, err}- if !headingNumberEnabled(tree, Conf.Editor.HeadingNumber) {+ if !headingNumberEnabled(tree, confEditorSnapshot.HeadingNumber) {return map[string]string{}, nil}- return headingNumberLabels(tree, Conf.Editor.HeadingNumberFormat), nil+ return headingNumberLabels(tree, confEditorSnapshot.HeadingNumberFormat), nil}func headingNumberLabels(tree *parse.Tree, format string) map[string]string {diff --git a/kernel/model/history.go b/kernel/model/history.goindex 3f06ec952a..f1682a965d 100644--- a/kernel/model/history.go+++ b/kernel/model/history.go@@ -54,7 +54,7 @@ import (var historyTicker = time.NewTicker(time.Minute * 10)func AutoGenerateFileHistory() {- ChangeHistoryTick(Conf.Editor.GenerateHistoryInterval)+ ChangeHistoryTick(Conf.Editor.Load().GenerateHistoryInterval)for {<-historyTicker.Ctask.AppendTask(task.HistoryGenerateFile, GenerateFileHistory)@@ -65,7 +65,7 @@ func AutoGenerateFileHistory() {// 锁定后定时器(GenerateFileHistory)无法为加密笔记本生成历史(不在 GetOpenedBoxes 里)。func GenerateFileHistoryForBox(box *Box) {defer logging.Recover()- if 1 > Conf.Editor.GenerateHistoryInterval {+ if 1 > Conf.Editor.Load().GenerateHistoryInterval {return}box.generateDocHistory0()@@ -74,7 +74,7 @@ func GenerateFileHistoryForBox(box *Box) {func GenerateFileHistory() {defer logging.Recover()- if 1 > Conf.Editor.GenerateHistoryInterval {+ if 1 > Conf.Editor.Load().GenerateHistoryInterval {return}@@ -858,7 +858,7 @@ func buildSearchHistoryQueryFilter(query, op, box, table string, typ int) (stmtstmt += " AND path LIKE '%/storage/av/%'"}- ago := time.Now().Add(-24 * time.Hour * time.Duration(Conf.Editor.HistoryRetentionDays))+ ago := time.Now().Add(-24 * time.Hour * time.Duration(Conf.Editor.Load().HistoryRetentionDays))stmt += " AND CAST(created AS INTEGER) > " + fmt.Sprintf("%d", ago.Unix()) + ""return}@@ -1056,7 +1056,7 @@ func clearOutdatedHistoryDir() {}now := time.Now()- ago := now.Add(-24 * time.Hour * time.Duration(Conf.Editor.HistoryRetentionDays)).Unix()+ ago := now.Add(-24 * time.Hour * time.Duration(Conf.Editor.Load().HistoryRetentionDays)).Unix()var removes []stringfor _, dir := range dirs {dirInfo, err := dir.Info()diff --git a/kernel/model/history_diff.go b/kernel/model/history_diff.goindex 1789ca129c..49ba35a5ba 100644--- a/kernel/model/history_diff.go+++ b/kernel/model/history_diff.go@@ -398,7 +398,7 @@ func loadSnapshotDocVersion(fileID string) (ret *loadedDocVersion, err error) {if "" == fileID {return nil, errors.New("snapshot file ID is required")}- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {return nil, errors.New(Conf.Language(26))}repo, err := newRepository()diff --git a/kernel/model/history_diff_test.go b/kernel/model/history_diff_test.goindex 3f01d441f7..2c45370e48 100644--- a/kernel/model/history_diff_test.go+++ b/kernel/model/history_diff_test.go@@ -250,8 +250,8 @@ func TestRenderFallbackDocVersionUsesRawContent(t *testing.T) {func TestParseDocVersionTreeNormalizesSpecAndRootID(t *testing.T) {oldConf := ConfConf = NewAppConf()- Conf.Editor = conf.NewEditor()- Conf.Export = conf.NewExport()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Export.Store(conf.NewExport())defer func() {Conf = oldConf}()diff --git a/kernel/model/history_search_injection_test.go b/kernel/model/history_search_injection_test.goindex ec5b51a402..76243b64ed 100644--- a/kernel/model/history_search_injection_test.go+++ b/kernel/model/history_search_injection_test.go@@ -42,12 +42,12 @@ func TestHistorySearchInjection(t *testing.T) {}}Conf = NewAppConf()- Conf.Editor = conf.NewEditor()- Conf.Export = conf.NewExport()- Conf.Search = conf.NewSearch()- Conf.FileTree = conf.NewFileTree()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Export.Store(conf.NewExport())+ Conf.Search.Store(conf.NewSearch())+ Conf.FileTree.Store(conf.NewFileTree())Conf.NotebookCrypto = conf.NewNotebookCrypto()- Conf.Sync = conf.NewSync()+ Conf.Sync.Store(conf.NewSync())sql.InitDatabase(true)sql.InitHistoryDatabase(true)sql.InitAssetContentDatabase(true)diff --git a/kernel/model/history_snapshots.go b/kernel/model/history_snapshots.goindex baf8230dea..750aef3819 100644--- a/kernel/model/history_snapshots.go+++ b/kernel/model/history_snapshots.go@@ -93,7 +93,7 @@ func GetDocHistorySnapshots(ctx context.Context, id string, histories []*DocHistkey := matchKey{boxID, hash}matches[key] = append(matches[key], history)}- if len(Conf.Repo.Key) == 0 {+ if len(Conf.Repo.Load().Key) == 0 {return nil}repo, err := newRepository()@@ -253,7 +253,7 @@ func localTaggedSnapshotIndexes(ctx context.Context, repo *dejavu.Repo) (map[strif readErr != nil {return nil, nil, readErr}- if index.ID != indexID || !index.VerifyAESKey(Conf.Repo.Key) {+ if index.ID != indexID || !index.VerifyAESKey(Conf.Repo.Load().Key) {return nil, nil, errors.New("invalid tagged snapshot index")}indexes[indexID] = indexdiff --git a/kernel/model/history_snapshots_test.go b/kernel/model/history_snapshots_test.goindex eef7c9abf1..744281e65b 100644--- a/kernel/model/history_snapshots_test.go+++ b/kernel/model/history_snapshots_test.go@@ -38,8 +38,8 @@ func historySnapshotTestEntry(t *testing.T, data []byte) *DocHistorySnapshotEntrfunc TestDocHistorySnapshotsMatching(t *testing.T) {_, repo, _ := prepareAssetDownloadRepoTest(t)- Conf.Editor = conf.NewEditor()- Conf.Export = conf.NewExport()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Export.Store(conf.NewExport())data := historySnapshotData("original")docPath := filepath.Join(util.DataDir, historySnapshotBoxID, historySnapshotDocID+".sy")writeHistorySnapshotTestFile(t, docPath, data)@@ -132,8 +132,8 @@ func TestDocHistorySnapshotsMatching(t *testing.T) {func TestDocHistorySnapshotsEncrypted(t *testing.T) {prepareAssetDownloadRepoTest(t)- Conf.Editor = conf.NewEditor()- Conf.Export = conf.NewExport()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Export.Store(conf.NewExport())defer prepareEncryptedBoxLifecycleTest(t, historySnapshotBoxID)()setEncryptedBoxState(historySnapshotBoxID, EncryptedBoxStateUnlocked)dek, err := GetDEKIfUnlocked(historySnapshotBoxID)diff --git a/kernel/model/history_test.go b/kernel/model/history_test.goindex 568c8100d6..9e777c7e5c 100644--- a/kernel/model/history_test.go+++ b/kernel/model/history_test.go@@ -173,7 +173,7 @@ func setupNotebookHistoryRollbackTest(t *testing.T) (historyPath, boxID string)util.DataDir = filepath.Join(tempDir, "data")util.HistoryDir = filepath.Join(tempDir, "history")Conf = NewAppConf()- Conf.Sync = conf.NewSync()+ Conf.Sync.Store(conf.NewSync())t.Cleanup(func() {Conf = originalConfutil.WorkspaceDir = originalWorkspaceDirdiff --git a/kernel/model/hpath_refresh_test.go b/kernel/model/hpath_refresh_test.goindex e03b6d0377..0d0a9734ca 100644--- a/kernel/model/hpath_refresh_test.go+++ b/kernel/model/hpath_refresh_test.go@@ -304,10 +304,20 @@ func prepareHPathRefreshTest(t *testing.T) {}}Conf = NewAppConf()- Conf.FileTree, Conf.NotebookCrypto, Conf.Sync = conf.NewFileTree(), conf.NewNotebookCrypto(), conf.NewSync()- Conf.Editor, Conf.Export, Conf.Search = conf.NewEditor(), conf.NewExport(), conf.NewSearch()+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewFileTree(), conf.NewNotebookCrypto(), conf.NewSync()+ Conf.FileTree.Store(confSectionValue0)+ Conf.NotebookCrypto = confSectionValue1+ Conf.Sync.Store(confSectionValue2)+ }+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewEditor(), conf.NewExport(), conf.NewSearch()+ Conf.Editor.Store(confSectionValue0)+ Conf.Export.Store(confSectionValue1)+ Conf.Search.Store(confSectionValue2)+ }Conf.Lang, util.Lang = "en", "en"- util.StatusBarCfg = util.NewStatusBar(false)+ util.StatusBarCfg.Store(util.NewStatusBar(false))util.WorkingDir, _ = filepath.Abs(filepath.Join("..", "..", "app"))initLang()sql.InitDatabase(true)diff --git a/kernel/model/import.go b/kernel/model/import.goindex b6bffcc1d4..c118168e4c 100644--- a/kernel/model/import.go+++ b/kernel/model/import.go@@ -264,6 +264,8 @@ func buildImportedSYSortValues(importedDocs []*importedSYSortDoc, sourceSortIDs}func applyImportedSYSort(boxID, targetPath string, importedDocs []*importedSYSortDoc, sourceSortIDs map[string]int) error {+ confFileTreeSnapshot := Conf.LoadFileTree()+if 1 > len(importedDocs) {return nil}@@ -293,7 +295,7 @@ func applyImportedSYSort(boxID, targetPath string, importedDocs []*importedSYSor}}- createDocAtTop := nil != Conf.FileTree.CreateDocAtTop && *Conf.FileTree.CreateDocAtTop+ createDocAtTop := nil != confFileTreeSnapshot.CreateDocAtTop && *confFileTreeSnapshot.CreateDocAtTopsortValues := buildImportedSYSortValues(importedDocs, sourceSortIDs, existingRootIDs, createDocAtTop)if 1 > len(sortValues) {return nil@@ -354,12 +356,14 @@ func importedBlockDocTitles(trees map[string]*parse.Tree) map[string]string {// 加密笔记本是孤岛,闪卡牌组与调度依赖全局数据库,因此必须拒绝导入;// 报错会指出包内哪些文档的卡片位于牌组中,便于用户在源笔记本中移除闪卡后重新导出。func checkEncryptedImportDeck(unzipRootPath string, trees map[string]*parse.Tree, blockIDs map[string]string) error {+ confFlashcardSnapshot := Conf.LoadFlashcard()+storageRiffDir := filepath.Join(unzipRootPath, "storage", "riff")if !gulu.File.IsExist(storageRiffDir) {return nil}- deck, loadErr := riff.LoadDeck(storageRiffDir, builtinDeckID, Conf.Flashcard.RequestRetention, Conf.Flashcard.MaximumInterval, Conf.Flashcard.Weights)+ deck, loadErr := riff.LoadDeck(storageRiffDir, builtinDeckID, confFlashcardSnapshot.RequestRetention, confFlashcardSnapshot.MaximumInterval, confFlashcardSnapshot.Weights)if nil != loadErr || nil == deck {// 牌组无法解析时仍要拒绝导入,此时无法指出具体文档,只报告包内牌组路径logging.LogErrorf("load imported deck [%s] failed: %s", storageRiffDir, loadErr)@@ -874,7 +878,7 @@ func importSY0(zipPath, boxID, toPath string, createNotebook, autoDetect bool, s// 普通笔记本将关联的闪卡数据合并到默认卡包 data/storage/riff/20230218211946-2kw8jgx 中storageRiffDir := filepath.Join(storage, "riff")if gulu.File.IsExist(storageRiffDir) {- deckToImport, loadErr := riff.LoadDeck(storageRiffDir, builtinDeckID, Conf.Flashcard.RequestRetention, Conf.Flashcard.MaximumInterval, Conf.Flashcard.Weights)+ deckToImport, loadErr := riff.LoadDeck(storageRiffDir, builtinDeckID, Conf.Flashcard.Load().RequestRetention, Conf.Flashcard.Load().MaximumInterval, Conf.Flashcard.Load().Weights)if nil != loadErr {logging.LogErrorf("load deck [%s] failed: %s", name, loadErr)} else {@@ -932,7 +936,7 @@ func importSY0(zipPath, boxID, toPath string, createNotebook, autoDetect bool, srenderer := render.NewJSONRenderer(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)data := renderer.Render()- if !util.UseSingleLineSave {+ if !util.UseSingleLineSave.Load() {buf := bytes.Buffer{}buf.Grow(1024 * 1024 * 2)if err = json.Indent(&buf, data, "", "\t"); err != nil {@@ -2489,7 +2493,7 @@ func convertWikiLinksAndTags(tree *parse.Tree, searchLinks map[string]string) {}func convertTags(text string) (ret string) {- if !util.MarkdownSettings.InlineTag {+ if !util.MarkdownSettings.Load().InlineTag {return text}diff --git a/kernel/model/import_attribute_view_fts5_test.go b/kernel/model/import_attribute_view_fts5_test.goindex 7a47a571cb..7ea890e554 100644--- a/kernel/model/import_attribute_view_fts5_test.go+++ b/kernel/model/import_attribute_view_fts5_test.go@@ -187,7 +187,7 @@ func TestImportSYAttributeViewBindingIsolation(t *testing.T) {if err = exportAv(avID, "", exportDir, exportDir, nil); err != nil {t.Fatalf("original database export failed after import: %v", err)}- Conf.Export.IncludeRelatedDocs = false+ Conf.Export.Load().IncludeRelatedDocs = falseif exportPath := ExportSYs([]string{externalID}); exportPath == "" {t.Fatal("original document export failed after import")}diff --git a/kernel/model/import_encrypted_flashcard_test.go b/kernel/model/import_encrypted_flashcard_test.goindex 84565e9e51..8b13ac259e 100644--- a/kernel/model/import_encrypted_flashcard_test.go+++ b/kernel/model/import_encrypted_flashcard_test.go@@ -137,7 +137,7 @@ func newImportDeckFixture(t *testing.T, cards map[string]string) (root string) {func TestCheckEncryptedImportDeckReportsAffectedDocuments(t *testing.T) {oldConf, oldLangs := Conf, util.LangsConf = &AppConf{Lang: "en"}- Conf.Flashcard = conf.NewFlashcard()+ Conf.Flashcard.Store(conf.NewFlashcard())util.Langs = map[string]map[int]string{"en": {385: "Encrypted notebooks do not support flashcards, so a .sy.zip containing flashcard deck data cannot be imported (documents: %s)",diff --git a/kernel/model/import_markdown_batch_fts5_test.go b/kernel/model/import_markdown_batch_fts5_test.goindex dfa5c25566..7eb42c0102 100644--- a/kernel/model/import_markdown_batch_fts5_test.go+++ b/kernel/model/import_markdown_batch_fts5_test.go@@ -25,7 +25,7 @@ func TestMarkdownImportBatchesPreserveReferencesAndEncryption(t *testing.T) {t.Run(map[bool]string{false: "plain", true: "encrypted"}[encrypted], func(t *testing.T) {const boxID = "20261010000000-batch01"setupExportRelatedTest(t, boxID)- Conf.Editor = conf.NewEditor()+ Conf.Editor.Store(conf.NewEditor())setupNotebookDocumentImportDatabase(t)t.Cleanup(func() { cache.ClearTreeCache(); cache.ClearDocsIAL(); cache.ClearBlocksIAL() })if encrypted {@@ -164,7 +164,7 @@ func TestMarkdownImportBatchesPreserveReferencesAndEncryption(t *testing.T) {func TestMarkdownImportSingleFileSkipsStaging(t *testing.T) {const boxID = "20261010000000-single1"setupExportRelatedTest(t, boxID)- Conf.Editor = conf.NewEditor()+ Conf.Editor.Store(conf.NewEditor())setupNotebookDocumentImportDatabase(t)source := filepath.Join(t.TempDir(), "source.md")original := []byte("# Single document\n\nContent")@@ -186,7 +186,7 @@ func TestMarkdownImportSingleFileSkipsStaging(t *testing.T) {func TestMarkdownImportStagingFailurePreservesSource(t *testing.T) {const boxID = "20261010000000-error01"setupExportRelatedTest(t, boxID)- Conf.Editor = conf.NewEditor()+ Conf.Editor.Store(conf.NewEditor())sourceDir := t.TempDir()source := filepath.Join(sourceDir, "source.md")original := []byte("# source content")diff --git a/kernel/model/import_markdown_benchmark_test.go b/kernel/model/import_markdown_benchmark_test.goindex 51d5fd38a0..ac1d6eed68 100644--- a/kernel/model/import_markdown_benchmark_test.go+++ b/kernel/model/import_markdown_benchmark_test.go@@ -20,7 +20,11 @@ import (func BenchmarkMarkdownImportWorkingSet(b *testing.B) {originalConf, originalTemp := Conf, util.TempDirConf = NewAppConf()- Conf.Editor, Conf.Export = conf.NewEditor(), conf.NewExport()+ {+ confSectionValue0, confSectionValue1 := conf.NewEditor(), conf.NewExport()+ Conf.Editor.Store(confSectionValue0)+ Conf.Export.Store(confSectionValue1)+ }util.TempDir = b.TempDir()b.Cleanup(func() { Conf, util.TempDir = originalConf, originalTemp })markdown := "# Heading\n\n" + strings.Repeat("Paragraph with **bold**, *emphasis*, [a link](https://example.com) and `code`.\n\n", 540)diff --git a/kernel/model/import_markdown_fts5_test.go b/kernel/model/import_markdown_fts5_test.goindex d1d5cf82d6..a878adec6f 100644--- a/kernel/model/import_markdown_fts5_test.go+++ b/kernel/model/import_markdown_fts5_test.go@@ -17,7 +17,7 @@ func TestMarkdownImportTargetAndHPath(t *testing.T) {const boxID = "20260910000000-box0001"const parentID = "20260910000001-doc0001"setupExportRelatedTest(t, boxID)- Conf.Editor = conf.NewEditor()+ Conf.Editor.Store(conf.NewEditor())setupNotebookDocumentImportDatabase(t)parentPath := "/" + parentID + ".sy"writeExportRelatedTestTree(t, treenode.NewTree(boxID, parentPath, "/Parent", "Parent"))diff --git a/kernel/model/import_markdown_spool_test.go b/kernel/model/import_markdown_spool_test.goindex 47c636b46a..42972b873b 100644--- a/kernel/model/import_markdown_spool_test.go+++ b/kernel/model/import_markdown_spool_test.go@@ -20,7 +20,11 @@ func setupMarkdownSpoolTest(t *testing.T) {t.Helper()originalConf, originalTemp := Conf, util.TempDirConf = NewAppConf()- Conf.Editor, Conf.Export = conf.NewEditor(), conf.NewExport()+ {+ confSectionValue0, confSectionValue1 := conf.NewEditor(), conf.NewExport()+ Conf.Editor.Store(confSectionValue0)+ Conf.Export.Store(confSectionValue1)+ }util.TempDir = t.TempDir()t.Cleanup(func() { Conf, util.TempDir = originalConf, originalTemp })}diff --git a/kernel/model/import_notebook_as_document_fts5_test.go b/kernel/model/import_notebook_as_document_fts5_test.goindex 033a5230c6..59fe30d373 100644--- a/kernel/model/import_notebook_as_document_fts5_test.go+++ b/kernel/model/import_notebook_as_document_fts5_test.go@@ -43,7 +43,7 @@ func TestImportNotebookSYAsChildDocuments(t *testing.T) {)setupExportRelatedTest(t, sourceBoxID, targetBoxID)setupNotebookDocumentImportDatabase(t)- *Conf.FileTree.CreateDocAtTop = false+ *Conf.FileTree.Load().CreateDocAtTop = falsesourceBox := &Box{ID: sourceBoxID}sourceConf := sourceBox.GetConf()diff --git a/kernel/model/import_obsidian.go b/kernel/model/import_obsidian.goindex d6aded239e..5c2c4c872f 100644--- a/kernel/model/import_obsidian.go+++ b/kernel/model/import_obsidian.go@@ -2373,7 +2373,7 @@ func writeObsidianTempTree(docsTemp string, tree *parse.Tree) error {if !json.Valid(data) {return fmt.Errorf("generated tree [%s] is not valid JSON", tree.HPath)}- if !util.UseSingleLineSave {+ if !util.UseSingleLineSave.Load() {var buffer bytes.Bufferif err := json.Indent(&buffer, data, "", "\t"); err != nil {return errdiff --git a/kernel/model/inline_style_test.go b/kernel/model/inline_style_test.goindex 3cbb12b74f..d272eaf99c 100644--- a/kernel/model/inline_style_test.go+++ b/kernel/model/inline_style_test.go@@ -668,7 +668,7 @@ func setupInlineStylesTest(t *testing.T) {t.Helper()oldDataDir, oldConf := util.DataDir, Confutil.DataDir, Conf = t.TempDir(), NewAppConf()- Conf.Sync = conf.NewSync()+ Conf.Sync.Store(conf.NewSync())t.Cleanup(func() {util.DataDir, Conf = oldDataDir, oldConf})diff --git a/kernel/model/lan_sync.go b/kernel/model/lan_sync.goindex 9f82eeda1f..444cc09fc2 100644--- a/kernel/model/lan_sync.go+++ b/kernel/model/lan_sync.go@@ -67,19 +67,19 @@ func refreshLANSyncManagerWithForce(force bool) {if lanSyncShuttingDown {return}- if nil == Conf || nil == Conf.Sync || nil == Conf.Sync.LAN || !Conf.Sync.LAN.Enabled || !Conf.Sync.Enabled ||- 1 > len(Conf.Repo.Key) || util.ContainerDocker == util.Container {+ if nil == Conf || nil == Conf.Sync.Load() || nil == Conf.Sync.Load().LAN || !Conf.Sync.Load().LAN.Enabled || !Conf.Sync.Load().Enabled ||+ 1 > len(Conf.Repo.Load().Key) || util.ContainerDocker == util.Container {stopLANSyncManagerLocked()return}nativeDiscovery := util.ContainerIOS == util.Container || util.ContainerHarmony == util.Containerconfig := &lanSyncRuntimeConfig{- repoKeyHash: sha256.Sum256(Conf.Repo.Key),+ repoKeyHash: sha256.Sum256(Conf.Repo.Load().Key),scope: lanSyncScope(),- deviceName: Conf.System.Name,- deviceOS: Conf.System.OS,+ deviceName: Conf.System.Load().Name,+ deviceOS: Conf.System.Load().OS,appVersion: util.Ver,- maxConcurrentReqs: Conf.Sync.LAN.MaxConcurrentReqs,+ maxConcurrentReqs: Conf.Sync.Load().LAN.MaxConcurrentReqs,nativeDiscovery: nativeDiscovery,}lanSyncManagerMu.RLock()@@ -98,14 +98,14 @@ func refreshLANSyncManagerWithForce(force bool) {manager, err := lansync.Start(lansync.Config{RepoPath: util.RepoDir,IdentityPath: filepath.Join(util.ConfDir, "lan-sync-identity.json"),- RepoKey: append([]byte(nil), Conf.Repo.Key...),+ RepoKey: append([]byte(nil), Conf.Repo.Load().Key...),Scope: config.scope,- DeviceName: Conf.System.Name,- DeviceOS: Conf.System.OS,+ DeviceName: Conf.System.Load().Name,+ DeviceOS: Conf.System.Load().OS,AppVersion: util.Ver,IPs: ips,IPsProvider: collectLANSyncIPs,- MaxConcurrentReqs: Conf.Sync.LAN.MaxConcurrentReqs,+ MaxConcurrentReqs: Conf.Sync.Load().LAN.MaxConcurrentReqs,NativeDiscovery: nativeDiscovery,OnCommitHint: handleLANSyncCommitHint,})@@ -121,16 +121,18 @@ func refreshLANSyncManagerWithForce(force bool) {}func lanSyncScope() string {- cloudName := Conf.Sync.CloudName- if conf.ProviderS3 == Conf.Sync.Provider {+ confSyncSnapshot := Conf.LoadSync()++ cloudName := confSyncSnapshot.CloudName+ if conf.ProviderS3 == confSyncSnapshot.Provider {// S3 只使用存储桶定位仓库,v1 作用域中的目录槽位固定为存储桶名。cloudName = ""- if nil != Conf.Sync.S3 {- cloudName = Conf.Sync.S3.Bucket+ if nil != confSyncSnapshot.S3 {+ cloudName = confSyncSnapshot.S3.Bucket}}- base := fmt.Sprintf("v1:%d:%s", Conf.Sync.Provider, cloudName)- switch Conf.Sync.Provider {+ base := fmt.Sprintf("v1:%d:%s", confSyncSnapshot.Provider, cloudName)+ switch confSyncSnapshot.Provider {case conf.ProviderSiYuan:userID := ""if user := Conf.GetUser(); nil != user {@@ -138,16 +140,16 @@ func lanSyncScope() string {}return fmt.Sprintf("%s:%d:%s", base, util.CurrentCloudRegion, userID)case conf.ProviderS3:- if nil != Conf.Sync.S3 {- return fmt.Sprintf("%s:%s:%s:%s", base, Conf.Sync.S3.Endpoint, Conf.Sync.S3.Bucket, Conf.Sync.S3.Region)+ if nil != confSyncSnapshot.S3 {+ return fmt.Sprintf("%s:%s:%s:%s", base, confSyncSnapshot.S3.Endpoint, confSyncSnapshot.S3.Bucket, confSyncSnapshot.S3.Region)}case conf.ProviderWebDAV:- if nil != Conf.Sync.WebDAV {- return fmt.Sprintf("%s:%s", base, Conf.Sync.WebDAV.Endpoint)+ if nil != confSyncSnapshot.WebDAV {+ return fmt.Sprintf("%s:%s", base, confSyncSnapshot.WebDAV.Endpoint)}case conf.ProviderLocal:- if nil != Conf.Sync.Local {- return fmt.Sprintf("%s:%s", base, Conf.Sync.Local.Endpoint)+ if nil != confSyncSnapshot.Local {+ return fmt.Sprintf("%s:%s", base, confSyncSnapshot.Local.Endpoint)}}return base@@ -285,7 +287,7 @@ func notifyLANSyncCommit(repo *dejavu.Repo) {}func handleLANSyncCommitHint(latestID string) {- if nil == Conf.Sync || nil == Conf.Sync.LAN || !Conf.Sync.LAN.Enabled || !Conf.Sync.Enabled || 1 != Conf.Sync.Mode {+ if nil == Conf.Sync.Load() || nil == Conf.Sync.Load().LAN || !Conf.Sync.Load().LAN.Enabled || !Conf.Sync.Load().Enabled || 1 != Conf.Sync.Load().Mode {return}lanSyncHintMu.Lock()@@ -296,10 +298,12 @@ func handleLANSyncCommitHint(latestID string) {lastLANSyncHintID = latestIDlastLANSyncSchedule = time.Now()lanSyncHintMu.Unlock()- hash := sha256.Sum256([]byte(Conf.System.ID + ":" + latestID))+ hash := sha256.Sum256([]byte(Conf.System.Load().ID + ":" + latestID))delay := time.Second + time.Duration(binary.BigEndian.Uint32(hash[:4])%5000)*time.Millisecondtime.AfterFunc(delay, func() {- if nil != Conf.Sync && nil != Conf.Sync.LAN && Conf.Sync.LAN.Enabled && Conf.Sync.Enabled && 1 == Conf.Sync.Mode {+ confSyncSnapshot := Conf.LoadSync()++ if nil != confSyncSnapshot && nil != confSyncSnapshot.LAN && confSyncSnapshot.LAN.Enabled && confSyncSnapshot.Enabled && 1 == confSyncSnapshot.Mode {syncDataFromLAN(latestID)}})@@ -315,27 +319,20 @@ func syncDataFromLAN(latestID string) {}func SetSyncLAN(enabled bool, maxConcurrentReqs int) {- if nil == Conf.Sync {- Conf.Sync = conf.NewSync()- }- if nil == Conf.Sync.LAN {- Conf.Sync.LAN = &conf.LANSync{}- }- if 1 > maxConcurrentReqs {- maxConcurrentReqs = Conf.Sync.LAN.MaxConcurrentReqs+ UpdateSyncConf(func(sync *conf.Sync) {+ if nil == sync.LAN {+ sync.LAN = &conf.LANSync{}+ }if 1 > maxConcurrentReqs {- maxConcurrentReqs = 16+ // 未指定并发数时沿用当前值,越界值由同步配置规范化处理+ maxConcurrentReqs = sync.LAN.MaxConcurrentReqs}- }- if 128 < maxConcurrentReqs {- maxConcurrentReqs = 128- }- Conf.Sync.LAN.Enabled = enabled- Conf.Sync.LAN.MaxConcurrentReqs = maxConcurrentReqs- if !enabled {- Conf.Sync.Stat = removeLANSyncTrafficStat(Conf.Sync.Stat)- }- Conf.Save()+ sync.LAN.Enabled = enabled+ sync.LAN.MaxConcurrentReqs = maxConcurrentReqs+ if !enabled {+ sync.Stat = removeLANSyncTrafficStat(sync.Stat)+ }+ })refreshLANSyncManager()}@@ -348,6 +345,8 @@ type SyncLANStatus struct {}func GetSyncLANStatus() SyncLANStatus {+ confSyncSnapshot := Conf.LoadSync()+lanSyncManagerMu.RLock()manager := lanSyncManagerlanSyncManagerMu.RUnlock()@@ -363,9 +362,9 @@ func GetSyncLANStatus() SyncLANStatus {}enabled := falsemaxConcurrentReqs := 16- if nil != Conf.Sync && nil != Conf.Sync.LAN {- enabled = Conf.Sync.LAN.Enabled- maxConcurrentReqs = Conf.Sync.LAN.MaxConcurrentReqs+ if nil != confSyncSnapshot && nil != confSyncSnapshot.LAN {+ enabled = confSyncSnapshot.LAN.Enabled+ maxConcurrentReqs = confSyncSnapshot.LAN.MaxConcurrentReqs}return SyncLANStatus{Enabled: enabled,diff --git a/kernel/model/lan_sync_test.go b/kernel/model/lan_sync_test.goindex 93d2f8366d..f6ba95a723 100644--- a/kernel/model/lan_sync_test.go+++ b/kernel/model/lan_sync_test.go@@ -10,28 +10,28 @@ import (func TestLANSyncScopeS3IdentityAndCompatibility(t *testing.T) {prepareSyncDirectoryTest(t)- Conf.Sync.S3.Endpoint = "https://storage.example.com"+ Conf.Sync.Load().S3.Endpoint = "https://storage.example.com"legacyScope := "v1:2:notes.backup:https://storage.example.com:notes.backup:us-east-1"for _, name := range []string{"main", "work", "notes.backup", ""} {- Conf.Sync.CloudName = name+ Conf.Sync.Load().CloudName = nameif got := lanSyncScope(); got != legacyScope {t.Fatalf("S3 scope depends on directory %q or breaks bucket-named peers: %q", name, got)}}- originalS3 := *Conf.Sync.S3- for _, field := range []*string{&Conf.Sync.S3.Endpoint, &Conf.Sync.S3.Bucket, &Conf.Sync.S3.Region} {+ originalS3 := *Conf.Sync.Load().S3+ for _, field := range []*string{&Conf.Sync.Load().S3.Endpoint, &Conf.Sync.Load().S3.Bucket, &Conf.Sync.Load().S3.Region} {*field += "-other"if lanSyncScope() == legacyScope {t.Fatal("different S3 repositories share a LAN scope")}- *Conf.Sync.S3 = originalS3+ *Conf.Sync.Load().S3 = originalS3}- Conf.Sync.S3.AccessKey, Conf.Sync.S3.SecretKey = "rotated-key", "rotated-secret"- Conf.Sync.S3.Timeout = 60+ Conf.Sync.Load().S3.AccessKey, Conf.Sync.Load().S3.SecretKey = "rotated-key", "rotated-secret"+ Conf.Sync.Load().S3.Timeout = 60if lanSyncScope() != legacyScope {t.Fatal("connection settings changed the LAN scope")}- Conf.Sync.S3 = nil+ Conf.Sync.Load().S3 = nilif got := lanSyncScope(); got != "v1:2:" {t.Fatalf("unconfigured S3 depends on a directory: %q", got)}@@ -40,8 +40,8 @@ func TestLANSyncScopeS3IdentityAndCompatibility(t *testing.T) {func TestLANSyncScopePreservesOtherProviders(t *testing.T) {prepareSyncDirectoryTest(t)Conf.SetUser(&conf.User{UserId: "scope-user"})- Conf.Sync.WebDAV = &conf.WebDAV{Endpoint: "https://dav.example.com"}- Conf.Sync.Local = &conf.Local{Endpoint: "local-sync"}+ Conf.Sync.Load().WebDAV = &conf.WebDAV{Endpoint: "https://dav.example.com"}+ Conf.Sync.Load().Local = &conf.Local{Endpoint: "local-sync"}for _, tc := range []struct {provider intsuffix string@@ -50,9 +50,9 @@ func TestLANSyncScopePreservesOtherProviders(t *testing.T) {{conf.ProviderWebDAV, "https://dav.example.com"},{conf.ProviderLocal, "local-sync"},} {- Conf.Sync.Provider = tc.provider+ Conf.Sync.Load().Provider = tc.providerfor _, name := range []string{"main", "work"} {- Conf.Sync.CloudName = name+ Conf.Sync.Load().CloudName = namewant := fmt.Sprintf("v1:%d:%s:%s", tc.provider, name, tc.suffix)if got := lanSyncScope(); got != want {t.Fatalf("provider %d scope changed: got %q, want %q", tc.provider, got, want)diff --git a/kernel/model/mcp_oauth.go b/kernel/model/mcp_oauth.goindex 5568148a1b..4d029fad29 100644--- a/kernel/model/mcp_oauth.go+++ b/kernel/model/mcp_oauth.go@@ -74,7 +74,7 @@ func (w *mcpOAuthChallengeWriter) WriteHeader(status int) {func CheckMCPAuth(c *gin.Context) {header := strings.Fields(c.GetHeader("Authorization"))isBearer := len(header) == 2 && strings.EqualFold(header[0], "Bearer")- if isBearer && util.AuthCodeEquals(Conf.Api.Token, header[1]) {+ if isBearer && util.AuthCodeEquals(Conf.Api.Load().Token, header[1]) {CheckAuth(c)return}diff --git a/kernel/model/mount.go b/kernel/model/mount.goindex 49922ccbe9..6961d9cc67 100644--- a/kernel/model/mount.go+++ b/kernel/model/mount.go@@ -65,6 +65,8 @@ func CreateBox(name string) (id string, err error) {}func createBox(name string, initializeBoxDoc bool) (id string, err error) {+ confFileTreeSnapshot := Conf.LoadFileTree()+name = normalizeBoxName(name)if 512 < utf8.RuneCountInString(name) {// 限制笔记本名和文档名最大长度为 `512` https://github.com/siyuan-note/siyuan/issues/6299@@ -96,7 +98,7 @@ func createBox(name string, initializeBoxDoc bool) (id string, err error) {box := &Box{ID: id, Name: name}boxConf := box.GetConf()boxConf.Name = name- boxConf.Sort = newBoxSort(boxes, nil != Conf.FileTree.CreateDocAtTop && *Conf.FileTree.CreateDocAtTop)+ boxConf.Sort = newBoxSort(boxes, nil != confFileTreeSnapshot.CreateDocAtTop && *confFileTreeSnapshot.CreateDocAtTop)if err := box.SaveConf(boxConf); err != nil {logging.LogErrorf("save box conf [%s] failed: %s", id, err)}@@ -504,6 +506,8 @@ func Mount(boxID string) (alreadyMount bool, err error) {}func mountBox(boxID string) (alreadyMount bool, err error) {+ confFileTreeSnapshot := Conf.LoadFileTree()+if _, loaded := boxLock.LoadOrStore(boxID, true); loaded {err = errors.New(Conf.language(239))return@@ -533,7 +537,7 @@ func mountBox(boxID string) (alreadyMount bool, err error) {}boxes, _ := ListNotebooks()- sort := newBoxSort(boxes, nil != Conf.FileTree.CreateDocAtTop && *Conf.FileTree.CreateDocAtTop)+ sort := newBoxSort(boxes, nil != confFileTreeSnapshot.CreateDocAtTop && *confFileTreeSnapshot.CreateDocAtTop)p := filepath.Join(util.WorkingDir, "guide", boxID)if err = filelock.Copy(p, localPath); err != nil {@@ -601,7 +605,7 @@ func mountBox(boxID string) (alreadyMount bool, err error) {}// 缓存根一级的文档树展开- files, _, _ := ListDocTree(box.ID, "/", util.SortModeUnassigned, false, false, Conf.FileTree.MaxListCount)+ files, _, _ := ListDocTree(box.ID, "/", util.SortModeUnassigned, false, false, confFileTreeSnapshot.MaxListCount)box = Conf.Box(boxID)if 0 < len(files) || (nil != box && box.Exist(boxDocPath(box.ID))) {box.Index()diff --git a/kernel/model/notebook_archive.go b/kernel/model/notebook_archive.goindex 7fb3e78c12..e34a25a271 100644--- a/kernel/model/notebook_archive.go+++ b/kernel/model/notebook_archive.go@@ -117,6 +117,8 @@ func listNotebookArchiveCandidates() ([]NotebookArchiveCandidate, error) {}func walkNotebookArchiveSnapshots(visit func(*dejavu.Repo, *entity.Index, []*entity.File) error) error {+ confRepoSnapshot := Conf.LoadRepo()+if util.RepoDir == "" {return nil}@@ -127,7 +129,7 @@ func walkNotebookArchiveSnapshots(visit func(*dejavu.Repo, *entity.Index, []*entif err != nil {return err}- if Conf.Repo == nil || len(Conf.Repo.Key) == 0 {+ if confRepoSnapshot == nil || len(confRepoSnapshot.Key) == 0 {return ErrNotebookArchiveBusy}assetDownloadSourceMu.RLock()@@ -162,8 +164,8 @@ func notebookArchiveKeys() (map[string][]byte, error) {return nil, err}keys["keys/conf.json"] = data- data, err = os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))- if err == nil {+ // 持久化形态取自本进程最近一次生成的配置字节,与打包时磁盘文件的写入时机无关。+ if data = lastPersistedConf(); data != nil {var persisted struct {NotebookCrypto json.RawMessage `json:"notebookCrypto"`}@@ -173,8 +175,9 @@ func notebookArchiveKeys() (map[string][]byte, error) {if len(persisted.NotebookCrypto) != 0 {keys["keys/persisted-conf.json"] = persisted.NotebookCrypto}- } else if !os.IsNotExist(err) {- return nil, err+ }+ if len(keys["keys/persisted-conf.json"]) == 0 {+ keys["keys/persisted-conf.json"] = append([]byte(nil), keys["keys/conf.json"]...)}for name, source := range map[string]string{"keys/backup.json": dataCryptoBackupPath(), "keys/migration.json": masterPasswordMigrationPath()} {data, err = os.ReadFile(source)diff --git a/kernel/model/notebook_archive_import.go b/kernel/model/notebook_archive_import.goindex f45476bdb2..605f475141 100644--- a/kernel/model/notebook_archive_import.go+++ b/kernel/model/notebook_archive_import.go@@ -20,6 +20,8 @@ import ()func checkNotebookArchiveImportTarget() error {+ confSyncSnapshot := Conf.LoadSync()+if NotebookCryptoLifecycleState(false) != NotebookCryptoStateDisabled {return ErrNotebookArchiveConfigured}@@ -36,7 +38,7 @@ func checkNotebookArchiveImportTarget() error {if err != nil {return err}- if len(ids) != 0 || history || Conf.Sync != nil && Conf.Sync.Enabled {+ if len(ids) != 0 || history || confSyncSnapshot != nil && confSyncSnapshot.Enabled {return ErrNotebookArchiveConfigured}candidates, err := listNotebookArchiveCandidates()diff --git a/kernel/model/notebook_archive_test.go b/kernel/model/notebook_archive_test.goindex 4cf42f55bd..1d1ef1b8b4 100644--- a/kernel/model/notebook_archive_test.go+++ b/kernel/model/notebook_archive_test.go@@ -17,10 +17,11 @@ import (func notebookArchiveTestWorkspace(t *testing.T) {t.Helper()- oldConf := Conf+ oldConf, oldPersisted := Conf, lastPersistedConf()oldWorkspace, oldData, oldHistory, oldConfig, oldTemp, oldRepo := util.WorkspaceDir, util.DataDir, util.HistoryDir, util.ConfDir, util.TempDir, util.RepoDirt.Cleanup(func() {Conf = oldConf+ recordPersistedConf(oldPersisted)util.WorkspaceDir, util.DataDir, util.HistoryDir, util.ConfDir, util.TempDir, util.RepoDir = oldWorkspace, oldData, oldHistory, oldConfig, oldTemp, oldRepo})root := t.TempDir()@@ -31,10 +32,12 @@ func notebookArchiveTestWorkspace(t *testing.T) {t.Fatal(err)}}+ // 新工作空间尚未持久化配置+ recordPersistedConf(nil)Conf = NewAppConf()Conf.NotebookCrypto = conf.NewNotebookCrypto()- Conf.Sync = conf.NewSync()- Conf.Sync.Enabled = false+ Conf.Sync.Store(conf.NewSync())+ Conf.Sync.Load().Enabled = false}func notebookArchiveTestBox(t *testing.T, boxID string, kek []byte) []byte {@@ -253,9 +256,11 @@ func TestNotebookArchiveMissingBackupAndLaterRecoveredKey(t *testing.T) {}Conf.NotebookCrypto = conf.NewNotebookCrypto()Conf.NotebookCrypto.MasterSalt = []byte("partial old configuration")+ // 模拟进程启动时配置文件缺失、从未持久化过配置if err = os.Remove(filepath.Join(util.ConfDir, "conf.json")); err != nil {t.Fatal(err)}+ recordPersistedConf(nil)if err = os.Remove(dataCryptoBackupPath()); err != nil {t.Fatal(err)}@@ -643,3 +648,36 @@ func TestNotebookArchiveDownloadsDeferredEncryptedAssets(t *testing.T) {t.Fatalf("download changed ciphertext: %v %v", err, expectedErr)}}++// 归档携带的持久化形态来自本进程最近一次落盘的配置,打包时磁盘文件被改写或删除不影响结果。+func TestNotebookArchivePersistedConfIndependentOfDiskTiming(t *testing.T) {+ notebookArchiveTestWorkspace(t)+ if err := EnableEncryptedNotebook("archive-password"); err != nil {+ t.Fatal(err)+ }+ keys, err := notebookArchiveKeys()+ if err != nil {+ t.Fatal(err)+ }+ expected := keys["keys/persisted-conf.json"]+ if len(expected) == 0 {+ t.Fatal("persisted notebook crypto configuration was not archived")+ }+ confPath := filepath.Join(util.ConfDir, "conf.json")+ for _, content := range [][]byte{[]byte(`{"notebookCrypto":{"enabled":false}}`), nil} {+ if content == nil {+ err = os.Remove(confPath)+ } else {+ err = os.WriteFile(confPath, content, 0644)+ }+ if err != nil {+ t.Fatal(err)+ }+ if keys, err = notebookArchiveKeys(); err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(keys["keys/persisted-conf.json"], expected) {+ t.Fatalf("archived persisted configuration depends on disk state: %s", keys["keys/persisted-conf.json"])+ }+ }+}diff --git a/kernel/model/notebook_bundle.go b/kernel/model/notebook_bundle.goindex 66fb170278..d2be6113e9 100644--- a/kernel/model/notebook_bundle.go+++ b/kernel/model/notebook_bundle.go@@ -92,11 +92,9 @@ func exportNotebooksSYBundle(ids []string) (zipPath string) {boxes = append(boxes, box)}- originalIncludeRelatedDocs := Conf.Export.IncludeRelatedDocs- Conf.Export.IncludeRelatedDocs = false- defer func() {- Conf.Export.IncludeRelatedDocs = originalIncludeRelatedDocs- }()+ // 笔记本包只包含所选笔记本,关联文档由各笔记本自身导出+ config := resolveExportOptions(nil)+ config.IncludeRelatedDocs = falseworkDir := filepath.Join(util.TempDir, "export", "notebooks-"+gulu.Rand.String(7))if err := os.MkdirAll(workDir, 0755); nil != err {@@ -109,7 +107,7 @@ func exportNotebooksSYBundle(ids []string) (zipPath string) {manifest := &syNotebookBundleManifest{Spec: syNotebookBundleSpec}innerArchives := map[string]string{}for _, box := range boxes {- innerURI := exportBoxSYZip(box.ID)+ innerURI := exportBoxSYZip(box.ID, config)innerPath, err := exportedFilePath(innerURI)if nil != err {logging.LogErrorf("resolve exported notebook archive failed: %s", err)diff --git a/kernel/model/ocr.go b/kernel/model/ocr.goindex f43d7da856..6ab2e05e12 100644--- a/kernel/model/ocr.go+++ b/kernel/model/ocr.go@@ -45,19 +45,15 @@ func ocrModelFilesChanged(changes ...[]string) bool {// 新设备使用内置 PaddleOCR 并关闭自动识别,已有设备缺少 OCR 配置时保留 Tesseract 自动识别。func normalizeOCRConfig(value *conf.OCR, confFileExists bool) *conf.OCR {- if value != nil {- // 内置模型统一为 Tiny,自行导入的模型仍保留内容摘要标识。- if value.Model == "small" {- value.Model = "tiny"+ if value == nil {+ // 已有工作空间缺失 OCR 配置时沿用升级前的 Tesseract 自动识别行为。+ value = conf.NewOCR()+ if confFileExists {+ value.Provider = string(ocr.Tesseract)+ value.Auto = true}- return value}- value = conf.NewOCR()- if confFileExists {- value.Provider = string(ocr.Tesseract)- value.Auto = true- }- return value+ return conf.NormalizeOCR(value)}func InitOCR() {@@ -74,22 +70,18 @@ func InitOCR() {func (config *AppConf) GetOCR() conf.OCR {config.m.RLock()defer config.m.RUnlock()- if config.OCR == nil {+ if config.OCR.Load() == nil {return *conf.NewOCR()}- return *config.OCR+ return *config.OCR.Load()}-func (config *AppConf) SetOCR(value conf.OCR) error {+func validateOCRSetting(value *conf.OCR) error {switch value.ReasoningEffort {case "", "none", "low", "medium", "high", "xhigh", "max":default:return errors.New("invalid OCR reasoning effort")}- // 兼容旧客户端提交的内置 Small 标识,响应和持久化配置均使用 Tiny。- if value.Model == "small" {- value.Model = "tiny"- }if err := (ocr.Thresholds(value.Thresholds)).Validate(); err != nil {return err}@@ -106,26 +98,35 @@ func (config *AppConf) SetOCR(value conf.OCR) error {return err}}- config.m.Lock()- previous := config.OCR+ previous := Conf.OCR.Load()if value.Provider == "ai" && (previous == nil || previous.AIModelID == "" || previous.AIModelID != value.AIModelID) {- provider, model := getOCRAIModel(value)+ provider, model := getOCRAIModel(*value)if provider == nil || model == nil {- config.m.Unlock()return errors.New(Conf.Language(414))}}+ return nil+}++func (config *AppConf) SetOCR(value conf.OCR) error {+ previous := config.OCR.Load()if value.Provider == "ai" && (previous == nil || previous.Provider != "ai") {value.Auto = false}- changed := config.OCR == nil || config.OCR.Provider != value.Provider || config.OCR.Model != value.Model- config.OCR = &value- config.m.Unlock()- config.Save()- if changed {- go nativePaddle.Close()+ _, err := ApplyConfSection("ocr", &value)+ return err+}++func ocrSectionSpec() *SectionSpec[*conf.OCR] {+ spec := newSectionSpec("ocr", &Conf.OCR, conf.NormalizeOCR,+ Reaction[*conf.OCR]{Name: "provider", Changed: func(old, next *conf.OCR) bool { return old.Provider != next.Provider || old.Model != next.Model }, Apply: func(old, next *conf.OCR) { go nativePaddle.Close() }})+ spec.Validate = func(value *conf.OCR) []Issue {+ if err := validateOCRSetting(value); err != nil {+ return []Issue{{Field: "ocr", Severity: "error", Message: err.Error()}}+ }+ return nil}- return nil+ return spec}func ocrModelDirectory(id string) string {diff --git a/kernel/model/ocr_ai.go b/kernel/model/ocr_ai.goindex c0d4624cef..513ab91dc4 100644--- a/kernel/model/ocr_ai.go+++ b/kernel/model/ocr_ai.go@@ -29,6 +29,8 @@ func AIOCRAsset(ctx context.Context, path string) (string, error) {}func aiOCRAsset(ctx context.Context, path string, value conf.OCR, automatic bool) (string, error) {+ confAISnapshot := Conf.LoadAI()+if util.IsDisabledFeature("ai") {return "", errors.New(Conf.Language(380))}@@ -36,7 +38,7 @@ func aiOCRAsset(ctx context.Context, path string, value conf.OCR, automatic boolif IsEncryptedOCRAsset(path) {return "", errors.New(Conf.Language(380))}- if Conf.AI == nil {+ if confAISnapshot == nil {return "", errors.New("AI configuration is unavailable")}provider, model := getOCRAIModel(value)@@ -76,8 +78,8 @@ func aiOCRAsset(ctx context.Context, path string, value conf.OCR, automatic boolreturn "", err}maxTokens := 8192- if value.AIModelID == "" && Conf.AI.Agent != nil {- maxTokens = Conf.AI.Agent.MaxCompletionTokens+ if value.AIModelID == "" && confAISnapshot.Agent != nil {+ maxTokens = confAISnapshot.Agent.MaxCompletionTokens}if maxTokens == 0 {maxTokens = 8192@@ -124,16 +126,18 @@ func aiOCRAsset(ctx context.Context, path string, value conf.OCR, automatic bool}func getOCRAIModel(value conf.OCR) (*conf.Provider, *conf.Model) {- if util.IsDisabledFeature("ai") || Conf.AI == nil {+ confAISnapshot := Conf.LoadAI()++ if util.IsDisabledFeature("ai") || confAISnapshot == nil {return nil, nil}if value.AIModelID == "" {if value.Provider == "ai" {return nil, nil}- return Conf.AI.GetAgentModel()+ return confAISnapshot.GetAgentModel()}- provider, model := Conf.AI.GetModel(value.AIModelID)+ provider, model := confAISnapshot.GetModel(value.AIModelID)if model == nil || model.ID != value.AIModelID || model.Name == "" {return nil, nil}@@ -146,10 +150,12 @@ type OCRAIModel struct {// OCRAIModels 返回可选模型的显示信息;保留配置中的顺序,不泄露连接凭据。func OCRAIModels() (result []OCRAIModel) {- if util.IsDisabledFeature("ai") || Conf.AI == nil {+ confAISnapshot := Conf.LoadAI()++ if util.IsDisabledFeature("ai") || confAISnapshot == nil {return}- for _, provider := range Conf.AI.Providers {+ for _, provider := range confAISnapshot.Providers {if provider == nil || !provider.Enabled {continue}diff --git a/kernel/model/ocr_ai_index_test.go b/kernel/model/ocr_ai_index_test.goindex 46af034be0..5d4b85fa5c 100644--- a/kernel/model/ocr_ai_index_test.go+++ b/kernel/model/ocr_ai_index_test.go@@ -23,9 +23,15 @@ import (func testAIOCRAssetIndex(t *testing.T, path, blockID string) {t.Helper()- previousAI := Conf.AI+ previousAI := Conf.AI.Load()previousOCR := Conf.GetOCR()- defer func() { Conf.AI, Conf.OCR = previousAI, &previousOCR }()+ defer func() {+ {+ confSectionValue0, confSectionValue1 := previousAI, &previousOCR+ Conf.AI.Store(confSectionValue0)+ Conf.OCR.Store(confSectionValue1)+ }+ }()calls := 0providerFailure := falsevar beforeResponse func()@@ -43,9 +49,9 @@ func testAIOCRAssetIndex(t *testing.T, path, blockID string) {_, _ = io.WriteString(w, `{"choices":[{"finish_reason":"stop","message":{"content":"aiocrkeyword\nsecond column"}}]}`)}))defer server.Close()- Conf.AI = conf.NewAI()- Conf.AI.Agent.ModelID = "vision"- Conf.AI.Providers = []*conf.Provider{{ID: "provider", Enabled: true, APIKey: "test", BaseURL: server.URL + "/v1",+ Conf.AI.Store(conf.NewAI())+ Conf.AI.Load().Agent.ModelID = "vision"+ Conf.AI.Load().Providers = []*conf.Provider{{ID: "provider", Enabled: true, APIKey: "test", BaseURL: server.URL + "/v1",Models: []*conf.Model{{ID: "vision", Enabled: true, Name: "vision-test"}}}}file, err := os.Create(filepath.Join(util.DataDir, filepath.FromSlash(path)))if err != nil {@@ -73,23 +79,23 @@ func testAIOCRAssetIndex(t *testing.T, path, blockID string) {if err != nil || len(matches) != 0 {t.Fatalf("obsolete OCR text remains searchable: %v, %v", matches, err)}- Conf.OCR = &conf.OCR{Provider: "ai", Model: "tiny", AIModelID: "vision", Auto: true}+ Conf.OCR.Store(&conf.OCR{Provider: "ai", Model: "tiny", AIModelID: "vision", Auto: true})for _, test := range []struct {name stringchange func()want string}{- {"automatic disabled", func() { Conf.m.Lock(); Conf.OCR.Auto = false; Conf.m.Unlock() }, ""},- {"model changed", func() { Conf.m.Lock(); Conf.OCR.AIModelID = "other"; Conf.m.Unlock() }, ""},- {"reasoning changed", func() { Conf.m.Lock(); Conf.OCR.ReasoningEffort = "none"; Conf.m.Unlock() }, ""},- {"AI model disabled", func() { Conf.AI.Providers[0].Models[0].Enabled = false }, ""},+ {"automatic disabled", func() { Conf.m.Lock(); Conf.OCR.Load().Auto = false; Conf.m.Unlock() }, ""},+ {"model changed", func() { Conf.m.Lock(); Conf.OCR.Load().AIModelID = "other"; Conf.m.Unlock() }, ""},+ {"reasoning changed", func() { Conf.m.Lock(); Conf.OCR.Load().ReasoningEffort = "none"; Conf.m.Unlock() }, ""},+ {"AI model disabled", func() { Conf.AI.Load().Providers[0].Models[0].Enabled = false }, ""},{"manually edited", func() { SetOCRAssetText(path, "manual text") }, "manual text"},} {t.Run(test.name, func(t *testing.T) {util.RemoveAssetText(path)value := conf.OCR{Provider: "ai", Model: "tiny", AIModelID: "vision", Auto: true}- Conf.OCR = &value- Conf.AI.Providers[0].Models[0].Enabled = true+ Conf.OCR.Store(&value)+ Conf.AI.Load().Providers[0].Models[0].Enabled = truebeforeResponse = test.change_, _, err := ocrAsset(context.Background(), path, value, true)if !errors.Is(err, context.Canceled) || util.GetAssetText(path) != test.want {@@ -98,8 +104,8 @@ func testAIOCRAssetIndex(t *testing.T, path, blockID string) {})}beforeResponse = nil- Conf.AI.Providers[0].Models[0].Enabled = true- Conf.OCR = &conf.OCR{Provider: "ai", Model: "tiny", AIModelID: "vision", Auto: true}+ Conf.AI.Load().Providers[0].Models[0].Enabled = true+ Conf.OCR.Store(&conf.OCR{Provider: "ai", Model: "tiny", AIModelID: "vision", Auto: true})util.RemoveAssetText(path)const extra = "assets/automatic-20261005000000-abcdefg.png"extraFile, err := os.Create(filepath.Join(util.DataDir, filepath.FromSlash(extra)))@@ -131,14 +137,14 @@ func testAIOCRAssetIndex(t *testing.T, path, blockID string) {t.Fatal("AI automatic OCR reran saved results")}util.RemoveAssetText(extra)- Conf.OCR.Auto = false+ Conf.OCR.Load().Auto = falseautoOCRAssets()- Conf.OCR.Auto, Conf.OCR.AIModelID = true, "missing"+ Conf.OCR.Load().Auto, Conf.OCR.Load().AIModelID = true, "missing"autoOCRAssets()if calls != previousCalls+2 {t.Fatal("disabled automatic OCR or unavailable model reached provider")}- Conf.OCR.AIModelID = "vision"+ Conf.OCR.Load().AIModelID = "vision"providerFailure = trueautoOCRAssets()providerFailure = false@@ -146,7 +152,7 @@ func testAIOCRAssetIndex(t *testing.T, path, blockID string) {if calls != previousCalls+3 || util.ExistsAssetText(extra) {t.Fatal("failed automatic OCR was not held for retry")}- Conf.OCR.ReasoningEffort = "none"+ Conf.OCR.Load().ReasoningEffort = "none"autoOCRAssets()if calls != previousCalls+4 || !util.ExistsAssetText(extra) {t.Fatal("changed reasoning effort inherited the previous retry delay")diff --git a/kernel/model/ocr_index_test.go b/kernel/model/ocr_index_test.goindex f90e21dabe..e9d57bfc2e 100644--- a/kernel/model/ocr_index_test.go+++ b/kernel/model/ocr_index_test.go@@ -49,8 +49,13 @@ func TestOCRResultReindexesWithoutTesseract(t *testing.T) {return}fixture := setupFileOperationTest(t)- Conf.Search, Conf.Editor, Conf.Export = conf.NewSearch(), conf.NewEditor(), conf.NewExport()- Conf.OCR = &conf.OCR{Provider: "paddleocr", Model: "tiny", Auto: true}+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewSearch(), conf.NewEditor(), conf.NewExport()+ Conf.Search.Store(confSectionValue0)+ Conf.Editor.Store(confSectionValue1)+ Conf.Export.Store(confSectionValue2)+ }+ Conf.OCR.Store(&conf.OCR{Provider: "paddleocr", Model: "tiny", Auto: true})util.WorkspaceDir = filepath.Dir(util.DataDir)util.TempDir, util.HistoryDir = t.TempDir(), t.TempDir()util.ConfDir = t.TempDir()@@ -142,12 +147,12 @@ func TestOCRResultReindexesWithoutTesseract(t *testing.T) {}util.RemoveAssetText(path)provider.err = nil- Conf.OCR.Auto = false+ Conf.OCR.Load().Auto = falseautoOCRAssets()if provider.called {t.Fatal("disabled automatic OCR reached provider")}- Conf.OCR.Auto = true+ Conf.OCR.Load().Auto = trueautoOCRAssets()if !provider.called || !strings.Contains(util.GetAssetText(path), "nativeocrkeyword") {t.Fatalf("headless automatic OCR did not save text: called=%v text=%q", provider.called, util.GetAssetText(path))@@ -179,7 +184,7 @@ func TestOCRResultReindexesWithoutTesseract(t *testing.T) {repairEncryptedBoxStateFromDEK(encryptedBox)}for _, selected := range []string{"paddleocr", "tesseract"} {- Conf.OCR.Provider = selected+ Conf.OCR.Load().Provider = selectedfor _, path := range []string{"assets/encrypted.png?box=" + encryptedBox, "assets/encrypted.png?box=" + encryptedBox + "#fragment", "assets/missing.png?box=" + encryptedBox + "#fragment"} {provider.called = falseif _, _, err := OCRAsset(context.Background(), path); err == nil || provider.called {@@ -252,7 +257,7 @@ func testOCRNotebookIsolation(t *testing.T, provider *ocrFixtureProvider, firstBsql.IndexTreeQueue(tree)}sql.FlushQueue()- Conf.OCR.Provider = "paddleocr"+ Conf.OCR.Load().Provider = "paddleocr"for _, test := range []struct{ reference, box, text string }{{" " + first + "&width=100#preview", firstBox, "firstocrkeyword"},{second, secondBox, "secondocrkeyword"},diff --git a/kernel/model/onboarding.go b/kernel/model/onboarding.goindex de9fb91581..267c2694d7 100644--- a/kernel/model/onboarding.go+++ b/kernel/model/onboarding.go@@ -84,11 +84,11 @@ func EnsureOnboarding() (ret *conf.Onboarding, notebookCreated bool, err error)onboardingLock.Lock()defer onboardingLock.Unlock()- if nil == Conf.Onboarding {- Conf.Onboarding = &conf.Onboarding{State: conf.OnboardingCompleted}+ if nil == Conf.Onboarding.Load() {+ Conf.Onboarding.Store(&conf.Onboarding{State: conf.OnboardingCompleted})Conf.Save()}- onboarding := Conf.Onboarding+ onboarding := Conf.Onboarding.Load()if !onboarding.NewUser || onboarding.Dismissed {return cloneOnboarding(onboarding), false, nil}@@ -105,7 +105,7 @@ func EnsureOnboarding() (ret *conf.Onboarding, notebookCreated bool, err error)if !onboarding.NewUser || onboarding.State == conf.OnboardingCompleted {return cloneOnboarding(onboarding), false, nil}- if util.ReadOnly || Conf.Publish.Enable {+ if util.ReadOnly || Conf.Publish.Load().Enable {return cloneOnboarding(onboarding), false, errors.New(Conf.Language(34))}@@ -159,21 +159,21 @@ func TriggerOnboardingIfEmpty() {onboardingLock.Lock()defer onboardingLock.Unlock()- if nil == Conf.Onboarding {- Conf.Onboarding = &conf.Onboarding{State: conf.OnboardingCompleted}+ if nil == Conf.Onboarding.Load() {+ Conf.Onboarding.Store(&conf.Onboarding{State: conf.OnboardingCompleted})}boxes, err := ListNotebooks()if err != nil {logging.LogErrorf("list notebooks before triggering onboarding failed: %s", err)return}- publishEnabled := Conf.Publish != nil && Conf.Publish.Enable- if !prepareOnboardingForEmptyWorkspace(Conf.Onboarding, util.ReadOnly || publishEnabled, len(boxes)) {+ publishEnabled := Conf.Publish.Load() != nil && Conf.Publish.Load().Enable+ if !prepareOnboardingForEmptyWorkspace(Conf.Onboarding.Load(), util.ReadOnly || publishEnabled, len(boxes)) {return}Conf.Save()evt := util.NewCmdResult("onboarding", 0, util.PushModeBroadcast)- evt.Data = cloneOnboarding(Conf.Onboarding)+ evt.Data = cloneOnboarding(Conf.Onboarding.Load())util.PushEvent(evt)}@@ -181,12 +181,11 @@ func DismissOnboarding() *conf.Onboarding {onboardingLock.Lock()defer onboardingLock.Unlock()- if nil == Conf.Onboarding {- Conf.Onboarding = &conf.Onboarding{State: conf.OnboardingCompleted}+ if nil == Conf.Onboarding.Load() {+ Conf.Onboarding.Store(&conf.Onboarding{State: conf.OnboardingCompleted})}- Conf.Onboarding.Dismissed = true- Conf.Save()- return cloneOnboarding(Conf.Onboarding)+ UpdateOnboardingConf(func(s *conf.Onboarding) { s.Dismissed = true })+ return cloneOnboarding(Conf.Onboarding.Load())}func cloneOnboarding(onboarding *conf.Onboarding) *conf.Onboarding {diff --git a/kernel/model/outline.go b/kernel/model/outline.goindex 794b7c4bd1..a305d13cd2 100644--- a/kernel/model/outline.go+++ b/kernel/model/outline.go@@ -214,6 +214,8 @@ func Outline(rootID string, preview bool) (ret []*Path, err error) {// OutlineInBox 与 Outline 一致,但按 boxID 路由 blocktree 查询到加密 db 或全局 db。func OutlineInBox(rootID string, preview bool, boxID string) (ret []*Path, err error) {+ confEditorSnapshot := Conf.LoadEditor()+FlushTxQueue()ret = []*Path{}@@ -222,11 +224,11 @@ func OutlineInBox(rootID string, preview bool, boxID string) (ret []*Path, err ereturn}headingNumbers := map[string]string{}- if headingNumberEnabled(tree, Conf.Editor.HeadingNumber) {- headingNumbers = headingNumberLabels(tree, Conf.Editor.HeadingNumberFormat)+ if headingNumberEnabled(tree, confEditorSnapshot.HeadingNumber) {+ headingNumbers = headingNumberLabels(tree, confEditorSnapshot.HeadingNumberFormat)}- if preview && Conf.Export.AddTitle {+ if preview && Conf.Export.Load().AddTitle {if root, _ := getBlock(tree.ID, tree); nil != root {root.IAL["type"] = "doc"title := &ast.Node{ID: root.ID, Type: ast.NodeHeading, HeadingLevel: 1}diff --git a/kernel/model/plugin.go b/kernel/model/plugin.goindex 57dda87b1a..7eea9e5c8d 100644--- a/kernel/model/plugin.go+++ b/kernel/model/plugin.go@@ -28,6 +28,7 @@ import ("github.com/siyuan-note/filelock""github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/bazaar"+ "github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/util""golang.org/x/sync/singleflight")@@ -167,11 +168,16 @@ var loadPetalsFlight singleflight.Group// IsPetalsEnabled returns whether petals are enabled and trusted to be loadedfunc IsPetalsEnabled() bool {- if Conf.Bazaar.PetalDisabled {+ return petalsEnabled(Conf.Bazaar.Load())+}++func petalsEnabled(confBazaarSnapshot *conf.Bazaar) bool {++ if confBazaarSnapshot.PetalDisabled {return false}- if !Conf.Bazaar.Trust {+ if !confBazaarSnapshot.Trust {// 移动端为了兼容通过同步获得的已有插件,不要求先确认集市信任;桌面端和 Docker 容器仍需用户手动确认if util.Container == util.ContainerStd || util.Container == util.ContainerDocker {return falsediff --git a/kernel/model/plugin_publish_test.go b/kernel/model/plugin_publish_test.goindex b06a247bf4..27b213c960 100644--- a/kernel/model/plugin_publish_test.go+++ b/kernel/model/plugin_publish_test.go@@ -18,8 +18,8 @@ func setupPluginPublishTest(t *testing.T) func(string) {root := t.TempDir()util.DataDir, util.ConfDir = filepath.Join(root, "data"), filepath.Join(root, "conf")Conf = NewAppConf()- Conf.Sync = conf.NewSync()- Conf.Bazaar = &conf.Bazaar{Trust: true}+ Conf.Sync.Store(conf.NewSync())+ Conf.Bazaar.Store(&conf.Bazaar{Trust: true})Conf.Lang = "en"t.Cleanup(func() { util.DataDir, util.ConfDir, Conf = originalData, originalConfDir, originalConf })write := func(declaration string) {@@ -93,11 +93,11 @@ func TestPluginPublishDataLifecycle(t *testing.T) {if _, err = SetPetalPublishEnabled("example", true); err != nil {t.Fatal(err)}- Conf.Bazaar.PetalDisabled = true+ Conf.Bazaar.Load().PetalDisabled = trueif _, err = LoadPluginPublishData("example"); !errors.Is(err, ErrPluginPublishDenied) {t.Fatalf("global disable read: %v", err)}- Conf.Bazaar.PetalDisabled = false+ Conf.Bazaar.Load().PetalDisabled = falseif _, err = SetPetalEnabled("example", false); err != nil {t.Fatal(err)}diff --git a/kernel/model/plugin_settings_test.go b/kernel/model/plugin_settings_test.goindex a0684643cf..219961462a 100644--- a/kernel/model/plugin_settings_test.go+++ b/kernel/model/plugin_settings_test.go@@ -13,8 +13,8 @@ import (func TestLoadSettingsWindowPetals(t *testing.T) {originalConf, originalDataDir := Conf, util.DataDirConf = NewAppConf()- Conf.Sync = conf.NewSync()- Conf.Bazaar = &conf.Bazaar{Trust: true}+ Conf.Sync.Store(conf.NewSync())+ Conf.Bazaar.Store(&conf.Bazaar{Trust: true})util.DataDir = t.TempDir()t.Cleanup(func() { Conf, util.DataDir = originalConf, originalDataDir })for _, item := range []struct {@@ -52,11 +52,11 @@ func TestLoadSettingsWindowPetals(t *testing.T) {if ordinary := LoadPetals("desktop", false); len(ordinary) != 3 {t.Fatal("settings loading changed ordinary loading")}- Conf.Bazaar.PetalDisabled = true+ Conf.Bazaar.Load().PetalDisabled = trueif len(LoadSettingsWindowPetals("desktop", false)) != 0 {t.Fatal("globally disabled plugins loaded")}- Conf.Bazaar.PetalDisabled, Conf.Bazaar.Trust = false, false+ Conf.Bazaar.Load().PetalDisabled, Conf.Bazaar.Load().Trust = false, falseif util.Container == util.ContainerStd || util.Container == util.ContainerDocker {if len(LoadSettingsWindowPetals("desktop", false)) != 0 {t.Fatal("untrusted plugins loaded")diff --git a/kernel/model/plugin_test.go b/kernel/model/plugin_test.goindex 6e064f1ba4..bc392a3c4f 100644--- a/kernel/model/plugin_test.go+++ b/kernel/model/plugin_test.go@@ -29,8 +29,8 @@ func TestSetPetalPublishEnabled(t *testing.T) {originalConf := ConforiginalDataDir := util.DataDirConf = NewAppConf()- Conf.Sync = conf.NewSync()- Conf.Bazaar = &conf.Bazaar{Trust: true}+ Conf.Sync.Store(conf.NewSync())+ Conf.Bazaar.Store(&conf.Bazaar{Trust: true})util.DataDir = t.TempDir()t.Cleanup(func() {Conf = originalConf@@ -105,9 +105,9 @@ func TestIsPetalsEnabled(t *testing.T) {})Conf = NewAppConf()- Conf.Bazaar = conf.NewBazaar()- Conf.Bazaar.PetalDisabled = false- Conf.Bazaar.Trust = false+ Conf.Bazaar.Store(conf.NewBazaar())+ Conf.Bazaar.Load().PetalDisabled = false+ Conf.Bazaar.Load().Trust = falsefor _, container := range []string{util.ContainerAndroid, util.ContainerIOS, util.ContainerHarmony} {util.Container = container@@ -123,12 +123,12 @@ func TestIsPetalsEnabled(t *testing.T) {}}- Conf.Bazaar.Trust = true+ Conf.Bazaar.Load().Trust = trueif !IsPetalsEnabled() {t.Fatal("petals should be enabled after bazaar trust")}- Conf.Bazaar.PetalDisabled = true+ Conf.Bazaar.Load().PetalDisabled = trueif IsPetalsEnabled() {t.Fatal("petals should be disabled explicitly")}diff --git a/kernel/model/publish_access_test.go b/kernel/model/publish_access_test.goindex 4157e414e9..d3f5ec6d44 100644--- a/kernel/model/publish_access_test.go+++ b/kernel/model/publish_access_test.go@@ -1393,20 +1393,20 @@ func TestFilterGraphByPublishAccess(t *testing.T) {}newGraph := func() ([]*GraphNode, []*GraphLink) {return []*GraphNode{- {ID: publicDocID, Box: boxID, Path: "/" + publicDocID + ".sy", Size: 10, Type: "NodeDocument"},- {ID: protectedBlockID, Box: boxID, Path: "/" + protectedDocID + "/" + protectedBlockID + ".sy", Size: 10, Type: "NodeParagraph"},- {ID: hiddenDocID, Box: boxID, Path: "/" + hiddenDocID + ".sy", Size: 10, Type: "NodeDocument"},- {ID: disabledDocID, Box: boxID, Path: "/" + disabledDocID + ".sy", Size: 10, Type: "NodeDocument"},- {ID: sharedTagID, Label: sharedTagID, Size: 10, Type: "NodeTag"},- {ID: protectedTagID, Label: protectedTagID, Size: 10, Type: "NodeTag"},- }, []*GraphLink{- {From: sharedTagID, To: publicDocID},- {From: sharedTagID, To: protectedBlockID},- {From: protectedTagID, To: protectedBlockID},- {From: publicDocID, To: protectedBlockID, Ref: true},- {From: publicDocID, To: hiddenDocID, Ref: true},- {From: publicDocID, To: disabledDocID, Ref: true},- }+ {ID: publicDocID, Box: boxID, Path: "/" + publicDocID + ".sy", Size: 10, Type: "NodeDocument"},+ {ID: protectedBlockID, Box: boxID, Path: "/" + protectedDocID + "/" + protectedBlockID + ".sy", Size: 10, Type: "NodeParagraph"},+ {ID: hiddenDocID, Box: boxID, Path: "/" + hiddenDocID + ".sy", Size: 10, Type: "NodeDocument"},+ {ID: disabledDocID, Box: boxID, Path: "/" + disabledDocID + ".sy", Size: 10, Type: "NodeDocument"},+ {ID: sharedTagID, Label: sharedTagID, Size: 10, Type: "NodeTag"},+ {ID: protectedTagID, Label: protectedTagID, Size: 10, Type: "NodeTag"},+ }, []*GraphLink{+ {From: sharedTagID, To: publicDocID},+ {From: sharedTagID, To: protectedBlockID},+ {From: protectedTagID, To: protectedBlockID},+ {From: publicDocID, To: protectedBlockID, Ref: true},+ {From: publicDocID, To: hiddenDocID, Ref: true},+ {From: publicDocID, To: disabledDocID, Ref: true},+ }}c, _ := gin.CreateTestContext(httptest.NewRecorder())@@ -1913,7 +1913,7 @@ func TestFilterBlockInfoByPublishAccessFiltersSubFileCount(t *testing.T) {util.DataDir = t.TempDir()util.BlockTreeDBPath = filepath.Join(util.DataDir, "blocktree.db")Conf = NewAppConf()- Conf.FileTree = conf.NewFileTree()+ Conf.FileTree.Store(conf.NewFileTree())treenode.InitBlockTree(true)t.Cleanup(func() {treenode.CloseDatabase()@@ -1982,7 +1982,7 @@ func TestFilterBlockInfoByPublishAccessFiltersRefIDs(t *testing.T) {util.DataDir = t.TempDir()util.BlockTreeDBPath = filepath.Join(util.DataDir, "blocktree.db")Conf = NewAppConf()- Conf.FileTree = conf.NewFileTree()+ Conf.FileTree.Store(conf.NewFileTree())treenode.InitBlockTree(true)t.Cleanup(func() {treenode.CloseDatabase()diff --git a/kernel/model/publish_resource_access_test.go b/kernel/model/publish_resource_access_test.goindex 6fcd0c4988..167aadbf31 100644--- a/kernel/model/publish_resource_access_test.go+++ b/kernel/model/publish_resource_access_test.go@@ -190,8 +190,8 @@ func TestCheckPluginAccessableInPublish(t *testing.T) {originalConf := Confutil.DataDir = t.TempDir()Conf = NewAppConf()- Conf.Sync = conf.NewSync()- Conf.Bazaar = &conf.Bazaar{Trust: true}+ Conf.Sync.Store(conf.NewSync())+ Conf.Bazaar.Store(&conf.Bazaar{Trust: true})t.Cleanup(func() {util.DataDir = originalDataDirConf = originalConfdiff --git a/kernel/model/push_reload.go b/kernel/model/push_reload.goindex 0a8113286f..a2b20aa683 100644--- a/kernel/model/push_reload.go+++ b/kernel/model/push_reload.go@@ -127,6 +127,18 @@ func pluginStorageName(absPath string) (pluginName string, ok bool) {// PushReloadAllEnabledPlugins 向前端推送已启用插件的全局状态,并返回相同的权威状态供请求方应用。func PushReloadAllEnabledPlugins(enabled, petalDisabled bool, revision uint64, changed bool) map[string]any {+ payload := PluginReloadPayload(enabled, petalDisabled, revision, changed)+ if changed {+ if len(payload["unloadPlugins"].([]string))+len(payload["reloadPlugins"].([]string)) > 0 {+ util.ReloadPublishServiceSessions()+ }+ util.BroadcastByType("main", "reloadPlugin", 0, "", payload)+ }+ return payload+}++// PluginReloadPayload 构造插件生命周期结果,响应与广播复用同一形态。+func PluginReloadPayload(enabled, petalDisabled bool, revision uint64, changed bool) map[string]any {pluginNames := []string{}for _, petal := range getPetals() {if petal.Enabled {@@ -156,10 +168,6 @@ func PushReloadAllEnabledPlugins(enabled, petalDisabled bool, revision uint64, cif changed {logging.LogInfof("reload plugins for global state, unloads=%v, reloads=%v, revision=%d",unloadPlugins, reloadPlugins, revision)- if 0 < len(unloadPlugins)+len(reloadPlugins) {- util.ReloadPublishServiceSessions()- }- util.BroadcastByType("main", "reloadPlugin", 0, "", payload)}return payload}diff --git a/kernel/model/render.go b/kernel/model/render.goindex f67d1d3141..1eaa13e407 100644--- a/kernel/model/render.go+++ b/kernel/model/render.go@@ -343,7 +343,7 @@ func resolveEmbedR(n *ast.Node, blockEmbedMode int, luteEngine *lute.Lute, resolstmt := n.ChildByType(ast.NodeBlockQueryEmbedScript).TokensStr()stmt = html.UnescapeString(stmt)stmt = strings.ReplaceAll(stmt, editor.IALValEscNewLine, "\n")- sqlBlocks := sql.SelectBlocksRawStmt(stmt, 1, Conf.Search.Limit)+ sqlBlocks := sql.SelectBlocksRawStmt(stmt, 1, Conf.Search.Load().Limit)var embedAccessChecker EmbedBlockAccessCheckerif 0 < len(accessChecker) {embedAccessChecker = accessChecker[0]@@ -393,7 +393,7 @@ func resolveEmbedR(n *ast.Node, blockEmbedMode int, luteEngine *lute.Lute, resolvar hChildren []*ast.Node// 从嵌入块的 IAL 属性中解析 custom-heading-mode,使用全局配置作为默认值- blockHeadingMode := Conf.Editor.HeadingEmbedMode+ blockHeadingMode := Conf.Editor.Load().HeadingEmbedModeif customHeadingMode := n.IALAttr(embedHeadingModeAttr); "" != customHeadingMode {if mode, err := strconv.Atoi(customHeadingMode); nil == err && (mode == 0 || mode == 1 || mode == 2) {blockHeadingMode = mode@@ -557,6 +557,8 @@ func renderBlockMarkdownR(id string, rendered *[]string, boxIDs ...string) (retfor _, child := range children {var unlinks, inserts []*ast.Nodeast.Walk(child, func(n *ast.Node, entering bool) ast.WalkStatus {+ confSearchSnapshot := Conf.LoadSearch()+if !entering || !n.IsBlock() {return ast.WalkContinue}@@ -567,9 +569,9 @@ func renderBlockMarkdownR(id string, rendered *[]string, boxIDs ...string) (retstmt = strings.ReplaceAll(stmt, editor.IALValEscNewLine, "\n")var sqlBlocks []*sql.Blockif boxID != "" && IsEncryptedBox(boxID) {- sqlBlocks = sql.SelectBlocksRawStmtInBox(stmt, 1, Conf.Search.Limit, boxID)+ sqlBlocks = sql.SelectBlocksRawStmtInBox(stmt, 1, confSearchSnapshot.Limit, boxID)} else {- sqlBlocks = sql.SelectBlocksRawStmt(stmt, 1, Conf.Search.Limit)+ sqlBlocks = sql.SelectBlocksRawStmt(stmt, 1, confSearchSnapshot.Limit)}for _, sqlBlock := range sqlBlocks {subNodes := renderBlockMarkdownR(sqlBlock.ID, rendered, boxID)diff --git a/kernel/model/repository.go b/kernel/model/repository.goindex 99eaae3dee..9b2e61f7be 100644--- a/kernel/model/repository.go+++ b/kernel/model/repository.go@@ -95,7 +95,7 @@ func autoPurgeRepo(cron bool) {lastAutoPurgeRepo = time.Now()}()- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {return}@@ -122,7 +122,7 @@ func autoPurgeRepo(cron bool) {tooOld := falsefor _, index := range indexes {- if now.UnixMilli()-index.Created <= int64(Conf.Repo.IndexRetentionDays)*24*60*60*1000 {+ if now.UnixMilli()-index.Created <= int64(Conf.Repo.Load().IndexRetentionDays)*24*60*60*1000 {date = time.UnixMilli(index.Created).Format("2006-01-02")if _, ok := dateGroupedIndexes[date]; !ok {dateGroupedIndexes[date] = []*entity.Index{}@@ -146,7 +146,7 @@ func autoPurgeRepo(cron bool) {// 过滤出每日需要保留的索引var retentionIndexIDs []stringfor date, indexes := range dateGroupedIndexes {- if len(indexes) <= Conf.Repo.RetentionIndexesDaily || todayDate == date {+ if len(indexes) <= Conf.Repo.Load().RetentionIndexesDaily || todayDate == date {for _, index := range indexes {retentionIndexIDs = append(retentionIndexIDs, index.ID)}@@ -156,9 +156,9 @@ func autoPurgeRepo(cron bool) {keepIndexes := hashset.New()keepIndexes.Add(indexes[0]) // 每天最后一个固定保留// 随机保留指定数量的索引- for i := 0; i < Conf.Repo.RetentionIndexesDaily*7; i++ {+ for i := 0; i < Conf.Repo.Load().RetentionIndexesDaily*7; i++ {keepIndexes.Add(indexes[mathRand.Intn(len(indexes)-1)])- if keepIndexes.Size() >= Conf.Repo.RetentionIndexesDaily {+ if keepIndexes.Size() >= Conf.Repo.Load().RetentionIndexesDaily {break}}@@ -201,7 +201,7 @@ func cancelPurge() {}func GetRepoFile(fileID string) (ret []byte, p string, err error) {- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {err = errors.New(Conf.Language(26))return}@@ -217,7 +217,7 @@ func GetRepoFile(fileID string) (ret []byte, p string, err error) {// ResolveRepoFileBoxID 返回仓库文件路径中明确记录的加密笔记本 ID。func ResolveRepoFileBoxID(fileID string) (boxID string, err error) {- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {return "", errors.New(Conf.Language(26))}repo, err := newRepository()@@ -241,7 +241,7 @@ func encryptedBoxIDFromRepoPath(repoPath string) string {}func RollbackRepoSnapshotFile(fileID string) (err error) {- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {err = errors.New(Conf.Language(26))return}@@ -378,7 +378,7 @@ func RollbackRepoSnapshotFile(fileID string) (err error) {}func OpenRepoSnapshotFile(fileID string) (title, content string, displayInText bool, updated int64, err error) {- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {err = errors.New(Conf.Language(26))return}@@ -573,7 +573,7 @@ type DiffIndex struct {}func DiffRepoSnapshots(left, right string) (ret *LeftRightDiff, err error) {- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {err = errors.New(Conf.Language(26))return}@@ -783,7 +783,7 @@ func parseTreeInSnapshot(data []byte, luteEngine *lute.Lute) (isLargeDoc bool, tfunc SearchRepoFile(keyword string, page int) (ret []*DiffFile, pageCount, totalCount int, err error) {ret = []*DiffFile{}- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {err = errors.New(Conf.Language(26))return}@@ -828,7 +828,7 @@ func SearchRepoFile(keyword string, page int) (ret []*DiffFile, pageCount, totalfunc GetRepoDocHistory(id string, page int) (ret []*RepoDocHistory, pageCount, totalCount int, err error) {ret = []*RepoDocHistory{}- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {err = errors.New(Conf.Language(26))return}@@ -860,7 +860,7 @@ func GetRepoDocHistory(id string, page int) (ret []*RepoDocHistory, pageCount, t}func ExportRepoFile(id string) (exportPath string, err error) {- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {err = errors.New(Conf.Language(26))return}@@ -1002,7 +1002,7 @@ func SearchRepoSnapshot(id string, includeFiles bool) (ret []*Snapshot, pageCounif includeFiles && len(id) != sha1.Size*2 {return ret, 0, 0, errors.New("complete snapshot ID is required to include files")}- if len(Conf.Repo.Key) == 0 {+ if len(Conf.Repo.Load().Key) == 0 {return ret, 0, 0, errors.New(Conf.Language(26))}repo, err := newRepository()@@ -1061,7 +1061,7 @@ func SearchRepoSnapshot(id string, includeFiles bool) (ret []*Snapshot, pageCounfunc GetRepoSnapshots(page int) (ret []*Snapshot, pageCount, totalCount int, err error) {ret = []*Snapshot{}- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {err = errors.New(Conf.Language(26))return}@@ -1195,14 +1195,13 @@ func ImportRepoKey(base64Key string) (retKey string, err error) {}suspendLANSyncManager()- Conf.Repo.Key = key- Conf.Save()- logging.LogInfof("imported repo key [%x]", sha1.Sum(Conf.Repo.Key))+ UpdateRepoConf(func(s *conf.Repo) { s.Key = key })+ logging.LogInfof("imported repo key [%x]", sha1.Sum(Conf.Repo.Load().Key))- if err = os.RemoveAll(Conf.Repo.GetSaveDir()); err != nil {+ if err = os.RemoveAll(Conf.Repo.Load().GetSaveDir()); err != nil {return}- if err = os.MkdirAll(Conf.Repo.GetSaveDir(), 0755); err != nil {+ if err = os.MkdirAll(Conf.Repo.Load().GetSaveDir(), 0755); err != nil {return}@@ -1236,9 +1235,8 @@ func ResetRepo() (err error) {}logging.LogInfof("reset data repo completed")- Conf.Repo.Key = nil- Conf.Sync.Enabled = false- Conf.Save()+ UpdateRepoConf(func(s *conf.Repo) { s.Key = nil })+ UpdateSyncConf(func(s *conf.Sync) { s.Enabled = false })refreshLANSyncManager()util.PushUpdateMsg(msgId, Conf.Language(145), 3000)@@ -1318,10 +1316,10 @@ func InitRepoKeyFromPassphrase(passphrase string) (err error) {util.PushMsg(Conf.Language(136), 3000)suspendLANSyncManager()- if err = os.RemoveAll(Conf.Repo.GetSaveDir()); err != nil {+ if err = os.RemoveAll(Conf.Repo.Load().GetSaveDir()); err != nil {return}- if err = os.MkdirAll(Conf.Repo.GetSaveDir(), 0755); err != nil {+ if err = os.MkdirAll(Conf.Repo.Load().GetSaveDir(), 0755); err != nil {return}@@ -1340,9 +1338,8 @@ func InitRepoKeyFromPassphrase(passphrase string) (err error) {}}- Conf.Repo.Key = key- Conf.Save()- logging.LogInfof("inited repo key [%x]", sha1.Sum(Conf.Repo.Key))+ UpdateRepoConf(func(s *conf.Repo) { s.Key = key })+ logging.LogInfof("inited repo key [%x]", sha1.Sum(Conf.Repo.Load().Key))release()initDataRepo()@@ -1362,10 +1359,10 @@ func InitRepoKey() (err error) {util.PushMsg(Conf.Language(136), 3000)suspendLANSyncManager()- if err = os.RemoveAll(Conf.Repo.GetSaveDir()); err != nil {+ if err = os.RemoveAll(Conf.Repo.Load().GetSaveDir()); err != nil {return}- if err = os.MkdirAll(Conf.Repo.GetSaveDir(), 0755); err != nil {+ if err = os.MkdirAll(Conf.Repo.Load().GetSaveDir(), 0755); err != nil {return}@@ -1388,9 +1385,8 @@ func InitRepoKey() (err error) {logging.LogErrorf("init data repo key failed: %s", err)return}- Conf.Repo.Key = key- Conf.Save()- logging.LogInfof("inited repo key [%x]", sha1.Sum(Conf.Repo.Key))+ UpdateRepoConf(func(s *conf.Repo) { s.Key = key })+ logging.LogInfof("inited repo key [%x]", sha1.Sum(Conf.Repo.Load().Key))release()initDataRepo()@@ -1416,7 +1412,7 @@ func CheckoutRepoDirect(id string) error {}func checkoutRepo(id string) (err error) {- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {err = errors.New(Conf.Language(26))util.PushErrMsg(err.Error(), 7000)return@@ -1452,9 +1448,8 @@ func checkoutRepo(id string) (err error) {defer WatchThemes()// 恢复快照时自动暂停同步,避免刚刚恢复后的数据又被同步覆盖- syncEnabled := Conf.Sync.Enabled- Conf.Sync.Enabled = false- Conf.Save()+ syncEnabled := Conf.Sync.Load().Enabled+ UpdateSyncConf(func(s *conf.Sync) { s.Enabled = false })if syncEnabled {util.PushMsg(Conf.Language(134), 0)}@@ -1562,7 +1557,7 @@ func appendAgentRollbackEntries() {func DownloadCloudSnapshot(tag, id string) (err error) {assetDownloadSourceMu.RLock()defer assetDownloadSourceMu.RUnlock()- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {err = errors.New(Conf.Language(26))return}@@ -1574,7 +1569,7 @@ func DownloadCloudSnapshot(tag, id string) (err error) {return}- switch Conf.Sync.Provider {+ switch Conf.Sync.Load().Provider {case conf.ProviderSiYuan:if !IsSubscriber() {util.PushErrMsg(Conf.Language(29), 5000)@@ -1606,9 +1601,11 @@ func DownloadCloudSnapshot(tag, id string) (err error) {}func UploadCloudSnapshot(tag, id string) (err error) {+ confSyncSnapshot := Conf.LoadSync()+assetDownloadSourceMu.RLock()defer assetDownloadSourceMu.RUnlock()- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {err = errors.New(Conf.Language(26))return}@@ -1620,7 +1617,7 @@ func UploadCloudSnapshot(tag, id string) (err error) {return}- switch Conf.Sync.Provider {+ switch confSyncSnapshot.Provider {case conf.ProviderSiYuan:if !IsSubscriber() {util.PushErrMsg(Conf.Language(29), 5000)@@ -1641,7 +1638,7 @@ func UploadCloudSnapshot(tag, id string) (err error) {err = fmt.Errorf(Conf.Language(84), Conf.Language(154))return}- if conf.ProviderSiYuan == Conf.Sync.Provider && errors.Is(err, dejavu.ErrCloudStorageSizeExceeded) {+ if conf.ProviderSiYuan == confSyncSnapshot.Provider && errors.Is(err, dejavu.ErrCloudStorageSizeExceeded) {u := Conf.GetUser()msg := fmt.Sprintf(Conf.Language(43), humanize.BytesCustomCeil(uint64(u.UserSiYuanRepoSize), 2))if 2 == u.UserSiYuanSubscriptionPlan {@@ -1663,7 +1660,7 @@ func UploadCloudSnapshot(tag, id string) (err error) {func RemoveCloudRepoTag(tag string) (err error) {assetDownloadSourceMu.RLock()defer assetDownloadSourceMu.RUnlock()- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {err = errors.New(Conf.Language(26))return}@@ -1675,7 +1672,7 @@ func RemoveCloudRepoTag(tag string) (err error) {return}- switch Conf.Sync.Provider {+ switch Conf.Sync.Load().Provider {case conf.ProviderSiYuan:if !IsSubscriber() {util.PushErrMsg(Conf.Language(29), 5000)@@ -1699,7 +1696,7 @@ func GetCloudRepoTagSnapshots() (ret []*dejavu.Log, err error) {assetDownloadSourceMu.RLock()defer assetDownloadSourceMu.RUnlock()ret = []*dejavu.Log{}- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {err = errors.New(Conf.Language(26))return}@@ -1711,7 +1708,7 @@ func GetCloudRepoTagSnapshots() (ret []*dejavu.Log, err error) {return}- switch Conf.Sync.Provider {+ switch Conf.Sync.Load().Provider {case conf.ProviderSiYuan:if !IsSubscriber() {util.PushErrMsg(Conf.Language(29), 5000)@@ -1743,7 +1740,7 @@ func GetCloudRepoSnapshotsByTime(page int, startTime, endTime int64) (ret []*dejassetDownloadSourceMu.RLock()defer assetDownloadSourceMu.RUnlock()ret = []*dejavu.Log{}- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {err = errors.New(Conf.Language(26))return}@@ -1755,7 +1752,7 @@ func GetCloudRepoSnapshotsByTime(page int, startTime, endTime int64) (ret []*dejreturn}- switch Conf.Sync.Provider {+ switch Conf.Sync.Load().Provider {case conf.ProviderSiYuan:if !IsSubscriber() {util.PushErrMsg(Conf.Language(29), 5000)@@ -1785,7 +1782,7 @@ func GetCloudRepoSnapshotsByTime(page int, startTime, endTime int64) (ret []*dejfunc GetTagSnapshots() (ret []*Snapshot, err error) {ret = []*Snapshot{}- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {err = errors.New(Conf.Language(26))return}@@ -1810,7 +1807,7 @@ func GetTagSnapshots() (ret []*Snapshot, err error) {func RemoveTagSnapshot(tag string) (err error) {assetDownloadSourceMu.RLock()defer assetDownloadSourceMu.RUnlock()- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {err = errors.New(Conf.Language(26))return}@@ -1827,7 +1824,7 @@ func RemoveTagSnapshot(tag string) (err error) {func TagSnapshot(id, name string) (err error) {assetDownloadSourceMu.RLock()defer assetDownloadSourceMu.RUnlock()- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {err = errors.New(Conf.Language(26))return}@@ -1881,7 +1878,7 @@ func normalizeSnapshotMemo(memo string) string {}func CreateRepoSnapshot(memo string) (id string, created bool, err error) {- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {err = errors.New(Conf.Language(26))return}@@ -1936,7 +1933,7 @@ func CreateRepoSnapshot(memo string) (id string, created bool, err error) {}func CheckRepoSnapshot() (changed bool, err error) {- if len(Conf.Repo.Key) == 0 {+ if len(Conf.Repo.Load().Key) == 0 {return false, errors.New(Conf.Language(26))}FlushTxQueue()@@ -1955,7 +1952,7 @@ func CheckRepoSnapshot() (changed bool, err error) {}func SetRepoSnapshotMemo(id, memo string) error {- if len(Conf.Repo.Key) == 0 {+ if len(Conf.Repo.Load().Key) == 0 {return errors.New(Conf.Language(26))}assetDownloadSourceMu.RLock()@@ -1986,7 +1983,7 @@ func IsSyncingFile(rootID string) (ret bool) {}func syncStatusBarDisabled() bool {- return util.StatusBarCfg.MsgDataSyncDisabled+ return util.StatusBarCfg.Load().MsgDataSyncDisabled}func pushSyncStatusBar(msg string) {@@ -2005,7 +2002,7 @@ func newSyncContext() map[string]any {}func formatSyncRepoErrorMsg(err error) string {- if conf.ProviderSiYuan == Conf.Sync.Provider && errors.Is(err, dejavu.ErrCloudStorageSizeExceeded) {+ if conf.ProviderSiYuan == Conf.Sync.Load().Provider && errors.Is(err, dejavu.ErrCloudStorageSizeExceeded) {u := Conf.GetUser()if 2 == u.UserSiYuanSubscriptionPlan {return fmt.Sprintf(Conf.Language(68), humanize.BytesCustomCeil(uint64(u.UserSiYuanRepoSize), 2))@@ -2016,7 +2013,7 @@ func formatSyncRepoErrorMsg(err error) string {}func syncRepoDownload() (err error) {- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {planSyncAfter(fixSyncInterval)msg := Conf.Language(26)@@ -2039,7 +2036,7 @@ func syncRepoDownload() (err error) {return}- logging.LogInfof("downloading data repo [device=%s, kernel=%s, provider=%d, mode=%s/%t]", Conf.System.ID, KernelID, Conf.Sync.Provider, "d", true)+ logging.LogInfof("downloading data repo [device=%s, kernel=%s, provider=%d, mode=%s/%t]", Conf.System.Load().ID, KernelID, Conf.Sync.Load().Provider, "d", true)defer finishAssetDownloadRecovery(repo, &err)start := time.Now()indexStart := time.Now()@@ -2050,8 +2047,7 @@ func syncRepoDownload() (err error) {logging.LogErrorf("sync data repo download failed: %s", err)msg := fmt.Sprintf(Conf.Language(80), formatRepoErrorMsg(err))- Conf.Sync.Stat = msg- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.Stat = msg })pushSyncStatusBar(msg)util.PushErrMsg(msg, 0)return@@ -2069,19 +2065,17 @@ func syncRepoDownload() (err error) {logging.LogErrorf("sync data repo download failed: %s", err)msg := formatSyncRepoErrorMsg(err)- Conf.Sync.Stat = msg- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.Stat = msg })pushSyncStatusBar(msg)util.PushErrMsg(msg, 0)return}pushSyncStatusBar(fmt.Sprintf(Conf.Language(149), elapsed.Seconds()))- Conf.Sync.Synced = util.CurrentTimeMillis()+ UpdateSyncConf(func(s *conf.Sync) { s.Synced = util.CurrentTimeMillis() })msg := fmt.Sprintf(Conf.Language(150), trafficStat.UploadFileCount, trafficStat.DownloadFileCount, trafficStat.UploadChunkCount, trafficStat.DownloadChunkCount, humanize.BytesCustomCeil(uint64(trafficStat.UploadBytes), 2), humanize.BytesCustomFloor(uint64(trafficStat.DownloadBytes+trafficStat.PeerDownloadBytes), 2))msg = appendLANSyncTrafficStat(msg, trafficStat)- Conf.Sync.Stat = msg- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.Stat = msg })autoSyncErrCount = 0BootSyncSucc.Store(0)@@ -2094,7 +2088,7 @@ func syncRepoDownload() (err error) {}func syncRepoUpload() (err error) {- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {planSyncAfter(fixSyncInterval)msg := Conf.Language(26)@@ -2117,7 +2111,7 @@ func syncRepoUpload() (err error) {return}- logging.LogInfof("uploading data repo [device=%s, kernel=%s, provider=%d, mode=%s/%t]", Conf.System.ID, KernelID, Conf.Sync.Provider, "u", true)+ logging.LogInfof("uploading data repo [device=%s, kernel=%s, provider=%d, mode=%s/%t]", Conf.System.Load().ID, KernelID, Conf.Sync.Load().Provider, "u", true)defer finishAssetDownloadRecovery(repo, &err)start := time.Now()indexStart := time.Now()@@ -2128,8 +2122,7 @@ func syncRepoUpload() (err error) {logging.LogErrorf("sync data repo upload failed: %s", err)msg := fmt.Sprintf(Conf.Language(80), formatRepoErrorMsg(err))- Conf.Sync.Stat = msg- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.Stat = msg })pushSyncStatusBar(msg)util.PushErrMsg(msg, 0)return@@ -2145,19 +2138,17 @@ func syncRepoUpload() (err error) {logging.LogErrorf("sync data repo upload failed: %s", err)msg := formatSyncRepoErrorMsg(err)- Conf.Sync.Stat = msg- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.Stat = msg })pushSyncStatusBar(msg)util.PushErrMsg(msg, 0)return}pushSyncStatusBar(fmt.Sprintf(Conf.Language(149), elapsed.Seconds()))- Conf.Sync.Synced = util.CurrentTimeMillis()+ UpdateSyncConf(func(s *conf.Sync) { s.Synced = util.CurrentTimeMillis() })msg := fmt.Sprintf(Conf.Language(150), trafficStat.UploadFileCount, trafficStat.DownloadFileCount, trafficStat.UploadChunkCount, trafficStat.DownloadChunkCount, humanize.BytesCustomCeil(uint64(trafficStat.UploadBytes), 2), humanize.BytesCustomCeil(uint64(trafficStat.DownloadBytes+trafficStat.PeerDownloadBytes), 2))msg = appendLANSyncTrafficStat(msg, trafficStat)- Conf.Sync.Stat = msg- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.Stat = msg })autoSyncErrCount = 0BootSyncSucc.Store(0)@@ -2172,7 +2163,7 @@ func syncRepoUpload() (err error) {var isBootSyncing = atomic.Bool{}func bootSyncRepo() (err error) {- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {autoSyncErrCount++planSyncAfter(fixSyncInterval)@@ -2200,7 +2191,7 @@ func bootSyncRepo() (err error) {if err != nil {return}- preparedSourceScope := assetDownloadScope(Conf.Sync.Provider, preparedSourceConf, Conf.Repo.Key)+ preparedSourceScope := assetDownloadScope(Conf.Sync.Load().Provider, preparedSourceConf, Conf.Repo.Load().Key)isBootSyncing.Store(true)@@ -2249,8 +2240,7 @@ func bootSyncRepo() (err error) {logging.LogErrorf("sync data repo failed: %s", err)msg := formatSyncRepoErrorMsg(err)- Conf.Sync.Stat = msg- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.Stat = msg })pushSyncStatusBar(msg)util.PushErrMsg(msg, 0)BootSyncSucc.Store(1)@@ -2277,13 +2267,15 @@ func bootSyncRepo() (err error) {if 0 < len(fetchedFiles) {go func() {+ confSyncSnapshot := Conf.LoadSync()+defer logging.Recover()defer isBootSyncing.Store(false)lockSync()defer unlockSync()currentSourceConf, sourceErr := buildCloudConf()- if sourceErr != nil || preparedSourceScope != assetDownloadScope(Conf.Sync.Provider, currentSourceConf, Conf.Repo.Key) {+ if sourceErr != nil || preparedSourceScope != assetDownloadScope(confSyncSnapshot.Provider, currentSourceConf, Conf.Repo.Load().Key) {logging.LogInfof("skip prepared boot sync after repository source changed")return}@@ -2293,7 +2285,7 @@ func bootSyncRepo() (err error) {return}- logging.LogInfof("syncing prepared boot data repo [device=%s, kernel=%s, provider=%d]", Conf.System.ID, KernelID, Conf.Sync.Provider)+ logging.LogInfof("syncing prepared boot data repo [device=%s, kernel=%s, provider=%d]", Conf.System.Load().ID, KernelID, confSyncSnapshot.Provider)syncStart := time.Now()indexStart := time.Now()_, _, syncErr := indexRepoBeforeCloudSync(repo)@@ -2313,7 +2305,7 @@ func bootSyncRepo() (err error) {}func syncRepo(exit, byHand bool) (cloudPublished bool, err error) {- if 1 > len(Conf.Repo.Key) {+ if 1 > len(Conf.Repo.Load().Key) {autoSyncErrCount++planSyncAfter(fixSyncInterval)@@ -2338,7 +2330,7 @@ func syncRepo(exit, byHand bool) (cloudPublished bool, err error) {return}- logging.LogInfof("syncing data repo [device=%s, kernel=%s, provider=%d, mode=%s/%t]", Conf.System.ID, KernelID, Conf.Sync.Provider, "a", byHand)+ logging.LogInfof("syncing data repo [device=%s, kernel=%s, provider=%d, mode=%s/%t]", Conf.System.Load().ID, KernelID, Conf.Sync.Load().Provider, "a", byHand)start := time.Now()indexStart := time.Now()_, _, err = indexRepoBeforeCloudSync(repo)@@ -2349,8 +2341,7 @@ func syncRepo(exit, byHand bool) (cloudPublished bool, err error) {logging.LogErrorf("sync data repo failed: %s", err)msg := fmt.Sprintf(Conf.Language(80), formatRepoErrorMsg(err))- Conf.Sync.Stat = msg- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.Stat = msg })pushSyncStatusBar(msg)if 1 > autoSyncErrCount || byHand {util.PushErrMsg(msg, 0)@@ -2388,8 +2379,7 @@ func syncIndexedRepo(repo *dejavu.Repo, exit, byHand bool, start time.Time, indelogging.LogErrorf("sync data repo failed: %s", err)msg := formatSyncRepoErrorMsg(err)- Conf.Sync.Stat = msg- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.Stat = msg })pushSyncStatusBar(msg)if 1 > autoSyncErrCount || byHand {util.PushErrMsg(msg, 0)@@ -2408,11 +2398,10 @@ func syncIndexedRepo(repo *dejavu.Repo, exit, byHand bool, start time.Time, inde}pushSyncStatusBar(fmt.Sprintf(Conf.Language(149), elapsed.Seconds()))- Conf.Sync.Synced = util.CurrentTimeMillis()+ UpdateSyncConf(func(s *conf.Sync) { s.Synced = util.CurrentTimeMillis() })msg := fmt.Sprintf(Conf.Language(150), trafficStat.UploadFileCount, trafficStat.DownloadFileCount, trafficStat.UploadChunkCount, trafficStat.DownloadChunkCount, humanize.BytesCustomCeil(uint64(trafficStat.UploadBytes), 2), humanize.BytesCustomCeil(uint64(trafficStat.DownloadBytes+trafficStat.PeerDownloadBytes), 2))msg = appendLANSyncTrafficStat(msg, trafficStat)- Conf.Sync.Stat = msg- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.Stat = msg })autoSyncErrCount = 0calcPetalDiff(beforeSyncPetals, mergeResult)@@ -2469,8 +2458,10 @@ func calcPetalDiff(beforeSyncPetals []*Petal, mergeResult *dejavu.MergeResult) {}func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult, trafficStat *dejavu.TrafficStat, mode string, elapsed time.Duration, immediateIndex ...bool) {+ confSyncSnapshot := Conf.LoadSync()+logging.LogInfof("synced data repo [device=%s, kernel=%s, provider=%d, mode=%s/%t, ufc=%d, dfc=%d, ucc=%d, dcc=%d, ub=%s, db=%s, pfc=%d, pcc=%d, pb=%s, pf=%d] in [%.2fs], merge result [conflicts=%d, upserts=%d, removes=%d]\n\n",- Conf.System.ID, KernelID, Conf.Sync.Provider, mode, byHand,+ Conf.System.Load().ID, KernelID, confSyncSnapshot.Provider, mode, byHand,trafficStat.UploadFileCount, trafficStat.DownloadFileCount, trafficStat.UploadChunkCount, trafficStat.DownloadChunkCount, humanize.BytesCustomCeil(uint64(trafficStat.UploadBytes), 2), humanize.BytesCustomCeil(uint64(trafficStat.DownloadBytes), 2),trafficStat.PeerDownloadFileCount, trafficStat.PeerDownloadChunkCount, humanize.BytesCustomCeil(uint64(trafficStat.PeerDownloadBytes), 2), trafficStat.PeerFallbackCount,elapsed.Seconds(),@@ -2483,7 +2474,7 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,conflictCount := mergeResult.ConflictCount()if 0 < conflictCount || mergeResult.HasHistory() {luteEngine := util.NewLute()- if 0 < conflictCount && Conf.Sync.GenerateConflictDoc {+ if 0 < conflictCount && confSyncSnapshot.GenerateConflictDoc {// 云端同步发生冲突时生成副本 https://github.com/siyuan-note/siyuan/issues/5687conflictCopyFiles := mergeResult.ConflictCopyFiles()@@ -2766,7 +2757,7 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,}if needReloadSnippet {- PushReloadSnippet(Conf.Snippet)+ PushReloadSnippet(Conf.Snippet.Load())}removeEmptyPackageDirs(filepath.Join(util.DataDir, "plugins"), removePluginDirSet)@@ -2947,7 +2938,7 @@ func cleanupSyncedBoxResiduals(removedBoxIDs map[string]bool) {}func appendLANSyncTrafficStat(message string, trafficStat *dejavu.TrafficStat) string {- if nil == Conf.Sync || nil == Conf.Sync.LAN || !Conf.Sync.LAN.Enabled {+ if nil == Conf.Sync.Load() || nil == Conf.Sync.Load().LAN || !Conf.Sync.Load().LAN.Enabled {return message}traffic := humanize.BytesCustomCeil(uint64(trafficStat.PeerDownloadBytes), 2)@@ -3023,7 +3014,7 @@ func indexRepoBeforeCloudSync(repo *dejavu.Repo) (beforeIndex, afterIndex *entitpushSyncStatusBar(fmt.Sprintf(Conf.Language(148), elapsed.Seconds()))}- if Conf.Repo.SyncIndexTiming < elapsed.Milliseconds() {+ if Conf.Repo.Load().SyncIndexTiming < elapsed.Milliseconds() {logging.LogWarnf("index data repo before cloud sync elapsed [%dms]", elapsed.Milliseconds())if !promotedPurgeDataRepo {go func() {@@ -3051,14 +3042,15 @@ func newRepository() (ret *dejavu.Repo, err error) {// newCloudRepositoryWithAssetSourceLocked 在访问云端前校验配置,保留未配置云端时的本地快照功能。func newCloudRepositoryWithAssetSourceLocked() (*dejavu.Repo, error) {+ confSyncSnapshot := Conf.LoadSync()var err error- switch Conf.Sync.Provider {+ switch confSyncSnapshot.Provider {case conf.ProviderS3:- err = validateSyncS3(Conf.Sync.S3)+ err = validateSyncS3(confSyncSnapshot.S3)case conf.ProviderWebDAV:- err = validateSyncWebDAV(Conf.Sync.WebDAV)+ err = validateSyncWebDAV(confSyncSnapshot.WebDAV)case conf.ProviderLocal:- err = validateSyncLocal(Conf.Sync.Local)+ err = validateSyncLocal(confSyncSnapshot.Local)}if err != nil {return nil, err@@ -3068,6 +3060,12 @@ func newCloudRepositoryWithAssetSourceLocked() (*dejavu.Repo, error) {// newRepositoryWithAssetSourceLocked 由已持有来源锁的调用方创建仓库,避免读写锁递归等待。func newRepositoryWithAssetSourceLocked() (ret *dejavu.Repo, err error) {+ confRepoSnapshot := Conf.LoadRepo()++ confSyncSnapshot := Conf.LoadSync()++ confSystemSnapshot := Conf.LoadSystem()+if err = recoverSortConfAppends(); err != nil {return}@@ -3077,7 +3075,7 @@ func newRepositoryWithAssetSourceLocked() (ret *dejavu.Repo, err error) {}var cloudRepo cloud.Cloud- switch Conf.Sync.Provider {+ switch confSyncSnapshot.Provider {case conf.ProviderSiYuan:cloudRepo = cloud.NewSiYuan(&cloud.BaseCloud{Conf: cloudConf})case conf.ProviderS3:@@ -3097,7 +3095,7 @@ func newRepositoryWithAssetSourceLocked() (ret *dejavu.Repo, err error) {case conf.ProviderLocal:cloudRepo = cloud.NewLocal(&cloud.BaseCloud{Conf: cloudConf})default:- err = fmt.Errorf("unknown cloud provider [%d]", Conf.Sync.Provider)+ err = fmt.Errorf("unknown cloud provider [%d]", confSyncSnapshot.Provider)return}@@ -3106,13 +3104,13 @@ func newRepositoryWithAssetSourceLocked() (ret *dejavu.Repo, err error) {return nil, err}dataDir := util.DataDir- scope := assetDownloadScope(Conf.Sync.Provider, cloudConf, Conf.Repo.Key)+ scope := assetDownloadScope(confSyncSnapshot.Provider, cloudConf, confRepoSnapshot.Key)ret, err = dejavu.NewRepoWithOptions(dejavu.Options{DataPath: util.DataDir, RepoPath: util.RepoDir, HistoryPath: util.HistoryDir, TempPath: util.TempDir,- DeviceID: Conf.System.ID, DeviceName: Conf.System.Name, DeviceOS: Conf.System.OS,- AESKey: Conf.Repo.Key, IgnoreLines: ignoreLines, Cloud: cloudRepo,+ DeviceID: confSystemSnapshot.ID, DeviceName: confSystemSnapshot.Name, DeviceOS: confSystemSnapshot.OS,+ AESKey: confRepoSnapshot.Key, IgnoreLines: ignoreLines, Cloud: cloudRepo,IgnoreRulePath: syncIgnoreRulePath, HiddenDirectoryNames: []string{".siyuan"},- OnCloudIndexList: newSyncCloudIndexListObserver(scope, Conf.Sync.Provider),+ OnCloudIndexList: newSyncCloudIndexListObserver(scope, confSyncSnapshot.Provider),PathFilter: func(info os.FileInfo, absPath string) (bool, error) {return syncPathFilter(dataDir, info, absPath)},@@ -3121,8 +3119,8 @@ func newRepositoryWithAssetSourceLocked() (ret *dejavu.Repo, err error) {logging.LogErrorf("init data repo failed: %s", err)return}- if Conf.Sync.Provider == conf.ProviderSiYuan && Conf.GetUser() == nil {- stored, readErr := dejavu.ReadAssetDownloadScope(assetDownloadStatePath(), Conf.Repo.Key)+ if confSyncSnapshot.Provider == conf.ProviderSiYuan && Conf.GetUser() == nil {+ stored, readErr := dejavu.ReadAssetDownloadScope(assetDownloadStatePath(), confRepoSnapshot.Key)if readErr != nil {return nil, readErr}@@ -3130,7 +3128,7 @@ func newRepositoryWithAssetSourceLocked() (ret *dejavu.Repo, err error) {scope = stored}}- err = ret.ConfigureAssetDownloads(Conf.Sync.AssetDownloadMode == 1, assetDownloadStatePath(), scope)+ err = ret.ConfigureAssetDownloads(confSyncSnapshot.AssetDownloadMode == 1, assetDownloadStatePath(), scope)return}@@ -3360,14 +3358,13 @@ func subscribeRepoEvents() {}func buildCloudConf() (ret *cloud.Conf, err error) {- if conf.ProviderS3 != Conf.Sync.Provider && !cloud.IsValidCloudDirName(Conf.Sync.CloudName) {+ if conf.ProviderS3 != Conf.Sync.Load().Provider && !cloud.IsValidCloudDirName(Conf.Sync.Load().CloudName) {logging.LogWarnf("invalid cloud repo name, rename it to [main]")- Conf.Sync.CloudName = "main"- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.CloudName = "main" })}userId, token, availableSize := "0", "", int64(1024*1024*1024*1024*2)- if nil != Conf.User && conf.ProviderSiYuan == Conf.Sync.Provider {+ if nil != Conf.User && conf.ProviderSiYuan == Conf.Sync.Load().Provider {u := Conf.GetUser()userId = u.UserIdtoken = u.UserToken@@ -3375,45 +3372,45 @@ func buildCloudConf() (ret *cloud.Conf, err error) {}ret = &cloud.Conf{- Dir: Conf.Sync.CloudName,+ Dir: Conf.Sync.Load().CloudName,UserID: userId,Token: token,AvailableSize: availableSize,Server: util.GetCloudServer(),}- switch Conf.Sync.Provider {+ switch Conf.Sync.Load().Provider {case conf.ProviderSiYuan:ret.Endpoint = util.GetCloudSyncServer()case conf.ProviderS3:ret.S3 = &cloud.ConfS3{- Endpoint: Conf.Sync.S3.Endpoint,- AccessKey: Conf.Sync.S3.AccessKey,- SecretKey: Conf.Sync.S3.SecretKey,- Bucket: Conf.Sync.S3.Bucket,- Region: Conf.Sync.S3.Region,- PathStyle: Conf.Sync.S3.PathStyle,- SkipTlsVerify: Conf.Sync.S3.SkipTlsVerify,- Timeout: Conf.Sync.S3.Timeout,- ConcurrentReqs: Conf.Sync.S3.ConcurrentReqs,+ Endpoint: Conf.Sync.Load().S3.Endpoint,+ AccessKey: Conf.Sync.Load().S3.AccessKey,+ SecretKey: Conf.Sync.Load().S3.SecretKey,+ Bucket: Conf.Sync.Load().S3.Bucket,+ Region: Conf.Sync.Load().S3.Region,+ PathStyle: Conf.Sync.Load().S3.PathStyle,+ SkipTlsVerify: Conf.Sync.Load().S3.SkipTlsVerify,+ Timeout: Conf.Sync.Load().S3.Timeout,+ ConcurrentReqs: Conf.Sync.Load().S3.ConcurrentReqs,}case conf.ProviderWebDAV:ret.WebDAV = &cloud.ConfWebDAV{- Endpoint: Conf.Sync.WebDAV.Endpoint,- Username: Conf.Sync.WebDAV.Username,- Password: Conf.Sync.WebDAV.Password,- SkipTlsVerify: Conf.Sync.WebDAV.SkipTlsVerify,- Timeout: Conf.Sync.WebDAV.Timeout,- ConcurrentReqs: Conf.Sync.WebDAV.ConcurrentReqs,+ Endpoint: Conf.Sync.Load().WebDAV.Endpoint,+ Username: Conf.Sync.Load().WebDAV.Username,+ Password: Conf.Sync.Load().WebDAV.Password,+ SkipTlsVerify: Conf.Sync.Load().WebDAV.SkipTlsVerify,+ Timeout: Conf.Sync.Load().WebDAV.Timeout,+ ConcurrentReqs: Conf.Sync.Load().WebDAV.ConcurrentReqs,}case conf.ProviderLocal:ret.Local = &cloud.ConfLocal{- Endpoint: Conf.Sync.Local.Endpoint,- Timeout: Conf.Sync.Local.Timeout,- ConcurrentReqs: Conf.Sync.Local.ConcurrentReqs,+ Endpoint: Conf.Sync.Load().Local.Endpoint,+ Timeout: Conf.Sync.Load().Local.Timeout,+ ConcurrentReqs: Conf.Sync.Load().Local.ConcurrentReqs,}default:- err = fmt.Errorf("invalid provider [%d]", Conf.Sync.Provider)+ err = fmt.Errorf("invalid provider [%d]", Conf.Sync.Load().Provider)return}return@@ -3467,7 +3464,7 @@ func GetCloudSpace() (s *Sync, b *Backup, hSize, hAssetSize, hTotalSize, hExchanhTrafficDownloadSize = "-"hTrafficAPIGet = "-"hTrafficAPIPut = "-"- if conf.ProviderSiYuan == Conf.Sync.Provider {+ if conf.ProviderSiYuan == Conf.Sync.Load().Provider {s.HSize = humanize.BytesCustomCeil(uint64(syncSize), 2)b.HSize = humanize.BytesCustomCeil(uint64(backupSize), 2)hAssetSize = humanize.BytesCustomCeil(uint64(assetSize), 2)diff --git a/kernel/model/repository_error_test.go b/kernel/model/repository_error_test.goindex b89fbc0ff5..14afe271f4 100644--- a/kernel/model/repository_error_test.go+++ b/kernel/model/repository_error_test.go@@ -41,7 +41,7 @@ func TestFormatSyncRepoErrorMsg(t *testing.T) {Conf = &AppConf{userLock: &sync.RWMutex{},Lang: lang,- Sync: &conf.Sync{Provider: provider},+ Sync: NewConfSection(&conf.Sync{Provider: provider}),User: &conf.User{UserSiYuanRepoSize: 8 * 1000 * 1000 * 1000, UserSiYuanSubscriptionPlan: plan},}want := "Sync failed: " + html.EscapeString(repoErr.Error()) + " (Provider: " + conf.ProviderToStr(provider) + ")"diff --git a/kernel/model/repository_range.go b/kernel/model/repository_range.goindex 98f1118e06..9f8da02c05 100644--- a/kernel/model/repository_range.go+++ b/kernel/model/repository_range.go@@ -35,7 +35,7 @@ func GetRepoSnapshotsByTime(page int, startTime, endTime int64) (ret []*Snapshotreturn GetRepoSnapshots(page)}ret = []*Snapshot{}- if len(Conf.Repo.Key) == 0 {+ if len(Conf.Repo.Load().Key) == 0 {return ret, 0, 0, errors.New(Conf.Language(26))}repo, err := newRepository()diff --git a/kernel/model/repository_range_test.go b/kernel/model/repository_range_test.goindex 65964fbe87..3bb58ef153 100644--- a/kernel/model/repository_range_test.go+++ b/kernel/model/repository_range_test.go@@ -17,7 +17,7 @@ func TestRepoSnapshotTimeRange(t *testing.T) {if err != nil {t.Fatal(err)}- store, err := dejavu.NewStore(util.RepoDir, Conf.Repo.Key)+ store, err := dejavu.NewStore(util.RepoDir, Conf.Repo.Load().Key)if err != nil {t.Fatal(err)}diff --git a/kernel/model/repository_snapshot_test.go b/kernel/model/repository_snapshot_test.goindex 3954cba517..38d62ec672 100644--- a/kernel/model/repository_snapshot_test.go+++ b/kernel/model/repository_snapshot_test.go@@ -54,7 +54,7 @@ func TestSearchRepoSnapshot(t *testing.T) {t.Fatalf("invalid ID accepted: %q", id)}}- store, err := dejavu.NewStore(util.RepoDir, Conf.Repo.Key)+ store, err := dejavu.NewStore(util.RepoDir, Conf.Repo.Load().Key)if err != nil {t.Fatal(err)}diff --git a/kernel/model/rerank.go b/kernel/model/rerank.goindex 45cf19b332..f90808cd92 100644--- a/kernel/model/rerank.go+++ b/kernel/model/rerank.go@@ -23,48 +23,62 @@ const defaultRerankCandidateCount = 30// isRerankEnabled 判断重排是否可用:配置已开启且填了 APIKey。语义搜索在召回后会据此决定是否走重排。func isRerankEnabled() bool {- return !util.IsDisabledFeature("ai") && nil != Conf.AI.Rerank && Conf.AI.Rerank.Enabled && len(Conf.AI.Rerank.APIKey) > 0+ confAISnapshot := Conf.LoadAI()++ return !util.IsDisabledFeature("ai") && nil != confAISnapshot.Rerank && confAISnapshot.Rerank.Enabled && len(confAISnapshot.Rerank.APIKey) > 0}func rerankKey() string {- if nil != Conf.AI.Rerank && Conf.AI.Rerank.Enabled && "" != Conf.AI.Rerank.APIKey {- return Conf.AI.Rerank.APIKey+ confAISnapshot := Conf.LoadAI()++ if nil != confAISnapshot.Rerank && confAISnapshot.Rerank.Enabled && "" != confAISnapshot.Rerank.APIKey {+ return confAISnapshot.Rerank.APIKey}return ""}func rerankEndpoint() string {- if nil != Conf.AI.Rerank && Conf.AI.Rerank.Enabled && "" != Conf.AI.Rerank.Endpoint {- return Conf.AI.Rerank.Endpoint+ confAISnapshot := Conf.LoadAI()++ if nil != confAISnapshot.Rerank && confAISnapshot.Rerank.Enabled && "" != confAISnapshot.Rerank.Endpoint {+ return confAISnapshot.Rerank.Endpoint}return ""}func rerankModel() string {- if nil != Conf.AI.Rerank && Conf.AI.Rerank.Enabled && "" != Conf.AI.Rerank.Name {- return Conf.AI.Rerank.Name+ confAISnapshot := Conf.LoadAI()++ if nil != confAISnapshot.Rerank && confAISnapshot.Rerank.Enabled && "" != confAISnapshot.Rerank.Name {+ return confAISnapshot.Rerank.Name}return ""}func rerankRequestFormat() util.RerankRequestFormat {- if nil != Conf.AI.Rerank && Conf.AI.Rerank.Enabled {- return Conf.AI.Rerank.RequestFormat+ confAISnapshot := Conf.LoadAI()++ if nil != confAISnapshot.Rerank && confAISnapshot.Rerank.Enabled {+ return confAISnapshot.Rerank.RequestFormat}return util.RerankRequestFormatCohere}func rerankTimeout() int {- if nil != Conf.AI.Rerank && Conf.AI.Rerank.Enabled && 0 < Conf.AI.Rerank.Timeout {- return Conf.AI.Rerank.Timeout+ confAISnapshot := Conf.LoadAI()++ if nil != confAISnapshot.Rerank && confAISnapshot.Rerank.Enabled && 0 < confAISnapshot.Rerank.Timeout {+ return confAISnapshot.Rerank.Timeout}return 30}// rerankCandidateCount 返回向量召回后送入重排的候选文档数。Normalize 已保证落在 [5,100],这里做兜底。func rerankCandidateCount() int {- if nil != Conf.AI.Rerank && Conf.AI.Rerank.Enabled && 0 < Conf.AI.Rerank.CandidateCount {- return Conf.AI.Rerank.CandidateCount+ confAISnapshot := Conf.LoadAI()++ if nil != confAISnapshot.Rerank && confAISnapshot.Rerank.Enabled && 0 < confAISnapshot.Rerank.CandidateCount {+ return confAISnapshot.Rerank.CandidateCount}return defaultRerankCandidateCount}diff --git a/kernel/model/search.go b/kernel/model/search.goindex 2318533f46..c38604b020 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -336,11 +336,13 @@ func SearchEmbedBlockForPublish(embedBlockID, stmt string, excludeIDs []string,func searchEmbedBlockInBox(embedBlockID, stmt string, excludeIDs []string, headingMode int, breadcrumb bool, boxID string,updateIndex bool) (ret []*EmbedBlock) {+ confSearchSnapshot := Conf.LoadSearch()+var sqlBlocks []*sql.Blockif "" != boxID {- sqlBlocks = sql.SelectBlocksRawStmtNoParseInBox(stmt, Conf.Search.Limit, boxID)+ sqlBlocks = sql.SelectBlocksRawStmtNoParseInBox(stmt, confSearchSnapshot.Limit, boxID)} else {- sqlBlocks = sql.SelectBlocksRawStmtNoParse(stmt, Conf.Search.Limit)+ sqlBlocks = sql.SelectBlocksRawStmtNoParse(stmt, confSearchSnapshot.Limit)}ret = buildEmbedBlock(embedBlockID, excludeIDs, headingMode, breadcrumb, treenode.GetEmbedBlockRefID(stmt), sqlBlocks, updateIndex, boxID)return@@ -420,6 +422,8 @@ func SearchRefBlock(id, rootID, keyword string, beforeLen int, isSquareBrackets,// SearchRefBlockInBox 与 SearchRefBlock 一致,但按 boxID 路由到加密 db 或全局 db。// 加密笔记本内搜索块引目标时传入 boxID,只搜该 box 自己的加密 db,避免跨加密边界引用。func SearchRefBlockInBox(id, rootID, keyword string, beforeLen int, isSquareBrackets, isDatabase bool, boxID string) (ret []*Block, newDoc bool) {+ confEditorSnapshot := Conf.LoadEditor()+cachedTrees := map[string]*parse.Tree{}nodeTrees := map[string]*parse.Tree{}var nodeIDs []string@@ -427,13 +431,13 @@ func SearchRefBlockInBox(id, rootID, keyword string, beforeLen int, isSquareBraconlyDoc := falseif isSquareBrackets {- onlyDoc = Conf.Editor.OnlySearchForDoc+ onlyDoc = confEditorSnapshot.OnlySearchForDoc}if "" == keyword {// 查询为空时默认的块引排序规则按最近引用优先 https://github.com/siyuan-note/siyuan/issues/3218- typeFilter := Conf.Search.TypeFilter()+ typeFilter := Conf.Search.Load().TypeFilter()ignoreLines := getRefSearchIgnoreLines()refUsed := GetRefUsed()refs := sql.QueryRefsRecentInBox(onlyDoc, typeFilter, ignoreLines, sortedRefUsedIDs(refUsed), boxID)@@ -491,7 +495,7 @@ func SearchRefBlockInBox(id, rootID, keyword string, beforeLen int, isSquareBracblock := fromSQLBlock(sqlBlock, "", 0)block.RefText = getNodeRefText(node)- block.RefText = maxContent(block.RefText, Conf.Editor.BlockRefDynamicAnchorTextMaxLen)+ block.RefText = maxContent(block.RefText, confEditorSnapshot.BlockRefDynamicAnchorTextMaxLen)block.RefCount = refCount[node.ID]ret = append(ret, block)}@@ -1203,7 +1207,7 @@ func replaceEscapedTextMarkContent(content string, method int, keyword, replacem// replaceSearchText 的文本匹配遵循大小写设置并按字面量替换,正则模式保持捕获组展开语义。func replaceSearchText(input string, method int, keyword, replacement string, r *regexp.Regexp) (string, bool) {if method == 0 {- if !Conf.Search.CaseSensitive {+ if !Conf.Search.Load().CaseSensitive {return replaceCaseInsensitiveText(input, keyword, replacement)}if strings.Contains(input, keyword) {@@ -1223,7 +1227,7 @@ func replaceSearchTokens(input []byte, method int, keyword, replacement string,}func equalSearchText(input, keyword string) bool {- if Conf.Search.CaseSensitive {+ if Conf.Search.Load().CaseSensitive {return input == keyword}return strings.EqualFold(input, keyword)@@ -1371,7 +1375,7 @@ func findReplaceTextMatchIndexes(content string, method int, keyword string, r *}exp := regexp.QuoteMeta(keyword)- if !Conf.Search.CaseSensitive {+ if !Conf.Search.Load().CaseSensitive {exp = "(?i:" + exp + ")"}matcher, err := regexp.Compile(exp)@@ -2071,7 +2075,7 @@ func buildOrderBy(query string, method, orderBy int) string {func buildExactSearchOrderCondition(field, query string) string {escapedQuery := strings.ReplaceAll(query, "'", "''")- if Conf.Search.CaseSensitive {+ if Conf.Search.Load().CaseSensitive {return field + " = '" + escapedQuery + "'"}escapedQuery = conf.EscapeSearchLikePattern(query)@@ -2084,7 +2088,7 @@ func buildExactAliasSearchOrderCondition(field, query string) string {}escapedQuery := strings.ReplaceAll(query, "'", "''")- if Conf.Search.CaseSensitive {+ if Conf.Search.Load().CaseSensitive {return "instr(',' || " + field + " || ',', '," + escapedQuery + ",') > 0"}escapedQuery = conf.EscapeSearchLikePattern(query)@@ -2093,12 +2097,14 @@ func buildExactAliasSearchOrderCondition(field, query string) string {// buildTypeFilter 按父类型独立限制子类型,组内为空时仅按父类型筛选。func buildTypeFilter(types, subTypes map[string]bool, alias ...string) string {+ confSearchSnapshot := Conf.LoadSearch()+prefix := ""if 0 < len(alias) && "" != alias[0] {prefix = alias[0]}s := conf.NewSearch()- if err := copier.Copy(s, Conf.Search); err != nil {+ if err := copier.Copy(s, confSearchSnapshot); err != nil {logging.LogErrorf("copy search conf failed: %s", err)}if nil != types {@@ -2126,26 +2132,26 @@ func buildTypeFilter(types, subTypes map[string]bool, alias ...string) string {s.TabItem = types["tabItem"]s.CustomBlock = new(types["customBlock"])} else {- s.Document = Conf.Search.Document- s.Heading = Conf.Search.Heading- s.List = Conf.Search.List- s.ListItem = Conf.Search.ListItem- s.CodeBlock = Conf.Search.CodeBlock- s.MathBlock = Conf.Search.MathBlock- s.Table = Conf.Search.Table- s.Blockquote = Conf.Search.Blockquote- s.SuperBlock = Conf.Search.SuperBlock- s.Paragraph = Conf.Search.Paragraph- s.HTMLBlock = Conf.Search.HTMLBlock- s.EmbedBlock = Conf.Search.EmbedBlock- s.DatabaseBlock = Conf.Search.DatabaseBlock- s.AudioBlock = Conf.Search.AudioBlock- s.VideoBlock = Conf.Search.VideoBlock- s.IFrameBlock = Conf.Search.IFrameBlock- s.WidgetBlock = Conf.Search.WidgetBlock- s.Callout = Conf.Search.Callout- s.Tabs = Conf.Search.Tabs- s.TabItem = Conf.Search.TabItem+ s.Document = confSearchSnapshot.Document+ s.Heading = confSearchSnapshot.Heading+ s.List = confSearchSnapshot.List+ s.ListItem = confSearchSnapshot.ListItem+ s.CodeBlock = confSearchSnapshot.CodeBlock+ s.MathBlock = confSearchSnapshot.MathBlock+ s.Table = confSearchSnapshot.Table+ s.Blockquote = confSearchSnapshot.Blockquote+ s.SuperBlock = confSearchSnapshot.SuperBlock+ s.Paragraph = confSearchSnapshot.Paragraph+ s.HTMLBlock = confSearchSnapshot.HTMLBlock+ s.EmbedBlock = confSearchSnapshot.EmbedBlock+ s.DatabaseBlock = confSearchSnapshot.DatabaseBlock+ s.AudioBlock = confSearchSnapshot.AudioBlock+ s.VideoBlock = confSearchSnapshot.VideoBlock+ s.IFrameBlock = confSearchSnapshot.IFrameBlock+ s.WidgetBlock = confSearchSnapshot.WidgetBlock+ s.Callout = confSearchSnapshot.Callout+ s.Tabs = confSearchSnapshot.Tabs+ s.TabItem = confSearchSnapshot.TabItem}var simpleTypes []string@@ -2222,7 +2228,7 @@ func isDocumentSearchEnabled(types map[string]bool) bool {if nil != types {return types["document"]}- return Conf.Search.Document+ return Conf.Search.Load().Document}func sqlQuoteJoin(items []string) string {@@ -2322,6 +2328,8 @@ func removeLimitClause(stmt string) string {// fullTextSearchRefBlockInBox 在指定笔记本内搜索可引用块,空 boxID 使用全局数据库。func fullTextSearchRefBlockInBox(keyword string, beforeLen int, onlyDoc bool, boxID string) (ret []*Block) {+ confSearchSnapshot := Conf.LoadSearch()+keyword = filterQueryInvisibleChars(keyword)if id := extractID(keyword); "" != id {@@ -2344,7 +2352,7 @@ func fullTextSearchRefBlockInBox(keyword string, beforeLen int, onlyDoc bool, boif onlyDoc {stmt += " = 'd'"} else {- stmt += " IN " + Conf.Search.TypeFilter()+ stmt += " IN " + confSearchSnapshot.TypeFilter()}if ignoreLines := getRefSearchIgnoreLines(); 0 < len(ignoreLines) {@@ -2373,8 +2381,8 @@ func fullTextSearchRefBlockInBox(keyword string, beforeLen int, onlyDoc bool, boWHEN content LIKE '%${keyword}%' and type != 'i' and type != 'l' THEN 100ELSE 65535 END ASC, sort ASC, length ASC`orderBy = strings.ReplaceAll(orderBy, "${keyword}", strings.ReplaceAll(keyword, "'", "''"))- stmt += orderBy + " LIMIT " + strconv.Itoa(Conf.Search.Limit)- blocks := sql.SelectBlocksRawStmtNoParseInBox(stmt, Conf.Search.Limit, boxID)+ stmt += orderBy + " LIMIT " + strconv.Itoa(confSearchSnapshot.Limit)+ blocks := sql.SelectBlocksRawStmtNoParseInBox(stmt, confSearchSnapshot.Limit, boxID)ret = fromSQLBlocks(&blocks, "", beforeLen)if 1 > len(ret) {ret = []*Block{}@@ -2446,6 +2454,8 @@ func extractID(content string) (ret string) {}func fullTextSearchByRegexpInBox(exp, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int, boxID string) (ret []*Block, matchedBlockCount, matchedRootCount int) {+ confSearchSnapshot := Conf.LoadSearch()+fieldFilter := fieldRegexp(exp)stmt := "SELECT * FROM `blocks` WHERE " + fieldFilter + " AND " + typeFilterstmt += boxFilter + pathFilter + ignoreFilter + " " + orderBy@@ -2457,7 +2467,7 @@ func fullTextSearchByRegexpInBox(exp, boxFilter, pathFilter string, boxArgs, pat// box/path 过滤值通过绑定参数传递,避免 SQL 拼接注入args := append(append([]any{}, boxArgs...), pathArgs...)- blocks := sql.SelectBlocksRegexArgsInBox(stmt, regex, Conf.Search.Name, Conf.Search.Alias, Conf.Search.Memo, Conf.Search.IAL, page, pageSize, boxID, args...)+ blocks := sql.SelectBlocksRegexArgsInBox(stmt, regex, confSearchSnapshot.Name, confSearchSnapshot.Alias, confSearchSnapshot.Memo, confSearchSnapshot.IAL, page, pageSize, boxID, args...)ret = fromSQLBlocks(&blocks, "", beforeLen)if 1 > len(ret) {ret = []*Block{}@@ -2687,20 +2697,24 @@ func buildFTSAndHPathMatchesCTE(rawQuery, query, boxFilter, pathFilter string, b}func buildHPathContainsCondition(query string) (condition, arg string) {- if Conf.Search.CaseSensitive && Conf.Search.HanSensitiveVal() {+ confSearchSnapshot := Conf.LoadSearch()++ if confSearchSnapshot.CaseSensitive && confSearchSnapshot.HanSensitiveVal() {return "instr(hpath, ?) > 0", query}caseSensitive, hanSensitive := searchNormalizationFlags()condition = "instr(search_normalize(hpath, " + strconv.Itoa(caseSensitive) + ", " + strconv.Itoa(hanSensitive) + "), ?) > 0"- arg = search.NormalizeSearchText(query, Conf.Search.CaseSensitive, Conf.Search.HanSensitiveVal())+ arg = search.NormalizeSearchText(query, confSearchSnapshot.CaseSensitive, confSearchSnapshot.HanSensitiveVal())return}func searchNormalizationFlags() (caseSensitive, hanSensitive int) {- if Conf.Search.CaseSensitive {+ confSearchSnapshot := Conf.LoadSearch()++ if confSearchSnapshot.CaseSensitive {caseSensitive = 1}- if Conf.Search.HanSensitiveVal() {+ if confSearchSnapshot.HanSensitiveVal() {hanSensitive = 1}return@@ -2910,9 +2924,11 @@ func buildSearchDocumentLikeFilter(field string, keywords []string) string {}func buildSearchDocumentLikeFilterWithHPath(contentField, hPathField string, keywords []string) string {+ confSearchSnapshot := Conf.LoadSearch()+var ret strings.Builderfor i, keyword := range keywords {- normalizedKeyword := search.NormalizeSearchText(keyword, Conf.Search.CaseSensitive, Conf.Search.HanSensitiveVal())+ normalizedKeyword := search.NormalizeSearchText(keyword, confSearchSnapshot.CaseSensitive, confSearchSnapshot.HanSensitiveVal())ret.WriteString("(")ret.WriteString(contentField)ret.WriteString(" LIKE '%")@@ -2986,6 +3002,8 @@ func highlightByFTSInBox(query, typeFilter, id, boxID string) (ret []string) {// highlightByRegexpInBox 按 boxID 选择加密或全局数据库,获取正则检索高亮片段。func highlightByRegexpInBox(query, typeFilter, id, boxID string) (ret []string) {+ confSearchSnapshot := Conf.LoadSearch()+fieldFilter := fieldRegexp(query)stmt := "SELECT * FROM `blocks` WHERE " + fieldFilter + " AND " + typeFilterstmt += " AND root_id = '" + id + "'"@@ -2993,7 +3011,7 @@ func highlightByRegexpInBox(query, typeFilter, id, boxID string) (ret []string)if nil == regex {return}- sqlBlocks := sql.SelectBlocksRegexInBox(stmt, regex, Conf.Search.Name, Conf.Search.Alias, Conf.Search.Memo, Conf.Search.IAL, 1, 256, boxID)+ sqlBlocks := sql.SelectBlocksRegexInBox(stmt, regex, confSearchSnapshot.Name, confSearchSnapshot.Alias, confSearchSnapshot.Memo, confSearchSnapshot.IAL, 1, 256, boxID)for _, block := range sqlBlocks {keyword := gulu.Str.SubstringsBetween(block.HPath, search.SearchMarkLeft, search.SearchMarkRight)if 0 < len(keyword) {@@ -3025,6 +3043,8 @@ func highlightByRegexpInBox(query, typeFilter, id, boxID string) (ret []string)}func markSearch(text string, keyword string, beforeLen int) (marked string, score float64) {+ confSearchSnapshot := Conf.LoadSearch()+if 0 == len(keyword) {if strings.Contains(text, search.SearchMarkLeft) { // 使用 FTS snippet() 处理过高亮片段,这里简单替换后就返回marked = util.EscapeHTML(text)@@ -3038,12 +3058,12 @@ func markSearch(text string, keyword string, beforeLen int) (marked string, scorkeyword = strings.Join(keywords, search.TermSep)marked = strings.ReplaceAll(text, search.SearchMarkLeft, "")marked = strings.ReplaceAll(marked, search.SearchMarkRight, "")- _, marked = search.MarkText(marked, keyword, beforeLen, Conf.Search.CaseSensitive)+ _, marked = search.MarkText(marked, keyword, beforeLen, confSearchSnapshot.CaseSensitive)marked = util.EscapeHTML(marked)return}- pos, marked := search.MarkText(text, keyword, beforeLen, Conf.Search.CaseSensitive)+ pos, marked := search.MarkText(text, keyword, beforeLen, confSearchSnapshot.CaseSensitive)if -1 < pos {if 0 == pos {score = 1@@ -3059,7 +3079,7 @@ func markSearch(text string, keyword string, beforeLen int) (marked string, scorfunc partitionSearchTerms(text, terms string) (matched, unmatched string) {var matchedTerms, unmatchedTerms []stringfor _, term := range search.SplitKeyword(terms) {- pos, _ := search.MarkText(text, term, -1, Conf.Search.CaseSensitive)+ pos, _ := search.MarkText(text, term, -1, Conf.Search.Load().CaseSensitive)if -1 < pos {matchedTerms = append(matchedTerms, term)} else {@@ -3186,28 +3206,30 @@ func maxContent(content string, maxLen int) string {}func fieldRegexp(regexp string) string {+ confSearchSnapshot := Conf.LoadSearch()+regexp = strings.ReplaceAll(regexp, "'", "''") // 不需要转义双引号,因为条件都是通过单引号包裹的,只需要转义单引号即可buf := bytes.Buffer{}buf.WriteString("(")buf.WriteString("content REGEXP '")buf.WriteString(regexp)buf.WriteString("'")- if Conf.Search.Name {+ if confSearchSnapshot.Name {buf.WriteString(" OR name REGEXP '")buf.WriteString(regexp)buf.WriteString("'")}- if Conf.Search.Alias {+ if confSearchSnapshot.Alias {buf.WriteString(" OR alias REGEXP '")buf.WriteString(regexp)buf.WriteString("'")}- if Conf.Search.Memo {+ if confSearchSnapshot.Memo {buf.WriteString(" OR memo REGEXP '")buf.WriteString(regexp)buf.WriteString("'")}- if Conf.Search.IAL {+ if confSearchSnapshot.IAL {buf.WriteString(" OR ial REGEXP '")buf.WriteString(regexp)buf.WriteString("'")@@ -3219,18 +3241,20 @@ func fieldRegexp(regexp string) string {}func columnFilter() string {+ confSearchSnapshot := Conf.LoadSearch()+buf := bytes.Buffer{}buf.WriteString("{content")- if Conf.Search.Name {+ if confSearchSnapshot.Name {buf.WriteString(" name")}- if Conf.Search.Alias {+ if confSearchSnapshot.Alias {buf.WriteString(" alias")}- if Conf.Search.Memo {+ if confSearchSnapshot.Memo {buf.WriteString(" memo")}- if Conf.Search.IAL {+ if confSearchSnapshot.IAL {buf.WriteString(" ial")}buf.WriteString(" tag}")@@ -3238,18 +3262,20 @@ func columnFilter() string {}func columnConcat() string {+ confSearchSnapshot := Conf.LoadSearch()+buf := bytes.Buffer{}buf.WriteString("content")- if Conf.Search.Name {+ if confSearchSnapshot.Name {buf.WriteString("||name")}- if Conf.Search.Alias {+ if confSearchSnapshot.Alias {buf.WriteString("||alias")}- if Conf.Search.Memo {+ if confSearchSnapshot.Memo {buf.WriteString("||memo")}- if Conf.Search.IAL {+ if confSearchSnapshot.IAL {buf.WriteString("||ial")}buf.WriteString("||tag")@@ -3285,9 +3311,11 @@ func stringQuery(query string) string {// markReplaceSpan 用于处理搜索高亮。func markReplaceSpan(n *ast.Node, unlinks *[]*ast.Node, keywords []string, markSpanDataType string, luteEngine *lute.Lute) bool {+ confSearchSnapshot := Conf.LoadSearch()+if ast.NodeText == n.Type {text := n.Content()- text, matched := search.EncloseHighlightingRaw(text, keywords, search.GetMarkSpanStart(markSpanDataType), search.GetMarkSpanEnd(), Conf.Search.CaseSensitive, false)+ text, matched := search.EncloseHighlightingRaw(text, keywords, search.GetMarkSpanStart(markSpanDataType), search.GetMarkSpanEnd(), confSearchSnapshot.CaseSensitive, false)if !matched {return false}@@ -3313,7 +3341,7 @@ func markReplaceSpan(n *ast.Node, unlinks *[]*ast.Node, keywords []string, markStext := n.Content()startTag := search.GetMarkSpanStart(markSpanDataType)- text, matched := search.EncloseHighlightingRaw(text, keywords, startTag, search.GetMarkSpanEnd(), Conf.Search.CaseSensitive, false)+ text, matched := search.EncloseHighlightingRaw(text, keywords, startTag, search.GetMarkSpanEnd(), confSearchSnapshot.CaseSensitive, false)if matched {dataType := search.GetMarkSpanStart(n.TextMarkType + " " + search.MarkDataType)text = strings.ReplaceAll(text, startTag, dataType)@@ -3366,7 +3394,7 @@ func markReplaceSpanWithSplit(text string, keywords []string, replacementStart,// 虚拟引用和反链提及关键字按最长匹配优先 https://github.com/siyuan-note/siyuan/issues/7465sort.Slice(keywords, func(i, j int) bool { return len(keywords[i]) > len(keywords[j]) })- tmp, matched := search.EncloseHighlightingRaw(text, keywords, replacementStart, replacementEnd, Conf.Search.CaseSensitive, true)+ tmp, matched := search.EncloseHighlightingRaw(text, keywords, replacementStart, replacementEnd, Conf.Search.Load().CaseSensitive, true)if !matched {ret = tmpreturndiff --git a/kernel/model/search_case_replace_fts5_test.go b/kernel/model/search_case_replace_fts5_test.goindex cf3ebb9815..03fad7385c 100644--- a/kernel/model/search_case_replace_fts5_test.go+++ b/kernel/model/search_case_replace_fts5_test.go@@ -38,8 +38,8 @@ func TestFindReplaceCaseSensitivityAcrossTypes(t *testing.T) {t.Run(tc.name, func(t *testing.T) {fixture := setupStructureTransactionTest(t)setupFoldTransactionDatabase(t, fixture)- Conf.Search = conf.NewSearch()- Conf.Search.CaseSensitive = tc.caseSensitive+ Conf.Search.Store(conf.NewSearch())+ Conf.Search.Load().CaseSensitive = tc.caseSensitivetree, err := LoadTreeByBlockID(fixture.sourceID)if err != nil {t.Fatal(err)diff --git a/kernel/model/search_custom_test.go b/kernel/model/search_custom_test.goindex 555d71dcd0..5a8549fcae 100644--- a/kernel/model/search_custom_test.go+++ b/kernel/model/search_custom_test.go@@ -11,7 +11,7 @@ import (func TestCustomBlockSearchTypeFilter(t *testing.T) {previous := ConfConf = NewAppConf()- Conf.Search = conf.NewSearch()+ Conf.Search.Store(conf.NewSearch())t.Cleanup(func() { Conf = previous })for _, tc := range []struct {types map[string]bool@@ -21,7 +21,7 @@ func TestCustomBlockSearchTypeFilter(t *testing.T) {t.Fatalf("unexpected filter for %v: %s", tc.types, got)}}- Conf.Search.CustomBlock = new(false)+ Conf.Search.Load().CustomBlock = new(false)if strings.Contains(buildTypeFilter(nil, nil), "'custom'") {t.Fatal("disabled custom blocks included")}diff --git a/kernel/model/search_document_test.go b/kernel/model/search_document_test.goindex c1367f18f2..3375e3edad 100644--- a/kernel/model/search_document_test.go+++ b/kernel/model/search_document_test.go@@ -12,11 +12,11 @@ import (func TestDocumentTypeFilterFromSettings(t *testing.T) {setSearchCaseSensitive(t, false)- Conf.Search = &conf.Search{Document: true, Mindmap: new(false), MindmapItem: new(false), CustomBlock: new(false)}+ Conf.Search.Store(&conf.Search{Document: true, Mindmap: new(false), MindmapItem: new(false), CustomBlock: new(false)})if got := buildTypeFilter(nil, nil); got != "(type = 'd')" {t.Fatalf("document-only settings: %s", got)}- Conf.Search.Paragraph = true+ Conf.Search.Load().Paragraph = trueif got := buildTypeFilter(nil, nil); got != "(type IN ('d','p'))" {t.Fatalf("mixed settings: %s", got)}diff --git a/kernel/model/search_highlight_test.go b/kernel/model/search_highlight_test.goindex f634a2b164..5ac9b68e1c 100644--- a/kernel/model/search_highlight_test.go+++ b/kernel/model/search_highlight_test.go@@ -29,7 +29,7 @@ import (func TestMarkReplaceSpanMatchesRawText(t *testing.T) {previousConf := ConfConf = NewAppConf()- Conf.Search = conf.NewSearch()+ Conf.Search.Store(conf.NewSearch())t.Cleanup(func() {Conf = previousConf})@@ -114,7 +114,7 @@ func TestMarkReplaceSpanMatchesRawText(t *testing.T) {func TestExtractedMarkContentsMatchRawText(t *testing.T) {previousConf := ConfConf = NewAppConf()- Conf.Search = conf.NewSearch()+ Conf.Search.Store(conf.NewSearch())t.Cleanup(func() {Conf = previousConf})diff --git a/kernel/model/search_mindmap_fts5_test.go b/kernel/model/search_mindmap_fts5_test.goindex 55e8992380..68e6da2c88 100644--- a/kernel/model/search_mindmap_fts5_test.go+++ b/kernel/model/search_mindmap_fts5_test.go@@ -68,12 +68,12 @@ func TestMindmapSearchFTS(t *testing.T) {check(buildTypeFilter(tc.types, nil), tc.want)}// 引用和嵌入候选搜索共用全局类型过滤。- Conf.Search.Mindmap = new(true)- Conf.Search.MindmapItem = new(false)- check("type IN "+Conf.Search.TypeFilter(), 2)- Conf.Search.Mindmap = new(false)- Conf.Search.MindmapItem = new(true)- check("type IN "+Conf.Search.TypeFilter(), 2)- Conf.Search.MindmapItem = new(false)- check("type IN "+Conf.Search.TypeFilter(), 1)+ Conf.Search.Load().Mindmap = new(true)+ Conf.Search.Load().MindmapItem = new(false)+ check("type IN "+Conf.Search.Load().TypeFilter(), 2)+ Conf.Search.Load().Mindmap = new(false)+ Conf.Search.Load().MindmapItem = new(true)+ check("type IN "+Conf.Search.Load().TypeFilter(), 2)+ Conf.Search.Load().MindmapItem = new(false)+ check("type IN "+Conf.Search.Load().TypeFilter(), 1)}diff --git a/kernel/model/search_mindmap_test.go b/kernel/model/search_mindmap_test.goindex 376e3bf85a..dc351e87a1 100644--- a/kernel/model/search_mindmap_test.go+++ b/kernel/model/search_mindmap_test.go@@ -11,7 +11,7 @@ import (func TestMindmapSearchTypeFilter(t *testing.T) {previous := ConfConf = NewAppConf()- Conf.Search = conf.NewSearch()+ Conf.Search.Store(conf.NewSearch())t.Cleanup(func() { Conf = previous })for _, tc := range []struct {types map[string]bool@@ -29,8 +29,8 @@ func TestMindmapSearchTypeFilter(t *testing.T) {t.Fatalf("unexpected filter for %v: %s", tc.types, filter)}}- Conf.Search.Mindmap = new(false)- Conf.Search.MindmapItem = new(true)+ Conf.Search.Load().Mindmap = new(false)+ Conf.Search.Load().MindmapItem = new(true)if filter := buildTypeFilter(nil, nil); strings.Contains(filter, "'mindmap'") || !strings.Contains(filter, "'mindmap_item'") {t.Fatalf("global choices ignored: %s", filter)}diff --git a/kernel/model/search_sql_comments_test.go b/kernel/model/search_sql_comments_test.goindex d244aef0d6..736b15cab8 100644--- a/kernel/model/search_sql_comments_test.go+++ b/kernel/model/search_sql_comments_test.go@@ -30,7 +30,11 @@ func TestSQLSearchPreservesCommentsAndLiteralCase(t *testing.T) {util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")Conf = NewAppConf()- Conf.Search, Conf.FileTree = conf.NewSearch(), conf.NewFileTree()+ {+ confSectionValue0, confSectionValue1 := conf.NewSearch(), conf.NewFileTree()+ Conf.Search.Store(confSectionValue0)+ Conf.FileTree.Store(confSectionValue1)+ }sql.InitDatabase(true)sql.InitHistoryDatabase(true)sql.InitAssetContentDatabase(true)diff --git a/kernel/model/search_test.go b/kernel/model/search_test.goindex 79d481e7a7..d45d4ce706 100644--- a/kernel/model/search_test.go+++ b/kernel/model/search_test.go@@ -33,7 +33,7 @@ import (func TestFromSQLBlockMapsTimestamps(t *testing.T) {previousConf := ConfConf = NewAppConf()- Conf.Search = conf.NewSearch()+ Conf.Search.Store(conf.NewSearch())t.Cleanup(func() {Conf = previousConf})@@ -340,7 +340,7 @@ func TestBuildExactSearchOrderConditionEscapesKeyword(t *testing.T) {t.Fatalf("区分大小写的完全命中条件错误:got %q, want %q", condition, expected)}- Conf.Search.CaseSensitive = false+ Conf.Search.Load().CaseSensitive = falsecondition = buildExactSearchOrderCondition("content", "O'Reilly%_\\")if expected := "content LIKE 'O''Reilly\\%\\_\\\\' ESCAPE '\\'"; expected != condition {t.Fatalf("忽略大小写的完全命中条件错误:got %q, want %q", condition, expected)@@ -477,13 +477,13 @@ func TestBuildHPathContainsCondition(t *testing.T) {t.Fatalf("区分大小写的路径条件错误:%q,%q", condition, arg)}- Conf.Search.CaseSensitive = false+ Conf.Search.Load().CaseSensitive = falsecondition, arg = buildHPathContainsCondition("Parent%_\\")if "instr(search_normalize(hpath, 0, 1), ?) > 0" != condition || "parent%_\\" != arg {t.Fatalf("忽略大小写的路径条件错误:%q,%q", condition, arg)}- Conf.Search.SetHanSensitive(false)+ Conf.Search.Load().SetHanSensitive(false)condition, arg = buildHPathContainsCondition("詩經")if "instr(search_normalize(hpath, 0, 0), ?) > 0" != condition || "诗经" != arg {t.Fatalf("忽略繁简的路径条件错误:%q,%q", condition, arg)@@ -832,7 +832,7 @@ func TestDocumentSearchFieldMatchesMultipleHPathLevels(t *testing.T) {t.Fatalf("关闭路径搜索后只能命中正文文档:%d", count)}- Conf.Search.SetHanSensitive(false)+ Conf.Search.Load().SetHanSensitive(false)insertSearchHPathTestBlock(t, testDB, "20260729121004-child02", "20260729121004-child02", "/詩經/Child", "Child", "d")hPathField = "MAX(CASE WHEN type = 'd' THEN " + normalizedHPathSearchField("hpath") + " ELSE '' END)"filter = buildSearchDocumentLikeFilterWithHPath("GROUP_CONCAT("+contentField+")", hPathField, []string{"诗经", "Child"})@@ -873,8 +873,8 @@ func setSearchCaseSensitive(t *testing.T, caseSensitive bool) {t.Helper()previousConf := ConfConf = NewAppConf()- Conf.Search = conf.NewSearch()- Conf.Search.CaseSensitive = caseSensitive+ Conf.Search.Store(conf.NewSearch())+ Conf.Search.Load().CaseSensitive = caseSensitivet.Cleanup(func() {Conf = previousConf})diff --git a/kernel/model/session.go b/kernel/model/session.goindex 000de9b8c7..e5a78a2acc 100644--- a/kernel/model/session.go+++ b/kernel/model/session.go@@ -421,7 +421,7 @@ func authByAPIToken(c *gin.Context, source, token string) (handled bool) {c.Abort()return true}- if util.AuthCodeEquals(Conf.Api.Token, token) {+ if util.AuthCodeEquals(Conf.Api.Load().Token, token) {util.AuthThrottleReset(ip)c.Set(RoleContextKey, RoleAdministrator)c.Next()diff --git a/kernel/model/session_test.go b/kernel/model/session_test.goindex 8199e8e953..325aa62f76 100644--- a/kernel/model/session_test.go+++ b/kernel/model/session_test.go@@ -33,9 +33,9 @@ import (func TestAuthByAPITokenThrottle(t *testing.T) {originalConf := ConfConf = NewAppConf()- Conf.Api = conf.NewAPI()+ Conf.Api.Store(conf.NewAPI())t.Cleanup(func() { Conf = originalConf })- Conf.Api.Token = "test-api-token-123"+ Conf.Api.Load().Token = "test-api-token-123"engine := gin.New()engine.GET("/api/test", CheckAuth, func(c *gin.Context) {diff --git a/kernel/model/settings_reset.go b/kernel/model/settings_reset.goindex ae76ae90f6..60686c1ef4 100644--- a/kernel/model/settings_reset.go+++ b/kernel/model/settings_reset.go@@ -10,7 +10,6 @@ import ("github.com/88250/gulu""github.com/siyuan-note/filelock""github.com/siyuan-note/siyuan/kernel/conf"- "github.com/siyuan-note/siyuan/kernel/sql""github.com/siyuan-note/siyuan/kernel/task""github.com/siyuan-note/siyuan/kernel/util")@@ -24,53 +23,62 @@ var resetSettingsStorageKeys = []string{}func defaultWorkspaceSettings(current *AppConf) *AppConf {- next := *current- next.Editor = conf.NewEditor()- next.Editor.Markdown = util.NewMarkdown()- if current.Editor != nil {- next.Editor.HistoryRetentionDays = current.Editor.HistoryRetentionDays- next.Editor.Emoji = current.Editor.Emoji- }- next.FileTree = conf.NewFileTree()- next.FileTree.UseSingleLineSave = util.DefaultUseSingleLineSave- next.FileTree.LargeFileWarningSize = util.DefaultLargeFileWarningSize- next.FileTree.RecentDocsMaxListCount = conf.MinFileTreeRecentDocsListCount- next.Tag = conf.NewTag()- next.Export = conf.NewExport()- next.Search = conf.NewSearch()- next.Graph = conf.NewGraph()- next.Flashcard = conf.NewFlashcard()- next.OCR = conf.NewOCR()- next.Appearance = conf.NewAppearance()- next.Appearance.Lang = current.Lang- if current.Appearance != nil {- next.Appearance.Mode = current.Appearance.Mode- next.Appearance.DarkThemes = current.Appearance.DarkThemes- next.Appearance.LightThemes = current.Appearance.LightThemes- next.Appearance.Icons = current.Appearance.Icons- }- next.UILayout = &conf.UILayout{}+ next := current.cloneSettings()+ next.Editor.Store(conf.NewEditor())+ next.Editor.Load().Markdown = util.NewMarkdown()+ if current.Editor.Load() != nil {+ next.Editor.Load().HistoryRetentionDays = current.Editor.Load().HistoryRetentionDays+ next.Editor.Load().Emoji = current.Editor.Load().Emoji+ }+ next.FileTree.Store(conf.NewFileTree())+ next.FileTree.Load().RecentDocsMaxListCount = conf.MinFileTreeRecentDocsListCount+ next.Tag.Store(conf.NewTag())+ next.Export.Store(conf.NewExport())+ next.Search.Store(conf.NewSearch())+ next.Graph.Store(conf.NewGraph())+ next.Flashcard.Store(conf.NewFlashcard())+ next.OCR.Store(conf.NewOCR())+ next.Appearance.Store(conf.NewAppearanceForContainer(util.IsMobileContainer()))+ next.Appearance.Load().Lang = current.Lang+ if current.Appearance.Load() != nil {+ next.Appearance.Load().Mode = current.Appearance.Load().Mode+ next.Appearance.Load().DarkThemes = current.Appearance.Load().DarkThemes+ next.Appearance.Load().LightThemes = current.Appearance.Load().LightThemes+ next.Appearance.Load().Icons = current.Appearance.Load().Icons+ }+ next.UILayout.Store(&conf.UILayout{})keymap := conf.Keymap{}- if current.Keymap != nil {+ if current.Keymap.Load() != nil {// 内置快捷键在前端启动时按平台补全,插件快捷键完整保留。- for key, value := range *current.Keymap {+ for key, value := range *current.Keymap.Load() {if key != "general" && key != "editor" {keymap[key] = value}}}- next.Keymap = &keymap- if current.System != nil {- system := *current.System+ next.Keymap.Store(&keymap)+ if current.System.Load() != nil {+ system := *current.System.Load()system.DownloadInstallPkg = conf.NewSystem().DownloadInstallPkgsystem.SettingsWindow = false- next.System = &system+ next.System.Store(&system)}- next.Editor = conf.NormalizeEditor(next.Editor)- next.Export = conf.NormalizeExport(next.Export)- next.FileTree = conf.NormalizeFileTree(next.FileTree)- next.Search = conf.NormalizeSearch(next.Search)- next.Flashcard, _ = conf.NormalizeFlashcard(next.Flashcard)+ // 仅规范化被重置的配置段,未重置的配置段与当前内存配置共享,保持原样。+ next.Appearance.Store(conf.NormalizeAppearance(next.Appearance.Load(), util.IsMobileContainer()))+ next.UILayout.Store(conf.NormalizeUILayout(next.UILayout.Load()))+ next.Keymap.Store(conf.NormalizeKeymap(next.Keymap.Load()))+ next.Editor.Store(conf.NormalizeEditor(next.Editor.Load()))+ next.Export.Store(conf.NormalizeExport(next.Export.Load()))+ next.FileTree.Store(conf.NormalizeFileTree(next.FileTree.Load()))+ next.Tag.Store(conf.NormalizeTag(next.Tag.Load()))+ next.Search.Store(conf.NormalizeSearch(next.Search.Load()))+ next.Graph.Store(conf.NormalizeGraph(next.Graph.Load()))+ {+ confSectionValue0, confSectionValue1 := conf.NormalizeFlashcard(next.Flashcard.Load())+ next.Flashcard.Store(confSectionValue0)+ _ = confSectionValue1+ }+ next.OCR.Store(conf.NormalizeOCR(next.OCR.Load()))return &next}@@ -118,36 +126,54 @@ func ResetSettings() error {if err = writeSettingsReset([][]byte{config, local, boot}, filelock.WriteFile); err != nil {return err}- Conf.Editor, Conf.FileTree, Conf.Tag = next.Editor, next.FileTree, next.Tag- Conf.Export, Conf.Search, Conf.Graph = next.Export, next.Search, next.Graph- Conf.Flashcard, Conf.OCR, Conf.Appearance = next.Flashcard, next.OCR, next.Appearance- Conf.UILayout, Conf.Keymap = next.UILayout, next.Keymap- if Conf.System != nil {- Conf.System.DownloadInstallPkg = next.System.DownloadInstallPkg- Conf.System.SettingsWindow = next.System.SettingsWindow+ recordPersistedConf(config)+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := next.Editor.Load(), next.FileTree.Load(), next.Tag.Load()+ Conf.Editor.Store(confSectionValue0)+ Conf.FileTree.Store(confSectionValue1)+ Conf.Tag.Store(confSectionValue2)+ }+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := next.Export.Load(), next.Search.Load(), next.Graph.Load()+ Conf.Export.Store(confSectionValue0)+ Conf.Search.Store(confSectionValue1)+ Conf.Graph.Store(confSectionValue2)+ }+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := next.Flashcard.Load(), next.OCR.Load(), next.Appearance.Load()+ Conf.Flashcard.Store(confSectionValue0)+ Conf.OCR.Store(confSectionValue1)+ Conf.Appearance.Store(confSectionValue2)+ }+ {+ confSectionValue0, confSectionValue1 := next.UILayout.Load(), next.Keymap.Load()+ Conf.UILayout.Store(confSectionValue0)+ Conf.Keymap.Store(confSectionValue1)+ }+ if Conf.System.Load() != nil {+ replaceConfSectionLocked(&Conf.System, func(system *conf.System) bool {+ system.DownloadInstallPkg = next.System.Load().DownloadInstallPkg+ system.SettingsWindow = next.System.Load().SettingsWindow+ return true+ })}return nil}// ApplyResetSettings 更新运行时依赖,索引按现有队列重建,不修改笔记本密钥或历史保留策略。func ApplyResetSettings(previousSearch *conf.Search) {- util.MarkdownSettings = Conf.Editor.Markdown- util.UseSingleLineSave = Conf.FileTree.UseSingleLineSave- util.LargeFileWarningSize = Conf.FileTree.LargeFileWarningSize- util.StatusBarCfg = Conf.Appearance.StatusBar- util.NotificationsCfg = Conf.Appearance.Notifications- ChangeHistoryTick(Conf.Editor.GenerateHistoryInterval)+ confSearchSnapshot := Conf.LoadSearch()++ applyConfRuntime()+ ChangeHistoryTick(Conf.Editor.Load().GenerateHistoryInterval)ResetVirtualBlockRefCache()RefreshBoxDocFeature()refreshAppearanceConfig()WatchThemes()- sql.SetCaseSensitive(Conf.Search.CaseSensitive)- sql.SetHanSensitive(Conf.Search.HanSensitiveVal())- sql.SetIndexAssetPath(Conf.Search.IndexAssetPath)go nativePaddle.Close()- if previousSearch == nil || previousSearch.CaseSensitive != Conf.Search.CaseSensitive ||- previousSearch.HanSensitiveVal() != Conf.Search.HanSensitiveVal() ||- previousSearch.IndexAssetPath != Conf.Search.IndexAssetPath {+ if previousSearch == nil || previousSearch.CaseSensitive != confSearchSnapshot.CaseSensitive ||+ previousSearch.HanSensitiveVal() != confSearchSnapshot.HanSensitiveVal() ||+ previousSearch.IndexAssetPath != confSearchSnapshot.IndexAssetPath {// 队列重建会重新加载闪卡调度参数,保留卡片和复习进度。task.AppendTask(task.DatabaseIndexFull, fullReindex)} else {diff --git a/kernel/model/settings_reset_test.go b/kernel/model/settings_reset_test.goindex 2b13f2cf8d..c8a5234e77 100644--- a/kernel/model/settings_reset_test.go+++ b/kernel/model/settings_reset_test.go@@ -21,10 +21,15 @@ import (func settingsResetTestEnvironment(t *testing.T) {t.Helper()previousConf, previousConfDir, previousDataDir, previousReadonly := Conf, util.ConfDir, util.DataDir, util.ReadOnly- previousMarkdown, previousSingleLine, previousWarning := util.MarkdownSettings, util.UseSingleLineSave, util.LargeFileWarningSize+ previousMarkdown, previousSingleLine, previousWarning := util.MarkdownSettings.Load(), util.UseSingleLineSave.Load(), util.LargeFileWarningSize.Load()t.Cleanup(func() {Conf, util.ConfDir, util.DataDir, util.ReadOnly = previousConf, previousConfDir, previousDataDir, previousReadonly- util.MarkdownSettings, util.UseSingleLineSave, util.LargeFileWarningSize = previousMarkdown, previousSingleLine, previousWarning+ {+ derivedValue0, derivedValue1, derivedValue2 := previousMarkdown, previousSingleLine, previousWarning+ util.MarkdownSettings.Store(derivedValue0)+ util.UseSingleLineSave.Store(derivedValue1)+ util.LargeFileWarningSize.Store(derivedValue2)+ }})root := t.TempDir()util.ConfDir, util.DataDir, util.ReadOnly = filepath.Join(root, "conf"), filepath.Join(root, "data"), false@@ -35,8 +40,8 @@ func settingsResetTestEnvironment(t *testing.T) {}Conf = NewAppConf()Conf.Lang = "ja"- Conf.System = conf.NewSystem()- Conf.Editor = conf.NewEditor()+ Conf.System.Store(conf.NewSystem())+ Conf.Editor.Store(conf.NewEditor())Conf.NotebookCrypto = conf.NewNotebookCrypto()Conf.NotebookCrypto.MasterSalt = []byte("retained-salt")Conf.NotebookCrypto.HistoryKEKs = [][]byte{[]byte("retained-history-key")}@@ -44,37 +49,41 @@ func settingsResetTestEnvironment(t *testing.T) {Conf.CookieKey = "cookie-signing-key"Conf.MCPOAuth = "encrypted-oauth"Conf.UserData = "encrypted-account"- Conf.Api = conf.NewAPI()- Conf.Api.Token = "preserved-token"- Conf.AI = conf.NewAI()- Conf.AI.Providers = []*conf.Provider{{APIKey: "retained-provider-key"}}+ Conf.Api.Store(conf.NewAPI())+ Conf.Api.Load().Token = "preserved-token"+ Conf.AI.Store(conf.NewAI())+ Conf.AI.Load().Providers = []*conf.Provider{{APIKey: "retained-provider-key"}}Conf.OIDC.ClientSecret = "retained-oidc-secret"- Conf.Secrets = &conf.Secrets{Items: []*conf.Secret{{Name: "secret", Value: "retained-secret"}}}- Conf.Sync = conf.NewSync()- Conf.Repo = conf.NewRepo()- Conf.Snippet = conf.NewSnpt()- Conf.Bazaar = conf.NewBazaar()- Conf.Bazaar.PetalDisabled = true+ Conf.Secrets.Store(&conf.Secrets{Items: []*conf.Secret{{Name: "secret", Value: "retained-secret"}}})+ Conf.Sync.Store(conf.NewSync())+ Conf.Repo.Store(conf.NewRepo())+ Conf.Snippet.Store(conf.NewSnpt())+ Conf.Bazaar.Store(conf.NewBazaar())+ Conf.Bazaar.Load().PetalDisabled = trueConf.Save()}func TestSettingsResetPreservesDataAndProtectedConfiguration(t *testing.T) {settingsResetTestEnvironment(t)- Conf.Editor.FontSize = 31- Conf.Editor.HistoryRetentionDays = 3650- Conf.System.AutoLaunch2 = 2- Conf.System.NetworkServe = true- Conf.System.NetworkServeTLS = true- Conf.System.NetworkProxy = &conf.NetworkProxy{Host: "proxy"}- Conf.System.LockScreenMode = 1- Conf.System.EncryptedNotebookFollowSystemLock = true- Conf.System.DownloadInstallPkg = false- Conf.System.SettingsWindow = true- util.MarkdownSettings = util.NewMarkdown()- util.MarkdownSettings.InlineMath = false- util.UseSingleLineSave, util.LargeFileWarningSize = false, 64+ Conf.Editor.Load().FontSize = 31+ Conf.Editor.Load().HistoryRetentionDays = 3650+ Conf.System.Load().AutoLaunch2 = 2+ Conf.System.Load().NetworkServe = true+ Conf.System.Load().NetworkServeTLS = true+ Conf.System.Load().NetworkProxy = &conf.NetworkProxy{Host: "proxy"}+ Conf.System.Load().LockScreenMode = 1+ Conf.System.Load().EncryptedNotebookFollowSystemLock = true+ Conf.System.Load().DownloadInstallPkg = false+ Conf.System.Load().SettingsWindow = true+ util.MarkdownSettings.Store(util.NewMarkdown())+ util.MarkdownSettings.Load().InlineMath = false+ {+ derivedValue0, derivedValue1 := false, 64+ util.UseSingleLineSave.Store(derivedValue0)+ util.LargeFileWarningSize.Store(derivedValue1)+ }keymap := conf.Keymap{"general": map[string]any{"test": "custom"}, "editor": map[string]any{}, "plugin": map[string]any{"kept": true}}- Conf.Keymap = &keymap+ Conf.Keymap.Store(&keymap)Conf.Save()protected := *Confstorage := []byte(`{"local-zoom":2,"local-mobile-bars":{"autoHide":false},"local-layouts":[{"name":"saved"}],"plugin-unknown":{"key":"value"}}`)@@ -90,26 +99,26 @@ func TestSettingsResetPreservesDataAndProtectedConfiguration(t *testing.T) {if err := ResetSettings(); err != nil {t.Fatal(err)}- if Conf.Editor.FontSize != 16 || !Conf.Editor.Markdown.InlineMath || !Conf.FileTree.UseSingleLineSave || Conf.FileTree.LargeFileWarningSize != 8 {+ if Conf.Editor.Load().FontSize != 16 || !Conf.Editor.Load().Markdown.InlineMath || !Conf.FileTree.Load().UseSingleLineSave || Conf.FileTree.Load().LargeFileWarningSize != 8 {t.Fatal("reset must not inherit mutable runtime defaults")}- if Conf.Editor.HistoryRetentionDays != 3650 || Conf.Lang != "ja" || Conf.Appearance.Lang != "ja" {+ if Conf.Editor.Load().HistoryRetentionDays != 3650 || Conf.Lang != "ja" || Conf.Appearance.Load().Lang != "ja" {t.Fatal("retention and language must be preserved")}- if Conf.NotebookCrypto != protected.NotebookCrypto || Conf.Api != protected.Api || Conf.AccessAuthCode != protected.AccessAuthCode ||+ if Conf.NotebookCrypto != protected.NotebookCrypto || Conf.Api.Load() != protected.Api.Load() || Conf.AccessAuthCode != protected.AccessAuthCode ||Conf.CookieKey != protected.CookieKey || Conf.MCPOAuth != protected.MCPOAuth || Conf.UserData != protected.UserData ||- Conf.Snippet != protected.Snippet || Conf.Bazaar != protected.Bazaar || Conf.AI != protected.AI ||- Conf.OIDC != protected.OIDC || Conf.Secrets != protected.Secrets || Conf.Sync != protected.Sync || Conf.Repo != protected.Repo {+ Conf.Snippet.Load() != protected.Snippet.Load() || Conf.Bazaar.Load() != protected.Bazaar.Load() || Conf.AI.Load() != protected.AI.Load() ||+ Conf.OIDC != protected.OIDC || Conf.Secrets.Load() != protected.Secrets.Load() || Conf.Sync.Load() != protected.Sync.Load() || Conf.Repo.Load() != protected.Repo.Load() {t.Fatal("protected configuration changed")}- if Conf.System.AutoLaunch2 != 2 || !Conf.System.NetworkServe || !Conf.System.NetworkServeTLS ||- Conf.System.NetworkProxy.Host != "proxy" || Conf.System.LockScreenMode != 1 || !Conf.System.EncryptedNotebookFollowSystemLock {+ if Conf.System.Load().AutoLaunch2 != 2 || !Conf.System.Load().NetworkServe || !Conf.System.Load().NetworkServeTLS ||+ Conf.System.Load().NetworkProxy.Host != "proxy" || Conf.System.Load().LockScreenMode != 1 || !Conf.System.Load().EncryptedNotebookFollowSystemLock {t.Fatal("host, networking and authentication settings changed")}- if Conf.System.SettingsWindow {+ if Conf.System.Load().SettingsWindow {t.Fatal("desktop settings window preference must be reset to its default")}- if !reflect.DeepEqual((*Conf.Keymap)["plugin"], keymap["plugin"]) || (*Conf.Keymap)["general"] != nil {+ if !reflect.DeepEqual((*Conf.Keymap.Load())["plugin"], keymap["plugin"]) || (*Conf.Keymap.Load())["general"] != nil {t.Fatal("only built-in shortcuts should be reset")}}@@ -143,11 +152,11 @@ func TestSettingsResetPreservesDataAndProtectedConfiguration(t *testing.T) {bytes.Contains(data, []byte("retained-secret")) {t.Fatal("reset persisted plaintext credentials")}- reloaded.AI.DecryptAPIKeys()+ reloaded.AI.Load().DecryptAPIKeys()reloaded.OIDC.DecryptClientSecret()- reloaded.Secrets.Decrypt()- if reloaded.AI.Providers[0].APIKey != Conf.AI.Providers[0].APIKey ||- reloaded.OIDC.ClientSecret != Conf.OIDC.ClientSecret || reloaded.Secrets.Items[0].Value != Conf.Secrets.Items[0].Value {+ reloaded.Secrets.Load().Decrypt()+ if reloaded.AI.Load().Providers[0].APIKey != Conf.AI.Load().Providers[0].APIKey ||+ reloaded.OIDC.ClientSecret != Conf.OIDC.ClientSecret || reloaded.Secrets.Load().Items[0].Value != Conf.Secrets.Load().Items[0].Value {t.Fatal("credentials no longer decrypt after reset")}}@@ -200,7 +209,7 @@ func TestSettingsResetFailureAndRecovery(t *testing.T) {func TestSettingsResetRejectsCorruptionAndReadonly(t *testing.T) {settingsResetTestEnvironment(t)- before := Conf.Editor+ before := Conf.Editor.Load()util.ReadOnly = trueif ResetSettings() == nil {t.Fatal("readonly reset accepted")@@ -209,7 +218,7 @@ func TestSettingsResetRejectsCorruptionAndReadonly(t *testing.T) {if err := os.WriteFile(settingsResetPaths()[1], []byte("invalid json"), 0600); err != nil {t.Fatal(err)}- if ResetSettings() == nil || Conf.Editor != before {+ if ResetSettings() == nil || Conf.Editor.Load() != before {t.Fatal("corrupt storage reset must preserve configuration")}if err := os.WriteFile(settingsResetJournalPath(), []byte(`{"version":99,"files":[]}`), 0600); err != nil {@@ -327,13 +336,13 @@ func TestSettingsResetRollbackFailureStopsWrites(t *testing.T) {t.Fatalf("original configuration was not recovered: %s, %v", path, readErr)}}- Conf.Api.Token = "token-after-successful-recovery"+ Conf.Api.Load().Token = "token-after-successful-recovery"Conf.Save()if err = recoverSettingsReset(); err != nil {t.Fatal(err)}data, err := os.ReadFile(paths[0])- if err != nil || !bytes.Contains(data, []byte(Conf.Api.Token)) {+ if err != nil || !bytes.Contains(data, []byte(Conf.Api.Load().Token)) {t.Fatal("recovery reverted a later configuration save")}})diff --git a/kernel/model/shortcuts.go b/kernel/model/shortcuts.goindex 397b5a4a95..63e6720f0c 100644--- a/kernel/model/shortcuts.go+++ b/kernel/model/shortcuts.go@@ -82,7 +82,7 @@ func MoveLocalShorthands(boxID string) (retIDs []string, err error) {}}- hPath := Conf.FileTree.ShorthandSavePath+ hPath := Conf.FileTree.Load().ShorthandSavePathif "" != hPath {var renderErr errorhPath, renderErr = RenderGoTemplateInBox(hPath, boxID)@@ -393,7 +393,7 @@ func consumeShorthands() {}boxes := Conf.GetBoxes()- box := selectShorthandSaveBox(Conf.FileTree.ShorthandSaveBox, boxes)+ box := selectShorthandSaveBox(Conf.FileTree.Load().ShorthandSaveBox, boxes)if nil == box {logging.LogWarnf("auto consume shorthands failed: no available notebook found")if !shorthandSaveBoxUnavailableNotified {diff --git a/kernel/model/shortcuts_fts5_test.go b/kernel/model/shortcuts_fts5_test.goindex f5dcbc4388..d97b515d13 100644--- a/kernel/model/shortcuts_fts5_test.go+++ b/kernel/model/shortcuts_fts5_test.go@@ -63,7 +63,7 @@ func TestMoveLocalShorthandsIndexesInlineTags(t *testing.T) {}}Conf.Lang = "en"- Conf.Search = conf.NewSearch()+ Conf.Search.Store(conf.NewSearch())util.WorkingDir = filepath.Clean(filepath.Join("..", "..", "app"))initLang()sql.InitDatabase(true)@@ -89,8 +89,8 @@ func TestMoveLocalShorthandsIndexesInlineTags(t *testing.T) {{name: "disabled", hPath: "/Source"},} {t.Run(tc.name, func(t *testing.T) {- Conf.FileTree.ShorthandSavePath = tc.hPath- util.MarkdownSettings.InlineTag = tc.enabled+ Conf.FileTree.Load().ShorthandSavePath = tc.hPath+ util.MarkdownSettings.Load().InlineTag = tc.enabledcreated := time.Date(2026, 9, 8, 8, i, 0, 0, time.Local)label := "shorthand-" + tc.namemd := "**bold** [link](https://example.com)\n\n测试#" + label + "#" + tc.suffixdiff --git a/kernel/model/shortcuts_markdown_fts5_test.go b/kernel/model/shortcuts_markdown_fts5_test.goindex ba4c4a09f6..158f95e068 100644--- a/kernel/model/shortcuts_markdown_fts5_test.go+++ b/kernel/model/shortcuts_markdown_fts5_test.go@@ -55,8 +55,8 @@ func TestMoveLocalShorthandsMarkdownSettings(t *testing.T) {for _, enabled := range []bool{true, false} {t.Run(fmt.Sprintf("%s/enabled=%t", route, enabled), func(t *testing.T) {settings := shorthandMarkdownTestSettings(enabled)- util.MarkdownSettings = settings- Conf.Editor.Markdown = settings+ util.MarkdownSettings.Store(settings)+ Conf.Editor.Load().Markdown = settingscreated := time.Date(2026, 9, 9, 8, caseIndex, 0, 0, time.Local)caseIndex++secondCreated := created.Add(11 * time.Second)@@ -99,13 +99,13 @@ func TestMoveLocalShorthandsMarkdownSettings(t *testing.T) {oldIDs := map[string]bool{}switch route {case "separate":- Conf.FileTree.ShorthandSavePath = ""+ Conf.FileTree.Load().ShorthandSavePath = ""hPath = "/" + created.Format("2006-01-02 15:04:05")case "merged":- Conf.FileTree.ShorthandSavePath = hPath+ Conf.FileTree.Load().ShorthandSavePath = hPathcase "append":hPath = "/Source"- Conf.FileTree.ShorthandSavePath = hPath+ Conf.FileTree.Load().ShorthandSavePath = hPathbt := treenode.GetBlockTreeRootByHPath(fixture.box.ID, hPath)if nil == bt {t.Fatal("existing shorthand document fixture missing")@@ -224,7 +224,7 @@ func TestMoveLocalShorthandsMarkdownSettings(t *testing.T) {func setupShorthandMarkdownTest(t *testing.T) (*fileOperationTestFixture, string) {t.Helper()- originalMarkdown := util.MarkdownSettings+ originalMarkdown := util.MarkdownSettings.Load()originalPaths := map[*string]string{&util.TempDir: util.TempDir, &util.QueueDir: util.QueueDir, &util.ConfDir: util.ConfDir,&util.ShortcutsPath: util.ShortcutsPath, &util.DBPath: util.DBPath,@@ -232,7 +232,7 @@ func setupShorthandMarkdownTest(t *testing.T) (*fileOperationTestFixture, string&util.WorkingDir: util.WorkingDir,}t.Cleanup(func() {- util.MarkdownSettings = originalMarkdown+ util.MarkdownSettings.Store(originalMarkdown)for target, original := range originalPaths {*target = original}@@ -252,8 +252,8 @@ func setupShorthandMarkdownTest(t *testing.T) (*fileOperationTestFixture, string}}Conf.Lang = "en"- Conf.Search = conf.NewSearch()- Conf.Editor = conf.NewEditor()+ Conf.Search.Store(conf.NewSearch())+ Conf.Editor.Store(conf.NewEditor())util.WorkingDir = filepath.Clean(filepath.Join("..", "..", "app"))initLang()sql.InitDatabase(true)diff --git a/kernel/model/shorthand_markdown.go b/kernel/model/shorthand_markdown.goindex 9c39704418..43b713993e 100644--- a/kernel/model/shorthand_markdown.go+++ b/kernel/model/shorthand_markdown.go@@ -49,7 +49,7 @@ type shorthandMarker struct {// parseShorthandMarkdown 仅在消费速记时应用编辑器语法,不改变普通 Markdown 导入的解析配置。func parseShorthandMarkdown(md string, created time.Time, engine *lute.Lute) *parse.Tree {- engine.SetMark(util.MarkdownSettings.InlineMark)+ engine.SetMark(util.MarkdownSettings.Load().InlineMark)md, tasks := normalizeShorthandMarkdown(md, engine.ParseOptions)tree := parse.Parse("", []byte(md), engine.ParseOptions)if nil == tree {@@ -92,7 +92,7 @@ func parseShorthandMarkdown(md string, created time.Time, engine *lute.Lute) *pa// normalizeShorthandMarkdown 由解析器判断标记的上下文,避免修改代码、公式、HTML 块和转义正文。func normalizeShorthandMarkdown(md string, options *parse.Options) (string, map[string]byte) {- settings := util.MarkdownSettings+ settings := util.MarkdownSettings.Load()dotsEnabled := nil == settings.CodeBlockMiddleDot || *settings.CodeBlockMiddleDottasksEnabled := nil == settings.BlockFullWidthTaskList || *settings.BlockFullWidthTaskListif !dotsEnabled && !tasksEnabled {diff --git a/kernel/model/shorthand_markdown_test.go b/kernel/model/shorthand_markdown_test.goindex 7565744bc7..b918b4e3c3 100644--- a/kernel/model/shorthand_markdown_test.go+++ b/kernel/model/shorthand_markdown_test.go@@ -29,9 +29,9 @@ import ()func shorthandSyntaxTestSettings(t testing.TB) {- previous := util.MarkdownSettings- util.MarkdownSettings = util.NewMarkdown()- t.Cleanup(func() { util.MarkdownSettings = previous })+ previous := util.MarkdownSettings.Load()+ util.MarkdownSettings.Store(util.NewMarkdown())+ t.Cleanup(func() { util.MarkdownSettings.Store(previous) })}func shorthandSyntaxNodes(tree *parse.Tree, typ ast.NodeType) (ret []*ast.Node) {@@ -55,17 +55,17 @@ func TestShorthandMarkdownSettings(t *testing.T) {set func(bool)node ast.NodeType}{- {"asterisk", "**text**", "strong", func(v bool) { util.MarkdownSettings.InlineAsterisk = v }, ast.NodeTextMark},- {"underscore", "__text__", "strong", func(v bool) { util.MarkdownSettings.InlineUnderscore = v }, ast.NodeTextMark},- {"sup", "^text^", "sup", func(v bool) { util.MarkdownSettings.InlineSup = v }, ast.NodeTextMark},- {"sub", "~text~", "sub", func(v bool) { util.MarkdownSettings.InlineSub = v }, ast.NodeTextMark},- {"tag", "#text#", "tag", func(v bool) { util.MarkdownSettings.InlineTag = v }, ast.NodeTextMark},- {"math", "$text$", "inline-math", func(v bool) { util.MarkdownSettings.InlineMath = v }, ast.NodeTextMark},- {"strikethrough", "~~text~~", "s", func(v bool) { util.MarkdownSettings.InlineStrikethrough = v }, ast.NodeTextMark},- {"full-width-strikethrough", "~~text~~", "s", func(v bool) { util.MarkdownSettings.InlineFullWidthStrikethrough = v }, ast.NodeTextMark},- {"mark", "==text==", "mark", func(v bool) { util.MarkdownSettings.InlineMark = v }, ast.NodeTextMark},- {"middle-dot", "···go\ntext\n···", "", func(v bool) { util.MarkdownSettings.CodeBlockMiddleDot = &v }, ast.NodeCodeBlock},- {"full-width-task", "【X】text", "", func(v bool) { util.MarkdownSettings.BlockFullWidthTaskList = &v }, ast.NodeListItem},+ {"asterisk", "**text**", "strong", func(v bool) { util.MarkdownSettings.Load().InlineAsterisk = v }, ast.NodeTextMark},+ {"underscore", "__text__", "strong", func(v bool) { util.MarkdownSettings.Load().InlineUnderscore = v }, ast.NodeTextMark},+ {"sup", "^text^", "sup", func(v bool) { util.MarkdownSettings.Load().InlineSup = v }, ast.NodeTextMark},+ {"sub", "~text~", "sub", func(v bool) { util.MarkdownSettings.Load().InlineSub = v }, ast.NodeTextMark},+ {"tag", "#text#", "tag", func(v bool) { util.MarkdownSettings.Load().InlineTag = v }, ast.NodeTextMark},+ {"math", "$text$", "inline-math", func(v bool) { util.MarkdownSettings.Load().InlineMath = v }, ast.NodeTextMark},+ {"strikethrough", "~~text~~", "s", func(v bool) { util.MarkdownSettings.Load().InlineStrikethrough = v }, ast.NodeTextMark},+ {"full-width-strikethrough", "~~text~~", "s", func(v bool) { util.MarkdownSettings.Load().InlineFullWidthStrikethrough = v }, ast.NodeTextMark},+ {"mark", "==text==", "mark", func(v bool) { util.MarkdownSettings.Load().InlineMark = v }, ast.NodeTextMark},+ {"middle-dot", "···go\ntext\n···", "", func(v bool) { util.MarkdownSettings.Load().CodeBlockMiddleDot = &v }, ast.NodeCodeBlock},+ {"full-width-task", "【X】text", "", func(v bool) { util.MarkdownSettings.Load().BlockFullWidthTaskList = &v }, ast.NodeListItem},} {for _, enabled := range []bool{false, true} {name := factory.name + "/" + tc.name + "/disabled"@@ -73,7 +73,7 @@ func TestShorthandMarkdownSettings(t *testing.T) {name = factory.name + "/" + tc.name + "/enabled"}t.Run(name, func(t *testing.T) {- util.MarkdownSettings = util.NewMarkdown()+ util.MarkdownSettings.Store(util.NewMarkdown())tc.set(enabled)tree := parseShorthandMarkdown(tc.md, time.Now(), factory.new())found := false@@ -166,8 +166,8 @@ func TestShorthandTaskMarkersAndLiteralProtection(t *testing.T) {}})}- util.MarkdownSettings.CodeBlockMiddleDot = nil- util.MarkdownSettings.BlockFullWidthTaskList = nil+ util.MarkdownSettings.Load().CodeBlockMiddleDot = nil+ util.MarkdownSettings.Load().BlockFullWidthTaskList = niltree := parseShorthandMarkdown("···\ncode\n···\n\n【】task", time.Now(), util.NewLute())if 1 != len(shorthandSyntaxNodes(tree, ast.NodeCodeBlock)) || 1 != len(shorthandSyntaxNodes(tree, ast.NodeListItem)) {t.Fatal("missing default shortcut settings disabled conversion")diff --git a/kernel/model/slash_frequent.go b/kernel/model/slash_frequent.goindex bc72ac3d5f..7c3160405e 100644--- a/kernel/model/slash_frequent.go+++ b/kernel/model/slash_frequent.go@@ -3,11 +3,11 @@ package modelimport "github.com/siyuan-note/siyuan/kernel/conf"// 将常用命令开关迁移到自定义方案,读取失败时保留未配置状态以便下次重试。-func migrateSlashFrequent(entryVisibility *conf.EntryVisibility, loadStorage func() (map[string]any, error)) {+func migrateSlashFrequent(entryVisibility *conf.EntryVisibility, loadStorage func() (map[string]any, error)) error {const key = "editor.slash.menu.frequent"var profiles []*conf.EntryVisibilityProfileif nil == entryVisibility {- return+ return nil}for _, profile := range entryVisibility.Profiles {if nil == profile || "" == profile.ID || "" == profile.Name ||@@ -20,11 +20,11 @@ func migrateSlashFrequent(entryVisibility *conf.EntryVisibility, loadStorage fun}}if 0 == len(profiles) {- return+ return nil}storage, err := loadStorage()if nil != err {- return+ return err}enabled, configured := storage["local-slash-frequent-enabled"].(bool)for _, profile := range profiles {@@ -33,4 +33,5 @@ func migrateSlashFrequent(entryVisibility *conf.EntryVisibility, loadStorage fun}profile.Entries[key] = !configured || enabled}+ return nil}diff --git a/kernel/model/sort_conf.go b/kernel/model/sort_conf.goindex 1e429d0511..567b43960c 100644--- a/kernel/model/sort_conf.go+++ b/kernel/model/sort_conf.go@@ -73,7 +73,7 @@ func salvageSortConfMap(data []byte) map[string]int {func sortConfFromSnapshots(relPath string) (map[string]int, string, error) {// 未配置快照密钥或没有本地索引时不访问云端,直接使用原文件中的可用条目。- if Conf.Repo == nil || len(Conf.Repo.Key) == 0 {+ if Conf.Repo.Load() == nil || len(Conf.Repo.Load().Key) == 0 {return nil, "", nil}if _, err := os.Stat(filepath.Join(util.RepoDir, "indexes")); err != nil {diff --git a/kernel/model/sort_conf_append.go b/kernel/model/sort_conf_append.goindex 382d415795..107f21ce49 100644--- a/kernel/model/sort_conf_append.go+++ b/kernel/model/sort_conf_append.go@@ -274,7 +274,7 @@ func recoverSortConfAppend(confPath string) (err error) {return}logging.LogInfof("recovered incremental sort conf [%s]", confPath)- if Conf != nil && Conf.Sync != nil {+ if Conf != nil && Conf.Sync.Load() != nil {IncSync()} else {// 启动恢复发生在同步配置加载前,先标记待同步状态。diff --git a/kernel/model/storage.go b/kernel/model/storage.goindex be9bc86dac..e83c8eed9e 100644--- a/kernel/model/storage.go+++ b/kernel/model/storage.go@@ -517,6 +517,8 @@ func buildRecentDocsByTimeStmt(sortBy string, hiddenRootIDs []string, limit int)}func getRecentDocs(sortBy string) (ret []*RecentDoc, err error) {+ confFileTreeSnapshot := Conf.LoadFileTree()+ret = []*RecentDoc{} // 初始化为空切片,确保 API 始终返回非 nilrecentDocs, err := loadRecentDocsRaw()if err != nil {@@ -595,8 +597,8 @@ func getRecentDocs(sortBy string) (ret []*RecentDoc, err error) {switch sortBy {case "created", "updated": // 按创建时间或更新时间排序// 从数据库查询最近创建或修改的文档- stmt, boxDocArgs := buildRecentDocsByTimeStmt(sortBy, hiddenBoxDocRootIDs(), Conf.FileTree.RecentDocsMaxListCount)- sqlBlocks := sql.SelectBlocksRawStmtArgs(stmt, boxDocArgs, Conf.FileTree.RecentDocsMaxListCount)+ stmt, boxDocArgs := buildRecentDocsByTimeStmt(sortBy, hiddenBoxDocRootIDs(), confFileTreeSnapshot.RecentDocsMaxListCount)+ sqlBlocks := sql.SelectBlocksRawStmtArgs(stmt, boxDocArgs, confFileTreeSnapshot.RecentDocsMaxListCount)ret = []*RecentDoc{}if 1 > len(sqlBlocks) {return@@ -684,7 +686,7 @@ func getRecentDocs(sortBy string) (ret []*RecentDoc, err error) {// normalizeRecentDocs 规范化最近文档列表:去重、清空 Title/Icon、按类型截取配置的最大数量记录func normalizeRecentDocs(recentDocs []*RecentDoc) []*RecentDoc {- maxCount := Conf.FileTree.RecentDocsMaxListCount+ maxCount := Conf.FileTree.Load().RecentDocsMaxListCount// 去重seen := make(map[string]struct{}, len(recentDocs))diff --git a/kernel/model/sync.go b/kernel/model/sync.goindex 16c8100e28..d0eded64e2 100644--- a/kernel/model/sync.go+++ b/kernel/model/sync.go@@ -67,14 +67,14 @@ func syncDataDownloadLocked() (err error) {util.BroadcastByType("main", "syncing", 0, Conf.Language(81), nil)now := util.CurrentTimeMillis()- Conf.Sync.Synced = now+ UpdateSyncConf(func(s *conf.Sync) { s.Synced = now })err = syncRepoDownloadWithDNSRetry()code := 1if err != nil {code = 2}- util.BroadcastByType("main", "syncing", code, Conf.Sync.Stat, nil)+ util.BroadcastByType("main", "syncing", code, Conf.Sync.Load().Stat, nil)pendingSync.finish(revision, err == nil, notifySyncPending)if 1 == code {consumeShorthands()@@ -137,14 +137,14 @@ func SyncDataUpload() (err error) {util.BroadcastByType("main", "syncing", 0, Conf.Language(81), nil)now := util.CurrentTimeMillis()- Conf.Sync.Synced = now+ UpdateSyncConf(func(s *conf.Sync) { s.Synced = now })err = syncRepoUploadWithDNSRetry()code := 1if err != nil {code = 2}- util.BroadcastByType("main", "syncing", code, Conf.Sync.Stat, nil)+ util.BroadcastByType("main", "syncing", code, Conf.Sync.Load().Stat, nil)pendingSync.finish(revision, err == nil, notifySyncPending)return}@@ -181,7 +181,7 @@ func BootSyncData() {defer logging.Recover()refreshLANSyncManager()- if Conf.Sync.Perception {+ if Conf.Sync.Load().Perception {connectSyncWebSocket()}@@ -204,7 +204,7 @@ func BootSyncData() {}now := util.CurrentTimeMillis()- Conf.Sync.Synced = now+ UpdateSyncConf(func(s *conf.Sync) { s.Synced = now })revision := pendingSync.begin()if iosAfterBoot {// 本地界面已可编辑,保持同步入口可见直到云端合并成功。@@ -224,15 +224,14 @@ func BootSyncData() {BootSyncSucc.Store(1)if iosAfterBoot {msg := formatSyncRepoErrorMsg(err)- Conf.Sync.Stat = msg- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.Stat = msg })pushSyncStatusBar(msg)util.PushErrMsg(msg, 0)}} else {BootSyncSucc.Store(0)}- util.BroadcastByType("main", "syncing", code, Conf.Sync.Stat, nil)+ util.BroadcastByType("main", "syncing", code, Conf.Sync.Load().Stat, nil)pendingSync.finish(revision, err == nil, notifySyncPending)if 1 == code {// 启动同步成功后消费本地速记临时文件,避免移动端开启云同步时需手动触发同步才能刷新闪念速记@@ -251,10 +250,12 @@ func SyncData(byHand bool) {// SyncDataBeforeEnableEncryptedNotebook 在启用加密笔记本前执行一次完整同步。// 未启用数据同步时直接返回;已启用数据同步时,任何同步失败都会阻止继续创建新的密钥体系。func SyncDataBeforeEnableEncryptedNotebook() error {- if !Conf.Sync.Enabled {+ confSyncSnapshot := Conf.LoadSync()++ if !confSyncSnapshot.Enabled {return nil}- if conf.ProviderS3 != Conf.Sync.Provider && !cloud.IsValidCloudDirName(Conf.Sync.CloudName) {+ if conf.ProviderS3 != confSyncSnapshot.Provider && !cloud.IsValidCloudDirName(confSyncSnapshot.CloudName) {return errors.New(Conf.Language(123))}if !checkSync(false, false, true) {@@ -265,8 +266,8 @@ func SyncDataBeforeEnableEncryptedNotebook() error {lockSync()defer unlockSync()if err := syncDataLocked(false, true); err != nil {- if Conf.Sync.Stat != "" {- return errors.New(Conf.Sync.Stat)+ if confSyncSnapshot.Stat != "" {+ return errors.New(confSyncSnapshot.Stat)}return err}@@ -338,7 +339,7 @@ func syncDataLocked(exit, byHand bool) error {}now := util.CurrentTimeMillis()- Conf.Sync.Synced = now+ UpdateSyncConf(func(s *conf.Sync) { s.Synced = now })cloudPublished, err := syncRepoWithDNSRetry(exit, byHand)code := 1@@ -347,7 +348,7 @@ func syncDataLocked(exit, byHand bool) error {} else {BootSyncSucc.Store(0)}- util.BroadcastByType("main", "syncing", code, Conf.Sync.Stat, nil)+ util.BroadcastByType("main", "syncing", code, Conf.Sync.Load().Stat, nil)pendingSync.finish(revision, err == nil, notifySyncPending)if !exit && 1 == code {@@ -360,16 +361,18 @@ func syncDataLocked(exit, byHand bool) error {// completeSyncPerception 恢复感知连接,并在自动同步成功发布新版本后通知其他设备。func completeSyncPerception(cloudPublished bool, err error) {- if nil == webSocketConn && Conf.Sync.Perception {+ confSyncSnapshot := Conf.LoadSync()++ if nil == webSocketConn && confSyncSnapshot.Perception {// 如果 websocket 连接已经断开,则重新连接connectSyncWebSocket()}- if nil == err && cloudPublished && 1 == Conf.Sync.Mode && nil != webSocketConn && Conf.Sync.Perception {+ if nil == err && cloudPublished && 1 == confSyncSnapshot.Mode && nil != webSocketConn && confSyncSnapshot.Perception {// 自动同步成功发布新云端版本后通知其他设备,纯下载不发送同步信号。request := map[string]any{"cmd": "synced",- "synced": Conf.Sync.Synced,+ "synced": confSyncSnapshot.Synced,}if writeErr := webSocketConn.WriteJSON(request); nil != writeErr {logging.LogErrorf("write websocket message failed: %v", writeErr)@@ -378,22 +381,22 @@ func completeSyncPerception(cloudPublished bool, err error) {}func checkSync(boot, exit, byHand bool) bool {- if 2 == Conf.Sync.Mode && !boot && !exit && !byHand { // 手动模式下只有启动和退出进行同步+ if 2 == Conf.Sync.Load().Mode && !boot && !exit && !byHand { // 手动模式下只有启动和退出进行同步return false}- if 3 == Conf.Sync.Mode && !byHand { // 完全手动模式下只有手动进行同步+ if 3 == Conf.Sync.Load().Mode && !byHand { // 完全手动模式下只有手动进行同步return false}- if !Conf.Sync.Enabled {+ if !Conf.Sync.Load().Enabled {if byHand {util.PushMsg(Conf.Language(124), 5000)}return false}- if conf.ProviderS3 != Conf.Sync.Provider && !cloud.IsValidCloudDirName(Conf.Sync.CloudName) {+ if conf.ProviderS3 != Conf.Sync.Load().Provider && !cloud.IsValidCloudDirName(Conf.Sync.Load().CloudName) {if byHand {util.PushMsg(Conf.Language(123), 5000)}@@ -403,17 +406,15 @@ func checkSync(boot, exit, byHand bool) bool {return false}- switch Conf.Sync.Provider {+ switch Conf.Sync.Load().Provider {case conf.ProviderSiYuan:if !IsSubscriber() {- Conf.Sync.Enabled = false- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.Enabled = false })return false}case conf.ProviderWebDAV, conf.ProviderS3, conf.ProviderLocal:if !IsPaidUser() {- Conf.Sync.Enabled = false- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.Enabled = false })return false}}@@ -560,35 +561,32 @@ func upsertIndexes(upsertFilePaths []string) (upsertRootIDs []string) {func SetCloudSyncDir(name string) error {release := lockAssetSourceChange()defer release()- if conf.ProviderS3 == Conf.Sync.Provider {+ if conf.ProviderS3 == Conf.Sync.Load().Provider {return errors.New(Conf.Language(131))}if !cloud.IsValidCloudDirName(name) {return errors.New(Conf.Language(37))}- if Conf.Sync.CloudName == name {+ if Conf.Sync.Load().CloudName == name {return nil}if err := requireCompleteAssetDownloads(); err != nil {return err}- Conf.Sync.CloudName = name- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.CloudName = name })syncIndexListNotice.reset(util.PushClearMsg)refreshLANSyncManager()return nil}func SetSyncGenerateConflictDoc(b bool) {- Conf.Sync.GenerateConflictDoc = b- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.GenerateConflictDoc = b })}func SetSyncEnable(b bool) {- Conf.Sync.Enabled = b- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.Enabled = b })if !b {syncIndexListNotice.reset(util.PushClearMsg)}@@ -603,8 +601,7 @@ func SetSyncInterval(interval int) {interval = 43200}- Conf.Sync.Interval = interval- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.Interval = interval })planSyncAfter(time.Duration(interval) * time.Second)}@@ -613,8 +610,7 @@ func SetSyncPerception(enabled bool) {enabled = false}- Conf.Sync.Perception = enabled- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.Perception = enabled })if enabled {connectSyncWebSocket()@@ -625,20 +621,19 @@ func SetSyncPerception(enabled bool) {}func SetSyncMode(mode int) {- Conf.Sync.Mode = mode- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.Mode = mode })}func SetSyncProvider(provider int, completeAssets bool) (err error) {release := lockAssetSourceChange()defer release()- if provider != Conf.Sync.Provider {+ if provider != Conf.Sync.Load().Provider {if completeAssets {util.PushEndlessProgress(Conf.Language(398))defer util.ClearPushProgress(100)err = ensureCompleteSyncAssets(func() { util.PushEndlessProgress(Conf.Language(399)) })if err != nil {- logging.LogWarnf("complete data before switching sync provider [%d -> %d] failed: %s", Conf.Sync.Provider, provider, err)+ logging.LogWarnf("complete data before switching sync provider [%d -> %d] failed: %s", Conf.Sync.Load().Provider, provider, err)err = fmt.Errorf(Conf.Language(400), err)}} else {@@ -648,8 +643,7 @@ func SetSyncProvider(provider int, completeAssets bool) (err error) {return}}- Conf.Sync.Provider = provider- Conf.Save()+ UpdateSyncConf(func(s *conf.Sync) { s.Provider = provider })syncIndexListNotice.reset(util.PushClearMsg)refreshLANSyncManager()return@@ -669,16 +663,15 @@ func SetSyncProviderS3(s3 *conf.S3) (err error) {s3.Region = strings.TrimSpace(s3.Region)s3.Timeout = util.NormalizeTimeout(s3.Timeout)s3.ConcurrentReqs = util.NormalizeConcurrentReqs(s3.ConcurrentReqs, conf.ProviderS3)- if Conf.Sync.Provider == conf.ProviderS3 && (Conf.Sync.S3 == nil ||- Conf.Sync.S3.Endpoint != s3.Endpoint || Conf.Sync.S3.Bucket != s3.Bucket) {+ if Conf.Sync.Load().Provider == conf.ProviderS3 && (Conf.Sync.Load().S3 == nil ||+ Conf.Sync.Load().S3.Endpoint != s3.Endpoint || Conf.Sync.Load().S3.Bucket != s3.Bucket) {if err = requireCompleteAssetDownloads(); err != nil {return}}- Conf.Sync.S3 = s3- Conf.Save()- if Conf.Sync.Provider == conf.ProviderS3 {+ UpdateSyncConf(func(value *conf.Sync) { value.S3 = cloneConfSection(s3) })+ if Conf.Sync.Load().Provider == conf.ProviderS3 {syncIndexListNotice.reset(util.PushClearMsg)}refreshLANSyncManager()@@ -748,16 +741,15 @@ func SetSyncProviderWebDAV(webdav *conf.WebDAV) (err error) {webdav.Password = strings.TrimSpace(webdav.Password)webdav.Timeout = util.NormalizeTimeout(webdav.Timeout)webdav.ConcurrentReqs = util.NormalizeConcurrentReqs(webdav.ConcurrentReqs, conf.ProviderWebDAV)- if Conf.Sync.Provider == conf.ProviderWebDAV && (Conf.Sync.WebDAV == nil ||- Conf.Sync.WebDAV.Endpoint != webdav.Endpoint || Conf.Sync.WebDAV.Username != webdav.Username) {+ if Conf.Sync.Load().Provider == conf.ProviderWebDAV && (Conf.Sync.Load().WebDAV == nil ||+ Conf.Sync.Load().WebDAV.Endpoint != webdav.Endpoint || Conf.Sync.Load().WebDAV.Username != webdav.Username) {if err = requireCompleteAssetDownloads(); err != nil {return}}- Conf.Sync.WebDAV = webdav- Conf.Save()- if Conf.Sync.Provider == conf.ProviderWebDAV {+ UpdateSyncConf(func(s *conf.Sync) { s.WebDAV = webdav })+ if Conf.Sync.Load().Provider == conf.ProviderWebDAV {syncIndexListNotice.reset(util.PushClearMsg)}refreshLANSyncManager()@@ -802,16 +794,15 @@ func SetSyncProviderLocal(local *conf.Local) (err error) {local.Timeout = util.NormalizeTimeout(local.Timeout)local.ConcurrentReqs = util.NormalizeConcurrentReqs(local.ConcurrentReqs, conf.ProviderLocal)- if Conf.Sync.Provider == conf.ProviderLocal && (Conf.Sync.Local == nil ||- filepath.Clean(Conf.Sync.Local.Endpoint) != filepath.Clean(local.Endpoint)) {+ if Conf.Sync.Load().Provider == conf.ProviderLocal && (Conf.Sync.Load().Local == nil ||+ filepath.Clean(Conf.Sync.Load().Local.Endpoint) != filepath.Clean(local.Endpoint)) {if err = requireCompleteAssetDownloads(); err != nil {return}}- Conf.Sync.Local = local- Conf.Save()- if Conf.Sync.Provider == conf.ProviderLocal {+ UpdateSyncConf(func(s *conf.Sync) { s.Local = local })+ if Conf.Sync.Load().Provider == conf.ProviderLocal {syncIndexListNotice.reset(util.PushClearMsg)}refreshLANSyncManager()@@ -831,7 +822,7 @@ var (func CreateCloudSyncDir(name string) (err error) {assetDownloadSourceMu.RLock()defer assetDownloadSourceMu.RUnlock()- switch Conf.Sync.Provider {+ switch Conf.Sync.Load().Provider {case conf.ProviderSiYuan, conf.ProviderLocal:breakdefault:@@ -863,12 +854,12 @@ func CreateCloudSyncDir(name string) (err error) {func RemoveCloudSyncDir(name string) (err error) {release := lockAssetSourceChange()defer release()- if name == Conf.Sync.CloudName {+ if name == Conf.Sync.Load().CloudName {if err = requireCompleteAssetDownloads(); err != nil {return}}- switch Conf.Sync.Provider {+ switch Conf.Sync.Load().Provider {case conf.ProviderSiYuan, conf.ProviderLocal:breakdefault:@@ -894,15 +885,16 @@ func RemoveCloudSyncDir(name string) (err error) {util.PushClearMsg(msgId)time.Sleep(500 * time.Millisecond)- if Conf.Sync.CloudName == name {- Conf.Sync.CloudName = "main"- Conf.Save()+ if Conf.Sync.Load().CloudName == name {+ UpdateSyncConf(func(s *conf.Sync) { s.CloudName = "main" })util.PushMsg(Conf.Language(155), 5000)}return}func ListCloudSyncDir() (syncDirs []*Sync, hSize string, err error) {+ confSyncSnapshot := Conf.LoadSync()+assetDownloadSourceMu.RLock()defer assetDownloadSourceMu.RUnlock()syncDirs = []*Sync{}@@ -922,7 +914,7 @@ func ListCloudSyncDir() (syncDirs []*Sync, hSize string, err error) {err = errors.New(formatRepoErrorMsg(err))return}- if 1 > len(dirs) && conf.ProviderS3 != Conf.Sync.Provider {+ if 1 > len(dirs) && conf.ProviderS3 != confSyncSnapshot.Provider {dirs = append(dirs, &cloud.Repo{Name: "main",Size: 0,@@ -938,13 +930,13 @@ func ListCloudSyncDir() (syncDirs []*Sync, hSize string, err error) {Updated: d.Updated,CloudName: d.Name,}- if conf.ProviderSiYuan == Conf.Sync.Provider {+ if conf.ProviderSiYuan == confSyncSnapshot.Provider {sync.HSize = humanize.BytesCustomCeil(uint64(dirSize), 2)}syncDirs = append(syncDirs, sync)}hSize = "-"- if conf.ProviderSiYuan == Conf.Sync.Provider {+ if conf.ProviderSiYuan == confSyncSnapshot.Provider {hSize = humanize.BytesCustomCeil(uint64(size), 2)}return@@ -1003,7 +995,7 @@ func formatRepoErrorMsg(err error) string {msg = Conf.Language(28)}}- msg += " (Provider: " + conf.ProviderToStr(Conf.Sync.Provider) + ")"+ msg += " (Provider: " + conf.ProviderToStr(Conf.Sync.Load().Provider) + ")"return msg}@@ -1133,7 +1125,7 @@ func loadSyncIgnoreLines() (ret []string, err error) {func IncSync() {syncSameCount.Store(0)- planSyncAfter(time.Duration(Conf.Sync.Interval) * time.Second)+ planSyncAfter(time.Duration(Conf.Sync.Load().Interval) * time.Second)pendingSync.change(notifySyncPending)}@@ -1199,7 +1191,7 @@ func closeSyncWebSocket() {func connectSyncWebSocket() {defer logging.Recover()- if !Conf.Sync.Enabled || !IsSubscriber() || conf.ProviderSiYuan != Conf.Sync.Provider {+ if !Conf.Sync.Load().Enabled || !IsSubscriber() || conf.ProviderSiYuan != Conf.Sync.Load().Provider {return}@@ -1302,7 +1294,7 @@ func dialSyncWebSocket() (c *websocket.Conn, err error) {"x-siyuan-ver": []string{util.Ver},"x-siyuan-os": []string{runtime.GOOS},"x-siyuan-hostname": []string{util.GetDeviceName()},- "x-siyuan-repo": []string{Conf.Sync.CloudName},+ "x-siyuan-repo": []string{Conf.Sync.Load().CloudName},}c, _, err = websocket.DefaultDialer.Dial(endpoint, header)if err == nil {diff --git a/kernel/model/sync_config_clear.go b/kernel/model/sync_config_clear.goindex cc3fd44a58..82c58ebdf5 100644--- a/kernel/model/sync_config_clear.go+++ b/kernel/model/sync_config_clear.go@@ -18,7 +18,7 @@ func ClearSyncProviderConfig(provider int) error {}release := lockAssetSourceChange()defer release()- if provider == Conf.Sync.Provider {+ if provider == Conf.Sync.Load().Provider {if err := requireCompleteAssetDownloads(); err != nil {return err}@@ -29,7 +29,7 @@ func ClearSyncProviderConfig(provider int) error {if err := persistClearedSyncProviderConfig(provider); err != nil {return err}- if provider == Conf.Sync.Provider {+ if provider == Conf.Sync.Load().Provider {syncIndexListNotice.reset(util.PushClearMsg)}refreshLANSyncManager()@@ -40,9 +40,9 @@ func ClearSyncProviderConfig(provider int) error {func persistClearedSyncProviderConfig(provider int) error {Conf.m.Lock()defer Conf.m.Unlock()- next := *Conf- syncConfig := *Conf.Sync- next.Sync = &syncConfig+ next := Conf.cloneSettings()+ // 深复制同步配置段,避免与生效配置共享子结构+ syncConfig := cloneConfSection(Conf.Sync.Load())if provider == syncConfig.Provider {syncConfig.Enabled = false}@@ -56,6 +56,7 @@ func persistClearedSyncProviderConfig(provider int) error {case conf.ProviderLocal:syncConfig.Local = &conf.Local{Timeout: timeout, ConcurrentReqs: concurrentReqs}}+ next.Sync.Store(conf.NormalizeSync(syncConfig))data, err := next.marshalForSave()if err != nil {return err@@ -63,6 +64,7 @@ func persistClearedSyncProviderConfig(provider int) error {if err = atomicWriteFile(filepath.Join(util.ConfDir, "conf.json"), data); err != nil {return err}- Conf.Sync = &syncConfig+ recordPersistedConf(data)+ Conf.Sync.Store(next.Sync.Load())return nil}diff --git a/kernel/model/sync_config_clear_test.go b/kernel/model/sync_config_clear_test.goindex 983c9d36af..1f17ac5933 100644--- a/kernel/model/sync_config_clear_test.go+++ b/kernel/model/sync_config_clear_test.go@@ -23,13 +23,19 @@ func prepareSyncConfigClearTest(t *testing.T) {util.ConfDir, util.DataDir, util.RepoDir = root, filepath.Join(root, "data"), filepath.Join(root, "repo")util.ReadOnly = falseConf = NewAppConf()- Conf.Sync, Conf.Repo = conf.NewSync(), conf.NewRepo()- Conf.Sync.S3 = &conf.S3{Endpoint: "https://s3.example", AccessKey: "access", SecretKey: "secret", Bucket: "notes", Region: "auto"}- Conf.Sync.WebDAV = &conf.WebDAV{Endpoint: "https://dav.example", Username: "name", Password: "password"}- Conf.Sync.Local = &conf.Local{Endpoint: filepath.Join(root, "cloud")}- Conf.Repo.Key = []byte("0123456789abcdef0123456789abcdef")- Conf.Sync.Enabled = true- Conf.Sync.AssetDownloadMode = 1+ {+ confSectionValue0, confSectionValue1 := conf.NewSync(), conf.NewRepo()+ Conf.Sync.Store(confSectionValue0)+ Conf.Repo.Store(confSectionValue1)+ }+ Conf.Sync.Load().S3 = &conf.S3{Endpoint: "https://s3.example", AccessKey: "access", SecretKey: "secret", Bucket: "notes", Region: "auto"}+ Conf.Sync.Load().WebDAV = &conf.WebDAV{Endpoint: "https://dav.example", Username: "name", Password: "password"}+ Conf.Sync.Load().Local = &conf.Local{Endpoint: filepath.Join(root, "cloud")}+ Conf.Repo.Load().Key = []byte("0123456789abcdef0123456789abcdef")+ Conf.Sync.Load().Enabled = true+ Conf.Sync.Load().AssetDownloadMode = 1+ // 与启动加载一致,测试配置先经过规范化+ Conf.Sync.Store(conf.NormalizeSync(Conf.Sync.Load()))Conf.Save()}@@ -39,35 +45,35 @@ func TestClearSyncProviderConfiguration(t *testing.T) {t.Run(conf.ProviderToStr(provider)+"/active="+map[bool]string{true: "true", false: "false"}[active], func(t *testing.T) {prepareSyncConfigClearTest(t)if active {- Conf.Sync.Provider = provider+ Conf.Sync.Load().Provider = provider}- old := *Conf.Sync- key := append([]byte(nil), Conf.Repo.Key...)+ old := *Conf.Sync.Load()+ key := append([]byte(nil), Conf.Repo.Load().Key...)if err := ClearSyncProviderConfig(provider); err != nil {t.Fatal(err)}- if Conf.Sync.Enabled == active || Conf.Sync.Provider != old.Provider || Conf.Sync.AssetDownloadMode != 1 || !reflect.DeepEqual(Conf.Repo.Key, key) {+ if Conf.Sync.Load().Enabled == active || Conf.Sync.Load().Provider != old.Provider || Conf.Sync.Load().AssetDownloadMode != 1 || !reflect.DeepEqual(Conf.Repo.Load().Key, key) {t.Fatal("clear changed unrelated preferences or failed to disable the current service")}if provider == conf.ProviderS3 {- if Conf.Sync.S3.Endpoint != "" || Conf.Sync.S3.AccessKey != "" || Conf.Sync.S3.SecretKey != "" || Conf.Sync.S3.Bucket != "" || Conf.Sync.S3.Region != "" || Conf.Sync.S3.Timeout < 7 {+ if Conf.Sync.Load().S3.Endpoint != "" || Conf.Sync.Load().S3.AccessKey != "" || Conf.Sync.Load().S3.SecretKey != "" || Conf.Sync.Load().S3.Bucket != "" || Conf.Sync.Load().S3.Region != "" || Conf.Sync.Load().S3.Timeout < 7 {t.Fatal("S3 configuration was not cleared")}- } else if Conf.Sync.S3 != old.S3 {+ } else if !reflect.DeepEqual(Conf.Sync.Load().S3, old.S3) {t.Fatal("unrelated S3 configuration changed")}if provider == conf.ProviderWebDAV {- if Conf.Sync.WebDAV.Endpoint != "" || Conf.Sync.WebDAV.Username != "" || Conf.Sync.WebDAV.Password != "" || Conf.Sync.WebDAV.Timeout < 7 {+ if Conf.Sync.Load().WebDAV.Endpoint != "" || Conf.Sync.Load().WebDAV.Username != "" || Conf.Sync.Load().WebDAV.Password != "" || Conf.Sync.Load().WebDAV.Timeout < 7 {t.Fatal("WebDAV configuration was not cleared")}- } else if Conf.Sync.WebDAV != old.WebDAV {+ } else if !reflect.DeepEqual(Conf.Sync.Load().WebDAV, old.WebDAV) {t.Fatal("unrelated WebDAV configuration changed")}if provider == conf.ProviderLocal {- if Conf.Sync.Local.Endpoint != "" || Conf.Sync.Local.Timeout < 7 {+ if Conf.Sync.Load().Local.Endpoint != "" || Conf.Sync.Load().Local.Timeout < 7 {t.Fatal("local configuration was not cleared")}- } else if Conf.Sync.Local != old.Local {+ } else if !reflect.DeepEqual(Conf.Sync.Load().Local, old.Local) {t.Fatal("unrelated local configuration changed")}data, err := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))@@ -75,7 +81,7 @@ func TestClearSyncProviderConfiguration(t *testing.T) {t.Fatal(err)}var saved AppConf- if err = json.Unmarshal(data, &saved); err != nil || !reflect.DeepEqual(saved.Sync, Conf.Sync) {+ if err = json.Unmarshal(data, &saved); err != nil || !reflect.DeepEqual(saved.Sync.Load(), Conf.Sync.Load()) {t.Fatalf("cleared configuration was not persisted: %v", err)}})@@ -85,15 +91,15 @@ func TestClearSyncProviderConfiguration(t *testing.T) {func TestClearSyncProviderConfigurationFailure(t *testing.T) {prepareSyncConfigClearTest(t)- Conf.Sync.Provider = conf.ProviderS3- previous := Conf.Sync+ Conf.Sync.Load().Provider = conf.ProviderS3+ previous := Conf.Sync.Load()for _, provider := range []int{-1, 0, 1, 5} {- if err := ClearSyncProviderConfig(provider); err == nil || Conf.Sync != previous {+ if err := ClearSyncProviderConfig(provider); err == nil || Conf.Sync.Load() != previous {t.Fatal("invalid provider changed configuration")}}util.ReadOnly = true- if err := ClearSyncProviderConfig(conf.ProviderS3); err == nil || Conf.Sync != previous {+ if err := ClearSyncProviderConfig(conf.ProviderS3); err == nil || Conf.Sync.Load() != previous {t.Fatal("readonly clear changed configuration")}util.ReadOnly = false@@ -103,7 +109,7 @@ func TestClearSyncProviderConfigurationFailure(t *testing.T) {if err := os.Mkdir(filepath.Join(util.ConfDir, "conf.json"), 0755); err != nil {t.Fatal(err)}- if err := ClearSyncProviderConfig(conf.ProviderS3); err == nil || Conf.Sync != previous || !Conf.Sync.Enabled {+ if err := ClearSyncProviderConfig(conf.ProviderS3); err == nil || Conf.Sync.Load() != previous || !Conf.Sync.Load().Enabled {t.Fatal("failed persistence discarded the active configuration")}}diff --git a/kernel/model/sync_config_test.go b/kernel/model/sync_config_test.goindex 9d787c1528..dee87e5d53 100644--- a/kernel/model/sync_config_test.go+++ b/kernel/model/sync_config_test.go@@ -25,8 +25,8 @@ import (func TestCheckSyncPreservesEnabledWithoutUser(t *testing.T) {originalConf := ConfConf = NewAppConf()- Conf.Sync = conf.NewSync()- Conf.Sync.Enabled = true+ Conf.Sync.Store(conf.NewSync())+ Conf.Sync.Load().Enabled = truet.Cleanup(func() {Conf = originalConf})@@ -34,7 +34,7 @@ func TestCheckSyncPreservesEnabledWithoutUser(t *testing.T) {if checkSync(false, false, true) {t.Fatal("sync must not start without a user")}- if !Conf.Sync.Enabled {+ if !Conf.Sync.Load().Enabled {t.Fatal("sync configuration must remain enabled without a user")}}diff --git a/kernel/model/sync_directory_test.go b/kernel/model/sync_directory_test.goindex 5158eec0b9..81d4b68c72 100644--- a/kernel/model/sync_directory_test.go+++ b/kernel/model/sync_directory_test.go@@ -30,11 +30,16 @@ func prepareSyncDirectoryTest(t *testing.T) {t.Fatal(err)}Conf = NewAppConf()- Conf.Sync, Conf.Repo, Conf.System = conf.NewSync(), conf.NewRepo(), conf.NewSystem()- Conf.Sync.Provider = conf.ProviderS3- Conf.Sync.S3 = &conf.S3{Bucket: "notes.backup", Region: "us-east-1", Timeout: 5, PathStyle: true,+ {+ confSectionValue0, confSectionValue1, confSectionValue2 := conf.NewSync(), conf.NewRepo(), conf.NewSystem()+ Conf.Sync.Store(confSectionValue0)+ Conf.Repo.Store(confSectionValue1)+ Conf.System.Store(confSectionValue2)+ }+ Conf.Sync.Load().Provider = conf.ProviderS3+ Conf.Sync.Load().S3 = &conf.S3{Bucket: "notes.backup", Region: "us-east-1", Timeout: 5, PathStyle: true,AccessKey: "test-key", SecretKey: "test-secret"}- Conf.Repo.Key = []byte("0123456789abcdef0123456789abcdef")+ Conf.Repo.Load().Key = []byte("0123456789abcdef0123456789abcdef")}func TestS3DirectoryListingPreservesConfiguration(t *testing.T) {@@ -63,7 +68,7 @@ func TestS3DirectoryListingPreservesConfiguration(t *testing.T) {fmt.Fprintf(w, `<ListAllMyBucketsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Buckets>%s</Buckets></ListAllMyBucketsResult>`, bucket)}))defer server.Close()- Conf.Sync.S3.Endpoint, Conf.Sync.CloudName = server.URL, name+ Conf.Sync.Load().S3.Endpoint, Conf.Sync.Load().CloudName = server.URL, nameConf.Save()confPath := filepath.Join(util.ConfDir, "conf.json")before, err := os.ReadFile(confPath)@@ -83,12 +88,12 @@ func TestS3DirectoryListingPreservesConfiguration(t *testing.T) {t.Fatalf("unexpected fallback directory: %+v", dirs)}after, err := os.ReadFile(confPath)- if err != nil || !bytes.Equal(before, after) || Conf.Sync.CloudName != name || lanSyncScope() != scope {- t.Fatalf("listing changed configuration or LAN scope: name=%q, err=%v", Conf.Sync.CloudName, err)+ if err != nil || !bytes.Equal(before, after) || Conf.Sync.Load().CloudName != name || lanSyncScope() != scope {+ t.Fatalf("listing changed configuration or LAN scope: name=%q, err=%v", Conf.Sync.Load().CloudName, err)}if name == "work" && result == "matched" {for _, provider := range []int{conf.ProviderSiYuan, conf.ProviderLocal, conf.ProviderWebDAV} {- if err = SetSyncProvider(provider, false); err != nil || Conf.Sync.CloudName != name {+ if err = SetSyncProvider(provider, false); err != nil || Conf.Sync.Load().CloudName != name {t.Fatalf("provider %d did not retain the chosen directory: %v", provider, err)}}@@ -100,7 +105,7 @@ func TestS3DirectoryListingPreservesConfiguration(t *testing.T) {func TestS3DirectorySelectionIsRejected(t *testing.T) {prepareSyncDirectoryTest(t)- Conf.Sync.CloudName = "work"+ Conf.Sync.Load().CloudName = "work"Conf.Save()confPath := filepath.Join(util.ConfDir, "conf.json")before, err := os.ReadFile(confPath)@@ -113,13 +118,13 @@ func TestS3DirectorySelectionIsRejected(t *testing.T) {}}after, err := os.ReadFile(confPath)- if err != nil || !bytes.Equal(before, after) || Conf.Sync.CloudName != "work" {+ if err != nil || !bytes.Equal(before, after) || Conf.Sync.Load().CloudName != "work" {t.Fatalf("rejected selection changed configuration: %v", err)}for _, provider := range []int{conf.ProviderSiYuan, conf.ProviderLocal, conf.ProviderWebDAV} {- Conf.Sync.Provider = provider+ Conf.Sync.Load().Provider = providername := fmt.Sprintf("chosen-%d", provider)- if err = SetCloudSyncDir(name); err != nil || Conf.Sync.CloudName != name {+ if err = SetCloudSyncDir(name); err != nil || Conf.Sync.Load().CloudName != name {t.Fatalf("provider %d cannot select a directory: %v", provider, err)}}@@ -127,17 +132,17 @@ func TestS3DirectorySelectionIsRejected(t *testing.T) {func TestS3SyncIgnoresDirectoryValidation(t *testing.T) {prepareSyncDirectoryTest(t)- Conf.Sync.Enabled = true+ Conf.Sync.Load().Enabled = trueConf.SetUser(&conf.User{UserId: "sync-test", UserSiYuanOneTimePayStatus: 1})for _, name := range []string{"notes.backup", ""} {- Conf.Sync.CloudName = name+ Conf.Sync.Load().CloudName = nameif !checkSync(false, false, true) {t.Fatalf("S3 sync rejected an unused directory name: %q", name)}- Conf.Sync.Provider = conf.ProviderWebDAV+ Conf.Sync.Load().Provider = conf.ProviderWebDAVif checkSync(false, false, false) {t.Fatalf("WebDAV sync accepted an invalid directory: %q", name)}- Conf.Sync.Provider = conf.ProviderS3+ Conf.Sync.Load().Provider = conf.ProviderS3}}diff --git a/kernel/model/sync_error_test.go b/kernel/model/sync_error_test.goindex 8a73f34e99..f3662da86e 100644--- a/kernel/model/sync_error_test.go+++ b/kernel/model/sync_error_test.go@@ -48,7 +48,7 @@ func TestCloudLockErrorDetail(t *testing.T) {func TestFormatRepoCloudLockError(t *testing.T) {previousConf, previousLangs := Conf, util.Langst.Cleanup(func() { Conf, util.Langs = previousConf, previousLangs })- Conf = &AppConf{Lang: "en", Sync: &conf.Sync{Provider: conf.ProviderSiYuan}}+ Conf = &AppConf{Lang: "en", Sync: NewConfSection(&conf.Sync{Provider: conf.ProviderSiYuan})}util.Langs = map[string]map[int]string{"en": {24: "timeout", 31: "auth", 188: "lock failed", 189: "another device", 249: "forbidden", 408: "DNS failed",}}@@ -83,7 +83,7 @@ func TestFormatRepoCloudLockError(t *testing.T) {func TestFormatRepoPermissionError(t *testing.T) {previousConf, previousLangs := Conf, util.Langst.Cleanup(func() { Conf, util.Langs = previousConf, previousLangs })- Conf = &AppConf{Lang: "en", Sync: &conf.Sync{Provider: conf.ProviderS3}}+ Conf = &AppConf{Lang: "en", Sync: NewConfSection(&conf.Sync{Provider: conf.ProviderS3})}util.Langs = map[string]map[int]string{"en": {33: "check workspace permissions"}}for _, message := range []string{"Access is denied.", "access is denied", "ACCESS IS DENIED", "permission denied"} {t.Run(message, func(t *testing.T) {diff --git a/kernel/model/sync_mutation_test.go b/kernel/model/sync_mutation_test.goindex 3a72615cba..0cc2eb600f 100644--- a/kernel/model/sync_mutation_test.go+++ b/kernel/model/sync_mutation_test.go@@ -21,7 +21,7 @@ func setupSyncMutationTest(t *testing.T) {oldPlan := syncPlanTimesyncPlanTimeLock.Unlock()Conf, util.DataDir = NewAppConf(), t.TempDir()- Conf.Sync = conf.NewSync()+ Conf.Sync.Store(conf.NewSync())util.SnippetsPath = filepath.Join(util.DataDir, "snippets")t.Cleanup(func() {pendingSync.mu.Lock()@@ -61,7 +61,7 @@ func assertSyncMutation(t *testing.T, want bool, mutate func() error) {syncPlanTimeLock.Lock()delay := time.Until(syncPlanTime)syncPlanTimeLock.Unlock()- if want && (syncSameCount.Load() != 0 || delay > time.Duration(Conf.Sync.Interval)*time.Second) {+ if want && (syncSameCount.Load() != 0 || delay > time.Duration(Conf.Sync.Load().Interval)*time.Second) {t.Fatalf("mutation did not reset backoff: count=%d, delay=%v", syncSameCount.Load(), delay)}if !want && (syncSameCount.Load() != 10 || delay < 1000*time.Minute) {@@ -167,7 +167,7 @@ func TestPackageRemovalSyncMutation(t *testing.T) {func TestFlashcardDeckSyncMutation(t *testing.T) {setupSyncMutationTest(t)- Conf.Flashcard = conf.NewFlashcard()+ Conf.Flashcard.Store(conf.NewFlashcard())oldDecks := DecksDecks = map[string]*riff.Deck{}t.Cleanup(func() { Decks = oldDecks })@@ -185,7 +185,7 @@ func TestFlashcardDeckSyncMutation(t *testing.T) {func TestFlashcardReviewSyncAfterLogFailure(t *testing.T) {setupSyncMutationTest(t)- Conf.Flashcard = conf.NewFlashcard()+ Conf.Flashcard.Store(conf.NewFlashcard())oldDecks, oldReviews, oldSkipped := Decks, reviewCardCache, skipCardCacheDecks, reviewCardCache, skipCardCache = map[string]*riff.Deck{}, map[string]riff.Card{}, map[string]riff.Card{}oldDBPath := util.BlockTreeDBPath@@ -217,7 +217,7 @@ func TestFlashcardReviewSyncAfterLogFailure(t *testing.T) {}return nil})- loaded, err := riff.LoadDeck(getRiffDir(), deck.ID, Conf.Flashcard.RequestRetention, Conf.Flashcard.MaximumInterval, Conf.Flashcard.Weights)+ loaded, err := riff.LoadDeck(getRiffDir(), deck.ID, Conf.Flashcard.Load().RequestRetention, Conf.Flashcard.Load().MaximumInterval, Conf.Flashcard.Load().Weights)if err != nil {t.Fatal(err)}diff --git a/kernel/model/sync_perception.go b/kernel/model/sync_perception.goindex 95e7e27a2a..6cc12e445f 100644--- a/kernel/model/sync_perception.go+++ b/kernel/model/sync_perception.go@@ -43,8 +43,10 @@ func syncCloudAlreadyApplied(repoPath, latestID string) (bool, error) {}func syncDataFromCloud() {+ confSyncSnapshot := Conf.LoadSync()+defer logging.Recover()- if !Conf.Sync.Perception || conf.ProviderSiYuan != Conf.Sync.Provider || !checkSync(false, false, false) {+ if !confSyncSnapshot.Perception || conf.ProviderSiYuan != confSyncSnapshot.Provider || !checkSync(false, false, false) {return}scope := lanSyncScope()diff --git a/kernel/model/sync_perception_test.go b/kernel/model/sync_perception_test.goindex e74061bea9..e0baf11105 100644--- a/kernel/model/sync_perception_test.go+++ b/kernel/model/sync_perception_test.go@@ -186,8 +186,8 @@ func TestSyncPerceptionDelayedNotificationPreservesLocalEdit(t *testing.T) {a.index()prepareSyncDirectoryTest(t)- Conf.Sync.Provider, Conf.Sync.CloudName, Conf.Sync.Enabled = conf.ProviderLocal, "main", true- Conf.Sync.Local = &conf.Local{Endpoint: "perception-test"}+ Conf.Sync.Load().Provider, Conf.Sync.Load().CloudName, Conf.Sync.Load().Enabled = conf.ProviderLocal, "main", true+ Conf.Sync.Load().Local = &conf.Local{Endpoint: "perception-test"}Conf.User = &conf.User{UserId: "perception-test", UserSiYuanOneTimePayStatus: 1}util.RepoDir = a.repo.PathpreviousRequests := syncRemoteRequests@@ -195,20 +195,20 @@ func TestSyncPerceptionDelayedNotificationPreservesLocalEdit(t *testing.T) {syncRemoteRequests = newSyncRemoteDeduper(time.Minute)scope := lanSyncScope()for _, mode := range []int{2, 3} {- Conf.Sync.Mode = mode+ Conf.Sync.Load().Mode = modesyncDataFromRemote(scope, latest.ID)if syncRemoteRequests.isCompleted(scope, latest.ID) {t.Fatal("skipped automatic sync was recorded as completed")}}- Conf.Sync.Mode = 1+ Conf.Sync.Load().Mode = 1for range 2 {// 丢弃内存缓存模拟进程重启,仍需通过持久化同步点识别延迟及重复通知。syncRemoteRequests = newSyncRemoteDeduper(time.Minute)for range 2 {syncDataFromRemote(lanSyncScope(), latest.ID)a.assertContent("doc.txt", "still editing locally")- if Conf.Sync.Synced != 0 {+ if Conf.Sync.Load().Synced != 0 {t.Fatal("already applied cloud version started another sync")}}diff --git a/kernel/model/sync_plugin_rename_uninstall_test.go b/kernel/model/sync_plugin_rename_uninstall_test.goindex 2ad7b6e6d2..bd097ab70c 100644--- a/kernel/model/sync_plugin_rename_uninstall_test.go+++ b/kernel/model/sync_plugin_rename_uninstall_test.go@@ -39,8 +39,8 @@ func setupSyncMergePluginTest(t *testing.T) {}Conf = NewAppConf()- Conf.System = conf.NewSystem()- Conf.Sync = conf.NewSync()+ Conf.System.Store(conf.NewSystem())+ Conf.Sync.Store(conf.NewSync())Conf.NotebookCrypto = conf.NewNotebookCrypto()logging.SetLogPath(util.LogPath)diff --git a/kernel/model/sync_provider_completion_test.go b/kernel/model/sync_provider_completion_test.goindex 3b13dae55d..cb857d80ba 100644--- a/kernel/model/sync_provider_completion_test.go+++ b/kernel/model/sync_provider_completion_test.go@@ -40,15 +40,15 @@ func TestSyncProviderCompletionPreservesHistory(t *testing.T) {t.Fatal(err)}// 保留缺失历史内容的状态,覆盖配置恢复后已经显示全部下载的情况。- Conf.Sync.AssetDownloadMode = mode- key := append([]byte(nil), Conf.Repo.Key...)+ Conf.Sync.Load().AssetDownloadMode = mode+ key := append([]byte(nil), Conf.Repo.Load().Key...)if err = SetSyncProvider(conf.ProviderS3, false); err == nil {t.Fatal("legacy request unexpectedly downloaded missing content")}if err = SetSyncProvider(conf.ProviderS3, true); err != nil {t.Fatal(err)}- if Conf.Sync.Provider != conf.ProviderS3 || Conf.Sync.AssetDownloadMode != mode || !bytes.Equal(Conf.Repo.Key, key) {+ if Conf.Sync.Load().Provider != conf.ProviderS3 || Conf.Sync.Load().AssetDownloadMode != mode || !bytes.Equal(Conf.Repo.Load().Key, key) {t.Fatal("completion changed the mode or recovery key")}if incomplete, err := partial.HasIncompleteSnapshots(); err != nil || incomplete {@@ -73,14 +73,14 @@ func TestSyncProviderCompletionFailurePreservesSource(t *testing.T) {t.Fatal(err)}if failure == "offline" {- Conf.Sync.Enabled = false+ Conf.Sync.Load().Enabled = false} else if failure == "missing-current-chunk" {files, err := deferredSyncAssets()if err != nil || len(files) != 1 {t.Fatalf("expected deferred asset: %v %v", files, err)}chunk := files[0].Chunks[0]- if err = os.Remove(filepath.Join(Conf.Sync.Local.Endpoint, "main", "objects", chunk[:2], chunk[2:])); err != nil {+ if err = os.Remove(filepath.Join(Conf.Sync.Load().Local.Endpoint, "main", "objects", chunk[:2], chunk[2:])); err != nil {t.Fatal(err)}} else {@@ -97,11 +97,11 @@ func TestSyncProviderCompletionFailurePreservesSource(t *testing.T) {if err != nil {t.Fatal(err)}- key := append([]byte(nil), Conf.Repo.Key...)+ key := append([]byte(nil), Conf.Repo.Load().Key...)if err = SetSyncProvider(conf.ProviderS3, true); err == nil {t.Fatal("failed completion allowed source change")}- if Conf.Sync.Provider != conf.ProviderLocal || Conf.Sync.AssetDownloadMode != 1 || !bytes.Equal(Conf.Repo.Key, key) {+ if Conf.Sync.Load().Provider != conf.ProviderLocal || Conf.Sync.Load().AssetDownloadMode != 1 || !bytes.Equal(Conf.Repo.Load().Key, key) {t.Fatal("failed completion changed source, mode or key")}remaining, err := os.ReadFile(assetDownloadStatePath())@@ -172,7 +172,7 @@ func TestSyncProviderCompletionHistoricalDocument(t *testing.T) {t.Fatal(err)}if !available {- if err = os.Remove(filepath.Join(Conf.Sync.Local.Endpoint, "main", "objects", chunk[:2], chunk[2:])); err != nil {+ if err = os.Remove(filepath.Join(Conf.Sync.Load().Local.Endpoint, "main", "objects", chunk[:2], chunk[2:])); err != nil {t.Fatal(err)}}@@ -189,7 +189,7 @@ func TestSyncProviderCompletionHistoricalDocument(t *testing.T) {t.Fatalf("historical document unavailable: %q %v", data, err)}}- if Conf.Sync.Provider != provider || Conf.Sync.AssetDownloadMode != 0 {+ if Conf.Sync.Load().Provider != provider || Conf.Sync.Load().AssetDownloadMode != 0 {t.Fatal("unexpected provider or download mode")}if data, err := os.ReadFile(filepath.Join(util.DataDir, "history.txt")); err != nil || string(data) != "current document contents are different" {@@ -204,7 +204,7 @@ func TestSyncProviderCompletionOfflineCompleteRepo(t *testing.T) {if err := SetSyncAssetDownloadMode(0); err != nil {t.Fatal(err)}- Conf.Sync.Enabled = false+ Conf.Sync.Load().Enabled = falseif err := SetSyncProvider(conf.ProviderS3, true); err != nil {t.Fatalf("complete repository should switch without cloud access: %v", err)}diff --git a/kernel/model/sync_provider_validation_test.go b/kernel/model/sync_provider_validation_test.goindex 7df0017100..eb780e1cd5 100644--- a/kernel/model/sync_provider_validation_test.go+++ b/kernel/model/sync_provider_validation_test.go@@ -14,16 +14,16 @@ func TestThirdPartySyncAddressValidation(t *testing.T) {for _, provider := range []int{conf.ProviderWebDAV, conf.ProviderLocal} {t.Run(conf.ProviderToStr(provider), func(t *testing.T) {prepareSyncDirectoryTest(t)- Conf.Sync.Provider, Conf.Sync.Enabled = provider, true- Conf.Sync.WebDAV = &conf.WebDAV{Endpoint: "https://dav.example", Username: "old", Password: "secret"}- Conf.Sync.Local = &conf.Local{Endpoint: t.TempDir()}+ Conf.Sync.Load().Provider, Conf.Sync.Load().Enabled = provider, true+ Conf.Sync.Load().WebDAV = &conf.WebDAV{Endpoint: "https://dav.example", Username: "old", Password: "secret"}+ Conf.Sync.Load().Local = &conf.Local{Endpoint: t.TempDir()}Conf.Save()configPath := filepath.Join(util.ConfDir, "conf.json")before, err := os.ReadFile(configPath)if err != nil {t.Fatal(err)}- oldDAV, oldLocal := Conf.Sync.WebDAV, Conf.Sync.Local+ oldDAV, oldLocal := Conf.Sync.Load().WebDAV, Conf.Sync.Load().Localvalues := []string{"", " \t\n "}if provider == conf.ProviderWebDAV {values = append(values, "https://", "ftp://dav.example", "https://bad host/")@@ -34,7 +34,7 @@ func TestThirdPartySyncAddressValidation(t *testing.T) {} else {err = SetSyncProviderLocal(&conf.Local{Endpoint: value})}- if err == nil || !Conf.Sync.Enabled || Conf.Sync.WebDAV != oldDAV || Conf.Sync.Local != oldLocal {+ if err == nil || !Conf.Sync.Load().Enabled || Conf.Sync.Load().WebDAV != oldDAV || Conf.Sync.Load().Local != oldLocal {t.Fatalf("invalid %s address %q changed configuration: %v", conf.ProviderToStr(provider), value, err)}after, readErr := os.ReadFile(configPath)@@ -42,11 +42,11 @@ func TestThirdPartySyncAddressValidation(t *testing.T) {t.Fatal("rejected address changed persisted configuration")}}- Conf.Sync.WebDAV, Conf.Sync.Local = &conf.WebDAV{}, &conf.Local{}+ Conf.Sync.Load().WebDAV, Conf.Sync.Load().Local = &conf.WebDAV{}, &conf.Local{}if _, err = newCloudRepositoryWithAssetSourceLocked(); err == nil {t.Fatal("cloud operations accepted an existing empty address")}- if _, err = newSyncRepositoryWithAssetSourceLocked(); err == nil || !Conf.Sync.Enabled {+ if _, err = newSyncRepositoryWithAssetSourceLocked(); err == nil || !Conf.Sync.Load().Enabled {t.Fatal("sync validation failed to preserve the enabled flag")}if _, err = newRepository(); err != nil {@@ -63,7 +63,7 @@ func TestThirdPartySyncAddressCompatibility(t *testing.T) {if err := SetSyncProviderWebDAV(candidate); err != nil {t.Fatalf("anonymous WebDAV address %q was rejected: %v", endpoint, err)}- if Conf.Sync.WebDAV.Endpoint != util.NormalizeEndpoint(endpoint) || Conf.Sync.WebDAV.Username != "" || Conf.Sync.WebDAV.Password != "" {+ if Conf.Sync.Load().WebDAV.Endpoint != util.NormalizeEndpoint(endpoint) || Conf.Sync.Load().WebDAV.Username != "" || Conf.Sync.Load().WebDAV.Password != "" {t.Fatal("anonymous access or endpoint normalization changed")}}diff --git a/kernel/model/sync_s3_validation_test.go b/kernel/model/sync_s3_validation_test.goindex 0b676add3e..01d9e70f4e 100644--- a/kernel/model/sync_s3_validation_test.go+++ b/kernel/model/sync_s3_validation_test.go@@ -38,7 +38,7 @@ func TestS3ConfigurationValidation(t *testing.T) {candidate.Endpoint = "https://"message = Conf.Language(249)}- Conf.Sync.S3 = &valid+ Conf.Sync.Load().S3 = &validConf.Save()path := filepath.Join(util.ConfDir, "conf.json")before, err := os.ReadFile(path)@@ -49,10 +49,10 @@ func TestS3ConfigurationValidation(t *testing.T) {t.Fatalf("expected localized configuration error: %v", err)}after, err := os.ReadFile(path)- if err != nil || !bytes.Equal(before, after) || Conf.Sync.S3 != &valid {+ if err != nil || !bytes.Equal(before, after) || Conf.Sync.Load().S3 != &valid {t.Fatal("invalid configuration changed the saved settings")}- Conf.Sync.S3 = &candidate+ Conf.Sync.Load().S3 = &candidateif _, err = GetCloudRepoTagSnapshots(); err == nil || err.Error() != message {t.Fatalf("cloud tags did not reject invalid settings: %v", err)}@@ -73,7 +73,7 @@ func TestS3ConfigurationValidation(t *testing.T) {if err := validateSyncS3(nil); err == nil || err.Error() != Conf.Language(142) {t.Fatalf("expected missing-input error for nil configuration: %v", err)}- Conf.Sync.S3 = &conf.S3{}+ Conf.Sync.Load().S3 = &conf.S3{}if _, err := newRepository(); err != nil {t.Fatalf("incomplete cloud settings blocked the local repository: %v", err)}diff --git a/kernel/model/table_cell_rich_test.go b/kernel/model/table_cell_rich_test.goindex f27c7c23a8..2476d85d01 100644--- a/kernel/model/table_cell_rich_test.go+++ b/kernel/model/table_cell_rich_test.go@@ -19,8 +19,8 @@ import (func TestTableCellRichDocumentReaders(t *testing.T) {originalConf := ConfConf = NewAppConf()- Conf.Editor = conf.NewEditor()- Conf.Export = conf.NewExport()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Export.Store(conf.NewExport())t.Cleanup(func() { Conf = originalConf })legacy, err := os.ReadFile("../treenode/testdata/table-cell-legacy.sy")if nil != err {@@ -84,8 +84,8 @@ func TestTableCellRichDocumentReaders(t *testing.T) {func TestLegacyTableAlignmentReadersAndExports(t *testing.T) {originalConf := ConfConf = NewAppConf()- Conf.Editor = conf.NewEditor()- Conf.Export = conf.NewExport()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Export.Store(conf.NewExport())t.Cleanup(func() { Conf = originalConf })legacy, err := os.ReadFile("../treenode/testdata/table-alignment-legacy.sy")if err != nil {diff --git a/kernel/model/tabs_test.go b/kernel/model/tabs_test.goindex 424a6ff5f9..6d8719d300 100644--- a/kernel/model/tabs_test.go+++ b/kernel/model/tabs_test.go@@ -33,12 +33,12 @@ func TestTabTitleAssetScanRewriteAndExport(t *testing.T) {t.Fatalf("title rewrite: %s", item.TabItemTitle)}oldConf := Conf- Conf = &AppConf{Export: &conf.Export{+ Conf = &AppConf{Export: NewConfSection(&conf.Export{RemoveAssetsID: true,- }}+ })}t.Cleanup(func() { Conf = oldConf })oldNew, newOld := map[string]string{}, map[string]string{}- removeAssetsID(tree, oldNew, newOld, Conf.Export.RemoveAssetsID)+ removeAssetsID(tree, oldNew, newOld, Conf.Export.Load().RemoveAssetsID)if !strings.Contains(item.TabItemTitle, "assets/renamed.png") || strings.Contains(item.TabItemTitle, "asset01") || item.FirstChild != body {t.Fatalf("export title asset: %s", item.TabItemTitle)}diff --git a/kernel/model/tag.go b/kernel/model/tag.goindex 35cb5ebbf1..0cf71f7d85 100644--- a/kernel/model/tag.go+++ b/kernel/model/tag.go@@ -248,6 +248,8 @@ type Tag struct {type Tags []*Tagfunc BuildTags(ignoreMaxListHintArg bool, appID string, sortVal int) (ret *Tags) {+ confFileTreeSnapshot := Conf.LoadFileTree()+FlushTxQueue()sql.FlushQueue()@@ -265,9 +267,9 @@ func BuildTags(ignoreMaxListHintArg bool, appID string, sortVal int) (ret *Tags)for _, tag := range tags {*tmp = append(*tmp, tag)countTag(tag, &total)- if Conf.FileTree.MaxListCount < total && !ignoreMaxListHintArg {- if nil == util.NotificationsCfg || util.NotificationsCfg.TagMaxList {- util.PushMsgWithApp(appID, fmt.Sprintf(Conf.Language(243), Conf.FileTree.MaxListCount), 7000)+ if confFileTreeSnapshot.MaxListCount < total && !ignoreMaxListHintArg {+ if nil == util.NotificationsCfg.Load() || util.NotificationsCfg.Load().TagMaxList {+ util.PushMsgWithApp(appID, fmt.Sprintf(Conf.Language(243), confFileTreeSnapshot.MaxListCount), 7000)}break}@@ -326,7 +328,7 @@ func SearchTags(keyword string) (ret []string) {continue}- _, t := search.MarkText(label, keyword, 1024, Conf.Search.CaseSensitive)+ _, t := search.MarkText(label, keyword, 1024, Conf.Search.Load().CaseSensitive)ret = append(ret, t)}sort.Strings(ret)@@ -336,7 +338,7 @@ func SearchTags(keyword string) (ret []string) {func labelBlocksByKeyword(keyword string) (ret map[string]TagBlocks) {ret = map[string]TagBlocks{}- tags := sql.QueryTagSpansByKeyword(keyword, Conf.Search.Limit)+ tags := sql.QueryTagSpansByKeyword(keyword, Conf.Search.Load().Limit)set := hashset.New()for _, tag := range tags {set.Add(tag.BlockID)diff --git a/kernel/model/template.go b/kernel/model/template.goindex 0d547a1fa3..c3753baf40 100644--- a/kernel/model/template.go+++ b/kernel/model/template.go@@ -215,7 +215,7 @@ func SearchTemplate(keyword string) (ret []*TemplateSearchResult) {content = strings.TrimPrefix(path, templates)content = strings.TrimSuffix(content, ".md")content = filepath.ToSlash(content)- _, content = search.MarkText(content, strings.Join(keywords, search.TermSep), 32, Conf.Search.CaseSensitive)+ _, content = search.MarkText(content, strings.Join(keywords, search.TermSep), 32, Conf.Search.Load().CaseSensitive)relativePath, relErr := filepath.Rel(templates, path)if nil != relErr {return nil@@ -245,7 +245,7 @@ func SearchTemplate(keyword string) (ret []*TemplateSearchResult) {}if hit {content = filepath.ToSlash(content)- _, content = search.MarkText(content, strings.Join(keywords, search.TermSep), 32, Conf.Search.CaseSensitive)+ _, content = search.MarkText(content, strings.Join(keywords, search.TermSep), 32, Conf.Search.Load().CaseSensitive)b := &TemplateSearchResult{Path: filepath.Join(templates, group.Name()), RelativePath: group.Name(), Content: content}results = append(results, &result{item: b, score: score})}diff --git a/kernel/model/template_doc_tree.go b/kernel/model/template_doc_tree.goindex f5cb1c123c..eef2230567 100644--- a/kernel/model/template_doc_tree.go+++ b/kernel/model/template_doc_tree.go@@ -284,11 +284,13 @@ func flattenTemplateDocTreeNodes0(nodes []*TemplateDocTreeNode) (ret []*Template}func (collector *templateDocTreeCollector) validateLocations() error {+ confFileTreeSnapshot := Conf.LoadFileTree()+box := Conf.Box(collector.boxID)if nil == box {return ErrBoxNotFound}- allowCreateDeeper := nil != Conf.FileTree && Conf.FileTree.AllowCreateDeeper+ allowCreateDeeper := nil != confFileTreeSnapshot && confFileTreeSnapshot.AllowCreateDeeperfor _, node := range flattenTemplateDocTreeNodes0(collector.nodes) {if depth := strings.Count(node.path, "/"); 7 < depth && !allowCreateDeeper {return errors.New(Conf.Language(118))diff --git a/kernel/model/template_doc_tree_fts5_test.go b/kernel/model/template_doc_tree_fts5_test.goindex ef974be29b..5907bdcaa1 100644--- a/kernel/model/template_doc_tree_fts5_test.go+++ b/kernel/model/template_doc_tree_fts5_test.go@@ -442,8 +442,8 @@ func runTemplateDocTreeTransactionTestInSubprocess(t *testing.T) bool {func setupTemplateDocTreeTransactionTest(t *testing.T) *fileOperationTestFixture {t.Helper()fixture := setupStructureTransactionTest(t)- Conf.Editor = conf.NewEditor()- Conf.Export = conf.NewExport()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Export.Store(conf.NewExport())originalTempDir := util.TempDiroriginalQueueDir := util.QueueDiroriginalConfDir := util.ConfDirdiff --git a/kernel/model/template_doc_tree_test.go b/kernel/model/template_doc_tree_test.goindex 13f1d3e793..b913300320 100644--- a/kernel/model/template_doc_tree_test.go+++ b/kernel/model/template_doc_tree_test.go@@ -425,8 +425,8 @@ func TestValidateTemplateCallGraphRejectsCyclesAndExcessiveDepth(t *testing.T) {func TestRenderTemplateDocTreeNodesLimitsAggregateOutput(t *testing.T) {setupFileOperationTest(t)- Conf.Editor = conf.NewEditor()- Conf.Export = conf.NewExport()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Export.Store(conf.NewExport())rootTemplate, err := template.New("").Delims(".action{", "}").Parse(`.action{define "one-byte"}x.action{end}`,)@@ -734,11 +734,11 @@ func newTemplateDocTreeInsertTransaction(planID, parentID string) (*Transaction,func writeTemplateDocTreeTestFile(t *testing.T, content string) string {t.Helper()- if nil == Conf.Editor {- Conf.Editor = conf.NewEditor()+ if nil == Conf.Editor.Load() {+ Conf.Editor.Store(conf.NewEditor())}- if nil == Conf.Export {- Conf.Export = conf.NewExport()+ if nil == Conf.Export.Load() {+ Conf.Export.Store(conf.NewExport())}templateDir := filepath.Join(util.DataDir, "templates")if err := os.MkdirAll(templateDir, 0755); nil != err {diff --git a/kernel/model/template_manage_test.go b/kernel/model/template_manage_test.goindex 6efe319c11..6566a0fbdd 100644--- a/kernel/model/template_manage_test.go+++ b/kernel/model/template_manage_test.go@@ -213,8 +213,8 @@ func TestPreviewTemplateUnsavedSource(t *testing.T) {func TestExportTemplateDocumentAttributesAndDirectory(t *testing.T) {fixture := setupFileOperationTest(t)- Conf.Editor = conf.NewEditor()- Conf.Export = conf.NewExport()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Export.Store(conf.NewExport())tree, err := LoadTreeByBlockID(fixture.sourceID)if err != nil {t.Fatal(err)@@ -271,8 +271,8 @@ func TestExportTemplateDocumentAttributesAndDirectory(t *testing.T) {func TestDocSaveAsTemplateInfoAndRememberedAttrs(t *testing.T) {fixture := setupFileOperationTest(t)- Conf.Editor = conf.NewEditor()- Conf.Export = conf.NewExport()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Export.Store(conf.NewExport())info, err := GetDocSaveAsTemplateInfo(fixture.sourceID)if nil != err {@@ -409,7 +409,7 @@ func TestTemplatePackageIdentity(t *testing.T) {previous, previousConf := util.DataDir, Confutil.DataDir = t.TempDir()Conf = NewAppConf()- Conf.Search = conf.NewSearch()+ Conf.Search.Store(conf.NewSearch())t.Cleanup(func() { util.DataDir, Conf = previous, previousConf })root, err := openTemplateRoot()if err != nil {@@ -462,7 +462,11 @@ func TestExportTemplateDocumentAttributeScope(t *testing.T) {} {t.Run(test.name, func(t *testing.T) {fixture := setupFileOperationTest(t)- Conf.Editor, Conf.Export = conf.NewEditor(), conf.NewExport()+ {+ confSectionValue0, confSectionValue1 := conf.NewEditor(), conf.NewExport()+ Conf.Editor.Store(confSectionValue0)+ Conf.Export.Store(confSectionValue1)+ }tree, err := LoadTreeByBlockID(fixture.sourceID)if err != nil {t.Fatal(err)@@ -502,7 +506,11 @@ func TestExportTemplateDocumentAttributeScope(t *testing.T) {func TestTemplateDocumentAttributeFormats(t *testing.T) {setupFileOperationTest(t)- Conf.Editor, Conf.Export = conf.NewEditor(), conf.NewExport()+ {+ confSectionValue0, confSectionValue1 := conf.NewEditor(), conf.NewExport()+ Conf.Editor.Store(confSectionValue0)+ Conf.Export.Store(confSectionValue1)+ }legacy, err := parseTemplateKTree([]byte(`Body{: id="20260718000001-abcdefg" icon="legacy" type="doc"}`))diff --git a/kernel/model/template_test.go b/kernel/model/template_test.goindex b6d85b9d35..97d48eb380 100644--- a/kernel/model/template_test.go+++ b/kernel/model/template_test.go@@ -100,11 +100,11 @@ type templateAttributeViewTestFixture struct {func addTemplateAttributeViewTestFixture(t *testing.T, fixture *fileOperationTestFixture,avID string) *templateAttributeViewTestFixture {t.Helper()- if nil == Conf.Editor {- Conf.Editor = conf.NewEditor()+ if nil == Conf.Editor.Load() {+ Conf.Editor.Store(conf.NewEditor())}- if nil == Conf.Export {- Conf.Export = conf.NewExport()+ if nil == Conf.Export.Load() {+ Conf.Export.Store(conf.NewExport())}if err := os.MkdirAll(filepath.Join(util.DataDir, "templates"), 0755); nil != err {t.Fatalf("create templates directory failed: %v", err)diff --git a/kernel/model/theme.go b/kernel/model/theme.goindex c756d1664d..c4273ad435 100644--- a/kernel/model/theme.go+++ b/kernel/model/theme.go@@ -33,16 +33,18 @@ const maxCSSVarResolveDepth = 64// 将文档中的 CSS 变量替换为具体的主题样式值func fillThemeStyleVar(tree *parse.Tree) {+ confAppearanceSnapshot := Conf.LoadAppearance()+if nil == tree || nil == tree.Root {return}- isDarkMode := 1 == Conf.Appearance.Mode+ isDarkMode := 1 == confAppearanceSnapshot.Modevar themeStyles map[string]stringif isDarkMode {- themeStyles = getThemeStyleVar(Conf.Appearance.ThemeDark, true)+ themeStyles = getThemeStyleVar(confAppearanceSnapshot.ThemeDark, true)} else {- themeStyles = getThemeStyleVar(Conf.Appearance.ThemeLight, false)+ themeStyles = getThemeStyleVar(confAppearanceSnapshot.ThemeLight, false)}inlineStyles, err := GetInlineStyles()if err != nil {diff --git a/kernel/model/theme_test.go b/kernel/model/theme_test.goindex 1b9bfb12a3..90bcb71a3b 100644--- a/kernel/model/theme_test.go+++ b/kernel/model/theme_test.go@@ -114,8 +114,8 @@ func TestFillThemeStyleVarUsesBuiltinOverrides(t *testing.T) {--b3-card-error-color: #020202;--b3-card-error-background: #030303;}`)- Conf.Appearance.Mode = 0- Conf.Appearance.ThemeLight = "daylight"+ Conf.Appearance.Load().Mode = 0+ Conf.Appearance.Load().ThemeLight = "daylight"if _, _, err := SetInlineStylesData(&InlineStyles{Version: InlineStylesVersion,@@ -146,7 +146,7 @@ func TestFillThemeStyleVarUsesBuiltinOverrides(t *testing.T) {t.Fatalf("unexpected builtin inline style export: %s", actual)}for _, mode := range []int{0, 1} {- Conf.Appearance.Mode = mode+ Conf.Appearance.Load().Mode = modefor _, source := range []string{"color: var(--b3-card-error-color); background-color: var(--b3-card-error-background);","color: var(--b3-inline-builtin-error-color, var(--b3-card-error-color)); " +@@ -167,8 +167,8 @@ func TestFillThemeStyleVarUsesBuiltinOverrides(t *testing.T) {func TestFillThemeStyleVarUsesCurrentInlineStyleMode(t *testing.T) {setupThemeTest(t, "midnight", `:root {}`)- Conf.Appearance.Mode = 1- Conf.Appearance.ThemeDark = "midnight"+ Conf.Appearance.Load().Mode = 1+ Conf.Appearance.Load().ThemeDark = "midnight"const id = "20260821000000-abcdefg"if _, _, err := SetInlineStyles([]*InlineStyle{{@@ -190,8 +190,8 @@ func TestFillThemeStyleVarUsesCurrentInlineStyleMode(t *testing.T) {func TestFillThemeStyleVarFallsBackForInvalidInlineStyles(t *testing.T) {setupThemeTest(t, "daylight", `:root { --theme-background: #112233; }`)- Conf.Appearance.Mode = 0- Conf.Appearance.ThemeLight = "daylight"+ Conf.Appearance.Load().Mode = 0+ Conf.Appearance.Load().ThemeLight = "daylight"if err := os.MkdirAll(filepath.Dir(inlineStylesPath()), 0755); err != nil {t.Fatal(err)@@ -224,8 +224,8 @@ func setupThemeTest(t *testing.T, theme, css string) {util.ThemesPath = filepath.Join(tempDir, "themes")util.AppearancePath, util.Mode = filepath.Join(tempDir, "appearance"), "prod"Conf = NewAppConf()- Conf.Appearance = conf.NewAppearance()- Conf.Sync = conf.NewSync()+ Conf.Appearance.Store(conf.NewAppearance())+ Conf.Sync.Store(conf.NewSync())t.Cleanup(func() {util.DataDir, util.ThemesPath, Conf = oldDataDir, oldThemesPath, oldConfutil.AppearancePath, util.Mode = oldAppearancePath, oldModediff --git a/kernel/model/themes_watcher_test.go b/kernel/model/themes_watcher_test.goindex 7d404c77f3..691fea831b 100644--- a/kernel/model/themes_watcher_test.go+++ b/kernel/model/themes_watcher_test.go@@ -47,32 +47,32 @@ func TestWatchThemesCurrentThemeOnly(t *testing.T) {}}Conf = NewAppConf()- Conf.Appearance = conf.NewAppearance()+ Conf.Appearance.Store(conf.NewAppearance())WatchThemes()assertThemesWatchList(t, themesDir, util.AppearancePackagePath("themes", "daylight"))Conf.m.Lock()- Conf.Appearance.Mode = 1+ Conf.Appearance.Load().Mode = 1Conf.m.Unlock()WatchThemes()assertThemesWatchList(t, themesDir, util.AppearancePackagePath("themes", "midnight"))Conf.m.Lock()- Conf.Appearance.ThemeDark = "unused"+ Conf.Appearance.Load().ThemeDark = "unused"Conf.m.Unlock()WatchThemes()assertThemesWatchList(t, themesDir, filepath.Join(themesDir, "unused"))Conf.m.Lock()- Conf.Appearance.Mode = -1+ Conf.Appearance.Load().Mode = -1Conf.m.Unlock()WatchThemes()assertThemesWatchList(t, themesDir)Conf.m.Lock()- Conf.Appearance.Mode = 0- Conf.Appearance.ThemeLight = ".."+ Conf.Appearance.Load().Mode = 0+ Conf.Appearance.Load().ThemeLight = ".."Conf.m.Unlock()WatchThemes()assertThemesWatchList(t, themesDir)diff --git a/kernel/model/transaction_fold_fts5_test.go b/kernel/model/transaction_fold_fts5_test.goindex 2f43706dd6..d90ea61bd3 100644--- a/kernel/model/transaction_fold_fts5_test.go+++ b/kernel/model/transaction_fold_fts5_test.go@@ -469,8 +469,8 @@ func assertFoldMoveState(t *testing.T, rootID string, wantIDs []string, headingIfunc setupFoldTransactionDatabase(t *testing.T, fixture *fileOperationTestFixture) {t.Helper()- Conf.Editor = conf.NewEditor()- Conf.Export = conf.NewExport()+ Conf.Editor.Store(conf.NewEditor())+ Conf.Export.Store(conf.NewExport())originalTempDir := util.TempDiroriginalQueueDir := util.QueueDiroriginalConfDir := util.ConfDirdiff --git a/kernel/model/update_channel.go b/kernel/model/update_channel.goindex aaa90431d9..a4f80b7055 100644--- a/kernel/model/update_channel.go+++ b/kernel/model/update_channel.go@@ -71,7 +71,7 @@ func SetUpdateChannel(channel string) error {if err = filelock.WriteFile(configPath, data); err != nil {return err}- Conf.System.UpdateChannel = channel+ UpdateSystemConf(func(s *conf.System) { s.UpdateChannel = channel })return nil}diff --git a/kernel/model/updater.go b/kernel/model/updater.goindex c639c0e3bc..4380aeecf4 100644--- a/kernel/model/updater.go+++ b/kernel/model/updater.go@@ -237,7 +237,7 @@ func CheckUpdate(showMsg bool) {return}- if Conf.System.IsMicrosoftStore {+ if Conf.System.Load().IsMicrosoftStore {return}@@ -270,6 +270,8 @@ func isVersionUpToDate(releaseVer string) bool {var skipInstallPkgPlatformCached = -1func skipNewVerInstallPkg() bool {+ confSystemSnapshot := Conf.LoadSystem()+if skipInstallPkgPlatformCached == -1 {skipInstallPkgPlatformCached = 0if !gulu.OS.IsWindows() && !gulu.OS.IsDarwin() {@@ -277,7 +279,7 @@ func skipNewVerInstallPkg() bool {} else if util.ISMicrosoftStore || util.ContainerStd != util.Container {skipInstallPkgPlatformCached = 1} else if gulu.OS.IsWindows() {- plat := strings.ToLower(Conf.System.OSPlatform)+ plat := strings.ToLower(confSystemSnapshot.OSPlatform)// Windows 7, 8 and Server 2012 are no longer supported https://github.com/siyuan-note/siyuan/issues/7347if strings.Contains(plat, " 7 ") || strings.Contains(plat, " 8 ") || strings.Contains(plat, "2012") {skipInstallPkgPlatformCached = 1@@ -285,7 +287,7 @@ func skipNewVerInstallPkg() bool {}}- if skipInstallPkgPlatformCached == 1 || !Conf.System.DownloadInstallPkg {+ if skipInstallPkgPlatformCached == 1 || !confSystemSnapshot.DownloadInstallPkg {return true}return falsediff --git a/kernel/model/updater_release.go b/kernel/model/updater_release.goindex 1be67f8134..166595aaf4 100644--- a/kernel/model/updater_release.go+++ b/kernel/model/updater_release.go@@ -79,7 +79,7 @@ var ()func getUpdateRelease(force bool) (*updateRelease, error) {- channel := Conf.System.UpdateChannel+ channel := Conf.System.Load().UpdateChannelif conf.UpdateChannelStable == channel {return getStableUpdateRelease(force)}diff --git a/kernel/model/upload_test.go b/kernel/model/upload_test.goindex 6ab64b0d2a..125a8479f5 100644--- a/kernel/model/upload_test.go+++ b/kernel/model/upload_test.go@@ -53,7 +53,7 @@ func setupAssetUploadTest(t *testing.T) string {t.Helper()originalConf, originalDataDir := Conf, util.DataDirConf = NewAppConf()- Conf.Sync = conf.NewSync()+ Conf.Sync.Store(conf.NewSync())util.DataDir = t.TempDir()t.Cleanup(func() {Conf = originalConfdiff --git a/kernel/model/virtualref_test.go b/kernel/model/virtualref_test.goindex e5c9b902bd..dc858aa9c8 100644--- a/kernel/model/virtualref_test.go+++ b/kernel/model/virtualref_test.go@@ -27,9 +27,9 @@ import (func TestProcessVirtualRefDoesNotMatchHTMLEntity(t *testing.T) {previousConf := ConfConf = NewAppConf()- Conf.Editor = conf.NewEditor()- Conf.Search = conf.NewSearch()- Conf.Editor.VirtualBlockRef = true+ Conf.Editor.Store(conf.NewEditor())+ Conf.Search.Store(conf.NewSearch())+ Conf.Editor.Load().VirtualBlockRef = truet.Cleanup(func() {Conf = previousConf})@@ -73,7 +73,7 @@ func TestProcessVirtualRefDoesNotMatchHTMLEntity(t *testing.T) {func TestMarkReplaceSpanWithSplitReportsFinalMatch(t *testing.T) {previousConf := ConfConf = NewAppConf()- Conf.Search = conf.NewSearch()+ Conf.Search.Store(conf.NewSearch())t.Cleanup(func() {Conf = previousConf})diff --git a/kernel/model/virutalref.go b/kernel/model/virutalref.goindex ab070b0963..d67a48d332 100644--- a/kernel/model/virutalref.go+++ b/kernel/model/virutalref.go@@ -32,6 +32,7 @@ import ("github.com/ClarkThan/ahocorasick""github.com/dgraph-io/ristretto""github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/search""github.com/siyuan-note/siyuan/kernel/sql""github.com/siyuan-note/siyuan/kernel/task"@@ -91,7 +92,7 @@ func putBlockVirtualRefKeywords(blockContent string, root *ast.Node, boxID strincontentTmp := blockContentvar keywordsTmp []string- if !Conf.Search.CaseSensitive {+ if !Conf.Search.Load().CaseSensitive {contentTmp = strings.ToLower(blockContent)for _, keyword := range keywords {keywordsTmp = append(keywordsTmp, strings.ToLower(keyword))@@ -120,7 +121,7 @@ func putBlockVirtualRefKeywords(blockContent string, root *ast.Node, boxID strin}func CacheVirtualBlockRefJob() {- if !Conf.Editor.VirtualBlockRef {+ if !Conf.Editor.Load().VirtualBlockRef {return}task.AppendTask(task.CacheVirtualBlockRef, ResetVirtualBlockRefCache)@@ -131,16 +132,16 @@ func ResetVirtualBlockRefCache() {if nil == Conf {return}- if !Conf.Editor.VirtualBlockRef {+ if !Conf.Editor.Load().VirtualBlockRef {return}searchIgnoreLines := getSearchIgnoreLines()refSearchIgnoreLines := getRefSearchIgnoreLines()- keywords := sql.QueryVirtualRefKeywords(Conf.Search.VirtualRefName, Conf.Search.VirtualRefAlias, Conf.Search.VirtualRefAnchor, Conf.Search.VirtualRefDoc, searchIgnoreLines, refSearchIgnoreLines)+ keywords := sql.QueryVirtualRefKeywords(Conf.Search.Load().VirtualRefName, Conf.Search.Load().VirtualRefAlias, Conf.Search.Load().VirtualRefAnchor, Conf.Search.Load().VirtualRefDoc, searchIgnoreLines, refSearchIgnoreLines)putVirtualRefCache("virtual_ref", keywords, 0)for _, boxID := range treenode.GetOpenedEncryptedBoxIDs() {- boxKeywords := sql.QueryVirtualRefKeywords(Conf.Search.VirtualRefName, Conf.Search.VirtualRefAlias, Conf.Search.VirtualRefAnchor, Conf.Search.VirtualRefDoc, searchIgnoreLines, refSearchIgnoreLines, boxID)+ boxKeywords := sql.QueryVirtualRefKeywords(Conf.Search.Load().VirtualRefName, Conf.Search.Load().VirtualRefAlias, Conf.Search.Load().VirtualRefAnchor, Conf.Search.Load().VirtualRefDoc, searchIgnoreLines, refSearchIgnoreLines, boxID)putVirtualRefCache(boxID+"\x00virtual_ref", boxKeywords, 0)}}@@ -191,8 +192,7 @@ func AddVirtualBlockRefInclude(keyword []string) {if 1 > len(keyword) {return}- Conf.Editor.VirtualBlockRefInclude = addNewKeywords(Conf.Editor.VirtualBlockRefInclude, keyword)- Conf.Save()+ UpdateEditorConf(func(s *conf.Editor) { s.VirtualBlockRefInclude = addNewKeywords(s.VirtualBlockRefInclude, keyword) })ResetVirtualBlockRefCache()}@@ -200,13 +200,12 @@ func AddVirtualBlockRefExclude(keyword []string) {if 1 > len(keyword) {return}- Conf.Editor.VirtualBlockRefExclude = addNewKeywords(Conf.Editor.VirtualBlockRefExclude, keyword)- Conf.Save()+ UpdateEditorConf(func(s *conf.Editor) { s.VirtualBlockRefExclude = addNewKeywords(s.VirtualBlockRefExclude, keyword) })ResetVirtualBlockRefCache()}func processVirtualRef(n *ast.Node, unlinks *[]*ast.Node, virtualBlockRefKeywords []string, refCount map[string]int, luteEngine *lute.Lute) bool {- if !Conf.Editor.VirtualBlockRef || 1 > len(virtualBlockRefKeywords) {+ if !Conf.Editor.Load().VirtualBlockRef || 1 > len(virtualBlockRefKeywords) {return false}@@ -292,7 +291,11 @@ func parseKeywords(keywordsStr string) (keywords []string) {}func getVirtualRefKeywords(root *ast.Node, boxIDs ...string) (ret []string) {- if !Conf.Editor.VirtualBlockRef {+ confEditorSnapshot := Conf.LoadEditor()++ confSearchSnapshot := Conf.LoadSearch()++ if !confEditorSnapshot.VirtualBlockRef {return}@@ -305,18 +308,18 @@ func getVirtualRefKeywords(root *ast.Node, boxIDs ...string) (ret []string) {} else {searchIgnoreLines := getSearchIgnoreLines()refSearchIgnoreLines := getRefSearchIgnoreLines()- ret = sql.QueryVirtualRefKeywords(Conf.Search.VirtualRefName, Conf.Search.VirtualRefAlias,- Conf.Search.VirtualRefAnchor, Conf.Search.VirtualRefDoc, searchIgnoreLines, refSearchIgnoreLines, boxIDs...)+ ret = sql.QueryVirtualRefKeywords(confSearchSnapshot.VirtualRefName, confSearchSnapshot.VirtualRefAlias,+ confSearchSnapshot.VirtualRefAnchor, confSearchSnapshot.VirtualRefDoc, searchIgnoreLines, refSearchIgnoreLines, boxIDs...)putVirtualRefCache(key, ret, 0)}- includes := parseKeywords(Conf.Editor.VirtualBlockRefInclude)+ includes := parseKeywords(confEditorSnapshot.VirtualBlockRefInclude)if 0 < len(includes) {ret = append(ret, includes...)ret = gulu.Str.RemoveDuplicatedElem(ret)}- ret = excludeKeywords(ret, Conf.Editor.VirtualBlockRefExclude)+ ret = excludeKeywords(ret, confEditorSnapshot.VirtualBlockRefExclude)// 虚拟引用排除当前文档名 https://github.com/siyuan-note/siyuan/issues/4537// Virtual references exclude the name and aliases from the current document https://github.com/siyuan-note/siyuan/issues/9204diff --git a/kernel/plugin/api_secrets_vars.go b/kernel/plugin/api_secrets_vars.goindex b7a0fda3b6..c115a58322 100644--- a/kernel/plugin/api_secrets_vars.go+++ b/kernel/plugin/api_secrets_vars.go@@ -37,13 +37,13 @@ func injectSecretsVars(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (secrets := rt.NewObject()lo.Must0(secrets.Set("resolve", rt.ToValue(makeResolver(func(tpl string) string {- return model.Conf.Secrets.Resolve(tpl)+ return model.Conf.Secrets.Load().Resolve(tpl)}))))lo.Must0(siyuan.Set("secrets", secrets))vars := rt.NewObject()lo.Must0(vars.Set("resolve", rt.ToValue(makeResolver(func(tpl string) string {- return model.Conf.Variables.Resolve(tpl)+ return model.Conf.Variables.Load().Resolve(tpl)}))))lo.Must0(siyuan.Set("vars", vars))diff --git a/kernel/search/hanconv_test.go b/kernel/search/hanconv_test.goindex 0316875e3c..3329ac2490 100644--- a/kernel/search/hanconv_test.go+++ b/kernel/search/hanconv_test.go@@ -67,10 +67,10 @@ func TestNormalizeSearchText(t *testing.T) {}func TestEncloseHighlightingHanInsensitive(t *testing.T) {- old := util.SearchHanSensitive- defer func() { util.SearchHanSensitive = old }()+ old := util.SearchHanSensitive.Load()+ defer func() { util.SearchHanSensitive.Store(old) }()- util.SearchHanSensitive = false+ util.SearchHanSensitive.Store(false)got := EncloseHighlighting("詩經研究", []string{"诗经"}, "<mark>", "</mark>", false, false)if want := "<mark>詩經</mark>研究"; want != got {t.Errorf("繁简不敏感高亮 = %q, want %q", got, want)@@ -82,7 +82,7 @@ func TestEncloseHighlightingHanInsensitive(t *testing.T) {t.Errorf("大小写+繁简 = %q, want %q", got, want)}- util.SearchHanSensitive = true+ util.SearchHanSensitive.Store(true)got = EncloseHighlighting("詩經研究", []string{"诗经"}, "<mark>", "</mark>", false, false)if want := "詩經研究"; want != got {t.Errorf("默认(区分繁简)不应高亮,got %q", got)diff --git a/kernel/search/mark.go b/kernel/search/mark.goindex ace88b1046..10038e8849 100644--- a/kernel/search/mark.go+++ b/kernel/search/mark.go@@ -146,7 +146,7 @@ func compileHighlightingRegexp(keywords []string, caseSensitive, splitWords boolif splitWords {wordBoundary = lex.IsASCIILetterNums(gulu.Str.ToBytes(k)) // Improve virtual reference split words https://github.com/siyuan-note/siyuan/issues/7833}- if !util.SearchHanSensitive {+ if !util.SearchHanSensitive.Load() {// 不区分繁简:将关键字逐字符展开为繁简等价字符类,如 "诗经" -> "[诗詩][经經]"k = hanInsensitiveRegexp(k)} else {diff --git a/kernel/search/mark_test.go b/kernel/search/mark_test.goindex b7767ba3eb..215e05c309 100644--- a/kernel/search/mark_test.go+++ b/kernel/search/mark_test.go@@ -23,10 +23,10 @@ import ()func TestMarkTextMatchesRawText(t *testing.T) {- old := util.SearchHanSensitive- util.SearchHanSensitive = true+ old := util.SearchHanSensitive.Load()+ util.SearchHanSensitive.Store(true)t.Cleanup(func() {- util.SearchHanSensitive = old+ util.SearchHanSensitive.Store(old)})tests := []struct {@@ -85,10 +85,10 @@ func TestMarkTextMatchesRawText(t *testing.T) {}func TestEncloseHighlightingRaw(t *testing.T) {- old := util.SearchHanSensitive- util.SearchHanSensitive = true+ old := util.SearchHanSensitive.Load()+ util.SearchHanSensitive.Store(true)t.Cleanup(func() {- util.SearchHanSensitive = old+ util.SearchHanSensitive.Store(old)})start := GetMarkSpanStart(VirtualBlockRefDataType)@@ -179,10 +179,10 @@ func TestEncloseHighlightingRaw(t *testing.T) {}func TestEncloseHighlightingRawHanInsensitive(t *testing.T) {- old := util.SearchHanSensitive- util.SearchHanSensitive = false+ old := util.SearchHanSensitive.Load()+ util.SearchHanSensitive.Store(false)t.Cleanup(func() {- util.SearchHanSensitive = old+ util.SearchHanSensitive.Store(old)})got, matched := EncloseHighlightingRaw("詩經研究", []string{"诗经"}, "<mark>", "</mark>", false, false)diff --git a/kernel/server/plugin_publish_test.go b/kernel/server/plugin_publish_test.goindex 0c5451ea8b..d1a05f1157 100644--- a/kernel/server/plugin_publish_test.go+++ b/kernel/server/plugin_publish_test.go@@ -17,8 +17,8 @@ func TestPluginPublishStaticBoundaries(t *testing.T) {oldData, oldConf := util.DataDir, model.Confutil.DataDir = t.TempDir()model.Conf = model.NewAppConf()- model.Conf.Sync = conf.NewSync()- model.Conf.Bazaar = &conf.Bazaar{Trust: true}+ model.Conf.Sync.Store(conf.NewSync())+ model.Conf.Bazaar.Store(&conf.Bazaar{Trust: true})t.Cleanup(func() { util.DataDir, model.Conf = oldData, oldConf })for name, data := range map[string]string{"plugins/example/plugin.json": `{"name":"example","version":"1.0.0","minAppVersion":"0.0.1","publish":{"resources":["index.html","logo.txt"]}}`,diff --git a/kernel/server/proxy/publish.go b/kernel/server/proxy/publish.goindex 767877b8af..6c7fd3e2ff 100644--- a/kernel/server/proxy/publish.go+++ b/kernel/server/proxy/publish.go@@ -50,22 +50,24 @@ var ()func InitPublishService() (uint16, error) {+ confPublishSnapshot := model.Conf.LoadPublish()+model.InitPublishAccounts()if listener != nil {- if !model.Conf.Publish.Enable {+ if !confPublishSnapshot.Enable {closePublishListener()return 0, nil}if port, err := util.ParsePort(Port); err != nil {return 0, err- } else if port != model.Conf.Publish.Port {+ } else if port != confPublishSnapshot.Port {closePublishListener()initPublishService()}} else {- if !model.Conf.Publish.Enable {+ if !confPublishSnapshot.Enable {return 0, nil}@@ -82,7 +84,7 @@ func initPublishService() {}func initPublishListener() (err error) {- listener, err = net.Listen("tcp", fmt.Sprintf("%s:%d", Host, model.Conf.Publish.Port))+ listener, err = net.Listen("tcp", fmt.Sprintf("%s:%d", Host, model.Conf.Publish.Load().Port))if err != nil {logging.LogErrorf("start listener failed: %s", err)return@@ -196,7 +198,7 @@ func publishAuthRejectResponse(request *http.Request, statusCode, retryAfter int}func (PublishServiceTransport) RoundTrip(request *http.Request) (response *http.Response, err error) {- if model.Conf.Publish.Auth.Enable {+ if model.Conf.Publish.Load().Auth.Enable {// Session AuthsessionIdCookie, cookieErr := request.Cookie(model.SessionIdCookieName)if cookieErr == nil {diff --git a/kernel/server/proxy/publish_test.go b/kernel/server/proxy/publish_test.goindex a0533e9a02..2586bd4064 100644--- a/kernel/server/proxy/publish_test.go+++ b/kernel/server/proxy/publish_test.go@@ -156,14 +156,14 @@ func TestPublishSessionCookieAttributes(t *testing.T) {defer func() { model.Conf = previousConf }()model.Conf = model.NewAppConf()- model.Conf.Publish = &conf.Publish{+ model.Conf.Publish.Store(&conf.Publish{Enable: true,Port: 6808,Auth: &conf.BasicAuth{Enable: true,Accounts: []*conf.BasicAuthAccount{{Username: username, Password: password}},},- }+ })// 构建账户及其 token,Basic Auth 成功后由会话认证路径转发model.InitPublishAccounts()diff --git a/kernel/server/serve.go b/kernel/server/serve.goindex 38072cd1e9..6696ddcb55 100644--- a/kernel/server/serve.go+++ b/kernel/server/serve.go@@ -137,6 +137,10 @@ var ()func Serve(fastMode bool, cookieKey string) {+ confAISnapshot := model.Conf.LoadAI()++ confSystemSnapshot := model.Conf.LoadSystem()+gin.SetMode(gin.ReleaseMode)ginServer := gin.New()if err := ginServer.SetTrustedProxies([]string{"127.0.0.1", "::1"}); err != nil {@@ -193,7 +197,7 @@ func Serve(fastMode bool, cookieKey string) {api.ServeAPI(ginServer)var host string- if model.Conf.System.NetworkServe || util.ContainerDocker == util.Container {+ if confSystemSnapshot.NetworkServe || util.ContainerDocker == util.Container {host = "0.0.0.0"} else {host = "127.0.0.1"@@ -232,7 +236,7 @@ func Serve(fastMode bool, cookieKey string) {// 用户开启「启用 HTTPS」后网络服务必须真正强制加密传输,因此这里先把策略定下来:// 证书不可用时不能静默退回明文,否则等于开关没生效却仍然宣称已加密。// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-hpj5-f7cj-vvwr- tlsRequired := model.Conf.System.NetworkServeTLS && model.Conf.System.NetworkServe+ tlsRequired := confSystemSnapshot.NetworkServeTLS && confSystemSnapshot.NetworkServeutil.SetTLSRequired(tlsRequired)if tlsRequired && "" == certPath {logging.LogErrorf("network serve TLS is enabled but no TLS certificate is available, "+@@ -269,8 +273,8 @@ func Serve(fastMode bool, cookieKey string) {// 启动后自动连接已配置的 MCP server,让用户首次使用 AI Agent 时工具已就绪。// EnsureMCPConnected 是异步的,不阻塞 HTTP 监听;内置 mcpConnecting 标志防止重复连接。- if model.Conf.AI != nil && model.Conf.AI.MCP != nil {- go mcpclient.EnsureMCPConnected(model.Conf.AI.MCP.Servers)+ if confAISnapshot != nil && confAISnapshot.MCP != nil {+ go mcpclient.EnsureMCPConnected(confAISnapshot.MCP.Servers)}go func() {@@ -884,6 +888,10 @@ func serveCheckAuth(ginServer *gin.Engine) {}func serveAuthPage(c *gin.Context) {+ confAppearanceSnapshot := model.Conf.LoadAppearance()++ confKeymapSnapshot := model.Conf.LoadKeymap()+data, err := os.ReadFile(filepath.Join(util.WorkingDir, "stage/auth.html"))if err != nil {logging.LogErrorf("load auth page failed: %s", err)@@ -899,10 +907,10 @@ func serveAuthPage(c *gin.Context) {}keymapHideWindow := "⌥M"- if nil != (*model.Conf.Keymap)["general"] {- switch (*model.Conf.Keymap)["general"].(type) {+ if nil != (*confKeymapSnapshot)["general"] {+ switch (*confKeymapSnapshot)["general"].(type) {case map[string]any:- keymapGeneral := (*model.Conf.Keymap)["general"].(map[string]any)+ keymapGeneral := (*confKeymapSnapshot)["general"].(map[string]any)if nil != keymapGeneral["toggleWin"] {switch keymapGeneral["toggleWin"].(type) {case map[string]any:@@ -934,8 +942,8 @@ func serveAuthPage(c *gin.Context) {"l13": model.Conf.Language(365),"accessAuthCodeEnabled": model.Conf.AccessAuthCode != "","oidcEnabled": model.Conf.GetOIDC().Enabled,- "appearanceMode": model.Conf.Appearance.Mode,- "appearanceModeOS": model.Conf.Appearance.ModeOS,+ "appearanceMode": confAppearanceSnapshot.Mode,+ "appearanceModeOS": confAppearanceSnapshot.ModeOS,"workspace": util.WorkspaceName,"keymapGeneralToggleWin": keymapHideWindow,"trayMenuLangs": util.TrayMenuLangs[util.Lang],@@ -1315,7 +1323,7 @@ func serveSVG(context *gin.Context, assetAbsPath string) bool {}()}- if !model.Conf.Editor.AllowSVGScript {+ if !model.Conf.Editor.Load().AllowSVGScript {sanitized, sanitizeErr := util.SanitizeSVG(string(data))if sanitizeErr != nil {logging.LogWarnf("sanitize svg file failed [%s]: %s", assetAbsPath, sanitizeErr)diff --git a/kernel/server/serve_static_test.go b/kernel/server/serve_static_test.goindex c19d141d22..90555d5601 100644--- a/kernel/server/serve_static_test.go+++ b/kernel/server/serve_static_test.go@@ -488,8 +488,8 @@ func TestPluginPublishAccess(t *testing.T) {originalConf := model.Confutil.DataDir = testutil.PublicDataDir(t)model.Conf = model.NewAppConf()- model.Conf.Bazaar = &conf.Bazaar{Trust: true}- model.Conf.Sync = conf.NewSync()+ model.Conf.Bazaar.Store(&conf.Bazaar{Trust: true})+ model.Conf.Sync.Store(conf.NewSync())t.Cleanup(func() {util.DataDir = originalDataDirmodel.Conf = originalConfdiff --git a/kernel/server/serve_svg_test.go b/kernel/server/serve_svg_test.goindex 4ac53fd944..4774ff7d94 100644--- a/kernel/server/serve_svg_test.go+++ b/kernel/server/serve_svg_test.go@@ -24,7 +24,7 @@ import (func TestServeSVGSanitizesAndSetsSecurityHeaders(t *testing.T) {oldConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.Editor = conf.NewEditor()+ model.Conf.Editor.Store(conf.NewEditor())t.Cleanup(func() {model.Conf = oldConf})@@ -59,8 +59,8 @@ func TestServeSVGSanitizesAndSetsSecurityHeaders(t *testing.T) {func TestServeSVGPreservesAllowSVGScriptBehavior(t *testing.T) {oldConf := model.Confmodel.Conf = model.NewAppConf()- model.Conf.Editor = conf.NewEditor()- model.Conf.Editor.AllowSVGScript = true+ model.Conf.Editor.Store(conf.NewEditor())+ model.Conf.Editor.Load().AllowSVGScript = truet.Cleanup(func() {model.Conf = oldConf})diff --git a/kernel/server/serve_tls_test.go b/kernel/server/serve_tls_test.goindex 21bdd95125..2cc6e34aea 100644--- a/kernel/server/serve_tls_test.go+++ b/kernel/server/serve_tls_test.go@@ -38,7 +38,7 @@ func prepareTLSEnforceTest(t *testing.T, required, enforced bool) {previousConf := model.ConfpreviousRequired := util.TLSRequired()- model.Conf = &model.AppConf{System: &conf.System{NetworkServe: required, NetworkServeTLS: required}}+ model.Conf = &model.AppConf{System: model.NewConfSection(&conf.System{NetworkServe: required, NetworkServeTLS: required})}util.SetTLSRequired(required)if enforced {util.MarkTLSEnforced()diff --git a/kernel/sql/av.go b/kernel/sql/av.goindex cbe6fb0000..07665a9c0c 100644--- a/kernel/sql/av.go+++ b/kernel/sql/av.go@@ -1268,7 +1268,7 @@ func filterByQuery(query string, collection av.Collection) {for _, cell := range item.GetValues() {allKeywordsHit := truefor _, keyword := range keywords {- if !util.SearchCaseSensitive {+ if !util.SearchCaseSensitive.Load() {if !strings.Contains(strings.ToLower(cell.String(true)), strings.ToLower(keyword)) {allKeywordsHit = falsebreakdiff --git a/kernel/sql/block_query.go b/kernel/sql/block_query.goindex 2d6263b05d..2e23a00860 100644--- a/kernel/sql/block_query.go+++ b/kernel/sql/block_query.go@@ -88,7 +88,7 @@ func queryBlockHashes(tx *sql.Tx, rootID string) (ret map[string]string) {}func QueryRootBlockByCondition(condition, exactKeyword string, limit int, args ...any) (ret []*Block) {- exactCondition, exactArg := rootBlockExactMatchCondition(exactKeyword, caseSensitive)+ exactCondition, exactArg := rootBlockExactMatchCondition(exactKeyword, caseSensitive.Load())sqlStmt := "SELECT *, length(hpath) - length(replace(hpath, '/', '')) AS lv FROM blocks WHERE type = 'd' AND " + condition +" ORDER BY CASE WHEN " + exactCondition + " THEN 0 ELSE 1 END ASC, box DESC, lv ASC LIMIT ?"args = append(args, exactArg...)@@ -112,7 +112,7 @@ func QueryRootBlockByCondition(condition, exactKeyword string, limit int, args .}func QueryRootBlockByConditionInBox(condition, exactKeyword string, limit int, boxID string, args ...any) (ret []*Block) {- exactCondition, exactArg := rootBlockExactMatchCondition(exactKeyword, caseSensitive)+ exactCondition, exactArg := rootBlockExactMatchCondition(exactKeyword, caseSensitive.Load())sqlStmt := "SELECT *, length(hpath) - length(replace(hpath, '/', '')) AS lv FROM blocks WHERE type = 'd' AND " + condition +" ORDER BY CASE WHEN " + exactCondition + " THEN 0 ELSE 1 END ASC, box DESC, lv ASC LIMIT ?"args = append(args, exactArg...)diff --git a/kernel/sql/block_ref_query.go b/kernel/sql/block_ref_query.goindex 7fae8f88d6..a929df9a0f 100644--- a/kernel/sql/block_ref_query.go+++ b/kernel/sql/block_ref_query.go@@ -434,7 +434,7 @@ func QueryBlockDefIDsByRefText(refText string) (ret []string) {func QueryBlockDefIDsByRefTextInBox(refText, boxID string) (ret []string) {var q, arg string- if caseSensitive {+ if caseSensitive.Load() {q = "SELECT DISTINCT(def_block_id) FROM refs WHERE content = ?"arg = refText} else {@@ -459,7 +459,7 @@ func QueryBlockDefIDsByRefTextInBox(refText, boxID string) (ret []string) {escaped := escapeLikePattern(refText)aliasArg := "%," + escaped + ",%"var nameCond, docCond, exactArg string- if caseSensitive {+ if caseSensitive.Load() {nameCond = "name = ?"docCond = "content = ?"exactArg = refText@@ -491,7 +491,7 @@ func QueryBlockDefIDsByRefTextInBox(refText, boxID string) (ret []string) {func queryDefIDsByDefText(keyword string) (ret []string) {ret = []string{}var q, arg string- if caseSensitive {+ if caseSensitive.Load() {q = "SELECT DISTINCT(def_block_id) FROM refs WHERE content = ?"arg = keyword} else {@@ -520,7 +520,7 @@ func queryDefIDsByNameAliasAndDocTitle(keyword string) (ret []string) {escaped := escapeLikePattern(keyword)aliasArg := "%," + escaped + ",%"var nameCond, docCond, exactArg string- if caseSensitive {+ if caseSensitive.Load() {nameCond = "name = ?"docCond = "content = ?"exactArg = keyworddiff --git a/kernel/sql/database.go b/kernel/sql/database.goindex c90c70721a..25bec3e3b9 100644--- a/kernel/sql/database.go+++ b/kernel/sql/database.go@@ -510,14 +510,14 @@ func initAssetContentDBTables() {}var (- caseSensitive bool- hanSensitive bool- indexAssetPath bool+ caseSensitive = util.NewAtomicValue(false)+ hanSensitive = util.NewAtomicValue(false)+ indexAssetPath = util.NewAtomicValue(false))func SetCaseSensitive(b bool) {- caseSensitive = b- util.SearchCaseSensitive = b+ caseSensitive.Store(b)+ util.SearchCaseSensitive.Store(b)if nil == db {return@@ -531,25 +531,25 @@ func SetCaseSensitive(b bool) {}func SetHanSensitive(b bool) {- hanSensitive = b- util.SearchHanSensitive = b+ hanSensitive.Store(b)+ util.SearchHanSensitive.Store(b)}// ftsTokenize 返回 blocks FTS 表的 tokenize 参数。// 分词器参数在 CREATE VIRTUAL TABLE 时固化,切换区分大小写或区分繁简后需要重建索引。func ftsTokenize() string {ret := "siyuan"- if !caseSensitive {+ if !caseSensitive.Load() {ret += " case_insensitive"}- if !hanSensitive {+ if !hanSensitive.Load() {ret += " han_insensitive"}return ret}func SetIndexAssetPath(b bool) {- indexAssetPath = b+ indexAssetPath.Store(b)}func refsFromTree(tree *parse.Tree) (refs []*Ref, fileAnnotationRefs []*FileAnnotationRef) {@@ -1000,7 +1000,7 @@ func buildBlockFromNode(n *ast.Node, tree *parse.Tree) (block *Block, attributesif !treenode.IsNodeOCRed(n) {util.PushNodeOCRQueue(n)}- content = nodeStaticContent(n, nil, true, indexAssetPath, true, true)+ content = nodeStaticContent(n, nil, true, indexAssetPath.Load(), true, true)fc := treenode.FirstLeafBlock(n)if !treenode.IsNodeOCRed(fc) {@@ -1018,7 +1018,7 @@ func buildBlockFromNode(n *ast.Node, tree *parse.Tree) (block *Block, attributesif !treenode.IsNodeOCRed(n) {util.PushNodeOCRQueue(n)}- content = nodeStaticContent(n, nil, true, indexAssetPath, true, true)+ content = nodeStaticContent(n, nil, true, indexAssetPath.Load(), true, true)parentID = n.Parent.IDif h := treenode.HeadingParent(n); nil != h {diff --git a/kernel/sql/search_settings_test.go b/kernel/sql/search_settings_test.goindex ce8cca9dba..5712e2b3d6 100644--- a/kernel/sql/search_settings_test.go+++ b/kernel/sql/search_settings_test.go@@ -8,18 +8,28 @@ import ()func TestSearchSettingsBeforeDatabaseInitialization(t *testing.T) {- previousDB, previousCase, previousHan, previousAssets := db, caseSensitive, hanSensitive, indexAssetPath- previousUtilCase, previousUtilHan := util.SearchCaseSensitive, util.SearchHanSensitive+ previousDB, previousCase, previousHan, previousAssets := db, caseSensitive.Load(), hanSensitive.Load(), indexAssetPath.Load()+ previousUtilCase, previousUtilHan := util.SearchCaseSensitive.Load(), util.SearchHanSensitive.Load()t.Cleanup(func() {- db, caseSensitive, hanSensitive, indexAssetPath = previousDB, previousCase, previousHan, previousAssets- util.SearchCaseSensitive, util.SearchHanSensitive = previousUtilCase, previousUtilHan+ {+ derivedValue0, derivedValue1, derivedValue2, derivedValue3 := previousDB, previousCase, previousHan, previousAssets+ db = derivedValue0+ caseSensitive.Store(derivedValue1)+ hanSensitive.Store(derivedValue2)+ indexAssetPath.Store(derivedValue3)+ }+ {+ derivedValue0, derivedValue1 := previousUtilCase, previousUtilHan+ util.SearchCaseSensitive.Store(derivedValue0)+ util.SearchHanSensitive.Store(derivedValue1)+ }})db = nilfor _, sensitive := range []bool{true, false} {SetCaseSensitive(sensitive)SetHanSensitive(sensitive)SetIndexAssetPath(sensitive)- if util.SearchCaseSensitive != sensitive || util.SearchHanSensitive != sensitive || indexAssetPath != sensitive {+ if util.SearchCaseSensitive.Load() != sensitive || util.SearchHanSensitive.Load() != sensitive || indexAssetPath.Load() != sensitive {t.Fatal("search settings were not applied before opening the database")}for _, option := range []string{"case_insensitive", "han_insensitive"} {diff --git a/kernel/task/queue.go b/kernel/task/queue.goindex f96ef3bbbb..543c9defc3 100644--- a/kernel/task/queue.go+++ b/kernel/task/queue.go@@ -315,13 +315,13 @@ func StatusJob() {func skipPushTaskAction(action string) bool {switch action {case DatabaseIndexCommit:- return util.StatusBarCfg.MsgTaskDatabaseIndexCommitDisabled+ return util.StatusBarCfg.Load().MsgTaskDatabaseIndexCommitDisabledcase HistoryDatabaseIndexCommit:- return util.StatusBarCfg.MsgTaskHistoryDatabaseIndexCommitDisabled+ return util.StatusBarCfg.Load().MsgTaskHistoryDatabaseIndexCommitDisabledcase AssetContentDatabaseIndexCommit:- return util.StatusBarCfg.MsgTaskAssetDatabaseIndexCommitDisabled+ return util.StatusBarCfg.Load().MsgTaskAssetDatabaseIndexCommitDisabledcase HistoryGenerateFile:- return util.StatusBarCfg.MsgTaskHistoryGenerateFileDisabled+ return util.StatusBarCfg.Load().MsgTaskHistoryGenerateFileDisableddefault:return false}diff --git a/kernel/util/appearance.go b/kernel/util/appearance.goindex fd7218fd02..e51000300b 100644--- a/kernel/util/appearance.go+++ b/kernel/util/appearance.go@@ -56,7 +56,7 @@ func NormalizeStatusBar(statusBar *StatusBar, mobile bool) *StatusBar {return statusBar}-var StatusBarCfg *StatusBar+var StatusBarCfg = NewAtomicValue[*StatusBar](nil)// Notifications 外观通知开关配置。https://github.com/siyuan-note/siyuan/issues/17797// Appearance.Notifications 为 nil 时表示旧配置尚未迁移,整体按默认启用处理。@@ -83,4 +83,4 @@ func NewNotifications() *Notifications {}}-var NotificationsCfg *Notifications+var NotificationsCfg = NewAtomicValue[*Notifications](nil)diff --git a/kernel/util/atomic_value.go b/kernel/util/atomic_value.gonew file mode 100644index 0000000000..49c45204c4--- /dev/null+++ b/kernel/util/atomic_value.go@@ -0,0 +1,22 @@+package util++import "sync/atomic"++// AtomicValue 发布运行时派生值,读方不会与设置写入竞争。+type AtomicValue[T any] struct{ value atomic.Pointer[T] }++func NewAtomicValue[T any](value T) *AtomicValue[T] {+ ret := &AtomicValue[T]{}+ ret.Store(value)+ return ret+}++func (value *AtomicValue[T]) Load() T {+ if snapshot := value.value.Load(); snapshot != nil {+ return *snapshot+ }+ var zero T+ return zero+}++func (value *AtomicValue[T]) Store(next T) { value.value.Store(&next) }diff --git a/kernel/util/lute.go b/kernel/util/lute.goindex 511fbb9405..30f99a314e 100644--- a/kernel/util/lute.go+++ b/kernel/util/lute.go@@ -26,7 +26,7 @@ import ()// MarkdownSettings 运行时 Markdown 配置。-var MarkdownSettings = NewMarkdown()+var MarkdownSettings = NewAtomicValue(NewMarkdown())// NewMarkdown 返回独立的默认语法配置,不引用运行时设置。func NewMarkdown() *Markdown {@@ -73,15 +73,16 @@ func NewLute() (ret *lute.Lute) {ret.SetCustomBlock(true)ret.SetImgPathAllowSpace(true)ret.SetGitConflict(true)- ret.SetInlineAsterisk(MarkdownSettings.InlineAsterisk)- ret.SetInlineUnderscore(MarkdownSettings.InlineUnderscore)- ret.SetSup(MarkdownSettings.InlineSup)- ret.SetSub(MarkdownSettings.InlineSub)- ret.SetTag(MarkdownSettings.InlineTag)- ret.SetInlineMath(MarkdownSettings.InlineMath)- ret.SetGFMStrikethrough(MarkdownSettings.InlineStrikethrough)- ret.SetFullWidthStrikethrough(MarkdownSettings.InlineFullWidthStrikethrough)- ret.SetMark(MarkdownSettings.InlineMark)+ markdown := MarkdownSettings.Load()+ ret.SetInlineAsterisk(markdown.InlineAsterisk)+ ret.SetInlineUnderscore(markdown.InlineUnderscore)+ ret.SetSup(markdown.InlineSup)+ ret.SetSub(markdown.InlineSub)+ ret.SetTag(markdown.InlineTag)+ ret.SetInlineMath(markdown.InlineMath)+ ret.SetGFMStrikethrough(markdown.InlineStrikethrough)+ ret.SetFullWidthStrikethrough(markdown.InlineFullWidthStrikethrough)+ ret.SetMark(markdown.InlineMark)ret.SetInlineMathAllowDigitAfterOpenMarker(true)ret.SetGFMStrikethrough1(false)ret.SetFootnotes(false)@@ -122,14 +123,15 @@ func NewStdLute() (ret *lute.Lute) {// 导入 Markdown 时遵循编辑器 Markdown 语法设置// Follow editor Markdown syntax settings when importing Markdown https://github.com/siyuan-note/siyuan/issues/14731- ret.SetInlineAsterisk(MarkdownSettings.InlineAsterisk)- ret.SetInlineUnderscore(MarkdownSettings.InlineUnderscore)- ret.SetSup(MarkdownSettings.InlineSup)- ret.SetSub(MarkdownSettings.InlineSub)- ret.SetTag(MarkdownSettings.InlineTag)- ret.SetInlineMath(MarkdownSettings.InlineMath)- ret.SetGFMStrikethrough(MarkdownSettings.InlineStrikethrough)- ret.SetFullWidthStrikethrough(MarkdownSettings.InlineFullWidthStrikethrough)+ markdown := MarkdownSettings.Load()+ ret.SetInlineAsterisk(markdown.InlineAsterisk)+ ret.SetInlineUnderscore(markdown.InlineUnderscore)+ ret.SetSup(markdown.InlineSup)+ ret.SetSub(markdown.InlineSub)+ ret.SetTag(markdown.InlineTag)+ ret.SetInlineMath(markdown.InlineMath)+ ret.SetGFMStrikethrough(markdown.InlineStrikethrough)+ ret.SetFullWidthStrikethrough(markdown.InlineFullWidthStrikethrough)ret.SetGFMStrikethrough1(false)return}diff --git a/kernel/util/runtime.go b/kernel/util/runtime.goindex cd86d9f917..f12a709a0c 100644--- a/kernel/util/runtime.go+++ b/kernel/util/runtime.go@@ -65,12 +65,12 @@ const DefaultUseSingleLineSave = trueconst DefaultLargeFileWarningSize = 8var (- UseSingleLineSave = DefaultUseSingleLineSave // UseSingleLineSave 是否使用单行保存 .sy 和数据库 .json 文件。- LargeFileWarningSize = DefaultLargeFileWarningSize // LargeFileWarningSize 大文件警告大小,单位:MB+ UseSingleLineSave = NewAtomicValue(DefaultUseSingleLineSave) // UseSingleLineSave 是否使用单行保存 .sy 和数据库 .json 文件。+ LargeFileWarningSize = NewAtomicValue(DefaultLargeFileWarningSize) // LargeFileWarningSize 大文件警告大小,单位:MB)func ExceedLargeFileWarningSize(fileSize int) bool {- return fileSize > LargeFileWarningSize*1024*1024+ return fileSize > LargeFileWarningSize.Load()*1024*1024}// IsUILoaded 是否已经加载了 UI。@@ -138,7 +138,7 @@ func logBootInfo() {WaitForUILoaded()time.Sleep(3 * time.Second)}- if nil == NotificationsCfg || NotificationsCfg.WorkspaceNotSSD {+ if nil == NotificationsCfg.Load() || NotificationsCfg.Load().WorkspaceNotSSD {PushErrMsg(Langs[Lang][278], 15000)}}@@ -634,7 +634,7 @@ const (EvtSQLAssetContentRebuild = "sql.assetContent.rebuild")-var SearchCaseSensitive bool+var SearchCaseSensitive = NewAtomicValue(false)// SearchHanSensitive 是否区分繁简,由 sql.SetHanSensitive 维护;默认 true 与既往行为一致-var SearchHanSensitive = true+var SearchHanSensitive = NewAtomicValue(true)