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: Preserve setting input compatibility https://github.com/siyuan-note/siyuan/pull/20690
Daniel5dbc38a94a77
diff --git a/kernel/api/ai_decision_test.go b/kernel/api/ai_decision_test.goindex 5517720029..3452609271 100644--- a/kernel/api/ai_decision_test.go+++ b/kernel/api/ai_decision_test.go@@ -169,3 +169,54 @@ func TestAPIContractSettingDecisionLegacyPatch(t *testing.T) {t.Fatalf("legacy projection overwrote modern patch: %s", message)}}++func TestAPIContractSettingDecisionLegacySave(t *testing.T) {+ for _, route := range []struct {+ name string+ handler gin.HandlerFunc+ }{{"setAI", setAI}, {"patch", patchSetting}} {+ t.Run(route.name, func(t *testing.T) {+ aiContractConfiguration(t)+ previousReadOnly := util.ReadOnly+ util.ReadOnly = true+ t.Cleanup(func() { util.ReadOnly = previousReadOnly })+ decision := model.Conf.AI.Load().Decision+ decision.Provider = "openai"+ decision.Profiles["openai"].APIKey = "openai-key"+ for _, body := range []string{+ `{"decision":{"enabled":true,"endpoint":"https://legacy.example","apiKey":"legacy-key","name":"legacy-model","timeout":45}}`,+ `{"Decision":{"APIKey":"updated-key"}}`,+ } {+ if route.name == "patch" {+ body = `{"ai":` + body + `}`+ }+ code, message, _ := settingContractRequest(t, route.name, route.handler, body)+ if code != 0 {+ t.Fatalf("legacy save failed: %s", message)+ }+ }+ decision = model.Conf.AI.Load().Decision+ profile := decision.Profiles["typesafe"]+ if !decision.Enabled || decision.Provider != "openai" || decision.Profiles["openai"].APIKey != "openai-key" ||+ profile.APIKey != "updated-key" || profile.Endpoint != "https://legacy.example" || profile.Name != "legacy-model" || profile.Timeout != 45 {+ t.Fatalf("legacy fields or unrelated profile lost: %+v %+v", decision, profile)+ }+ for _, test := range []struct {+ body string+ key string+ }{+ {`{"decision":{"apiKey":null}}`, ""},+ {`{"decision":{"apiKey":"stale-key","profiles":{"typesafe":{"apiKey":"modern-key"}}}}`, "modern-key"},+ } {+ body := test.body+ if route.name == "patch" {+ body = `{"ai":` + body + `}`+ }+ code, message, _ := settingContractRequest(t, route.name, route.handler, body)+ if code != 0 || model.Conf.AI.Load().Decision.Profiles["typesafe"].APIKey != test.key {+ t.Fatalf("legacy clearing or modern precedence failed: %s", message)+ }+ }+ })+ }+}diff --git a/kernel/api/contract.go b/kernel/api/contract.goindex fc4c1f1ed5..2e1e6eab80 100644--- a/kernel/api/contract.go+++ b/kernel/api/contract.go@@ -168,7 +168,7 @@ func contractHandler[Request, Data any](endpoint apicontract.Endpoint[Request, D// mergeSettingBody 把请求体合并进当前配置段;合并失败时保留原始请求体,沿用契约的解码错误。func mergeSettingBody(namespace string, body []byte) []byte {- if merged, err := model.ConfSectionPatchJSON(namespace, body); err == nil {+ if merged, err := mergeSettingPatch(namespace, body); err == nil {return merged}return bodydiff --git a/kernel/api/setting_patch.go b/kernel/api/setting_patch.goindex 162d665520..9787f1c78e 100644--- a/kernel/api/setting_patch.go+++ b/kernel/api/setting_patch.go@@ -5,6 +5,7 @@ import ("encoding/json""fmt""sort"+ "strings""sync""sync/atomic"@@ -91,25 +92,48 @@ func migrateDecisionSettingPatch(patch []byte) ([]byte, error) {if err := json.Unmarshal(patch, &ai); err != nil {return nil, err}+ var input struct {+ Decision json.RawMessage `json:"decision"`+ }+ if err := json.Unmarshal(patch, &input); err != nil {+ return nil, err+ }var decision map[string]json.RawMessage- if json.Unmarshal(ai["decision"], &decision) != nil || decision == nil {+ if json.Unmarshal(input.Decision, &decision) != nil || decision == nil {return patch, nil}- if _, modern := decision["profiles"]; modern {+ var legacy struct {+ Profiles json.RawMessage `json:"profiles"`+ Endpoint json.RawMessage `json:"endpoint"`+ APIKey json.RawMessage `json:"apiKey"`+ Name json.RawMessage `json:"name"`+ Timeout json.RawMessage `json:"timeout"`+ }+ if err := json.Unmarshal(input.Decision, &legacy); err != nil {+ return nil, err+ }+ if len(legacy.Profiles) > 0 {return patch, nil}profile := map[string]json.RawMessage{}- for _, field := range []string{"endpoint", "apiKey", "name", "timeout"} {- if value, exists := decision[field]; exists {+ for _, field := range []struct {+ name string+ value json.RawMessage+ }{{"endpoint", legacy.Endpoint}, {"apiKey", legacy.APIKey}, {"name", legacy.Name}, {"timeout", legacy.Timeout}} {+ if value := field.value; len(value) > 0 {// 旧设置字段允许 null,保持清空密钥和恢复默认参数的既有语义。if bytes.Equal(bytes.TrimSpace(value), []byte("null")) {value = json.RawMessage(`""`)- if field == "timeout" {+ if field.name == "timeout" {value = json.RawMessage(`0`)}}- profile[field] = value- delete(decision, field)+ profile[field.name] = value+ for key := range decision {+ if strings.EqualFold(key, field.name) {+ delete(decision, key)+ }+ }}}if len(profile) == 0 {@@ -120,6 +144,11 @@ func migrateDecisionSettingPatch(patch []byte) ([]byte, error) {return nil, err}decision["profiles"] = profiles+ for key := range ai {+ if strings.EqualFold(key, "decision") {+ delete(ai, key)+ }+ }ai["decision"], err = json.Marshal(decision)if err != nil {return nil, err@@ -127,11 +156,71 @@ func migrateDecisionSettingPatch(patch []byte) ([]byte, error) {return json.Marshal(ai)}+// migrateEditorSettingPatch 在首选字体变化时重新生成字体列表,显式提交的字体列表优先。+func migrateEditorSettingPatch(patch []byte) ([]byte, error) {+ var legacy struct {+ FontFamilies json.RawMessage `json:"fontFamilies"`+ FontFamily json.RawMessage `json:"fontFamily"`+ FontWeight json.RawMessage `json:"fontWeight"`+ FontFamilyDisplay json.RawMessage `json:"fontFamilyDisplay"`+ }+ if err := json.Unmarshal(patch, &legacy); err != nil {+ return nil, err+ }+ if len(legacy.FontFamilies) > 0 || len(legacy.FontFamily) == 0 && len(legacy.FontWeight) == 0 || model.Conf == nil {+ return patch, nil+ }+ current := model.Conf.Editor.Load()+ if current == nil {+ return patch, nil+ }+ family, weight := current.FontFamily, float64(current.FontWeight)+ if len(legacy.FontFamily) > 0 {+ family = ""+ if err := json.Unmarshal(legacy.FontFamily, &family); err != nil {+ return patch, nil+ }+ }+ if len(legacy.FontWeight) > 0 {+ weight = 0+ if err := json.Unmarshal(legacy.FontWeight, &weight); err != nil {+ return patch, nil+ }+ }+ if family == current.FontFamily && weight == float64(current.FontWeight) {+ return patch, nil+ }+ var fields map[string]json.RawMessage+ if err := json.Unmarshal(patch, &fields); err != nil {+ return nil, err+ }+ fields["fontFamilies"] = json.RawMessage(`null`)+ if len(legacy.FontFamilyDisplay) == 0 {+ fields["fontFamilyDisplay"] = json.RawMessage(`null`)+ }+ return json.Marshal(fields)+}++// mergeSettingPatch 对设置写入统一执行输入迁移,再合并当前配置段。+func mergeSettingPatch(namespace string, patch []byte) ([]byte, error) {+ var err error+ switch namespace {+ case "ai":+ patch, err = migrateDecisionSettingPatch(patch)+ case "editor":+ patch, err = migrateEditorSettingPatch(patch)+ }+ if err != nil {+ return nil, err+ }+ return model.ConfSectionPatchJSON(namespace, patch)+}+// applySettingPatch 先把补丁合并进当前配置段再交给对应接口的处理函数,命名空间取自契约声明。func applySettingPatch[Request, Data any](c *gin.Context, patch []byte,endpoint apicontract.Endpoint[Request, Data], apply func(*gin.Context, Request) apicontract.Response[Data]) apicontract.Response[*apicontract.SettingPatchData] {namespace := endpoint.Definition().Setting.Namespace- merged, err := model.ConfSectionPatchJSON(namespace, patch)+ merged, err := mergeSettingPatch(namespace, patch)if err != nil {return apicontract.Failure[*apicontract.SettingPatchData](-1, err.Error())}@@ -183,11 +272,6 @@ var patchSetting = contractHandler(apicontract.PatchSetting, func(c *gin.Contextif util.IsDisabledFeature("ai") {return apicontract.Failure[*apicontract.SettingPatchData](-1, util.I18nTerm(model.Conf.Lang, "agentCapabilitiesUnavailable"))}- var err error- patch, err = migrateDecisionSettingPatch(patch)- if err != nil {- return apicontract.Failure[*apicontract.SettingPatchData](-1, err.Error())- }response = applySettingPatch(c, patch, apicontract.SetAI, applyAISetting)case "ocr":response = applySettingPatch(c, patch, apicontract.SetOCRConfig, applyOCRSetting)diff --git a/kernel/api/setting_patch_test.go b/kernel/api/setting_patch_test.goindex 6962b3ac34..f0e72162b7 100644--- a/kernel/api/setting_patch_test.go+++ b/kernel/api/setting_patch_test.go@@ -90,6 +90,24 @@ func TestAPIContractSettingPatchKeymapEnvelopeAndNullableFields(t *testing.T) {}}+func TestAPIContractSettingPatchKeymapCaseSensitiveCommands(t *testing.T) {+ previousConf, previousReadOnly := model.Conf, util.ReadOnly+ util.ReadOnly = true+ t.Cleanup(func() { model.Conf, util.ReadOnly = previousConf, previousReadOnly })+ model.Conf = model.NewAppConf()+ keymap := conf.Keymap{"plugin": map[string]any{"sample": map[string]any{"openFile": map[string]any{"custom": "F1"}}}}+ model.Conf.Keymap.Store(&keymap)+ code, message, _ := settingContractRequest(t, "patch", patchSetting,+ `{"keymap":{"plugin":{"sample":{"openfile":{"custom":"F2"}}}}}`)+ if code != 0 {+ t.Fatalf("keymap patch failed: %s", message)+ }+ actual, _ := json.Marshal(model.Conf.Keymap.Load())+ if string(actual) != `{"plugin":{"sample":{"openFile":{"custom":"F1"},"openfile":{"custom":"F2"}}}}` {+ t.Fatalf("independent command names were conflated: %s", actual)+ }+}+func TestAPIContractSettingTaskSnapshots(t *testing.T) {previousConf, previousTasks, previousRevision := model.Conf, settingTasks, settingTaskRevisionmodel.Conf = model.NewAppConf()diff --git a/kernel/api/setting_test.go b/kernel/api/setting_test.goindex 7d12562c4c..a309b16529 100644--- a/kernel/api/setting_test.go+++ b/kernel/api/setting_test.go@@ -81,6 +81,65 @@ func TestSetEditorNullRestoresDefault(t *testing.T) {}}+func TestAPIContractSettingEditorLegacyFont(t *testing.T) {+ for _, route := range []struct {+ name string+ handler gin.HandlerFunc+ }{{"setEditor", setEditor}, {"patch", patchSetting}} {+ for _, test := range []struct {+ name string+ body string+ family string+ weight int+ count int+ display string+ }{+ {"change font", `{"fontFamily":"Verdana","fontWeight":600}`, "Verdana", 600, 1, ""},+ {"change weight", `{"fontWeight":600}`, "Arial", 600, 1, ""},+ {"case-insensitive fields", `{"FontFamily":"Verdana","FontWeight":600}`, "Verdana", 600, 1, ""},+ {"unchanged primary keeps fallbacks", `{"fontFamily":"Arial","fontWeight":400}`, "Arial", 400, 2, "Arial Regular"},+ {"unrelated field keeps fallbacks", `{"fontSize":18}`, "Arial", 400, 2, "Arial Regular"},+ {"explicit list wins", `{"fontFamily":"Verdana","fontWeight":600,"fontFamilies":[{"family":"Georgia","weight":500}]}`, "Georgia", 500, 1, ""},+ {"case-insensitive list wins", `{"fontFamily":"Verdana","FontFamilies":[{"family":"Georgia","weight":500}]}`, "Georgia", 500, 1, ""},+ {"null legacy font resets", `{"fontFamily":null}`, "", 400, 0, ""},+ {"explicit legacy display", `{"fontFamily":"Verdana","fontFamilyDisplay":"Verdana Regular"}`, "Verdana", 400, 1, "Verdana Regular"},+ } {+ t.Run(route.name+"/"+test.name, func(t *testing.T) {+ previousConf, previousReadOnly, previousMarkdown := model.Conf, util.ReadOnly, util.MarkdownSettings.Load()+ util.ReadOnly = true+ t.Cleanup(func() {+ model.Conf, util.ReadOnly = previousConf, previousReadOnly+ util.MarkdownSettings.Store(previousMarkdown)+ })+ model.Conf = model.NewAppConf()+ editor := conf.NewEditor()+ editor.FontFamilies = []*conf.EditorFont{{Family: "Arial", Weight: 400, DisplayName: "Arial Regular"}, {Family: "serif", Weight: 400}}+ editor.CodeFontFamilies = []*conf.EditorFont{{Family: "monospace", Weight: 400}}+ editor.NormalizeFontFamilies()+ model.Conf.Editor.Store(editor)+ body := test.body+ if test.name == "change weight" && route.name == "setEditor" {+ body = `{"fontWeight":600.0}`+ }+ if route.name == "patch" {+ body = `{"editor":` + body + `}`+ }+ code, message, _ := settingContractRequest(t, route.name, route.handler, body)+ editor = model.Conf.Editor.Load()+ if code != 0 || editor.FontFamily != test.family || editor.FontWeight != test.weight || len(editor.FontFamilies) != test.count {+ t.Fatalf("font write failed: %s (%+v)", message, editor)+ }+ if editor.FontFamilyDisplay != test.display {+ t.Fatalf("font display name did not follow the font: %q", editor.FontFamilyDisplay)+ }+ if len(editor.CodeFontFamilies) != 1 || editor.CodeFontFamilies[0].Family != "monospace" {+ t.Fatal("legacy font write changed the code font list")+ }+ })+ }+ }+}+func TestSetBazaarPetalDisabledSerializesTransitions(t *testing.T) {gin.SetMode(gin.TestMode)previousConf := model.Confdiff --git a/kernel/model/conf_patch.go b/kernel/model/conf_patch.goindex b9e3e1d95d..5208d4faab 100644--- a/kernel/model/conf_patch.go+++ b/kernel/model/conf_patch.go@@ -17,8 +17,12 @@ import ("github.com/siyuan-note/siyuan/kernel/util")-// MergeConfJSON 对象递归合并,数组和 null 整体替换,未知字段由入站契约决定是否接受。+// MergeConfJSON 按精确键名递归合并对象,数组和 null 整体替换,未知字段由入站契约决定是否接受。func MergeConfJSON(base, patch []byte) ([]byte, error) {+ return mergeConfJSON(base, patch, nil)+}++func mergeConfJSON(base, patch []byte, valueType reflect.Type) ([]byte, error) {var current, changes map[string]json.RawMessageif err := json.Unmarshal(base, ¤t); err != nil {return nil, err@@ -36,9 +40,9 @@ func MergeConfJSON(base, patch []byte) ([]byte, error) {sort.Strings(keys)for _, key := range keys {value := changes[key]- target := mergeConfJSONKey(current, key)+ target, fieldType := mergeConfJSONField(valueType, key)if bytes.HasPrefix(bytes.TrimSpace(value), []byte("{")) && bytes.HasPrefix(bytes.TrimSpace(current[target]), []byte("{")) {- merged, err := MergeConfJSON(current[target], value)+ merged, err := mergeConfJSON(current[target], value, fieldType)if err != nil {return nil, err}@@ -50,17 +54,42 @@ func MergeConfJSON(base, patch []byte) ([]byte, error) {return json.Marshal(current)}-// mergeConfJSONKey 把补丁键映射到既有配置的等价键,保留大小写不同的字段写法。-func mergeConfJSONKey(current map[string]json.RawMessage, key string) string {- if _, exists := current[key]; exists {- return key+// mergeConfJSONField 按结构体声明匹配字段名,字典键保持精确匹配,并继续解析字典值的类型。+func mergeConfJSONField(valueType reflect.Type, key string) (string, reflect.Type) {+ for valueType != nil && valueType.Kind() == reflect.Pointer {+ valueType = valueType.Elem()+ }+ if valueType == nil {+ return key, nil}- for existing := range current {- if strings.EqualFold(existing, key) {- return existing+ if valueType.Kind() == reflect.Map {+ return key, valueType.Elem()+ }+ if valueType.Kind() != reflect.Struct {+ return key, nil+ }+ name := key+ var fieldType reflect.Type+ for i := 0; i < valueType.NumField(); i++ {+ field := valueType.Field(i)+ if field.PkgPath != "" {+ continue+ }+ fieldName := strings.Split(field.Tag.Get("json"), ",")[0]+ if fieldName == "-" {+ continue+ }+ if fieldName == "" {+ fieldName = field.Name+ }+ if fieldName == key {+ return fieldName, field.Type+ }+ if fieldType == nil && strings.EqualFold(fieldName, key) {+ name, fieldType = fieldName, field.Type}}- return key+ return name, fieldType}func (spec *SectionSpec[C]) patch(patch []byte) ([]Issue, error) {@@ -95,7 +124,7 @@ func MergeConfSectionJSON(current any, patch []byte) ([]byte, error) {if err != nil {return nil, err}- return MergeConfJSON(data, patch)+ return mergeConfJSON(data, patch, reflect.TypeOf(current))}// ConfSectionPatchJSON 返回合并后的配置段,调用方在发布前保留契约校验与专用领域动作。diff --git a/kernel/model/conf_patch_test.go b/kernel/model/conf_patch_test.gonew file mode 100644index 0000000000..474ca853be--- /dev/null+++ b/kernel/model/conf_patch_test.go@@ -0,0 +1,39 @@+package model++import (+ "encoding/json"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/conf"+)++func TestMergeConfSectionJSONFieldAndMapKeys(t *testing.T) {+ current := conf.NewAI()+ current.Decision.Profiles["typesafe"].APIKey = "keep-key"+ merged, err := MergeConfSectionJSON(current, []byte(`{"Decision":{"Profiles":{"typesafe":{"Timeout":45},"Typesafe":{"APIKey":"separate-key"}}}}`))+ if err != nil {+ t.Fatal(err)+ }+ var next conf.AI+ if err = json.Unmarshal(merged, &next); err != nil {+ t.Fatal(err)+ }+ profiles := next.Decision.Profiles+ if profiles["typesafe"].Timeout != 45 || profiles["typesafe"].APIKey != "keep-key" ||+ profiles["Typesafe"] == nil || profiles["Typesafe"].APIKey != "separate-key" {+ t.Fatalf("struct fields and dictionary keys did not retain their matching rules: %s", merged)+ }+}++func TestMergeConfSectionJSONFieldCaseDeterministic(t *testing.T) {+ for range 20 {+ merged, err := MergeConfSectionJSON(conf.NewEditor(), []byte(`{"BlockGutterMode":false,"blockGutterMode":true}`))+ if err != nil {+ t.Fatal(err)+ }+ var next conf.Editor+ if err = json.Unmarshal(merged, &next); err != nil || !next.BlockGutterMode {+ t.Fatalf("canonical field did not win consistently: %s (%v)", merged, err)+ }+ }+}