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: Restore deleted user guides before mounting https://github.com/siyuan-note/siyuan/issues/20891
Daniel44df1725c2cd
diff --git a/kernel/documentaddressing/mode_test.go b/kernel/documentaddressing/mode_test.goindex f9bfbfbe62..f0561f2d2d 100644--- a/kernel/documentaddressing/mode_test.go+++ b/kernel/documentaddressing/mode_test.go@@ -122,6 +122,23 @@ func TestCheckBoxPreservesSourcesAndNeverLowersFloor(t *testing.T) {}}+func TestCheckBoxRejectsRemovedNotebookWithConfirmedFloor(t *testing.T) {+ readerModeForTest(t, 2)+ root := t.TempDir()+ dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")+ writeTestFile(t, confDir, "document-addressing.json", `{"version":1,"notebooks":{"`+testBox+`":2}}`)+ if err := CheckBox(dataDir, confDir, testBox); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("removed notebook passed the addressing preflight on the local floor alone: %v", err)+ }+ if _, err := os.Stat(filepath.Join(dataDir, testBox)); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("preflight recreated removed notebook: %v", err)+ }+ writeTestFile(t, dataDir, testBox+"/existing.txt", "x")+ if err := CheckBox(dataDir, confDir, testBox); err != nil {+ t.Fatalf("existing notebook with a missing config must retain the confirmed floor: %v", err)+ }+}+func TestLegacyReaderDoesNotMigrateData(t *testing.T) {readerModeForTest(t, 1)root := t.TempDir()diff --git a/kernel/model/mount.go b/kernel/model/mount.goindex e3787ed148..9aa587f914 100644--- a/kernel/model/mount.go+++ b/kernel/model/mount.go@@ -278,10 +278,20 @@ func RemoveBox(boxID string) (err error) {if !ast.IsNodeIDPattern(boxID) {return errors.New("invalid notebook ID")}- addressingErr := filesys.CheckDocumentAddressing(boxID)- unsupportedAddressing := errors.Is(addressingErr, documentaddressing.ErrUnsupported)- if addressingErr != nil && !unsupportedAddressing {- return addressingErr+ localPath := filepath.Join(util.DataDir, boxID)+ _, statErr := os.Lstat(localPath)+ localExists := !os.IsNotExist(statErr)+ if statErr != nil && localExists {+ return statErr+ }+ unsupportedAddressing := false+ // 目录已删除时只清理运行时状态,不用本机下界记录重新创建笔记本。+ if localExists {+ addressingErr := filesys.CheckDocumentAddressing(boxID)+ unsupportedAddressing = errors.Is(addressingErr, documentaddressing.ErrUnsupported)+ if addressingErr != nil && !unsupportedAddressing {+ return addressingErr+ }}if _, loaded := boxLock.LoadOrStore(boxID, true); loaded {err = errors.New(Conf.language(239))@@ -301,8 +311,7 @@ func RemoveBox(boxID string) (err error) {return fmt.Errorf("query database-bound blocks in notebook [%s] failed: %w", boxID, err)}isUserGuide := IsUserGuide(boxID)- localPath := filepath.Join(util.DataDir, boxID)- if !filelock.IsExist(localPath) {+ if !localExists {removeHPathRefreshBox(boxID)forgetRuntimeNormalBox(boxID)removeMasterPasswordMigrationBox(boxID)@@ -525,7 +534,7 @@ func Mount(boxID string) (alreadyMount bool, err error) {}func mountBox(boxID string) (alreadyMount bool, err error) {- if err = filesys.CheckDocumentAddressing(boxID); err != nil {+ if err = checkMountDocumentAddressing(boxID); err != nil {return}confFileTreeSnapshot := Conf.LoadFileTree()@@ -565,6 +574,9 @@ func mountBox(boxID string) (alreadyMount bool, err error) {if err = filelock.Copy(p, localPath); err != nil {return}+ if err = filesys.CheckDocumentAddressing(boxID); err != nil {+ return+ }// 清除所有缓存,确保重开用户指南时数据是最新的cache.ClearTreeCache()@@ -645,6 +657,22 @@ func mountBox(boxID string) (alreadyMount bool, err error) {var userGuideIDs = []string{"20210808180117-6v0mkxr", "20210808180117-czj9bvb", "20211226090932-5lcq56f", "20240530133126-axarxgx"}+func checkMountDocumentAddressing(boxID string) error {+ if !IsUserGuide(boxID) {+ return filesys.CheckDocumentAddressing(boxID)+ }+ // 用户显式重开已删除的指南时,先校验内置副本及本机能力下界,复制后再迁移。+ // 已存在的指南仍须先通过源数据检查,不能借恢复流程覆盖不兼容或损坏的数据。+ if _, err := os.Lstat(filepath.Join(util.DataDir, boxID)); err == nil {+ if err = filesys.CheckDocumentAddressing(boxID); err != nil {+ return err+ }+ } else if !os.IsNotExist(err) {+ return err+ }+ return documentaddressing.CheckImport(util.DataDir, util.ConfDir, boxID, filepath.Join(util.WorkingDir, "guide", boxID))+}+func IsUserGuide(boxID string) bool {return slices.Contains(userGuideIDs, boxID)}diff --git a/kernel/model/mount_user_guide_test.go b/kernel/model/mount_user_guide_test.gonew file mode 100644index 0000000000..d39013f003--- /dev/null+++ b/kernel/model/mount_user_guide_test.go@@ -0,0 +1,130 @@+//go:build fts5++package model++import (+ "context"+ "encoding/json"+ "errors"+ "os"+ "os/exec"+ "path/filepath"+ "testing"+ "time"++ "github.com/siyuan-note/siyuan/kernel/documentaddressing"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/task"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestMountUserGuideAfterDeletion(t *testing.T) {+ const subprocessEnv = "SIYUAN_TEST_MOUNT_USER_GUIDE"+ if os.Getenv(subprocessEnv) != "1" {+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)+ defer cancel()+ cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestMountUserGuideAfterDeletion$", "-test.v")+ cmd.Env = append(os.Environ(), subprocessEnv+"=1")+ if output, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("user guide mount subprocess: %v\n%s", err, output)+ }+ return+ }+ prepareHPathRefreshTest(t)+ // 使用最小内置指南副本,执行实际挂载、删除和再次挂载流程。+ util.WorkingDir = t.TempDir()+ for _, boxID := range userGuideIDs {+ t.Run(boxID, func(t *testing.T) {+ source := filepath.Join(util.WorkingDir, "guide", boxID)+ config := filepath.Join(source, documentaddressing.ConfigPath)+ if err := os.MkdirAll(filepath.Dir(config), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(config, []byte(`{"name":"User guide","closed":true}`), 0644); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(source, "guide.txt"), []byte("bundled guide"), 0644); err != nil {+ t.Fatal(err)+ }+ if _, err := Mount(boxID); err != nil {+ t.Fatalf("first mount: %v", err)+ }+ for task.ContainIndexTask() {+ task.ExecTaskJob()+ }+ if err := filesys.CheckDocumentAddressing(boxID); err != nil {+ t.Fatal(err)+ }+ if err := RemoveBox(boxID); err != nil {+ t.Fatalf("delete guide: %v", err)+ }+ if _, err := os.Stat(filepath.Join(util.DataDir, boxID)); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("guide was not deleted: %v", err)+ }+ if err := RemoveBox(boxID); err != nil {+ t.Fatalf("repeat deletion of missing guide: %v", err)+ }+ if _, err := Mount(boxID); err != nil {+ t.Fatalf("reopen deleted guide: %v", err)+ }+ data, err := os.ReadFile(filepath.Join(util.DataDir, boxID, "guide.txt"))+ if err != nil || string(data) != "bundled guide" {+ t.Fatalf("guide content was not restored: %q, %v", data, err)+ }+ data, err = os.ReadFile(filepath.Join(util.DataDir, boxID, documentaddressing.ConfigPath))+ var fields map[string]any+ if err != nil || json.Unmarshal(data, &fields) != nil || fields["documentAddressingVersion"] != float64(2) {+ t.Fatalf("restored guide was not migrated: %s, %v", data, err)+ }+ if Conf.Box(boxID) == nil {+ t.Fatal("restored guide was not mounted")+ }+ for task.ContainIndexTask() {+ task.ExecTaskJob()+ }+ // 来源不兼容时,无论本地副本是否存在,都不能覆盖或创建副本。+ if err := os.WriteFile(config, []byte(`{"documentAddressingVersion":99}`), 0644); err != nil {+ t.Fatal(err)+ }+ if _, err := Mount(boxID); !errors.Is(err, documentaddressing.ErrUnsupported) {+ t.Fatalf("incompatible bundled guide was accepted: %v", err)+ }+ if actual, err := os.ReadFile(filepath.Join(util.DataDir, boxID, documentaddressing.ConfigPath)); err != nil || string(actual) != string(data) {+ t.Fatalf("rejected source changed local config: %s, %v", actual, err)+ }+ if err := RemoveBox(boxID); err != nil {+ t.Fatal(err)+ }+ if _, err := Mount(boxID); !errors.Is(err, documentaddressing.ErrUnsupported) {+ t.Fatalf("missing guide bypassed source check: %v", err)+ }+ if _, err := os.Stat(filepath.Join(util.DataDir, boxID)); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("rejected source recreated guide: %v", err)+ }+ })+ }+ // 普通笔记本的已确认模式不能作为重新创建已删除源数据的依据。+ const ordinaryBox = "20260101120000-abcdefg"+ ordinaryDir := filepath.Join(util.DataDir, ordinaryBox)+ if err := os.MkdirAll(filepath.Join(ordinaryDir, ".siyuan"), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(ordinaryDir, documentaddressing.ConfigPath), []byte(`{"documentAddressingVersion":2}`), 0644); err != nil {+ t.Fatal(err)+ }+ if err := filesys.CheckDocumentAddressing(ordinaryBox); err != nil {+ t.Fatal(err)+ }+ if err := removeBoxDir(ordinaryDir); err != nil {+ t.Fatal(err)+ }+ if _, err := Mount(ordinaryBox); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("ordinary notebook bypassed missing-source check: %v", err)+ }+ if err := RemoveBox(ordinaryBox); err != nil {+ t.Fatalf("repeat deletion of missing ordinary notebook: %v", err)+ }+ if _, err := os.Stat(ordinaryDir); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("ordinary notebook was recreated: %v", err)+ }+}