Skip to content

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

:recycle: Merge setting write requests into the current section

Jeffrey Chen3c8ea04a6669
diff --git a/app/src/block/popover.test.ts b/app/src/block/popover.test.ts
index 3b8cc8333c..937c628f2d 100644
--- a/app/src/block/popover.test.ts
+++ b/app/src/block/popover.test.ts
@@ -245,6 +245,7 @@ const browserCases = async (source: string) => {
check.equal(image.title, "");
check.equal(image.alt, "");
window.siyuan.config.ocr = {provider: "paddleocr", model: "tiny", auto: false,
+ aiModelId: "", reasoningEffort: "", thresholds: {detection: null, box: null, recognition: null},
showText: false, showEmpty: false, showError: false};
const previousOCRRequests = ocrRequests.length;
image.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));
diff --git a/app/src/config/ocr.test.ts b/app/src/config/ocr.test.ts
index 40a516342b..146bd37f4b 100644
--- a/app/src/config/ocr.test.ts
+++ b/app/src/config/ocr.test.ts
@@ -74,11 +74,17 @@ test("OCR settings register separate searchable rows in shared desktop and mobil
assert.match(readFileSync("src/mobile/menu/settingPanel.ts", "utf8"), /tabId === "ocr"[\s\S]*?unmountOCRTab\(root\)/);
});
-const createOCRPanel = async (initial?: {config?: SettingOCR}) => {
+const defaultOCRConfig = (value: Partial<SettingOCR> = {}): SettingOCR => ({
+ provider: "paddleocr", model: "tiny", auto: false, aiModelId: "", reasoningEffort: "",
+ showText: true, showEmpty: false, showError: false,
+ thresholds: {detection: null, box: null, recognition: null}, ...value,
+});
+
+const createOCRPanel = async (initial?: {config?: Partial<SettingOCR>}) => {
const compiled = transpileModule(readFileSync("src/config/ocr.ts", "utf8"), {
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
}).outputText;
- const config: {ocr: SettingOCR} = {ocr: initial?.config ?? {provider: "paddleocr", model: "tiny", auto: false}};
+ const config: {ocr: SettingOCR} = {ocr: defaultOCRConfig(initial?.config)};
let serverConfig = {...config.ocr};
let models = [{id: "tiny", name: "Tiny", builtIn: true}];
let aiModels: Array<{id: string; name: string; provider: string}> = [];
@@ -239,7 +245,7 @@ const createOCRPanel = async (initial?: {config?: SettingOCR}) => {
return listeners.get("change")({target: controls.ocrReasoningEffort, stopPropagation() {}});
},
deferRead: () => { deferredRead = true; },
- updateServer: (next: typeof config.ocr) => { serverConfig = next; },
+ updateServer: (next: Partial<typeof config.ocr>) => { serverConfig = defaultOCRConfig(next); },
addModel: (id: string) => { models = [...models, {id, name: "Imported", builtIn: false}]; },
changeAuto: (checked: boolean) => {
controls.ocrAuto.checked = checked;
diff --git a/kernel/api/ai_decision_test.go b/kernel/api/ai_decision_test.go
index f505a45028..5517720029 100644
--- a/kernel/api/ai_decision_test.go
+++ b/kernel/api/ai_decision_test.go
@@ -122,6 +122,7 @@ func TestAPIContractSettingDecisionPartialSave(t *testing.T) {
decision.Provider = "openai"
decision.Profiles["openai"].APIKey = "openai-key"
decision.Profiles["typesafe"].APIKey = "typesafe-key"
+ // 省略 decision 时保持已有供应商和凭据,仅更新提交的字段
for _, body := range []string{
`{}`,
`{"decision":{"enabled":true,"endpoint":"https://legacy.example","apiKey":"legacy-key","name":"legacy","timeout":30}}`,
diff --git a/kernel/api/contract.go b/kernel/api/contract.go
index 9cb4194965..fc4c1f1ed5 100644
--- a/kernel/api/contract.go
+++ b/kernel/api/contract.go
@@ -1,8 +1,10 @@
package api
import (
+ "bytes"
"encoding/base64"
"fmt"
+ "io"
"mime/multipart"
"github.com/88250/gulu"
@@ -42,19 +44,24 @@ func notebookConfContract(value *conf.BoxConf) *apicontract.NotebookConf {
// contractHandler 将请求绑定和响应类型与注册契约关联,业务入口继续使用现有中间件。
func contractHandler[Request, Data any](endpoint apicontract.Endpoint[Request, Data],
handler func(*gin.Context, Request) apicontract.Response[Data], beforeDecode ...func(*gin.Context) *apicontract.Response[Data]) gin.HandlerFunc {
- // 写配置端点按契约声明串行化并通知;读取完整配置与写入共用互斥,保证读到已提交的配置
- if setting := endpoint.Definition().Setting; setting.Declared() && setting.Mode == apicontract.SettingNotify {
- handler = serializeSetting(setting.Namespace, handler)
- } else if setting.Declared() && setting.Mode == apicontract.SettingSilent || endpoint.Definition().Path == "/api/system/getConf" {
- serialized := handler
- handler = func(c *gin.Context, request Request) apicontract.Response[Data] {
- namespace := setting.Namespace
- if namespace == "" {
- namespace = "*"
+ setting := endpoint.Definition().Setting
+ // 合并写入在取得配置段锁之后才读取当前配置,避免并发提交互相覆盖。
+ merge := setting.Declared() && setting.Merge
+ if !merge {
+ // 写配置端点按契约声明串行化并通知;读取完整配置与写入共用互斥,保证读到已提交的配置
+ 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" {
+ serialized := handler
+ handler = func(c *gin.Context, request Request) apicontract.Response[Data] {
+ namespace := setting.Namespace
+ if namespace == "" {
+ namespace = "*"
+ }
+ release := lockSetting(namespace)
+ defer release()
+ return serialized(c, request)
}
- release := lockSetting(namespace)
- defer release()
- return serialized(c, request)
}
}
return func(c *gin.Context) {
@@ -108,36 +115,63 @@ func contractHandler[Request, Data any](endpoint apicontract.Endpoint[Request, D
return
}
}
- var request Request
- var err error
- if endpoint.Definition().Body == apicontract.FormBody {
- // 保留 PostForm 对普通表单、重复字段和解析失败后已有字段的处理。
- c.PostForm("")
- form := &multipart.Form{Value: c.Request.PostForm}
- if c.Request.MultipartForm != nil {
- form.File = c.Request.MultipartForm.File
+ // 合并写入要基于锁内读取的配置段,请求体本身在取得锁之前读取完毕。
+ var rawBody []byte
+ if merge {
+ body, err := io.ReadAll(c.Request.Body)
+ if err != nil {
+ writeResponse(endpoint.DecodeFailure(err))
+ return
}
- request, err = endpoint.DecodeMultipart(form)
- } else if endpoint.Definition().Body == apicontract.MultipartBody {
- form, parseErr := c.MultipartForm()
- if parseErr != nil {
- err = parseErr
- } else {
- request, err = endpoint.DecodeMultipart(form)
+ rawBody = body
+ }
+ decodeRequest := func() (request Request, err error) {
+ switch endpoint.Definition().Body {
+ case apicontract.FormBody:
+ // 保留 PostForm 对普通表单、重复字段和解析失败后已有字段的处理。
+ c.PostForm("")
+ form := &multipart.Form{Value: c.Request.PostForm}
+ if c.Request.MultipartForm != nil {
+ form.File = c.Request.MultipartForm.File
+ }
+ return endpoint.DecodeMultipart(form)
+ case apicontract.MultipartBody:
+ form, parseErr := c.MultipartForm()
+ if parseErr != nil {
+ return request, parseErr
+ }
+ return endpoint.DecodeMultipart(form)
+ default:
+ if merge {
+ return endpoint.Decode(bytes.NewReader(mergeSettingBody(setting.Namespace, rawBody)))
+ }
+ return endpoint.Decode(c.Request.Body)
}
- } else {
- request, err = endpoint.Decode(c.Request.Body)
}
- if err != nil {
- writeResponse(endpoint.DecodeFailure(err))
- return
+ run := func() apicontract.Response[Data] {
+ request, err := decodeRequest()
+ if err != nil {
+ return endpoint.DecodeFailure(err)
+ }
+ if err = model.LockRequestAfterDecode(c); err != nil {
+ return endpoint.DecodeFailure(err)
+ }
+ return handler(c, request)
}
- if err = model.LockRequestAfterDecode(c); err != nil {
- writeResponse(endpoint.DecodeFailure(err))
+ if !merge {
+ writeResponse(run())
return
}
- writeResponse(handler(c, request))
+ writeResponse(withSettingLock(setting.Namespace, run))
+ }
+}
+
+// mergeSettingBody 把请求体合并进当前配置段;合并失败时保留原始请求体,沿用契约的解码错误。
+func mergeSettingBody(namespace string, body []byte) []byte {
+ if merged, err := model.ConfSectionPatchJSON(namespace, body); err == nil {
+ return merged
}
+ return body
}
// contractFailure 保留既有业务校验的错误码和消息,并限制其错误载荷形态。
diff --git a/kernel/api/contract_ocr_provider_test.go b/kernel/api/contract_ocr_provider_test.go
index 7fcb0a8eb0..bb56230d61 100644
--- a/kernel/api/contract_ocr_provider_test.go
+++ b/kernel/api/contract_ocr_provider_test.go
@@ -60,24 +60,26 @@ func TestAPIContractOCRAIProviderSettings(t *testing.T) {
if len(data.Providers) != 3 || len(data.AIModels) != 1 || data.AIModels[0].ID != "vision" || data.AIModels[0].Provider != "Images" {
t.Fatalf("enabled model choices: %+v", data)
}
- set := func(body string, success bool, automatic bool) {
+ set := func(body string, success bool, automatic bool, modelID string) {
var data apicontract.SettingOCR
code := requestOCRProvider(t, engine, "/api/asset/setOCRConfig", body, &data)
- if (code == 0) != success || success && (data.Auto != automatic || data.AIModelID == nil || *data.AIModelID != "vision") {
+ if (code == 0) != success || success && (data.Auto != automatic || data.AIModelID != modelID) {
t.Fatalf("set OCR settings: code=%d data=%+v", code, data)
}
}
- set(`{"provider":"ai","model":"tiny","auto":true,"aiModelId":"vision"}`, true, false)
- set(`{"provider":"ai","model":"tiny","auto":true}`, true, true)
- set(`{"provider":"ai","model":"tiny","auto":false,"aiModelId":null}`, true, false)
- set(`{"provider":"ai","model":"tiny","auto":false,"aiModelId":"missing"}`, false, false)
+ set(`{"provider":"ai","model":"tiny","auto":true,"aiModelId":"vision"}`, true, false, "vision")
+ // 合并写入:省略 aiModelId 保持当前选择
+ set(`{"provider":"ai","model":"tiny","auto":true}`, true, true, "vision")
+ // null 表示清空选择,provider 为 ai 时无法通过校验
+ set(`{"provider":"ai","model":"tiny","auto":false,"aiModelId":null}`, false, false, "vision")
+ set(`{"provider":"ai","model":"tiny","auto":false,"aiModelId":"missing"}`, false, false, "vision")
provider.Models[0].Enabled = false
data = get()
- if len(data.AIModels) != 0 || len(data.Providers) != 3 || data.Providers[2].Available || *data.Config.AIModelID != "vision" {
+ if len(data.AIModels) != 0 || len(data.Providers) != 3 || data.Providers[2].Available || data.Config.AIModelID != "vision" {
t.Fatalf("disabled selected model fell back: %+v", data)
}
- set(`{"provider":"ai","model":"tiny","auto":false}`, true, false)
- set(`{"provider":"tesseract","model":"tiny","auto":true}`, true, true)
+ set(`{"provider":"ai","model":"tiny","auto":false,"aiModelId":"vision"}`, true, false, "vision")
+ set(`{"provider":"tesseract","model":"tiny","auto":true}`, true, true, "vision")
if len(get().Providers) != 2 {
t.Fatal("AI choice shown without enabled models")
}
@@ -136,18 +138,20 @@ func TestAPIContractOCRReasoningSettingsCompatibility(t *testing.T) {
success bool
}{
{`,"reasoningEffort":"none"`, "none", true},
+ // 合并写入:省略保持当前值
{"", "none", true},
- {`,"reasoningEffort":null`, "none", true},
+ // null 表示回到默认值
+ {`,"reasoningEffort":null`, "", true},
{`,"reasoningEffort":"high"`, "high", true},
{`,"reasoningEffort":"invalid"`, "high", false},
{`,"reasoningEffort":3`, "high", false},
{`,"reasoningEffort":""`, "", true},
} {
- body := `{"provider":"ai","model":"tiny","auto":false` + test.field + `}`
+ body := `{"provider":"ai","model":"tiny","auto":false,"aiModelId":"vision"` + test.field + `}`
var response apicontract.SettingOCR
code := requestOCRProvider(t, engine, "/api/asset/setOCRConfig", body, &response)
if (code == 0) != test.success || model.Conf.GetOCR().ReasoningEffort != test.expected ||
- test.success && (response.ReasoningEffort == nil || *response.ReasoningEffort != test.expected) {
+ test.success && response.ReasoningEffort != test.expected {
t.Fatalf("reasoning settings changed unexpectedly: %s, %+v", body, response)
}
data, err := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))
diff --git a/kernel/api/contract_ocr_test.go b/kernel/api/contract_ocr_test.go
index 71a422ef7f..64006397ef 100644
--- a/kernel/api/contract_ocr_test.go
+++ b/kernel/api/contract_ocr_test.go
@@ -301,7 +301,8 @@ func TestAPIContractOCRSettings(t *testing.T) {
{`{"provider":"unknown","model":"tiny","auto":true}`, false},
{`{"provider":"paddleocr","model":"../../outside","auto":true}`, false},
{`{"provider":"tesseract","model":"tiny","auto":"false"}`, false},
- {`{"provider":"tesseract","model":"tiny"}`, false},
+ // 合并写入:省略的必填字段取当前配置,请求仍可成功
+ {`{"provider":"tesseract","model":"tiny"}`, true},
} {
previousRevision := model.ConfSettingRevision.Load()
recorder := httptest.NewRecorder()
@@ -362,12 +363,14 @@ func TestAPIContractOCRThresholdPersistence(t *testing.T) {
custom bool
}{
{`,"thresholds":{"detection":0.4,"box":0.7,"recognition":0.9}`, true, true},
+ // 省略的阈值保持当前值
{"", true, true},
- {`,"thresholds":null`, true, true},
{`,"thresholds":{"detection":0,"box":0.7,"recognition":0.9}`, false, true},
{`,"thresholds":{"detection":0.4,"box":1,"recognition":0.9}`, false, true},
{`,"thresholds":{"detection":0.4,"box":0.7,"recognition":1.1}`, false, true},
+ // null 表示恢复默认值
{`,"thresholds":{"detection":null,"box":null,"recognition":null}`, true, false},
+ {`,"thresholds":null`, true, false},
} {
body := `{"provider":"tesseract","model":"tiny","auto":false` + test.fields + `}`
recorder := httptest.NewRecorder()
@@ -386,10 +389,10 @@ func TestAPIContractOCRThresholdPersistence(t *testing.T) {
got := model.Conf.GetOCR().Thresholds
if test.custom {
if got.Detection == nil || *got.Detection != 0.4 || got.Box == nil || *got.Box != 0.7 || got.Recognition == nil || *got.Recognition != 0.9 {
- t.Fatalf("saved thresholds lost: %+v", got)
+ t.Fatalf("saved thresholds lost for %q: %+v", test.fields, got)
}
} else if got != (conf.OCRThresholds{}) {
- t.Fatalf("reset did not restore defaults: %+v", got)
+ t.Fatalf("reset did not restore defaults for %q: %+v", test.fields, got)
}
persisted, err := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))
if err != nil {
diff --git a/kernel/api/contract_ocr_tooltip_test.go b/kernel/api/contract_ocr_tooltip_test.go
index 9b804c1a55..9336281f98 100644
--- a/kernel/api/contract_ocr_tooltip_test.go
+++ b/kernel/api/contract_ocr_tooltip_test.go
@@ -25,23 +25,27 @@ func TestAPIContractOCRTooltipPreferences(t *testing.T) {
var initial apicontract.OCRConfigData
if requestOCRProvider(t, engine, "/api/asset/getOCRConfig", `{}`, &initial) != 0 ||
initial.Config.ShowText == nil || !*initial.Config.ShowText ||
- initial.Config.ShowEmpty == nil || *initial.Config.ShowEmpty ||
- initial.Config.ShowError == nil || *initial.Config.ShowError {
+ initial.Config.ShowEmpty || initial.Config.ShowError {
t.Fatalf("tooltip defaults: %+v", initial.Config)
}
const path = "assets/tooltip-preferences.png"
util.SetAssetText(path, "preserved text")
t.Cleanup(func() { util.RemoveAssetText(path) })
- for _, body := range []string{
- `{"provider":"tesseract","model":"tiny","auto":false,"showText":false,"showEmpty":true,"showError":true}`,
- `{"provider":"tesseract","model":"tiny","auto":true}`,
- `{"provider":"tesseract","model":"tiny","auto":false,"showText":null,"showEmpty":null,"showError":null}`,
+ for _, test := range []struct {
+ body string
+ showText, showEmpty, showError bool
+ }{
+ {`{"provider":"tesseract","model":"tiny","auto":false,"showText":false,"showEmpty":true,"showError":true}`, false, true, true},
+ // 省略的悬浮提示设置保持当前值
+ {`{"provider":"tesseract","model":"tiny","auto":true}`, false, true, true},
+ // null 表示回到默认值
+ {`{"provider":"tesseract","model":"tiny","auto":false,"showText":null,"showEmpty":null,"showError":null}`, true, false, false},
} {
var response apicontract.SettingOCR
- if requestOCRProvider(t, engine, "/api/asset/setOCRConfig", body, &response) != 0 ||
- response.ShowText == nil || *response.ShowText || response.ShowEmpty == nil || !*response.ShowEmpty ||
- response.ShowError == nil || !*response.ShowError {
- t.Fatalf("tooltip setting compatibility: %s: %+v", body, response)
+ if requestOCRProvider(t, engine, "/api/asset/setOCRConfig", test.body, &response) != 0 ||
+ response.ShowText == nil || *response.ShowText != test.showText ||
+ response.ShowEmpty != test.showEmpty || response.ShowError != test.showError {
+ t.Fatalf("tooltip setting compatibility: %s: %+v", test.body, response)
}
if util.GetAssetText(path) != "preserved text" {
t.Fatal("tooltip settings changed saved text")
@@ -49,7 +53,7 @@ func TestAPIContractOCRTooltipPreferences(t *testing.T) {
data, err := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))
var saved struct{ OCR conf.OCR }
if err != nil || json.Unmarshal(data, &saved) != nil || saved.OCR.ShowText == nil ||
- *saved.OCR.ShowText || !saved.OCR.ShowEmpty || !saved.OCR.ShowError {
+ *saved.OCR.ShowText != test.showText || saved.OCR.ShowEmpty != test.showEmpty || saved.OCR.ShowError != test.showError {
t.Fatalf("tooltip preferences were not persisted: %+v, %v", saved.OCR, err)
}
}
@@ -57,7 +61,7 @@ func TestAPIContractOCRTooltipPreferences(t *testing.T) {
t.Fatal("tooltip preferences could not be patched")
}
value := model.Conf.GetOCR()
- if value.ShowText == nil || !*value.ShowText || value.ShowEmpty || !value.ShowError || value.Auto {
+ if value.ShowText == nil || !*value.ShowText || value.ShowEmpty || value.ShowError || value.Auto {
t.Fatalf("partial patch changed independent fields: %+v", value)
}
}
diff --git a/kernel/api/contract_setting_ai_web_test.go b/kernel/api/contract_setting_ai_web_test.go
index 7b15e11d0a..cc951909f0 100644
--- a/kernel/api/contract_setting_ai_web_test.go
+++ b/kernel/api/contract_setting_ai_web_test.go
@@ -28,11 +28,12 @@ func TestAPIContractSettingAIWeb(t *testing.T) {
}
before := model.Conf.AI.Load().Web
code, message, _ = settingContractRequest(t, "setAI", setAI, `{"agent":{"maxRetries":2}}`)
- if code != 0 || *model.Conf.AI.Load().Web != *before || model.Conf.AI.Load().Web == before {
- t.Fatalf("legacy client lost or aliased web settings: %s", message)
+ web := model.Conf.AI.Load().Web
+ if code != 0 || *web != *before || web == before {
+ t.Fatalf("merge lost or aliased web settings: %s", message)
}
code, message, _ = settingContractRequest(t, "patch", patchSetting, `{"ai":{"web":{"fetchProvider":"deepseek"}}}`)
- web := model.Conf.AI.Load().Web
+ web = model.Conf.AI.Load().Web
if code != 0 || web.FetchProvider != "deepseek" || web.SearchProvider != "deepseek" || web.APIKey != "test-key" || web.Timeout != 600 {
t.Fatalf("partial web setting save lost another field: %s", message)
}
diff --git a/kernel/api/contract_setting_export_test.go b/kernel/api/contract_setting_export_test.go
index 13468be921..a3e9196cd9 100644
--- a/kernel/api/contract_setting_export_test.go
+++ b/kernel/api/contract_setting_export_test.go
@@ -33,7 +33,7 @@ func TestAPIContractSettingExportNormalization(t *testing.T) {
{`{"blockRefMode":0}`, 4}, {`{"blockRefMode":1}`, 4}, {`{"blockRefMode":5}`, 4},
{`{"blockRefMode":2}`, 2}, {`{"blockRefMode":3}`, 3}, {`{"blockRefMode":4}`, 4},
{`{"blockRefMode":-1}`, -1}, {`{"blockRefMode":6}`, 6},
- {`{"blockRefMode":null}`, 4}, {`{"addTitle":false}`, 4},
+ {`{"blockRefMode":null}`, 4}, {`{"addTitle":false}`, 3},
} {
t.Run(route.name+"/"+entry.body, func(t *testing.T) {
model.Conf = model.NewAppConf()
@@ -56,8 +56,8 @@ func TestAPIContractSettingExportNormalization(t *testing.T) {
if err := json.Unmarshal(data, &response); err != nil {
t.Fatal(err)
}
- if !reflect.DeepEqual(&response, model.Conf.Export.Load()) || response.BlockRefTextLeft != "" {
- t.Fatal("replacement response differs from the applied export settings")
+ if !reflect.DeepEqual(&response, model.Conf.Export.Load()) || response.BlockRefTextLeft != "[" {
+ t.Fatal("response differs from the applied export settings")
}
} else if model.Conf.Export.Load().BlockRefTextLeft != "[" {
t.Fatal("patch lost an omitted export setting")
diff --git a/kernel/api/contract_setting_file_tree_click_test.go b/kernel/api/contract_setting_file_tree_click_test.go
index 428b6fa8da..d82f2b70a8 100644
--- a/kernel/api/contract_setting_file_tree_click_test.go
+++ b/kernel/api/contract_setting_file_tree_click_test.go
@@ -26,12 +26,12 @@ func TestAPIContractSettingFileTreeClickMode(t *testing.T) {
docIcon, title int
echo bool // setFiletree 响应回显应用后的取值
}{
- // setFiletree 为整体替换,未提交的字段回到默认值
- {"/api/setting/setFiletree", `{}`, 0, 0, true},
+ // 未提交的字段保持当前值
+ {"/api/setting/setFiletree", `{}`, 0, 1, true},
{"/api/setting/setFiletree", `{"docIconClickMode":1,"parentDocTitleClickMode":2}`, 1, 2, true},
{"/api/setting/setFiletree", `{"DocIconClickMode":1,"ParentDocTitleClickMode":1}`, 1, 1, true},
{"/api/setting/setFiletree", `{"docIconClickMode":2,"parentDocTitleClickMode":9}`, 0, 0, true},
- {"/api/setting/setFiletree", `{"docIconClickMode":-1}`, 0, 0, true},
+ {"/api/setting/setFiletree", `{"docIconClickMode":-1}`, 0, 1, true},
// patch 在现有配置上合并,未提交的字段保留当前值,null 按零值处理
{"/api/setting/patch", `{"fileTree":{"docIconClickMode":1}}`, 1, 1, false},
{"/api/setting/patch", `{"fileTree":{"parentDocTitleClickMode":2}}`, 0, 2, false},
diff --git a/kernel/api/contract_setting_normalize_test.go b/kernel/api/contract_setting_normalize_test.go
index 7808321000..ac71856e9d 100644
--- a/kernel/api/contract_setting_normalize_test.go
+++ b/kernel/api/contract_setting_normalize_test.go
@@ -58,7 +58,7 @@ func TestAPIContractSettingNormalization(t *testing.T) {
}
}
code, message, _ := settingContractRequest(t, "setFlashcard", setFlashcard, `{"weights":"invalid","requestRetention":2,"maximumInterval":-1}`)
- if code != 0 || model.Conf.Flashcard.Load().Weights != conf.DefaultFSRSWeights() || model.Conf.Flashcard.Load().NewCardLimit != 0 {
+ if code != 0 || model.Conf.Flashcard.Load().Weights != conf.DefaultFSRSWeights() || model.Conf.Flashcard.Load().NewCardLimit != conf.NewFlashcard().NewCardLimit {
t.Fatalf("flashcard normalization failed: %s", message)
}
code, message, _ = settingContractRequest(t, "setFiletree", setFiletree, `{"maxListCount":0,"largeFileWarningSize":1,"shorthandSavePath":"notes"}`)
diff --git a/kernel/api/ocr.go b/kernel/api/ocr.go
index f7ceabc09c..277bfded4b 100644
--- a/kernel/api/ocr.go
+++ b/kernel/api/ocr.go
@@ -43,11 +43,12 @@ var getOCRConfig = contractHandler(apicontract.GetOCRConfig, func(c *gin.Context
})
func ocrConfigPayload(value conf.OCR) apicontract.SettingOCR {
- if value.ShowText == nil {
+ if nil == value.ShowText {
value.ShowText = new(true)
}
- thresholds := apicontract.OCRThresholds(value.Thresholds)
- return apicontract.SettingOCR{Provider: value.Provider, Model: value.Model, Auto: value.Auto, Thresholds: &thresholds, AIModelID: &value.AIModelID, ReasoningEffort: &value.ReasoningEffort, ShowText: value.ShowText, ShowEmpty: &value.ShowEmpty, ShowError: &value.ShowError}
+ return apicontract.SettingOCR{Provider: value.Provider, Model: value.Model, Auto: value.Auto, ShowText: value.ShowText,
+ ShowEmpty: value.ShowEmpty, ShowError: value.ShowError, AIModelID: value.AIModelID,
+ ReasoningEffort: value.ReasoningEffort, Thresholds: apicontract.OCRThresholds(value.Thresholds)}
}
func ocrModelPayload(id string) apicontract.OCRModel {
@@ -63,26 +64,9 @@ func ocrModelPayload(id string) apicontract.OCRModel {
var setOCRConfig = contractHandler(apicontract.SetOCRConfig, applyOCRSetting)
func applyOCRSetting(c *gin.Context, request apicontract.SettingOCR) apicontract.Response[apicontract.SettingOCR] {
- value := model.Conf.GetOCR()
- value.Provider, value.Model, value.Auto = request.Provider, request.Model, request.Auto
- if request.ShowText != nil {
- value.ShowText = request.ShowText
- }
- if request.ShowEmpty != nil {
- value.ShowEmpty = *request.ShowEmpty
- }
- if request.ShowError != nil {
- value.ShowError = *request.ShowError
- }
- if request.AIModelID != nil {
- value.AIModelID = *request.AIModelID
- }
- if request.ReasoningEffort != nil {
- value.ReasoningEffort = *request.ReasoningEffort
- }
- if request.Thresholds != nil {
- value.Thresholds = conf.OCRThresholds(*request.Thresholds)
- }
+ value := conf.OCR{Provider: request.Provider, Model: request.Model, Auto: request.Auto, ShowText: request.ShowText,
+ ShowEmpty: request.ShowEmpty, ShowError: request.ShowError, AIModelID: request.AIModelID,
+ ReasoningEffort: request.ReasoningEffort, Thresholds: conf.OCRThresholds(request.Thresholds)}
if err := model.Conf.SetOCR(value); err != nil {
return apicontract.Failure[apicontract.SettingOCR](-1, err.Error())
}
diff --git a/kernel/api/setting.go b/kernel/api/setting.go
index 2b3af3493c..a063a7b322 100644
--- a/kernel/api/setting.go
+++ b/kernel/api/setting.go
@@ -37,39 +37,51 @@ var (
bazaarPetalStateMu sync.Mutex
)
-var setEditorReadOnly = contractHandler(apicontract.SetEditorReadOnly, func(c *gin.Context, request apicontract.EditorReadOnlyRequest) apicontract.Response[apicontract.Null] {
- model.UpdateEditorConf(func(s *conf.Editor) { s.ReadOnly = request.ReadOnly })
- return apicontract.Success(apicontract.Null{})
-})
+// settingRequest 提供设置接口的配置段原始内容与解析诊断。
+type settingRequest interface {
+ ConfigError() error
+ ConfigJSON() []byte
+}
-var setConfSnippet = contractHandler(apicontract.SetConfSnippet, applySnippetSetting)
+// applySettingSection 解码整段设置并提交,返回提交后的配置段。
+// 从构造函数默认值开始解码,JSON null 对非指针字段不生效、对指针和集合字段置空,两者都回落默认值。
+func applySettingSection[Request settingRequest, Section, Data any](c *gin.Context, request Request, namespace string,
+ defaults func() *Section, load func() *Section, convert func(*Section) Data) apicontract.Response[Data] {
+ return applySettingSectionWith(c, request, func(section *Section) ([]model.Issue, error) {
+ return model.ApplyConfSection(namespace, section)
+ }, defaults, load, convert)
+}
-func applySnippetSetting(c *gin.Context, request apicontract.SetConfSnippetRequest) (ret apicontract.Response[*apicontract.SettingSnpt]) {
+// applySettingSectionWith 使用调用方指定的提交规则应用配置段。
+func applySettingSectionWith[Request settingRequest, Section, Data any](c *gin.Context, request Request,
+ apply func(*Section) ([]model.Issue, error), defaults func() *Section, load func() *Section,
+ convert func(*Section) Data) apicontract.Response[Data] {
if err := request.ConfigError(); err != nil {
- return apicontract.Failure[*apicontract.SettingSnpt](-1, err.Error())
+ return apicontract.Failure[Data](-1, err.Error())
}
- ret = apicontract.Success((*apicontract.SettingSnpt)(nil))
-
- param := request.ConfigJSON()
- var err error
-
- snippet := &conf.Snpt{}
- if err = gulu.JSON.UnmarshalJSON(param, snippet); err != nil {
- ret = apicontract.Failure[*apicontract.SettingSnpt](-1, err.Error())
- return
+ section := defaults()
+ if err := gulu.JSON.UnmarshalJSON(request.ConfigJSON(), section); err != nil {
+ return apicontract.Failure[Data](-1, err.Error())
}
-
- issues, applyErr := model.ApplyConfSection("snippet", snippet)
+ issues, err := apply(section)
recordSettingIssues(c, issues)
- err = applyErr
if err != nil {
- return apicontract.Failure[*apicontract.SettingSnpt](-1, err.Error())
+ return apicontract.Failure[Data](-1, err.Error())
}
+ return apicontract.Success(convert(load()))
+}
- ret = apicontract.Success(settingSnptPayload(model.Conf.Snippet.Load()))
- return
+var setEditorReadOnly = contractHandler(apicontract.SetEditorReadOnly, func(c *gin.Context, request apicontract.EditorReadOnlyRequest) apicontract.Response[apicontract.Null] {
+ model.UpdateEditorConf(func(s *conf.Editor) { s.ReadOnly = request.ReadOnly })
+ return apicontract.Success(apicontract.Null{})
+})
+
+var applySnippetSetting = func(c *gin.Context, request apicontract.SetConfSnippetRequest) apicontract.Response[*apicontract.SettingSnpt] {
+ return applySettingSection(c, request, "snippet", conf.NewSnpt, model.Conf.Snippet.Load, settingSnptPayload)
}
+var setConfSnippet = contractHandler(apicontract.SetConfSnippet, applySnippetSetting)
+
var addVirtualBlockRefExclude = contractHandler(apicontract.AddVirtualBlockRefExclude, func(c *gin.Context, request apicontract.VirtualBlockRefRequest) apicontract.Response[apicontract.Null] {
model.AddVirtualBlockRefExclude(request.Keywords)
return apicontract.Success(apicontract.Null{})
@@ -85,37 +97,14 @@ var refreshVirtualBlockRef = contractHandler(apicontract.RefreshVirtualBlockRef,
return apicontract.Success(apicontract.Null{})
})
-var setBazaar = contractHandler(apicontract.SetBazaar, applyBazaarSetting)
-
-func applyBazaarSetting(c *gin.Context, request apicontract.SetBazaarRequest) (ret apicontract.Response[*apicontract.SettingBazaar]) {
- if err := request.ConfigError(); err != nil {
- return apicontract.Failure[*apicontract.SettingBazaar](-1, err.Error())
- }
- ret = apicontract.Success((*apicontract.SettingBazaar)(nil))
-
- param := request.ConfigJSON()
- var err error
-
- bazaar := &conf.Bazaar{}
- if err = gulu.JSON.UnmarshalJSON(param, bazaar); err != nil {
- ret = apicontract.Failure[*apicontract.SettingBazaar](-1, err.Error())
- return
- }
-
+var applyBazaarSetting = func(c *gin.Context, request apicontract.SetBazaarRequest) apicontract.Response[*apicontract.SettingBazaar] {
bazaarPetalStateMu.Lock()
defer bazaarPetalStateMu.Unlock()
-
- issues, applyErr := model.ApplyConfSection("bazaar", bazaar)
- recordSettingIssues(c, issues)
- err = applyErr
- if err != nil {
- return apicontract.Failure[*apicontract.SettingBazaar](-1, err.Error())
- }
-
- ret = apicontract.Success(settingBazaarPayload(model.Conf.Bazaar.Load()))
- return
+ return applySettingSection(c, request, "bazaar", conf.NewBazaar, model.Conf.Bazaar.Load, settingBazaarPayload)
}
+var setBazaar = contractHandler(apicontract.SetBazaar, applyBazaarSetting)
+
var setBazaarPetalDisabled = contractHandler(apicontract.SetBazaarPetalDisabled, func(c *gin.Context, request apicontract.SettingPetalDisabledRequest) apicontract.Response[apicontract.SettingPetalDisabledData] {
petalDisabled := request.PetalDisabled
bazaarPetalStateMu.Lock()
@@ -146,22 +135,11 @@ func applyAISetting(c *gin.Context, request apicontract.SetAIRequest) (ret apico
param := request.ConfigJSON()
var err error
- ai := &conf.AI{}
+ ai := conf.NewAI()
if err = gulu.JSON.UnmarshalJSON(param, ai); err != nil {
ret = apicontract.Failure[*apicontract.SettingAI](-1, err.Error())
return
}
- if model.Conf.AI.Load() != nil {
- if ai.Web == nil && model.Conf.AI.Load().Web != nil {
- previousWeb := *model.Conf.AI.Load().Web
- ai.Web = &previousWeb
- }
- if ai.Decision == nil {
- ai.Decision = model.Conf.AI.Load().Decision.Clone()
- } else {
- ai.Decision.MergePrevious(model.Conf.AI.Load().Decision)
- }
- }
if ai.MCP != nil {
for _, server := range ai.MCP.Servers {
if err = mcpclient.ValidateMCPServerEnvironment(server); err != nil {
@@ -236,64 +214,26 @@ func preserveMCPServerIDs(oldServers, newServers []conf.MCPServer) {
}
}
-var setSecrets = contractHandler(apicontract.SetSecrets, applySecretsSetting)
-
-func applySecretsSetting(c *gin.Context, request apicontract.SetSecretsRequest) (ret apicontract.Response[*apicontract.SettingSecrets]) {
- if err := request.ConfigError(); err != nil {
- return apicontract.Failure[*apicontract.SettingSecrets](-1, err.Error())
+var applySecretsSetting = func(c *gin.Context, request apicontract.SetSecretsRequest) apicontract.Response[*apicontract.SettingSecrets] {
+ response := applySettingSection(c, request, "secrets", conf.NewSecrets, model.Conf.Secrets.Load, settingSecretsPayload)
+ if response.Code() == 0 {
+ reconnectStdioMCPWithEnvironment()
}
- ret = apicontract.Success((*apicontract.SettingSecrets)(nil))
-
- param := request.ConfigJSON()
- var err error
+ return response
+}
- secrets := &conf.Secrets{}
- if err = gulu.JSON.UnmarshalJSON(param, secrets); err != nil {
- ret = apicontract.Failure[*apicontract.SettingSecrets](-1, err.Error())
- return
- }
+var setSecrets = contractHandler(apicontract.SetSecrets, applySecretsSetting)
- issues, applyErr := model.ApplyConfSection("secrets", secrets)
- recordSettingIssues(c, issues)
- err = applyErr
- if err != nil {
- return apicontract.Failure[*apicontract.SettingSecrets](-1, err.Error())
+var applyVariablesSetting = func(c *gin.Context, request apicontract.SetVariablesRequest) apicontract.Response[*apicontract.SettingVariables] {
+ response := applySettingSection(c, request, "variables", conf.NewVariables, model.Conf.Variables.Load, settingVariablesPayload)
+ if response.Code() == 0 {
+ reconnectStdioMCPWithEnvironment()
}
- reconnectStdioMCPWithEnvironment()
-
- ret = apicontract.Success(settingSecretsPayload(model.Conf.Secrets.Load()))
- return
+ return response
}
var setVariables = contractHandler(apicontract.SetVariables, applyVariablesSetting)
-func applyVariablesSetting(c *gin.Context, request apicontract.SetVariablesRequest) (ret apicontract.Response[*apicontract.SettingVariables]) {
- if err := request.ConfigError(); err != nil {
- return apicontract.Failure[*apicontract.SettingVariables](-1, err.Error())
- }
- ret = apicontract.Success((*apicontract.SettingVariables)(nil))
-
- param := request.ConfigJSON()
- var err error
-
- variables := &conf.Variables{}
- if err = gulu.JSON.UnmarshalJSON(param, variables); err != nil {
- ret = apicontract.Failure[*apicontract.SettingVariables](-1, err.Error())
- return
- }
-
- issues, applyErr := model.ApplyConfSection("variables", variables)
- recordSettingIssues(c, issues)
- err = applyErr
- if err != nil {
- return apicontract.Failure[*apicontract.SettingVariables](-1, err.Error())
- }
- reconnectStdioMCPWithEnvironment()
-
- ret = apicontract.Success(settingVariablesPayload(model.Conf.Variables.Load()))
- return
-}
-
func reconnectStdioMCPWithEnvironment() {
confAISnapshot := model.Conf.LoadAI()
@@ -316,81 +256,18 @@ func stdioMCPServerIDsWithEnvironment(servers []conf.MCPServer) []string {
return serverIDs
}
-var setFlashcard = contractHandler(apicontract.SetFlashcard, applyFlashcardSetting)
-
-func applyFlashcardSetting(c *gin.Context, request apicontract.SetFlashcardRequest) (ret apicontract.Response[*apicontract.SettingFlashcard]) {
- if err := request.ConfigError(); err != nil {
- return apicontract.Failure[*apicontract.SettingFlashcard](-1, err.Error())
- }
- ret = apicontract.Success((*apicontract.SettingFlashcard)(nil))
-
- param := request.ConfigJSON()
- var err error
-
- flashcard := &conf.Flashcard{}
- if err = gulu.JSON.UnmarshalJSON(param, flashcard); err != nil {
- ret = apicontract.Failure[*apicontract.SettingFlashcard](-1, err.Error())
- return
- }
+var applyFlashcardSetting = func(c *gin.Context, request apicontract.SetFlashcardRequest) apicontract.Response[*apicontract.SettingFlashcard] {
+ return applySettingSection(c, request, "flashcard", conf.NewFlashcard, model.Conf.Flashcard.Load, settingFlashcardPayload)
+}
- issues, applyErr := model.ApplyConfSection("flashcard", flashcard)
- recordSettingIssues(c, issues)
- err = applyErr
- if err != nil {
- return apicontract.Failure[*apicontract.SettingFlashcard](-1, err.Error())
- }
+var setFlashcard = contractHandler(apicontract.SetFlashcard, applyFlashcardSetting)
- ret = apicontract.Success(settingFlashcardPayload(model.Conf.Flashcard.Load()))
- return
+var applyEditorSetting = func(c *gin.Context, request apicontract.SetEditorRequest) apicontract.Response[*apicontract.SettingEditor] {
+ return applySettingSection(c, request, "editor", conf.NewEditor, model.Conf.Editor.Load, settingEditorPayload)
}
var setEditor = contractHandler(apicontract.SetEditor, applyEditorSetting)
-func applyEditorSetting(c *gin.Context, request apicontract.SetEditorRequest) (ret apicontract.Response[*apicontract.SettingEditor]) {
- if err := request.ConfigError(); err != nil {
- return apicontract.Failure[*apicontract.SettingEditor](-1, err.Error())
- }
- ret = apicontract.Success((*apicontract.SettingEditor)(nil))
-
- param := request.ConfigJSON()
- var err error
-
- editor := conf.NewEditor()
- if err = gulu.JSON.UnmarshalJSON(param, editor); err != nil {
- ret = apicontract.Failure[*apicontract.SettingEditor](-1, err.Error())
- return
- }
- if !request.HasField("fontFamilies") && editor.FontFamily == model.Conf.Editor.Load().FontFamily &&
- editor.FontWeight == model.Conf.Editor.Load().FontWeight {
- editor.FontFamilies = model.Conf.Editor.Load().FontFamilies
- }
- if !request.HasField("codeFontFamilies") {
- editor.CodeFontFamilies = model.Conf.Editor.Load().CodeFontFamilies
- }
- if !request.HasFieldFold("displayImgName") {
- editor.DisplayImgName = model.Conf.Editor.Load().DisplayImgName
- }
- if !request.HasFieldFold("displayImgAlt") {
- editor.DisplayImgAlt = model.Conf.Editor.Load().DisplayImgAlt
- }
- if !request.HasFieldFold("pageScrollButtons") {
- editor.PageScrollButtons = model.Conf.Editor.Load().PageScrollButtons
- }
- if !request.HasFieldFold("blockGutterMode") {
- editor.BlockGutterMode = model.Conf.Editor.Load().BlockGutterMode
- }
-
- issues, applyErr := model.ApplyConfSection("editor", editor)
- recordSettingIssues(c, issues)
- err = applyErr
- if err != nil {
- return apicontract.Failure[*apicontract.SettingEditor](-1, err.Error())
- }
-
- ret = apicontract.Success(settingEditorPayload(model.Conf.Editor.Load()))
- return
-}
-
var setExport = contractHandler(apicontract.SetExport, applyExportSetting)
func applyExportSetting(c *gin.Context, request apicontract.SetExportRequest) (ret apicontract.Response[*apicontract.SettingExport]) {
@@ -402,20 +279,18 @@ func applyExportSetting(c *gin.Context, request apicontract.SetExportRequest) (r
param := request.ConfigJSON()
var err error
- export := &conf.Export{}
+ export := conf.NewExport()
if err = gulu.JSON.UnmarshalJSON(param, export); err != nil {
ret = apicontract.FailureWithTimeout[*apicontract.SettingExport](-1, err.Error(), 5000)
return
}
- // 整段旧接口保留废弃导出模式的转换行为
conf.MigrateExportBlockRefMode(export)
+ // 只校验本次实际改动的 Pandoc 路径,避免沿用已有路径时重复提示
previousPandocBin := model.Conf.Export.Load().PandocBin
- if "" != export.PandocBin {
- if !util.IsValidPandocBin(export.PandocBin) {
- util.PushErrMsg(fmt.Sprintf(model.Conf.Language(117), export.PandocBin), 5000)
- export.PandocBin = previousPandocBin
- }
+ if "" != export.PandocBin && export.PandocBin != previousPandocBin && !util.IsValidPandocBin(export.PandocBin) {
+ util.PushErrMsg(fmt.Sprintf(model.Conf.Language(117), export.PandocBin), 5000)
+ export.PandocBin = previousPandocBin
}
issues, applyErr := model.ApplyConfSection("export", export)
@@ -441,95 +316,18 @@ var getPandocBin = contractHandler(apicontract.GetPandocBin, func(c *gin.Context
return apicontract.Success(pandocRuntime.BinPath)
})
-var setFiletree = contractHandler(apicontract.SetFiletree, applyFiletreeSetting)
-
-func applyFiletreeSetting(c *gin.Context, request apicontract.SetFiletreeRequest) (ret apicontract.Response[*apicontract.SettingFileTree]) {
- if err := request.ConfigError(); err != nil {
- return apicontract.Failure[*apicontract.SettingFileTree](-1, err.Error())
- }
- ret = apicontract.Success((*apicontract.SettingFileTree)(nil))
-
- param := request.ConfigJSON()
- var err error
-
- fileTree := conf.NewFileTree()
- // 请求未携带的保存格式和大文件阈值沿用当前配置
- fileTree.UseSingleLineSave = model.Conf.FileTree.Load().UseSingleLineSave
- fileTree.LargeFileWarningSize = model.Conf.FileTree.Load().LargeFileWarningSize
- fileTree.BoxDocEnabled = nil
- fileTree.UseSVGDefaultIcon = nil
- if err = gulu.JSON.UnmarshalJSON(param, fileTree); err != nil {
- ret = apicontract.Failure[*apicontract.SettingFileTree](-1, err.Error())
- return
- }
- if nil == fileTree.BoxDocEnabled {
- if nil != model.Conf.FileTree.Load() && nil != model.Conf.FileTree.Load().BoxDocEnabled {
- fileTree.BoxDocEnabled = model.Conf.FileTree.Load().BoxDocEnabled
- } else {
- fileTree.BoxDocEnabled = new(bool)
- }
- }
- if nil == fileTree.UseSVGDefaultIcon {
- if nil != model.Conf.FileTree.Load() && nil != model.Conf.FileTree.Load().UseSVGDefaultIcon {
- fileTree.UseSVGDefaultIcon = model.Conf.FileTree.Load().UseSVGDefaultIcon
- } else {
- fileTree.UseSVGDefaultIcon = new(bool)
- }
- }
+var applyFiletreeSetting = func(c *gin.Context, request apicontract.SetFiletreeRequest) apicontract.Response[*apicontract.SettingFileTree] {
+ return applySettingSection(c, request, "fileTree", conf.NewFileTree, model.Conf.FileTree.Load, settingFileTreePayload)
+}
- issues, applyErr := model.ApplyConfSection("fileTree", fileTree)
- recordSettingIssues(c, issues)
- err = applyErr
- if err != nil {
- return apicontract.Failure[*apicontract.SettingFileTree](-1, err.Error())
- }
+var setFiletree = contractHandler(apicontract.SetFiletree, applyFiletreeSetting)
- ret = apicontract.Success(settingFileTreePayload(model.Conf.FileTree.Load()))
- return
+var applySearchSetting = func(c *gin.Context, request apicontract.SetSearchRequest) apicontract.Response[*apicontract.SettingSearch] {
+ return applySettingSection(c, request, "search", conf.NewSearch, model.Conf.Search.Load, settingSearchPayload)
}
var setSearch = contractHandler(apicontract.SetSearch, applySearchSetting)
-func applySearchSetting(c *gin.Context, request apicontract.SetSearchRequest) (ret apicontract.Response[*apicontract.SettingSearch]) {
- if err := request.ConfigError(); err != nil {
- return apicontract.Failure[*apicontract.SettingSearch](-1, err.Error())
- }
- ret = apicontract.Success((*apicontract.SettingSearch)(nil))
-
- param := request.ConfigJSON()
- var err error
-
- s := &conf.Search{}
- if err = gulu.JSON.UnmarshalJSON(param, s); err != nil {
- ret = apicontract.Failure[*apicontract.SettingSearch](-1, err.Error())
- return
- }
-
- if s.HanSensitive == nil {
- // 兼容未携带该字段的旧版前端/第三方调用:保持当前值,避免被零值意外关闭并触发重建索引
- s.HanSensitive = model.Conf.Search.Load().HanSensitive
- }
- if s.CustomBlock == nil {
- s.CustomBlock = new(model.Conf.Search.Load().CustomBlockEnabled())
- }
- if s.Mindmap == nil {
- s.Mindmap = new(model.Conf.Search.Load().MindmapEnabled())
- }
- if s.MindmapItem == nil {
- s.MindmapItem = new(model.Conf.Search.Load().MindmapItemEnabled())
- }
-
- issues, applyErr := model.ApplyConfSection("search", s)
- recordSettingIssues(c, issues)
- err = applyErr
- if err != nil {
- return apicontract.Failure[*apicontract.SettingSearch](-1, err.Error())
- }
-
- ret = apicontract.Success(settingSearchPayload(model.Conf.Search.Load()))
- return
-}
-
var setKeymap = contractHandler(apicontract.SetKeymap, applyKeymapSetting)
func applyKeymapSetting(c *gin.Context, request apicontract.SettingKeymapRequest) apicontract.Response[apicontract.Null] {
@@ -550,43 +348,14 @@ func applyKeymapSetting(c *gin.Context, request apicontract.SettingKeymapRequest
return apicontract.Success(apicontract.Null{})
}
-var setAppearance = contractHandler(apicontract.SetAppearance, applyAppearanceSetting)
-
-func applyAppearanceSetting(c *gin.Context, request apicontract.SetAppearanceRequest) (ret apicontract.Response[*apicontract.SettingAppearance]) {
- if err := request.ConfigError(); err != nil {
- return apicontract.Failure[*apicontract.SettingAppearance](-1, err.Error())
- }
- ret = apicontract.Success((*apicontract.SettingAppearance)(nil))
-
- param := request.ConfigJSON()
- var err error
-
- appearance := &conf.Appearance{}
- if err = gulu.JSON.UnmarshalJSON(param, appearance); err != nil {
- ret = apicontract.Failure[*apicontract.SettingAppearance](-1, err.Error())
- return
- }
-
- if nil == appearance.EntryVisibility {
- appearance.EntryVisibility = model.Conf.Appearance.Load().EntryVisibility
- }
- if !request.HasField("bodyGradient") {
- appearance.BodyGradient = model.Conf.Appearance.Load().BodyGradient
- }
- if !request.HasField("globalFontFamilies") {
- appearance.GlobalFontFamilies = model.Conf.Appearance.Load().GlobalFontFamilies
- }
- issues, applyErr := model.ApplyAppearanceSetting(appearance)
- recordSettingIssues(c, issues)
- err = applyErr
- if err != nil {
- return apicontract.Failure[*apicontract.SettingAppearance](-1, err.Error())
- }
-
- ret = apicontract.Success(settingAppearancePayload(model.Conf.Appearance.Load()))
- return
+var applyAppearanceSetting = func(c *gin.Context, request apicontract.SetAppearanceRequest) apicontract.Response[*apicontract.SettingAppearance] {
+ return applySettingSectionWith(c, request, model.ApplyAppearanceSetting,
+ func() *conf.Appearance { return conf.NewAppearanceForContainer(util.IsMobileContainer()) },
+ model.Conf.Appearance.Load, settingAppearancePayload)
}
+var setAppearance = contractHandler(apicontract.SetAppearance, applyAppearanceSetting)
+
var getBootAppearances = contractHandler(apicontract.GetBootAppearances, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.SettingBootAppearancesData] {
appearances := model.GetBootAppearances()
selection := model.GetBootAppearanceSelection()
@@ -672,17 +441,12 @@ func applyPublishSetting(c *gin.Context, request apicontract.SetPublishRequest)
param := request.ConfigJSON()
var err error
- publish := &conf.Publish{}
+ publish := conf.NewPublish()
if err = gulu.JSON.UnmarshalJSON(param, publish); err != nil {
ret = apicontract.Failure[apicontract.SettingPublishData](-1, err.Error())
return
}
- if nil == publish.Auth {
- // 请求体缺省 auth(如 null)时保留现有认证配置,避免把 null 写入 conf.json 导致下次启动崩溃
- // https://github.com/siyuan-note/siyuan/security/advisories/GHSA-rp9f-c2fj-h648
- publish.Auth = model.Conf.Publish.Load().Auth
- }
issues, applyErr := model.ApplyConfSection("publish", publish)
recordSettingIssues(c, issues)
err = applyErr
diff --git a/kernel/api/setting_patch.go b/kernel/api/setting_patch.go
index d5a00b6f54..162d665520 100644
--- a/kernel/api/setting_patch.go
+++ b/kernel/api/setting_patch.go
@@ -66,17 +66,22 @@ func lockSetting(namespace string) func() {
return func() { mu.Unlock(); settingMutationMu.RUnlock() }
}
+// withSettingLock 在配置段锁内提交写入,提交未自行发布修订时补发变更通知。
+func withSettingLock[Data any](namespace string, commit func() apicontract.Response[Data]) apicontract.Response[Data] {
+ release := lockSetting(namespace)
+ defer release()
+ previous := model.ConfNamespaceRevision(namespace)
+ response := commit()
+ if response.Code() == 0 && previous == model.ConfNamespaceRevision(namespace) {
+ model.NotifyConfChanged(namespace)
+ }
+ return response
+}
+
func serializeSetting[Request, Data any](namespace string,
apply func(*gin.Context, Request) apicontract.Response[Data]) func(*gin.Context, Request) apicontract.Response[Data] {
return func(c *gin.Context, request Request) apicontract.Response[Data] {
- release := lockSetting(namespace)
- defer release()
- previous := model.ConfNamespaceRevision(namespace)
- response := apply(c, request)
- if response.Code() == 0 && previous == model.ConfNamespaceRevision(namespace) {
- model.NotifyConfChanged(namespace)
- }
- return response
+ return withSettingLock(namespace, func() apicontract.Response[Data] { return apply(c, request) })
}
}
@@ -122,8 +127,10 @@ func migrateDecisionSettingPatch(patch []byte) ([]byte, error) {
return json.Marshal(ai)
}
-func applySettingPatch[Request, Data any](c *gin.Context, patch []byte, namespace string,
+// 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)
if err != nil {
return apicontract.Failure[*apicontract.SettingPatchData](-1, err.Error())
@@ -155,23 +162,23 @@ var patchSetting = contractHandler(apicontract.PatchSetting, func(c *gin.Context
var response apicontract.Response[*apicontract.SettingPatchData]
switch request.Namespace() {
case "editor":
- response = applySettingPatch(c, patch, request.Namespace(), apicontract.SetEditor, applyEditorSetting)
+ response = applySettingPatch(c, patch, apicontract.SetEditor, applyEditorSetting)
case "export":
- response = applySettingPatch(c, patch, request.Namespace(), apicontract.SetExport, applyExportSetting)
+ response = applySettingPatch(c, patch, apicontract.SetExport, applyExportSetting)
case "fileTree":
- response = applySettingPatch(c, patch, request.Namespace(), apicontract.SetFiletree, applyFiletreeSetting)
+ response = applySettingPatch(c, patch, apicontract.SetFiletree, applyFiletreeSetting)
case "search":
- response = applySettingPatch(c, patch, request.Namespace(), apicontract.SetSearch, applySearchSetting)
+ response = applySettingPatch(c, patch, apicontract.SetSearch, applySearchSetting)
case "appearance":
- response = applySettingPatch(c, patch, request.Namespace(), apicontract.SetAppearance, applyAppearanceSetting)
+ response = applySettingPatch(c, patch, apicontract.SetAppearance, applyAppearanceSetting)
case "flashcard":
- response = applySettingPatch(c, patch, request.Namespace(), apicontract.SetFlashcard, applyFlashcardSetting)
+ response = applySettingPatch(c, patch, apicontract.SetFlashcard, applyFlashcardSetting)
case "secrets":
- response = applySettingPatch(c, patch, request.Namespace(), apicontract.SetSecrets, applySecretsSetting)
+ response = applySettingPatch(c, patch, apicontract.SetSecrets, applySecretsSetting)
case "variables":
- response = applySettingPatch(c, patch, request.Namespace(), apicontract.SetVariables, applyVariablesSetting)
+ response = applySettingPatch(c, patch, apicontract.SetVariables, applyVariablesSetting)
case "keymap":
- response = applySettingPatch(c, patch, request.Namespace(), apicontract.SetKeymap, applyKeymapSetting)
+ response = applySettingPatch(c, patch, apicontract.SetKeymap, applyKeymapSetting)
case "ai":
if util.IsDisabledFeature("ai") {
return apicontract.Failure[*apicontract.SettingPatchData](-1, util.I18nTerm(model.Conf.Lang, "agentCapabilitiesUnavailable"))
@@ -181,15 +188,15 @@ var patchSetting = contractHandler(apicontract.PatchSetting, func(c *gin.Context
if err != nil {
return apicontract.Failure[*apicontract.SettingPatchData](-1, err.Error())
}
- response = applySettingPatch(c, patch, request.Namespace(), apicontract.SetAI, applyAISetting)
+ response = applySettingPatch(c, patch, apicontract.SetAI, applyAISetting)
case "ocr":
- response = applySettingPatch(c, patch, request.Namespace(), apicontract.SetOCRConfig, applyOCRSetting)
+ response = applySettingPatch(c, patch, apicontract.SetOCRConfig, applyOCRSetting)
case "bazaar":
- response = applySettingPatch(c, patch, request.Namespace(), apicontract.SetBazaar, applyBazaarSetting)
+ response = applySettingPatch(c, patch, apicontract.SetBazaar, applyBazaarSetting)
case "publish":
- response = applySettingPatch(c, patch, request.Namespace(), apicontract.SetPublish, applyPublishSetting)
+ response = applySettingPatch(c, patch, apicontract.SetPublish, applyPublishSetting)
case "snippet":
- response = applySettingPatch(c, patch, request.Namespace(), apicontract.SetConfSnippet, applySnippetSetting)
+ response = applySettingPatch(c, patch, apicontract.SetConfSnippet, applySnippetSetting)
case "system", "repo", "sync":
var err error
var issues []model.Issue
diff --git a/kernel/api/setting_test.go b/kernel/api/setting_test.go
index a716315018..7d12562c4c 100644
--- a/kernel/api/setting_test.go
+++ b/kernel/api/setting_test.go
@@ -20,6 +20,7 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "reflect"
"strings"
"sync"
"testing"
@@ -57,6 +58,29 @@ func TestSetAIRejectsInvalidProviderHeaders(t *testing.T) {
}
}
+func TestSetEditorNullRestoresDefault(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ 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()
+ model.Conf.Editor.Store(conf.NewEditor())
+ model.Conf.Editor.Load().DisplayBookmarkIcon = false
+ model.Conf.Editor.Load().Emoji = []string{"1f600"}
+
+ code, message, _ := settingContractRequest(t, "setEditor", setEditor, `{"displayBookmarkIcon":null,"emoji":null}`)
+ if code != 0 {
+ t.Fatalf("save failed: %s", message)
+ }
+ editor := model.Conf.Editor.Load()
+ if !editor.DisplayBookmarkIcon || !reflect.DeepEqual(editor.Emoji, conf.NewEditor().Emoji) {
+ t.Fatalf("null did not restore editor defaults: %+v", editor)
+ }
+}
+
func TestSetBazaarPetalDisabledSerializesTransitions(t *testing.T) {
gin.SetMode(gin.TestMode)
previousConf := model.Conf
@@ -168,47 +192,72 @@ func TestSetBazaarPetalDisabledSerializesTransitions(t *testing.T) {
}
}
-func TestSetFiletreePreservesUseSVGDefaultIconWhenMissing(t *testing.T) {
+func TestSetFiletreeMergeAndNull(t *testing.T) {
gin.SetMode(gin.TestMode)
- previousConf := model.Conf
- previousReadOnly := util.ReadOnly
+ previousConf, previousReadOnly := model.Conf, util.ReadOnly
util.ReadOnly = true
- t.Cleanup(func() {
- model.Conf = previousConf
- util.ReadOnly = previousReadOnly
- })
+ t.Cleanup(func() { model.Conf, util.ReadOnly = previousConf, previousReadOnly })
engine := gin.New()
engine.POST("/api/setting/setFiletree", setFiletree)
+ engine.POST("/api/setting/patch", patchSetting)
for _, test := range []struct {
- name string
- enabled bool
+ name string
+ path string
+ body string
+ want conf.FileTree
}{
- {name: "enabled", enabled: true},
- {name: "disabled"},
+ // 未提交的字段保持当前配置
+ {
+ name: "omitted keeps current",
+ path: "/api/setting/setFiletree",
+ body: `{}`,
+ want: conf.FileTree{BoxDocEnabled: true, UseSVGDefaultIcon: false, UseSingleLineSave: false, Sort: 3},
+ },
+ {
+ name: "explicit values",
+ path: "/api/setting/setFiletree",
+ body: `{"boxDocEnabled":false,"useSVGDefaultIcon":true}`,
+ want: conf.FileTree{UseSVGDefaultIcon: true, UseSingleLineSave: false, Sort: 3},
+ },
+ // null 还原构造函数默认值,而不是零值
+ {
+ name: "null restores defaults",
+ path: "/api/setting/setFiletree",
+ body: `{"useSingleLineSave":null,"sort":null}`,
+ want: conf.FileTree{BoxDocEnabled: true, UseSVGDefaultIcon: false,
+ UseSingleLineSave: util.DefaultUseSingleLineSave, Sort: util.SortModeCustom},
+ },
+ {
+ name: "patch null restores defaults",
+ path: "/api/setting/patch",
+ body: `{"fileTree":{"useSingleLineSave":null,"sort":null}}`,
+ want: conf.FileTree{BoxDocEnabled: true, UseSVGDefaultIcon: false,
+ UseSingleLineSave: util.DefaultUseSingleLineSave, Sort: util.SortModeCustom},
+ },
} {
t.Run(test.name, func(t *testing.T) {
model.Conf = model.NewAppConf()
model.Conf.FileTree.Store(conf.NewFileTree())
- model.Conf.FileTree.Load().UseSVGDefaultIcon = new(test.enabled)
+ model.Conf.FileTree.Load().BoxDocEnabled = true
+ model.Conf.FileTree.Load().UseSVGDefaultIcon = false
+ model.Conf.FileTree.Load().UseSingleLineSave = false
+ model.Conf.FileTree.Load().Sort = 3
recorder := httptest.NewRecorder()
- request := httptest.NewRequest(http.MethodPost, "/api/setting/setFiletree", strings.NewReader(`{}`))
+ request := httptest.NewRequest(http.MethodPost, test.path, strings.NewReader(test.body))
request.Header.Set("Content-Type", "application/json")
engine.ServeHTTP(recorder, request)
-
- response := &struct {
+ var response struct {
Code int `json:"code"`
- }{}
- if err := json.Unmarshal(recorder.Body.Bytes(), response); err != nil {
- t.Fatalf("unmarshal setFiletree response failed: %v", err)
}
- if 0 != response.Code {
- t.Fatalf("setFiletree failed: %s", recorder.Body.String())
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != 0 {
+ t.Fatalf("setting failed: %s (%v)", recorder.Body.String(), err)
}
- if nil == model.Conf.FileTree.Load().UseSVGDefaultIcon ||
- test.enabled != *model.Conf.FileTree.Load().UseSVGDefaultIcon {
- t.Fatalf("missing setting changed the current value: %#v", model.Conf.FileTree.Load().UseSVGDefaultIcon)
+ got := model.Conf.FileTree.Load()
+ if got.BoxDocEnabled != test.want.BoxDocEnabled || got.UseSVGDefaultIcon != test.want.UseSVGDefaultIcon ||
+ got.UseSingleLineSave != test.want.UseSingleLineSave || got.Sort != test.want.Sort {
+ t.Fatalf("unexpected file tree settings: %+v", got)
}
})
}
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 6bdae8ecac..23c061f150 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -1067,7 +1067,7 @@ var AssetOCR = define[AssetPathRequest, AssetOCRData]("ocr", "/api/asset/ocr", A
var AIOCR = define[AssetPathRequest, AssetTextData]("aiOCR", "/api/ai/ocr", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
var GetOCRConfig = define[EmptyRequest, OCRConfigData]("getOCRConfig", "/api/asset/getOCRConfig", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")
-var SetOCRConfig = define[SettingOCR, SettingOCR]("setOCRConfig", "/api/asset/setOCRConfig", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "ocr"}}, "POST")
+var SetOCRConfig = define[SettingOCR, SettingOCR]("setOCRConfig", "/api/asset/setOCRConfig", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "ocr", Merge: true}}, "POST")
var ImportOCRModels = define[ImportOCRModelsRequest, OCRModel]("importOCRModels", "/api/asset/importOCRModels", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{}, "POST")
// 重命名普通笔记本资源,并同步字面量及百分号编码的文档、数据库引用。
@@ -1142,27 +1142,27 @@ var InsertLocalAssets = define[InsertLocalAssetsRequest, AssetUploadData]("inser
var InsertCover = define[InsertCoverRequest, AssetInsertCoverData]("insertCover", "/api/asset/insertCover", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
var UploadAsset = define[UploadAssetRequest, AssetUploadData]("uploadAsset", "/api/asset/upload", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{}, "POST")
-var SetConfSnippet = define[SetConfSnippetRequest, *SettingSnpt]("setConfSnippet", "/api/setting/setSnippet", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "snippet"}}, "POST")
-var SetBazaar = define[SetBazaarRequest, *SettingBazaar]("setBazaar", "/api/setting/setBazaar", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "bazaar"}}, "POST")
+var SetConfSnippet = define[SetConfSnippetRequest, *SettingSnpt]("setConfSnippet", "/api/setting/setSnippet", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "snippet", Merge: true}}, "POST")
+var SetBazaar = define[SetBazaarRequest, *SettingBazaar]("setBazaar", "/api/setting/setBazaar", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "bazaar", Merge: true}}, "POST")
// SetAI 使用共享规范化规则;智能体确认超时负数回退 600 秒,0 保留无限等待语义。
-// web 省略时保留当前配置;初始搜索为 Exa、抓取为直接请求,可独立切换到共用密钥的 DeepSeek。
+// web 初始搜索为 Exa、抓取为直接请求,可独立切换到共用密钥的 DeepSeek。
// 工具调用轮数和输出 token 上限的负数归零;温度超出 0–2 回退 1。
// 嵌入并发数和批大小省略、null 或小于 1 时分别使用 8 和 10,超过上限时分别限制为 64 和 128。
// ChatGPT 账户绑定变化时与主配置一起可恢复提交,失败时回滚且不发布新配置;未变化时不访问绑定存储。
-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")
+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")
+var SetVariables = define[SetVariablesRequest, *SettingVariables]("setVariables", "/api/setting/setVariables", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "variables", Merge: true}}, "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")
+var SetFlashcard = define[SetFlashcardRequest, *SettingFlashcard]("setFlashcard", "/api/setting/setFlashcard", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "flashcard", Merge: true}}, "POST")
-// SetEditor 使用与启动、导入相同的规范化规则并同步保存。锚文本长度 1–5120 保持不变,小于 1 回退 64。
-// 字体大小超出 9–72 回退 16;省略字体列表和图片标题字段时继续保留原有兼容行为。
+// 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")
+var SetEditor = define[SetEditorRequest, *SettingEditor]("setEditor", "/api/setting/setEditor", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "editor", Merge: true}}, "POST")
// PatchSetting 保留省略字段,成功后客户端重新读取配置;通知不包含密码或密钥。
// export.blockRefMode 的旧值 0、1、5 按旧设置接口的兼容语义转换为 4;启动迁移由配置版本控制。
@@ -1176,27 +1176,36 @@ var PatchSetting = define[PatchSettingRequest, *SettingPatchData]("patchSetting"
// SetExport 整体替换导出配置,将 blockRefMode 的废弃值 0、1、5 转换为 4 后同步保存并回显。
// 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")
+var SetExport = define[SetExportRequest, *SettingExport]("setExport", "/api/setting/setExport", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "export", Merge: true}}, "POST")
-// SetFiletree 使用与启动、导入相同的路径和数值规范化规则;省略顶层笔记本文档和默认图标选项时保留当前值。
+// 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")
+var SetFiletree = define[SetFiletreeRequest, *SettingFileTree]("setFiletree", "/api/setting/setFiletree", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "fileTree", Merge: true}}, "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")
+// SetSearch 使用与启动、导入相同的规范化规则;limit 小于 1 回退 64,1–31 提升至 32,大于 10240 时截断至 10240。
+// 反链提及关键词上限小于 1 回退 512。
+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。
-var SetAppearance = define[SetAppearanceRequest, *SettingAppearance]("setAppearance", "/api/setting/setAppearance", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "appearance"}}, "POST")
+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,未覆盖的显隐跟随该内置方案。
// 省略 defaults 的方案及旧版本方案保留独立显隐语义;entries 中的布尔值始终优先,未知入口和插件排序保留。
var SetEntryVisibility = define[SetEntryVisibilityRequest, *SettingEntryVisibility]("setEntryVisibility", "/api/setting/setEntryVisibility", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "appearance"}}, "POST")
-var SetPublish = define[SetPublishRequest, SettingPublishData]("setPublish", "/api/setting/setPublish", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "publish"}}, "POST")
+
+// SetPublish 认证账户须提交完整数组,传 null 或空数组表示清空账户。
+var SetPublish = define[SetPublishRequest, SettingPublishData]("setPublish", "/api/setting/setPublish", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "publish", Merge: true}}, "POST")
+
+// GetSettingSection 读取单个配置段,字段与脱敏规则与 /api/system/getConf 一致,仅返回请求的配置段以减少传输量。
+// namespace 必须是已注册的配置段;需要完整配置的启动和重连场景仍使用 /api/system/getConf。
+var GetSettingSection = define[SettingGetSectionRequest, SettingSectionData]("getSettingSection", "/api/setting/getSection", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")
+
var GetBootAppearances = define[EmptyRequest, SettingBootAppearancesData]("getBootAppearances", "/api/setting/getBootAppearances", AuthenticatedAccess, NoBody, ResponseOptions{}, "POST")
var SetBootAppearance = define[SettingBootAppearanceRequest, *SettingBootAppearanceSelection]("setBootAppearance", "/api/setting/setBootAppearance", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "appearance", Mode: SettingSilent}}, "POST")
var SetBazaarPetalDisabled = define[SettingPetalDisabledRequest, SettingPetalDisabledData]("setBazaarPetalDisabled", "/api/setting/setBazaarPetalDisabled", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "bazaar"}}, "POST")
+
+// SetKeymap 整体替换快捷键配置:data 必须提交完整的快捷键对象,只提交部分分组会清空未提交的快捷键。
+// 单条快捷键请使用 /api/setting/patch 的 keymap 命名空间,该接口按对象递归合并。
var SetKeymap = define[SettingKeymapRequest, Null]("setKeymap", "/api/setting/setKeymap", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "keymap"}}, "POST")
// 接收可选的 exit(默认 false),要求管理员权限并禁止只读写入。
diff --git a/kernel/apicontract/ocr.go b/kernel/apicontract/ocr.go
index 203c72115a..2ce0934987 100644
--- a/kernel/apicontract/ocr.go
+++ b/kernel/apicontract/ocr.go
@@ -4,26 +4,24 @@ import "mime/multipart"
// SettingOCR 的选择仅保存在当前设备;切换提供商或模型不删除、重跑已有识别结果。
// auto 仅控制内核后台识别,手动识别继续使用 /api/asset/ocr 的既有输入和输出。
-// showText、showEmpty、showError 独立控制图片悬浮提示,不受 auto 影响,也不改变已有结果和搜索索引。
-// 三项省略或为 null 时保留已有选择;缺失设备配置默认开启文本预览,关闭无文本和失败提示。
-// thresholds 省略或为 null 时保留设备已保存的阈值;传入对象时整体替换。
-// 修改阈值只影响后续识别,不修改模型文件或已有结果,Tesseract 不使用这些参数。
+// showText 默认开启,showEmpty、showError 默认关闭;三项独立控制图片悬浮提示,不受 auto 影响,也不改变已有结果和搜索索引。
+// thresholds 为 null 或每项为 null 时使用模型默认值;修改阈值只影响后续识别,不修改模型文件或已有结果,Tesseract 不使用这些参数。
// 仅内置 tiny;旧内置模型标识 small 会归一化为 tiny,自行导入的模型仍使用内容摘要标识。
// provider 可为 tesseract、paddleocr 或 ai;aiModelId 是已配置 AI 模型的 ID,与本地 model 独立保存。
-// aiModelId 省略或为 null 时保留已有选择;失效的已保存 ID 保留并显示不可用,不回退到其他模型。
+// aiModelId 传 null 清空选择;失效的已保存 ID 保留并显示不可用,不回退到其他模型。
// 首次切换到 ai 时 auto 强制关闭;之后可显式开启,手动和自动识别均使用所选 AI 模型。
-// reasoningEffort 独立于智能体设置,省略或为 null 时保留;空字符串沿用模型默认行为。
+// reasoningEffort 独立于智能体设置;空字符串沿用模型默认行为。
// 可选 none、low、medium、high、xhigh、max,均复用现有协议适配;提供商拒绝参数时返回错误,不自动回退。
type SettingOCR struct {
- Provider string `json:"provider"`
- Model string `json:"model"`
- Auto bool `json:"auto"`
- ShowText *bool `json:"showText,omitempty" api:"optional"`
- ShowEmpty *bool `json:"showEmpty,omitempty" api:"optional"`
- ShowError *bool `json:"showError,omitempty" api:"optional"`
- AIModelID *string `json:"aiModelId,omitempty" api:"optional"`
- ReasoningEffort *string `json:"reasoningEffort,omitempty" api:"optional"`
- Thresholds *OCRThresholds `json:"thresholds,omitempty" api:"optional"`
+ Provider string `json:"provider"`
+ Model string `json:"model"`
+ Auto bool `json:"auto"`
+ ShowText *bool `json:"showText,omitempty" api:"optional,nullable"`
+ ShowEmpty bool `json:"showEmpty" api:"optional,nullable"`
+ ShowError bool `json:"showError" api:"optional,nullable"`
+ AIModelID string `json:"aiModelId" api:"optional,nullable"`
+ ReasoningEffort string `json:"reasoningEffort" api:"optional,nullable"`
+ Thresholds OCRThresholds `json:"thresholds" api:"optional,nullable"`
}
// OCRThresholds 的 detection、box 必须为 (0, 1) 内的有限数,recognition 为 [0, 1] 内的有限数。
diff --git a/kernel/apicontract/ocr_test.go b/kernel/apicontract/ocr_test.go
index de9eab2680..b2cb9d2be6 100644
--- a/kernel/apicontract/ocr_test.go
+++ b/kernel/apicontract/ocr_test.go
@@ -29,7 +29,7 @@ func TestOCRThresholdContract(t *testing.T) {
}
for _, fields := range []string{`{"detection":null,"box":null,"recognition":null}`, `{"detection":0.3,"box":0.6,"recognition":0}`} {
body := `{"provider":"paddleocr","model":"small","auto":false,"thresholds":` + fields + `}`
- if request, err := SetOCRConfig.Decode(strings.NewReader(body)); err != nil || request.Thresholds == nil {
+ if _, err := SetOCRConfig.Decode(strings.NewReader(body)); err != nil {
t.Fatalf("rejected valid thresholds: %s: %v", body, err)
}
}
@@ -38,7 +38,7 @@ func TestOCRThresholdContract(t *testing.T) {
func TestOCRAIModelCompatibility(t *testing.T) {
for _, field := range []string{"", `,"aiModelId":null`, `,"aiModelId":"vision"`} {
request, err := SetOCRConfig.Decode(strings.NewReader(`{"provider":"ai","model":"tiny","auto":false` + field + `}`))
- if err != nil || field == `,"aiModelId":"vision"` && (request.AIModelID == nil || *request.AIModelID != "vision") {
+ if err != nil || field == `,"aiModelId":"vision"` && request.AIModelID != "vision" {
t.Fatalf("valid independent model selection: %+v, %v", request, err)
}
}
diff --git a/kernel/apicontract/setting.go b/kernel/apicontract/setting.go
index dac94d6cf5..7a9f3fff39 100644
--- a/kernel/apicontract/setting.go
+++ b/kernel/apicontract/setting.go
@@ -22,8 +22,8 @@ type SettingAI struct {
Providers []*SettingProvider `json:"providers" api:"optional,nullable"`
}
-// SettingAIWeb 省略时沿用已保存的网页服务配置;初始搜索为 exa,抓取为 direct。
-// 可分别选择 deepseek,共用独立 API 密钥;超时默认 30 秒,上限 600 秒。
+// SettingAIWeb 初始搜索为 exa,抓取为 direct;可分别选择 deepseek,共用独立 API 密钥。
+// 超时默认 30 秒,上限 600 秒。
// DeepSeek Search 返回 5 条摘要且不取正文;Fetch 仅获取网页正文,不下载文件。
// Search 发送查询词,Fetch 发送目标 URL;不发送原始问题、浏览器凭证或额外笔记内容。
type SettingAIWeb struct {
@@ -208,9 +208,8 @@ type SettingFlashcard struct {
Weights string `json:"weights" api:"optional,nullable"`
}
-// SettingEditor 描述编辑器配置。displayImgName 和 displayImgAlt 默认关闭,更新设置时省略这些字段保留当前值。
-// blockGutterMode 控制是否显示完整块标,默认 false,输出及持久化均为布尔值。
-// 整段设置接口省略时保留当前值;null 表示关闭,其他非布尔类型拒绝更新。
+// SettingEditor 描述编辑器配置。displayImgName、displayImgAlt、blockGutterMode 和 pageScrollButtons 默认关闭,
+// null 表示回到默认值,其他非布尔类型拒绝更新。
type SettingEditor struct {
AllowSVGScript bool `json:"allowSVGScript" api:"optional,nullable"`
AllowHTMLBLockScript bool `json:"allowHTMLBLockScript" api:"optional,nullable"`
@@ -375,7 +374,7 @@ type SettingFileTree struct {
}
type SettingSearch struct {
- // 思维导图默认开启,思维导图项默认关闭;更新时省略或传 null 保留当前值。
+ // 思维导图默认开启,思维导图项默认关闭;null 表示回到默认值。
Mindmap *bool `json:"mindmap" api:"optional,nullable"`
MindmapItem *bool `json:"mindmapItem" api:"optional,nullable"`
CustomBlock *bool `json:"customBlock" api:"optional,nullable"`
diff --git a/kernel/apicontract/setting_config.go b/kernel/apicontract/setting_config.go
index d5684feb14..bff3733845 100644
--- a/kernel/apicontract/setting_config.go
+++ b/kernel/apicontract/setting_config.go
@@ -20,16 +20,6 @@ func (r settingConfig) ConfigJSON() []byte { return append([]byte(nil), r
func (r settingConfig) ConfigError() error { return r.configError }
func (r settingConfig) HasField(name string) bool { _, ok := r.fields[name]; return ok }
-// HasFieldFold 按配置结构的大小写兼容规则检查字段是否提交。
-func (r settingConfig) HasFieldFold(name string) bool {
- for field := range r.fields {
- if strings.EqualFold(field, name) {
- return true
- }
- }
- return false
-}
-
func decodeSettingConfig(reader io.Reader, path string, removeApp bool) (r settingConfig, err error) {
var raw json.RawMessage
err = json.NewDecoder(reader).Decode(&raw)
@@ -92,8 +82,11 @@ type SettingPetalDisabledData struct {
GlobalPetalRevision uint64 `json:"globalPetalRevision"`
GlobalPetalChanged bool `json:"globalPetalChanged"`
}
+
+// SettingKeymapRequest 承载完整的快捷键配置,data 与 conf.json 的 keymap 段同构且必须提交。
+// 内置快捷键由前端按平台补全,内核只保留提交的内容。
type SettingKeymapRequest struct {
- Data map[string]JSONValue `json:"data" api:"optional,nullable"`
+ Data map[string]JSONValue `json:"data"`
}
type SettingIconRequest struct {
Icon string `json:"icon" api:"trim"`
diff --git a/kernel/apicontract/setting_patch.go b/kernel/apicontract/setting_patch.go
index bac2eeb31d..8f307b6b71 100644
--- a/kernel/apicontract/setting_patch.go
+++ b/kernel/apicontract/setting_patch.go
@@ -20,8 +20,8 @@ type SettingPatchData struct {
Issues []SettingIssue `json:"issues"`
}
-// PatchSettingRequest 每次仅更新一个配置域。对象递归合并,数组和 null 整体替换,省略字段保留当前值。
-// 旧设置接口的整份配置提交和默认值语义不变;失败不发出配置变更通知。
+// PatchSettingRequest 每次仅更新一个配置域。对象递归合并,数组整体替换,省略字段保持当前值,null 还原默认值。
+// 失败不发出配置变更通知。
type PatchSettingRequest struct {
Editor *SettingEditor `json:"editor" api:"optional"`
Export *SettingExport `json:"export" api:"optional"`
diff --git a/kernel/apicontract/setting_test.go b/kernel/apicontract/setting_test.go
index eb40df19aa..66a16ecdcd 100644
--- a/kernel/apicontract/setting_test.go
+++ b/kernel/apicontract/setting_test.go
@@ -43,9 +43,8 @@ func TestSettingKeymapOpaqueValues(t *testing.T) {
t.Fatalf("keymap payload: %s %v", encoded, err)
}
for _, body := range []string{`{}`, `{"data":null}`} {
- request, err = SetKeymap.Decode(strings.NewReader(body))
- if err != nil || request.Data != nil {
- t.Fatalf("keymap omission: %+v %v", request, err)
+ if _, err = SetKeymap.Decode(strings.NewReader(body)); err == nil {
+ t.Fatalf("keymap must reject incomplete data: %s", body)
}
}
}
diff --git a/kernel/apicontract/setting_write.go b/kernel/apicontract/setting_write.go
index 8dfffd485e..a74205abdc 100644
--- a/kernel/apicontract/setting_write.go
+++ b/kernel/apicontract/setting_write.go
@@ -18,6 +18,8 @@ const (
type SettingWrite struct {
Namespace string // 变更通知中的配置命名空间,"*" 表示可能涉及多个配置段
Mode SettingWriteMode
+ // Merge 声明请求体与配置段同构:解码前先合并进当前段,未提交的字段保持当前值,null 还原默认值。
+ Merge bool
}
// Declared 报告端点是否声明了配置写入。
diff --git a/kernel/model/conf_patch.go b/kernel/model/conf_patch.go
index 970cc423f9..b9e3e1d95d 100644
--- a/kernel/model/conf_patch.go
+++ b/kernel/model/conf_patch.go
@@ -7,6 +7,7 @@ import (
"fmt"
"path/filepath"
"reflect"
+ "sort"
"strings"
"time"
@@ -28,20 +29,40 @@ func MergeConfJSON(base, patch []byte) ([]byte, error) {
if current == nil {
current = map[string]json.RawMessage{}
}
- for key, value := range changes {
- if bytes.HasPrefix(bytes.TrimSpace(value), []byte("{")) && bytes.HasPrefix(bytes.TrimSpace(current[key]), []byte("{")) {
- merged, err := MergeConfJSON(current[key], value)
+ keys := make([]string, 0, len(changes))
+ for key := range changes {
+ keys = append(keys, key)
+ }
+ sort.Strings(keys)
+ for _, key := range keys {
+ value := changes[key]
+ target := mergeConfJSONKey(current, key)
+ if bytes.HasPrefix(bytes.TrimSpace(value), []byte("{")) && bytes.HasPrefix(bytes.TrimSpace(current[target]), []byte("{")) {
+ merged, err := MergeConfJSON(current[target], value)
if err != nil {
return nil, err
}
- current[key] = merged
+ current[target] = merged
} else {
- current[key] = value
+ current[target] = value
}
}
return json.Marshal(current)
}
+// mergeConfJSONKey 把补丁键映射到既有配置的等价键,保留大小写不同的字段写法。
+func mergeConfJSONKey(current map[string]json.RawMessage, key string) string {
+ if _, exists := current[key]; exists {
+ return key
+ }
+ for existing := range current {
+ if strings.EqualFold(existing, key) {
+ return existing
+ }
+ }
+ return key
+}
+
func (spec *SectionSpec[C]) patch(patch []byte) ([]Issue, error) {
spec.WriteLock.Lock()
defer spec.WriteLock.Unlock()
@@ -79,6 +100,9 @@ func MergeConfSectionJSON(current any, patch []byte) ([]byte, error) {
// ConfSectionPatchJSON 返回合并后的配置段,调用方在发布前保留契约校验与专用领域动作。
func ConfSectionPatchJSON(namespace string, patch []byte) ([]byte, error) {
+ if nil == Conf {
+ return patch, nil
+ }
spec, ok := SectionSpecByNamespace(namespace)
if !ok {
return nil, fmt.Errorf("unsupported configuration section: %s", namespace)