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: Validate block structures before transaction commit https://github.com/siyuan-note/siyuan/issues/18613
Daniel6c8b00b07ede
diff --git a/app/src/protyle/wysiwyg/list.ts b/app/src/protyle/wysiwyg/list.tsindex 9b72337030..0e412c3f57 100644--- a/app/src/protyle/wysiwyg/list.ts+++ b/app/src/protyle/wysiwyg/list.ts@@ -8,7 +8,11 @@ import {hasClosestByClassName, isBlockElement} from "../util/hasClosest";import {getEmbedChildOperationContext, getParentBlock, getPreviousBlockSibling} from "./getBlock";import {setFold} from "../util/blockFold";import {scrollCenter} from "../../util/highlightById";-import {getFollowingOrderedListMarkerUpdates, type TListSubtype} from "./listContext";+import {+ getFollowingOrderedListMarkerUpdates,+ getOrderedListMarkerUpdates,+ type TListSubtype+} from "./listContext";import {fetchSyncPost} from "../../util/fetch";const getLastChildBlock = (element: Element) => {@@ -35,29 +39,26 @@ const unfoldElements = (protyle: IProtyle, elements: Element[]) => {export const updateListOrder = (listElement: Element, sIndex?: number) => {if (listElement.getAttribute("data-subtype") !== "o") {- return;+ return true;}- let starIndex: number;- Array.from(listElement.children).forEach((item, index) => {- // https://github.com/siyuan-note/siyuan/issues/16315 第三点会有为空的情况- if (!item.classList.contains("li")) {- return;- }- if (index === 0) {- if (sIndex) {- starIndex = sIndex;- item.setAttribute("data-marker", (starIndex) + ".");- item.querySelector(".protyle-action--order").textContent = (starIndex) + ".";- } else {- starIndex = parseInt(item.getAttribute("data-marker"));+ const blockChildren = Array.from(listElement.children).filter(item => item.hasAttribute("data-node-id"));+ if (blockChildren.some(item => item.getAttribute("data-type") !== "NodeListItem")) {+ return false;+ }+ const listItemElements = blockChildren as HTMLElement[];+ const markerUpdates = getOrderedListMarkerUpdates(+ listItemElements.map(item => item.getAttribute("data-marker")), sIndex);+ listItemElements.forEach((item, index) => {+ const marker = markerUpdates[index];+ if (marker) {+ item.setAttribute("data-marker", marker);+ const actionElement = item.querySelector(".protyle-action--order");+ if (actionElement) {+ actionElement.textContent = marker;}- } else if (item.classList.contains("li")) {- // 保证列表项的缩放和常规列表属性的存在- starIndex++;- item.setAttribute("data-marker", (starIndex) + ".");- item.querySelector(".protyle-action--order").textContent = (starIndex) + ".";}});+ return true;};export const toggleTaskListItem = (protyle: IProtyle, taskItemElement: Element): void => {diff --git a/app/src/protyle/wysiwyg/listContext.test.ts b/app/src/protyle/wysiwyg/listContext.test.tsindex 093c9e8a79..c7d1b2cbaa 100644--- a/app/src/protyle/wysiwyg/listContext.test.ts+++ b/app/src/protyle/wysiwyg/listContext.test.ts@@ -4,6 +4,7 @@ import {getFollowingOrderedListMarkerUpdates,getListContext,getListConversionType,+ getOrderedListMarkerUpdates,getListShortcutAction,shouldIgnoreListShortcut,type TListSubtype@@ -185,6 +186,22 @@ describe("getFollowingOrderedListMarkerUpdates", () => {});});+describe("getOrderedListMarkerUpdates", () => {+ it("preserves ordered lists starting from zero", () => {+ assert.deepEqual(getOrderedListMarkerUpdates(["0.", "1."]), [undefined, undefined]);+ assert.deepEqual(getOrderedListMarkerUpdates(["5.", "9."]), [undefined, "6."]);+ });++ it("supports an explicit zero start index", () => {+ assert.deepEqual(getOrderedListMarkerUpdates(["1.", "2."], 0), ["0.", "1."]);+ });++ it("replaces invalid markers instead of producing NaN", () => {+ assert.deepEqual(getOrderedListMarkerUpdates(["NaN.", "NaN."]), ["1.", "2."]);+ assert.deepEqual(getOrderedListMarkerUpdates(["2.", "3."], Number.NaN), ["1.", "2."]);+ });+});+describe("shouldIgnoreListShortcut", () => {it("ignores only a selected list item", () => {assert.equal(shouldIgnoreListShortcut(true, "NodeListItem"), true);diff --git a/app/src/protyle/wysiwyg/listContext.ts b/app/src/protyle/wysiwyg/listContext.tsindex a71676488b..245824c25d 100644--- a/app/src/protyle/wysiwyg/listContext.ts+++ b/app/src/protyle/wysiwyg/listContext.ts@@ -85,6 +85,18 @@ export const getFollowingOrderedListMarkerUpdates = (currentMarker: string, foll});};+export const getOrderedListMarkerUpdates = (markers: string[], startIndex?: number) => {+ if (markers.length === 0) {+ return [];+ }+ const parsedStartIndex = startIndex === undefined ? Number.parseInt(markers[0], 10) : startIndex;+ const normalizedStartIndex = Number.isFinite(parsedStartIndex) ? Math.trunc(parsedStartIndex) : 1;+ return markers.map((marker, index) => {+ const expectedMarker = `${normalizedStartIndex + index}.`;+ return marker === expectedMarker ? undefined : expectedMarker;+ });+};+export const shouldIgnoreListShortcut = (hasBlockSelection: boolean, selectedType?: string) => {return hasBlockSelection && selectedType === "NodeListItem";};diff --git a/kernel/model/outline.go b/kernel/model/outline.goindex a247e9da34..d4f82caddc 100644--- a/kernel/model/outline.go+++ b/kernel/model/outline.go@@ -200,6 +200,10 @@ func (tx *Transaction) doMoveOutlineHeading(operation *Operation) (ret *TxErr) {}}+ tx.markStructureCheck(heading)+ for _, child := range headingChildren {+ tx.markStructureCheck(child)+ }tx.writeTree(tree)return}diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex fdcc493ac1..2c1f5aa3a3 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -137,6 +137,10 @@ func flushTx(tx *Transaction) {}util.PushTxErr(pushMsg, txErr.code, nil)return+ case TxErrCodeReloadUI:+ logging.LogErrorf("transaction structure validation failed: %s", txErr.msg)+ util.ReloadUI()+ returncase TxErrCodeDataIsSyncing:util.PushMsg(Conf.Language(222), 5000)case TxErrHandleAttributeView:@@ -188,6 +192,7 @@ const (TxErrHandleAttributeView = 3TxErrCodePushMsg = 4TxErrCodeSkipTx = 5 // 操作被跳过,不弹状态异常+ TxErrCodeReloadUI = 6 // 事务已回滚,重新加载界面以恢复前后端一致状态)type TxErr struct {@@ -465,6 +470,10 @@ func performTx(tx *Transaction) (ret *TxErr) {tx.rollback()return}+ if ret = tx.validateStructureChanges(); nil != ret {+ tx.rollback()+ return+ }if cr := tx.commit(); nil != cr {logging.LogErrorf("commit tx failed: %s", cr)@@ -673,6 +682,10 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {treenode.RefreshUpdated(srcNode)tx.nodes[srcNode.ID] = srcNode+ tx.markStructureCheck(srcNode)+ for _, child := range headingChildren {+ tx.markStructureCheck(child)+ }treenode.RefreshUpdated(srcTree.Root)tx.writeTree(srcTree)if !isSameTree {@@ -760,6 +773,10 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {treenode.RefreshUpdated(srcNode)tx.nodes[srcNode.ID] = srcNode+ tx.markStructureCheck(srcNode)+ for _, child := range headingChildren {+ tx.markStructureCheck(child)+ }treenode.RefreshUpdated(srcTree.Root)tx.writeTree(srcTree)if !isSameTree {@@ -884,6 +901,7 @@ func (tx *Transaction) doPrependInsert(operation *Operation) (ret *TxErr) {treenode.CreatedUpdated(toInsert)tx.nodes[toInsert.ID] = toInsert+ tx.markStructureCheck(toInsert)}treenode.CreatedUpdated(insertedNode)@@ -998,6 +1016,7 @@ func (tx *Transaction) doAppendInsert(operation *Operation) (ret *TxErr) {treenode.CreatedUpdated(toInsert)tx.nodes[toInsert.ID] = toInsert+ tx.markStructureCheck(toInsert)}treenode.CreatedUpdated(insertedNode)@@ -1094,6 +1113,11 @@ func (tx *Transaction) doAppend(operation *Operation) (ret *TxErr) {if nil != srcEmptyList {srcEmptyList.Unlink()}+ tx.markStructureCheck(srcNode)+ tx.markStructureCheck(targetNewList)+ for _, child := range headingChildren {+ tx.markStructureCheck(child)+ }tx.writeTree(srcTree)if !isSameTree {@@ -1572,6 +1596,10 @@ func (tx *Transaction) doInsert0(operation *Operation, tree *parse.Tree) (ret *Ttreenode.CreatedUpdated(insertedNode)tx.nodes[insertedNode.ID] = insertedNode+ tx.markStructureCheck(insertedNode)+ for _, remain := range remains {+ tx.markStructureCheck(remain)+ }// 收集引用的定义块 IDrefDefIDs := getRefDefIDs(insertedNode)@@ -1690,7 +1718,7 @@ func (tx *Transaction) doUpdate(operation *Operation) (ret *TxErr) {}if err = treenode.ValidateBlockReplacement(oldNode, updatedNode); err != nil {logging.LogErrorf("validate updated block [%s] structure failed: %s", id, err)- return &TxErr{code: TxErrCodePushMsg, msg: err.Error(), id: id}+ return &TxErr{code: TxErrCodeReloadUI, msg: err.Error(), id: id}}if err = validateBlockUpdateType(oldNode, updatedNode, operation.LockType); err != nil {logging.LogError(err.Error())@@ -2021,6 +2049,7 @@ func (tx *Transaction) doCreate(operation *Operation) (ret *TxErr) {// 兜底校验:禁止跨加密边界块引(创建文档可能携带跨边界引用)// 必须在 getRefDefIDs 之前,避免跨边界引用被收集进引用缓存degradeCrossBoundaryBlockRefs(tree.Root, tree.Box)+ tx.markStructureCheck(tree.Root)tx.writeTree(tree)// 新建文档中的引用均为本次新增,刷新其最近引用时间用于块引"最近引用"排序TouchRefUsed(getRefDefIDs(tree.Root))@@ -2207,6 +2236,50 @@ type listItemFoldCandidate struct {tree *parse.Tree}+func (tx *Transaction) markStructureCheck(node *ast.Node) {+ if nil == node {+ return+ }+ if nil == tx.structureCheckNodes {+ tx.structureCheckNodes = map[*ast.Node]struct{}{}+ }+ tx.structureCheckNodes[node] = struct{}{}+}++func isNodeInDocument(node *ast.Node) bool {+ for current := node; nil != current; current = current.Parent {+ if ast.NodeDocument == current.Type {+ return true+ }+ }+ return false+}++func (tx *Transaction) structureOperationSummary() string {+ var operations []string+ for index, operation := range tx.DoOperations {+ switch operation.Action {+ case "append", "appendInsert", "insert", "move", "moveOutlineHeading", "prependInsert":+ operations = append(operations, fmt.Sprintf("%d:%s id=%s parent=%s previous=%s next=%s",+ index, operation.Action, operation.ID, operation.ParentID, operation.PreviousID, operation.NextID))+ }+ }+ return strings.Join(operations, "; ")+}++func (tx *Transaction) validateStructureChanges() (ret *TxErr) {+ for node := range tx.structureCheckNodes {+ if !isNodeInDocument(node) {+ continue+ }+ if err := treenode.ValidateBlockPlacement(node); nil != err {+ msg := fmt.Sprintf("%s, operations [%s]", err, tx.structureOperationSummary())+ return &TxErr{code: TxErrCodeReloadUI, msg: msg, id: node.ID}+ }+ }+ return+}+type Transaction struct {Timestamp int64 `json:"timestamp"`DoOperations []*Operation `json:"doOperations"`@@ -2230,6 +2303,7 @@ type Transaction struct {listItemFoldCandidates []listItemFoldCandidatelistItemFoldCandidateIDs map[string]struct{}deletedAttrViewBlockIDs map[string]map[string]struct{}+ structureCheckNodes map[*ast.Node]struct{}luteEngine *lute.Lutem *sync.Mutex@@ -2287,6 +2361,7 @@ func (tx *Transaction) begin() (err error) {tx.listItemFoldCandidates = niltx.listItemFoldCandidateIDs = map[string]struct{}{}tx.deletedAttrViewBlockIDs = map[string]map[string]struct{}{}+ tx.structureCheckNodes = map[*ast.Node]struct{}{}tx.luteEngine = util.NewLute()tx.m.Lock()tx.state.Store(1)@@ -2362,6 +2437,7 @@ func (tx *Transaction) rollback() {tx.trees, tx.nodes, tx.boxIcons, tx.removedCreatedDocs, tx.restoredCreatedDocs = nil, nil, nil, nil, niltx.listItemFoldCandidates, tx.listItemFoldCandidateIDs = nil, niltx.deletedAttrViewBlockIDs = nil+ tx.structureCheckNodes = niltx.state.Store(3)tx.m.Unlock()returndiff --git a/kernel/model/transaction_structure_test.go b/kernel/model/transaction_structure_test.gonew file mode 100644index 0000000000..8550204df2--- /dev/null+++ b/kernel/model/transaction_structure_test.go@@ -0,0 +1,137 @@+// 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 (+ "errors"+ "path/filepath"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func setupStructureTransactionTest(t *testing.T) *fileOperationTestFixture {+ originalHistoryDir := util.HistoryDir+ util.HistoryDir = filepath.Join(t.TempDir(), "history")+ t.Cleanup(func() {+ util.HistoryDir = originalHistoryDir+ })+ return setupFileOperationTest(t)+}++func addOrderedListForStructureTest(t *testing.T, rootID string) (listID, itemID string) {+ tree, err := LoadTreeByBlockID(rootID)+ if nil != err {+ t.Fatalf("load test tree failed: %s", err)+ }++ listID = "20260808000000-list001"+ itemID = "20260808000000-item001"+ paragraphID := "20260808000000-block01"+ list := &ast.Node{Type: ast.NodeList, ID: listID, ListData: &ast.ListData{Typ: 1}}+ item := &ast.Node{Type: ast.NodeListItem, ID: itemID, ListData: &ast.ListData{Typ: 1}}+ paragraph := treenode.NewParagraph(paragraphID)+ list.SetIALAttr("id", listID)+ item.SetIALAttr("id", itemID)+ item.AppendChild(paragraph)+ list.AppendChild(item)+ tree.Root.AppendChild(list)+ if _, err = filesys.WriteTree(tree); nil != err {+ t.Fatalf("write test tree failed: %s", err)+ }+ treenode.UpsertBlockTree(tree)+ return+}++func requireStructureTransactionError(t *testing.T, err error) {+ t.Helper()+ if nil == err {+ t.Fatal("expected invalid structure transaction to be rejected")+ }+ var txErr *TxErr+ if !errors.As(err, &txErr) {+ t.Fatalf("expected transaction error, got [%T] %v", err, err)+ }+ if TxErrCodeReloadUI != txErr.Code() {+ t.Fatalf("unexpected transaction error code: got %d, want %d", txErr.Code(), TxErrCodeReloadUI)+ }+}++func TestInsertRejectsParagraphDirectlyUnderList(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ listID, _ := addOrderedListForStructureTest(t, fixture.sourceID)+ dom := util.NewLute().Md2BlockDOM("inserted", false)+ tx := &Transaction{DoOperations: []*Operation{{+ Action: "insert",+ ParentID: listID,+ Data: dom,+ }}}++ requireStructureTransactionError(t, PerformTxSync(tx))++ tree, err := LoadTreeByBlockID(listID)+ if nil != err {+ t.Fatalf("reload test tree failed: %s", err)+ }+ list := treenode.GetNodeInTree(tree, listID)+ if ast.NodeListItem != list.FirstChild.Type || nil != list.FirstChild.Next {+ t.Fatal("rejected insert changed the persisted list structure")+ }+}++func TestMoveRejectsParagraphDirectlyUnderList(t *testing.T) {+ tests := []struct {+ name string+ operation func(sourceID, listID, itemID string) *Operation+ }{+ {+ name: "parent id",+ operation: func(sourceID, listID, itemID string) *Operation {+ return &Operation{Action: "move", ID: sourceID, ParentID: listID}+ },+ },+ {+ name: "previous id",+ operation: func(sourceID, listID, itemID string) *Operation {+ return &Operation{Action: "move", ID: sourceID, ParentID: listID, PreviousID: itemID}+ },+ },+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ listID, itemID := addOrderedListForStructureTest(t, fixture.sourceID)+ tx := &Transaction{DoOperations: []*Operation{+ test.operation(fixture.childID, listID, itemID),+ }}++ requireStructureTransactionError(t, PerformTxSync(tx))++ tree, err := LoadTreeByBlockID(fixture.childID)+ if nil != err {+ t.Fatalf("reload test tree failed: %s", err)+ }+ paragraph := treenode.GetNodeInTree(tree, fixture.childID)+ if nil == paragraph || ast.NodeDocument != paragraph.Parent.Type {+ t.Fatal("rejected move changed the persisted paragraph parent")+ }+ })+ }+}diff --git a/kernel/treenode/block_structure.go b/kernel/treenode/block_structure.goindex 46f6bb63a9..2692e2a17d 100644--- a/kernel/treenode/block_structure.go+++ b/kernel/treenode/block_structure.go@@ -56,6 +56,22 @@ func ValidateBlockSubtree(root *ast.Node) error {return ret}+// ValidateBlockPlacement 校验内容块在当前父节点中的位置,并校验其内部结构。+func ValidateBlockPlacement(node *ast.Node) error {+ if nil == node || !isContentBlock(node) {+ return invalidBlockNodeError(node)+ }++ parent := node.Parent+ for nil != parent && !isContentBlock(parent) {+ parent = parent.Parent+ }+ if nil != parent && !CanContainBlock(parent.Type, node.Type) {+ return invalidBlockContainmentError(parent, node)+ }+ return ValidateBlockSubtree(node)+}+// ValidateBlockReplacement 校验新块能否替换旧块,并校验新块内部的容纳关系。func ValidateBlockReplacement(oldNode, newNode *ast.Node) error {if nil == oldNode || !isContentBlock(oldNode) {diff --git a/kernel/treenode/block_structure_test.go b/kernel/treenode/block_structure_test.goindex 25eeb0f41e..6bb63bac54 100644--- a/kernel/treenode/block_structure_test.go+++ b/kernel/treenode/block_structure_test.go@@ -68,6 +68,36 @@ func TestValidateBlockSubtree(t *testing.T) {}}+func TestValidateBlockPlacement(t *testing.T) {+ document := &ast.Node{Type: ast.NodeDocument, ID: "document"}+ list := &ast.Node{Type: ast.NodeList, ID: "list"}+ item := &ast.Node{Type: ast.NodeListItem, ID: "item"}+ paragraph := &ast.Node{Type: ast.NodeParagraph, ID: "paragraph"}+ document.AppendChild(list)+ list.AppendChild(item)+ item.AppendChild(paragraph)++ if err := ValidateBlockPlacement(item); nil != err {+ t.Fatalf("expected list item placement to be valid, got [%s]", err)+ }+ if err := ValidateBlockPlacement(paragraph); nil != err {+ t.Fatalf("expected paragraph placement to be valid, got [%s]", err)+ }++ invalidParagraph := &ast.Node{Type: ast.NodeParagraph, ID: "invalid-paragraph"}+ list.AppendChild(invalidParagraph)+ if err := ValidateBlockPlacement(invalidParagraph); nil == err {+ t.Fatal("expected paragraph directly under list to be rejected")+ }++ invalidItem := &ast.Node{Type: ast.NodeListItem, ID: "invalid-item"}+ invalidItem.AppendChild(&ast.Node{Type: ast.NodeListItem, ID: "nested-item"})+ list.AppendChild(invalidItem)+ if err := ValidateBlockPlacement(invalidItem); nil == err {+ t.Fatal("expected invalid list item subtree to be rejected")+ }+}+func TestValidateBlockReplacement(t *testing.T) {list := &ast.Node{Type: ast.NodeList, ID: "list"}oldItem := &ast.Node{Type: ast.NodeListItem, ID: "item"}