An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Enforce configuration value ranges https://github.com/siyuan-note/siyuan/issues/20468
Daniel775b0a11f809
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex b4258b580d..4516cd0d8b 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -6580,6 +6580,9 @@ export interface APIPOSTRoutes {* export.blockRefMode 的旧值 0、1、5 按旧设置接口的兼容语义转换为 4;启动迁移由配置版本控制。* 同步地址沿用专用保存接口的校验,更换来源须保留完整资源检查,间隔使用规范化后的值调度。* 存在字段诊断时在 data.issues 返回;error 阻止写入,warning 随已规范化的成功结果返回。+ * 编辑器、导出、搜索、文档树、外观、闪卡和智能体字段使用对应设置接口的范围规范化规则。+ * system.autoLaunch2 仅接受 0、1、2,lockScreenMode 仅接受 0、1,越界值回退 0。+ * sync.assetDownloadMode 的非法值仍拒绝写入;repo.indexRetentionDays 的正值不设上限。*/"/api/setting/patch": {request: PatchSettingRequestInput;@@ -6612,6 +6615,10 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * 使用共享规范化规则;智能体确认超时负数回退 600 秒,0 保留无限等待语义。+ * 工具调用轮数和输出 token 上限的负数归零;温度超出 0–2 回退 1。+ */"/api/setting/setAI": {request: SetAIRequestInput;response: { "code": 0; "data": SettingAI | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -6619,6 +6626,9 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * 限定关闭按钮行为:closeButtonBehavior 仅接受 0、1,越界值回退 0。+ */"/api/setting/setAppearance": {request: SetAppearanceRequestInput;response: { "code": 0; "data": SettingAppearance | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -6650,6 +6660,8 @@ 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。*/"/api/setting/setEditor": {request: SetEditorRequestInput;@@ -6685,7 +6697,8 @@ export interface APIPOSTRoutes {};/*** 整体替换导出配置,将 blockRefMode 的废弃值 0、1、5 转换为 4 后同步保存并回显。- * 其他取值及字段省略、null 的解析行为保持不变。+ * blockEmbedMode 仅接受 0、1,越界值回退 1;fileAnnotationRefMode 仅接受 0、1,越界值回退 0。+ * blockRefMode 的其他取值及字段省略、null 的解析行为保持不变。*/"/api/setting/setExport": {request: SetExportRequestInput;@@ -6696,6 +6709,7 @@ export interface APIPOSTRoutes {};/*** 使用与启动、导入相同的路径和数值规范化规则;省略顶层笔记本文档和默认图标选项时保留当前值。+ * maxListCount 小于 1 回退 512,largeFileWarningSize 小于 2 回退 8,两者大于 10240 时截断至 10240。*/"/api/setting/setFiletree": {request: SetFiletreeRequestInput;@@ -6706,6 +6720,7 @@ export interface APIPOSTRoutes {};/*** 使用与启动、导入相同的规范化规则;保留零张上限,非法记忆参数和权重恢复默认值。+ * reviewMode 仅接受 0、1、2,越界值回退 0。*/"/api/setting/setFlashcard": {request: SetFlashcardRequestInput;@@ -6737,6 +6752,7 @@ export interface APIPOSTRoutes {};/*** 使用与启动、导入相同的规范化规则;limit 小于 1 回退 64,1–31 提升至 32。+ * limit 大于 10240 时截断至 10240。* 省略汉字敏感、自定义块和脑图选项时保留当前值;反链提及关键词上限小于 1 回退 512。*/"/api/setting/setSearch": {diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.tsindex ab23ba663f..8b4d7dc609 100644--- a/app/src/types/config.d.ts+++ b/app/src/types/config.d.ts@@ -160,10 +160,14 @@ declare namespace Config {modelId: string;sessionTimeout: number;streamIdleTimeout: number;+ /** 确认等待秒数;负数回退 600,0 保留无限等待语义 */confirmTimeout: number;maxRetries: number;+ /** 有效范围为 0–2;越界值在配置规范化时回退 1 */temperature: number;+ /** 输出 token 上限;负数归零,0 表示使用模型默认值 */maxCompletionTokens: number;+ /** 工具调用轮数上限;负数归零,0 表示不限制轮数 */maxToolCallRounds: number;capabilityPolicy: ICapabilityPolicy;skills: {@@ -325,6 +329,7 @@ declare namespace Config {* Close button behavior* - `0`: Exit application* - `1`: Minimize to pallets+ * 仅接受 0、1,越界值在配置规范化时回退 0*/closeButtonBehavior: number;/**@@ -594,7 +599,9 @@ declare namespace Config {* Backlink sort mode*/backlinkSort: number;+ /** 仅接受 0、1、2,越界值在配置规范化时回退 0 */backlinkGlobalSort: number;+ /** 仅接受 0、1、2,越界值在配置规范化时回退 0 */backlinkBlockSort: number;/*** Backmention sort mode@@ -623,6 +630,7 @@ declare namespace Config {/*** The number of spaces generated by the Tab key in the code block, configured as 0 means no* conversion to spaces+ * 仅接受 0、2、4、6、8,其他值回退 0;0 保留制表符*/codeTabSpaces: number;/**@@ -645,12 +653,14 @@ declare namespace Config {* Behavior when clicking a database badge* - `0`: Focus the block and expand the database panel* - `1`: Open the block attribute panel+ * 仅接受 0、1,越界值在配置规范化时回退 0*/databaseAttrClickMode: number;/*** Default state of database attributes* - `0`: Expanded* - `1`: Collapsed+ * 仅接受 0、1,越界值在配置规范化时回退 0*/databaseAttrViewMode: number;/**@@ -686,6 +696,7 @@ declare namespace Config {* - `0`: Show title with blocks below (default)* - `1`: Show only title* - `2`: Show only blocks below title+ * 仅接受 0、1、2,越界值在配置规范化时回退 0*/headingEmbedMode: number;/**@@ -697,6 +708,7 @@ declare namespace Config {* - `0`: Hover over the cursor* - `1`: Hover over the cursor while holding down Ctrl* - `2`: Do not trigger the floating window+ * 仅接受 0、1、2,越界值在配置规范化时回退 0*/floatWindowMode: number;/**@@ -822,6 +834,7 @@ declare namespace Config {* Embedded block export mode* - `0`: Original block content* - `1`: Quotation block+ * 仅接受 0、1,越界值在配置规范化时回退 1*/blockEmbedMode: number;/**@@ -846,6 +859,7 @@ declare namespace Config {* File annotation reference export mode* - `0`: File name - page number - anchor text* - `1`: Anchor text only+ * 仅接受 0、1,越界值在配置规范化时回退 0*/fileAnnotationRefMode: number;/**@@ -960,6 +974,7 @@ declare namespace Config {docCreateTemplatePath: string;/*** The maximum number of documents listed+ * 有效范围为 1–10240;小于 1 回退 512,大于 10240 截断至 10240*/maxListCount: number;/**@@ -1020,6 +1035,7 @@ declare namespace Config {useSingleLineSave: boolean;/*** The .sy and database .json files larger than this value will prompt a warning (unit: MB)+ * 有效范围为 2–10240 MB;小于 2 回退 8,大于 10240 截断至 10240*/largeFileWarningSize: number;/**@@ -1081,6 +1097,7 @@ declare namespace Config {* - `0`: New and old mixed* - `1`: New card priority* - `2`: Old card priority+ * 仅接受 0、1、2,越界值在配置规范化时回退 0*/reviewMode: number;/**@@ -1686,6 +1703,7 @@ declare namespace Config {indexAssetPath: boolean;/*** Number of search results displayed+ * 有效范围为 32–10240;小于 1 回退 64,1–31 提升至 32,大于 10240 截断至 10240*/limit: number;/**@@ -1870,6 +1888,7 @@ declare namespace Config {generateConflictDoc: boolean;/*** 当前设备的资源下载模式,0:全部下载,1:按需下载。+ * 仅接受 0、1;启动时越界值回退 0,写入 API 拒绝非法值并保留资源完整性检查*/assetDownloadMode: number;/**@@ -2028,6 +2047,7 @@ declare namespace Config {* - `0`: Do not boot automatically* - `1`: Boot automatically* - `2`: Boot automatically + Minimize UI+ * 仅接受 0、1、2,越界值在配置规范化时回退 0*/autoLaunch2: number;/**@@ -2075,6 +2095,7 @@ declare namespace Config {* Lock screen mode* - `0`: Manual* - `1`: Manual + Follow the operating system+ * 仅接受 0、1,越界值在配置规范化时回退 0*/lockScreenMode: number;encryptedNotebookFollowSystemLock: boolean;diff --git a/kernel/api/contract_setting_normalize_test.go b/kernel/api/contract_setting_normalize_test.goindex 0c3c1a0cfb..7808321000 100644--- a/kernel/api/contract_setting_normalize_test.go+++ b/kernel/api/contract_setting_normalize_test.go@@ -71,11 +71,15 @@ func TestAPIContractImportedSettingsNormalization(t *testing.T) {previous, temp, readOnly := model.Conf, util.TempDir, util.ReadOnlyutil.TempDir, util.ReadOnly = t.TempDir(), truet.Cleanup(func() { model.Conf, util.TempDir, util.ReadOnly = previous, temp, readOnly })- for _, payload := range []string{- `{"editor":{"blockRefDynamicAnchorTextMaxLen":1,"fontSize":100},"export":{"blockRefMode":0},"fileTree":{"maxListCount":0},"search":{"limit":0},"flashcard":{"weights":"invalid"}}`,- `{"editor":null,"export":null,"fileTree":null,"search":null,"flashcard":null}`,- `{"export":{"blockRefMode":1}}`,- `{"export":{"blockRefMode":5}}`,+ for _, entry := range []struct {+ payload string+ maxListCount, searchLimit int+ }{+ {`{"editor":{"blockRefDynamicAnchorTextMaxLen":1,"fontSize":100},"export":{"blockRefMode":0},"fileTree":{"maxListCount":0},"search":{"limit":0},"flashcard":{"weights":"invalid"}}`, 512, 64},+ {`{"editor":null,"export":null,"fileTree":null,"search":null,"flashcard":null}`, 512, 64},+ {`{"export":{"blockRefMode":1}}`, 512, 64},+ {`{"export":{"blockRefMode":5}}`, 512, 64},+ {`{"editor":{"backlinkGlobalSort":7,"codeTabSpaces":5},"export":{"blockRefMode":0,"blockEmbedMode":9,"fileAnnotationRefMode":-5},"fileTree":{"maxListCount":1000000},"search":{"limit":1000000},"flashcard":{"reviewMode":7}}`, 10240, 10240},} {model.Conf = model.NewAppConf()originalSync := model.Conf.Sync.Load()@@ -85,7 +89,7 @@ func TestAPIContractImportedSettingsNormalization(t *testing.T) {if err != nil {t.Fatal(err)}- if _, err = part.Write([]byte(payload)); err != nil {+ if _, err = part.Write([]byte(entry.payload)); err != nil {t.Fatal(err)}if err = writer.Close(); err != nil {@@ -105,9 +109,14 @@ func TestAPIContractImportedSettingsNormalization(t *testing.T) {}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.FileTree.Load().MaxListCount != entry.maxListCount || model.Conf.Search.Load().Limit != entry.searchLimit ||+ model.Conf.Editor.Load().BacklinkGlobalSort != 0 || model.Conf.Editor.Load().CodeTabSpaces != 0 ||+ model.Conf.Export.Load().FileAnnotationRefMode != 0 || model.Conf.Flashcard.Load().ReviewMode != 0 ||model.Conf.Flashcard.Load().Weights != conf.DefaultFSRSWeights() || model.Conf.Sync.Load() != originalSync {t.Fatal("import did not normalize preferences or replaced sync configuration")}+ if entry.maxListCount == 10240 && model.Conf.Export.Load().BlockEmbedMode != 1 {+ t.Fatal("import did not restore the default block embed mode")+ }}}diff --git a/kernel/api/contract_setting_ranges_test.go b/kernel/api/contract_setting_ranges_test.gonew file mode 100644index 0000000000..1dd1034a94--- /dev/null+++ b/kernel/api/contract_setting_ranges_test.go@@ -0,0 +1,100 @@+package api++import (+ "encoding/json"+ "strings"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAPIContractSettingValueRanges(t *testing.T) {+ previous, readonly, lang := model.Conf, util.ReadOnly, util.Lang+ markdown, singleLine, largeFile := util.MarkdownSettings.Load(), util.UseSingleLineSave.Load(), util.LargeFileWarningSize.Load()+ statusBar, notifications := util.StatusBarCfg.Load(), util.NotificationsCfg.Load()+ t.Cleanup(func() {+ model.Conf, util.ReadOnly, util.Lang = previous, readonly, lang+ util.MarkdownSettings.Store(markdown)+ util.UseSingleLineSave.Store(singleLine)+ util.LargeFileWarningSize.Store(largeFile)+ util.StatusBarCfg.Store(statusBar)+ util.NotificationsCfg.Store(notifications)+ if previous != nil && previous.Search.Load() != nil {+ model.ApplySearchRuntime()+ }+ })+ util.ReadOnly = true+ for _, entry := range []struct {+ namespace, route string+ handler gin.HandlerFunc+ payload string+ want map[string]float64+ }{+ {"editor", "setEditor", setEditor,+ `{"backlinkGlobalSort":7,"backlinkBlockSort":-9,"floatWindowMode":42,"headingEmbedMode":-3,"databaseAttrClickMode":99,"databaseAttrViewMode":-1,"codeTabSpaces":5,"fontSize":18}`,+ map[string]float64{"backlinkGlobalSort": 0, "backlinkBlockSort": 0, "floatWindowMode": 0, "headingEmbedMode": 0,+ "databaseAttrClickMode": 0, "databaseAttrViewMode": 0, "codeTabSpaces": 0, "fontSize": 18}},+ {"export", "setExport", setExport, `{"blockEmbedMode":9,"fileAnnotationRefMode":-5,"blockRefMode":3}`,+ map[string]float64{"blockEmbedMode": 1, "fileAnnotationRefMode": 0, "blockRefMode": 3}},+ {"fileTree", "setFiletree", setFiletree, `{"maxListCount":1000000,"largeFileWarningSize":1000000}`,+ map[string]float64{"maxListCount": 10240, "largeFileWarningSize": 10240}},+ {"search", "setSearch", setSearch, `{"limit":1000000}`, map[string]float64{"limit": 10240}},+ {"flashcard", "setFlashcard", setFlashcard, `{"reviewMode":7}`, map[string]float64{"reviewMode": 0}},+ {"ai", "setAI", setAI, `{"agent":{"maxToolCallRounds":-7,"confirmTimeout":-9,"temperature":-3,"maxCompletionTokens":-2}}`,+ map[string]float64{"agent.maxToolCallRounds": 0, "agent.confirmTimeout": 600, "agent.temperature": 1, "agent.maxCompletionTokens": 0}},+ {"system", "", nil, `{"autoLaunch2":9,"lockScreenMode":3}`, map[string]float64{"autoLaunch2": 0, "lockScreenMode": 0}},+ {"repo", "", nil, `{"indexRetentionDays":100000}`, map[string]float64{"indexRetentionDays": 100000}},+ } {+ for _, patch := range []bool{false, true} {+ route, handler, body := entry.route, entry.handler, entry.payload+ if patch {+ route, handler = "patch", patchSetting+ body = `{"` + entry.namespace + `":` + body + `}`+ } else if handler == nil {+ continue+ }+ t.Run(entry.namespace+"/"+route, func(t *testing.T) {+ model.Conf = model.NewAppConf()+ model.NormalizeAppConf(model.Conf)+ code, message, _ := settingContractRequest(t, route, handler, body)+ if code != 0 {+ t.Fatalf("setting failed: %d %s", code, message)+ }+ data, err := json.Marshal(model.Conf)+ if err != nil {+ t.Fatal(err)+ }+ var actual map[string]any+ if err = json.Unmarshal(data, &actual); err != nil {+ t.Fatal(err)+ }+ for field, want := range entry.want {+ value := actual[entry.namespace]+ for _, key := range strings.Split(field, ".") {+ value = value.(map[string]any)[key]+ }+ if value != want {+ t.Errorf("%s.%s: got %v, want %v", entry.namespace, field, value, want)+ }+ }+ })+ }+ }+}++func TestAPIContractSettingPatchRejectsInvalidAssetDownloadMode(t *testing.T) {+ previous, readonly := model.Conf, util.ReadOnly+ t.Cleanup(func() { model.Conf, util.ReadOnly = previous, readonly })+ model.Conf = model.NewAppConf()+ model.NormalizeAppConf(model.Conf)+ util.ReadOnly = true+ before := model.Conf.Sync.Load()+ revision := model.ConfNamespaceRevision("sync")+ code, message, _ := settingContractRequest(t, "patch", patchSetting, `{"sync":{"assetDownloadMode":7}}`)+ if code == 0 || message != "invalid asset download mode" || model.Conf.Sync.Load() != before ||+ model.ConfNamespaceRevision("sync") != revision {+ t.Fatalf("invalid mode was accepted or modified configuration: %d %s", code, message)+ }+}diff --git a/kernel/api/setting_appearance_refresh_test.go b/kernel/api/setting_appearance_refresh_test.goindex 35e856e904..58e14856f7 100644--- a/kernel/api/setting_appearance_refresh_test.go+++ b/kernel/api/setting_appearance_refresh_test.go@@ -70,12 +70,14 @@ func TestAPIContractAppearanceSameSelectionRefreshesPackages(t *testing.T) {selected := conf.NewAppearance()selected.ThemeLight, selected.ThemeDark, selected.Icon = "custom", "custom", "custom"selected.ModeOS, selected.HideStatusBar = false, true+ selected.CloseButtonBehavior = 5body, err := json.Marshal(selected)if err != nil {t.Fatal(err)}code, message, _ := settingContractRequest(t, "setAppearance", setAppearance, string(body))- if code != 0 || model.Conf.Appearance.Load().ThemeLight != "custom" || model.Conf.Appearance.Load().Icon != "custom" {+ if code != 0 || model.Conf.Appearance.Load().ThemeLight != "custom" || model.Conf.Appearance.Load().Icon != "custom" ||+ model.Conf.Appearance.Load().CloseButtonBehavior != 0 {t.Fatalf("initial package selection failed: %d %s", code, message)}model.CloseWatchThemes()@@ -90,7 +92,7 @@ func TestAPIContractAppearanceSameSelectionRefreshesPackages(t *testing.T) {code, message, data = settingContractRequest(t, endpoint, setAppearance, string(body))} else {code, message, data = settingContractRequest(t, endpoint, patchSetting,- `{"appearance":{"themeLight":"custom","themeDark":"custom","icon":"custom"}}`)+ `{"appearance":{"themeLight":"custom","themeDark":"custom","icon":"custom","closeButtonBehavior":5}}`)}if code != 0 {t.Fatalf("refresh failed: %d %s", code, message)@@ -98,7 +100,7 @@ func TestAPIContractAppearanceSameSelectionRefreshesPackages(t *testing.T) {assertFallback := func(value *conf.Appearance) {t.Helper()if value.ThemeLight != "daylight" || value.ThemeDark != "midnight" || value.Icon != "litheness" ||- value.ThemeVer != "1.0.0" || value.IconVer != "1.0.0" || !value.HideStatusBar {+ value.ThemeVer != "1.0.0" || value.IconVer != "1.0.0" || !value.HideStatusBar || value.CloseButtonBehavior != 0 {t.Fatalf("refresh did not expose the final fallback snapshot: %+v", value)}}diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex 7211c347a8..3e6e1cd957 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -1080,33 +1080,47 @@ var UploadAsset = define[UploadAssetRequest, AssetUploadData]("uploadAsset", "/avar 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")++// SetAI 使用共享规范化规则;智能体确认超时负数回退 600 秒,0 保留无限等待语义。+// 工具调用轮数和输出 token 上限的负数归零;温度超出 0–2 回退 1。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 使用与启动、导入相同的规范化规则;保留零张上限,非法记忆参数和权重恢复默认值。+// reviewMode 仅接受 0、1、2,越界值回退 0。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;省略字体列表和图片标题字段时继续保留原有兼容行为。+// backlinkGlobalSort、backlinkBlockSort、floatWindowMode、headingEmbedMode 仅接受 0、1、2,越界值回退 0。+// databaseAttrClickMode、databaseAttrViewMode 仅接受 0、1;codeTabSpaces 仅接受 0、2、4、6、8,越界值回退 0。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;启动迁移由配置版本控制。// 同步地址沿用专用保存接口的校验,更换来源须保留完整资源检查,间隔使用规范化后的值调度。// 存在字段诊断时在 data.issues 返回;error 阻止写入,warning 随已规范化的成功结果返回。+// 编辑器、导出、搜索、文档树、外观、闪卡和智能体字段使用对应设置接口的范围规范化规则。+// system.autoLaunch2 仅接受 0、1、2,lockScreenMode 仅接受 0、1,越界值回退 0。+// 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 后同步保存并回显。-// 其他取值及字段省略、null 的解析行为保持不变。+// blockEmbedMode 仅接受 0、1,越界值回退 1;fileAnnotationRefMode 仅接受 0、1,越界值回退 0。+// blockRefMode 的其他取值及字段省略、null 的解析行为保持不变。var SetExport = define[SetExportRequest, *SettingExport]("setExport", "/api/setting/setExport", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "export"}}, "POST")// SetFiletree 使用与启动、导入相同的路径和数值规范化规则;省略顶层笔记本文档和默认图标选项时保留当前值。+// maxListCount 小于 1 回退 512,largeFileWarningSize 小于 2 回退 8,两者大于 10240 时截断至 10240。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。+// limit 大于 10240 时截断至 10240。// 省略汉字敏感、自定义块和脑图选项时保留当前值;反链提及关键词上限小于 1 回退 512。var SetSearch = define[SetSearchRequest, *SettingSearch]("setSearch", "/api/setting/setSearch", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "search"}}, "POST")++// SetAppearance 限定关闭按钮行为:closeButtonBehavior 仅接受 0、1,越界值回退 0。var SetAppearance = define[SetAppearanceRequest, *SettingAppearance]("setAppearance", "/api/setting/setAppearance", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "appearance"}}, "POST")// SetEntryVisibility 的版本 7 方案可用 defaults 指定 simple 或 full,未覆盖的显隐跟随该内置方案。diff --git a/kernel/conf/ai.go b/kernel/conf/ai.goindex a1adb536ef..b5b389c281 100644--- a/kernel/conf/ai.go+++ b/kernel/conf/ai.go@@ -20,6 +20,7 @@ import ("encoding/hex""encoding/json""fmt"+ "math""net/url""os""strconv"@@ -719,6 +720,14 @@ func (ai *AI) Normalize() {} else if ai.Agent.MaxRetries > 10 {ai.Agent.MaxRetries = 10}+ if ai.Agent.ConfirmTimeout < 0 {+ ai.Agent.ConfirmTimeout = DefaultAgentConfirmTimeout+ }+ ai.Agent.MaxToolCallRounds = max(0, ai.Agent.MaxToolCallRounds)+ if ai.Agent.Temperature < 0 || ai.Agent.Temperature > 2 || math.IsNaN(ai.Agent.Temperature) {+ ai.Agent.Temperature = defaultAgent().Temperature+ }+ ai.Agent.MaxCompletionTokens = max(0, ai.Agent.MaxCompletionTokens)}ai.pruneOrphanedMCPCapabilityPolicies()if ai.Editing == nil {diff --git a/kernel/conf/settings_normalize.go b/kernel/conf/settings_normalize.goindex 4552a71c5c..c0cffc8b72 100644--- a/kernel/conf/settings_normalize.go+++ b/kernel/conf/settings_normalize.go@@ -16,6 +16,7 @@ func NormalizeFileTree(fileTree *FileTree) *FileTree {if fileTree.MaxListCount < 1 {fileTree.MaxListCount = 512}+ fileTree.MaxListCount = min(10240, fileTree.MaxListCount)if fileTree.MaxOpenTabCount < 1 {fileTree.MaxOpenTabCount = 8}@@ -46,6 +47,7 @@ func NormalizeFileTree(fileTree *FileTree) *FileTree {if fileTree.LargeFileWarningSize < 2 {fileTree.LargeFileWarningSize = 8}+ fileTree.LargeFileWarningSize = min(10240, fileTree.LargeFileWarningSize)if fileTree.CreateDocAtTop == nil {fileTree.CreateDocAtTop = new(true)}@@ -86,6 +88,29 @@ func NormalizeEditor(editor *Editor) *Editor {if editor.FontSize < 9 || editor.FontSize > 72 {editor.FontSize = 16}+ if editor.BacklinkGlobalSort < 0 || editor.BacklinkGlobalSort > 2 {+ editor.BacklinkGlobalSort = defaults.BacklinkGlobalSort+ }+ if editor.BacklinkBlockSort < 0 || editor.BacklinkBlockSort > 2 {+ editor.BacklinkBlockSort = defaults.BacklinkBlockSort+ }+ if editor.FloatWindowMode < 0 || editor.FloatWindowMode > 2 {+ editor.FloatWindowMode = defaults.FloatWindowMode+ }+ if editor.HeadingEmbedMode < 0 || editor.HeadingEmbedMode > 2 {+ editor.HeadingEmbedMode = defaults.HeadingEmbedMode+ }+ if editor.DatabaseAttrClickMode < 0 || editor.DatabaseAttrClickMode > 1 {+ editor.DatabaseAttrClickMode = defaults.DatabaseAttrClickMode+ }+ if editor.DatabaseAttrViewMode < 0 || editor.DatabaseAttrViewMode > 1 {+ editor.DatabaseAttrViewMode = defaults.DatabaseAttrViewMode+ }+ switch editor.CodeTabSpaces {+ case 0, 2, 4, 6, 8:+ default:+ editor.CodeTabSpaces = defaults.CodeTabSpaces+ }if editor.PlantUMLServePath == "" {editor.PlantUMLServePath = defaults.PlantUMLServePath}@@ -130,8 +155,15 @@ func NormalizeEditor(editor *Editor) *Editor {// NormalizeExport 补全缺失的导出配置,不推断配置格式版本。func NormalizeExport(export *Export) *Export {+ defaults := NewExport()if export == nil {- export = NewExport()+ export = defaults+ }+ if export.BlockEmbedMode < 0 || export.BlockEmbedMode > 1 {+ export.BlockEmbedMode = defaults.BlockEmbedMode+ }+ if export.FileAnnotationRefMode < 0 || export.FileAnnotationRefMode > 1 {+ export.FileAnnotationRefMode = defaults.FileAnnotationRefMode}return export}@@ -162,7 +194,7 @@ func NormalizeSearch(search *Search) *Search {if search.Limit < 1 {search.Limit = 64}- search.Limit = max(32, search.Limit)+ search.Limit = max(32, min(10240, search.Limit))if search.BacklinkMentionKeywordsLimit < 1 {search.BacklinkMentionKeywordsLimit = 512}@@ -178,6 +210,9 @@ func NormalizeFlashcard(flashcard *Flashcard) (*Flashcard, string) {if flashcard == nil {flashcard = defaults}+ if flashcard.ReviewMode < 0 || flashcard.ReviewMode > 2 {+ flashcard.ReviewMode = defaults.ReviewMode+ }if flashcard.NewCardLimit < 0 {flashcard.NewCardLimit = defaults.NewCardLimit}@@ -218,6 +253,9 @@ func NormalizeAppearance(appearance *Appearance, mobile bool) *Appearance {if appearance == nil {appearance = NewAppearanceForContainer(mobile)}+ if appearance.CloseButtonBehavior < 0 || appearance.CloseButtonBehavior > 1 {+ appearance.CloseButtonBehavior = 0+ }if "ant" == appearance.Icon || "material" == appearance.Icon {// v3.7.0 移除了 ant/material 图标包 https://github.com/siyuan-note/siyuan/issues/7976appearance.Icon = "litheness"@@ -242,6 +280,9 @@ func NormalizeSync(sync *Sync) *Sync {if sync == nil {sync = NewSync()}+ if sync.AssetDownloadMode < 0 || sync.AssetDownloadMode > 1 {+ sync.AssetDownloadMode = 0+ }if 0 == sync.Mode {sync.Mode = 1}@@ -279,6 +320,12 @@ func NormalizeSystem(system *System) *System {if system == nil {system = NewSystem()}+ if system.AutoLaunch2 < 0 || system.AutoLaunch2 > 2 {+ system.AutoLaunch2 = 0+ }+ if system.LockScreenMode < 0 || system.LockScreenMode > 1 {+ system.LockScreenMode = 0+ }if nil == system.NetworkProxy {system.NetworkProxy = &NetworkProxy{}}diff --git a/kernel/conf/settings_ranges_test.go b/kernel/conf/settings_ranges_test.gonew file mode 100644index 0000000000..320c76765c--- /dev/null+++ b/kernel/conf/settings_ranges_test.go@@ -0,0 +1,101 @@+package conf++import (+ "encoding/json"+ "math"+ "reflect"+ "strconv"+ "testing"+)++func checkNormalizedIntValues[T any](t *testing.T, constructor func() *T, normalize func(*T) *T,+ field string, cases [][2]int) {+ t.Helper()+ for _, entry := range cases {+ t.Run(field+"/"+strconv.Itoa(entry[0]), func(t *testing.T) {+ value := constructor()+ reflect.ValueOf(value).Elem().FieldByName(field).SetInt(int64(entry[0]))+ value = normalize(value)+ actual := reflect.ValueOf(value).Elem().FieldByName(field).Int()+ if actual != int64(entry[1]) {+ t.Fatalf("%s: input %d, got %d, want %d", field, entry[0], actual, entry[1])+ }+ before, err := json.Marshal(value)+ if err != nil {+ t.Fatal(err)+ }+ after, err := json.Marshal(normalize(value))+ if err != nil || string(before) != string(after) {+ t.Fatalf("normalization is not idempotent: %s -> %s (%v)", before, after, err)+ }+ })+ }+}++func TestNormalizeSettingsEnumRanges(t *testing.T) {+ binary := [][2]int{{-9, 0}, {-1, 0}, {0, 0}, {1, 1}, {2, 0}, {7, 0}, {math.MaxInt, 0}}+ ternary := [][2]int{{-9, 0}, {-1, 0}, {0, 0}, {1, 1}, {2, 2}, {3, 0}, {42, 0}, {math.MaxInt, 0}}+ for _, field := range []string{"BacklinkGlobalSort", "BacklinkBlockSort", "FloatWindowMode", "HeadingEmbedMode"} {+ checkNormalizedIntValues(t, NewEditor, NormalizeEditor, field, ternary)+ }+ for _, field := range []string{"DatabaseAttrClickMode", "DatabaseAttrViewMode"} {+ checkNormalizedIntValues(t, NewEditor, NormalizeEditor, field, binary)+ }+ checkNormalizedIntValues(t, NewEditor, NormalizeEditor, "CodeTabSpaces",+ [][2]int{{-1, 0}, {0, 0}, {1, 0}, {2, 2}, {3, 0}, {4, 4}, {5, 0}, {6, 6}, {7, 0}, {8, 8}, {9, 0}, {math.MaxInt, 0}})+ checkNormalizedIntValues(t, NewEditor, NormalizeEditor, "FontSize",+ [][2]int{{8, 16}, {9, 9}, {16, 16}, {72, 72}, {73, 16}, {200, 16}})+ checkNormalizedIntValues(t, NewExport, NormalizeExport, "BlockEmbedMode",+ [][2]int{{-5, 1}, {-1, 1}, {0, 0}, {1, 1}, {2, 1}, {9, 1}, {math.MaxInt, 1}})+ checkNormalizedIntValues(t, NewExport, NormalizeExport, "FileAnnotationRefMode", binary)+ checkNormalizedIntValues(t, NewAppearance, func(value *Appearance) *Appearance {+ return NormalizeAppearance(value, false)+ }, "CloseButtonBehavior", binary)+ checkNormalizedIntValues(t, NewSync, NormalizeSync, "AssetDownloadMode", binary)+ checkNormalizedIntValues(t, NewSystem, NormalizeSystem, "AutoLaunch2", ternary)+ checkNormalizedIntValues(t, NewSystem, NormalizeSystem, "LockScreenMode", binary)+ checkNormalizedIntValues(t, NewFlashcard, func(value *Flashcard) *Flashcard {+ value, warning := NormalizeFlashcard(value)+ if warning != "" {+ t.Fatal(warning)+ }+ return value+ }, "ReviewMode", ternary)+}++func TestNormalizeSettingsNumericRanges(t *testing.T) {+ checkNormalizedIntValues(t, NewSearch, NormalizeSearch, "Limit",+ [][2]int{{-1, 64}, {0, 64}, {1, 32}, {31, 32}, {32, 32}, {64, 64}, {10240, 10240}, {10241, 10240}, {1000000, 10240}})+ checkNormalizedIntValues(t, NewFileTree, NormalizeFileTree, "MaxListCount",+ [][2]int{{-1, 512}, {0, 512}, {1, 1}, {512, 512}, {10240, 10240}, {10241, 10240}, {1000000, 10240}})+ checkNormalizedIntValues(t, NewFileTree, NormalizeFileTree, "LargeFileWarningSize",+ [][2]int{{-1, 8}, {0, 8}, {1, 8}, {2, 2}, {8, 8}, {10240, 10240}, {10241, 10240}, {1000000, 10240}})+ checkNormalizedIntValues(t, NewRepo, NormalizeRepo, "IndexRetentionDays",+ [][2]int{{0, 180}, {1, 1}, {180, 180}, {3650, 3650}, {100000, 100000}})+}++func TestNormalizeSettingsAgentRanges(t *testing.T) {+ constructor := func() *Agent { return NewAI().Agent }+ normalize := func(agent *Agent) *Agent {+ ai := NewAI()+ ai.Agent = agent+ return NormalizeAI(ai).Agent+ }+ checkNormalizedIntValues(t, constructor, normalize, "ConfirmTimeout",+ [][2]int{{-9, 600}, {-1, 600}, {0, 0}, {1, 1}, {600, 600}, {3600, 3600}})+ checkNormalizedIntValues(t, constructor, normalize, "MaxToolCallRounds",+ [][2]int{{-7, 0}, {-1, 0}, {0, 0}, {1, 1}, {64, 64}, {100000, 100000}})+ checkNormalizedIntValues(t, constructor, normalize, "MaxCompletionTokens",+ [][2]int{{-2, 0}, {-1, 0}, {0, 0}, {1, 1}, {100000, 100000}})+ for _, entry := range []struct{ input, want float64 }{+ {-3, 1}, {0, 0}, {1, 1}, {2, 2}, {3, 1}, {math.NaN(), 1}, {math.Inf(-1), 1}, {math.Inf(1), 1},+ } {+ t.Run("Temperature/"+strconv.FormatFloat(entry.input, 'g', -1, 64), func(t *testing.T) {+ agent := constructor()+ agent.Temperature = entry.input+ if actual := normalize(agent).Temperature; actual != entry.want {+ t.Fatalf("temperature %v became %v, want %v", entry.input, actual, entry.want)+ }+ })+ }+}diff --git a/kernel/model/conf_regression_test.go b/kernel/model/conf_regression_test.goindex 4c9c7dbe0c..63356c31fb 100644--- a/kernel/model/conf_regression_test.go+++ b/kernel/model/conf_regression_test.go@@ -15,7 +15,16 @@ import (func TestConfAllSectionsShareStartupAndWriteNormalization(t *testing.T) {prepareConfConsistencyTest(t)- raw := []byte(`{"editor":{"fontSize":200},"sync":{"interval":1},"repo":{"indexRetentionDays":0},"ocr":{"provider":"tesseract","model":"tiny"}}`)+ raw := []byte(`{+ "editor":{"fontSize":200,"backlinkGlobalSort":7,"backlinkBlockSort":-9,"floatWindowMode":42,+ "headingEmbedMode":-3,"databaseAttrClickMode":99,"databaseAttrViewMode":-1,"codeTabSpaces":5},+ "export":{"blockEmbedMode":9,"fileAnnotationRefMode":-5},+ "appearance":{"closeButtonBehavior":5},"sync":{"interval":1,"assetDownloadMode":7},+ "system":{"autoLaunch2":9,"lockScreenMode":3},"flashcard":{"reviewMode":7},+ "search":{"limit":1000000},"fileTree":{"maxListCount":1000000,"largeFileWarningSize":1000000},+ "repo":{"indexRetentionDays":100000},"ocr":{"provider":"tesseract","model":"tiny"},+ "ai":{"agent":{"maxToolCallRounds":-7,"confirmTimeout":-9,"temperature":-3,"maxCompletionTokens":-2}}+ }`)startup := NewAppConf()if err := json.Unmarshal(raw, startup); err != nil {t.Fatal(err)