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: Return moveBlock transaction errors https://github.com/siyuan-note/siyuan/issues/20142
neariot523de88f137d
diff --git a/kernel/api/block_op.go b/kernel/api/block_op.goindex 1200aaf21f..1d50f11c7b 100644--- a/kernel/api/block_op.go+++ b/kernel/api/block_op.go@@ -469,8 +469,11 @@ var moveBlock = contractHandler(apicontract.MoveBlock, func(c *gin.Context, requ},}- model.PerformTransactions(&transactions)- model.FlushTxQueue()+ if err := model.PerformTransactionSync(transactions[0]); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return contractFailure[apicontract.Null](ret)+ }model.ReloadProtyle(currentBt.RootID)if currentBt.RootID != targetBt.RootID {diff --git a/kernel/api/contract_block_transaction_test.go b/kernel/api/contract_block_transaction_test.goindex bc16ba254c..305b62f1b5 100644--- a/kernel/api/contract_block_transaction_test.go+++ b/kernel/api/contract_block_transaction_test.go@@ -209,6 +209,7 @@ func TestAPIContractHeadingTransactions(t *testing.T) {}}testAPIContractBlockEdits(t, engine, box.ID, docID, heading.ID)+ testAPIContractMoveBlock(t, engine, box.ID)}func testAPIContractBlockEdits(t *testing.T, engine *gin.Engine, boxID, docID, headingID string) {diff --git a/kernel/api/contract_move_block_test.go b/kernel/api/contract_move_block_test.gonew file mode 100644index 0000000000..4f53e9dcd5--- /dev/null+++ b/kernel/api/contract_move_block_test.go@@ -0,0 +1,108 @@+package api++import (+ "bytes"+ "encoding/json"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func testAPIContractMoveBlock(t *testing.T, engine *gin.Engine, boxID string) {+ t.Helper()+ tree := treenode.NewTree(boxID, "/"+ast.NewNodeID()+".sy", "/Move", "Move")+ paragraphID := tree.Root.FirstChild.ID+ list := &ast.Node{Type: ast.NodeList, ID: ast.NewNodeID(), ListData: &ast.ListData{Typ: 0}}+ list.SetIALAttr("id", list.ID)+ for i := 0; i < 3; i++ {+ item := &ast.Node{Type: ast.NodeListItem, ID: ast.NewNodeID(), ListData: &ast.ListData{Typ: 0}}+ item.SetIALAttr("id", item.ID)+ paragraph := treenode.NewParagraph(ast.NewNodeID())+ paragraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("item")})+ item.AppendChild(paragraph)+ list.AppendChild(item)+ }+ tree.Root.AppendChild(list)+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ path := filepath.Join(util.DataDir, boxID, tree.Path)+ for _, test := range []struct {+ name, id, previousID, parentID string+ code int+ unchanged bool+ }{+ {"invalid structure", list.FirstChild.ID, list.ID, tree.ID, -1, true},+ {"self move", paragraphID, paragraphID, "", 0, true},+ {"move parent into child", list.ID, list.FirstChild.ID, "", 0, true},+ {"valid move", paragraphID, list.ID, "", 0, false},+ } {+ t.Run("moveBlock/"+test.name, func(t *testing.T) {+ before, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ request := map[string]string{"id": test.id, "previousID": test.previousID}+ if test.parentID != "" {+ request["parentID"] = test.parentID+ }+ body, _ := json.Marshal(request)+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/block/moveBlock", bytes.NewReader(body)))+ requireAPIContract(t, "POST", "/api/block/moveBlock", recorder)+ var response struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Data json.RawMessage `json:"data"`+ }+ if err = json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != test.code ||+ string(response.Data) != "null" {+ t.Fatalf("unexpected move response: %s, %v", recorder.Body.String(), err)+ }+ if test.code != 0 && !strings.Contains(response.Msg, "invalid block structure") {+ t.Fatalf("missing structural failure reason: %s", recorder.Body.String())+ }+ after, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ if test.unchanged && !bytes.Equal(before, after) {+ t.Fatal("rejected or skipped move changed the persisted document")+ }+ updated, err := model.LoadTreeByBlockID(tree.ID)+ if err != nil {+ t.Fatal(err)+ }+ if !test.unchanged {+ paragraph := treenode.GetNodeInTree(updated, paragraphID)+ if paragraph == nil || paragraph.Previous == nil || paragraph.Previous.ID != list.ID {+ t.Fatal("paragraph was not moved after the list")+ }+ }+ persistedList := treenode.GetNodeInTree(updated, list.ID)+ if persistedList == nil || persistedList.FirstChild == nil {+ t.Fatal("persisted list is missing")+ }+ item := persistedList.FirstChild+ for expected := list.FirstChild; expected != nil; expected = expected.Next {+ if item == nil || item.ID != expected.ID {+ t.Fatal("persisted list item order changed")+ }+ item = item.Next+ }+ if item != nil {+ t.Fatal("persisted list contains unexpected items")+ }+ })+ }+}diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex ee66b35aa3..8ec7cc1ce1 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -367,6 +367,8 @@ var UnfoldBlock = define[BlockIDRequest, Null]("unfoldBlock", "/api/block/unfoldvar FoldBlock = define[BlockIDRequest, Null]("foldBlock", "/api/block/foldBlock", JSONBody, ResponseOptions{}, "POST")+// MoveBlock 同步移动块,previousID 优先于 parentID,省略 previousID 时移动到父块开头。+// 成功和主动跳过返回 code=0、data=null;事务校验或提交失败返回 code=-1、data=null 和原因。var MoveBlock = define[MoveBlockRequest, Null]("moveBlock", "/api/block/moveBlock", JSONBody, ResponseOptions{}, "POST")var GetHeadingDeleteTransaction = define[BlockIDRequest, *BlockTransaction]("getHeadingDeleteTransaction", "/api/block/getHeadingDeleteTransaction", JSONBody, ResponseOptions{}, "POST")diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex 1061fbb723..77b1edc8e1 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -128,37 +128,7 @@ func flushTx(tx *Transaction) {start := time.Now()if txErr := performTx(tx); nil != txErr {- switch txErr.code {- case TxErrCodeSkipTx:- // 操作已跳过,不弹状态异常- return- case TxErrCodeBlockNotFound, TxErrCodePushMsg:- pushMsg := txErr.msg- if pushMsg == "" {- if TxErrCodeBlockNotFound == txErr.code {- pushMsg = "Transaction failed: block not found"- } else {- pushMsg = "Transaction failed"- }- }- if txErr.id != "" && !strings.Contains(pushMsg, txErr.id) {- pushMsg += fmt.Sprintf(" [%s]", txErr.id)- }- util.PushTxErr(pushMsg, txErr.code, nil)- return- case TxErrCodeReloadUI:- logging.LogErrorf("transaction failed and requires UI reload: %s", txErr.msg)- util.ReloadUI()- return- case TxErrCodeDataIsSyncing:- util.PushMsg(Conf.Language(222), 5000)- case TxErrHandleAttributeView:- util.PushMsg(Conf.language(258), 5000)- logging.LogErrorf("handle attribute view failed: %s", txErr.msg)- default:- txData, _ := gulu.JSON.MarshalJSON(tx)- logging.LogFatalf(logging.ExitCodeFatal, "transaction failed [%d]: %s\n tx [%s]", txErr.code, txErr.msg, txData)- }+ handleTxErr(tx, txErr)}elapsed := time.Since(start).Milliseconds()if 0 < len(tx.DoOperations) {@@ -168,6 +138,42 @@ func flushTx(tx *Transaction) {}}+// handleTxErr 按错误码处理事务失败:状态异常提示、界面重载或记录致命日志。+// 异步队列与同步执行共用本函数,避免同步路径丢失界面重载和提示。+func handleTxErr(tx *Transaction, txErr *TxErr) {+ switch txErr.code {+ case TxErrCodeSkipTx:+ // 操作已跳过,不弹状态异常+ return+ case TxErrCodeBlockNotFound, TxErrCodePushMsg:+ pushMsg := txErr.msg+ if pushMsg == "" {+ if TxErrCodeBlockNotFound == txErr.code {+ pushMsg = "Transaction failed: block not found"+ } else {+ pushMsg = "Transaction failed"+ }+ }+ if txErr.id != "" && !strings.Contains(pushMsg, txErr.id) {+ pushMsg += fmt.Sprintf(" [%s]", txErr.id)+ }+ util.PushTxErr(pushMsg, txErr.code, nil)+ return+ case TxErrCodeReloadUI:+ logging.LogErrorf("transaction failed and requires UI reload: %s", txErr.msg)+ util.ReloadUI()+ return+ case TxErrCodeDataIsSyncing:+ util.PushMsg(Conf.Language(222), 5000)+ case TxErrHandleAttributeView:+ util.PushMsg(Conf.language(258), 5000)+ logging.LogErrorf("handle attribute view failed: %s", txErr.msg)+ default:+ txData, _ := gulu.JSON.MarshalJSON(tx)+ logging.LogFatalf(logging.ExitCodeFatal, "transaction failed [%d]: %s\n tx [%s]", txErr.code, txErr.msg, txData)+ }+}+func PerformTransactions(transactions *[]*Transaction) {txQueueLock.Lock()defer txQueueLock.Unlock()@@ -180,6 +186,32 @@ func PerformTransactions(transactions *[]*Transaction) {})}+// PerformTransactionSync 先执行已排队编辑,再同步执行事务并返回实际错误,同时发送事务错误通知。+// 主动跳过的操作保持成功语义,结构校验或提交失败仍返回错误。+func PerformTransactionSync(transaction *Transaction) (err error) {+ flushLock.Lock()+ isFlushing.Store(true)+ defer func() {+ isFlushing.Store(false)+ flushLock.Unlock()+ }()++ // 先处理已入队的修改,确保目标校验和执行使用一致的文档状态。+ for _, queued := range takeQueuedTransactions() {+ flushTx(queued)+ }++ if err = performTxSyncLocked(transaction); nil != err {+ if txErr, ok := err.(*TxErr); ok {+ handleTxErr(transaction, txErr)+ if txErr.code == TxErrCodeSkipTx {+ return nil+ }+ }+ }+ return+}+func takeQueuedTransactions() (ret []*Transaction) {txQueueLock.Lock()defer txQueueLock.Unlock()diff --git a/kernel/model/transaction_sync_fts5_test.go b/kernel/model/transaction_sync_fts5_test.gonew file mode 100644index 0000000000..a8e441487b--- /dev/null+++ b/kernel/model/transaction_sync_fts5_test.go@@ -0,0 +1,36 @@+//go:build fts5++package model++import (+ "testing"++ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestPerformTransactionSyncPreservesQueueOrder(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ const insertedID = "20261006000000-queued1"+ dom := util.NewLute().Md2BlockDOM("queued\n{: id=\""+insertedID+"\"}", false)+ queued := []*Transaction{{DoOperations: []*Operation{{+ Action: "appendInsert", ParentID: fixture.sourceID, Data: dom,+ }}}}+ PerformTransactions(&queued)+ if err := PerformTransactionSync(&Transaction{DoOperations: []*Operation{{+ Action: "move", ID: fixture.childID, PreviousID: insertedID,+ }}}); err != nil {+ t.Fatalf("move after queued insert failed: %v", err)+ }+ cache.RemoveTreeData(fixture.sourceID)+ tree, err := LoadTreeByBlockID(fixture.sourceID)+ if err != nil {+ t.Fatal(err)+ }+ node := treenode.GetNodeInTree(tree, fixture.childID)+ if node == nil || node.Previous == nil || node.Previous.ID != insertedID {+ t.Fatal("queued insert was not applied before the persisted move")+ }+}diff --git a/kernel/model/transaction_sync_test.go b/kernel/model/transaction_sync_test.gonew file mode 100644index 0000000000..5f5f9c8962--- /dev/null+++ b/kernel/model/transaction_sync_test.go@@ -0,0 +1,118 @@+// 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.++package model++import (+ "bytes"+ "net/http"+ "net/http/httptest"+ "net/url"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/gorilla/websocket"+ "github.com/olahol/melody"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestPerformTransactionSyncReturnsTransactionError(t *testing.T) {+ for _, mode := range []string{"sync", "queue"} {+ t.Run(mode, func(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ listID, itemID := addOrderedListForStructureTest(t, fixture.sourceID)+ path := filepath.Join(util.DataDir, fixture.box.ID, fixture.sourcePath)+ before, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ push := melody.New()+ connected := make(chan *melody.Session, 1)+ push.HandleConnect(func(session *melody.Session) {+ util.AddPushChan(session)+ connected <- session+ })+ push.HandleDisconnect(util.RemovePushChan)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _ = push.HandleRequest(w, r)+ }))+ t.Cleanup(func() { _ = push.Close(); server.Close() })+ endpoint := "ws" + strings.TrimPrefix(server.URL, "http") + "/?app=" ++ url.QueryEscape(t.TempDir()) + "&id=main&type=main"+ connection, response, err := websocket.DefaultDialer.Dial(endpoint, nil)+ if err != nil {+ t.Fatal(err)+ }+ _ = response.Body.Close()+ select {+ case session := <-connected:+ t.Cleanup(func() { _ = connection.Close(); util.RemovePushChan(session) })+ case <-time.After(5 * time.Second):+ _ = connection.Close()+ t.Fatal("websocket registration timed out")+ }+ tx := &Transaction{DoOperations: []*Operation{{+ Action: "move", ID: itemID, PreviousID: listID, ParentID: fixture.sourceID,+ }}}+ if mode == "sync" {+ requireStructureTransactionError(t, PerformTransactionSync(tx))+ } else {+ queued := []*Transaction{tx}+ PerformTransactions(&queued)+ FlushTxQueue()+ }+ if err = push.Broadcast([]byte(`{"cmd":"barrier"}`)); err != nil {+ t.Fatal(err)+ }+ if err = connection.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {+ t.Fatal(err)+ }+ reloads := 0+ for {+ var event struct{ Cmd string }+ if err = connection.ReadJSON(&event); err != nil {+ t.Fatal(err)+ }+ if event.Cmd == "barrier" {+ break+ }+ if event.Cmd == "reloadui" {+ reloads+++ }+ }+ if reloads != 1 {+ t.Fatalf("expected one reload notification, got %d", reloads)+ }+ after, err := os.ReadFile(path)+ if err != nil || !bytes.Equal(before, after) {+ t.Fatalf("rejected move changed the persisted document: %v", err)+ }+ })+ }+}++func TestPerformTransactionSyncPreservesSkippedMove(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ path := filepath.Join(util.DataDir, fixture.box.ID, fixture.sourcePath)+ before, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ if err = PerformTransactionSync(&Transaction{DoOperations: []*Operation{{+ Action: "move", ID: fixture.childID, PreviousID: fixture.childID,+ }}}); err != nil {+ t.Fatalf("self move must remain a successful no-op: %v", err)+ }+ after, err := os.ReadFile(path)+ if err != nil || !bytes.Equal(before, after) {+ t.Fatalf("self move changed the persisted document: %v", err)+ }+}