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: Handle UTF-8 BOM in document reads and preserve load errors https://github.com/siyuan-note/siyuan/issues/20755
Daniel8b7d9d5e21f2
diff --git a/docs/SY-FORMAT.md b/docs/SY-FORMAT.mdindex 78668fda30..ffc26517f5 100644--- a/docs/SY-FORMAT.md+++ b/docs/SY-FORMAT.md@@ -24,6 +24,8 @@ This guide distinguishes the format that new writers should emit from historicalUnless a section explicitly says otherwise, "required" refers to canonical new writes. `dataparser.ParseJSON` is a compatibility reader rather than a strict schema validator: for example, it can add a missing empty paragraph, assign a missing block ID, and upgrade an old `Spec`.+Canonical plaintext `.sy` writes use UTF-8 JSON without a byte order mark (BOM). The file-system tree and document-property readers accept one UTF-8 BOM (`EF BB BF`) at the very beginning of the plaintext, before JSON validation and parsing. For encrypted notebooks, this normalization takes place only after authenticated decryption; a BOM must not be prepended to the ciphertext. Successful tree repair or saving writes JSON without a BOM. Read-only snapshots and property queries leave the source unchanged. Malformed JSON, unsupported document specifications, and authentication failures remain errors and must preserve the original file; BOM tolerance does not bypass these checks.+---## 0.5 When to read/write `.sy` directly (priority order)diff --git a/docs/SY-FORMAT.zh-CN.md b/docs/SY-FORMAT.zh-CN.mdindex 13ee3910ce..23529ccf55 100644--- a/docs/SY-FORMAT.zh-CN.md+++ b/docs/SY-FORMAT.zh-CN.md@@ -24,6 +24,8 @@除非某节另有说明,本文的“必需”均指新数据的规范写入要求。`dataparser.ParseJSON` 是兼容读取器,而不是严格的 Schema 校验器;例如,它可以填充缺失的空段落、为缺少 ID 的块分配 ID,并升级旧版 `Spec`。+规范写入的明文 `.sy` 使用不带字节顺序标记(BOM)的 UTF-8 JSON。文件系统的块树和文档属性读取器允许明文最开头存在一个 UTF-8 BOM(`EF BB BF`),并在 JSON 校验和解析前去除。加密笔记本仅在认证解密成功后进行此规范化,不能在密文前添加 BOM。块树订正成功或保存时写入不带 BOM 的 JSON;只读快照和属性查询保持源文件不变。JSON 损坏、文档规范不受支持或认证失败仍须返回错误并保留原文件,BOM 兼容不能绕过这些检查。+---## 0.5 何时直接读写 `.sy`(优先级)diff --git a/kernel/filesys/tree.go b/kernel/filesys/tree.goindex d5ba4c2f35..e1907d2003 100644--- a/kernel/filesys/tree.go+++ b/kernel/filesys/tree.go@@ -17,6 +17,7 @@package filesysimport (+ "bufio""bytes""encoding/json""errors"@@ -371,6 +372,7 @@ func readDocIAL(absPath string, strict bool) (map[string]string, error) {if err != nil {return nil, err}+ data = bytes.TrimPrefix(data, []byte("\xef\xbb\xbf"))if strict {if err = treenode.CheckSpecJSON(data); err != nil {return nil, err@@ -458,7 +460,11 @@ func (r *docIALReader) Read(p []byte) (int, error) {func parseDocIAL(reader io.Reader) (ret map[string]string, err error) {r := &docIALReader{Reader: reader}- iter := jsoniter.Parse(jsoniter.ConfigCompatibleWithStandardLibrary, r, 512)+ buffered := bufio.NewReaderSize(r, 512)+ if prefix, _ := buffered.Peek(3); bytes.Equal(prefix, []byte("\xef\xbb\xbf")) {+ _, _ = buffered.Discard(3)+ }+ iter := jsoniter.Parse(jsoniter.ConfigCompatibleWithStandardLibrary, buffered, 512)for field := iter.ReadObject(); field != ""; field = iter.ReadObject() {if field == "Properties" {iter.ReadVal(&ret)@@ -666,10 +672,15 @@ func fixTreeJSONData(boxID, p string, jsonData []byte, luteEngine *lute.Lute, deif err = validateTreePath(boxID, p); err != nil {return}+ // 这里只处理解密后的 JSON,密文必须先通过认证,订正成功后才允许写回。+ withoutBOM := bytes.TrimPrefix(jsonData, []byte("\xef\xbb\xbf"))+ needFix = len(withoutBOM) != len(jsonData)+ jsonData = withoutBOMif err = treenode.CheckSpecJSON(jsonData); nil != err {return}- jsonData, needFix = removeUnescapedUnicodeNull(jsonData)+ jsonData, removedNull := removeUnescapedUnicodeNull(jsonData)+ needFix = needFix || removedNullret, parseNeedFix, err := dataparser.ParseJSON(jsonData, luteEngine.ParseOptions)if parseNeedFix {needFix = true@@ -758,6 +769,7 @@ func fixTreeJSONData(boxID, p string, jsonData []byte, luteEngine *lute.Lute, de}func parseJSON2Tree(boxID, p string, jsonData []byte, luteEngine *lute.Lute) (ret *parse.Tree, err error) {+ jsonData = bytes.TrimPrefix(jsonData, []byte("\xef\xbb\xbf"))if err = treenode.CheckSpecJSON(jsonData); nil != err {return}diff --git a/kernel/filesys/tree_bom_test.go b/kernel/filesys/tree_bom_test.gonew file mode 100644index 0000000000..df6f557354--- /dev/null+++ b/kernel/filesys/tree_bom_test.go@@ -0,0 +1,167 @@+package filesys++import (+ "bytes"+ "encoding/json"+ "fmt"+ "os"+ "strings"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/render"+ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestTreeUTF8BOM(t *testing.T) {+ for _, encrypted := range []bool{false, true} {+ t.Run(fmt.Sprintf("encrypted=%v", encrypted), func(t *testing.T) {+ box, root, _, _ := setupStalePathTest(t)+ originalProvider := DEKProvider+ var dek []byte+ if encrypted {+ dek = bytes.Repeat([]byte{17}, 32)+ }+ DEKProvider = func(string) ([]byte, error) { return bytes.Clone(dek), nil }+ t.Cleanup(func() { DEKProvider = originalProvider })+ p := "/" + root + ".sy"+ engine := util.NewLute()+ tree := treenode.NewTree(box, p, "/Parent", "Parent")+ tree.Root.FirstChild.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("before\xef\xbb\xbfafter")})+ data := render.NewJSONRenderer(tree, engine.RenderOptions, engine.ParseOptions).Render()+ plain := append([]byte("\xef\xbb\xbf"), data...)+ raw, err := encryptDataWithDEK(box, p, plain, dek)+ if err != nil {+ t.Fatal(err)+ }+ abs := writeStalePathFixture(t, box, p, raw)+ assertUnchanged := func() {+ t.Helper()+ got, readErr := os.ReadFile(abs)+ if readErr != nil || !bytes.Equal(raw, got) {+ t.Fatalf("read-only operation changed source: %v", readErr)+ }+ }+ if loaded, loadErr := LoadTreeByData(plain, box, p, engine); loadErr != nil || loaded.Root.ID != root {+ t.Fatalf("BOM data not readable: %v", loadErr)+ }+ if ial, readErr := DocIAL(abs); readErr != nil || ial["title"] != "Parent" {+ t.Fatalf("BOM properties not readable: %v, %v", ial, readErr)+ }+ if _, _, readErr := ReadTreeSnapshot(box, p); readErr != nil {+ t.Fatalf("BOM read-only snapshot failed: %v", readErr)+ }+ if _, original, readErr := LoadTreeSnapshot(box, p, engine); readErr != nil || !bytes.Equal(original, raw) {+ t.Fatalf("BOM conditional snapshot lost original bytes: %v", readErr)+ }+ childPath := "/" + root + "/20260912000003-child02.sy"+ child := treenode.NewTree(box, childPath, "/Parent/Child", "Child")+ if _, err = WriteTree(child); err != nil {+ t.Fatal(err)+ }+ cache.RemoveTreeDataInBox(child.ID, box)+ if loaded, readErr := LoadTree(box, childPath, engine); readErr != nil || loaded.HPath != "/Parent/Child" {+ t.Fatalf("BOM parent not readable: %v", readErr)+ }+ assertUnchanged()+ loaded, fixed, err := LoadTreeWithFix(box, p, engine)+ if err != nil || !fixed || loaded.Root.ID != root {+ t.Fatalf("BOM tree not repaired: fixed=%v err=%v", fixed, err)+ }+ stored, err := os.ReadFile(abs)+ if err != nil {+ t.Fatal(err)+ }+ stored, err = decryptDataWithDEK(box, p, stored, dek)+ if err != nil || !json.Valid(stored) || bytes.HasPrefix(stored, []byte("\xef\xbb\xbf")) {+ t.Fatalf("repaired JSON still contains a BOM: %v", err)+ }+ if !strings.Contains(string(stored), "before\xef\xbb\xbfafter") {+ t.Fatal("BOM inside content was changed")+ }+ cache.RemoveTreeDataInBox(root, box)+ if _, fixed, err = LoadTreeWithFix(box, p, engine); err != nil || fixed {+ t.Fatalf("repair did not persist: fixed=%v err=%v", fixed, err)+ }+ })+ }+}++func TestTreeUTF8BOMRejectsInvalidSource(t *testing.T) {+ for _, encrypted := range []bool{false, true} {+ for name, data := range map[string][]byte{+ "malformed": []byte("\xef\xbb\xbf{\"Spec\":"),+ "future": []byte("\xef\xbb\xbf{\"Spec\":\"999\"}"),+ "repeated": []byte("\xef\xbb\xbf\xef\xbb\xbf{}"),+ "utf16": {0xff, 0xfe, '{', 0, '}', 0},+ } {+ t.Run(fmt.Sprintf("%s/encrypted=%v", name, encrypted), func(t *testing.T) {+ box, root, _, _ := setupStalePathTest(t)+ originalProvider := DEKProvider+ var dek []byte+ if encrypted {+ dek = bytes.Repeat([]byte{23}, 32)+ }+ DEKProvider = func(string) ([]byte, error) { return bytes.Clone(dek), nil }+ t.Cleanup(func() { DEKProvider = originalProvider })+ p := "/" + root + ".sy"+ raw, err := encryptDataWithDEK(box, p, data, dek)+ if err != nil {+ t.Fatal(err)+ }+ abs := writeStalePathFixture(t, box, p, raw)+ if _, _, err = LoadTreeWithFix(box, p, util.NewLute()); err == nil {+ t.Fatal("invalid source was accepted")+ }+ retained, err := os.ReadFile(abs)+ if err != nil || !bytes.Equal(raw, retained) {+ t.Fatalf("invalid source was changed: %v", err)+ }+ })+ }+ }+}++func TestTreeUTF8BOMDoesNotBypassAuthentication(t *testing.T) {+ box, root, _, _ := setupStalePathTest(t)+ originalProvider := DEKProvider+ dek := bytes.Repeat([]byte{31}, 32)+ DEKProvider = func(string) ([]byte, error) { return bytes.Clone(dek), nil }+ t.Cleanup(func() { DEKProvider = originalProvider })+ p := "/" + root + ".sy"+ engine := util.NewLute()+ tree := treenode.NewTree(box, p, "/Test", "Test")+ plain := append([]byte("\xef\xbb\xbf"), render.NewJSONRenderer(tree, engine.RenderOptions, engine.ParseOptions).Render()...)+ ciphertext, err := encryptDataWithDEK(box, p, plain, dek)+ if err != nil {+ t.Fatal(err)+ }+ tampered := bytes.Clone(ciphertext)+ tampered[len(tampered)-1] ^= 1+ for name, raw := range map[string][]byte{+ "tampered": tampered,+ "plaintext": plain,+ "ciphertext-prefix": append([]byte("\xef\xbb\xbf"), ciphertext...),+ } {+ t.Run(name, func(t *testing.T) {+ abs := writeStalePathFixture(t, box, p, raw)+ for _, read := range []func() error{+ func() error { _, err := LoadTree(box, p, engine); return err },+ func() error { _, _, err := ReadTreeSnapshot(box, p); return err },+ func() error { _, _, err := LoadTreeSnapshot(box, p, engine); return err },+ func() error { _, err := DocIAL(abs); return err },+ func() error { _, _, err := ReadDocHPath(box, p); return err },+ } {+ if err := read(); err == nil {+ t.Fatal("unauthenticated source was accepted")+ }+ }+ retained, err := os.ReadFile(abs)+ if err != nil || !bytes.Equal(retained, raw) {+ t.Fatalf("authentication failure changed source: %v", err)+ }+ })+ }+}diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex 9dabed991a..1bd9ff6c18 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -322,7 +322,11 @@ func performTx(tx *Transaction) (ret *TxErr) {tx.rollback()return ret}- isLargeDelete := tx.processLargeDelete()+ isLargeDelete, ret := tx.processLargeDelete()+ if ret != nil {+ tx.rollback()+ return ret+ }if !isLargeInsert {for operationIndex := 0; operationIndex < len(tx.DoOperations); operationIndex++ {op := tx.DoOperations[operationIndex]@@ -605,17 +609,17 @@ func txErrFromPanic(state int32, recovered any) *TxErr {return &TxErr{code: TxErrCodePushMsg, msg: fmt.Sprintf("transaction panic: %v", recovered)}}-func (tx *Transaction) processLargeDelete() bool {+func (tx *Transaction) processLargeDelete() (bool, *TxErr) {opSize := len(tx.DoOperations)if 32 > opSize {- return false+ return false, nil}var deleteOps []*Operationfor i, op := range tx.DoOperations {if "delete" != op.Action {if i != opSize-1 {- return false+ return false, nil}continue@@ -625,12 +629,14 @@ func (tx *Transaction) processLargeDelete() bool {}if 1 > len(deleteOps) {- return false+ return false, nil}- tx.doLargeDelete(deleteOps)+ if txErr := tx.doLargeDelete(deleteOps); txErr != nil {+ return true, txErr+ }tx.flushDeletedAttributeViewBlocks()- return true+ return true, nil}func (tx *Transaction) processLargeInsert() (bool, *TxErr) {@@ -690,8 +696,7 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {id := operation.IDsrcTree, err := tx.loadTree(id)if err != nil {- logging.LogErrorf("load tree [%s] failed: %s", id, err)- return &TxErr{code: TxErrCodeBlockNotFound, id: id}+ return loadTreeTxErr(id, err)}srcNode := treenode.GetNodeInTree(srcTree, id)@@ -746,8 +751,7 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {var targetTree *parse.TreetargetTree, err = tx.loadTree(targetSiblingID)if err != nil {- logging.LogErrorf("load tree [%s] failed: %s", targetSiblingID, err)- return &TxErr{code: TxErrCodeBlockNotFound, id: targetSiblingID}+ return loadTreeTxErr(targetSiblingID, err)}isSameTree := srcTree.ID == targetTree.IDif isSameTree {@@ -826,8 +830,7 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {targetTree, err := tx.loadTree(targetParentID)if err != nil {- logging.LogErrorf("load tree [%s] failed: %s", targetParentID, err)- return &TxErr{code: TxErrCodeBlockNotFound, id: targetParentID}+ return loadTreeTxErr(targetParentID, err)}isSameTree := srcTree.ID == targetTree.IDif isSameTree {@@ -1054,9 +1057,7 @@ func (tx *Transaction) doPrependInsert(operation *Operation) (ret *TxErr) {}tree, err := tx.loadTree(block.ID)if err != nil {- msg := fmt.Sprintf("load tree [%s] failed: %s", block.ID, err)- logging.LogError(msg)- return &TxErr{code: TxErrCodeBlockNotFound, id: block.ID}+ return loadTreeTxErr(block.ID, err)}data := strings.ReplaceAll(operation.Data.(string), editor.FrontEndCaret, "")@@ -1162,9 +1163,7 @@ func (tx *Transaction) doAppendInsert(operation *Operation) (ret *TxErr) {}tree, err := tx.loadTree(block.ID)if err != nil {- msg := fmt.Sprintf("load tree [%s] failed: %s", block.ID, err)- logging.LogError(msg)- return &TxErr{code: TxErrCodeBlockNotFound, id: block.ID}+ return loadTreeTxErr(block.ID, err)}data := strings.ReplaceAll(operation.Data.(string), editor.FrontEndCaret, "")@@ -1277,8 +1276,7 @@ func (tx *Transaction) doAppend(operation *Operation) (ret *TxErr) {id := operation.IDsrcTree, err := tx.loadTree(id)if err != nil {- logging.LogErrorf("load tree [%s] failed: %s", id, err)- return &TxErr{code: TxErrCodeBlockNotFound, id: id}+ return loadTreeTxErr(id, err)}srcNode := treenode.GetNodeInTree(srcTree, id)@@ -1316,8 +1314,7 @@ func (tx *Transaction) doAppend(operation *Operation) (ret *TxErr) {targetTree, err := tx.loadTree(targetRootID)if err != nil {- logging.LogErrorf("load tree [%s] failed: %s", targetRootID, err)- return &TxErr{code: TxErrCodeBlockNotFound, id: targetRootID}+ return loadTreeTxErr(targetRootID, err)}isSameTree := srcTree.ID == targetTree.IDif isSameTree {@@ -1368,11 +1365,13 @@ func (tx *Transaction) doAppend(operation *Operation) (ret *TxErr) {return}-func (tx *Transaction) doLargeDelete(operations []*Operation) {+func (tx *Transaction) doLargeDelete(operations []*Operation) *TxErr {tree, err := tx.loadTree(operations[0].ID)if err != nil {- logging.LogErrorf("load tree [%s] failed: %s", operations[0].ID, err)- return+ if errors.Is(err, ErrBlockNotFound) {+ return nil+ }+ return loadTreeTxErr(operations[0].ID, err)}var ids []string@@ -1383,6 +1382,7 @@ func (tx *Transaction) doLargeDelete(operations []*Operation) {ids = gulu.Str.RemoveDuplicatedElem(ids)treenode.RemoveBlockTreesByIDs(tree.Box, ids)tx.writeTree(tree)+ return nil}func (tx *Transaction) doDelete(operation *Operation) (ret *TxErr) {@@ -1395,9 +1395,7 @@ func (tx *Transaction) doDelete(operation *Operation) (ret *TxErr) {return}- msg := fmt.Sprintf("load tree [%s] failed: %s", id, err)- logging.LogError(msg)- return &TxErr{code: TxErrCodeBlockNotFound, id: id}+ return loadTreeTxErr(id, err)}deletedNode := tx.doDelete0(operation, tree)@@ -1690,14 +1688,15 @@ func removeAttributeViewBoundItems(attrView *av.AttributeView, deletedBlockIDs m}func (tx *Transaction) doLargeInsert(operations []*Operation) *TxErr {- tree, _ := tx.loadTree(operations[0].ID)- if nil == tree {- tree, _ = tx.loadTree(operations[0].PreviousID)- if nil == tree {- tree, _ = tx.loadTree(operations[0].ParentID)- }- if nil == tree {- tree, _ = tx.loadTree(operations[0].NextID)+ var tree *parse.Tree+ for _, id := range []string{operations[0].ID, operations[0].PreviousID, operations[0].ParentID, operations[0].NextID} {+ var err error+ tree, err = tx.loadTree(id)+ if err != nil && !errors.Is(err, ErrBlockNotFound) {+ return loadTreeTxErr(id, err)+ }+ if tree != nil {+ break}}@@ -1748,9 +1747,7 @@ func (tx *Transaction) doInsert(operation *Operation) (ret *TxErr) {var err errortree, err := tx.loadTreeByBlockTree(bt)if err != nil {- msg := fmt.Sprintf("load tree [%s] failed: %s", bt.ID, err)- logging.LogError(msg)- return &TxErr{code: TxErrCodeBlockNotFound, id: bt.ID}+ return loadTreeTxErr(bt.ID, err)}if ret = tx.doInsert0(operation, tree); nil != ret {@@ -1999,8 +1996,7 @@ func (tx *Transaction) doUpdate(operation *Operation) (ret *TxErr) {tree, err := tx.loadTree(id)if err != nil {- logging.LogErrorf("load tree [%s] failed: %s", id, err)- return &TxErr{code: TxErrCodeBlockNotFound, id: id}+ return loadTreeTxErr(id, err)}data := strings.ReplaceAll(updateData, editor.FrontEndCaret, "")@@ -2375,8 +2371,7 @@ func (tx *Transaction) doUpdateUpdated(operation *Operation) (ret *TxErr) {return}- logging.LogErrorf("load tree [%s] failed: %s", id, err)- return &TxErr{code: TxErrCodeBlockNotFound, id: id}+ return loadTreeTxErr(id, err)}node := treenode.GetNodeInTree(tree, id)@@ -2480,8 +2475,7 @@ func (tx *Transaction) doSetAttrs(operation *Operation) (ret *TxErr) {id := operation.IDtree, err := tx.loadTree(id)if err != nil {- logging.LogErrorf("load tree [%s] failed: %s", id, err)- return &TxErr{code: TxErrCodeBlockNotFound, id: id}+ return loadTreeTxErr(id, err)}node := treenode.GetNodeInTree(tree, id)@@ -3217,6 +3211,17 @@ func restoreCreatedDocTreeSnapshot(tree *parse.Tree) error {return nil}+// loadTreeTxErr 保留文档读取失败的原因,仅索引中缺失的块归类为块不存在。+func loadTreeTxErr(id string, err error) *TxErr {+ msg := fmt.Sprintf("load tree [%s] failed: %s", id, err)+ logging.LogError(msg)+ code := TxErrCodePushMsg+ if errors.Is(err, ErrBlockNotFound) {+ code = TxErrCodeBlockNotFound+ }+ return &TxErr{code: code, msg: msg, id: id}+}+func (tx *Transaction) loadTreeByBlockTree(bt *treenode.BlockTree) (ret *parse.Tree, err error) {if nil == bt {return nil, ErrBlockNotFounddiff --git a/kernel/model/transaction_sync_fts5_test.go b/kernel/model/transaction_sync_fts5_test.goindex a8e441487b..125891845c 100644--- a/kernel/model/transaction_sync_fts5_test.go+++ b/kernel/model/transaction_sync_fts5_test.go@@ -3,6 +3,11 @@package modelimport (+ "bytes"+ "fmt"+ "os"+ "path/filepath"+ "strings""testing""github.com/siyuan-note/siyuan/kernel/cache"@@ -10,6 +15,37 @@ import ("github.com/siyuan-note/siyuan/kernel/util")+func TestPerformTransactionSyncEditsUTF8BOMDocument(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ path := filepath.Join(util.DataDir, fixture.box.ID, fixture.sourcePath)+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(path, append([]byte("\xef\xbb\xbf"), data...), 0600); err != nil {+ t.Fatal(err)+ }+ cache.RemoveTreeDataInBox(fixture.sourceID, fixture.box.ID)+ dom := fmt.Sprintf(`<div data-node-id="%s" data-type="NodeParagraph"><div contenteditable="true">edited BOM document</div></div>`, fixture.childID)+ if err = PerformTransactionSync(&Transaction{DoOperations: []*Operation{{Action: "update", ID: fixture.childID, Data: dom}}}); err != nil {+ t.Fatalf("BOM document could not be edited: %v", err)+ }+ cache.RemoveTreeDataInBox(fixture.sourceID, fixture.box.ID)+ tree, err := LoadTreeByBlockID(fixture.childID)+ if err != nil {+ t.Fatal(err)+ }+ node := treenode.GetNodeInTree(tree, fixture.childID)+ if node == nil || !strings.Contains(util.NewLute().RenderNodeBlockDOM(node), "edited BOM document") {+ t.Fatal("edit was not persisted")+ }+ stored, err := os.ReadFile(path)+ if err != nil || bytes.HasPrefix(stored, []byte("\xef\xbb\xbf")) {+ t.Fatalf("BOM was not removed when saving: %v", err)+ }+}+func TestPerformTransactionSyncPreservesQueueOrder(t *testing.T) {fixture := setupStructureTransactionTest(t)setupFoldTransactionDatabase(t, fixture)diff --git a/kernel/model/transaction_sync_test.go b/kernel/model/transaction_sync_test.goindex 5f5f9c8962..473adb0b16 100644--- a/kernel/model/transaction_sync_test.go+++ b/kernel/model/transaction_sync_test.go@@ -21,9 +21,60 @@ import ("github.com/gorilla/websocket""github.com/olahol/melody"+ "github.com/siyuan-note/siyuan/kernel/cache""github.com/siyuan-note/siyuan/kernel/util")+func TestTransactionTreeLoadErrorPush(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ path := filepath.Join(util.DataDir, fixture.box.ID, fixture.sourcePath)+ if err := os.WriteFile(path, []byte(`{"Spec":`), 0600); err != nil {+ t.Fatal(err)+ }+ cache.RemoveTreeDataInBox(fixture.sourceID, fixture.box.ID)+ 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: "update", ID: fixture.childID, Data: "<div>updated</div>"}}}+ if err = PerformTransactionSync(tx); err == nil || !strings.Contains(err.Error(), "unexpected end of JSON input") {+ t.Fatalf("transaction did not report parse failure: %v", err)+ }+ if err = connection.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {+ t.Fatal(err)+ }+ var event struct {+ Cmd, Msg string+ Code int+ }+ if err = connection.ReadJSON(&event); err != nil {+ t.Fatal(err)+ }+ if event.Cmd != "txerr" || event.Code != TxErrCodePushMsg || !strings.Contains(event.Msg, "unexpected end of JSON input") || strings.Contains(event.Msg, "block not found") {+ t.Fatalf("frontend error lost its cause: %+v", event)+ }+}+func TestPerformTransactionSyncReturnsTransactionError(t *testing.T) {for _, mode := range []string{"sync", "queue"} {t.Run(mode, func(t *testing.T) {diff --git a/kernel/model/transaction_test.go b/kernel/model/transaction_test.goindex f94a16b265..8e9f972faf 100644--- a/kernel/model/transaction_test.go+++ b/kernel/model/transaction_test.go@@ -19,16 +19,84 @@ package modelimport ("encoding/json""errors"+ "fmt"+ "os""path/filepath""strings""testing""github.com/88250/lute/ast""github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/cache""github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util")+func TestTransactionTreeLoadErrors(t *testing.T) {+ for _, action := range []string{"update", "move", "append", "prependInsert", "appendInsert", "insert", "delete", "doUpdateUpdated", "setAttrs", "largeInsert", "largeDelete"} {+ t.Run(action, func(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ path := filepath.Join(util.DataDir, fixture.box.ID, fixture.sourcePath)+ corrupt := []byte(`{"Spec":`)+ if err := os.WriteFile(path, corrupt, 0600); err != nil {+ t.Fatal(err)+ }+ cache.RemoveTreeDataInBox(fixture.sourceID, fixture.box.ID)+ tx := &Transaction{trees: map[string]*parse.Tree{}, luteEngine: util.NewLute()}+ op := &Operation{ID: fixture.childID, ParentID: fixture.sourceID, Data: "<div>update</div>"}+ var txErr *TxErr+ switch action {+ case "update":+ txErr = tx.doUpdate(op)+ case "move":+ txErr = tx.doMove(op)+ case "append":+ txErr = tx.doAppend(op)+ case "prependInsert":+ txErr = tx.doPrependInsert(op)+ case "appendInsert":+ txErr = tx.doAppendInsert(op)+ case "insert":+ txErr = tx.doInsert(op)+ case "delete":+ txErr = tx.doDelete(op)+ case "doUpdateUpdated":+ txErr = tx.doUpdateUpdated(op)+ case "setAttrs":+ txErr = tx.doSetAttrs(op)+ case "largeInsert":+ op.ID = "20261020000000-new0001"+ txErr = tx.doLargeInsert([]*Operation{op})+ case "largeDelete":+ for i := 0; i < 32; i++ {+ tx.DoOperations = append(tx.DoOperations, &Operation{Action: "delete", ID: fixture.childID})+ }+ var handled bool+ handled, txErr = tx.processLargeDelete()+ if !handled {+ t.Fatal("bulk delete did not run")+ }+ }+ if txErr == nil || txErr.Code() != TxErrCodePushMsg || !strings.Contains(txErr.msg, "unexpected end of JSON input") || !strings.Contains(txErr.msg, "load tree [") {+ t.Fatalf("parse failure lost its cause: %v", txErr)+ }+ retained, err := os.ReadFile(path)+ if err != nil || string(retained) != string(corrupt) {+ t.Fatalf("failed transaction changed source: %v", err)+ }+ })+ }+}++func TestTransactionMissingBlockLoadError(t *testing.T) {+ for _, cause := range []error{ErrBlockNotFound, fmt.Errorf("wrapped: %w", ErrBlockNotFound)} {+ txErr := loadTreeTxErr("20261020000000-missing", cause)+ if txErr.Code() != TxErrCodeBlockNotFound || !strings.Contains(txErr.msg, cause.Error()) {+ t.Fatalf("missing block misclassified: %v", txErr)+ }+ }+}+func TestDoUpdateRejectsInvalidData(t *testing.T) {tests := []any{nil, 1, ""}for _, data := range tests {