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: Share preference normalization across startup and settings writes https://github.com/siyuan-note/siyuan/issues/20426
Danielfb6bda14fe12
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 0eac2e39b1..b5bd07e112 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -6660,6 +6660,10 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * 使用与启动、导入相同的规范化规则并同步保存。锚文本长度 1–5120 保持不变,小于 1 回退 64。+ * 字体大小超出 9–72 回退 16;省略字体列表和图片标题字段时继续保留原有兼容行为。+ */"/api/setting/setEditor": {request: SetEditorRequestInput;response: { "code": 0; "data": SettingEditor | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -6695,6 +6699,9 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * 使用与启动、导入相同的路径和数值规范化规则;省略顶层笔记本文档和默认图标选项时保留当前值。+ */"/api/setting/setFiletree": {request: SetFiletreeRequestInput;response: { "code": 0; "data": SettingFileTree | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -6702,6 +6709,9 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * 使用与启动、导入相同的规范化规则;保留零张上限,非法记忆参数和权重恢复默认值。+ */"/api/setting/setFlashcard": {request: SetFlashcardRequestInput;response: { "code": 0; "data": SettingFlashcard | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -6730,6 +6740,10 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * 使用与启动、导入相同的规范化规则;limit 小于 1 回退 64,1–31 提升至 32。+ * 省略汉字敏感、自定义块和脑图选项时保留当前值;反链提及关键词上限小于 1 回退 512。+ */"/api/setting/setSearch": {request: SetSearchRequestInput;response: { "code": 0; "data": SettingSearch | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -7342,6 +7356,9 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * 导入前按启动和设置接口的相同规则规范化编辑器、文档树、搜索和闪卡偏好,并同步保存。+ */"/api/system/importConf": {request: SystemImportConfRequestInput;response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };diff --git a/kernel/api/contract_setting_normalize_test.go b/kernel/api/contract_setting_normalize_test.gonew file mode 100644index 0000000000..2ed16a5b9f--- /dev/null+++ b/kernel/api/contract_setting_normalize_test.go@@ -0,0 +1,101 @@+package api++import (+ "bytes"+ "encoding/json"+ "mime/multipart"+ "net/http/httptest"+ "reflect"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAPIContractSettingNormalization(t *testing.T) {+ previous, readOnly, markdown := model.Conf, util.ReadOnly, util.MarkdownSettings+ singleLine, largeFile := util.UseSingleLineSave, util.LargeFileWarningSize+ util.ReadOnly = true+ t.Cleanup(func() {+ model.Conf, util.ReadOnly, util.MarkdownSettings = previous, readOnly, markdown+ util.UseSingleLineSave, util.LargeFileWarningSize = singleLine, largeFile+ })+ model.Conf = model.NewAppConf()+ model.Conf.Editor = conf.NewEditor()+ model.Conf.Editor.DisplayImgName = true+ model.Conf.FileTree = conf.NewFileTree()+ model.Conf.Flashcard = 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 {+ t.Fatal("saved editor differs from startup normalization or lost omitted fields")+ }+ want := length+ if want < 1 {+ want = 64+ }+ if want > 5120 {+ want = 5120+ }+ if editor.BlockRefDynamicAnchorTextMaxLen != want {+ t.Fatalf("anchor length %d became %d", length, editor.BlockRefDynamicAnchorTextMaxLen)+ }+ }+ 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 {+ 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" {+ t.Fatalf("file tree normalization failed: %s", message)+ }+}++func TestAPIContractImportedSettingsNormalization(t *testing.T) {+ previous, temp, readOnly := model.Conf, util.TempDir, util.ReadOnly+ util.TempDir, util.ReadOnly = t.TempDir(), true+ t.Cleanup(func() { model.Conf, util.TempDir, util.ReadOnly = previous, temp, readOnly })+ for _, payload := range []string{+ `{"editor":{"blockRefDynamicAnchorTextMaxLen":1,"fontSize":100},"fileTree":{"maxListCount":0},"search":{"limit":0},"flashcard":{"weights":"invalid"}}`,+ `{"editor":null,"fileTree":null,"search":null,"flashcard":null}`,+ } {+ model.Conf = model.NewAppConf()+ originalSync := model.Conf.Sync+ var body bytes.Buffer+ writer := multipart.NewWriter(&body)+ part, err := writer.CreateFormFile("file", "settings.json")+ if err != nil {+ t.Fatal(err)+ }+ if _, err = part.Write([]byte(payload)); err != nil {+ t.Fatal(err)+ }+ if err = writer.Close(); err != nil {+ t.Fatal(err)+ }+ recorder := httptest.NewRecorder()+ context, _ := gin.CreateTestContext(recorder)+ context.Request = httptest.NewRequest("POST", "/api/system/importConf", &body)+ context.Request.Header.Set("Content-Type", writer.FormDataContentType())+ importConf(context)+ requireAPIContract(t, "POST", "/api/system/importConf", recorder)+ var response struct {+ Code int `json:"code"`+ }+ 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.FileTree.MaxListCount != 512 || model.Conf.Search.Limit != 64 ||+ model.Conf.Flashcard.Weights != conf.DefaultFSRSWeights() || model.Conf.Sync != originalSync {+ t.Fatal("import did not normalize preferences or replaced sync configuration")+ }+ }+}diff --git a/kernel/api/setting.go b/kernel/api/setting.goindex 438c8f34b1..71b4c5867c 100644--- a/kernel/api/setting.go+++ b/kernel/api/setting.go@@ -19,7 +19,6 @@ package apiimport ("fmt""reflect"- "strings""sync""github.com/88250/gulu"@@ -352,13 +351,7 @@ func applyFlashcardSetting(c *gin.Context, request apicontract.SetFlashcardRequereturn}- if 0 > flashcard.NewCardLimit {- flashcard.NewCardLimit = 20- }-- if 0 > flashcard.ReviewCardLimit {- flashcard.ReviewCardLimit = 200- }+ flashcard, _ = conf.NormalizeFlashcard(flashcard)model.Conf.Flashcard = flashcardmodel.Conf.Save()@@ -398,30 +391,7 @@ func applyEditorSetting(c *gin.Context, request apicontract.SetEditorRequest) (rif !request.HasFieldFold("displayImgAlt") {editor.DisplayImgAlt = model.Conf.Editor.DisplayImgAlt}- editor.NormalizeFontFamilies()-- if "" == editor.PlantUMLServePath {- editor.PlantUMLServePath = "https://www.plantuml.com/plantuml/svg/~1"- }-- if "" == editor.KaTexMacros {- editor.KaTexMacros = "{}"- }-- if 1 > editor.HistoryRetentionDays {- editor.HistoryRetentionDays = 30- }- if 3650 < editor.HistoryRetentionDays {- editor.HistoryRetentionDays = 3650- }-- if nil == editor.FloatWindowDelay {- editor.FloatWindowDelay = new(620)- } else {- *editor.FloatWindowDelay = max(0, min(2000, *editor.FloatWindowDelay))- }- editor.CursorSurroundingLines = conf.NormalizeCursorSurroundingLines(editor.CursorSurroundingLines)- editor.AssetOpen = conf.NormalizeAssetOpen(editor.AssetOpen)+ editor = conf.NormalizeEditor(editor)oldVirtualBlockRef := model.Conf.Editor.VirtualBlockRefoldVirtualBlockRefInclude := model.Conf.Editor.VirtualBlockRefInclude@@ -535,47 +505,7 @@ func applyFiletreeSetting(c *gin.Context, request apicontract.SetFiletreeRequest}oldBoxDocEnabled := model.IsBoxDocEnabled()- fileTree.DocCreateSavePath = util.TrimSpaceInPath(fileTree.DocCreateSavePath)- fileTree.DocCreateTemplatePath = util.NormalizeTemplatePath(fileTree.DocCreateTemplatePath)-- fileTree.RefCreateSavePath = util.TrimSpaceInPath(fileTree.RefCreateSavePath)-- fileTree.ShorthandSavePath = util.TrimSpaceInPath(fileTree.ShorthandSavePath)- if "" != fileTree.ShorthandSavePath {- if !strings.HasPrefix(fileTree.ShorthandSavePath, "/") {- fileTree.ShorthandSavePath = "/" + fileTree.ShorthandSavePath- }- }-- if 1 > fileTree.MaxOpenTabCount {- fileTree.MaxOpenTabCount = 8- }- if 32 < fileTree.MaxOpenTabCount {- fileTree.MaxOpenTabCount = 32- }- if 0 > fileTree.DocIconClickMode || 1 < fileTree.DocIconClickMode {- fileTree.DocIconClickMode = 0- }- if 0 > fileTree.ParentDocTitleClickMode || 2 < fileTree.ParentDocTitleClickMode {- fileTree.ParentDocTitleClickMode = 0- }- if nil == fileTree.TabStartupMode {- fileTree.TabStartupMode = new(int)- if fileTree.CloseTabsOnStart {- *fileTree.TabStartupMode = 2- }- }- if 0 > *fileTree.TabStartupMode || 2 < *fileTree.TabStartupMode {- *fileTree.TabStartupMode = 0- }- fileTree.CloseTabsOnStart = 2 == *fileTree.TabStartupMode-- if conf.MinFileTreeRecentDocsListCount > fileTree.RecentDocsMaxListCount {- fileTree.RecentDocsMaxListCount = conf.MinFileTreeRecentDocsListCount- }- if conf.MaxFileTreeRecentDocsListCount < fileTree.RecentDocsMaxListCount {- fileTree.RecentDocsMaxListCount = conf.MaxFileTreeRecentDocsListCount- }+ fileTree = conf.NormalizeFileTree(fileTree)model.Conf.FileTree = fileTreemodel.Conf.Save()@@ -624,9 +554,7 @@ func applySearchSetting(c *gin.Context, request apicontract.SetSearchRequest) (rs.MindmapItem = new(model.Conf.Search.MindmapItemEnabled())}- if 32 > s.Limit {- s.Limit = 32- }+ s = conf.NormalizeSearch(s)oldCaseSensitive := model.Conf.Search.CaseSensitiveoldHanSensitive := model.Conf.Search.HanSensitiveVal()diff --git a/kernel/api/system.go b/kernel/api/system.goindex 27755a2c27..6368a44d7f 100644--- a/kernel/api/system.go+++ b/kernel/api/system.go@@ -691,6 +691,10 @@ var importConf = contractHandler(apicontract.SystemImportConf, func(c *gin.ConteimportedConf.System.NetworkProxy = model.Conf.System.NetworkProxy}+ importedConf.FileTree = conf.NormalizeFileTree(importedConf.FileTree)+ importedConf.Editor = conf.NormalizeEditor(importedConf.Editor)+ importedConf.Search = conf.NormalizeSearch(importedConf.Search)+ importedConf.Flashcard, _ = conf.NormalizeFlashcard(importedConf.Flashcard)model.Conf.FileTree = importedConf.FileTreemodel.Conf.Tag = importedConf.Tagmodel.Conf.Editor = importedConf.Editordiff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex 58f99c2906..2e8adc43d7 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -1071,13 +1071,23 @@ var SetBazaar = define[SetBazaarRequest, *SettingBazaar]("setBazaar", "/api/settvar 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")++// SetFlashcard 使用与启动、导入相同的规范化规则;保留零张上限,非法记忆参数和权重恢复默认值。var SetFlashcard = define[SetFlashcardRequest, *SettingFlashcard]("setFlashcard", "/api/setting/setFlashcard", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")++// SetEditor 使用与启动、导入相同的规范化规则并同步保存。锚文本长度 1–5120 保持不变,小于 1 回退 64。+// 字体大小超出 9–72 回退 16;省略字体列表和图片标题字段时继续保留原有兼容行为。var SetEditor = define[SetEditorRequest, *SettingEditor]("setEditor", "/api/setting/setEditor", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")// PatchSetting 保留省略字段,成功后客户端重新读取配置;通知不包含密码或密钥。var PatchSetting = define[PatchSettingRequest, Null]("patchSetting", "/api/setting/patch", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var SetExport = define[SetExportRequest, *SettingExport]("setExport", "/api/setting/setExport", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")++// SetFiletree 使用与启动、导入相同的路径和数值规范化规则;省略顶层笔记本文档和默认图标选项时保留当前值。var SetFiletree = define[SetFiletreeRequest, *SettingFileTree]("setFiletree", "/api/setting/setFiletree", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "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 SetEntryVisibility = define[SetEntryVisibilityRequest, *SettingEntryVisibility]("setEntryVisibility", "/api/setting/setEntryVisibility", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")@@ -1305,6 +1315,8 @@ var SystemGetEmojiConf = define[EmptyRequest, []*SystemEmojiGroup]("getEmojiConfvar SystemGetMobileWorkspaces = define[EmptyRequest, []string]("getMobileWorkspaces", "/api/system/getMobileWorkspaces", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")var SystemGetSysFonts = define[EmptyRequest, []*SystemFont]("getSysFonts", "/api/system/getSysFonts", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")var 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 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")diff --git a/kernel/conf/settings_normalize.go b/kernel/conf/settings_normalize.gonew file mode 100644index 0000000000..b03237a7a7--- /dev/null+++ b/kernel/conf/settings_normalize.go@@ -0,0 +1,196 @@+package conf++import (+ "math"+ "strconv"+ "strings"++ "github.com/siyuan-note/siyuan/kernel/util"+)++// NormalizeFileTree 统一文档树偏好边界;默认图标的版本迁移由加载入口处理。+func NormalizeFileTree(fileTree *FileTree) *FileTree {+ if fileTree == nil {+ fileTree = NewFileTree()+ }+ if fileTree.MaxListCount < 1 {+ fileTree.MaxListCount = 512+ }+ if fileTree.MaxOpenTabCount < 1 {+ fileTree.MaxOpenTabCount = 8+ }+ fileTree.MaxOpenTabCount = min(fileTree.MaxOpenTabCount, 32)+ if fileTree.DocIconClickMode < 0 || fileTree.DocIconClickMode > 1 {+ fileTree.DocIconClickMode = 0+ }+ if fileTree.ParentDocTitleClickMode < 0 || fileTree.ParentDocTitleClickMode > 2 {+ fileTree.ParentDocTitleClickMode = 0+ }+ if fileTree.TabStartupMode == nil {+ fileTree.TabStartupMode = new(int)+ if fileTree.CloseTabsOnStart {+ *fileTree.TabStartupMode = 2+ }+ }+ if *fileTree.TabStartupMode < 0 || *fileTree.TabStartupMode > 2 {+ fileTree.TabStartupMode = new(int)+ }+ fileTree.CloseTabsOnStart = *fileTree.TabStartupMode == 2+ fileTree.DocCreateSavePath = util.TrimSpaceInPath(fileTree.DocCreateSavePath)+ fileTree.DocCreateTemplatePath = util.NormalizeTemplatePath(fileTree.DocCreateTemplatePath)+ fileTree.RefCreateSavePath = util.TrimSpaceInPath(fileTree.RefCreateSavePath)+ fileTree.ShorthandSavePath = util.TrimSpaceInPath(fileTree.ShorthandSavePath)+ if fileTree.ShorthandSavePath != "" && !strings.HasPrefix(fileTree.ShorthandSavePath, "/") {+ fileTree.ShorthandSavePath = "/" + fileTree.ShorthandSavePath+ }+ if fileTree.LargeFileWarningSize < 2 {+ fileTree.LargeFileWarningSize = 8+ }+ if fileTree.CreateDocAtTop == nil {+ fileTree.CreateDocAtTop = new(true)+ }+ if fileTree.BoxDocEnabled == nil {+ fileTree.BoxDocEnabled = new(false)+ }+ fileTree.RecentDocsMaxListCount = max(MinFileTreeRecentDocsListCount, min(MaxFileTreeRecentDocsListCount, fileTree.RecentDocsMaxListCount))+ return fileTree+}++// NormalizeEditor 保留合法的历史配置,并为缺失字段和越界值补全默认值。+func NormalizeEditor(editor *Editor) *Editor {+ defaults := NewEditor()+ if editor == nil {+ editor = defaults+ }+ if editor.BacklinkSort == nil {+ editor.BacklinkSort = defaults.BacklinkSort+ }+ if editor.BackmentionSort == nil {+ editor.BackmentionSort = defaults.BackmentionSort+ }+ if editor.DatabaseAttrShow == nil {+ editor.DatabaseAttrShow = defaults.DatabaseAttrShow+ }+ if editor.DatabaseAttrUseTabs == nil {+ editor.DatabaseAttrUseTabs = defaults.DatabaseAttrUseTabs+ }+ if editor.CheckBlockRef == nil {+ editor.CheckBlockRef = defaults.CheckBlockRef+ }+ if editor.HashTagSearch == nil {+ editor.HashTagSearch = defaults.HashTagSearch+ }+ editor.AssetOpen = NormalizeAssetOpen(editor.AssetOpen)+ editor.NormalizeFontFamilies()+ editor.Emoji = util.FilterRecentIconValues(editor.Emoji)+ if editor.FontSize < 9 || editor.FontSize > 72 {+ editor.FontSize = 16+ }+ if editor.PlantUMLServePath == "" {+ editor.PlantUMLServePath = defaults.PlantUMLServePath+ }+ if editor.KaTexMacros == "" {+ editor.KaTexMacros = "{}"+ }+ if editor.BlockRefDynamicAnchorTextMaxLen < 1 {+ editor.BlockRefDynamicAnchorTextMaxLen = 64+ }+ editor.BlockRefDynamicAnchorTextMaxLen = min(5120, editor.BlockRefDynamicAnchorTextMaxLen)+ editor.GenerateHistoryInterval = min(1440, editor.GenerateHistoryInterval)+ if editor.HistoryRetentionDays < 1 {+ editor.HistoryRetentionDays = 30+ }+ editor.HistoryRetentionDays = min(3650, editor.HistoryRetentionDays)+ if editor.FloatWindowDelay == nil {+ editor.FloatWindowDelay = new(620)+ } else {+ editor.FloatWindowDelay = new(max(0, min(2000, *editor.FloatWindowDelay)))+ }+ editor.CursorSurroundingLines = NormalizeCursorSurroundingLines(editor.CursorSurroundingLines)+ editor.DynamicLoadBlocks = max(MinDynamicLoadBlocks, editor.DynamicLoadBlocks)+ if len(editor.SpellcheckLanguages) == 0 {+ editor.SpellcheckLanguages = []string{"en-US"}+ }+ editor.BacklinkExpandCount = NormalizeBacklinkExpandCount(editor.BacklinkExpandCount)+ editor.BackmentionExpandCount = NormalizeBacklinkExpandCount(editor.BackmentionExpandCount)+ if editor.HeadingNumberFormat == "" {+ editor.HeadingNumberFormat = DefaultHeadingNumberFormat+ }+ if editor.Markdown == nil {+ editor.Markdown = &util.Markdown{}+ }+ if editor.Markdown.CodeBlockMiddleDot == nil {+ editor.Markdown.CodeBlockMiddleDot = defaults.Markdown.CodeBlockMiddleDot+ }+ if editor.Markdown.BlockFullWidthTaskList == nil {+ editor.Markdown.BlockFullWidthTaskList = defaults.Markdown.BlockFullWidthTaskList+ }+ return editor+}++// NormalizeSearch 保留非空布尔指针表示的用户选择。+func NormalizeSearch(search *Search) *Search {+ if search == nil {+ search = NewSearch()+ }+ if search.CustomBlock == nil {+ search.CustomBlock = new(true)+ }+ if search.Mindmap == nil {+ search.Mindmap = new(true)+ }+ if search.MindmapItem == nil {+ search.MindmapItem = new(false)+ }+ if search.Limit < 1 {+ search.Limit = 64+ }+ search.Limit = max(32, search.Limit)+ if search.BacklinkMentionKeywordsLimit < 1 {+ search.BacklinkMentionKeywordsLimit = 512+ }+ if search.HanSensitive == nil {+ search.SetHanSensitive(true)+ }+ return search+}++// NormalizeFlashcard 返回权重修复原因,由调用入口决定是否通知用户。+func NormalizeFlashcard(flashcard *Flashcard) (*Flashcard, string) {+ defaults := NewFlashcard()+ if flashcard == nil {+ flashcard = defaults+ }+ if flashcard.NewCardLimit < 0 {+ flashcard.NewCardLimit = defaults.NewCardLimit+ }+ if flashcard.ReviewCardLimit < 0 {+ flashcard.ReviewCardLimit = defaults.ReviewCardLimit+ }+ if flashcard.RequestRetention <= 0 || flashcard.RequestRetention >= 1 || math.IsNaN(flashcard.RequestRetention) {+ flashcard.RequestRetention = defaults.RequestRetention+ }+ if flashcard.MaximumInterval <= 0 || flashcard.MaximumInterval >= 36500 {+ flashcard.MaximumInterval = defaults.MaximumInterval+ }+ if flashcard.Weights == "" {+ flashcard.Weights = defaults.Weights+ }+ message := ""+ weights := strings.Split(flashcard.Weights, ",")+ if len(weights) != 19 {+ message = "fsrs store weights length must be [19]"+ } else {+ for _, weight := range weights {+ value, err := strconv.ParseFloat(strings.TrimSpace(weight), 64)+ if err != nil || math.IsNaN(value) || math.IsInf(value, 0) {+ message = "fsrs store weights contain invalid number"+ break+ }+ }+ }+ if message != "" {+ flashcard.Weights = defaults.Weights+ }+ return flashcard, message+}diff --git a/kernel/conf/settings_normalize_test.go b/kernel/conf/settings_normalize_test.gonew file mode 100644index 0000000000..760b54c6cd--- /dev/null+++ b/kernel/conf/settings_normalize_test.go@@ -0,0 +1,71 @@+package conf++import (+ "encoding/json"+ "strings"+ "testing"+)++func TestNormalizeSettingsEditorCompatibility(t *testing.T) {+ for _, entry := range []struct{ input, want int }{{-1, 64}, {0, 64}, {1, 1}, {63, 63}, {64, 64}, {95, 95}, {5120, 5120}, {5121, 5120}} {+ editor := NewEditor()+ editor.BlockRefDynamicAnchorTextMaxLen = entry.input+ editor.FontSize = 100+ editor.HistoryRetentionDays = 5000+ editor.FloatWindowDelay = new(-1)+ editor.DatabaseAttrShow = new(false)+ editor = NormalizeEditor(editor)+ if editor.BlockRefDynamicAnchorTextMaxLen != entry.want || editor.FontSize != 16 ||+ editor.HistoryRetentionDays != 3650 || *editor.FloatWindowDelay != 0 || *editor.DatabaseAttrShow {+ t.Fatalf("unexpected editor normalization for %d: %+v", entry.input, editor)+ }+ before, _ := json.Marshal(editor)+ after, _ := json.Marshal(NormalizeEditor(editor))+ if string(before) != string(after) {+ t.Fatal("editor normalization is not idempotent")+ }+ }+ if NormalizeEditor(nil).Markdown == nil {+ t.Fatal("missing editor defaults")+ }+}++func TestNormalizeSettingsFileTreeAndSearch(t *testing.T) {+ fileTree := NormalizeFileTree(&FileTree{CloseTabsOnStart: true, ShorthandSavePath: "notes", MaxOpenTabCount: 99})+ if *fileTree.TabStartupMode != 2 || !fileTree.CloseTabsOnStart || fileTree.ShorthandSavePath != "/notes" ||+ fileTree.MaxOpenTabCount != 32 || fileTree.MaxListCount != 512 || fileTree.LargeFileWarningSize != 8 ||+ !*fileTree.CreateDocAtTop || *fileTree.BoxDocEnabled {+ t.Fatalf("unexpected file tree normalization: %+v", fileTree)+ }+ for _, entry := range []struct{ input, want int }{{-1, 64}, {0, 64}, {1, 32}, {31, 32}, {32, 32}, {128, 128}} {+ search := NormalizeSearch(&Search{Limit: entry.input, HanSensitive: new(false), CustomBlock: new(false)})+ if search.Limit != entry.want || search.BacklinkMentionKeywordsLimit != 512 ||+ search.HanSensitiveVal() || search.CustomBlockEnabled() || !search.MindmapEnabled() || search.MindmapItemEnabled() {+ t.Fatalf("unexpected search normalization for %d: %+v", entry.input, search)+ }+ before, _ := json.Marshal(search)+ after, _ := json.Marshal(NormalizeSearch(search))+ if string(before) != string(after) {+ t.Fatal("search normalization is not idempotent")+ }+ }+}++func TestNormalizeSettingsFlashcard(t *testing.T) {+ for _, weight := range []string{"bad", "NaN", "+Inf"} {+ weights := strings.Split(DefaultFSRSWeights(), ",")+ weights[0] = weight+ flashcard, warning := NormalizeFlashcard(&Flashcard{Weights: strings.Join(weights, ","), RequestRetention: 2, MaximumInterval: -1})+ if warning == "" || flashcard.Weights != DefaultFSRSWeights() || flashcard.RequestRetention != NewFlashcard().RequestRetention ||+ flashcard.MaximumInterval != NewFlashcard().MaximumInterval || flashcard.NewCardLimit != 0 || flashcard.ReviewCardLimit != 0 {+ t.Fatalf("unexpected flashcard normalization: %+v, %s", flashcard, warning)+ }+ if _, warning = NormalizeFlashcard(flashcard); warning != "" {+ t.Fatal("normalized weights remain invalid")+ }+ }+ flashcard, warning := NormalizeFlashcard(NewFlashcard())+ if warning != "" || flashcard.Weights != DefaultFSRSWeights() {+ t.Fatal("valid weights changed")+ }+}diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex 3f9f2436f5..aaf115c402 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -405,48 +405,9 @@ func InitConf() {}util.NotificationsCfg = Conf.Appearance.NotificationsConf.FileTree = normalizeFileTreeDefaultIcon(Conf.FileTree, confFileExists)- if 1 > Conf.FileTree.MaxListCount {- Conf.FileTree.MaxListCount = 512- }- if 1 > Conf.FileTree.MaxOpenTabCount {- Conf.FileTree.MaxOpenTabCount = 8- }- if 32 < Conf.FileTree.MaxOpenTabCount {- Conf.FileTree.MaxOpenTabCount = 32- }- if nil == Conf.FileTree.TabStartupMode {- Conf.FileTree.TabStartupMode = new(int)- if Conf.FileTree.CloseTabsOnStart {- *Conf.FileTree.TabStartupMode = 2- }- }- if 0 > *Conf.FileTree.TabStartupMode || 2 < *Conf.FileTree.TabStartupMode {- *Conf.FileTree.TabStartupMode = 0- }- Conf.FileTree.CloseTabsOnStart = 2 == *Conf.FileTree.TabStartupMode- Conf.FileTree.DocCreateSavePath = util.TrimSpaceInPath(Conf.FileTree.DocCreateSavePath)- Conf.FileTree.DocCreateTemplatePath = util.NormalizeTemplatePath(Conf.FileTree.DocCreateTemplatePath)- Conf.FileTree.RefCreateSavePath = util.TrimSpaceInPath(Conf.FileTree.RefCreateSavePath)- Conf.FileTree.ShorthandSavePath = util.TrimSpaceInPath(Conf.FileTree.ShorthandSavePath)+ Conf.FileTree = conf.NormalizeFileTree(Conf.FileTree)util.UseSingleLineSave = Conf.FileTree.UseSingleLineSave- if 2 > Conf.FileTree.LargeFileWarningSize {- Conf.FileTree.LargeFileWarningSize = 8- }util.LargeFileWarningSize = Conf.FileTree.LargeFileWarningSize- if nil == Conf.FileTree.CreateDocAtTop { // v3.4.0 之前的版本没有该字段,设置默认值为 true,即在顶部创建新文档,不改变用户习惯- Conf.FileTree.CreateDocAtTop = new(true)- }- if nil == Conf.FileTree.BoxDocEnabled {- // 配置缺失时默认关闭顶层笔记本文档。- Conf.FileTree.BoxDocEnabled = new(bool)- }-- if conf.MinFileTreeRecentDocsListCount > Conf.FileTree.RecentDocsMaxListCount {- Conf.FileTree.RecentDocsMaxListCount = conf.MinFileTreeRecentDocsListCount- }- if conf.MaxFileTreeRecentDocsListCount < Conf.FileTree.RecentDocsMaxListCount {- Conf.FileTree.RecentDocsMaxListCount = conf.MaxFileTreeRecentDocsListCount- }util.CurrentCloudRegion = Conf.CloudRegion@@ -454,81 +415,8 @@ func InitConf() {Conf.Tag = conf.NewTag()}- defaultEditor := conf.NewEditor()- if nil == Conf.Editor {- Conf.Editor = defaultEditor- }-- // 新增字段的默认值,使用指针类型来区分字段不存在(nil)和用户设置为 0(非 nil)- if nil == Conf.Editor.BacklinkSort {- Conf.Editor.BacklinkSort = defaultEditor.BacklinkSort- }- if nil == Conf.Editor.BackmentionSort {- Conf.Editor.BackmentionSort = defaultEditor.BackmentionSort- }- if nil == Conf.Editor.DatabaseAttrShow {- Conf.Editor.DatabaseAttrShow = defaultEditor.DatabaseAttrShow- }- if nil == Conf.Editor.DatabaseAttrUseTabs {- Conf.Editor.DatabaseAttrUseTabs = defaultEditor.DatabaseAttrUseTabs- }- if nil == Conf.Editor.CheckBlockRef {- Conf.Editor.CheckBlockRef = defaultEditor.CheckBlockRef- }- if nil == Conf.Editor.HashTagSearch {- Conf.Editor.HashTagSearch = defaultEditor.HashTagSearch- }- Conf.Editor.AssetOpen = conf.NormalizeAssetOpen(Conf.Editor.AssetOpen)- Conf.Editor.NormalizeFontFamilies()+ Conf.Editor = conf.NormalizeEditor(Conf.Editor)Conf.Appearance.NormalizeGlobalFontFamilies()- Conf.Editor.Emoji = util.FilterRecentIconValues(Conf.Editor.Emoji)- if 9 > Conf.Editor.FontSize || 72 < Conf.Editor.FontSize {- Conf.Editor.FontSize = 16- }- if "" == Conf.Editor.PlantUMLServePath {- Conf.Editor.PlantUMLServePath = "https://www.plantuml.com/plantuml/svg/~1"- }- if 1 > Conf.Editor.BlockRefDynamicAnchorTextMaxLen {- Conf.Editor.BlockRefDynamicAnchorTextMaxLen = 64- }- if 5120 < Conf.Editor.BlockRefDynamicAnchorTextMaxLen {- Conf.Editor.BlockRefDynamicAnchorTextMaxLen = 5120- }- if 1440 < Conf.Editor.GenerateHistoryInterval {- Conf.Editor.GenerateHistoryInterval = 1440- }- if 1 > Conf.Editor.HistoryRetentionDays {- Conf.Editor.HistoryRetentionDays = 30- }- if 3650 < Conf.Editor.HistoryRetentionDays {- Conf.Editor.HistoryRetentionDays = 3650- }- if nil == Conf.Editor.FloatWindowDelay {- Conf.Editor.FloatWindowDelay = new(620)- } else {- *Conf.Editor.FloatWindowDelay = max(0, min(2000, *Conf.Editor.FloatWindowDelay))- }- Conf.Editor.CursorSurroundingLines = conf.NormalizeCursorSurroundingLines(Conf.Editor.CursorSurroundingLines)- if conf.MinDynamicLoadBlocks > Conf.Editor.DynamicLoadBlocks {- Conf.Editor.DynamicLoadBlocks = conf.MinDynamicLoadBlocks- }- if 1 > len(Conf.Editor.SpellcheckLanguages) {- Conf.Editor.SpellcheckLanguages = []string{"en-US"}- }- Conf.Editor.BacklinkExpandCount = conf.NormalizeBacklinkExpandCount(Conf.Editor.BacklinkExpandCount)- Conf.Editor.BackmentionExpandCount = conf.NormalizeBacklinkExpandCount(Conf.Editor.BackmentionExpandCount)- if "" == Conf.Editor.HeadingNumberFormat {- Conf.Editor.HeadingNumberFormat = conf.DefaultHeadingNumberFormat- }- if nil == Conf.Editor.Markdown {- Conf.Editor.Markdown = &util.Markdown{}- }- if nil == Conf.Editor.Markdown.CodeBlockMiddleDot {- Conf.Editor.Markdown.CodeBlockMiddleDot = defaultEditor.Markdown.CodeBlockMiddleDot- }- if nil == Conf.Editor.Markdown.BlockFullWidthTaskList {- Conf.Editor.Markdown.BlockFullWidthTaskList = defaultEditor.Markdown.BlockFullWidthTaskList- }util.MarkdownSettings = Conf.Editor.Markdownif nil == Conf.Export {@@ -709,79 +597,20 @@ func InitConf() {// Enabled=true 但备份缺失/无效属配置不完整,解锁时由 deriveKEK 返回恢复提示(Language 315),// 引导用户导入匹配的备份文件后重新验证主密码。- if nil == Conf.Search {- Conf.Search = conf.NewSearch()- }- if nil == Conf.Search.CustomBlock {- Conf.Search.CustomBlock = new(true)- }- if nil == Conf.Search.Mindmap {- Conf.Search.Mindmap = new(true)- }- if nil == Conf.Search.MindmapItem {- Conf.Search.MindmapItem = new(false)- }- if 1 > Conf.Search.Limit {- Conf.Search.Limit = 64- }- if 32 > Conf.Search.Limit {- Conf.Search.Limit = 32- }- if 1 > Conf.Search.BacklinkMentionKeywordsLimit {- Conf.Search.BacklinkMentionKeywordsLimit = 512- }- if nil == Conf.Search.HanSensitive {- Conf.Search.SetHanSensitive(true)- }+ Conf.Search = conf.NormalizeSearch(Conf.Search)sql.SetHanSensitive(Conf.Search.HanSensitiveVal())if nil == Conf.Stat {Conf.Stat = conf.NewStat()}- if nil == Conf.Flashcard {- Conf.Flashcard = conf.NewFlashcard()- }- if 0 > Conf.Flashcard.NewCardLimit {- Conf.Flashcard.NewCardLimit = 20- }- if 0 > Conf.Flashcard.ReviewCardLimit {- Conf.Flashcard.ReviewCardLimit = 200- }- if 0 >= Conf.Flashcard.RequestRetention || 1 <= Conf.Flashcard.RequestRetention {- Conf.Flashcard.RequestRetention = conf.NewFlashcard().RequestRetention- }- if 0 >= Conf.Flashcard.MaximumInterval || 36500 <= Conf.Flashcard.MaximumInterval {- Conf.Flashcard.MaximumInterval = conf.NewFlashcard().MaximumInterval- }- if "" == Conf.Flashcard.Weights {- Conf.Flashcard.Weights = conf.NewFlashcard().Weights- }- if 19 != len(strings.Split(Conf.Flashcard.Weights, ",")) {- defaultWeights := conf.DefaultFSRSWeights()- msg := "fsrs store weights length must be [19]"- logging.LogWarnf("%s , given [%s], reset to default weights [%s]", msg, Conf.Flashcard.Weights, defaultWeights)- Conf.Flashcard.Weights = defaultWeights- go func() {- util.WaitForUILoaded()- task.AppendAsyncTaskWithDelay(task.PushMsg, 2*time.Second, util.PushErrMsg, msg, 15000)- }()- }- isInvalidFlashcardWeights := false- for w := range strings.SplitSeq(Conf.Flashcard.Weights, ",") {- if _, err := strconv.ParseFloat(strings.TrimSpace(w), 64); err != nil {- isInvalidFlashcardWeights = true- break- }- }- if isInvalidFlashcardWeights {- defaultWeights := conf.DefaultFSRSWeights()- msg := "fsrs store weights contain invalid number"- logging.LogWarnf("%s, given [%s], reset to default weights [%s]", msg, Conf.Flashcard.Weights, defaultWeights)- Conf.Flashcard.Weights = defaultWeights+ 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, msg, 15000)+ task.AppendAsyncTaskWithDelay(task.PushMsg, 2*time.Second, util.PushErrMsg, flashcardWarning, 15000)}()}diff --git a/kernel/model/settings_reset.go b/kernel/model/settings_reset.goindex f18350eb93..b86e233c6d 100644--- a/kernel/model/settings_reset.go+++ b/kernel/model/settings_reset.go@@ -27,7 +27,6 @@ func defaultWorkspaceSettings(current *AppConf) *AppConf {next := *currentnext.Editor = conf.NewEditor()next.Editor.Markdown = util.NewMarkdown()- next.Editor.NormalizeFontFamilies()if current.Editor != nil {next.Editor.HistoryRetentionDays = current.Editor.HistoryRetentionDaysnext.Editor.Emoji = current.Editor.Emoji@@ -67,6 +66,10 @@ func defaultWorkspaceSettings(current *AppConf) *AppConf {system.SettingsWindow = falsenext.System = &system}+ next.Editor = conf.NormalizeEditor(next.Editor)+ next.FileTree = conf.NormalizeFileTree(next.FileTree)+ next.Search = conf.NormalizeSearch(next.Search)+ next.Flashcard, _ = conf.NormalizeFlashcard(next.Flashcard)return &next}