An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Prevent panic when pasting images in Agent chat https://github.com/siyuan-note/siyuan/issues/18973
Danielc89a9b5dadf4
diff --git a/kernel/api/asset.go b/kernel/api/asset.goindex d1cbba0fc8..498144c5cb 100644--- a/kernel/api/asset.go+++ b/kernel/api/asset.go@@ -611,7 +611,7 @@ func insertLocalAssets(c *gin.Context) {if nil != isUploadArg {isUpload = isUploadArg.(bool)}- id := arg["id"].(string)+ id, _ := arg["id"].(string)fromHTMLPaste, _ := arg["fromHTMLPaste"].(bool)var succMap map[string]anyvar succFiles []model.AssetUploadSuccessdiff --git a/kernel/api/asset_authorization_test.go b/kernel/api/asset_authorization_test.goindex 1a132d9c14..f9c405bc7a 100644--- a/kernel/api/asset_authorization_test.go+++ b/kernel/api/asset_authorization_test.go@@ -17,15 +17,71 @@package apiimport (+ "bytes"+ "encoding/json""net/http""net/http/httptest"+ "os"+ "path/filepath""strings""testing""github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util")+func TestInsertLocalAssetsWithoutBlockID(t *testing.T) {+ originalConf, originalWorkspaceDir, originalDataDir := model.Conf, util.WorkspaceDir, util.DataDir+ workspaceDir := t.TempDir()+ util.WorkspaceDir = workspaceDir+ util.DataDir = filepath.Join(workspaceDir, "data")+ model.Conf = model.NewAppConf()+ model.Conf.Sync = conf.NewSync()+ t.Cleanup(func() {+ model.Conf = originalConf+ util.WorkspaceDir = originalWorkspaceDir+ util.DataDir = originalDataDir+ })++ assetPath := filepath.Join(util.DataDir, "assets", "pasted.png")+ if err := os.MkdirAll(filepath.Dir(assetPath), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(assetPath, []byte("image"), 0644); err != nil {+ t.Fatal(err)+ }+ body, err := json.Marshal(map[string]any{+ "assetPaths": []string{assetPath},+ "isUpload": true,+ })+ if err != nil {+ t.Fatal(err)+ }++ recorder := httptest.NewRecorder()+ context, _ := gin.CreateTestContext(recorder)+ request := httptest.NewRequest(http.MethodPost, "/api/asset/insertLocalAssets", bytes.NewReader(body))+ request.Header.Set("Content-Type", "application/json")+ context.Request = request+ insertLocalAssets(context)++ response := struct {+ Code int `json:"code"`+ Data struct {+ SuccFiles []model.AssetUploadSuccess `json:"succFiles"`+ } `json:"data"`+ }{}+ if err = json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ if response.Code != 0 || len(response.Data.SuccFiles) != 1 ||+ response.Data.SuccFiles[0].Path != "assets/pasted.png" {+ t.Fatalf("unexpected insert local assets response: %s", recorder.Body.String())+ }+}+func TestAssetAdminEndpointsRejectReader(t *testing.T) {gin.SetMode(gin.TestMode)diff --git a/kernel/model/upload.go b/kernel/model/upload.goindex 1fb7d10559..fd3844d950 100644--- a/kernel/model/upload.go+++ b/kernel/model/upload.go@@ -147,14 +147,18 @@ func insertLocalAssets(id string, assetAbsPaths []string, isUpload, validateHTMLsuccFiles = make([]AssetUploadSuccess, 0, len(assetAbsPaths))failedFiles = make([]AssetUploadFailure, 0)- bt := treenode.GetBlockTree(id)- if nil == bt {- err = errors.New(Conf.Language(71))- return+ boxID := ""+ assetsDirPath := filepath.Join(util.DataDir, "assets")+ if id != "" {+ bt := treenode.GetBlockTree(id)+ if nil == bt {+ err = errors.New(Conf.Language(71))+ return+ }+ boxID = bt.BoxID+ docDirLocalPath := filepath.Join(util.DataDir, boxID, path.Dir(bt.Path))+ assetsDirPath = getAssetsDir(filepath.Join(util.DataDir, boxID), docDirLocalPath)}-- docDirLocalPath := filepath.Join(util.DataDir, bt.BoxID, path.Dir(bt.Path))- assetsDirPath := getAssetsDir(filepath.Join(util.DataDir, bt.BoxID), docDirLocalPath)if !gulu.File.IsExist(assetsDirPath) {if err = os.MkdirAll(assetsDirPath, 0755); err != nil {return@@ -213,7 +217,7 @@ func insertLocalAssets(id string, assetAbsPaths []string, isUpload, validateHTMLhash = "random_1_" + gulu.Rand.String(12)}- existAssetPath := GetAssetPathByHash(hash, bt.BoxID)+ existAssetPath := GetAssetPathByHash(hash, boxID)if "" != existAssetPath {originalName := util.RemoveID(filepath.Base(existAssetPath))if strings.ToLower(fName) != strings.ToLower(originalName) {@@ -226,7 +230,7 @@ func insertLocalAssets(id string, assetAbsPaths []string, isUpload, validateHTMLf.Close()} else {blockID := ast.NewNodeID()- if IsEncryptedBox(bt.BoxID) {+ if IsEncryptedBox(boxID) {// 加密 box:磁盘文件名脱敏为 uuid-blockID.ext,原始名存加密映射fName = encryptedAssetName(util.Ext(fName), blockID)} else {@@ -238,7 +242,7 @@ func insertLocalAssets(id string, assetAbsPaths []string, isUpload, validateHTMLrecordAssetUploadFailure(&failedFiles, index, baseName, seekErr)continue}- if writeErr := writeAssetFile(writePath, f, bt.BoxID, baseName); writeErr != nil {+ if writeErr := writeAssetFile(writePath, f, boxID, baseName); writeErr != nil {f.Close()recordAssetUploadFailure(&failedFiles, index, baseName, writeErr)continue@@ -246,11 +250,11 @@ func insertLocalAssets(id string, assetAbsPaths []string, isUpload, validateHTMLf.Close()p := "assets/" + fName- if IsEncryptedBox(bt.BoxID) {- p += "?box=" + bt.BoxID+ if IsEncryptedBox(boxID) {+ p += "?box=" + boxID}recordAssetUploadSuccess(succMap, &succFiles, index, baseName, p)- if !IsEncryptedBox(bt.BoxID) {+ if !IsEncryptedBox(boxID) {cache.SetAssetHash(hash, p) // 加密笔记本不写全局 cache,避免跨边界去重污染}}diff --git a/kernel/model/upload_test.go b/kernel/model/upload_test.goindex c057ab1ae5..e5fe0477b4 100644--- a/kernel/model/upload_test.go+++ b/kernel/model/upload_test.go@@ -151,6 +151,48 @@ func TestRecordAssetUploadFailurePreservesInputIndex(t *testing.T) {}}+func TestInsertLocalAssetsWithoutBlockIDUsesGlobalAssets(t *testing.T) {+ assetsDir := setupAssetUploadTest(t)+ sourceData := []byte("agent pasted image")+ sourcePath := filepath.Join(t.TempDir(), "pasted.png")+ if err := os.WriteFile(sourcePath, sourceData, 0644); err != nil {+ t.Fatal(err)+ }+ hash, err := util.GetEtagByHandle(bytes.NewReader(sourceData), int64(len(sourceData)))+ if err != nil {+ t.Fatal(err)+ }+ if err = os.MkdirAll(assetsDir, 0755); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(filepath.Join(assetsDir, "existing.png"), sourceData, 0644); err != nil {+ t.Fatal(err)+ }+ cache.SetAssetHash(hash, "assets/existing.png")+ t.Cleanup(func() { cache.RemoveAssetHash(hash) })++ succMap, succFiles, failedFiles, err := InsertLocalAssets("", []string{sourcePath}, true)+ if err != nil {+ t.Fatal(err)+ }+ if len(failedFiles) != 0 || len(succFiles) != 1 {+ t.Fatalf("unexpected local asset result: successes=%+v failures=%+v", succFiles, failedFiles)+ }+ if succMap["pasted.png"] != succFiles[0].Path || filepath.ToSlash(filepath.Dir(succFiles[0].Path)) != "assets" {+ t.Fatalf("local asset was not inserted into global assets: %+v", succFiles[0])+ }+ uploadedData, err := os.ReadFile(filepath.Join(assetsDir, filepath.Base(succFiles[0].Path)))+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(uploadedData, sourceData) {+ t.Fatalf("unexpected uploaded data: %q", uploadedData)+ }+ if uploadedHash := cache.GetAssetHashByPath(succFiles[0].Path); uploadedHash != nil {+ cache.RemoveAssetHash(uploadedHash.Hash)+ }+}+func TestMultipartUploadContinuesAfterFileOpenFailure(t *testing.T) {assetsDir := setupAssetUploadTest(t)firstData := []byte("first upload")