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 undoing deleted database entries https://github.com/siyuan-note/siyuan/issues/10907
Daniel27717665afcb
diff --git a/app/src/protyle/render/av/deleteRow.test.ts b/app/src/protyle/render/av/deleteRow.test.tsnew file mode 100644index 0000000000..3268d0a85e--- /dev/null+++ b/app/src/protyle/render/av/deleteRow.test.ts@@ -0,0 +1,55 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";++const source = readFileSync("src/protyle/render/av/row.ts", "utf8");+const compiled = transpileModule(source.slice(source.indexOf("export const deleteRow ="),+ source.indexOf("export const insertRows =")), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++for (const binding of ["omitted", "bound", "detached"]) {+ test(`delete row undo preserves the ${binding} binding source over JSON`, () => {+ const primaryValue = {+ ...(binding === "omitted" ? {} : {isDetached: binding === "detached"}),+ block: {id: binding === "detached" ? "" : "bound-block", content: "Primary"},+ };+ let operations: any[];+ let inverse: any[];+ const exports: any = {};+ const blockElement = {+ dataset: {nodeId: "database-block"},+ getAttribute: (name: string) => name === "data-av-id" ? "database" : "20260916090000",+ setAttribute: () => {},+ querySelectorAll: (): HTMLElement[] => [],+ querySelector: (): HTMLElement | null => null,+ };+ runInNewContext(compiled, {+ exports,+ getAVSelectedItemInfos: () => [{+ itemID: "original-item", previousID: "previous", groupID: "group",+ primaryCell: {value: primaryValue},+ }],+ Lute: {NewNodeID: () => "restored-item"},+ dayjs: () => ({format: () => "20260916100000"}),+ transaction: (_protyle: any, doOperations: any[], undoOperations: any[]) => {+ operations = JSON.parse(JSON.stringify(doOperations));+ inverse = JSON.parse(JSON.stringify(undoOperations));+ },+ clearSelect: () => {},+ stickyRow: () => {},+ updateHeader: () => {},+ });+ exports.deleteRow(blockElement, {});+ const restore = inverse.find(operation => operation.action === "insertAttrViewBlock");+ assert.equal(restore.srcs[0].isDetached, binding === "detached");+ assert.equal(restore.srcs[0].id, binding === "detached" ? "original-item" : "bound-block");+ assert.equal(restore.srcs[0].content, "Primary");+ assert.equal(restore.previousID, "previous");+ assert.equal(restore.groupID, "group");+ assert.ok(operations[0].srcIDs.includes("original-item"));+ assert.ok(operations[0].srcIDs.includes(restore.srcs[0].itemID));+ });+}diff --git a/app/src/protyle/render/av/row.ts b/app/src/protyle/render/av/row.tsindex c5164eb00a..e31f5e7696 100644--- a/app/src/protyle/render/av/row.ts+++ b/app/src/protyle/render/av/row.ts@@ -889,8 +889,8 @@ export const deleteRow = (blockElement: HTMLElement, protyle: IProtyle) => {previousID: item.previousID,srcs: [{itemID,- id: item.itemID,- isDetached: blockValue.isDetached,+ id: blockValue.isDetached ? item.itemID : blockValue.block.id,+ isDetached: blockValue.isDetached === true,content: blockValue.block.content}],blockID: blockElement.dataset.nodeId,diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.goindex 33988faa61..c8980632d5 100644--- a/kernel/model/attribute_view.go+++ b/kernel/model/attribute_view.go@@ -6051,11 +6051,24 @@ func addAttributeViewBlocks(tx *Transaction, srcs []map[string]any, avID, dbBloc// 整批校验完成后再写入,避免后续条目越界时已修改前面的绑定。boundTrees := map[string]*parse.Tree{}- for _, src := range srcs {- if src["isDetached"].(bool) {+ detachedSources := make([]bool, len(srcs))+ for index, src := range srcs {+ if nil == src {+ return result, fmt.Errorf("invalid attribute view source [%d]", index)+ }+ // 绑定条目的序列化数据可能省略值为 false 的字段,撤销重放时按绑定状态读取。+ isDetached, ok := src["isDetached"].(bool)+ if !ok && nil != src["isDetached"] {+ return result, fmt.Errorf("invalid attribute view source [%d]: isDetached must be a boolean", index)+ }+ detachedSources[index] = isDetached+ if isDetached {continue}- id := src["id"].(string)+ id, ok := src["id"].(string)+ if !ok {+ return result, fmt.Errorf("invalid attribute view source [%d]: id must be a string", index)+ }if !ast.IsNodeIDPattern(id) {continue}@@ -6075,14 +6088,14 @@ func addAttributeViewBlocks(tx *Transaction, srcs []map[string]any, avID, dbBloc}now := time.Now().UnixMilli()- for _, src := range srcs {+ for index, src := range srcs {boundBlockID := ""srcItemID := ast.NewNodeID()if nil != src["itemID"] {srcItemID = src["itemID"].(string)}- isDetached := src["isDetached"].(bool)+ isDetached := detachedSources[index]var tree *parse.Treeif !isDetached {boundBlockID = src["id"].(string)diff --git a/kernel/model/attribute_view_insert_test.go b/kernel/model/attribute_view_insert_test.gonew file mode 100644index 0000000000..ec3fb10291--- /dev/null+++ b/kernel/model/attribute_view_insert_test.go@@ -0,0 +1,107 @@+package model++import (+ "bytes"+ "encoding/json"+ "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"+)++func TestAttributeViewInsertSourceBindingState(t *testing.T) {+ for _, test := range []struct {+ name string+ field string+ isDetached bool+ }{+ {name: "omitted"},+ {name: "null", field: `,"isDetached":null`},+ {name: "bound", field: `,"isDetached":false`},+ {name: "detached", field: `,"isDetached":true`, isDetached: true},+ } {+ t.Run(test.name, func(t *testing.T) {+ fixture := setupDatabaseBlockTransactionTest(t, false)+ boxConf := conf.NewBoxConf()+ boxConf.Closed = false+ if err := (&Box{ID: fixture.tree.Box}).SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ itemID := ast.NewNodeID()+ var operation Operation+ data := `{"action":"insertAttrViewBlock","avID":"` + fixture.attrView.ID ++ `","srcs":[{"itemID":"` + itemID + `","id":"` + fixture.tree.Root.ID ++ `","content":"Primary"` + test.field + `}],"ignoreDefaultFill":true}`+ if err := json.Unmarshal([]byte(data), &operation); err != nil {+ t.Fatal(err)+ }+ tx := &Transaction{+ trees: map[string]*parse.Tree{fixture.tree.ID: fixture.tree},+ nodes: map[string]*ast.Node{},+ }+ if txErr := tx.doInsertAttrViewBlock(&operation); txErr != nil {+ t.Fatalf("insert source failed: %v", txErr)+ }+ saved, err := av.ParseAttributeView(fixture.attrView.ID)+ if err != nil {+ t.Fatal(err)+ }+ value := saved.GetBlockValue(itemID)+ if value == nil || value.IsDetached != test.isDetached {+ t.Fatalf("unexpected restored primary value: %+v", value)+ }+ if test.isDetached {+ if value.Block.ID != "" || value.Block.Content != "Primary" {+ t.Fatalf("unexpected detached primary value: %+v", value.Block)+ }+ } else if value.Block.ID != fixture.tree.Root.ID ||+ fixture.tree.Root.IALAttr(av.NodeAttrNameAvs) != fixture.attrView.ID {+ t.Fatalf("bound source did not restore the original block binding: %+v", value.Block)+ }+ })+ }+}++func TestAttributeViewInsertSourceValidationBeforeBinding(t *testing.T) {+ for name, invalid := range map[string]map[string]any{+ "null source": nil,+ "invalid detached": {"isDetached": "false"},+ "missing block": {"isDetached": false},+ "invalid block": {"id": 1},+ } {+ t.Run(name, func(t *testing.T) {+ fixture := setupDatabaseBlockTransactionTest(t, false)+ before, err := json.Marshal(fixture.attrView)+ if err != nil {+ t.Fatal(err)+ }+ tx := &Transaction{+ trees: map[string]*parse.Tree{fixture.tree.ID: fixture.tree},+ nodes: map[string]*ast.Node{},+ }+ // 插入顺序会反转,先读取有效来源,再校验错误来源,整批失败时不能留下绑定。+ operation := &Operation{AvID: fixture.attrView.ID, Srcs: []map[string]any{+ invalid, {"id": fixture.tree.Root.ID, "isDetached": false},+ }}+ if txErr := tx.doInsertAttrViewBlock(operation); txErr == nil {+ t.Fatal("invalid source was accepted")+ }+ if fixture.tree.Root.IALAttr(av.NodeAttrNameAvs) != "" {+ t.Fatal("rejected batch changed document bindings")+ }+ saved, err := av.ParseAttributeView(fixture.attrView.ID)+ if err != nil {+ t.Fatal(err)+ }+ after, err := json.Marshal(saved)+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(before, after) {+ t.Fatal("rejected batch changed the persisted database")+ }+ })+ }+}