An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Preserve existing emojis and refresh partial snapshot restores https://github.com/siyuan-note/siyuan/issues/19511
Daniel7c130a70d7a6
diff --git a/kernel/api/system.go b/kernel/api/system.goindex 1e3bcae124..9075ef06a2 100644--- a/kernel/api/system.go+++ b/kernel/api/system.go@@ -234,13 +234,13 @@ func readCustomEmojis(rootDir, relativeDir string, items *[]*apicontract.SystemEcontinue}- if !util.IsValidUploadFileName(html.UnescapeString(name)) {+ if !util.IsValidExistingEmojiFileName(html.UnescapeString(name)) {oldPath := filepath.Join(dir, name)name = util.FilterUploadEmojiFileName(name)newPath := filepath.Join(dir, name)// XSS through emoji name https://github.com/siyuan-note/siyuan/issues/15034logging.LogWarnf("renaming invalid custom emoji file [%s] to [%s]", oldPath, newPath)- if renameErr := filelock.Rename(oldPath, newPath); nil != renameErr {+ if renameErr := util.RenameEmojiFile(oldPath, newPath); nil != renameErr {logging.LogErrorf("renaming invalid custom emoji file to [%s] failed: %s", newPath, renameErr)continue}diff --git a/kernel/api/system_emoji_test.go b/kernel/api/system_emoji_test.goindex 7ed4cb2a72..ff0472a870 100644--- a/kernel/api/system_emoji_test.go+++ b/kernel/api/system_emoji_test.go@@ -143,3 +143,34 @@ func TestReadCustomEmojisRecursively(t *testing.T) {t.Fatalf("unexpected custom emoji path [%v]", actual)}}++func TestReadCustomEmojisPreservesExistingNames(t *testing.T) {+ model.ClearCustomEmojis()+ t.Cleanup(model.ClearCustomEmojis)+ root := t.TempDir()+ files := map[string]string{"\ufffd.png": "replacement", "_.png": "underscore", "[icon].png": "invalid", "icon.png": "existing"}+ for name, data := range files {+ if err := os.WriteFile(filepath.Join(root, name), []byte(data), 0600); err != nil {+ t.Fatal(err)+ }+ }+ for range 2 {+ items := []*apicontract.SystemEmoji{}+ readCustomEmojis(root, "", &items)+ seen := map[string]bool{}+ for _, item := range items {+ seen[item.Unicode] = true+ }+ for _, name := range []string{"\ufffd.png", "_.png", "icon.png"} {+ if !seen[name] {+ t.Errorf("existing emoji disappeared from list: %q", name)+ }+ }+ for name, want := range files {+ got, err := os.ReadFile(filepath.Join(root, name))+ if err != nil || string(got) != want {+ t.Errorf("existing emoji %q changed: %q, %v", name, got, err)+ }+ }+ }+}diff --git a/kernel/model/import.go b/kernel/model/import.goindex a3c0c6353d..b2eaf9f664 100644--- a/kernel/model/import.go+++ b/kernel/model/import.go@@ -1058,12 +1058,12 @@ func importSY0(zipPath, boxID, toPath string, createNotebook, autoDetect bool, sif d == nil {return nil}- if !util.IsValidUploadFileName(d.Name()) {+ if !util.IsValidExistingEmojiFileName(d.Name()) {emojiFullName := pathfullPathFilteredName := filepath.Join(filepath.Dir(path), util.FilterUploadEmojiFileName(d.Name()))// XSS through emoji name https://github.com/siyuan-note/siyuan/issues/15034logging.LogWarnf("renaming invalid custom emoji file [%s] to [%s]", d.Name(), fullPathFilteredName)- if removeErr := filelock.Rename(emojiFullName, fullPathFilteredName); nil != removeErr {+ if removeErr := util.RenameEmojiFile(emojiFullName, fullPathFilteredName); nil != removeErr {logging.LogErrorf("renaming invalid custom emoji file to [%s] failed: %s", fullPathFilteredName, removeErr)}}@@ -1431,12 +1431,12 @@ func ImportData(zipPath string) (err error) {if d == nil {return nil}- if !util.IsValidUploadFileName(d.Name()) {+ if !util.IsValidExistingEmojiFileName(d.Name()) {emojiFullName := pathfullPathFilteredName := filepath.Join(filepath.Dir(path), util.FilterUploadEmojiFileName(d.Name()))// XSS through emoji name https://github.com/siyuan-note/siyuan/issues/15034logging.LogWarnf("renaming invalid custom emoji file [%s] to [%s]", d.Name(), fullPathFilteredName)- if removeErr := filelock.Rename(emojiFullName, fullPathFilteredName); nil != removeErr {+ if removeErr := util.RenameEmojiFile(emojiFullName, fullPathFilteredName); nil != removeErr {logging.LogErrorf("renaming invalid custom emoji file to [%s] failed: %s", fullPathFilteredName, removeErr)}}diff --git a/kernel/model/repository.go b/kernel/model/repository.goindex 6096ac75fe..34117d096d 100644--- a/kernel/model/repository.go+++ b/kernel/model/repository.go@@ -1378,7 +1378,18 @@ func checkoutRepo(id string) (err error) {return}- _, _, err = repo.Checkout(id, map[string]any{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress})+ err = checkoutRepoSnapshot(repo, id, func(checkoutErr error) {+ release()+ FullReindexDirect()+ if checkoutErr != nil {+ util.ReloadUI()+ return+ }+ appendAgentRollbackEntries()+ time.Sleep(time.Second)+ FlushTxQueue()+ task.AppendAsyncTaskWithDelay(task.ReloadUI, 1*time.Second, util.ReloadUI)+ })if err != nil {logging.LogErrorf("checkout repository failed: %s", err)util.PushClearProgress()@@ -1386,15 +1397,16 @@ func checkoutRepo(id string) (err error) {return}- release()- FullReindexDirect()- appendAgentRollbackEntries()- time.Sleep(time.Second)- FlushTxQueue()- task.AppendAsyncTaskWithDelay(task.ReloadUI, 1*time.Second, util.ReloadUI)return}+// checkoutRepoSnapshot 恢复失败前可能已有文件落盘,返回结果前同步更新索引、缓存和界面。+func checkoutRepoSnapshot(repo *dejavu.Repo, id string, refresh func(error)) error {+ _, _, err := repo.Checkout(id, map[string]any{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress})+ refresh(err)+ return err+}+func appendAgentRollbackEntries() {pattern := filepath.Join(util.TempDir, "ai", "agent", "agentRollback_*.json")markers, err := filepath.Glob(pattern)diff --git a/kernel/model/repository_checkout_test.go b/kernel/model/repository_checkout_test.gonew file mode 100644index 0000000000..36e35aee47--- /dev/null+++ b/kernel/model/repository_checkout_test.go@@ -0,0 +1,83 @@+package model++import (+ "errors"+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/siyuan-note/dejavu"+)++func TestCheckoutRepoSnapshotRefreshesPartialFailure(t *testing.T) {+ previousConf := Conf+ Conf = &AppConf{Lang: "en"}+ t.Cleanup(func() { Conf = previousConf })+ for _, fail := range []bool{false, true} {+ t.Run(map[bool]string{false: "success", true: "partial failure"}[fail], func(t *testing.T) {+ base := t.TempDir()+ dataDir := filepath.Join(base, "data")+ repo, err := dejavu.NewRepo(dataDir, filepath.Join(base, "repo"), filepath.Join(base, "history"),+ filepath.Join(base, "temp"), "device", "device", "windows", []byte("0123456789abcdef0123456789abcdef"), nil, nil)+ if err != nil {+ t.Fatal(err)+ }+ first := filepath.Join(dataDir, "notebook", "first.sy")+ second := filepath.Join(dataDir, "notebook", "nested", "second.sy")+ write := func(name, content string, tick int64) {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(name), 0700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(name, []byte(content), 0600); err != nil {+ t.Fatal(err)+ }+ stamp := time.Unix(1700000000+tick, 0)+ if err := os.Chtimes(name, stamp, stamp); err != nil {+ t.Fatal(err)+ }+ }+ write(first, "snapshot first", 10)+ write(second, "snapshot second", 10)+ snapshot, err := repo.Index("snapshot", false, nil)+ if err != nil {+ t.Fatal(err)+ }+ write(first, "current first", 20)+ write(second, "current second", 20)+ if fail {+ if err := os.Remove(second); err != nil {+ t.Fatal(err)+ }+ write(filepath.Join(second, "keep"), "occupied", 20)+ }+ var refreshErr error+ calls := 0+ visibleContent := "current first"+ err = checkoutRepoSnapshot(repo, snapshot.ID, func(checkoutErr error) {+ calls+++ refreshErr = checkoutErr+ content, readErr := os.ReadFile(first)+ if readErr != nil {+ t.Fatal(readErr)+ }+ visibleContent = string(content)+ })+ if (err != nil) != fail || !errors.Is(err, refreshErr) {+ t.Fatalf("checkout result was not preserved: returned %v, refreshed %v", err, refreshErr)+ }+ if calls != 1 || visibleContent != "snapshot first" {+ t.Fatalf("partially restored content was not refreshed: calls=%d, content=%q", calls, visibleContent)+ }+ if fail {+ if content, readErr := os.ReadFile(filepath.Join(second, "keep")); readErr != nil || string(content) != "occupied" {+ t.Fatalf("failed destination changed: %q, %v", content, readErr)+ }+ if _, readErr := repo.GetIndex(snapshot.ID); readErr != nil {+ t.Fatalf("recovery snapshot lost: %v", readErr)+ }+ }+ })+ }+}diff --git a/kernel/util/file.go b/kernel/util/file.goindex d2f6fd840e..61e996a5cc 100644--- a/kernel/util/file.go+++ b/kernel/util/file.go@@ -218,6 +218,33 @@ func IsValidUploadFileName(name string) bool {return name == FilterUploadFileName(name)}+// IsValidExistingEmojiFileName 保留已有表情名中的合法替换字符,新上传文件仍按命名规则清洗。+func IsValidExistingEmojiFileName(name string) bool {+ return utf8.ValidString(name) && strings.ReplaceAll(name, "\ufffd", "_") == FilterUploadFileName(name)+}++// RenameEmojiFile 在源和目标文件锁内迁移表情,目标已存在时保留两者,不覆盖文件或合并目录。+func RenameEmojiFile(oldPath, newPath string) error {+ oldPath, newPath = filepath.Clean(oldPath), filepath.Clean(newPath)+ if oldPath == newPath {+ return nil+ }+ first, second := oldPath, newPath+ if first > second {+ first, second = second, first+ }+ filelock.Lock(first)+ defer filelock.Unlock(first)+ filelock.Lock(second)+ defer filelock.Unlock(second)+ if _, err := os.Lstat(newPath); err == nil {+ return &os.LinkError{Op: "rename", Old: oldPath, New: newPath, Err: os.ErrExist}+ } else if !os.IsNotExist(err) {+ return err+ }+ return os.Rename(oldPath, newPath)+}+func IsNetworkIconURL(icon string) bool {u, err := url.Parse(icon)return nil == err && "" != u.Host && ("http" == strings.ToLower(u.Scheme) || "https" == strings.ToLower(u.Scheme))diff --git a/kernel/util/file_name_test.go b/kernel/util/file_name_test.goindex 0faa5a102a..1c9dce4847 100644--- a/kernel/util/file_name_test.go+++ b/kernel/util/file_name_test.go@@ -1,6 +1,10 @@package util-import "testing"+import (+ "os"+ "path/filepath"+ "testing"+)func TestFilterFileNamePortableUnicode(t *testing.T) {for _, tc := range []struct{ input, want string }{@@ -16,3 +20,52 @@ func TestFilterFileNamePortableUnicode(t *testing.T) {}}}++func TestExistingEmojiFileNameCompatibility(t *testing.T) {+ for _, name := range []string{"\ufffd.png", "_.png", "\ue000.png"} {+ if !IsValidExistingEmojiFileName(name) {+ t.Errorf("existing emoji name rejected: %q", name)+ }+ }+ for _, name := range []string{"bad\xff.png", "[icon].png", "<img>.png", "a/b.png"} {+ if IsValidExistingEmojiFileName(name) {+ t.Errorf("unsafe emoji name accepted: %q", name)+ }+ }+ if IsValidUploadFileName("\ufffd.png") {+ t.Fatal("new upload validation accepted an unfiltered name")+ }+}++func TestRenameEmojiFilePreservesExistingDestination(t *testing.T) {+ for _, directory := range []bool{false, true} {+ t.Run(map[bool]string{false: "file", true: "directory"}[directory], func(t *testing.T) {+ root := t.TempDir()+ source, destination := filepath.Join(root, "[icon]"), filepath.Join(root, "icon")+ paths := []string{source, destination}+ for i, name := range paths {+ if directory {+ if err := os.Mkdir(name, 0700); err != nil {+ t.Fatal(err)+ }+ paths[i] = filepath.Join(name, "keep")+ }+ if err := os.WriteFile(paths[i], []byte{byte(i)}, 0600); err != nil {+ t.Fatal(err)+ }+ }+ if err := RenameEmojiFile(source, destination); !os.IsExist(err) {+ t.Fatalf("expected destination-exists error, got %v", err)+ }+ for i, name := range paths {+ got, err := os.ReadFile(name)+ if err != nil || len(got) != 1 || got[0] != byte(i) {+ t.Fatalf("existing data changed: %q, %v", got, err)+ }+ }+ if err := RenameEmojiFile(source, filepath.Join(root, "available")); err != nil {+ t.Fatalf("rename to available destination failed: %v", err)+ }+ })+ }+}