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: Collect copied, templated and moved documents https://github.com/siyuan-note/siyuan/issues/20923
Danielc07ce8c59d47
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex f9fc02308d..6f93691df7 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -5464,6 +5464,9 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * evaluates block collection rules for the new document and its blocks, initializing only new rows.+ */"/api/filetree/duplicateDoc": {request: FileTreeIDRequestInput;response: { "code": 0; "data": FileTreeDuplicateData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -5471,6 +5474,9 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * evaluates block collection rules for every copied document and block, initializing only new rows.+ */"/api/filetree/duplicateDocTree": {request: FileTreeIDRequestInput;response: { "code": 0; "data": FileTreeDuplicateData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -5637,6 +5643,11 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated"];};+ /**+ * evaluates block collection rules for moved documents and descendants entering a watched scope.+ * Existing database rows and their field values are preserved. A collection failure is returned after the+ * physical move; successfully moved documents remain at their new locations.+ */"/api/filetree/moveDocs": {request: FileTreeMoveRequestInput;response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -5644,6 +5655,9 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * has the same collection and partial-failure behavior as MoveDocs.+ */"/api/filetree/moveDocsByID": {request: FileTreeMoveIDsRequestInput;response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };diff --git a/docs/API.ja.md b/docs/API.ja.mdindex 20665c7787..c794c5007a 100644--- a/docs/API.ja.md+++ b/docs/API.ja.md@@ -504,6 +504,8 @@ if (response.code === 0 && response.data) {### ドキュメントを移動+両方の移動 API は、監視範囲に入ったドキュメントと子ドキュメントのブロック収集ルールを評価し、既存のデータベース行とフィールド値を保持します。移動後に収集が失敗した場合はエラーを返し、移動済みのドキュメントは新しい場所に残ります。+* `/api/filetree/moveDocs`* パラメータdiff --git a/docs/API.md b/docs/API.mdindex 237dbbc73a..39a9ee80c0 100644--- a/docs/API.md+++ b/docs/API.md@@ -509,6 +509,8 @@ Remove a document by `id`:### Move documents+Both move endpoints evaluate block collection rules for moved documents and descendants entering a watched scope. Existing database rows and field values are preserved. If collection fails after a document has moved, the endpoint returns an error and that document remains at its new location.+* `/api/filetree/moveDocs`* Parametersdiff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.mdindex d774a6b010..7854aa8d0a 100644--- a/docs/API.zh-CN.md+++ b/docs/API.zh-CN.md@@ -509,6 +509,8 @@ if (response.code === 0 && response.data) {### 移动文档+两个移动接口都会为进入监听范围的文档及子文档判断块收集规则,并保留已有数据库行和字段值。若文档移动后收集失败,接口返回错误,已移动的文档保留在新位置。+* `/api/filetree/moveDocs`* 参数diff --git a/kernel/api/contract_duplicate_doc_tree_test.go b/kernel/api/contract_duplicate_doc_tree_test.goindex 0c37320ba9..6681e9678d 100644--- a/kernel/api/contract_duplicate_doc_tree_test.go+++ b/kernel/api/contract_duplicate_doc_tree_test.go@@ -94,7 +94,7 @@ func TestAPIContractDuplicateDocTree(t *testing.T) {engine := gin.New()engine.Use(sessions.Sessions("duplicate-tree-test", cookie.NewStore([]byte("duplicate-tree-session-test-key"))))ServeAPI(engine)- const endpoint = "/api/filetree/duplicateDocTree"+ endpoint := "/api/filetree/duplicateDocTree"request := func(id string) *http.Request {ret := httptest.NewRequest("POST", endpoint, strings.NewReader(`{"id":"`+id+`"}`))ret.Header.Set("Authorization", "Token duplicate-tree-test")@@ -165,6 +165,40 @@ func TestAPIContractDuplicateDocTree(t *testing.T) {if recorder.Code != http.StatusUnauthorized {t.Fatalf("unauthenticated copy admitted: %s", recorder.Body.String())}+ t.Run("collection-failure", func(t *testing.T) {+ originalEndpoint := endpoint+ defer func() { endpoint = originalEndpoint }()+ view := av.NewAttributeView(ast.NewNodeID())+ keyID := ast.NewNodeID()+ view.KeyValues = append(view.KeyValues, &av.KeyValues{Key: &av.Key{ID: keyID, Name: "Date", Type: av.KeyTypeDate}})+ view.Automations = &av.AutomationConfig{Spec: 2, Rules: []*av.AutomationRule{{+ ID: ast.NewNodeID(), Name: "Invalid date", Trigger: "block", Enabled: true,+ BlockSource: &av.AutomationBlockSource{NotebookIDs: []string{box.ID}, Types: []string{"d"}, Tags: []string{"todo"}},+ Actions: []*av.AutomationAction{{Type: "collect", Target: "current", Fields: map[string]*av.AutomationValue{+ keyID: {Mode: "template", Template: "invalid date"},+ }}},+ }}}+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ source.Root.SetIALAttr("tags", "todo")+ if _, err := filesys.WriteTree(source); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(source)+ before := len(treenode.GetBlockTreesByTypeInBox("d", box.ID))+ for _, name := range []string{"duplicateDoc", "duplicateDocTree"} {+ endpoint = "/api/filetree/" + name+ post(source.ID, false)+ if got := len(treenode.GetBlockTreesByTypeInBox("d", box.ID)); got != before {+ t.Fatalf("%s left a failed copy in the index: %d != %d", name, got, before)+ }+ }+ view.Automations.Rules[0].Enabled = false+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ })const password = "duplicate-password"if err = model.EnableEncryptedNotebook(password); err != nil {diff --git a/kernel/api/filetree.go b/kernel/api/filetree.goindex 11ddab44b0..5bc09b57ae 100644--- a/kernel/api/filetree.go+++ b/kernel/api/filetree.go@@ -744,7 +744,9 @@ func duplicateDocContract(c *gin.Context, request apicontract.FileTreeIDRequest)}notebook := tree.Box- model.DuplicateDoc(tree)+ if err = model.DuplicateDoc(tree); err != nil {+ return apicontract.FailureWithTimeout[apicontract.FileTreeDuplicateData](-1, err.Error(), 7000)+ }return apicontract.Success(apicontract.FileTreeDuplicateData{ID: tree.Root.ID, Notebook: notebook, Path: tree.Path, HPath: tree.HPath})}diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex 9f3e6135ff..6e15604da8 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -1135,14 +1135,24 @@ var GetFullHPathByID = define[FileTreeOptionalIDRequest, *string]("getFullHPathB// unsupportedIDs, filtered by existing access restrictions. Missing, pending, inconsistent or failed// metadata returns indexUnavailable. Prefer resolveDocPath with independent title segments.var GetIDsByHPath = define[FileTreeOptionalPathRequest, LegacyPathIDsResult]("getIDsByHPath", "/api/filetree/getIDsByHPath", AuthenticatedAccess, JSONBody, ResponseOptions{DataOnError: true}, "POST")++// MoveDocs evaluates block collection rules for moved documents and descendants entering a watched scope.+// Existing database rows and their field values are preserved. A collection failure is returned after the+// physical move; successfully moved documents remain at their new locations.var MoveDocs = define[FileTreeMoveRequest, Null]("moveDocs", "/api/filetree/moveDocs", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")++// MoveDocsByID has the same collection and partial-failure behavior as MoveDocs.var MoveDocsByID = define[FileTreeMoveIDsRequest, Null]("moveDocsByID", "/api/filetree/moveDocsByID", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var RemoveDoc = define[FileTreePathRequest, Null]("removeDoc", "/api/filetree/removeDoc", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var RemoveDocByID = define[FileTreeTrimIDRequest, Null]("removeDocByID", "/api/filetree/removeDocByID", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var RemoveDocs = define[FileTreePathsRequest, Null]("removeDocs", "/api/filetree/removeDocs", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var RenameDoc = define[FileTreeRenameRequest, Null]("renameDoc", "/api/filetree/renameDoc", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var RenameDocByID = define[FileTreeRenameIDRequest, Null]("renameDocByID", "/api/filetree/renameDocByID", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")++// DuplicateDoc evaluates block collection rules for the new document and its blocks, initializing only new rows.var DuplicateDoc = define[FileTreeIDRequest, FileTreeDuplicateData]("duplicateDoc", "/api/filetree/duplicateDoc", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")++// DuplicateDocTree evaluates block collection rules for every copied document and block, initializing only new rows.var DuplicateDocTree = define[FileTreeIDRequest, FileTreeDuplicateData]("duplicateDocTree", "/api/filetree/duplicateDocTree", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var CreateDoc = define[FileTreeCreateRequest, FileTreeCreateData]("createDoc", "/api/filetree/createDoc", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var CreateDailyNote = define[FileTreeDailyNoteRequest, FileTreeCreateData]("createDailyNote", "/api/filetree/createDailyNote", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")diff --git a/kernel/cli/cmd/document.go b/kernel/cli/cmd/document.goindex c269e13d03..0ec47de23d 100644--- a/kernel/cli/cmd/document.go+++ b/kernel/cli/cmd/document.go@@ -262,7 +262,9 @@ var documentDuplicateCmd = &cobra.Command{if err != nil {return err}- model.DuplicateDoc(tree)+ if err = model.DuplicateDoc(tree); err != nil {+ return err+ }model.AppendPushReloadFiletreeEntry()fmt.Println(tree.ID)return nildiff --git a/kernel/mcp/tools/document.go b/kernel/mcp/tools/document.goindex 71943ec9de..8a033709d2 100644--- a/kernel/mcp/tools/document.go+++ b/kernel/mcp/tools/document.go@@ -307,7 +307,9 @@ func documentDuplicate(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("load doc failed: %s", err)}}, IsError: true}, nil}- model.DuplicateDoc(tree)+ if err = model.DuplicateDoc(tree); err != nil {+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("duplicate doc failed: %s", err)}}, IsError: true}, nil+ }util.PushReloadFiletree()return CallToolResult{Content: []ContentItem{{Type: "text", Text: "document duplicated: " + id}}}, nil}diff --git a/kernel/model/attribute_view_collection.go b/kernel/model/attribute_view_collection.goindex 507b4a43d1..9d3d6d4808 100644--- a/kernel/model/attribute_view_collection.go+++ b/kernel/model/attribute_view_collection.go@@ -410,7 +410,7 @@ func (tx *Transaction) captureDocumentCollectionTree(tree *parse.Tree) (captureEif tx.attributeViewRollback == nil {tx.attributeViewRollback = &attributeViewRollback{views: map[string]*av.AttributeView{}, trees: map[string]*parse.Tree{}, leases: map[string]bool{}}}- original, err := filesys.LoadTree(tree.Box, tree.Path, tx.luteEngine)+ original, _, err := filesys.LoadTreeSnapshot(tree.Box, tree.Path, tx.luteEngine)if err != nil {if _, statErr := os.Stat(filepath.Join(util.DataDir, tree.Box, tree.Path)); !os.IsNotExist(statErr) {return err@@ -426,6 +426,31 @@ func (tx *Transaction) captureDocumentCollectionTree(tree *parse.Tree) (captureE// Caller holds flushLock and has checked the replacement's source bytes.func writeDocumentWithCollections(tree *parse.Tree, write func(*parse.Tree) error) (handled bool, err error) {+ return writeDocumentsWithCollections([]*parse.Tree{tree}, nil, write)+}++// collectDocumentChanges observes committed user-created or moved documents. An explicit+// nil before snapshot represents creation; import, sync and recovery never call this entry.+// Rollback snapshots come from the committed after locations, not the old matching scope.+// Caller holds flushLock until collection and its document writes finish.+func collectDocumentChanges(before map[string]*parse.Tree, after []*parse.Tree) error {+ _, err := writeDocumentsWithCollections(after, before, nil)+ return err+}++func documentCollectionIndex(boxID string) (*av.BlockCollectionIndex, error) {+ boundary := ""+ if IsEncryptedBox(boxID) {+ boundary = boxID+ }+ if av.BlockCollectionIndexKnownEmpty(boundary) {+ return nil, nil+ }+ return av.BlockCollectionIndexInBox(boundary)+}++func writeDocumentsWithCollections(after []*parse.Tree, before map[string]*parse.Tree,+ write func(*parse.Tree) error) (handled bool, err error) {tx := &Transaction{fromAPI: true, m: &sync.Mutex{}}if err = tx.begin(); err != nil {return false, err@@ -435,18 +460,42 @@ func writeDocumentWithCollections(tree *parse.Tree, write func(*parse.Tree) errotx.rollback()}}()- if err = tx.captureDocumentCollectionTree(tree); err != nil {- return true, err+ for _, tree := range after {+ if err = tx.captureDocumentCollectionTree(tree); err != nil {+ return true, err+ }}- if tx.attributeViewCollections == nil || tx.attributeViewCollections.before[tree.ID] == nil {+ if tx.attributeViewCollections == nil || len(tx.attributeViewCollections.before) == 0 {return false, nil}- tx.trees[tree.ID] = tree+ sources := map[string]bool{}+ for _, tree := range after {+ if _, captured := tx.attributeViewCollections.before[tree.ID]; !captured {+ continue+ }+ if before != nil {+ tx.attributeViewCollections.before[tree.ID] = before[tree.ID]+ }+ sources[tree.ID] = true+ tx.trees[tree.ID] = tree+ if write != nil {+ // Content templates may introduce blocks that collection must resolve before commit.+ treenode.UpsertBlockTreePending(tree)+ }+ }if err = tx.runAttributeViewCollections(); err != nil {return true, err}+ if write == nil {+ // The file operation already committed its sources; persist only new binding changes.+ for id := range tx.trees {+ if tx.indexChanges[id] == nil {+ delete(tx.trees, id)+ }+ }+ }tx.writeTransactionTree = func(changed *parse.Tree) error {- if changed.ID == tree.ID {+ if write != nil && sources[changed.ID] {return write(changed)}return writeTreeUpsertQueue(changed)@@ -765,6 +814,10 @@ func (tx *Transaction) rollbackCollectionCreatedTrees() {if before != nil {continue}+ if tx.attributeViewRollback != nil && tx.attributeViewRollback.trees[id] != nil {+ // A committed copy has a rollback baseline even though its matching "before" is empty.+ continue+ }tree := tx.trees[id]if tree == nil {continuediff --git a/kernel/model/attribute_view_collection_document_fts5_test.go b/kernel/model/attribute_view_collection_document_fts5_test.gonew file mode 100644index 0000000000..33f1d09784--- /dev/null+++ b/kernel/model/attribute_view_collection_document_fts5_test.go@@ -0,0 +1,319 @@+//go:build fts5++package model++import (+ "bytes"+ "errors"+ "os"+ "path"+ "path/filepath"+ "strings"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func saveDocumentCollectionFixture(t *testing.T, tree *parse.Tree) {+ t.Helper()+ if err := indexWriteTreeUpsertQueue(tree); err != nil {+ t.Fatal(err)+ }+ sql.FlushQueue()+}++func addDocumentCollectionChild(t *testing.T, parent *parse.Tree) *parse.Tree {+ t.Helper()+ tree := treenode.NewTree(parent.Box, strings.TrimSuffix(parent.Path, ".sy")+"/"+ast.NewNodeID()+".sy", parent.HPath+"/Child", "Child")+ tree.Root.SetIALAttr("tags", "todo")+ saveDocumentCollectionFixture(t, tree)+ return tree+}++func TestDocumentCollectionCopiesCreateRowsWithoutResettingSource(t *testing.T) {+ for _, subtree := range []bool{false, true} {+ t.Run(map[bool]string{false: "document", true: "subtree"}[subtree], func(t *testing.T) {+ fixture, view, keyID := setupBlockCollectionTest(t)+ view.Automations.Rules[0].BlockSource.DocumentIDs = nil+ view.Automations.Rules[0].BlockSource.NotebookIDs = []string{fixture.box.ID}+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ if err := PerformTxSync(blockCollectionTags(t, fixture.sourceID, "todo")); err != nil {+ t.Fatal(err)+ }+ view = readAttributeViewItemsTest(t, view.ID)+ originalRow := view.GetBlockValueByBoundID(fixture.sourceID)+ view.GetValue(keyID, originalRow.BlockID).Text.Content = "User value"+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ source, err := LoadTreeByBlockID(fixture.sourceID)+ if err != nil {+ t.Fatal(err)+ }+ wantCopies := 1+ if subtree {+ addDocumentCollectionChild(t, source)+ wantCopies+++ }+ filename := filepath.Join(util.DataDir, source.Box, source.Path)+ original, err := os.ReadFile(filename)+ if err != nil {+ t.Fatal(err)+ }+ var copiedID string+ if subtree {+ copied, copyErr := DuplicateDocTree(source.ID)+ if copyErr != nil {+ t.Fatal(copyErr)+ }+ copiedID = copied.ID+ } else {+ if err = DuplicateDoc(source); err != nil {+ t.Fatal(err)+ }+ copiedID = source.ID+ }+ view = readAttributeViewItemsTest(t, view.ID)+ if len(view.GetBlockKeyValues().Values) != wantCopies+1 || view.GetBlockValueByBoundID(copiedID) == nil {+ t.Fatalf("copy did not collect every new document: %+v", view.GetBlockKeyValues().Values)+ }+ if view.GetValue(keyID, originalRow.BlockID).Text.Content != "User value" {+ t.Fatal("copy reset source row fields")+ }+ for _, row := range view.GetBlockKeyValues().Values {+ if row.Block.ID == fixture.sourceID {+ continue+ }+ if view.GetValue(keyID, row.BlockID).Text.Content != "New" {+ t.Fatal("copy row fields were not initialized")+ }+ tree, loadErr := LoadTreeByBlockID(row.Block.ID)+ if loadErr != nil || tree.Root.IALAttr(av.NodeAttrNameAvs) != view.ID {+ t.Fatalf("copy binding was not persisted: %v", loadErr)+ }+ }+ current, err := os.ReadFile(filename)+ if err != nil || !bytes.Equal(current, original) {+ t.Fatalf("copy changed its source: %v", err)+ }+ })+ }+}++func TestDocumentCollectionContentTemplateCollectsBlocksAndAttributes(t *testing.T) {+ for _, attributes := range []bool{false, true} {+ t.Run(map[bool]string{false: "tagged-block", true: "document-attributes"}[attributes], func(t *testing.T) {+ fixture, view, keyID := setupBlockCollectionTest(t)+ rule := view.Automations.Rules[0]+ rule.BlockSource.DocumentIDs = []string{fixture.targetID}+ if attributes {+ rule.BlockSource.Tags = nil+ rule.BlockSource.Attributes = []*av.AutomationBlockAttribute{{Name: "custom-state", Operator: "equals", Value: "active"}}+ } else {+ rule.BlockSource.Types = []string{"p"}+ }+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ source, err := LoadTreeByBlockID(fixture.sourceID)+ if err != nil {+ t.Fatal(err)+ }+ source.Root.SetIALAttr("custom-state", "active")+ source.Root.FirstChild.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "tag", TextMarkTextContent: "todo"})+ saveDocumentCollectionFixture(t, source)+ if _, err = DocSaveAsTemplate(fixture.sourceID, "collection-template", false); err != nil {+ t.Fatal(err)+ }+ if err = applyDocContentTemplate("collection-template.md", fixture.targetID); err != nil {+ t.Fatal(err)+ }+ view = readAttributeViewItemsTest(t, view.ID)+ rows := view.GetBlockKeyValues().Values+ if len(rows) != 1 || view.GetValue(keyID, rows[0].BlockID).Text.Content != "New" {+ t.Fatalf("template was not collected: %+v", rows)+ }+ if attributes {+ if rows[0].Block.ID != fixture.targetID {+ t.Fatal("template attributes collected the wrong document")+ }+ itemID := rows[0].BlockID+ view.GetValue(keyID, itemID).Text.Content = "User value"+ if err = av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ if err = applyDocContentTemplate("collection-template.md", fixture.targetID); err != nil {+ t.Fatal(err)+ }+ view = readAttributeViewItemsTest(t, view.ID)+ if len(view.GetBlockKeyValues().Values) != 1 || view.GetValue(keyID, itemID).Text.Content != "User value" {+ t.Fatal("reapplying template reset or duplicated an existing row")+ }+ }+ })+ }+}++func TestDocumentCollectionMovesIncludeDescendantsAndPreserveRows(t *testing.T) {+ for _, notebook := range []bool{false, true} {+ t.Run(map[bool]string{false: "document-scope", true: "notebook-scope"}[notebook], func(t *testing.T) {+ fixture, view, keyID := setupBlockCollectionTest(t)+ toBox, toPath := fixture.box.ID, fixture.targetPath+ rule := view.Automations.Rules[0]+ rule.BlockSource.DocumentIDs = []string{fixture.targetID}+ if notebook {+ other := &Box{ID: ast.NewNodeID()}+ boxConf := conf.NewBoxConf()+ boxConf.Closed, boxConf.Name = false, "Other"+ if err := other.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ toBox, toPath = other.ID, "/"+ rule.BlockSource.DocumentIDs, rule.BlockSource.NotebookIDs = nil, []string{other.ID}+ }+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ source, err := LoadTreeByBlockID(fixture.sourceID)+ if err != nil {+ t.Fatal(err)+ }+ source.Root.SetIALAttr("tags", "todo")+ saveDocumentCollectionFixture(t, source)+ child := addDocumentCollectionChild(t, source)+ if err = MoveDocs([]string{source.Path}, toBox, toPath, nil); err != nil {+ t.Fatal(err)+ }+ view = readAttributeViewItemsTest(t, view.ID)+ if len(view.GetBlockKeyValues().Values) != 2 {+ t.Fatalf("move omitted descendants: %+v", view.GetBlockKeyValues().Values)+ }+ for _, id := range []string{source.ID, child.ID} {+ row := view.GetBlockValueByBoundID(id)+ if row == nil || view.GetValue(keyID, row.BlockID).Text.Content != "New" {+ t.Fatalf("move did not collect %s", id)+ }+ view.GetValue(keyID, row.BlockID).Text.Content = "User value"+ }+ if err = av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ current := treenode.GetBlockTreeInExactBox(source.ID, toBox)+ if err = MoveDocs([]string{current.Path}, fixture.box.ID, "/", nil); err != nil {+ t.Fatal(err)+ }+ if err = MoveDocs([]string{source.Path}, toBox, toPath, nil); err != nil {+ t.Fatal(err)+ }+ view = readAttributeViewItemsTest(t, view.ID)+ if len(view.GetBlockKeyValues().Values) != 2 {+ t.Fatal("re-entering scope duplicated rows")+ }+ for _, id := range []string{source.ID, child.ID} {+ row := view.GetBlockValueByBoundID(id)+ if row == nil || view.GetValue(keyID, row.BlockID).Text.Content != "User value" {+ t.Fatal("move reset user fields")+ }+ }+ })+ }+}++func TestDocumentCollectionCopyFailureCleansCreatedFiles(t *testing.T) {+ fixture, view, keyID := setupBlockCollectionTest(t)+ view.Automations.Rules[0].BlockSource.DocumentIDs = nil+ view.Automations.Rules[0].BlockSource.NotebookIDs = []string{fixture.box.ID}+ view.Automations.Spec = 2+ key, err := view.GetKey(keyID)+ if err != nil {+ t.Fatal(err)+ }+ key.Type = av.KeyTypeDate+ view.Automations.Rules[0].Actions[0].Fields[keyID] = &av.AutomationValue{Mode: "template", Template: "invalid date"}+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ source, err := LoadTreeByBlockID(fixture.sourceID)+ if err != nil {+ t.Fatal(err)+ }+ source.Root.SetIALAttr("tags", "todo")+ saveDocumentCollectionFixture(t, source)+ addDocumentCollectionChild(t, source)+ plan, err := prepareDuplicateDocTree(source.Box, source.Path)+ if err != nil {+ t.Fatal(err)+ }+ if err = plan.commit(filesys.WriteTree); err == nil {+ t.Fatal("expected invalid collection template to fail")+ }+ for _, tree := range plan.trees {+ if _, err = os.Stat(filepath.Join(util.DataDir, tree.Box, tree.Path)); !os.IsNotExist(err) {+ t.Fatalf("failed copy left document %s: %v", tree.Path, err)+ }+ if treenode.GetBlockTreeInExactBox(tree.ID, tree.Box) != nil {+ t.Fatal("failed copy left block-tree rows")+ }+ }+ if len(readAttributeViewItemsTest(t, view.ID).GetBlockKeyValues().Values) != 0 {+ t.Fatal("failed copy retained collected rows")+ }+}++func TestDocumentCollectionMoveWriteFailureKeepsNewLocation(t *testing.T) {+ fixture, view, _ := setupBlockCollectionTest(t)+ rule := view.Automations.Rules[0]+ rule.Enabled = false+ rule.BlockSource.DocumentIDs = []string{fixture.targetID}+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ before, err := LoadTreeByBlockID(fixture.sourceID)+ if err != nil {+ t.Fatal(err)+ }+ before.Root.SetIALAttr("tags", "todo")+ saveDocumentCollectionFixture(t, before)+ if err = MoveDocs([]string{before.Path}, fixture.box.ID, fixture.targetPath, nil); err != nil {+ t.Fatal(err)+ }+ newPath := path.Join(strings.TrimSuffix(fixture.targetPath, ".sy"), before.ID+".sy")+ after, _, err := filesys.ReadTreeSnapshot(before.Box, newPath)+ if err != nil {+ t.Fatal(err)+ }+ original, err := os.ReadFile(filepath.Join(util.DataDir, after.Box, after.Path))+ if err != nil {+ t.Fatal(err)+ }+ rule.Enabled = true+ if err = av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ injected := errors.New("injected collection binding write failure")+ flushLock.Lock()+ _, err = writeDocumentsWithCollections([]*parse.Tree{after}, map[string]*parse.Tree{before.ID: before}, func(*parse.Tree) error { return injected })+ flushLock.Unlock()+ if !errors.Is(err, injected) {+ t.Fatalf("unexpected write result: %v", err)+ }+ if _, err = os.Stat(filepath.Join(util.DataDir, before.Box, before.Path)); !os.IsNotExist(err) {+ t.Fatal("collection rollback recreated the old source path")+ }+ current, err := os.ReadFile(filepath.Join(util.DataDir, after.Box, after.Path))+ if err != nil || !bytes.Equal(current, original) {+ t.Fatalf("failed collection lost the moved document: %v", err)+ }+ if len(readAttributeViewItemsTest(t, view.ID).GetBlockKeyValues().Values) != 0 {+ t.Fatal("failed move collection retained a row")+ }+}diff --git a/kernel/model/attribute_view_collection_document_sqlcipher_test.go b/kernel/model/attribute_view_collection_document_sqlcipher_test.gonew file mode 100644index 0000000000..772cc0d4ba--- /dev/null+++ b/kernel/model/attribute_view_collection_document_sqlcipher_test.go@@ -0,0 +1,129 @@+//go:build fts5 && (sqlcipher || libsqlcipher)++package model++import (+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestDocumentCollectionEncryptedCopiesTemplatesAndMoves(t *testing.T) {+ if !prepareStructuredTitlesCryptoTest(t) {+ return+ }+ util.Lang = "en"+ util.AttrViewLangs = map[string]map[string]any{"en": {"key": "Key", "table": "Table", "select": "Select"}}+ box := newStructuredTitlesEncryptedBox(t)+ root := createStructuredTitlesEncryptedDoc(t, box, nil, "Source")+ child := createStructuredTitlesEncryptedDoc(t, box, &root.ID, "Child")+ target := createStructuredTitlesEncryptedDoc(t, box, nil, "Target")+ for _, document := range []*treenode.DocumentPath{root, child} {+ tree, _, err := filesys.ReadTreeSnapshot(box, document.Path)+ if err != nil {+ t.Fatal(err)+ }+ tree.Root.FirstChild.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "tag", TextMarkTextContent: "todo"})+ if err = indexWriteTreeUpsertQueue(tree); err != nil {+ t.Fatal(err)+ }+ }+ view := av.NewAttributeView(ast.NewNodeID())+ keyID := ast.NewNodeID()+ view.KeyValues = append(view.KeyValues, &av.KeyValues{Key: &av.Key{ID: keyID, Name: "Status", Type: av.KeyTypeText}})+ view.Automations = &av.AutomationConfig{Spec: 1, Rules: []*av.AutomationRule{{+ ID: ast.NewNodeID(), Name: "Collect", Trigger: "block", Enabled: true,+ BlockSource: &av.AutomationBlockSource{NotebookIDs: []string{box}, Types: []string{"p"}, Tags: []string{"todo"}},+ Actions: []*av.AutomationAction{{Type: "collect", Target: "current", Fields: map[string]*av.AutomationValue{+ keyID: {Mode: "static", Value: &av.Value{Type: av.KeyTypeText, Text: &av.ValueText{Content: "New"}}},+ }}},+ }}}+ av.SetAVBoxID(view.ID, box)+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ readView := func(want int) *av.AttributeView {+ t.Helper()+ stored, err := av.ParseAttributeViewForIndexInBox(view.ID, box)+ if err != nil || len(stored.GetBlockKeyValues().Values) != want {+ t.Fatalf("private collection rows: want=%d view=%+v err=%v", want, stored, err)+ }+ return stored+ }+ source, _, err := filesys.ReadTreeSnapshot(box, root.Path)+ if err != nil {+ t.Fatal(err)+ }+ original := structuredTitlesCiphertext(t, root)+ if err = DuplicateDoc(source); err != nil {+ t.Fatal(err)+ }+ readView(1)+ assertEncryptedFileBytes(t, filepath.Join(util.DataDir, box, root.Path), original)+ if _, err = DuplicateDocTree(root.ID); err != nil {+ t.Fatal(err)+ }+ view = readView(3)+ assertEncryptedFileBytes(t, filepath.Join(util.DataDir, box, root.Path), original)+ view.Automations.Rules[0].BlockSource.NotebookIDs = nil+ view.Automations.Rules[0].BlockSource.DocumentIDs = []string{target.ID}+ if err = av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ if err = MoveDocs([]string{root.Path}, box, target.Path, nil); err != nil {+ t.Fatal(err)+ }+ readView(5)+ current := treenode.GetBlockTreeInExactBox(root.ID, box)+ if current == nil {+ t.Fatal("moved encrypted source disappeared")+ }+ template := filepath.Join(util.DataDir, "templates", "encrypted-collection.md")+ if err = os.MkdirAll(filepath.Dir(template), 0755); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(template, []byte("#todo#"), 0600); err != nil {+ t.Fatal(err)+ }+ if err = applyDocContentTemplate(filepath.Base(template), root.ID); err != nil {+ t.Fatal(err)+ }+ view = readView(6)+ sql.FlushQueue()+ for _, row := range view.GetBlockKeyValues().Values {+ if sql.GetBlock(row.Block.ID) != nil {+ t.Fatal("private collection leaked into the global index")+ }+ }+ if _, err = os.Stat(filepath.Join(util.DataDir, "storage", "av", view.ID+".json")); !os.IsNotExist(err) {+ t.Fatal("private collection created a plaintext database")+ }+ if err = filepath.WalkDir(filepath.Join(util.DataDir, box), func(p string, entry os.DirEntry, walkErr error) error {+ if walkErr != nil {+ return walkErr+ }+ if entry.IsDir() || !strings.HasSuffix(p, ".sy") {+ return nil+ }+ data, err := os.ReadFile(p)+ if err != nil || !util.IsCiphertext(data) {+ t.Fatalf("encrypted document became plaintext: %s %v", p, err)+ }+ relative, err := filepath.Rel(filepath.Join(util.DataDir, box), p)+ if err != nil {+ return err+ }+ _, _, err = filesys.ReadTreeSnapshot(box, "/"+filepath.ToSlash(relative))+ return err+ }); err != nil {+ t.Fatal(err)+ }+}diff --git a/kernel/model/document_move.go b/kernel/model/document_move.goindex 867b982eef..7a0aae0335 100644--- a/kernel/model/document_move.go+++ b/kernel/model/document_move.go@@ -15,6 +15,11 @@ import (// preflightDocumentMove 检查整棵子树,未知格式、认证失败和目标冲突都先于首次改动。func preflightDocumentMove(fromBox, fromPath, toBox, toPath string) ([]*treenode.BlockTree, error) {+ return preflightDocumentMoveSnapshots(fromBox, fromPath, toBox, toPath, nil)+}++func preflightDocumentMoveSnapshots(fromBox, fromPath, toBox, toPath string,+ visit func(before *parse.Tree, destination string)) ([]*treenode.BlockTree, error) {if err := filesys.CheckDocumentAddressing(toBox); err != nil {return nil, err}@@ -63,6 +68,9 @@ func preflightDocumentMove(fromBox, fromPath, toBox, toPath string) ([]*treenodedocuments = append(documents,&treenode.BlockTree{BoxID: fromBox, ID: tree.ID, RootID: tree.ID, Path: sourcePath, Type: "d"},&treenode.BlockTree{BoxID: toBox, ID: tree.ID, RootID: tree.ID, Path: destination, Type: "d"})+ if visit != nil {+ visit(tree, destination)+ }return nil})return documents, errdiff --git a/kernel/model/duplicate_doc_hpath_test.go b/kernel/model/duplicate_doc_hpath_test.goindex 98930ce5a5..627d8eb2bb 100644--- a/kernel/model/duplicate_doc_hpath_test.go+++ b/kernel/model/duplicate_doc_hpath_test.go@@ -80,7 +80,9 @@ func TestDuplicateDocHPath(t *testing.T) {if err != nil || util.IsCiphertext(before) != encrypted {t.Fatalf("invalid source fixture: encrypted=%v, %v", encrypted, err)}- DuplicateDoc(source)+ if err := DuplicateDoc(source); err != nil {+ t.Fatal(err)+ }title := source.Root.IALAttr("title")wantHPath := parentHPath + "/" + titleif source.HPath != wantHPath || !strings.HasPrefix(title, "Example Document (Duplicated ") {diff --git a/kernel/model/duplicate_doc_tree.go b/kernel/model/duplicate_doc_tree.goindex b887c75c8b..3e3f851ffa 100644--- a/kernel/model/duplicate_doc_tree.go+++ b/kernel/model/duplicate_doc_tree.go@@ -323,11 +323,15 @@ func (plan *duplicateDocTreePlan) commit(writeTree func(*parse.Tree) (uint64, ercache.RemoveTreeDataInBox(tree.ID, tree.Box)cache.RemoveDocIALInBox(tree.Path, tree.Box)treenode.RemoveBlockTreesByRootID(tree.Box, tree.ID)+ sql.RemoveTreeQueue(tree.Box, tree.ID)// 只删除空的副本目录,保留并发写入或无法清理的数据。if i > 0 {_ = os.Remove(filepath.Dir(abs))}}+ for _, node := range plan.avNodes {+ av.RemoveBlockRel(node.AttributeViewID, node.ID, func(string) bool { return true })+ }}()for _, tree := range plan.trees {attempted = append(attempted, tree)@@ -373,5 +377,14 @@ func (plan *duplicateDocTreePlan) commit(writeTree func(*parse.Tree) (uint64, eravBoxID = plan.boxID}err = av.AddCopiedBlockRels(avBoxID, plan.avNodes)+ if err != nil {+ return err+ }+ before := map[string]*parse.Tree{}+ for _, tree := range plan.trees {+ treenode.UpsertBlockTree(tree)+ before[tree.ID] = nil+ }+ err = collectDocumentChanges(before, plan.trees)return}diff --git a/kernel/model/file.go b/kernel/model/file.goindex abdc2562fe..2fe48d33b0 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -1283,7 +1283,7 @@ func renameWriteJSONQueue(tree *parse.Tree) (err error) {return}-func DuplicateDoc(tree *parse.Tree) {+func DuplicateDoc(tree *parse.Tree) error {msgId := util.PushMsg(Conf.Language(116), 30000)defer util.PushClearMsg(msgId)@@ -1310,7 +1310,9 @@ func DuplicateDoc(tree *parse.Tree) {return ast.WalkContinue})- createTreeTx(tree)+ if err := performCreateDocTransaction(tree, true); err != nil {+ return err+ }box := Conf.Box(tree.Box)if nil != box {box.addSort(previousPath, tree.ID)@@ -1320,8 +1322,10 @@ func DuplicateDoc(tree *parse.Tree) {arg := map[string]any{}arg["listDocTree"] = truePushCreate(box, tree.Path, arg)+ return nil}+// Repository recovery rebuilds existing data and must not trigger user automations.func createTreeTx(tree *parse.Tree) {transaction := &Transaction{DoOperations: []*Operation{{Action: "create", Tree: tree}}}PerformTransactions(&[]*Transaction{transaction})@@ -1843,10 +1847,22 @@ func moveDocs(fromPaths []string, toBoxID, toPath string, callback any, placeByCfor _, queued := range takeQueuedTransactions() {flushTx(queued)}+ collectionIndex, err := documentCollectionIndex(toBoxID)+ if err != nil {+ return err+ }+ collectionBefore := map[string]map[string]*parse.Tree{}for _, fromPath := range fromPaths {- if _, err = preflightDocumentMove(pathsBoxes[fromPath].ID, fromPath, toBoxID, toPath); err != nil {+ before := map[string]*parse.Tree{}+ if _, err = preflightDocumentMoveSnapshots(pathsBoxes[fromPath].ID, fromPath, toBoxID, toPath,+ func(tree *parse.Tree, destination string) {+ if collectionIndex != nil && collectionIndex.MatchesDocument(toBoxID, tree.ID, destination) {+ before[tree.ID] = tree+ }+ }); err != nil {return}+ collectionBefore[fromPath] = before}luteEngine := util.NewLute()refresh := newMoveDocsRefresh()@@ -1855,6 +1871,8 @@ func moveDocs(fromPaths []string, toBoxID, toPath string, callback any, placeByCconfFileTreeSnapshot := Conf.LoadFileTree()if 0 < len(movedDocs) {+ cache.ClearDocsIAL()+ IncSync()// 部分移动失败时也保存已完成文档的整组顺序,再通知前端刷新。if placeByConf {ids := make([]string, 0, len(movedDocs))@@ -1896,9 +1914,25 @@ func moveDocs(fromPaths []string, toBoxID, toPath string, callback any, placeByCToPath: toPath,NewPath: newPath,})+ before := collectionBefore[fromPath]+ var after []*parse.Tree+ for id := range before {+ bt := treenode.GetBlockTreeInExactBox(id, toBoxID)+ if bt == nil {+ return ErrBlockNotFound+ }+ tree, _, readErr := filesys.ReadTreeSnapshot(toBoxID, bt.Path)+ if readErr != nil {+ return readErr+ }+ after = append(after, tree)+ }+ if len(after) > 0 {+ if err = collectDocumentChanges(before, after); err != nil {+ return+ }+ }}- cache.ClearDocsIAL()- IncSync()return}diff --git a/kernel/model/template.go b/kernel/model/template.goindex ad61573f13..a56c79ee0e 100644--- a/kernel/model/template.go+++ b/kernel/model/template.go@@ -1328,7 +1328,17 @@ func applyDocContentTemplateAt(templatePath, docID string, now *time.Time) errorif "" == templateDOM {return nil}- tree, err := LoadTreeByBlockID(docID)+ FlushTxQueue()+ flushLock.Lock()+ defer flushLock.Unlock()+ for _, queued := range takeQueuedTransactions() {+ flushTx(queued)+ }+ bt, err := lookupBlockTreeInBox(docID, "", true)+ if err != nil {+ return err+ }+ tree, original, err := filesys.LoadTreeSnapshot(bt.BoxID, bt.Path, util.NewLute())if nil != err {return err}@@ -1351,9 +1361,27 @@ func applyDocContentTemplateAt(templatePath, docID string, now *time.Time) error}}tree.Root.SetIALAttr("updated", util.CurrentTimeSecondsStr())- if err = indexWriteTreeUpsertQueue(tree); nil != err {+ write := func(changed *parse.Tree) error {+ size, writeErr := filesys.WriteTreeIfUnchanged(changed, original)+ if writeErr != nil {+ return writeErr+ }+ treenode.UpsertBlockTree(changed)+ sql.UpsertTreeQueue(changed)+ refreshDocInfoWithSize(changed, size)+ return nil+ }+ handled, err := writeDocumentWithCollections(tree, write)+ if err != nil {return err}+ if !handled {+ if err = write(tree); err != nil {+ return err+ }+ IncSync()+ }+ invalidateDocumentHistory(tree.ID)av.BatchUpsertBlockRel(tree.Root.ChildrenByType(ast.NodeAttributeView))return nil}