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 original database item bindings on undo https://github.com/siyuan-note/siyuan/issues/10907
Daniel56c22cb936f2
diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.tsindex fb500ba1c2..af75091f17 100644--- a/app/src/protyle/hint/index.ts+++ b/app/src/protyle/hint/index.ts@@ -59,6 +59,8 @@ import {isNotCtrl, isOnlyMeta} from "../util/compatibility";import {avRender} from "../render/av/render";import {genIconHTML} from "../render/util";import {updateAttrViewCellAnimation} from "../render/av/action";+import {getAVBindingOperations} from "../render/av/binding";+import {genCellValueByElement} from "../render/av/cell";import {setFold} from "../util/blockFold";import {getIconValueKind} from "../../emoji/iconValue";import {getCreateTargetContext, isSameCreateTargetContext} from "./createTargetContext";@@ -771,6 +773,7 @@ ${genHintItemHTML(item)}}const previousID = rowElement.dataset.id;const avID = nodeElement.getAttribute("data-av-id");+ const previousValue = genCellValueByElement("block", cellElement);let tempElement = document.createElement("div");tempElement.innerHTML = value.replace(/<mark>/g, "").replace(/<\/mark>/g, "");tempElement = tempElement.firstElementChild as HTMLDivElement;@@ -781,22 +784,9 @@ ${genHintItemHTML(item)}const realFileName = fileNames.length === 1 ? fileNames[0] : fileNames[1];const newID = Lute.NewNodeID();const bindNewDoc = () => {- transaction(protyle, [{- action: "replaceAttrViewBlock",- avID,- previousID,- nextID: newID,- isDetached: false,- blockID: nodeElement.dataset.nodeId,- context: {protyleID: protyle.id},- }], [{- action: "replaceAttrViewBlock",- avID,- previousID,- isDetached: true,- blockID: nodeElement.dataset.nodeId,- context: {protyleID: protyle.id},- }]);+ const operations = getAVBindingOperations(avID, previousID, newID, nodeElement.dataset.nodeId,+ previousValue, {protyleID: protyle.id});+ transaction(protyle, operations.doOperations, operations.undoOperations);};if (isNewSubDoc) {newSubDocByRefHint(protyle, realFileName, bindNewDoc, newID);@@ -810,22 +800,9 @@ ${genHintItemHTML(item)}});} else {const sourceId = tempElement.getAttribute("data-id");- transaction(protyle, [{- action: "replaceAttrViewBlock",- avID,- previousID,- nextID: sourceId,- isDetached: false,- blockID: nodeElement.dataset.nodeId,- context: {protyleID: protyle.id},- }], [{- action: "replaceAttrViewBlock",- avID,- previousID,- isDetached: true,- blockID: nodeElement.dataset.nodeId,- context: {protyleID: protyle.id},- }]);+ const operations = getAVBindingOperations(avID, previousID, sourceId, nodeElement.dataset.nodeId,+ previousValue, {protyleID: protyle.id});+ transaction(protyle, operations.doOperations, operations.undoOperations);updateAttrViewCellAnimation(cellElement, {type: "block",isDetached: false,diff --git a/app/src/protyle/render/av/binding.test.ts b/app/src/protyle/render/av/binding.test.tsnew file mode 100644index 0000000000..8e121e9e5f--- /dev/null+++ b/app/src/protyle/render/av/binding.test.ts@@ -0,0 +1,23 @@+import * as assert from "node:assert/strict";+import {test} from "node:test";+import {getAVBindingOperations} from "./binding";++for (const isDetached of [false, true]) {+ test(`binding operations preserve item identity and the ${isDetached ? "detached" : "bound"} original`, () => {+ const operations = getAVBindingOperations("database", "item", "new-block", "carrier", {+ type: "block", isDetached, block: {id: isDetached ? "" : "old-block", content: "Original"},+ }, {protyleID: "editor"});+ const {doOperations, undoOperations} = JSON.parse(JSON.stringify(operations));+ for (const operation of [...doOperations, ...undoOperations]) {+ assert.equal(operation.action, "replaceAttrViewBlock");+ assert.equal(operation.avID, "database");+ assert.equal(operation.previousID, "item");+ assert.equal(operation.blockID, "carrier");+ assert.deepEqual(operation.context, {protyleID: "editor"});+ }+ assert.equal(doOperations[0].nextID, "new-block");+ assert.equal(doOperations[0].isDetached, false);+ assert.equal(undoOperations[0].nextID, isDetached ? "" : "old-block");+ assert.equal(undoOperations[0].isDetached, isDetached);+ });+}diff --git a/app/src/protyle/render/av/binding.ts b/app/src/protyle/render/av/binding.tsnew file mode 100644index 0000000000..8877a9d50e--- /dev/null+++ b/app/src/protyle/render/av/binding.ts@@ -0,0 +1,10 @@+// 条目 ID 在换绑前后保持不变,绑定块 ID 只用于指定目标。+export const getAVBindingOperations = (avID: string, itemID: string, nextID: string, blockID: string,+ previousValue: IAVCellValue, context?: Record<string, string>) => {+ const base = {action: "replaceAttrViewBlock" as const, avID, previousID: itemID, blockID, context};+ const isDetached = previousValue.isDetached === true || !previousValue.block?.id;+ return {+ doOperations: [{...base, nextID, isDetached: false}] as IOperation[],+ undoOperations: [{...base, nextID: isDetached ? "" : previousValue.block.id, isDetached}] as IOperation[],+ };+};diff --git a/app/src/protyle/util/insertHTML.ts b/app/src/protyle/util/insertHTML.tsindex d8e6bc3deb..5b973f0fee 100644--- a/app/src/protyle/util/insertHTML.ts+++ b/app/src/protyle/util/insertHTML.ts@@ -30,7 +30,8 @@ import {highlightRender} from "../render/highlightRender";import {scrollCenter} from "../../util/highlightById";import {updateAttrViewCellAnimation, updateAVName} from "../render/av/action";import {getDefaultDateFormat} from "../render/av/dateFormat";-import {genCellValue, updateCellsValue} from "../render/av/cell";+import {genCellValue, genCellValueByElement, updateCellsValue} from "../render/av/cell";+import {getAVBindingOperations} from "../render/av/binding";import {input} from "../wysiwyg/input";import {updateListOrder} from "../wysiwyg/list";import {fetchPost, fetchSyncPost} from "../../util/fetch";@@ -738,19 +739,9 @@ const processAV = (range: Range, html: string, protyle: IProtyle, blockElement:if (selectCellElement) {const sourceId = contenteditableElement.firstElementChild.getAttribute("data-id");const previousID = getFieldIdByCellElement(selectCellElement, blockElement.getAttribute("data-av-type") as TAVView);- transaction(protyle, [{- action: "replaceAttrViewBlock",- avID,- previousID,- nextID: sourceId,- isDetached: false,- }], [{- action: "replaceAttrViewBlock",- avID,- previousID: sourceId,- nextID: previousID,- isDetached: selectCellElement.dataset.detached === "true",- }]);+ const operations = getAVBindingOperations(avID, previousID, sourceId, blockElement.dataset.nodeId,+ genCellValueByElement("block", selectCellElement), {protyleID: protyle.id});+ transaction(protyle, operations.doOperations, operations.undoOperations);updateAttrViewCellAnimation(selectCellElement, {type: "block",isDetached: false,diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.goindex f8330aa336..6a1ec002e2 100644--- a/kernel/model/attribute_view.go+++ b/kernel/model/attribute_view.go@@ -7778,11 +7778,9 @@ func RemoveAttributeViewKey(avID, keyID string, removeRelationDest bool) (err er}func (tx *Transaction) doReplaceAttrViewBlock(operation *Operation) (ret *TxErr) {- targetItemID, duplicate, err := replaceAttributeViewBlock(operation.AvID, operation.PreviousID, operation.NextID, operation.IsDetached, tx)- if err != nil {- return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID}+ if err := tx.replaceAttributeViewBinding(operation); err != nil {+ return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID, msg: err.Error()}}- operation.RetData = map[string]any{"targetItemID": targetItemID, "duplicate": duplicate}return}diff --git a/kernel/model/attribute_view_binding_undo.go b/kernel/model/attribute_view_binding_undo.gonew file mode 100644index 0000000000..557c98e339--- /dev/null+++ b/kernel/model/attribute_view_binding_undo.go@@ -0,0 +1,214 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "fmt"+ "slices"+ "strings"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// 换绑快照只保留主键值,条目 ID 和其他字段值始终保持不变。+type attributeViewBindingSnapshot struct {+ avID, blockID, boxID string+ before, after *av.Value+ duplicateItemID string+}++func (tx *Transaction) replaceAttributeViewBinding(op *Operation) error {+ state := op.attributeViewBinding+ if state != nil {+ if !tx.isReplay || state.avID != op.AvID || state.before.BlockID != op.PreviousID {+ return fmt.Errorf("invalid database binding replay")+ }+ current, err := tx.readAttributeViewForMutation(state.avID, state.blockID, state.boxID)+ if err != nil {+ return err+ }+ if state.duplicateItemID != "" {+ op.RetData = map[string]any{"targetItemID": state.duplicateItemID, "duplicate": true}+ return nil+ }+ expected, desired := state.before, state.after+ if op.attributeViewBindingUndo {+ expected, desired = desired, expected+ }+ value := current.GetBlockValue(expected.BlockID)+ if value == nil || value.Block == nil || value.ID != expected.ID || value.KeyID != expected.KeyID ||+ value.IsDetached != expected.IsDetached || value.Block.ID != expected.Block.ID {+ return fmt.Errorf("database entry binding [%s] changed", expected.BlockID)+ }+ if err = tx.applyAttributeViewBinding(current, value, desired, state); err != nil {+ return err+ }+ op.RetData = map[string]any{"targetItemID": value.BlockID, "duplicate": false}+ return nil+ }++ var inverse *Operation+ if tx.fromAPI && !tx.isReplay {+ for _, undo := range tx.UndoOperations {+ if undo.Action == "replaceAttrViewBlock" && undo.AvID == op.AvID &&+ undo.PreviousID == op.PreviousID && undo.attributeViewBinding == nil {+ inverse = undo+ break+ }+ }+ }+ blockID := op.BlockID+ if blockID == "" {+ for _, operation := range tx.DoOperations {+ if operation.Action == "doUpdateUpdated" {+ blockID = operation.ID+ break+ }+ }+ }+ if _, err := avParseView(op.AvID, blockID); err != nil {+ return err+ }+ state = &attributeViewBindingSnapshot{avID: op.AvID, blockID: blockID, boxID: av.GetAVBoxID(op.AvID)}+ current, err := tx.readAttributeViewForMutation(op.AvID, blockID, state.boxID)+ if err != nil {+ return err+ }+ value := current.GetBlockValue(op.PreviousID)+ if value == nil || value.Block == nil {+ return av.ErrItemNotFound+ }+ state.before = value.Clone()+ desired := value.Clone()+ desired.IsDetached, desired.Block.ID = op.IsDetached, op.NextID+ if op.IsDetached {+ desired.Block.ID, desired.Block.RefSubtype = "", ""+ } else if existing := current.GetBlockValueByBoundID(op.NextID); existing != nil && existing.BlockID != value.BlockID {+ // 重复绑定仅定位到已有条目,撤销和重做都不能修改两个条目的绑定。+ node, tree, loadErr := getNodeByBlockID(tx, op.NextID)+ if loadErr != nil {+ return loadErr+ }+ if node == nil {+ return ErrBlockNotFound+ }+ if err = validateAttributeViewBinding(current.ID, tree); err != nil {+ return err+ }+ state.duplicateItemID = existing.BlockID+ }+ if state.duplicateItemID == "" {+ if err = tx.applyAttributeViewBinding(current, value, desired, state); err != nil {+ return err+ }+ } else if err = tx.rememberAttributeViewMutationTree(blockID); err != nil {+ return err+ }+ state.after = value.Clone()+ if inverse != nil {+ op.attributeViewBinding, inverse.attributeViewBinding = state, state+ inverse.attributeViewBindingUndo = true+ }+ targetItemID := value.BlockID+ if state.duplicateItemID != "" {+ targetItemID = state.duplicateItemID+ }+ op.RetData = map[string]any{"targetItemID": targetItemID, "duplicate": state.duplicateItemID != ""}+ return nil+}++func (tx *Transaction) applyAttributeViewBinding(current *av.AttributeView, value, desired *av.Value,+ state *attributeViewBindingSnapshot) error {+ if !desired.IsDetached {+ if existing := current.GetBlockValueByBoundID(desired.Block.ID); existing != nil && existing.BlockID != value.BlockID {+ return fmt.Errorf("database block [%s] is already bound", desired.Block.ID)+ }+ }+ ids := []string{}+ if !value.IsDetached {+ ids = append(ids, value.Block.ID)+ }+ if !desired.IsDetached && !slices.Contains(ids, desired.Block.ID) {+ ids = append(ids, desired.Block.ID)+ }+ nodes, trees := map[string]*ast.Node{}, map[string]*parse.Tree{}+ for _, id := range ids {+ node, tree, err := getNodeByBlockID(tx, id)+ if err != nil {+ return err+ }+ if node == nil {+ return ErrBlockNotFound+ }+ if err = validateAttributeViewBinding(current.ID, tree); err != nil {+ return err+ }+ nodes[id], trees[id] = node, tree+ }+ restoredDocs := append(append([]*parse.Tree{}, tx.restoredCreatedDocs...), tx.restoredTemplateCreatedDocs...)+ for _, id := range append([]string{state.blockID}, ids...) {+ // 本事务恢复的文档由创建文档事务负责回滚,此时可能尚未写入磁盘。+ if slices.ContainsFunc(restoredDocs, func(tree *parse.Tree) bool {+ return trees[id] != nil && tree.ID == trees[id].ID+ }) {+ continue+ }+ if err := tx.rememberAttributeViewMutationTree(id); err != nil {+ return err+ }+ }+ key := state.boxID + "/" + current.ID+ if tx.attributeViewRollback.views[key] == nil {+ original, err := cloneAttributeViewForFieldMutation(current)+ if err != nil {+ return err+ }+ tx.attributeViewRollback.views[key] = original+ }+ for _, id := range ids {+ bound := !desired.IsDetached && id == desired.Block.ID+ avIDs := strings.Split(nodes[id].IALAttr(av.NodeAttrNameAvs), ",")+ avIDs = slices.DeleteFunc(avIDs, func(id string) bool { return id == "" || (!bound && id == current.ID) })+ if bound && !slices.Contains(avIDs, current.ID) {+ avIDs = append(avIDs, current.ID)+ }+ avs := strings.Join(avIDs, ",")+ if err := setNodeAttrsWithTx(tx, nodes[id], trees[id], map[string]string{+ av.NodeAttrNameAvs: avs, av.NodeAttrViewNames: getAvNames(avs),+ }); err != nil {+ return err+ }+ }+ block := desired.Clone().Block+ block.Created, block.Updated = value.Block.Created, value.Block.Updated+ value.IsDetached, value.Block = desired.IsDetached, block+ if !value.IsDetached {+ node := nodes[value.Block.ID]+ icon, content := getNodeAvBlockText(node, current.ID)+ value.Block.Icon, value.Block.Content = icon, util.UnescapeHTML(content)+ value.Block.RefSubtype = getNodeAvBlockRefSubtype(node, current.ID)+ }+ regenAttrViewGroups(current)+ if err := avSaveView(current, state.blockID); err != nil {+ return err+ }+ refreshRelatedSrcAvsInBlock(current.ID, state.blockID, tx)+ return nil+}diff --git a/kernel/model/attribute_view_binding_undo_fts5_test.go b/kernel/model/attribute_view_binding_undo_fts5_test.gonew file mode 100644index 0000000000..94f0f0e6d7--- /dev/null+++ b/kernel/model/attribute_view_binding_undo_fts5_test.go@@ -0,0 +1,242 @@+//go:build fts5++package model++import (+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "slices"+ "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/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAttributeViewBindingUndoRedo(t *testing.T) {+ for _, bound := range []bool{false, true} {+ t.Run(map[bool]string{false: "detached", true: "bound"}[bound], func(t *testing.T) {+ fixture, before, tx := setupAttributeViewBindingUndoTest(t, bound)+ if err := PerformTxSync(tx); err != nil {+ t.Fatal(err)+ }+ entry := GlobalUndoLog.Peek(fixture.sourceID)+ if entry == nil {+ t.Fatal("binding did not enter the database document undo log")+ }+ itemID := tx.DoOperations[0].PreviousID+ data, err := json.Marshal(tx)+ if err != nil || strings.Contains(string(data), "Original primary") {+ t.Fatalf("private primary snapshot leaked into response: %s, %v", data, err)+ }+ after := readAttributeViewItemsTest(t, before.ID)+ if after.GetBlockValue(itemID).Block.ID != fixture.sourceID {+ t.Fatal("replacement did not bind the new block")+ }+ for cycle := 0; cycle < 3; cycle++ {+ assertAttributeViewBindingBacklink(t, fixture.targetID, before.ID, false)+ assertAttributeViewBindingBacklink(t, fixture.sourceID, before.ID, true)+ if err = PerformTxSync(&Transaction{DoOperations: entry.UndoOperationsForReplay(), isReplay: true}); err != nil {+ t.Fatal(err)+ }+ assertAttributeViewItemsEqual(t, before, readAttributeViewItemsTest(t, before.ID))+ assertAttributeViewBindingBacklink(t, fixture.targetID, before.ID, bound)+ assertAttributeViewBindingBacklink(t, fixture.sourceID, before.ID, false)+ if err = PerformTxSync(&Transaction{DoOperations: entry.DoOperationsForReplay(), isReplay: true}); err != nil {+ t.Fatal(err)+ }+ assertAttributeViewItemsEqual(t, after, readAttributeViewItemsTest(t, before.ID))+ }+ })+ }+}++func TestAttributeViewBindingUndoPreservesOtherEdits(t *testing.T) {+ fixture, before, tx := setupAttributeViewBindingUndoTest(t, true)+ if err := PerformTxSync(tx); err != nil {+ t.Fatal(err)+ }+ current := readAttributeViewItemsTest(t, before.ID)+ for _, view := range []*av.AttributeView{before, current} {+ view.Name = "New database name"+ view.KeyValues[2].Values[1].Text.Content = "Later field edit"+ view.GetBlockValue(tx.DoOperations[0].PreviousID).Block.Updated = 789+ }+ if err := av.SaveAttributeView(current); err != nil {+ t.Fatal(err)+ }+ if err := PerformTxSync(&Transaction{DoOperations: GlobalUndoLog.Peek(fixture.sourceID).UndoOperationsForReplay(), isReplay: true}); err != nil {+ t.Fatal(err)+ }+ assertAttributeViewItemsEqual(t, before, readAttributeViewItemsTest(t, before.ID))+}++func TestAttributeViewBindingCreatedDocumentReplay(t *testing.T) {+ fixture, before, tx := setupAttributeViewBindingUndoTest(t, false)+ docID := ast.NewNodeID()+ tree := treenode.NewTree(fixture.box.ID, "/"+docID+".sy", "/Created", "Created")+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ op := tx.DoOperations[0]+ op.NextID = docID+ tx.DoOperations = append([]*Operation{{Action: "restoreCreatedDoc", ID: docID, Tree: tree}}, tx.DoOperations...)+ tx.UndoOperations = append(tx.UndoOperations, &Operation{Action: "removeCreatedDoc", ID: docID, Tree: tree})+ if err := PerformTxSync(tx); err != nil {+ t.Fatal(err)+ }+ entry := GlobalUndoLog.Peek(fixture.sourceID)+ for cycle := 0; cycle < 2; cycle++ {+ if err := PerformTxSync(&Transaction{DoOperations: entry.UndoOperationsForReplay(), isReplay: true}); err != nil {+ t.Fatal(err)+ }+ assertAttributeViewItemsEqual(t, before, readAttributeViewItemsTest(t, before.ID))+ if _, err := os.Stat(filepath.Join(util.DataDir, fixture.box.ID, tree.Path)); !os.IsNotExist(err) {+ t.Fatalf("undo did not remove the created document: %v", err)+ }+ if err := PerformTxSync(&Transaction{DoOperations: entry.DoOperationsForReplay(), isReplay: true}); err != nil {+ t.Fatal(err)+ }+ current := readAttributeViewItemsTest(t, before.ID)+ if current.GetBlockValue(op.PreviousID).Block.ID != docID {+ t.Fatal("redo did not restore the created document binding")+ }+ assertAttributeViewBindingBacklink(t, docID, before.ID, true)+ }+}++func TestAttributeViewBindingDuplicateUndo(t *testing.T) {+ fixture, before, tx := setupAttributeViewBindingUndoTest(t, true)+ other := before.GetBlockKeyValues().Values[0]+ other.IsDetached, other.Block.ID = false, fixture.sourceID+ if err := av.SaveAttributeView(before); err != nil {+ t.Fatal(err)+ }+ if err := PerformTxSync(tx); err != nil {+ t.Fatal(err)+ }+ result := tx.DoOperations[0].RetData.(map[string]any)+ if result["duplicate"] != true || result["targetItemID"] != other.BlockID {+ t.Fatalf("duplicate binding did not locate the existing item: %v", result)+ }+ entry := GlobalUndoLog.Peek(fixture.sourceID)+ for _, operations := range [][]*Operation{entry.UndoOperationsForReplay(), entry.DoOperationsForReplay()} {+ if err := PerformTxSync(&Transaction{DoOperations: operations, isReplay: true}); err != nil {+ t.Fatal(err)+ }+ assertAttributeViewItemsEqual(t, before, readAttributeViewItemsTest(t, before.ID))+ assertAttributeViewBindingBacklink(t, fixture.targetID, before.ID, true)+ }+}++func TestAttributeViewBindingReplayConflict(t *testing.T) {+ for _, conflict := range []string{"duplicate", "changed", "missing"} {+ t.Run(conflict, func(t *testing.T) {+ fixture, before, tx := setupAttributeViewBindingUndoTest(t, true)+ if err := PerformTxSync(tx); err != nil {+ t.Fatal(err)+ }+ current := readAttributeViewItemsTest(t, before.ID)+ switch conflict {+ case "duplicate":+ other := current.GetBlockKeyValues().Values[0]+ other.IsDetached, other.Block.ID = false, fixture.targetID+ case "changed":+ value := current.GetBlockValue(tx.DoOperations[0].PreviousID)+ value.IsDetached, value.Block.ID = true, ""+ case "missing":+ treenode.RemoveBlockTree(fixture.box.ID, fixture.targetID)+ }+ if err := av.SaveAttributeView(current); err != nil {+ t.Fatal(err)+ }+ if err := PerformTxSync(&Transaction{DoOperations: GlobalUndoLog.Peek(fixture.sourceID).UndoOperationsForReplay(), isReplay: true}); err == nil {+ t.Fatal("conflicting binding replay succeeded")+ }+ assertAttributeViewItemsEqual(t, current, readAttributeViewItemsTest(t, before.ID))+ assertAttributeViewBindingBacklink(t, fixture.sourceID, before.ID, true)+ })+ }+}++func TestAttributeViewBindingWriteFailure(t *testing.T) {+ for _, undo := range []bool{false, true} {+ t.Run(map[bool]string{false: "replace", true: "undo"}[undo], func(t *testing.T) {+ fixture, before, tx := setupAttributeViewBindingUndoTest(t, true)+ if undo {+ if err := PerformTxSync(tx); err != nil {+ t.Fatal(err)+ }+ tx = &Transaction{DoOperations: GlobalUndoLog.Peek(fixture.sourceID).UndoOperationsForReplay(), isReplay: true}+ }+ before = readAttributeViewItemsTest(t, before.ID)+ writes := 0+ tx.writeTransactionTree = func(tree *parse.Tree) error {+ writes+++ if writes == 2 {+ return errors.New("injected binding write failure")+ }+ _, err := filesys.WriteTree(tree)+ return err+ }+ if err := PerformTxSync(tx); err == nil || !strings.Contains(err.Error(), "injected binding write failure") {+ t.Fatalf("unexpected write result: %v", err)+ }+ assertAttributeViewItemsEqual(t, before, readAttributeViewItemsTest(t, before.ID))+ assertAttributeViewBindingBacklink(t, fixture.targetID, before.ID, !undo)+ assertAttributeViewBindingBacklink(t, fixture.sourceID, before.ID, undo)+ })+ }+}++func setupAttributeViewBindingUndoTest(t *testing.T, bound bool) (*fileOperationTestFixture, *av.AttributeView, *Transaction) {+ t.Helper()+ fixture, view, deletion, _ := setupAttributeViewItemsTest(t, bound)+ value := view.GetBlockValue(deletion.SrcIDs[0])+ value.Block.Content, value.Block.Icon = "Original primary", "1f600"+ if bound {+ tree, err := LoadTreeByBlockID(fixture.targetID)+ if err != nil {+ t.Fatal(err)+ }+ tree.Root.SetIALAttr(av.NodeAttrViewStaticText+"-"+view.ID, value.Block.Content)+ tree.Root.SetIALAttr("icon", value.Block.Icon)+ if _, err = filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ value.Block.RefSubtype = av.BlockRefSubtypeStatic+ }+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ op := &Operation{Action: "replaceAttrViewBlock", AvID: view.ID, BlockID: fixture.sourceID,+ PreviousID: value.BlockID, NextID: fixture.sourceID}+ // 前端可能只发送取消绑定,内核必须以执行前的真实状态恢复原绑定和主键文本。+ inverse := &Operation{Action: "replaceAttrViewBlock", AvID: view.ID, BlockID: fixture.sourceID,+ PreviousID: value.BlockID, IsDetached: true}+ return fixture, readAttributeViewItemsTest(t, view.ID), &Transaction{+ DoOperations: []*Operation{op}, UndoOperations: []*Operation{inverse}, fromAPI: true}+}++func assertAttributeViewBindingBacklink(t *testing.T, blockID, avID string, bound bool) {+ t.Helper()+ tree, err := LoadTreeByBlockID(blockID)+ if err != nil {+ t.Fatal(err)+ }+ node := treenode.GetNodeInTree(tree, blockID)+ if slices.Contains(strings.Split(node.IALAttr(av.NodeAttrNameAvs), ","), avID) != bound {+ t.Fatalf("block [%s] has incorrect database bindings: %s", blockID, node.IALAttr(av.NodeAttrNameAvs))+ }+ if !bound && node.IALAttr(av.NodeAttrNameAvs) == "" && node.IALAttr(av.NodeAttrViewNames) != "" {+ t.Fatal("unbound block retained database names")+ }+}diff --git a/kernel/model/attribute_view_binding_undo_sqlcipher_test.go b/kernel/model/attribute_view_binding_undo_sqlcipher_test.gonew file mode 100644index 0000000000..1d94a91087--- /dev/null+++ b/kernel/model/attribute_view_binding_undo_sqlcipher_test.go@@ -0,0 +1,120 @@+//go:build fts5 && (sqlcipher || libsqlcipher)++package model++import (+ "bytes"+ "encoding/json"+ "os"+ "path/filepath"+ "testing"++ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAttributeViewBindingEncryptedReplay(t *testing.T) {+ fixture, before, tx := setupAttributeViewBindingUndoTest(t, true)+ boxID := fixture.box.ID+ var trees []*parse.Tree+ for _, id := range []string{fixture.sourceID, fixture.targetID} {+ tree, err := LoadTreeByBlockID(id)+ if err != nil {+ t.Fatal(err)+ }+ trees = append(trees, tree)+ }+ markRuntimeEncryptedBox(boxID)+ dek := bytes.Repeat([]byte{0x63}, 32)+ setDEKForTest(boxID, dek)+ boxConf := conf.NewBoxConf()+ boxConf.Encrypted = true+ boxConf.BoxCrypt = &conf.BoxEncryption{Spec: boxEncryptionSpec}+ if err := encryptBoxMetadata(boxID, boxConf, dek); err != nil {+ t.Fatal(err)+ }+ configData, err := json.Marshal(boxConf)+ if err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json"), configData, 0600); err != nil {+ t.Fatal(err)+ }+ mountedEncryptedBoxes.Store(boxID, true)+ oldTempDir := util.TempDir+ util.TempDir = t.TempDir()+ t.Cleanup(func() {+ treenode.CloseEncryptedBlockTreeDB(boxID)+ util.TempDir = oldTempDir+ })+ if err = treenode.OpenEncryptedBlockTreeDB(boxID, dek); err != nil {+ t.Fatal(err)+ }+ av.SetAVBoxID(before.ID, boxID)+ t.Cleanup(func() {+ mountedEncryptedBoxes.Delete(boxID)+ av.SetAVBoxID(before.ID, "")+ forgetRuntimeEncryptedBox(boxID)+ encryptedBoxLifecycles.Delete(boxID)+ cachedDEKsLock.Lock()+ delete(cachedDEKs, boxID)+ cachedDEKsLock.Unlock()+ })+ for _, tree := range trees {+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ }+ if err := av.SaveAttributeView(before); err != nil {+ t.Fatal(err)+ }+ plainPath := filepath.Join(util.DataDir, "storage", "av", before.ID+".json")+ if err := os.Remove(plainPath); err != nil {+ t.Fatal(err)+ }+ if err := PerformTxSync(tx); err != nil {+ t.Fatal(err)+ }+ for _, operations := range [][]*Operation{cloneOperations(tx.UndoOperations), cloneOperations(tx.DoOperations)} {+ if err := PerformTxSync(&Transaction{DoOperations: operations, isReplay: true}); err != nil {+ t.Fatal(err)+ }+ }+ path := filepath.Join(util.DataDir, boxID, "storage", "av", before.ID+".json")+ ciphertext, err := os.ReadFile(path)+ if err != nil || !util.IsCiphertext(ciphertext) {+ t.Fatalf("binding replay did not preserve encryption: %v", err)+ }+ if _, err = os.Stat(plainPath); !os.IsNotExist(err) {+ t.Fatalf("binding replay produced plaintext: %v", err)+ }+ for _, failure := range []string{"locked", "corrupted"} {+ t.Run(failure, func(t *testing.T) {+ if failure == "locked" {+ cachedDEKsLock.Lock()+ delete(cachedDEKs, boxID)+ cachedDEKsLock.Unlock()+ defer setDEKForTest(boxID, bytes.Repeat([]byte{0x63}, 32))+ } else {+ ciphertext[len(ciphertext)-1] ^= 1+ if err = os.WriteFile(path, ciphertext, 0600); err != nil {+ t.Fatal(err)+ }+ }+ cache.ClearAVCache()+ if err = PerformTxSync(&Transaction{DoOperations: cloneOperations(tx.UndoOperations), isReplay: true}); err == nil {+ t.Fatal("binding replay accepted inaccessible encrypted data")+ }+ preserved, readErr := os.ReadFile(path)+ if readErr != nil || !bytes.Equal(ciphertext, preserved) {+ t.Fatalf("failed replay changed encrypted data: %v", readErr)+ }+ })+ }+}diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex 03e51f89c4..fa89b1c52a 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -2228,6 +2228,10 @@ func (tx *Transaction) doRestoreCreatedDoc(operation *Operation) (ret *TxErr) {existing, loadErr = LoadTreeByBlockIDInExactBox(tree.Root.ID, tree.Box)} else {existing, loadErr = LoadTreeByBlockID(tree.Root.ID)+ if errors.Is(loadErr, ErrIndexing) {+ // 已知文档快照按原笔记本查找,后台索引任务不应阻止重做;下方仍检查目标文件是否存在。+ existing, loadErr = LoadTreeByBlockIDInExactBox(tree.Root.ID, tree.Box)+ }}if nil == loadErr && nil != existing {if "" != operation.templateDocTreeRootID || tx.isReplay || existing.Box != tree.Box || existing.Path != tree.Path {@@ -2389,14 +2393,16 @@ type Operation struct {BlockIDs []string `json:"blockIDs"` // move/append 时为随折叠标题移动的顶层块,闪卡操作时为目标块BlockID string `json:"blockID"`- DeckID string `json:"deckID"` // 用于添加/删除闪卡- Tree *parse.Tree `json:"-"` // 仅用于内核事务重放,不发送到前端- templateDocTreeRootID string- blockSwapState *blockSwapState- blockSwapUndo bool- attributeViewItems *attributeViewItemsSnapshot- attributeViewFields *attributeViewFieldsSnapshot- attributeViewFieldUndo bool+ DeckID string `json:"deckID"` // 用于添加/删除闪卡+ Tree *parse.Tree `json:"-"` // 仅用于内核事务重放,不发送到前端+ templateDocTreeRootID string+ blockSwapState *blockSwapState+ blockSwapUndo bool+ attributeViewItems *attributeViewItemsSnapshot+ attributeViewFields *attributeViewFieldsSnapshot+ attributeViewFieldUndo bool+ attributeViewBinding *attributeViewBindingSnapshot+ attributeViewBindingUndo boolLockType bool `json:"-"` // 外部块更新是否禁止改变主类型