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: Preserve editor state after database collection https://github.com/siyuan-note/siyuan/issues/20668
Daniel4a31471ca510
diff --git a/kernel/api/contract_av_automation_broadcast_test.go b/kernel/api/contract_av_automation_broadcast_test.gonew file mode 100644index 0000000000..42777a4f6b--- /dev/null+++ b/kernel/api/contract_av_automation_broadcast_test.go@@ -0,0 +1,131 @@+package api++import (+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/gorilla/websocket"+ "github.com/olahol/melody"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// 使用真实自动收集事务和多个会话,验证发起方保留本地正文,其他客户端最终收到绑定属性。+func testAutomationCollectionBroadcast(t *testing.T, fixture *attributeViewContextFilterAPIFixture) {+ t.Helper()+ push := melody.New()+ connected := make(chan *melody.Session, 3)+ push.HandleConnect(func(session *melody.Session) {+ util.AddPushChan(session)+ connected <- session+ })+ push.HandleDisconnect(util.RemovePushChan)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {+ _ = push.HandleRequest(w, request)+ }))+ defer server.Close()+ defer push.Close()+ clients := map[string]*websocket.Conn{}+ for _, id := range []string{"source", "desktop", "mobile"} {+ connection, response, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http")++ "/?app=automation-broadcast&id="+id+"&type=protyle", nil)+ if err != nil {+ t.Fatal(err)+ }+ response.Body.Close()+ defer connection.Close()+ select {+ case session := <-connected:+ defer util.RemovePushChan(session)+ case <-time.After(5 * time.Second):+ t.Fatal("automation observer did not connect")+ }+ clients[id] = connection+ }+ dom := func(content string) string {+ return fmt.Sprintf(`<div data-node-id="%s" data-type="NodeParagraph"><div contenteditable="true">%s</div></div>`, fixture.paragraphID, content)+ }+ tx := &model.Transaction{+ DoOperations: []*model.Operation{{Action: "update", ID: fixture.paragraphID,+ Data: dom(`Source <span data-type="tag">collect</span>`)}},+ UndoOperations: []*model.Operation{{Action: "update", ID: fixture.paragraphID, Data: dom("not a database")}},+ }+ tx.MarkFromAPI()+ if err := model.PerformTxSync(tx); err != nil {+ t.Fatal(err)+ }+ defer func() {+ undo := &model.Transaction{DoOperations: tx.UndoOperations}+ undo.MarkReplay()+ if err := model.PerformTxSync(undo); err != nil {+ t.Error(err)+ }+ }()+ if shouldBroadcastAttrViewTransactions([]*model.Transaction{tx}) {+ t.Error("automatic collection would replay the source edit in its initiating editor")+ }+ contracts, err := transactionContracts([]*model.Transaction{tx})+ if err != nil || len(contracts) != 1 {+ t.Fatalf("transaction contract conversion failed: %v", err)+ }+ pushTransactions("automation-broadcast", "source", []*model.Transaction{tx})+ if err = push.Broadcast([]byte(`{"cmd":"automation-broadcast-barrier"}`)); err != nil {+ t.Fatal(err)+ }+ for id, connection := range clients {+ if err = connection.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {+ t.Fatal(err)+ }+ var operations []*model.Operation+ for {+ var event struct {+ Cmd string+ Data json.RawMessage+ }+ if err = connection.ReadJSON(&event); err != nil {+ t.Fatal(err)+ }+ if event.Cmd == "automation-broadcast-barrier" {+ break+ }+ if event.Cmd == "transactions" {+ var transactions []*model.Transaction+ if err = json.Unmarshal(event.Data, &transactions); err != nil {+ t.Fatal(err)+ }+ for _, transaction := range transactions {+ operations = append(operations, transaction.DoOperations...)+ }+ }+ }+ var sourceUpdates int+ var finalAttrs map[string]any+ var collected bool+ for _, operation := range operations {+ if operation.Action == "update" && operation.ID == fixture.paragraphID {+ sourceUpdates+++ finalAttrs = nil+ }+ if operation.Action == "insertAttrViewBlock" && operation.AvID == fixture.attrView.ID {+ collected = true+ }+ if operation.Action == "updateAttrs" && operation.ID == fixture.paragraphID {+ finalAttrs = operation.Data.(map[string]any)["new"].(map[string]any)+ }+ }+ wantUpdates := 1+ if id == "source" {+ wantUpdates = 0+ }+ if sourceUpdates != wantUpdates || !collected || finalAttrs[av.NodeAttrNameAvs] != fixture.attrView.ID ||+ finalAttrs[av.NodeAttrViewNames] == nil || finalAttrs[av.NodeAttrViewNames] == "" {+ t.Errorf("%s: source updates=%d, collected=%v, final binding=%v", id, sourceUpdates, collected, finalAttrs)+ }+ }+}diff --git a/kernel/api/contract_av_automation_test.go b/kernel/api/contract_av_automation_test.goindex 8e9679af97..21f3e6c229 100644--- a/kernel/api/contract_av_automation_test.go+++ b/kernel/api/contract_av_automation_test.go@@ -162,6 +162,7 @@ func TestAVContractAutomationWrites(t *testing.T) {Data: &av.AutomationConfig{Spec: 1, Rules: []*av.AutomationRule{collection}}}}); err != nil {t.Fatal(err)}+ t.Run("collection broadcast", func(t *testing.T) { testAutomationCollectionBroadcast(t, fixture) })call("/api/av/getAttributeView", map[string]any{"id": database.ID}, getAttributeView)call("/api/av/previewAttributeViewCollection", map[string]any{"avID": database.ID, "ruleID": collection.ID}, previewAttributeViewCollection)call("/api/block/appendBlock", map[string]any{"parentID": tree.ID, "dataType": "markdown", "data": "Source #collect#"}, appendBlock)diff --git a/kernel/api/transaction.go b/kernel/api/transaction.goindex 39d2b81227..0d09295b1c 100644--- a/kernel/api/transaction.go+++ b/kernel/api/transaction.go@@ -224,6 +224,27 @@ func pushTransactions(app, session string, transactions []*model.Transaction) {}util.PushEvent(evt)+ if pushMode == util.PushModeBroadcastExcludeSelf {+ // 发起编辑器只补充自动操作,正文继续使用本地输入和光标。+ var automatic []*model.Transaction+ for _, tx := range transactions {+ var operations []*model.Operation+ for _, operation := range tx.DoOperations {+ if operation.IsAutomaticAttributeViewOperation() {+ operations = append(operations, operation)+ }+ }+ if len(operations) > 0 {+ automatic = append(automatic, &model.Transaction{Timestamp: tx.Timestamp,+ DoOperations: operations, UndoOperations: []*model.Operation{}})+ }+ }+ if len(automatic) > 0 {+ evt.PushMode = util.PushModeSingleSelf+ evt.Data = automatic+ util.PushEvent(evt)+ }+ }}// undoState 查询指定文档的撤销/重做可用性及栈顶关联的 mutatedRootIDs。@@ -401,7 +422,8 @@ func holdBlockSwapReplayRequests(c *gin.Context, tx *model.Transaction, rootIDsfunc shouldBroadcastAttrViewTransactions(transactions []*model.Transaction) bool {for _, tx := range transactions {for _, operation := range tx.DoOperations {- if nil != operation && "setAttrViewName" != operation.Action && strings.Contains(strings.ToLower(operation.Action), "attrview") {+ if nil != operation && !operation.IsAutomaticAttributeViewOperation() &&+ "setAttrViewName" != operation.Action && strings.Contains(strings.ToLower(operation.Action), "attrview") {return true}}diff --git a/kernel/model/attribute_view_automation.go b/kernel/model/attribute_view_automation.goindex 521ffd92ad..dfdadbd914 100644--- a/kernel/model/attribute_view_automation.go+++ b/kernel/model/attribute_view_automation.go@@ -40,6 +40,23 @@ type attributeViewAutomationState struct {recordUndo boolpaused []automationPausedRuleresults map[string]*automationRuleResult+ blockAttrs map[string]*Operation+}++// 将自动化产生的最终属性补在正文操作之后,避免旧正文覆盖新绑定。+func (tx *Transaction) appendAutomationBlockAttrs() {+ state := tx.attributeViewAutomations+ if state == nil {+ return+ }+ ids := make([]string, 0, len(state.blockAttrs))+ for id := range state.blockAttrs {+ ids = append(ids, id)+ }+ sort.Strings(ids)+ for _, id := range ids {+ tx.DoOperations = append(tx.DoOperations, state.blockAttrs[id])+ }}type automationUnavailableReference struct {diff --git a/kernel/model/attribute_view_collection.go b/kernel/model/attribute_view_collection.goindex 1056ce085b..9d395ad6ce 100644--- a/kernel/model/attribute_view_collection.go+++ b/kernel/model/attribute_view_collection.go@@ -448,6 +448,10 @@ func (tx *Transaction) runAttributeViewCollections() error {row := view.GetBlockValueByBoundID(blockID)// 已有条目及用户字段始终保留,失配不触发隐式清理。if row != nil {+ // 连续输入可能使用绑定通知前的快照,按数据库现存条目补回绑定属性。+ if !slices.Contains(strings.Split(afterNodes[blockID].IALAttr(av.NodeAttrNameAvs), ","), id) {+ bindBlockAv0(tx, id, afterNodes[blockID], tree)+ }continue}for _, rule := range rules {diff --git a/kernel/model/attribute_view_collection_fts5_test.go b/kernel/model/attribute_view_collection_fts5_test.goindex 7d781ba21f..062823cb94 100644--- a/kernel/model/attribute_view_collection_fts5_test.go+++ b/kernel/model/attribute_view_collection_fts5_test.go@@ -5,6 +5,7 @@ package modelimport ("encoding/json""errors"+ "fmt""os""path/filepath""testing"@@ -107,6 +108,75 @@ func TestBlockCollectionTransitionsAndUndo(t *testing.T) {}}+func TestBlockCollectionSynchronizesFinalBindingAttrs(t *testing.T) {+ fixture, view, _ := setupBlockCollectionTest(t)+ tx := blockCollectionTags(t, fixture.sourceID, "todo")+ if err := PerformTxSync(tx); err != nil {+ t.Fatal(err)+ }+ last := tx.DoOperations[len(tx.DoOperations)-1]+ if last.Action != "updateAttrs" || last.ID != fixture.sourceID || !last.IsAutomaticAttributeViewOperation() {+ t.Fatalf("final binding attributes must follow the source and database operations: %+v", last)+ }+ data := last.Data.(map[string]any)+ attrs := data["new"].(map[string]string)+ if attrs[av.NodeAttrNameAvs] != view.ID || attrs[av.NodeAttrViewNames] == "" {+ t.Fatalf("missing binding or badge in the transaction: %v", attrs)+ }+ tree, err := LoadTreeByBlockID(fixture.sourceID)+ if err != nil {+ t.Fatal(err)+ }+ if tree.Root.IALAttr(av.NodeAttrNameAvs) != attrs[av.NodeAttrNameAvs] {+ t.Fatal("broadcast binding differs from the persisted source")+ }+ for _, operations := range [][]*Operation{cloneOperations(tx.UndoOperations), cloneOperations(tx.DoOperations)} {+ replay := &Transaction{DoOperations: operations, isReplay: true}+ if err = PerformTxSync(replay); err != nil {+ t.Fatal(err)+ }+ last = replay.DoOperations[len(replay.DoOperations)-1]+ if last.Action != "updateAttrs" || last.ID != fixture.sourceID {+ t.Fatalf("replay did not finish with the current binding attributes: %+v", last)+ }+ tree, err = LoadTreeByBlockID(fixture.sourceID)+ if err != nil {+ t.Fatal(err)+ }+ attrs = last.Data.(map[string]any)["new"].(map[string]string)+ if attrs[av.NodeAttrNameAvs] != tree.Root.IALAttr(av.NodeAttrNameAvs) {+ t.Fatal("replay sent a stale binding")+ }+ }+}++func TestBlockCollectionPreservesBindingDuringQueuedEdits(t *testing.T) {+ fixture, view, _ := setupBlockCollectionTest(t)+ view.Automations.Rules[0].BlockSource.Types = []string{"p"}+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ for _, content := range []string{`<span data-type="tag">todo</span>`, `More <span data-type="tag">todo</span> text`} {+ // 连续输入的正文快照可能早于上一笔自动绑定的属性通知。+ dom := fmt.Sprintf(`<div data-node-id="%s" data-type="NodeParagraph"><div contenteditable="true">%s</div></div>`, fixture.childID, content)+ tx := &Transaction{fromAPI: true, DoOperations: []*Operation{{Action: "update", ID: fixture.childID, Data: dom}}}+ if err := PerformTxSync(tx); err != nil {+ t.Fatal(err)+ }+ tree, err := LoadTreeByBlockID(fixture.childID)+ if err != nil {+ t.Fatal(err)+ }+ if treenode.GetNodeInTree(tree, fixture.childID).IALAttr(av.NodeAttrNameAvs) != view.ID {+ t.Fatal("queued source edit discarded the existing database binding")+ }+ view = readAttributeViewItemsTest(t, view.ID)+ if len(view.GetBlockKeyValues().Values) != 1 || view.GetBlockValueByBoundID(fixture.childID) == nil {+ t.Fatal("queued source edit duplicated or removed the collected row")+ }+ }+}+func TestBlockCollectionMultipleRulesAndManualRows(t *testing.T) {fixture, view, _ := setupBlockCollectionTest(t)first := view.Automations.Rules[0]diff --git a/kernel/model/attribute_view_collection_notification_fts5_test.go b/kernel/model/attribute_view_collection_notification_fts5_test.gonew file mode 100644index 0000000000..70676ee215--- /dev/null+++ b/kernel/model/attribute_view_collection_notification_fts5_test.go@@ -0,0 +1,114 @@+//go:build fts5++package model++import (+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "net/url"+ "strings"+ "testing"+ "time"++ "github.com/88250/lute/parse"+ "github.com/gorilla/websocket"+ "github.com/olahol/melody"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestBlockCollectionBindingNotificationsFollowCommit(t *testing.T) {+ for _, fail := range []bool{false, true} {+ name := "commit"+ if fail {+ name = "rollback"+ }+ t.Run(name, func(t *testing.T) {+ fixture, _, _ := setupBlockCollectionTest(t)+ 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, request *http.Request) {+ _ = push.HandleRequest(w, request)+ }))+ defer server.Close()+ defer push.Close()+ connection, response, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http")++ "/?app="+url.QueryEscape(t.Name())+"&id=observer&type=protyle", nil)+ if err != nil {+ t.Fatal(err)+ }+ response.Body.Close()+ defer connection.Close()+ select {+ case session := <-connected:+ defer util.RemovePushChan(session)+ case <-time.After(5 * time.Second):+ t.Fatal("collection observer did not connect")+ }+ countAttrs := func() int {+ t.Helper()+ if err := push.Broadcast([]byte(`{"cmd":"collection-notification-barrier"}`)); err != nil {+ t.Fatal(err)+ }+ if err := connection.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {+ t.Fatal(err)+ }+ count := 0+ for {+ var event struct {+ Cmd string+ Data json.RawMessage+ }+ if err := connection.ReadJSON(&event); err != nil {+ t.Fatal(err)+ }+ if event.Cmd == "collection-notification-barrier" {+ return count+ }+ if event.Cmd != "transactions" {+ continue+ }+ var transactions []*Transaction+ if err := json.Unmarshal(event.Data, &transactions); err != nil {+ t.Fatal(err)+ }+ for _, tx := range transactions {+ for _, operation := range tx.DoOperations {+ if operation.Action == "updateAttrs" && operation.ID == fixture.sourceID {+ count+++ }+ }+ }+ }+ }+ tx := blockCollectionTags(t, fixture.sourceID, "todo")+ tx.writeTransactionTree = func(tree *parse.Tree) error {+ if count := countAttrs(); count != 0 {+ t.Errorf("binding was announced before commit: %d", count)+ }+ if fail {+ return errors.New("injected collection commit failure")+ }+ _, err := filesys.WriteTree(tree)+ return err+ }+ if err = PerformTxSync(tx); (err != nil) != fail {+ t.Fatalf("unexpected commit result: %v", err)+ }+ want := 1+ if fail {+ want = 0+ }+ if count := countAttrs(); count != want {+ t.Fatalf("binding notifications after %s: %d, want %d", name, count, want)+ }+ })+ }+}diff --git a/kernel/model/attribute_view_transaction.go b/kernel/model/attribute_view_transaction.goindex c86957c2a6..d06bcaa577 100644--- a/kernel/model/attribute_view_transaction.go+++ b/kernel/model/attribute_view_transaction.go@@ -126,6 +126,18 @@ func (tx *Transaction) invalidateAttributeViewHistory(avID string) {func (tx *Transaction) finishAttributeViewMutation(rollback bool) {if !rollback {if automation := tx.attributeViewAutomations; automation != nil {+ var attrs []*Operation+ for _, operation := range tx.DoOperations {+ if operation == automation.blockAttrs[operation.ID] {+ attrs = append(attrs, operation)+ }+ }+ if len(attrs) > 0 {+ // 块 API 不广播完整事务,提交后仍需独立同步属性。+ event := util.NewCmdResult("transactions", 0, util.PushModeBroadcast)+ event.Data = []*Transaction{{DoOperations: attrs, UndoOperations: []*Operation{}}}+ util.PushEvent(event)+ }for _, paused := range automation.paused {util.PushMsg(paused.message(), 7000)}diff --git a/kernel/model/blockial.go b/kernel/model/blockial.goindex 6ee4ac61bb..0af2ca21b8 100644--- a/kernel/model/blockial.go+++ b/kernel/model/blockial.go@@ -359,7 +359,19 @@ func setNodeAttrsWithTx(tx *Transaction, node *ast.Node, tree *parse.Tree, nameVcache.RemoveDocIALInBox(tree.Path, tree.Box)cache.PutDocIALInBox(tree.Path, tree.Box, newAttrs)}- pushBlockAttrs(oldAttrs, node)+ if state := tx.attributeViewAutomations; state != nil {+ if state.blockAttrs == nil {+ state.blockAttrs = map[string]*Operation{}+ }+ operation := blockAttrsOperation(oldAttrs, node)+ if previous := state.blockAttrs[node.ID]; previous != nil {+ operation.Data.(map[string]any)["old"] = previous.Data.(map[string]any)["old"]+ }+ operation.attributeViewAutomation = true+ state.blockAttrs[node.ID] = operation+ } else {+ pushBlockAttrs(oldAttrs, node)+ }pushDocSortModeChanged(oldAttrs, node, tree)return}@@ -541,16 +553,19 @@ func normalizeIconValue(value string) string {return ret}-func pushBlockAttrs(oldAttrs map[string]string, node *ast.Node) {+func blockAttrsOperation(oldAttrs map[string]string, node *ast.Node) *Operation {newAttrs := parse.IAL2Map(node.KramdownIAL)data := map[string]any{"old": oldAttrs, "new": newAttrs}if "" != node.AttributeViewType {data["data-av-type"] = node.AttributeViewType}- doOp := &Operation{Action: "updateAttrs", Data: data, ID: node.ID, RootID: treenode.TreeRoot(node).ID}+ return &Operation{Action: "updateAttrs", Data: data, ID: node.ID, RootID: treenode.TreeRoot(node).ID}+}++func pushBlockAttrs(oldAttrs map[string]string, node *ast.Node) {evt := util.NewCmdResult("transactions", 0, util.PushModeBroadcast)evt.Data = []*Transaction{{- DoOperations: []*Operation{doOp},+ DoOperations: []*Operation{blockAttrsOperation(oldAttrs, node)},UndoOperations: []*Operation{},}}util.PushEvent(evt)diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex 07750e530d..15bcbc590c 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -3066,6 +3066,7 @@ func (tx *Transaction) commit() (err error) {crossTreeMoveRefRefreshes := append([]crossTreeMoveRefRefresh(nil), tx.crossTreeMoveRefRefreshes...)IncSync()tx.mutatedRootIDs = tx.GetMutatedRootIDs()+ tx.appendAutomationBlockAttrs()tx.state.Store(2)committed = true// 已提交且 trees 稳定后记录到全局撤销日志(rollback 不记录)