An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Initialize OpenFreeMap for new map settings https://github.com/siyuan-note/siyuan/issues/20129
Daniel9b2f30bdcc90
diff --git a/app/src/config/map.test.ts b/app/src/config/map.test.tsindex 6de1fbb3b1..af691fc853 100644--- a/app/src/config/map.test.ts+++ b/app/src/config/map.test.ts@@ -19,6 +19,7 @@ const createPanel = async (initial: Service[] = [service()], missingID?: string,backend: Backend = {services: initial, version: 0}) => {let deferRead = deferInitial;let reads = 0;+ const requests: string[] = [];const readRequests: Array<(response: unknown) => void> = [];const writes: Array<{services: Write[]; expectedRevision: string;resolve: (response: unknown) => void; reject: (error: Error) => void}> = [];@@ -68,6 +69,7 @@ const createPanel = async (initial: Service[] = [service()], missingID?: string,showMessage: (message: string) => messages.push(message),confirmDialog: (_title: string, _text: string, confirm: () => void) => confirmations.push(confirm),fetchSyncPost: (url: string, data: {services: Write[]; expectedRevision: string}) => {+ requests.push(url);if (url === "/api/map/getConf") {reads++;if (deferRead) {@@ -85,7 +87,7 @@ const createPanel = async (initial: Service[] = [service()], missingID?: string,await tick();const event = (id: string) => ({target: controls[id], stopPropagation() {}});return {- controls, writes, readRequests, messages, confirmations, close, config,+ controls, writes, readRequests, requests, messages, confirmations, close, config,reads: () => reads, notify: () => notifications.get("map-change")?.(),deferRead: () => { deferRead = true; },updateServer: (services: Service[]) => { backend.services = services; backend.version++; },@@ -184,6 +186,18 @@ test("changing providers away and back clears both old AMap credentials", asyncawait p.finishWrite(); await saving; p.close();});+test("preconfigured OpenFreeMap is ready without a settings write or runtime request", async () => {+ const p = await createPanel([{...service("builtin-openfreemap", "openfreemap"), name: "OpenFreeMap"}]);+ assert.equal(p.controls.mapServiceSelect.value, "builtin-openfreemap");+ assert.equal(p.controls.mapServiceName.value, "OpenFreeMap");+ assert.equal(p.controls.mapServiceProvider.value, "openfreemap");+ assert.equal(p.controls.mapAPIKeyRow.classList.contains("fn__none"), true);+ assert.equal(p.controls.mapSecurityCodeRow.classList.contains("fn__none"), true);+ assert.deepEqual(p.requests, ["/api/map/getConf"]);+ assert.equal(p.writes.length, 0);+ p.close();+});+test("OpenFreeMap writes no credentials and missing IDs are explicitly preserved", async () => {const p = await createPanel([service()], "other-device-id");assert.equal(p.controls.mapServiceID, undefined);diff --git a/kernel/apicontract/map.go b/kernel/apicontract/map.goindex 1d0032d2d4..bd388afe53 100644--- a/kernel/apicontract/map.go+++ b/kernel/apicontract/map.go@@ -9,6 +9,8 @@ import ()// MapConfig 为脱敏配置,只提供服务标识、供应商和凭据存在状态,不返回凭据内容。+// 启动时仅缺失或 null 的本机地图配置预置一项免密钥 OpenFreeMap;已有配置及删除后的空列表保持不变。+// 初始化不会选择或创建地图视图,也不请求地图供应商。type MapConfig struct {Services []*MapService `json:"services"`Revision string `json:"revision"`@@ -25,7 +27,7 @@ type MapService struct {// MapSetConfRequest 整体替换最多 100 个本机服务,要求管理员和可写工作空间。// 空列表删除全部服务;不接受未知字段、null 或任意远程服务地址。-// expectedRevision 必须与读取的 revision 一致;旧配置初始为空字符串。+// expectedRevision 必须与读取的 revision 一致;未保存过版本号的已有配置保持空字符串。// 冲突返回 code=-1、msg=mapSettingsConflict,不修改服务和凭据;成功后生成新的独立版本号。type MapSetConfRequest struct {Services []MapServiceInput `json:"services"`diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex 733baf3938..84e647a9c5 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -100,7 +100,6 @@ func NewAppConf() *AppConf {return &AppConf{LogLevel: "debug",OIDC: conf.NewOIDC(),- Map: conf.NewMap(),m: &sync.RWMutex{},userLock: &sync.RWMutex{},}diff --git a/kernel/model/map.go b/kernel/model/map.goindex e252718a44..044ad63f1e 100644--- a/kernel/model/map.go+++ b/kernel/model/map.go@@ -26,7 +26,12 @@ type MapServiceInput struct {func normalizeMapConfig(config *conf.Map) *conf.Map {if config == nil {- return conf.NewMap()+ // 仅缺失配置时预置服务;已保存的空列表表示用户没有服务,不再自动补回。+ // 内置服务使用稳定标识,使其他设备首次初始化后可以解析同步视图中的同一引用。+ return &conf.Map{+ Services: []*conf.MapService{{ID: "builtin-openfreemap", Name: "OpenFreeMap", Provider: conf.MapProviderOpenFreeMap}},+ Revision: ast.NewNodeID(),+ }}if config.Services == nil {config.Services = []*conf.MapService{}diff --git a/kernel/model/map_test.go b/kernel/model/map_test.goindex 2921416e52..2396ceac76 100644--- a/kernel/model/map_test.go+++ b/kernel/model/map_test.go@@ -28,32 +28,167 @@ func mapTestConfig(t *testing.T) *AppConf {oldDir, oldReadonly := util.ConfDir, util.ReadOnlyutil.ConfDir, util.ReadOnly = t.TempDir(), falset.Cleanup(func() { util.ConfDir, util.ReadOnly = oldDir, oldReadonly })- return NewAppConf()+ app := NewAppConf()+ app.Map = normalizeMapConfig(app.Map)+ return app}func TestMapConfigDefaultsAndLegacyNil(t *testing.T) {- for _, body := range []string{`{}`, `{"map":null}`, `{"map":{}}`, `{"map":{"services":null}}`} {+ var serviceID, previousRevision string+ for _, body := range []string{`{}`, `{"map":null}`} {app := NewAppConf()if err := json.Unmarshal([]byte(body), app); err != nil {t.Fatal(err)}app.Map = normalizeMapConfig(app.Map)- if app.Map.Services == nil || len(app.Map.Services) != 0 || app.Map.Revision != "" {- t.Fatalf("legacy configuration acquired a default service: %s", body)+ if len(app.Map.Services) != 1 || app.Map.Revision == "" {+ t.Fatalf("missing map configuration was not initialized: %s", body)+ }+ service := app.Map.Services[0]+ if !conf.IsMapServiceID(service.ID) || service.Name != "OpenFreeMap" || service.Provider != conf.MapProviderOpenFreeMap ||+ !service.Configured() || service.HasAPIKey() || service.HasSecurityCode() {+ t.Fatalf("invalid default map service: %#v", service)+ }+ if serviceID != "" && serviceID != service.ID {+ t.Fatal("default service reference differs across initializations")+ }+ serviceID = service.ID+ if app.Map.Revision == previousRevision {+ t.Fatal("separate initializations reused the same revision")+ }+ previousRevision = app.Map.Revision+ before := app.Map+ app.Map = normalizeMapConfig(app.Map)+ if app.Map != before || len(app.Map.Services) != 1 {+ t.Fatal("normalization repeated default initialization")}app.Map.DecryptCredentials()+ runtime, err := app.GetMapRuntime(service.ID)+ if err != nil || runtime.Provider != conf.MapProviderOpenFreeMap || runtime.APIKey != "" || runtime.SecurityCode != "" {+ t.Fatal("default service did not resolve without credentials")+ }if _, err := app.GetMapRuntime("missing"); err == nil {- t.Fatal("empty configuration resolved a runtime")+ t.Fatal("missing service reference fell back to the default")+ }+ }++ for _, body := range []string{`{"map":{}}`, `{"map":{"services":null}}`, `{"map":{"services":[]}}`,+ `{"map":{"services":[],"revision":"saved-empty"}}`, `{"map":{"revision":"saved-empty"}}`} {+ app := NewAppConf()+ if err := json.Unmarshal([]byte(body), app); err != nil {+ t.Fatal(err)+ }+ revision := app.Map.Revision+ app.Map = normalizeMapConfig(app.Map)+ if app.Map.Services == nil || len(app.Map.Services) != 0 || app.Map.Revision != revision {+ t.Fatalf("existing empty configuration was replaced: %s", body)}}+var config *conf.Mapconfig.EncryptCredentials()config.DecryptCredentials()- if len(config.Masked().Services) != 0 {+ if len(config.Masked().Services) != 0 || len(conf.NewMap().Services) != 0 {t.Fatal("nil map configuration is not safely readable")}}+func TestMapConfigInitializationPreservesExistingServices(t *testing.T) {+ for _, revision := range []string{"", "saved-revision"} {+ app := NewAppConf()+ app.Map = &conf.Map{Revision: revision, Services: []*conf.MapService{+ {ID: "custom-free", Name: "My map", Provider: conf.MapProviderOpenFreeMap},+ {ID: "another-free", Name: "Another map", Provider: conf.MapProviderOpenFreeMap},+ {ID: "custom-key", Name: "Custom", Provider: conf.MapProviderAMap, APIKey: "fixture-key", SecurityCode: "fixture-code"},+ }}+ data, err := app.marshalForSave()+ if err != nil {+ t.Fatal(err)+ }+ stored := NewAppConf()+ if err = json.Unmarshal(data, stored); err != nil {+ t.Fatal(err)+ }+ stored.Map = normalizeMapConfig(stored.Map)+ stored.Map.DecryptCredentials()+ if !reflect.DeepEqual(stored.Map, app.Map) {+ t.Fatal("initialization changed existing services, credentials, IDs, order, or revision")+ }+ }+}++func TestMapConfigDefaultPersistsAndDeletedDefaultStaysDeleted(t *testing.T) {+ app := mapTestConfig(t)+ initial := app.GetMap()+ app.Save()+ for range 2 {+ data, err := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))+ if err != nil {+ t.Fatal(err)+ }+ app = NewAppConf()+ if err = json.Unmarshal(data, app); err != nil {+ t.Fatal(err)+ }+ app.Map = normalizeMapConfig(app.Map)+ app.Map.DecryptCredentials()+ if !reflect.DeepEqual(app.GetMap(), initial) {+ t.Fatal("restart changed the default service or its revision")+ }+ app.Save()+ }+ deleted, err := app.SetMap([]MapServiceInput{}, initial.Revision)+ if err != nil || len(deleted.Services) != 0 || deleted.Revision == initial.Revision {+ t.Fatal("default service deletion failed")+ }+ for range 2 {+ data, err := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))+ if err != nil {+ t.Fatal(err)+ }+ app = NewAppConf()+ if err = json.Unmarshal(data, app); err != nil {+ t.Fatal(err)+ }+ app.Map = normalizeMapConfig(app.Map)+ if !reflect.DeepEqual(app.GetMap(), deleted) {+ t.Fatal("restart restored the deleted default service")+ }+ if _, err = app.SetMap([]MapServiceInput{}, initial.Revision); err == nil || err.Error() != "mapSettingsConflict" {+ t.Fatal("restart accepted a revision from before the default service was deleted")+ }+ app.Save()+ }+}++func TestMapConfigSettingsResetPreservesServiceInitialization(t *testing.T) {+ settingsResetTestEnvironment(t)+ Conf.Map = normalizeMapConfig(Conf.Map)+ for _, remove := range []bool{false, true} {+ if remove {+ if _, err := Conf.SetMap([]MapServiceInput{}, Conf.Map.Revision); err != nil {+ t.Fatal(err)+ }+ }+ before := Conf.GetMap()+ if err := ResetSettings(); err != nil {+ t.Fatal(err)+ }+ data, err := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))+ if err != nil {+ t.Fatal(err)+ }+ stored := NewAppConf()+ if err = json.Unmarshal(data, stored); err != nil {+ t.Fatal(err)+ }+ stored.Map = normalizeMapConfig(stored.Map)+ if !reflect.DeepEqual(before, Conf.GetMap()) || !reflect.DeepEqual(before, stored.GetMap()) {+ t.Fatal("settings reset changed map services or restored a deleted default")+ }+ }+}+func TestMapConfigCredentialsAndStableReferences(t *testing.T) {app := mapTestConfig(t)inputs := []MapServiceInput{