Skip to content

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

:bug: Stop publishing setting notifications for storage writes

Jeffrey Chen62fceeb9a5f9
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 0d90da95fa..2cfbee858c 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -5489,6 +5489,9 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin","writable"];
};
+ /**
+ * 图谱查询需要与配置写入互斥;查询自带的配置由配置段发布负责通知,包装层不再补发。
+ */
"/api/graph/getGraph": {
request: GlobalGraphRequestInput;
response: { "code": 0; "data": GlobalGraphResult | (GraphCorrelation & { "box"?: never; "conf"?: never; "links"?: never; "nodes"?: never; }); "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null | GlobalGraphResult | (GraphCorrelation & { "box"?: never; "conf"?: never; "links"?: never; "nodes"?: never; }); "msg": string; };
@@ -6069,6 +6072,9 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin","writable"];
};
+ /**
+ * 自动锁定分钟数由内核内存值驱动锁定行为,写入后无需广播供其他客户端重读。
+ */
"/api/notebook/setNotebookCryptoAutoLock": {
request: NotebookCryptoAutoLockRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -6871,6 +6877,7 @@ export interface APIPOSTRoutes {
* web 初始搜索为 Exa、抓取为直接请求,可独立切换到共用密钥的 DeepSeek。
* 工具调用轮数和输出 token 上限的负数归零;温度超出 0–2 回退 1。
* 嵌入并发数和批大小省略、null 或小于 1 时分别使用 8 和 10,超过上限时分别限制为 64 和 128。
+ * 旧客户端的平铺 decision.endpoint、apiKey、name、timeout 迁移到 profiles.typesafe;提交 profiles 时以该对象为准。
* ChatGPT 账户绑定变化时与主配置一起可恢复提交,失败时回滚且不发布新配置;未变化时不访问绑定存储。
*/
"/api/setting/setAI": {
@@ -6882,6 +6889,7 @@ export interface APIPOSTRoutes {
};
/**
* 限定关闭按钮行为:closeButtonBehavior 仅接受 0、1,越界值回退 0。
+ * entryVisibility 省略时保持当前方案,null 还原默认显隐方案。
*/
"/api/setting/setAppearance": {
request: SetAppearanceRequestInput;
@@ -6916,6 +6924,7 @@ export interface APIPOSTRoutes {
* 锚文本长度 1–5120 保持不变,小于 1 回退 64;字体大小超出 9–72 回退 16。
* backlinkGlobalSort、backlinkBlockSort、floatWindowMode、headingEmbedMode 仅接受 0、1、2,越界值回退 0。
* databaseAttrClickMode、databaseAttrViewMode 仅接受 0、1;codeTabSpaces 仅接受 0、2、4、6、8,越界值回退 0。
+ * 只提交 fontFamily、fontWeight 时按新的首选字体重建 fontFamilies;显式提交 fontFamilies 时以该列表为准。
*/
"/api/setting/setEditor": {
request: SetEditorRequestInput;
@@ -6950,9 +6959,9 @@ export interface APIPOSTRoutes {
authorization?: readonly ["authenticated","admin","writable"];
};
/**
- * 整体替换导出配置,将 blockRefMode 的废弃值 0、1、5 转换为 4 后同步保存并回显。
+ * 合并提交的导出配置,将 blockRefMode 的废弃值 0、1、5 转换为 4 后同步保存并回显。
* blockEmbedMode 仅接受 0、1,越界值回退 1;fileAnnotationRefMode 仅接受 0、1,越界值回退 0。
- * blockRefMode 的其他取值及字段省略、null 的解析行为保持不变。
+ * blockRefMode 的其他取值原样保留;省略的字段保持当前值,null 还原默认值。
*/
"/api/setting/setExport": {
request: SetExportRequestInput;
@@ -7199,6 +7208,9 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin","writable"];
};
+ /**
+ * 行级样式与数据库调色板变化由 reloadInlineStyles 专用推送通知其他窗口,不走配置段刷新。
+ */
"/api/storage/setInlineStyles": {
request: SetInlineStylesRequestInput;
response: { "code": 0; "data": InlineStyles | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -7220,6 +7232,9 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin","writable"];
};
+ /**
+ * 写入 data/storage 下独立存储的端点都不是 conf.json 的配置段,因此只持锁不广播。
+ */
"/api/storage/setOutlineStorage": {
request: OutlineStorageSetRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
diff --git a/kernel/api/contract.go b/kernel/api/contract.go
index 2e1e6eab80..7ba52a0da4 100644
--- a/kernel/api/contract.go
+++ b/kernel/api/contract.go
@@ -48,7 +48,8 @@ func contractHandler[Request, Data any](endpoint apicontract.Endpoint[Request, D
// 合并写入在取得配置段锁之后才读取当前配置,避免并发提交互相覆盖。
merge := setting.Declared() && setting.Merge
if !merge {
- // 写配置端点按契约声明串行化并通知;读取完整配置与写入共用互斥,保证读到已提交的配置
+ // 按契约声明的模式串行化:Notify 补发变更通知,Silent 只取配置互斥锁。
+ // 读取完整配置与写入共用互斥,保证读到已提交的配置。
if 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" {
diff --git a/kernel/api/contract_notebook_system_lock_test.go b/kernel/api/contract_notebook_system_lock_test.go
index e9bf24cace..6839e7d1c8 100644
--- a/kernel/api/contract_notebook_system_lock_test.go
+++ b/kernel/api/contract_notebook_system_lock_test.go
@@ -210,7 +210,7 @@ func TestAPIContractNotebookSystemLockNotifications(t *testing.T) {
engine := gin.New()
path := "/api/notebook/setEncryptedNotebookFollowSystemLock"
engine.POST(path, setEncryptedNotebookFollowSystemLock)
- connection := connectOCRNotifications(t, engine)
+ connection := connectSettingNotifications(t, engine)
for _, enabled := range []bool{true, false} {
recorder := httptest.NewRecorder()
engine.ServeHTTP(recorder, httptest.NewRequest("POST", path, strings.NewReader(fmt.Sprintf(`{"enabled":%t}`, enabled))))
diff --git a/kernel/api/contract_ocr_test.go b/kernel/api/contract_ocr_test.go
index 64006397ef..b3a9edb944 100644
--- a/kernel/api/contract_ocr_test.go
+++ b/kernel/api/contract_ocr_test.go
@@ -174,7 +174,7 @@ func TestAPIContractOCRNativeImportAndHeadlessRecognition(t *testing.T) {
engine := gin.New()
engine.POST("/api/asset/importOCRModels", importOCRModels)
engine.POST("/api/asset/ocr", ocr)
- connection := connectOCRNotifications(t, engine)
+ connection := connectSettingNotifications(t, engine)
upload := func(invalid bool) apicontract.OCRModel {
t.Helper()
var body bytes.Buffer
@@ -419,7 +419,8 @@ func TestAPIContractOCRThresholdPersistence(t *testing.T) {
}
}
-func connectOCRNotifications(t *testing.T, engine *gin.Engine) *websocket.Conn {
+// connectSettingNotifications 建立 main 会话并返回可读取推送的连接,供各设置通知测试共用。
+func connectSettingNotifications(t *testing.T, engine *gin.Engine) *websocket.Conn {
t.Helper()
push := melody.New()
connected := make(chan *melody.Session, 1)
@@ -431,7 +432,7 @@ func connectOCRNotifications(t *testing.T, engine *gin.Engine) *websocket.Conn {
engine.GET("/ws", func(c *gin.Context) { _ = push.HandleRequest(c.Writer, c.Request) })
server := httptest.NewServer(engine)
t.Cleanup(func() { push.Close(); server.Close() })
- endpoint := "ws" + strings.TrimPrefix(server.URL, "http") + "/ws?app=" + t.Name() + "&id=ocr-settings&type=main"
+ endpoint := "ws" + strings.TrimPrefix(server.URL, "http") + "/ws?app=" + t.Name() + "&id=settings-notifications&type=main"
connection, response, err := websocket.DefaultDialer.Dial(endpoint, nil)
if err != nil {
t.Fatal(err)
@@ -442,7 +443,7 @@ func connectOCRNotifications(t *testing.T, engine *gin.Engine) *websocket.Conn {
case session := <-connected:
t.Cleanup(func() { util.RemovePushChan(session) })
case <-time.After(5 * time.Second):
- t.Fatal("OCR settings WebSocket did not connect")
+ t.Fatal("settings WebSocket did not connect")
}
return connection
}
@@ -454,7 +455,7 @@ func TestAPIContractOCRSettingsNotifications(t *testing.T) {
t.Cleanup(func() { util.ConfDir = previousConfDir })
engine := gin.New()
engine.POST("/api/asset/setOCRConfig", setOCRConfig)
- connection := connectOCRNotifications(t, engine)
+ connection := connectSettingNotifications(t, engine)
for _, auto := range []bool{true, false} {
body, err := json.Marshal(apicontract.SettingOCR{Provider: "tesseract", Model: "tiny", Auto: auto})
if err != nil {
diff --git a/kernel/api/setting_notification_test.go b/kernel/api/setting_notification_test.go
new file mode 100644
index 0000000000..ebe9f67234
--- /dev/null
+++ b/kernel/api/setting_notification_test.go
@@ -0,0 +1,94 @@
+package api
+
+import (
+ "encoding/json"
+ "net"
+ "net/http/httptest"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+// settingReadAction 匹配读取类端点的动作名。这类端点即使顺带写入配置,也由配置段发布通知,
+// 包装层再补一次只会在内容未变化时产生多余广播。
+var settingReadAction = regexp.MustCompile(`^/(get|list|search|query)[A-Z]`)
+
+// 通知会让客户端按命名空间读取配置段,因此只有能读取的命名空间才允许广播。
+func TestSettingNotificationsTargetReadableSections(t *testing.T) {
+ previousConf := model.Conf
+ model.Conf = model.NewAppConf()
+ t.Cleanup(func() { model.Conf = previousConf })
+ for _, definition := range apicontract.Definitions() {
+ setting := definition.Setting
+ if !setting.Declared() || setting.Mode != apicontract.SettingNotify {
+ continue
+ }
+ if settingReadAction.MatchString(definition.Path[strings.LastIndex(definition.Path, "/"):]) {
+ t.Errorf("%s is a read action but publishes settingChanged", definition.Path)
+ }
+ if "*" == setting.Namespace {
+ continue
+ }
+ if _, ok := model.SectionSpecByNamespace(setting.Namespace); !ok {
+ t.Errorf("%s notifies %q, which no client can read as a configuration section", definition.Path, setting.Namespace)
+ }
+ }
+}
+
+// 独立存储不是 conf.json 的配置段,写入后不得向客户端广播 settingChanged。
+func TestSettingStorageWritesDoNotPublishNotifications(t *testing.T) {
+ previousConf, previousReadOnly, previousConfDir, previousDataDir := model.Conf, util.ReadOnly, util.ConfDir, util.DataDir
+ util.ReadOnly, util.ConfDir, util.DataDir = false, t.TempDir(), t.TempDir()
+ t.Cleanup(func() {
+ model.Conf, util.ReadOnly, util.ConfDir, util.DataDir = previousConf, previousReadOnly, previousConfDir, previousDataDir
+ })
+ model.Conf = model.NewAppConf()
+ model.NormalizeAppConf(model.Conf)
+
+ engine := gin.New()
+ engine.POST("/api/storage/setOutlineStorage", setOutlineStorage)
+ engine.POST("/api/notebook/setNotebookCryptoAutoLock", setNotebookCryptoAutoLock)
+ connection := connectSettingNotifications(t, engine)
+ for _, request := range []struct{ path, body string }{
+ {"/api/storage/setOutlineStorage", `{"docID":"20260820000000-outline","val":{"expandIds":["20260820000000-heading"]}}`},
+ {"/api/notebook/setNotebookCryptoAutoLock", `{"autoLockMinutes":15}`},
+ } {
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", request.path, strings.NewReader(request.body)))
+ requireAPIContract(t, "POST", request.path, recorder)
+ var response struct{ Code int }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != 0 {
+ t.Fatalf("%s failed: %s (%v)", request.path, recorder.Body.String(), err)
+ }
+ }
+ // 保存会顺带触发同步排期等其他推送,这里只关心是否出现了配置段变更通知。
+ deadline := time.Now().Add(time.Second)
+ for {
+ if err := connection.SetReadDeadline(deadline); err != nil {
+ t.Fatal(err)
+ }
+ var event struct {
+ Cmd string `json:"cmd"`
+ Data json.RawMessage `json:"data"`
+ }
+ if err := connection.ReadJSON(&event); err != nil {
+ if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
+ return
+ }
+ t.Fatalf("read push failed: %v", err)
+ }
+ if "settingChanged" == event.Cmd {
+ var data struct {
+ Namespace string `json:"namespace"`
+ }
+ _ = json.Unmarshal(event.Data, &data)
+ t.Fatalf("storage write published a setting notification for %q", data.Namespace)
+ }
+ }
+}
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 2f2d64ded6..d9427d4d46 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -326,7 +326,7 @@ var (
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{Setting: SettingWrite{Namespace: "tag"}}, "POST")
+ GetTag = define[GetTagRequest, []*TagData]("getTag", "/api/tag/getTag", AuthenticatedAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "tag", Mode: SettingSilent}}, "POST")
)
var (
@@ -353,11 +353,12 @@ var (
// 保存本机加密笔记本锁屏策略,成功后广播 system 设置变更通知,供其他客户端重新读取配置。
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{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")
- GetNotebookArchiveCandidates = define[EmptyRequest, NotebookArchiveCandidatesData]("getNotebookArchiveCandidates", "/api/notebook/getNotebookArchiveCandidates", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")
+ // 自动锁定分钟数由内核内存值驱动锁定行为,写入后无需广播供其他客户端重读。
+ SetNotebookCryptoAutoLock = define[NotebookCryptoAutoLockRequest, Null]("setNotebookCryptoAutoLock", "/api/notebook/setNotebookCryptoAutoLock", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "notebookCrypto", Mode: SettingSilent}}, "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")
+ GetNotebookArchiveCandidates = define[EmptyRequest, NotebookArchiveCandidatesData]("getNotebookArchiveCandidates", "/api/notebook/getNotebookArchiveCandidates", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")
// 接收已锁定的加密笔记本 ID,返回归档 ID 和下载路径,不删除源数据,要求管理员权限。
// 下载完成后,必须由用户确认已保存归档,再调用 `/api/notebook/commitNotebookArchive` 并传入 saved: true。
PrepareNotebookArchive = define[PrepareNotebookArchiveRequest, NotebookArchiveData]("prepareNotebookArchive", "/api/notebook/prepareNotebookArchive", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
@@ -520,16 +521,18 @@ var SetLocalStorageVals = define[StorageSetKeysRequest, Null]("setLocalStorageVa
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{Setting: SettingWrite{Namespace: "storage"}}, "POST")
-var RemoveOutlineStorage = define[OutlineStorageRequest, Null]("removeOutlineStorage", "/api/storage/removeOutlineStorage", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "storage"}}, "POST")
+
+// 写入 data/storage 下独立存储的端点都不是 conf.json 的配置段,因此只持锁不广播。
+var SetOutlineStorage = define[OutlineStorageSetRequest, Null]("setOutlineStorage", "/api/storage/setOutlineStorage", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "storage", Mode: SettingSilent}}, "POST")
+var RemoveOutlineStorage = define[OutlineStorageRequest, Null]("removeOutlineStorage", "/api/storage/removeOutlineStorage", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "storage", Mode: SettingSilent}}, "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{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 PatchViewState = define[ViewStatePatchRequest, map[string]JSONValue]("patchViewState", "/api/storage/patchViewState", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "storage", Mode: SettingSilent}}, "POST")
+var RemoveViewState = define[StorageKeyRequest, Null]("removeViewState", "/api/storage/removeViewState", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "storage", Mode: SettingSilent}}, "POST")
var GetRecentDocs = define[RecentDocsRequest, []*RecentDoc]("getRecentDocs", "/api/storage/getRecentDocs", AuthenticatedAccess, LegacyOptionalBody, 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{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 SetCriterion = define[SetCriterionRequest, Null]("setCriterion", "/api/storage/setCriterion", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "storage", Mode: SettingSilent}}, "POST")
+var RemoveCriterion = define[RemoveCriterionRequest, Null]("removeCriterion", "/api/storage/removeCriterion", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "storage", Mode: SettingSilent}}, "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")
@@ -540,8 +543,10 @@ var GetDocOutline = define[OutlineRequest, []*SearchPath]("getDocOutline", "/api
var 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{Setting: SettingWrite{Namespace: "storage"}}, "POST")
-var SetWorkspaceAVPalette = define[WorkspaceAVPaletteRequest, *InlineStyles]("setWorkspaceAVPalette", "/api/storage/setWorkspaceAVPalette", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "storage"}}, "POST")
+
+// 行级样式与数据库调色板变化由 reloadInlineStyles 专用推送通知其他窗口,不走配置段刷新。
+var SetInlineStyles = define[SetInlineStylesRequest, *InlineStyles]("setInlineStyles", "/api/storage/setInlineStyles", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "storage", Mode: SettingSilent}}, "POST")
+var SetWorkspaceAVPalette = define[WorkspaceAVPaletteRequest, *InlineStyles]("setWorkspaceAVPalette", "/api/storage/setWorkspaceAVPalette", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "storage", Mode: SettingSilent}}, "POST")
var HTML2BlockDOM = define[HTMLClipboardRequest, HTMLClipboardData]("html2BlockDOM", "/api/lute/html2BlockDOM", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
@@ -637,9 +642,10 @@ var ResetLocalGraph = define[EmptyRequest, ResetLocalGraphData]("resetLocalGraph
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, Setting: SettingWrite{Namespace: "graph"}}, "POST")
+// 图谱查询需要与配置写入互斥;查询自带的配置由配置段发布负责通知,包装层不再补发。
+var GetGraph = define[GlobalGraphRequest, GlobalGraphData]("getGraph", "/api/graph/getGraph", AuthenticatedAccess, JSONBody, ResponseOptions{DataOnError: true, Setting: SettingWrite{Namespace: "graph", Mode: SettingSilent}}, "POST")
-var GetLocalGraph = define[LocalGraphRequest, LocalGraphData]("getLocalGraph", "/api/graph/getLocalGraph", AuthenticatedAccess, JSONBody, ResponseOptions{DataOnError: true, Setting: SettingWrite{Namespace: "graph"}}, "POST")
+var GetLocalGraph = define[LocalGraphRequest, LocalGraphData]("getLocalGraph", "/api/graph/getLocalGraph", AuthenticatedAccess, JSONBody, ResponseOptions{DataOnError: true, Setting: SettingWrite{Namespace: "graph", Mode: SettingSilent}}, "POST")
var RefreshBacklink = define[RefreshBacklinkRequest, Null]("refreshBacklink", "/api/ref/refreshBacklink", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
@@ -1151,6 +1157,7 @@ var SetBazaar = define[SetBazaarRequest, *SettingBazaar]("setBazaar", "/api/sett
// web 初始搜索为 Exa、抓取为直接请求,可独立切换到共用密钥的 DeepSeek。
// 工具调用轮数和输出 token 上限的负数归零;温度超出 0–2 回退 1。
// 嵌入并发数和批大小省略、null 或小于 1 时分别使用 8 和 10,超过上限时分别限制为 64 和 128。
+// 旧客户端的平铺 decision.endpoint、apiKey、name、timeout 迁移到 profiles.typesafe;提交 profiles 时以该对象为准。
// ChatGPT 账户绑定变化时与主配置一起可恢复提交,失败时回滚且不发布新配置;未变化时不访问绑定存储。
var SetAI = define[SetAIRequest, *SettingAI]("setAI", "/api/setting/setAI", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "ai", Merge: true}}, "POST")
var SetSecrets = define[SetSecretsRequest, *SettingSecrets]("setSecrets", "/api/setting/setSecrets", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "secrets", Merge: true}}, "POST")
@@ -1164,6 +1171,7 @@ var SetFlashcard = define[SetFlashcardRequest, *SettingFlashcard]("setFlashcard"
// 锚文本长度 1–5120 保持不变,小于 1 回退 64;字体大小超出 9–72 回退 16。
// backlinkGlobalSort、backlinkBlockSort、floatWindowMode、headingEmbedMode 仅接受 0、1、2,越界值回退 0。
// databaseAttrClickMode、databaseAttrViewMode 仅接受 0、1;codeTabSpaces 仅接受 0、2、4、6、8,越界值回退 0。
+// 只提交 fontFamily、fontWeight 时按新的首选字体重建 fontFamilies;显式提交 fontFamilies 时以该列表为准。
var SetEditor = define[SetEditorRequest, *SettingEditor]("setEditor", "/api/setting/setEditor", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "editor", Merge: true}}, "POST")
// PatchSetting 保留省略字段,成功后客户端重新读取配置;通知不包含密码或密钥。
@@ -1175,9 +1183,9 @@ var SetEditor = define[SetEditorRequest, *SettingEditor]("setEditor", "/api/sett
// sync.assetDownloadMode 的非法值仍拒绝写入;repo.indexRetentionDays 的正值不设上限。
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 后同步保存并回显。
+// SetExport 合并提交的导出配置,将 blockRefMode 的废弃值 0、1、5 转换为 4 后同步保存并回显。
// blockEmbedMode 仅接受 0、1,越界值回退 1;fileAnnotationRefMode 仅接受 0、1,越界值回退 0。
-// blockRefMode 的其他取值及字段省略、null 的解析行为保持不变。
+// blockRefMode 的其他取值原样保留;省略的字段保持当前值,null 还原默认值。
var SetExport = define[SetExportRequest, *SettingExport]("setExport", "/api/setting/setExport", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "export", Merge: true}}, "POST")
// SetFiletree 使用与启动、导入相同的路径和数值规范化规则。
@@ -1189,6 +1197,7 @@ var SetFiletree = define[SetFiletreeRequest, *SettingFileTree]("setFiletree", "/
var SetSearch = define[SetSearchRequest, *SettingSearch]("setSearch", "/api/setting/setSearch", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "search", Merge: true}}, "POST")
// SetAppearance 限定关闭按钮行为:closeButtonBehavior 仅接受 0、1,越界值回退 0。
+// entryVisibility 省略时保持当前方案,null 还原默认显隐方案。
var SetAppearance = define[SetAppearanceRequest, *SettingAppearance]("setAppearance", "/api/setting/setAppearance", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "appearance", Merge: true}}, "POST")
// SetEntryVisibility 的版本 7 方案可用 defaults 指定 simple 或 full,未覆盖的显隐跟随该内置方案。
diff --git a/kernel/apicontract/setting_write.go b/kernel/apicontract/setting_write.go
index a74205abdc..6b2c959c0d 100644
--- a/kernel/apicontract/setting_write.go
+++ b/kernel/apicontract/setting_write.go
@@ -4,10 +4,11 @@ package apicontract
type SettingWriteMode int
const (
- // SettingNotify 在配置互斥锁内执行处理器,成功后向全部主界面广播 settingChanged 和命名空间。
+ // SettingNotify 在配置互斥锁内执行处理器,处理器未发布新的段修订时由包装层补发 settingChanged。
+ // 适用于写入 conf.json 普通配置段、但自身不经过配置段提交通知的端点。
SettingNotify SettingWriteMode = iota
- // SettingSilent 仅在配置互斥锁内执行,用于独立存储的布局、本地偏好和启动外观选择。
- // conf.json 的普通配置段使用 SettingNotify,由提交漏斗发布变更。
+ // SettingSilent 仅在配置互斥锁内执行,不补发通知。
+ // 用于独立存储、仍然需要互斥的读取端点,以及写入由处理器自行发布通知的配置。
SettingSilent
// SettingSelfManaged 由处理器自行加锁和广播:命名空间取决于请求内容,或加锁前需要等待外部条件。
SettingSelfManaged
@@ -19,6 +20,7 @@ type SettingWrite struct {
Namespace string // 变更通知中的配置命名空间,"*" 表示可能涉及多个配置段
Mode SettingWriteMode
// Merge 声明请求体与配置段同构:解码前先合并进当前段,未提交的字段保持当前值,null 还原默认值。
+ // 合并语义由 contractHandler 统一执行,与 /api/setting/patch 共用同一套输入迁移。
Merge bool
}
diff --git a/kernel/model/conf_notify.go b/kernel/model/conf_notify.go
index f37e277b0f..cf33c99fed 100644
--- a/kernel/model/conf_notify.go
+++ b/kernel/model/conf_notify.go
@@ -4,6 +4,7 @@ import (
"sync"
"sync/atomic"
+ "github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -19,7 +20,13 @@ func ConfNamespaceRevision(namespace string) uint64 {
}
// NotifyConfChanged 统一发布配置提交通知,不在事件中携带配置或凭据。
+// 客户端收到通知后按命名空间读取配置段,未知命名空间会让这次读取失败并向用户报错,
+// 因此这里只记录日志而不广播。写入独立存储的端点不应走到这里。
func NotifyConfChanged(namespace string) {
+ if !confNamespaceReadable(namespace) {
+ logging.LogErrorf("skip setting change notification for unknown namespace [%s]", namespace)
+ return
+ }
revision := ConfSettingRevision.Add(1)
value, _ := confNamespaceRevisions.LoadOrStore(namespace, &atomic.Uint64{})
value.(*atomic.Uint64).Store(revision)
@@ -28,3 +35,13 @@ func NotifyConfChanged(namespace string) {
Revision uint64 `json:"revision"`
}{namespace, revision})
}
+
+// confNamespaceReadable 报告命名空间能否被读取配置段的接口解析。
+// 这里只查注册表,不构造配置段,避免在配置锁之外触碰段容器。
+func confNamespaceReadable(namespace string) bool {
+ if "*" == namespace || nil == Conf {
+ return true
+ }
+ _, ok := confSectionSpecFactories[namespace]
+ return ok
+}
diff --git a/kernel/model/conf_notify_test.go b/kernel/model/conf_notify_test.go
new file mode 100644
index 0000000000..c84743578b
--- /dev/null
+++ b/kernel/model/conf_notify_test.go
@@ -0,0 +1,22 @@
+package model
+
+import "testing"
+
+// 客户端按命名空间读取配置段,未注册的命名空间不能发布通知,否则客户端读取失败并提示用户。
+func TestNotifyConfChangedRequiresKnownNamespace(t *testing.T) {
+ previousConf := Conf
+ Conf = NewAppConf()
+ t.Cleanup(func() { Conf = previousConf })
+
+ before := ConfSettingRevision.Load()
+ for _, namespace := range []string{"storage", "localStorage", "unknown"} {
+ NotifyConfChanged(namespace)
+ if ConfNamespaceRevision(namespace) != 0 || ConfSettingRevision.Load() != before {
+ t.Fatalf("unknown namespace %q published a configuration notification", namespace)
+ }
+ }
+ NotifyConfChanged("editor")
+ if ConfNamespaceRevision("editor") == 0 || ConfSettingRevision.Load() == before {
+ t.Fatal("registered namespace did not publish a configuration notification")
+ }
+}