An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Store ChatGPT account bindings on each device https://github.com/siyuan-note/siyuan/issues/20572
Daniel73f77d0b6464
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z.syindex 5947ba0622..418bab3142 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z.sy@@ -6,7 +6,7 @@"id": "20230304000547-ibldj1z","title": "Artificial Intelligence","type": "doc",- "updated": "20261007020517"+ "updated": "20261015225720"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20260804170000-qss2syl",- "updated": "20260804180000"+ "updated": "20261015225720"},"Children": [{@@ -38,6 +38,38 @@}]},+ {+ "ID": "20261015225720-okoj5kh",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261015225720-okoj5kh",+ "updated": "20261015225720"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "To use a ChatGPT account, open its provider configuration in "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Settings"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "AI"+ },+ {+ "Type": "NodeText",+ "Data": " and select and save an account for this workspace on the current device. Credentials and account bindings stay on this device and are excluded from conf.json and settings exports. Sign in and select an account separately on each device. Copying configuration then preserves the destination device’s bindings for existing providers. Select an account again after adding a provider or moving the workspace directory. After upgrading, select an account once more; existing sign-in credentials are retained."+ }+ ]+ },{"ID": "20260804170002-24z0hpx","Type": "NodeHeading",diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e.syindex 1e2013a454..74d07f9757 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e.sy@@ -6,7 +6,7 @@"id": "20230303235619-ex5l63e","title": "人工智能","type": "doc",- "updated": "20261007020517"+ "updated": "20261015225720"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20260804170000-jvxb09n",- "updated": "20260804180000"+ "updated": "20261015225720"},"Children": [{@@ -38,6 +38,38 @@}]},+ {+ "ID": "20261015225720-x7zbbw0",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261015225720-x7zbbw0",+ "updated": "20261015225720"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "使用 ChatGPT 账号时,在 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "设置"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "AI"+ },+ {+ "Type": "NodeText",+ "Data": " 中打开 ChatGPT 服务商配置,为当前设备的工作空间选择账号并保存。登录凭证和账号绑定保存在本机,不随 conf.json 或设置导出文件保存。每台设备需分别登录并选择一次账号;之后复制配置时,已有服务商仍使用目标设备自己的账号绑定。新增服务商或移动工作空间目录后,需要重新选择账号。升级后也需要重新选择一次,已有登录凭证会保留。"+ }+ ]+ },{"ID": "20260804170002-f53lzwu","Type": "NodeHeading",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po.syindex eb9981741d..f3806d2976 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po.sy@@ -6,7 +6,7 @@"id": "20230304000829-9jwu3po","title": "人工智能","type": "doc",- "updated": "20261007020517"+ "updated": "20261015225720"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20260804170000-wwy3fg7",- "updated": "20260804180000"+ "updated": "20261015225720"},"Children": [{@@ -38,6 +38,38 @@}]},+ {+ "ID": "20261015225720-wuiykps",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261015225720-wuiykps",+ "updated": "20261015225720"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "使用 ChatGPT 帳號時,在 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "設定"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "AI"+ },+ {+ "Type": "NodeText",+ "Data": " 中開啟 ChatGPT 服務商設定,為目前裝置的工作空間選擇帳號並儲存。登入憑證與帳號綁定儲存在本機,不隨 conf.json 或設定匯出檔案儲存。每台裝置需分別登入並選擇一次帳號;之後複製設定時,既有服務商仍使用目標裝置自己的帳號綁定。新增服務商或移動工作空間目錄後,需要重新選擇帳號。升級後也需要重新選擇一次,既有登入憑證會保留。"+ }+ ]+ },{"ID": "20260804170002-ffdgp2j","Type": "NodeHeading",diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt.syindex 2fccc3f26c..c72e3b207c 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt.sy@@ -6,7 +6,7 @@"id": "20240530101000-ei5t6tt","title": "人工知能","type": "doc",- "updated": "20261007020517"+ "updated": "20261015225720"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20260804170000-bsl73zy",- "updated": "20260804180000"+ "updated": "20261015225720"},"Children": [{@@ -38,6 +38,38 @@}]},+ {+ "ID": "20261015225720-y3mi68c",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261015225720-y3mi68c",+ "updated": "20261015225720"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "ChatGPT アカウントを使用するには、"+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "設定"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "AI"+ },+ {+ "Type": "NodeText",+ "Data": " で ChatGPT プロバイダーの設定を開き、この端末のワークスペースで使用するアカウントを選択して保存してください。ログイン認証情報とアカウントの関連付けは端末内に保存され、conf.json や設定のエクスポートファイルには含まれません。各端末で個別にログインし、一度アカウントを選択してください。その後に設定をコピーしても、既存のプロバイダーはコピー先の端末の関連付けを使用します。プロバイダーの追加やワークスペースディレクトリの移動後は、再度アカウントを選択してください。アップグレード後も再選択が必要ですが、既存のログイン認証情報は保持されます。"+ }+ ]+ },{"ID": "20260804170002-b4z0hyu","Type": "NodeHeading",diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 91d746dd3e..f17c813138 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -6681,6 +6681,7 @@ export interface APIPOSTRoutes {/*** 使用共享规范化规则;智能体确认超时负数回退 600 秒,0 保留无限等待语义。* 工具调用轮数和输出 token 上限的负数归零;温度超出 0–2 回退 1。+ * ChatGPT 账户绑定变化时与主配置一起可恢复提交,失败时回滚且不发布新配置;未变化时不访问绑定存储。*/"/api/setting/setAI": {request: SetAIRequestInput;@@ -7475,6 +7476,7 @@ export interface APIPOSTRoutes {};/*** 导入前按启动和设置接口的相同规则规范化编辑器、导出、文档树、搜索和闪卡偏好,并同步保存。+ * ChatGPT 账户引用从本机工作空间绑定加载,忽略导入文件中的引用;本机绑定读取失败时中止导入。*/"/api/system/importConf": {request: SystemImportConfRequestInput;diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.tsindex a6f9f4ea22..54e4f26a2b 100644--- a/app/src/types/config.d.ts+++ b/app/src/types/config.d.ts@@ -255,6 +255,7 @@ declare namespace Config {export interface IProvider {/** 账户认证只保存本机账户引用;省略时使用 API Key */authType?: string;+ /** 本机按工作空间路径和服务商 ID 保存的账号绑定,不随 conf.json 或设置导出保存 */accountID?: string;headers?: Record<string, string>;id: string;diff --git a/kernel/api/chatgpt_binding_test.go b/kernel/api/chatgpt_binding_test.gonew file mode 100644index 0000000000..9614656755--- /dev/null+++ b/kernel/api/chatgpt_binding_test.go@@ -0,0 +1,116 @@+package api++import (+ "bytes"+ "context"+ "encoding/json"+ "mime/multipart"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAPIContractChatGPTLocalBindingsAndConfTransfer(t *testing.T) {+ aiContractConfiguration(t)+ home, workspace, confDir, temp, readOnly := util.HomeDir, util.WorkspaceDir, util.ConfDir, util.TempDir, util.ReadOnly+ t.Cleanup(func() {+ util.HomeDir, util.WorkspaceDir, util.ConfDir, util.TempDir, util.ReadOnly = home, workspace, confDir, temp, readOnly+ })+ util.HomeDir, util.WorkspaceDir, util.ConfDir, util.TempDir, util.ReadOnly = t.TempDir(), t.TempDir(), t.TempDir(), t.TempDir(), false+ model.NormalizeAppConf(model.Conf)+ const providerID = "20261015120000-prov001"+ payload := `{"providers":[{"id":"20261015120000-prov001","authType":"chatgpt","accountID":"local-account"}]}`+ code, message, data := settingContractRequest(t, "setAI", setAI, payload)+ if code != 0 {+ t.Fatal(message)+ }+ var saved apicontract.SettingAI+ if err := json.Unmarshal(data, &saved); err != nil || saved.Providers[0].AccountID != "local-account" {+ t.Fatalf("response did not retain local selection: %s", data)+ }+ bindings, err := util.ChatGPTService().LoadBindings(util.WorkspaceDir)+ if err != nil || bindings[providerID] != "local-account" {+ t.Fatalf("binding not saved: %v %v", bindings, err)+ }+ persisted, err := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))+ if err != nil || bytes.Contains(persisted, []byte("accountID")) {+ t.Fatal("workspace configuration retained a local binding")+ }+ recorder := systemContractRequest(t, http.MethodPost, "exportConf", exportConf, nil)+ var exported struct {+ Code int `json:"code"`+ Data apicontract.SystemExportConfData `json:"data"`+ }+ if err = json.Unmarshal(recorder.Body.Bytes(), &exported); err != nil || exported.Code != 0 {+ t.Fatalf("export failed: %s", recorder.Body.String())+ }+ configuration, err := os.ReadFile(filepath.Join(util.TempDir, "export", exported.Data.Name))+ if err != nil || bytes.Contains(configuration, []byte("accountID")) || model.Conf.AI.Load().Providers[0].AccountID != "local-account" {+ t.Fatal("export leaked or changed a local binding")+ }+ for _, imported := range []string{string(configuration), `{"ai":{"providers":[{"id":"20261015120000-prov001","authType":"chatgpt","accountID":"foreign-account"},{"id":"20261015120000-prov002","authType":"chatgpt","accountID":"foreign-account"}]}}`} {+ var body bytes.Buffer+ writer := multipart.NewWriter(&body)+ part, err := writer.CreateFormFile("file", "settings.json")+ if err != nil {+ t.Fatal(err)+ }+ if _, err = part.Write([]byte(imported)); err != nil {+ t.Fatal(err)+ }+ if err = writer.Close(); err != nil {+ t.Fatal(err)+ }+ response := httptest.NewRecorder()+ c, _ := gin.CreateTestContext(response)+ c.Request = httptest.NewRequest(http.MethodPost, "/api/system/importConf", &body)+ c.Request.Header.Set("Content-Type", writer.FormDataContentType())+ importConf(c)+ requireAPIContract(t, "POST", "/api/system/importConf", response)+ var result struct {+ Code int `json:"code"`+ }+ if err = json.Unmarshal(response.Body.Bytes(), &result); err != nil || result.Code != 0 {+ t.Fatalf("import failed: %s", response.Body.String())+ }+ for _, provider := range model.Conf.AI.Load().Providers {+ want := ""+ if provider.ID == providerID {+ want = "local-account"+ }+ if provider.AccountID != want {+ t.Fatalf("import replaced local binding: %+v", provider)+ }+ }+ }+ code, message, _ = settingContractRequest(t, "setAI", setAI, `{"providers":[]}`)+ if code != 0 {+ t.Fatal(message)+ }+ bindings, err = util.ChatGPTService().LoadBindings(util.WorkspaceDir)+ if err != nil || len(bindings) != 0 {+ t.Fatal("removed providers retained their bindings")+ }+ if err = util.ChatGPTService().SaveBindings(context.Background(), util.WorkspaceDir, map[string]string{providerID: "local-account"}); err != nil {+ t.Fatal(err)+ }+ files, _ := filepath.Glob(filepath.Join(util.HomeDir, ".config", "siyuan", "chatgpt", "bindings", "*.json"))+ if len(files) != 1 {+ t.Fatalf("unexpected binding files: %v", files)+ }+ if err = os.WriteFile(files[0], []byte("damaged"), 0600); err != nil {+ t.Fatal(err)+ }+ before := model.Conf.AI.Load()+ code, _, _ = settingContractRequest(t, "setAI", setAI, payload)+ if code != -1 || model.Conf.AI.Load() != before {+ t.Fatal("failed binding write published configuration")+ }+}diff --git a/kernel/api/setting.go b/kernel/api/setting.goindex d5470a9d34..85d57970be 100644--- a/kernel/api/setting.go+++ b/kernel/api/setting.go@@ -179,7 +179,9 @@ func applyAISetting(c *gin.Context, request apicontract.SetAIRequest) (ret apicopreserveMCPServerIDs(oldServers, ai.MCP.Servers)}ai = conf.NormalizeAI(ai)- model.Conf.SetAI(ai)+ if err = model.Conf.SetAI(c.Request.Context(), ai); err != nil {+ return apicontract.Failure[*apicontract.SettingAI](-1, err.Error())+ }mcpserver.RefreshToolExposure()// MCP 配置可能变更(开关切换、编辑、增删 server),异步重连让连接立即跟上。diff --git a/kernel/api/system.go b/kernel/api/system.goindex 3ab7481d23..0b37397b0a 100644--- a/kernel/api/system.go+++ b/kernel/api/system.go@@ -470,6 +470,9 @@ var exportConf = contractHandler(apicontract.SystemExportConf, func(c *gin.Conte}clonedConf.Appearance.Load().GlobalFontFamilies = fonts}+ if clonedConf.AI.Load() != nil {+ clonedConf.AI.Load().ClearChatGPTAccountIDs()+ }if nil != clonedConf.Editor.Load() {clonedConf.Editor.Load().Emoji = []string{}fonts := make([]*conf.EditorFont, 0, len(clonedConf.Editor.Load().FontFamilies))@@ -695,6 +698,9 @@ var importConf = contractHandler(apicontract.SystemImportConf, func(c *gin.Conte}model.NormalizeAppConf(importedConf)+ if err = model.LoadChatGPTAccountBindings(importedConf.AI.Load()); err != nil {+ return apicontract.Failure[apicontract.Null](-1, err.Error())+ }model.Conf.FileTree.Store(importedConf.FileTree.Load())model.Conf.Tag.Store(importedConf.Tag.Load())model.Conf.Editor.Store(importedConf.Editor.Load())diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex 147befd3c1..5a298a56e3 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -1100,6 +1100,7 @@ var SetBazaar = define[SetBazaarRequest, *SettingBazaar]("setBazaar", "/api/sett// SetAI 使用共享规范化规则;智能体确认超时负数回退 600 秒,0 保留无限等待语义。// 工具调用轮数和输出 token 上限的负数归零;温度超出 0–2 回退 1。+// 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")@@ -1383,6 +1384,7 @@ var SystemGetSysFonts = define[EmptyRequest, []*SystemFont]("getSysFonts", "/apivar SystemGetWorkspaces = define[EmptyRequest, []*SystemWorkspace]("getWorkspaces", "/api/system/getWorkspaces", AuthenticatedAccess, NoBody, ResponseOptions{}, "POST")// SystemImportConf 导入前按启动和设置接口的相同规则规范化编辑器、导出、文档树、搜索和闪卡偏好,并同步保存。+// ChatGPT 账户引用从本机工作空间绑定加载,忽略导入文件中的引用;本机绑定读取失败时中止导入。var SystemImportConf = define[SystemImportConfRequest, Null]("importConf", "/api/system/importConf", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{Setting: SettingWrite{Namespace: "*"}}, "POST")var SystemImportCustomFont = define[SystemImportFileRequest, *SystemCustomFont]("importCustomFont", "/api/system/importCustomFont", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{AdditionalCodes: []int{400, 413}}, "POST")var SystemImportTLSCABundle = define[SystemImportFileRequest, SystemMessageData]("importTLSCABundle", "/api/system/importTLSCABundle", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{}, "POST")diff --git a/kernel/apicontract/setting.go b/kernel/apicontract/setting.goindex 7b12e19fe6..6430be1077 100644--- a/kernel/apicontract/setting.go+++ b/kernel/apicontract/setting.go@@ -132,7 +132,9 @@ type SettingImageGeneration struct {type SettingProvider struct {// 套餐认证固定使用公开 Responses API;账户引用不包含令牌,省略时保留 API Key 认证。- AuthType string `json:"authType,omitempty" api:"optional,nullable"`+ AuthType string `json:"authType,omitempty" api:"optional,nullable"`+ // AccountID 读写本机按工作空间路径和服务商 ID 保存的绑定,不随 conf.json 或设置导出保存。+ // 清空或省略时解除该服务商的本机绑定;旧配置中的账户引用不迁移,各设备需重新选择。AccountID string `json:"accountID,omitempty" api:"optional,nullable"`Headers map[string]string `json:"headers,omitempty" api:"optional,nullable"`ID string `json:"id" api:"optional,nullable"`diff --git a/kernel/apicontract/system.go b/kernel/apicontract/system.goindex 953d97dd59..5a87d6adaf 100644--- a/kernel/apicontract/system.go+++ b/kernel/apicontract/system.go@@ -32,7 +32,7 @@ type SystemZipData struct {Zip string `json:"zip"`}-// SystemExportConfData 返回设置导出文件名和压缩包路径。导出副本清空 AI 密钥(含决策模型)和 OIDC 客户端密钥,+// SystemExportConfData 返回设置导出文件名和压缩包路径。导出副本清空 ChatGPT 本机账户引用、AI 密钥和 OIDC 客户端密钥,// 不修改当前工作空间配置;导出的设置文件不包含笔记本加密密钥及恢复材料。type SystemExportConfData struct {Name string `json:"name"`diff --git a/kernel/chatgpt/bindings.go b/kernel/chatgpt/bindings.gonew file mode 100644index 0000000000..811af5da09--- /dev/null+++ b/kernel/chatgpt/bindings.go@@ -0,0 +1,107 @@+package chatgpt++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "time"++ "github.com/gofrs/flock"+)++type accountBindings struct {+ Version int `json:"version"`+ Providers map[string]string `json:"providers"`+}++// BindingPath 返回按本机工作空间路径隔离的绑定文件,供主配置与绑定的可恢复提交使用。+func (s *Service) BindingPath(workspace string) (string, error) {+ if workspace == "" {+ return "", errors.New("ChatGPT account binding requires a workspace")+ }+ path, err := filepath.Abs(workspace)+ if err != nil {+ return "", err+ }+ if resolved, resolveErr := filepath.EvalSymlinks(path); resolveErr == nil {+ path = resolved+ }+ if runtime.GOOS == "windows" {+ path = strings.ToLower(path)+ }+ digest := sha256.Sum256([]byte(filepath.Clean(path)))+ return filepath.Join(s.dir, "bindings", hex.EncodeToString(digest[:])+".json"), nil+}++func readAccountBindings(path string) (map[string]string, error) {+ data, err := os.ReadFile(path)+ if os.IsNotExist(err) {+ return map[string]string{}, nil+ }+ if err != nil {+ return nil, err+ }+ var saved accountBindings+ if err = json.Unmarshal(data, &saved); err != nil {+ return nil, err+ }+ if saved.Version != 1 || saved.Providers == nil {+ return nil, errors.New("unsupported ChatGPT account binding format")+ }+ return saved.Providers, nil+}++// LoadBindings 读取原子写入的本机绑定,不加载或刷新登录凭证。+func (s *Service) LoadBindings(workspace string) (map[string]string, error) {+ path, err := s.BindingPath(workspace)+ if err != nil {+ return nil, err+ }+ return readAccountBindings(path)+}++// SaveBindings 在进程间加锁后替换当前工作空间的绑定;损坏或未知格式保留原文件并报错。+func (s *Service) SaveBindings(ctx context.Context, workspace string, providers map[string]string) error {+ return s.UpdateBindings(ctx, workspace, providers, atomicWrite)+}++// UpdateBindings 在绑定锁内校验原文件,将写入交给调用方协调主配置提交;回调返回前不释放锁。+func (s *Service) UpdateBindings(ctx context.Context, workspace string, providers map[string]string,+ persist func(string, []byte) error) error {+ path, err := s.BindingPath(workspace)+ if err != nil {+ return err+ }+ if err = os.MkdirAll(filepath.Dir(path), 0700); err != nil {+ return err+ }+ lock := flock.New(path + ".lock")+ locked, err := lock.TryLockContext(ctx, 50*time.Millisecond)+ if err != nil {+ return err+ }+ if !locked {+ return ctx.Err()+ }+ defer lock.Unlock()+ if _, err = readAccountBindings(path); err != nil {+ return err+ }+ if err = ctx.Err(); err != nil {+ return err+ }+ if providers == nil {+ providers = map[string]string{}+ }+ data, err := json.Marshal(accountBindings{Version: 1, Providers: providers})+ if err != nil {+ return err+ }+ return persist(path, data)+}diff --git a/kernel/chatgpt/bindings_test.go b/kernel/chatgpt/bindings_test.gonew file mode 100644index 0000000000..c90433b3c7--- /dev/null+++ b/kernel/chatgpt/bindings_test.go@@ -0,0 +1,97 @@+package chatgpt++import (+ "context"+ "os"+ "path/filepath"+ "reflect"+ "testing"+)++func TestChatGPTBindingsDeviceWorkspaceAndProviderIsolation(t *testing.T) {+ ctx := context.Background()+ workspace, otherWorkspace := t.TempDir(), t.TempDir()+ first, second := Open(t.TempDir()), Open(t.TempDir())+ want := map[string]string{"provider-one": "account-one", "provider-two": "account-two"}+ if err := first.SaveBindings(ctx, workspace, want); err != nil {+ t.Fatal(err)+ }+ if err := first.SaveBindings(ctx, otherWorkspace, map[string]string{"provider-one": "other-workspace"}); err != nil {+ t.Fatal(err)+ }+ if err := second.SaveBindings(ctx, workspace, map[string]string{"provider-one": "other-device"}); err != nil {+ t.Fatal(err)+ }+ for _, entry := range []struct {+ service *Service+ path string+ want map[string]string+ }{+ {Open(first.dir), workspace, want},+ {first, otherWorkspace, map[string]string{"provider-one": "other-workspace"}},+ {second, workspace, map[string]string{"provider-one": "other-device"}},+ } {+ got, err := entry.service.LoadBindings(entry.path)+ if err != nil || !reflect.DeepEqual(got, entry.want) {+ t.Fatalf("bindings = %v, want %v: %v", got, entry.want, err)+ }+ }+ if err := first.SaveBindings(ctx, workspace, map[string]string{"provider-one": "changed-account"}); err != nil {+ t.Fatal(err)+ }+ got, _ := first.LoadBindings(workspace)+ if len(got) != 1 || got["provider-one"] != "changed-account" {+ t.Fatal("removed provider or changed selection was not persisted")+ }+ if err := first.SaveBindings(ctx, workspace, nil); err != nil {+ t.Fatal(err)+ }+ got, err := first.LoadBindings(workspace)+ if err != nil || len(got) != 0 {+ t.Fatal("cleared bindings restored a previous selection")+ }+ for _, name := range []string{"accounts", "key"} {+ if _, err = os.Stat(filepath.Join(first.dir, name)); !os.IsNotExist(err) {+ t.Fatal("binding storage accessed credential files")+ }+ }+}++func TestChatGPTBindingsPreserveInvalidFilesAndCancelledWrites(t *testing.T) {+ s, workspace := Open(t.TempDir()), t.TempDir()+ if _, err := s.LoadBindings(workspace); err != nil {+ t.Fatal(err)+ }+ path, _ := s.BindingPath(workspace)+ if _, err := os.Stat(filepath.Dir(path)); !os.IsNotExist(err) {+ t.Fatal("reading missing bindings created files")+ }+ want := map[string]string{"provider": "account"}+ if err := s.SaveBindings(context.Background(), workspace, want); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ if err := s.SaveBindings(ctx, workspace, map[string]string{"provider": "replacement"}); err == nil {+ t.Fatal("cancelled write succeeded")+ }+ got, _ := s.LoadBindings(workspace)+ if !reflect.DeepEqual(got, want) {+ t.Fatal("cancelled write replaced bindings")+ }+ for _, raw := range []string{`{broken`, `{"version":2,"providers":{}}`, `{"version":1,"providers":null}`} {+ if err := os.WriteFile(path, []byte(raw), 0600); err != nil {+ t.Fatal(err)+ }+ if _, err := s.LoadBindings(workspace); err == nil {+ t.Fatal("invalid binding file accepted")+ }+ if err := s.SaveBindings(context.Background(), workspace, want); err == nil {+ t.Fatal("invalid binding file overwritten")+ }+ data, _ := os.ReadFile(path)+ if string(data) != raw {+ t.Fatal("invalid binding file was modified")+ }+ }+}diff --git a/kernel/conf/ai.go b/kernel/conf/ai.goindex fd95347170..2bbedbe384 100644--- a/kernel/conf/ai.go+++ b/kernel/conf/ai.go@@ -267,7 +267,8 @@ type Rerank struct {}type Provider struct {- AuthType string `json:"authType,omitempty"`+ AuthType string `json:"authType,omitempty"`+ // AccountID 是本机绑定的运行时投影;工作空间配置持久化和设置导出时排除。AccountID string `json:"accountID,omitempty"`Headers map[string]string `json:"headers,omitempty"`ID string `json:"id"`@@ -280,6 +281,15 @@ type Provider struct {Models []*Model `json:"models"`}+// ClearChatGPTAccountIDs 清除可复制配置中的本机账户引用,不修改登录凭证。+func (ai *AI) ClearChatGPTAccountIDs() {+ for _, provider := range ai.Providers {+ if provider != nil {+ provider.AccountID = ""+ }+ }+}+// Model is the provider-scoped model registry entry. MaxTokens/Temperature/// MaxContexts remain the persisted UI-facing config (the settings page still// reads/writes them). Editing holds the runtime view derived from them.diff --git a/kernel/model/chatgpt.go b/kernel/model/chatgpt.gonew file mode 100644index 0000000000..ff9b3bb0bb--- /dev/null+++ b/kernel/model/chatgpt.go@@ -0,0 +1,178 @@+package model++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "time"++ "github.com/88250/gulu"+ "github.com/gofrs/flock"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func chatGPTAccountBindingIDs(ai *conf.AI) map[string]string {+ bindings := map[string]string{}+ if ai != nil {+ for _, provider := range ai.Providers {+ if provider != nil && provider.AuthType == "chatgpt" && provider.AccountID != "" {+ bindings[provider.ID] = provider.AccountID+ }+ }+ }+ return bindings+}++type chatGPTBindingFile struct {+ Exists bool `json:"exists"`+ Data []byte `json:"data"`+}++type chatGPTBindingJournal struct {+ Version int `json:"version"`+ Files []chatGPTBindingFile `json:"files"`+}++func writeChatGPTBindingFile(path string, data []byte) error {+ return gulu.File.WriteFileSafer(path, data, 0600)+}++// writeChatGPTBindingConfiguration 在本机保存回滚日志,主配置字节保持原有凭据加密形式。+func writeChatGPTBindingConfiguration(bindingPath string, bindingData, configData []byte,+ write func(string, []byte) error) error {+ if err := recoverChatGPTBindingConfiguration(bindingPath); err != nil {+ return err+ }+ paths := []string{filepath.Join(util.ConfDir, "conf.json"), bindingPath}+ journal := chatGPTBindingJournal{Version: 1}+ for _, path := range paths {+ data, err := os.ReadFile(path)+ if err != nil && !os.IsNotExist(err) {+ return err+ }+ if err == nil && !json.Valid(data) {+ return errors.New("invalid ChatGPT binding configuration file")+ }+ journal.Files = append(journal.Files, chatGPTBindingFile{Exists: err == nil, Data: data})+ }+ data, err := json.Marshal(journal)+ if err != nil {+ return err+ }+ journalPath := bindingPath + ".pending"+ if err = writeChatGPTBindingFile(journalPath, data); err != nil {+ return err+ }+ rollback := func(cause error) error {+ if recoveryErr := recoverChatGPTBindingConfiguration(bindingPath); recoveryErr != nil {+ // 停止后续保存,保留日志供下次启动恢复,避免回滚覆盖稍后的配置。+ util.ReportFileSysFatalError(errors.Join(cause, recoveryErr))+ }+ return cause+ }+ for i, next := range [][]byte{configData, bindingData} {+ if err = write(paths[i], next); err != nil {+ return rollback(err)+ }+ }+ if err = os.Remove(journalPath); err != nil {+ return rollback(err)+ }+ return nil+}++// recoverChatGPTBindingConfiguration 只恢复两个固定路径;未知或损坏日志原样保留并报错。+func recoverChatGPTBindingConfiguration(bindingPath string) error {+ journalPath := bindingPath + ".pending"+ data, err := os.ReadFile(journalPath)+ if os.IsNotExist(err) {+ return nil+ }+ if err != nil {+ return err+ }+ var journal chatGPTBindingJournal+ if err = json.Unmarshal(data, &journal); err != nil {+ return err+ }+ if journal.Version != 1 || len(journal.Files) != 2 {+ return errors.New("unsupported ChatGPT binding journal")+ }+ for _, original := range journal.Files {+ if original.Exists && !json.Valid(original.Data) || !original.Exists && len(original.Data) != 0 {+ return errors.New("invalid ChatGPT binding journal data")+ }+ }+ paths := []string{filepath.Join(util.ConfDir, "conf.json"), bindingPath}+ for i, original := range journal.Files {+ if original.Exists {+ err = writeChatGPTBindingFile(paths[i], original.Data)+ } else {+ err = os.Remove(paths[i])+ if os.IsNotExist(err) {+ err = nil+ }+ }+ if err != nil {+ return fmt.Errorf("restore ChatGPT binding configuration: %w", err)+ }+ }+ return os.Remove(journalPath)+}++// recoverChatGPTAccountBindings 在主配置加载前回滚中断的保存;没有日志时不创建本机文件。+func recoverChatGPTAccountBindings() error {+ path, err := util.ChatGPTService().BindingPath(util.WorkspaceDir)+ if err != nil {+ return err+ }+ if _, err = os.Stat(path + ".pending"); os.IsNotExist(err) {+ return nil+ } else if err != nil {+ return err+ }+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ lock := flock.New(path + ".lock")+ locked, err := lock.TryLockContext(ctx, 50*time.Millisecond)+ if err != nil {+ return err+ }+ if !locked {+ return ctx.Err()+ }+ defer lock.Unlock()+ return recoverChatGPTBindingConfiguration(path)+}++// LoadChatGPTAccountBindings 用当前设备的工作空间绑定替换配置携带的账户引用,不迁移旧引用。+func LoadChatGPTAccountBindings(ai *conf.AI) error {+ if ai == nil {+ return nil+ }+ ai.ClearChatGPTAccountIDs()+ hasChatGPT := false+ for _, provider := range ai.Providers {+ if provider != nil && provider.AuthType == "chatgpt" {+ hasChatGPT = true+ break+ }+ }+ if !hasChatGPT {+ return nil+ }+ bindings, err := util.ChatGPTService().LoadBindings(util.WorkspaceDir)+ if err != nil {+ return err+ }+ for _, provider := range ai.Providers {+ if provider != nil && provider.AuthType == "chatgpt" {+ provider.AccountID = bindings[provider.ID]+ }+ }+ return nil+}diff --git a/kernel/model/chatgpt_test.go b/kernel/model/chatgpt_test.gonew file mode 100644index 0000000000..0c7129fbb9--- /dev/null+++ b/kernel/model/chatgpt_test.go@@ -0,0 +1,280 @@+package model++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "os"+ "os/exec"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func chatGPTBindingTestEnvironment(t *testing.T) {+ t.Helper()+ home, workspace, dir, readOnly := util.HomeDir, util.WorkspaceDir, util.ConfDir, util.ReadOnly+ persisted := lastPersistedConf()+ t.Cleanup(func() {+ util.HomeDir, util.WorkspaceDir, util.ConfDir, util.ReadOnly = home, workspace, dir, readOnly+ recordPersistedConf(persisted)+ })+ util.HomeDir, util.WorkspaceDir, util.ConfDir, util.ReadOnly = t.TempDir(), t.TempDir(), t.TempDir(), false+}++func TestChatGPTBindingsSurviveCopiedConfiguration(t *testing.T) {+ previousHome, previousWorkspace := util.HomeDir, util.WorkspaceDir+ defer func() { util.HomeDir, util.WorkspaceDir = previousHome, previousWorkspace }()+ util.WorkspaceDir = t.TempDir()+ deviceA, deviceB := t.TempDir(), t.TempDir()+ provider := func(id string) *conf.AI {+ return &conf.AI{Providers: []*conf.Provider{{ID: "provider", AuthType: "chatgpt", AccountID: id}}}+ }+ for _, entry := range []struct{ home, account string }{{deviceA, "account-A"}, {deviceB, "account-B"}} {+ util.HomeDir = entry.home+ if err := util.ChatGPTService().SaveBindings(context.Background(), util.WorkspaceDir, map[string]string{"provider": entry.account}); err != nil {+ t.Fatal(err)+ }+ }+ source := NewAppConf()+ source.AI.Store(provider("account-A"))+ data, err := source.marshalForSave()+ if err != nil || bytes.Contains(data, []byte("accountID")) || source.AI.Load().Providers[0].AccountID != "account-A" {+ t.Fatalf("persisted configuration leaked or changed binding: %v", err)+ }+ for _, entry := range []struct{ home, account string }{{deviceA, "account-A"}, {deviceB, "account-B"}, {t.TempDir(), ""}} {+ util.HomeDir = entry.home+ copied := NewAppConf()+ if err = json.Unmarshal(data, copied); err != nil {+ t.Fatal(err)+ }+ // 模拟外部配置携带其他设备的引用,加载时只认当前设备的绑定。+ copied.AI.Load().Providers[0].AccountID = "foreign-account"+ if err = LoadChatGPTAccountBindings(copied.AI.Load()); err != nil {+ t.Fatal(err)+ }+ if got := copied.AI.Load().Providers[0].AccountID; got != entry.account {+ t.Fatalf("loaded account %q, want %q", got, entry.account)+ }+ }+ util.HomeDir = deviceB+ util.WorkspaceDir = t.TempDir()+ ai := provider("foreign-account")+ if err = LoadChatGPTAccountBindings(ai); err != nil || ai.Providers[0].AccountID != "" {+ t.Fatal("another workspace inherited an account binding")+ }+}++func TestChatGPTBindingSaveFailureRetainsRuntimeConfiguration(t *testing.T) {+ previousHome, previousWorkspace, previousDir, previousReadOnly := util.HomeDir, util.WorkspaceDir, util.ConfDir, util.ReadOnly+ defer func() {+ util.HomeDir, util.WorkspaceDir, util.ConfDir, util.ReadOnly = previousHome, previousWorkspace, previousDir, previousReadOnly+ }()+ util.HomeDir, util.WorkspaceDir, util.ConfDir, util.ReadOnly = t.TempDir(), t.TempDir(), t.TempDir(), false+ app := NewAppConf()+ ai := &conf.AI{Providers: []*conf.Provider{{ID: "provider", AuthType: "chatgpt", AccountID: "local-account"}}}+ if err := app.SetAI(context.Background(), ai); err != nil {+ t.Fatal(err)+ }+ data, err := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))+ if err != nil || bytes.Contains(data, []byte("accountID")) {+ t.Fatal("saved configuration retained the account binding")+ }+ dir := filepath.Join(util.HomeDir, ".config", "siyuan", "chatgpt", "bindings")+ files, _ := filepath.Glob(filepath.Join(dir, "*.json"))+ if len(files) != 1 {+ t.Fatalf("unexpected binding files: %v", files)+ }+ if err = os.WriteFile(files[0], []byte("damaged"), 0600); err != nil {+ t.Fatal(err)+ }+ if err = app.SetAI(context.Background(), &conf.AI{}); err == nil || app.AI.Load().Providers[0].AccountID != "local-account" {+ t.Fatal("failed binding save published a new configuration")+ }+ if err = LoadChatGPTAccountBindings(ai); err == nil || ai.Providers[0].AccountID != "" {+ t.Fatal("failed binding load retained a foreign account reference")+ }+}++func TestChatGPTUnchangedBindingsDoNotAccessLocalStore(t *testing.T) {+ chatGPTBindingTestEnvironment(t)+ app := NewAppConf()+ parent := filepath.Join(util.HomeDir, ".config", "siyuan")+ if err := os.MkdirAll(parent, 0700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(parent, "chatgpt"), []byte("unavailable store"), 0600); err != nil {+ t.Fatal(err)+ }+ if err := app.SetAI(context.Background(), &conf.AI{Providers: []*conf.Provider{{APIKey: "ordinary-provider"}}}); err != nil {+ t.Fatalf("API key provider depends on ChatGPT storage: %v", err)+ }+ app.AI.Store(&conf.AI{Providers: []*conf.Provider{{ID: "provider", AuthType: "chatgpt", AccountID: "local-account"}}})+ next := cloneConfSection(app.AI.Load())+ next.Providers[0].Enabled = true+ if err := app.SetAI(context.Background(), next); err != nil || !app.AI.Load().Providers[0].Enabled {+ t.Fatalf("unchanged ChatGPT binding accessed local storage: %v", err)+ }+}++func TestChatGPTConfigurationFailureRetainsBindings(t *testing.T) {+ chatGPTBindingTestEnvironment(t)+ app := NewAppConf()+ ai := &conf.AI{Providers: []*conf.Provider{{ID: "provider", AuthType: "chatgpt", AccountID: "local-account"}}}+ if err := app.SetAI(context.Background(), ai); err != nil {+ t.Fatal(err)+ }+ originalDir := util.ConfDir+ original, err := os.ReadFile(filepath.Join(originalDir, "conf.json"))+ if err != nil {+ t.Fatal(err)+ }+ util.ConfDir = filepath.Join(t.TempDir(), "blocked")+ if err = os.WriteFile(util.ConfDir, []byte("not a directory"), 0600); err != nil {+ t.Fatal(err)+ }+ if err = app.SetAI(context.Background(), &conf.AI{}); err == nil {+ t.Fatal("configuration failure accepted")+ }+ bindings, err := util.ChatGPTService().LoadBindings(util.WorkspaceDir)+ if err != nil || bindings["provider"] != "local-account" || app.AI.Load() != ai {+ t.Fatal("configuration failure changed persisted or runtime bindings")+ }+ current, err := os.ReadFile(filepath.Join(originalDir, "conf.json"))+ if err != nil || !bytes.Equal(current, original) {+ t.Fatal("configuration failure changed original configuration")+ }+}++func prepareChatGPTBindingTransaction(t *testing.T) (string, [][]byte) {+ t.Helper()+ path, err := util.ChatGPTService().BindingPath(util.WorkspaceDir)+ if err != nil {+ t.Fatal(err)+ }+ if err = os.MkdirAll(filepath.Dir(path), 0700); err != nil {+ t.Fatal(err)+ }+ if err = os.MkdirAll(util.ConfDir, 0700); err != nil {+ t.Fatal(err)+ }+ before := [][]byte{[]byte(`{"ai":{"providers":[{"id":"provider"}]}}`), []byte(`{"version":1,"providers":{"provider":"account"}}`)}+ for i, file := range []string{filepath.Join(util.ConfDir, "conf.json"), path} {+ if err = writeChatGPTBindingFile(file, before[i]); err != nil {+ t.Fatal(err)+ }+ }+ return path, before+}++func assertChatGPTBindingTransactionRestored(t *testing.T, path string, before [][]byte) {+ t.Helper()+ for i, file := range []string{filepath.Join(util.ConfDir, "conf.json"), path} {+ data, err := os.ReadFile(file)+ if err != nil || !bytes.Equal(data, before[i]) {+ t.Fatalf("transaction file %d was not restored: %v", i, err)+ }+ }+ if _, err := os.Stat(path + ".pending"); !os.IsNotExist(err) {+ t.Fatal("successful rollback retained a journal")+ }+}++func TestChatGPTBindingTransactionRollsBackEachWriteFailure(t *testing.T) {+ for _, failAt := range []int{0, 1} {+ t.Run(string(rune('0'+failAt)), func(t *testing.T) {+ chatGPTBindingTestEnvironment(t)+ path, before := prepareChatGPTBindingTransaction(t)+ writes := 0+ err := writeChatGPTBindingConfiguration(path, []byte(`{"version":1,"providers":{}}`), []byte(`{"ai":{}}`), func(file string, data []byte) error {+ index := writes+ writes+++ if index == failAt {+ return errors.New("injected write failure")+ }+ return writeChatGPTBindingFile(file, data)+ })+ if err == nil {+ t.Fatal("failed transaction accepted")+ }+ assertChatGPTBindingTransactionRestored(t, path, before)+ })+ }+}++func TestChatGPTBindingInterruptedSaveRecovery(t *testing.T) {+ const rootEnv, stepEnv = "SIYUAN_CHATGPT_RECOVERY_ROOT", "SIYUAN_CHATGPT_RECOVERY_STEP"+ if root := os.Getenv(rootEnv); root != "" {+ util.HomeDir, util.WorkspaceDir = filepath.Join(root, "home"), filepath.Join(root, "workspace")+ util.ConfDir = filepath.Join(util.WorkspaceDir, "conf")+ path, _ := util.ChatGPTService().BindingPath(util.WorkspaceDir)+ index := 0+ _ = writeChatGPTBindingConfiguration(path, []byte(`{"version":1,"providers":{}}`), []byte(`{"ai":{}}`), func(file string, data []byte) error {+ if err := writeChatGPTBindingFile(file, data); err != nil {+ return err+ }+ if string(rune('0'+index)) == os.Getenv(stepEnv) {+ os.Exit(0)+ }+ index+++ return nil+ })+ t.Fatal("interruption was not reached")+ }+ for _, step := range []string{"0", "1"} {+ t.Run(step, func(t *testing.T) {+ chatGPTBindingTestEnvironment(t)+ root := t.TempDir()+ util.HomeDir, util.WorkspaceDir = filepath.Join(root, "home"), filepath.Join(root, "workspace")+ util.ConfDir = filepath.Join(util.WorkspaceDir, "conf")+ path, before := prepareChatGPTBindingTransaction(t)+ command := exec.Command(os.Args[0], "-test.run=^TestChatGPTBindingInterruptedSaveRecovery$")+ command.Env = append(os.Environ(), rootEnv+"="+root, stepEnv+"="+step)+ if output, err := command.CombinedOutput(); err != nil {+ t.Fatalf("interrupted process failed: %v %s", err, output)+ }+ if _, err := os.Stat(path + ".pending"); err != nil {+ t.Fatal("interrupted save lost the recovery journal")+ }+ if err := recoverChatGPTAccountBindings(); err != nil {+ t.Fatal(err)+ }+ assertChatGPTBindingTransactionRestored(t, path, before)+ if err := writeChatGPTBindingFile(filepath.Join(util.ConfDir, "conf.json"), []byte(`{"later":true}`)); err != nil {+ t.Fatal(err)+ }+ if err := recoverChatGPTAccountBindings(); err != nil {+ t.Fatal(err)+ }+ data, _ := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))+ if string(data) != `{"later":true}` {+ t.Fatal("completed recovery reverted a later save")+ }+ })+ }+}++func TestChatGPTBindingUnknownJournalPreservesFiles(t *testing.T) {+ chatGPTBindingTestEnvironment(t)+ path, before := prepareChatGPTBindingTransaction(t)+ raw := []byte(`{"version":2,"files":[]}`)+ if err := os.WriteFile(path+".pending", raw, 0600); err != nil {+ t.Fatal(err)+ }+ if err := recoverChatGPTAccountBindings(); err == nil {+ t.Fatal("unknown recovery journal accepted")+ }+ data, _ := os.ReadFile(path + ".pending")+ if !bytes.Equal(data, raw) {+ t.Fatal("unknown journal was modified")+ }+ for i, file := range []string{filepath.Join(util.ConfDir, "conf.json"), path} {+ data, _ = os.ReadFile(file)+ if !bytes.Equal(data, before[i]) {+ t.Fatal("unknown journal changed configuration files")+ }+ }+}diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex fbfbc31e75..75010c8413 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -229,11 +229,32 @@ func (appConf *AppConf) CompareAndSetOIDC(expectedVersion string, config *conf.Oreturn changed, true}-func (conf *AppConf) SetAI(ai *conf.AI) {+func (conf *AppConf) SetAI(ctx context.Context, ai *conf.AI) error {conf.m.Lock()+ defer conf.m.Unlock()+ bindings := chatGPTAccountBindingIDs(ai)+ if reflect.DeepEqual(bindings, chatGPTAccountBindingIDs(conf.AI.Load())) || util.ReadOnly {+ conf.AI.Store(ai)+ if !util.ReadOnly {+ conf.saveLocked()+ }+ return nil+ }+ next := conf.cloneSettings()+ next.AI.Store(ai)+ data, err := next.marshalForSave()+ if err != nil {+ return err+ }+ if err = util.ChatGPTService().UpdateBindings(ctx, util.WorkspaceDir, bindings, func(path string, bindingsData []byte) error {+ return writeChatGPTBindingConfiguration(path, bindingsData, data, writeChatGPTBindingFile)+ }); err != nil {+ return err+ }conf.AI.Store(ai)- conf.m.Unlock()- conf.Save()+ applyConfRuntime(conf)+ recordPersistedConf(data)+ return nil}func (conf *AppConf) SetUILayout(uiLayout *conf.UILayout) {@@ -260,6 +281,10 @@ func InitConf() {logging.LogFatalf(logging.ExitCodeFileSysErr, "recover settings reset failed: %s", err)return}+ if err := recoverChatGPTAccountBindings(); err != nil {+ logging.LogFatalf(logging.ExitCodeFileSysErr, "recover ChatGPT account bindings failed: %s", err)+ return+ }Conf = NewAppConf()// 先回滚未提交的目录移动,即使配置文件丢失也必须在挂载和同步之前恢复。@@ -401,6 +426,9 @@ func InitConf() {}flashcardWarning := normalizeAppConf(Conf)+ if err := LoadChatGPTAccountBindings(Conf.AI.Load()); err != nil {+ logging.LogErrorf("load local ChatGPT account bindings failed: %s", err)+ }if flashcardWarning != "" {logging.LogWarnf("%s, reset to default weights [%s]", flashcardWarning, Conf.Flashcard.Load().Weights)go func() {@@ -989,6 +1017,7 @@ func (conf *AppConf) marshalForSave() ([]byte, error) {return nil, err}if snapshot.AI.Load() != nil {+ snapshot.AI.Load().ClearChatGPTAccountIDs()snapshot.AI.Load().EncryptAPIKeys()}if snapshot.OIDC != nil {