Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Invalidate document undo history after batch writes https://github.com/siyuan-note/siyuan/issues/20414

Daniel734b8ac9a785
diff --git a/app/src/protyle/index.ts b/app/src/protyle/index.ts
index c5a2a4772c..c2928d6807 100644
--- a/app/src/protyle/index.ts
+++ b/app/src/protyle/index.ts
@@ -475,6 +475,7 @@ export class Protyle {
// 多窗口/多端:用广播附带的撤销状态同步本地镜像
if (data.context?.undoState) {
syncMirrorFromBroadcast(data.context.undoState);
+ refreshUndoButtons(this.protyle);
}
const transactionOperations = getTransactionOperations(data.data);
queueDatabaseRowRefreshForOperations(this.protyle.id, transactionOperations);
diff --git a/app/src/protyle/undo/undoStatus.test.ts b/app/src/protyle/undo/undoStatus.test.ts
index 284759ba0d..3ddc0a8a36 100644
--- a/app/src/protyle/undo/undoStatus.test.ts
+++ b/app/src/protyle/undo/undoStatus.test.ts
@@ -42,3 +42,35 @@ test("local undo and redo refresh statistics after applying operations and resto
assert.deepEqual(calls, ["apply", "selection", "selected IDs", "statistics"]);
}
});
+
+test("history invalidation broadcasts refresh buttons without editor operations", () => {
+ const calls: string[] = [];
+ const protyle = {
+ id: "editor", block: {rootID: "document"},
+ preview: {element: {classList: {contains: () => true}}},
+ wysiwyg: {element: {childElementCount: 1}},
+ element: {dataset: {loading: "finished"}},
+ };
+ const states = {document: {canUndo: false, canRedo: false}};
+ const dependencies = {
+ syncMirrorFromBroadcast: (value: unknown) => {
+ assert.equal(value, states);
+ calls.push("mirror");
+ },
+ refreshUndoButtons: (value: unknown) => {
+ assert.equal(value, protyle);
+ calls.push("buttons");
+ },
+ getTransactionOperations: (): unknown[] => [],
+ queueDatabaseRowRefreshForOperations() {},
+ };
+ const code = transpileModule(readFileSync("src/protyle/index.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText;
+ const exports: {Protyle?: {prototype: {onTransaction: (data: unknown) => void}}} = {};
+ runInNewContext(code, {exports, require: () => dependencies});
+ exports.Protyle.prototype.onTransaction.call({protyle}, {
+ data: [], context: {undoState: states, rootIDs: ["document"]},
+ });
+ assert.deepEqual(calls, ["mirror", "buttons"]);
+});
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 2213cf6a32..f278222241 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -3246,6 +3246,9 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin","writable"];
};
+ /**
+ * 实际重链接成功写盘后清理文档及关联跨文档撤销记录;预览和写入失败不清理历史。
+ */
"/api/asset/relinkAsset": {
request: RelinkAssetRequestInput;
response: { "code": 0; "data": AssetReferencesData; "msg": string; } | { "code": -1; "data": ({ "closeTimeout": number; } & { "dryRun"?: never; "historyPath"?: never; "items"?: never; "references"?: never; "skippedNotebooks"?: never; "unavailableAttributeViews"?: never; "updated"?: never; }) | null | (AssetReferencesData & { "closeTimeout"?: never; }); "msg": string; };
@@ -5227,6 +5230,9 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin","writable"];
};
+ /**
+ * 格式化成功写盘后清理文档及关联跨文档撤销记录,并广播更新后的撤销状态。
+ */
"/api/format/autoSpace": {
request: TrimmedIDRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -5234,6 +5240,9 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin","writable"];
};
+ /**
+ * 转换成功写盘后清理文档及关联跨文档撤销记录;未改写文档时保留历史。
+ */
"/api/format/netAssets2LocalAssets": {
request: TrimmedIDRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -5241,6 +5250,9 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin","writable"];
};
+ /**
+ * 转换成功写盘后清理文档及关联跨文档撤销记录;未改写文档时保留历史。
+ */
"/api/format/netImg2LocalAssets": {
request: NetImageAssetsRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -6382,6 +6394,7 @@ export interface APIPOSTRoutes {
* SQL(2)和语义搜索(4)返回 code=1 与提示信息,不执行替换;ids 为空时表示替换全部。
* 文本与查询语法替换的所有启用类型遵循搜索配置的 caseSensitive,替换串按字面量写入。
* 正则模式的大小写匹配由表达式决定,替换串支持捕获组展开。
+ * 每次文档写盘成功后清理该文档及关联跨文档撤销记录,并广播更新后的撤销状态。
*/
"/api/search/findReplace": {
request: FindReplaceRequestInput;
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 43c14eb51c..ff7f6b94c3 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -474,8 +474,14 @@ var GetRecentUpdatedBlocks = define[EmptyRequest, []*SearchBlock]("getRecentUpda
var Zip = define[ZipRequest, Null]("zip", "/api/archive/zip", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
var Unzip = define[UnzipRequest, Null]("unzip", "/api/archive/unzip", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
+
+// 格式化成功写盘后清理文档及关联跨文档撤销记录,并广播更新后的撤销状态。
var AutoSpace = define[TrimmedIDRequest, Null]("autoSpace", "/api/format/autoSpace", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
+
+// 转换成功写盘后清理文档及关联跨文档撤销记录;未改写文档时保留历史。
var NetAssets2LocalAssets = define[TrimmedIDRequest, Null]("netAssets2LocalAssets", "/api/format/netAssets2LocalAssets", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
+
+// 转换成功写盘后清理文档及关联跨文档撤销记录;未改写文档时保留历史。
var NetImg2LocalAssets = define[NetImageAssetsRequest, Null]("netImg2LocalAssets", "/api/format/netImg2LocalAssets", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
var PushMsg = define[NotificationRequest, NotificationData]("pushMsg", "/api/notification/pushMsg", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")
var PushErrMsg = define[NotificationRequest, NotificationData]("pushErrMsg", "/api/notification/pushErrMsg", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")
@@ -739,6 +745,7 @@ var SearchEmbedBlock = define[SearchEmbedBlockRequest, EmbedBlocksData]("searchE
// SQL(2)和语义搜索(4)返回 code=1 与提示信息,不执行替换;ids 为空时表示替换全部。
// 文本与查询语法替换的所有启用类型遵循搜索配置的 caseSensitive,替换串按字面量写入。
// 正则模式的大小写匹配由表达式决定,替换串支持捕获组展开。
+// 每次文档写盘成功后清理该文档及关联跨文档撤销记录,并广播更新后的撤销状态。
var FindReplace = define[FindReplaceRequest, Null]("findReplace", "/api/search/findReplace", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")
var SemanticSearchBlock = define[SearchBlockRequest, SearchBlocksData]("semanticSearchBlock", "/api/search/semanticSearchBlock", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")
@@ -1022,6 +1029,8 @@ var ImportOCRModels = define[ImportOCRModelsRequest, OCRModel]("importOCRModels"
// 拒绝加密笔记本资源重命名;空名称或与原文件名相同的名称返回 code=0、data.newPath=""。
var RenameAsset = define[RenameAssetRequest, AssetRenameData]("renameAsset", "/api/asset/renameAsset", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
var FindAssetReferences = define[FindAssetReferencesRequest, AssetReferencesData]("findAssetReferences", "/api/asset/findAssetReferences", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{DataOnError: true}, "POST")
+
+// 实际重链接成功写盘后清理文档及关联跨文档撤销记录;预览和写入失败不清理历史。
var RelinkAsset = define[RelinkAssetRequest, AssetReferencesData]("relinkAsset", "/api/asset/relinkAsset", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{DataOnError: true}, "POST")
var GetDocImageAssets = define[AssetDocumentRequest, []string]("getDocImageAssets", "/api/asset/getDocImageAssets", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")
var GetDocAssets = define[AssetDocumentAssetsRequest, []string]("getDocAssets", "/api/asset/getDocAssets", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")
diff --git a/kernel/model/asset_relink_batch.go b/kernel/model/asset_relink_batch.go
index aa1e872e64..a346b326c1 100644
--- a/kernel/model/asset_relink_batch.go
+++ b/kernel/model/asset_relink_batch.go
@@ -573,6 +573,7 @@ func (p *assetRelinkPlan) apply() (err error) {
var size uint64
size, writeErr = filesys.WriteTreeIfUnchanged(file.tree, file.before)
if writeErr == nil {
+ invalidateDocumentHistory(file.tree.ID)
sql.UpsertTreeQueue(file.tree)
refreshDocInfoWithSize(file.tree, size)
reload[file.tree.Root.ID] = true
diff --git a/kernel/model/asset_relink_integration_test.go b/kernel/model/asset_relink_integration_test.go
index e7edca69fb..6ecd2326da 100644
--- a/kernel/model/asset_relink_integration_test.go
+++ b/kernel/model/asset_relink_integration_test.go
@@ -74,10 +74,12 @@ func TestAssetRelinkPersistenceAndHistory(t *testing.T) {
if err != nil || len(preview.References) != 3 {
t.Fatalf("preview: %+v %v", preview, err)
}
+ seedDocumentHistory(t, tree.ID, fixture.targetID)
result, err := RelinkAsset("assets/a.png", "assets/b.webp", false)
if err != nil || result.Updated != 3 || result.HistoryPath == "" || len(result.References) != len(preview.References) {
t.Fatalf("apply: %+v %v", result, err)
}
+ requireDocumentHistoryCleared(t, tree.ID, fixture.targetID)
checkAssetRelinkUnavailable(t, result, orphan)
orphanAfter, _ := os.ReadFile(filepath.Join(util.DataDir, orphan.Box, orphan.Path))
if !bytes.Equal(orphanBefore, orphanAfter) {
diff --git a/kernel/model/assets.go b/kernel/model/assets.go
index 1f1c1f174c..f8878f0993 100644
--- a/kernel/model/assets.go
+++ b/kernel/model/assets.go
@@ -885,6 +885,7 @@ func netAssets2LocalAssets0(tree *parse.Tree, onlyImg bool, originalURL string,
if err = writeTreeUpsertQueue(tree); err != nil {
return
}
+ invalidateDocumentHistory(tree.ID)
util.PushUpdateMsg(msgId, fmt.Sprintf(Conf.Language(120), files, humanize.BytesCustomCeil(uint64(size), 2)), 5000)
if 0 < forbiddenCount {
diff --git a/kernel/model/document_history_fts5_test.go b/kernel/model/document_history_fts5_test.go
new file mode 100644
index 0000000000..34c9660878
--- /dev/null
+++ b/kernel/model/document_history_fts5_test.go
@@ -0,0 +1,90 @@
+//go:build fts5
+
+package model
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func seedDocumentHistory(t *testing.T, rootIDs ...string) {
+ t.Helper()
+ previous := GlobalUndoLog
+ GlobalUndoLog = newUndoLog(64)
+ t.Cleanup(func() { GlobalUndoLog = previous })
+ for _, id := range rootIDs {
+ entry := &UndoEntry{id: id, mutatedRootIDs: []string{id}}
+ GlobalUndoLog.stacks[id] = &undoStack{undoStack: []*UndoEntry{entry}, redoStack: []*UndoEntry{entry}}
+ }
+}
+
+func requireDocumentHistoryCleared(t *testing.T, changed, unrelated string) {
+ t.Helper()
+ if canUndo, canRedo, _ := GlobalUndoLog.State(changed); canUndo || canRedo {
+ t.Fatal("rewritten document retained stale undo or redo")
+ }
+ if canUndo, canRedo, _ := GlobalUndoLog.State(unrelated); !canUndo || !canRedo {
+ t.Fatal("unrelated document lost history")
+ }
+}
+
+func TestBatchDocumentWritesInvalidateHistory(t *testing.T) {
+ for _, action := range []string{"replace", "format", "network-assets", "network-no-change"} {
+ t.Run(action, func(t *testing.T) {
+ fixture := setupStructureTransactionTest(t)
+ setupFoldTransactionDatabase(t, fixture)
+ Conf.Search = conf.NewSearch()
+ tree, err := LoadTreeByBlockID(fixture.sourceID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ paragraph := tree.Root.FirstChild
+ paragraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("FOO")})
+ if action == "network-assets" {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "image/png")
+ w.Write([]byte("image data"))
+ }))
+ defer server.Close()
+ paragraph.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "a",
+ TextMarkAHref: server.URL + "/image.png", TextMarkTextContent: "image"})
+ }
+ if _, err = filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+ seedDocumentHistory(t, fixture.sourceID, fixture.targetID)
+ switch action {
+ case "replace":
+ err = FindReplaceInBox("FOO", "BAR", map[string]bool{"text": true}, []string{paragraph.ID}, nil, nil, nil, nil, 0, "")
+ case "format":
+ err = AutoSpace(fixture.sourceID)
+ default:
+ assetsDir := filepath.Join(util.DataDir, "assets")
+ if err = os.MkdirAll(assetsDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ err = netAssets2LocalAssets0(tree, false, "", assetsDir, true)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if action == "network-no-change" {
+ if canUndo, canRedo, _ := GlobalUndoLog.State(fixture.sourceID); !canUndo || !canRedo {
+ t.Fatal("operation without a document write cleared history")
+ }
+ } else {
+ requireDocumentHistoryCleared(t, fixture.sourceID, fixture.targetID)
+ }
+ })
+ }
+}
diff --git a/kernel/model/format.go b/kernel/model/format.go
index d34a8ab52d..7fed55cf0f 100644
--- a/kernel/model/format.go
+++ b/kernel/model/format.go
@@ -81,6 +81,7 @@ func AutoSpace(rootID string) (err error) {
if err != nil {
return
}
+ invalidateDocumentHistory(newTree.ID)
logging.LogInfof("formatted tree [%s]", rootID)
util.RandomSleep(500, 700)
return
diff --git a/kernel/model/search.go b/kernel/model/search.go
index 7bb4500e98..4a76fb34b2 100644
--- a/kernel/model/search.go
+++ b/kernel/model/search.go
@@ -1045,6 +1045,7 @@ func FindReplaceInBox(keyword, replacement string, replaceTypes map[string]bool,
if err = writeTreeUpsertQueue(tree); err != nil {
return
}
+ invalidateDocumentHistory(tree.ID)
updateNodes[id] = node
util.PushEndlessProgress(fmt.Sprintf(Conf.Language(206), i+1, len(ids)))
}
diff --git a/kernel/model/undolog.go b/kernel/model/undolog.go
index b2fa80eff7..855ee2ff2d 100644
--- a/kernel/model/undolog.go
+++ b/kernel/model/undolog.go
@@ -28,6 +28,7 @@ import (
"github.com/88250/lute/ast"
"github.com/88250/lute/parse"
"github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
)
// UndoEntry 是撤销栈中的一条记录。跨文档操作(MutatedRootIDs 含多个 rootID)的 entry
@@ -298,13 +299,22 @@ func (l *UndoLog) State(rootID string) (canUndo, canRedo bool, peekMutatedRootID
// Clear 清理撤销日志。rootID 非空时清该文档栈并联动移除其它栈中相关条目;为空时清空全部。
func (l *UndoLog) Clear(rootID string) {
+ l.clear(rootID)
+}
+
+// 返回状态发生变化的文档,包括联动移除跨文档记录的其他文档。
+func (l *UndoLog) clear(rootID string) (rootIDs []string) {
l.mu.Lock()
defer l.mu.Unlock()
if "" == rootID {
+ for id := range l.stacks {
+ rootIDs = append(rootIDs, id)
+ }
l.stacks = map[string]*undoStack{}
return
}
+ rootIDs = append(rootIDs, rootID)
s := l.stacks[rootID]
if nil == s {
@@ -328,12 +338,30 @@ func (l *UndoLog) Clear(rootID string) {
}
delete(l.stacks, rootID)
for otherID, other := range l.stacks {
+ beforeUndo, beforeRedo := len(other.undoStack), len(other.redoStack)
for id := range linkedIDs {
other.undoStack = removeEntryByID(other.undoStack, id)
other.redoStack = removeEntryByID(other.redoStack, id)
}
- _ = otherID
+ if beforeUndo != len(other.undoStack) || beforeRedo != len(other.redoStack) {
+ rootIDs = append(rootIDs, otherID)
+ }
}
+ return
+}
+
+// 非编辑器写盘成功后失效旧记录,并通知所有客户端更新撤销和重做状态。
+func invalidateDocumentHistory(rootID string) {
+ rootIDs := GlobalUndoLog.clear(rootID)
+ states := map[string]map[string]bool{}
+ for _, id := range rootIDs {
+ canUndo, canRedo, _ := GlobalUndoLog.State(id)
+ states[id] = map[string]bool{"canUndo": canUndo, "canRedo": canRedo}
+ }
+ event := util.NewCmdResult("transactions", 0, util.PushModeBroadcast)
+ event.Data = []*Transaction{}
+ event.Context = map[string]any{"rootIDs": rootIDs, "undoState": states}
+ util.PushEvent(event)
}
// ClearAttributeView 从各文档栈清理涉及指定数据库的整笔撤销、重做记录,保留无关记录。
diff --git a/kernel/model/undolog_test.go b/kernel/model/undolog_test.go
index 61aa428031..dc22649652 100644
--- a/kernel/model/undolog_test.go
+++ b/kernel/model/undolog_test.go
@@ -23,6 +23,29 @@ import (
"github.com/88250/lute/ast"
)
+func TestUndoLogClearReportsLinkedDocuments(t *testing.T) {
+ log := newUndoLog(64)
+ linked := &UndoEntry{id: "linked", mutatedRootIDs: []string{"source", "target"}}
+ kept := &UndoEntry{id: "kept", mutatedRootIDs: []string{"target"}}
+ log.stacks["source"] = &undoStack{undoStack: []*UndoEntry{linked}, redoStack: []*UndoEntry{linked}}
+ log.stacks["target"] = &undoStack{undoStack: []*UndoEntry{kept, linked}, redoStack: []*UndoEntry{linked}}
+ log.stacks["unrelated"] = &undoStack{undoStack: []*UndoEntry{kept}}
+ affected := log.clear("source")
+ slices.Sort(affected)
+ if !slices.Equal(affected, []string{"source", "target"}) {
+ t.Fatalf("affected document states: %v", affected)
+ }
+ if canUndo, canRedo, _ := log.State("source"); canUndo || canRedo {
+ t.Fatal("rewritten document retained history")
+ }
+ if log.Peek("target") != kept || log.Peek("unrelated") != kept {
+ t.Fatal("unrelated operations were removed")
+ }
+ if _, canRedo, _ := log.State("target"); canRedo {
+ t.Fatal("linked redo survived invalidation")
+ }
+}
+
func TestUndoLogClearAttributeView(t *testing.T) {
avID := "affected-database"
snapshot := &attributeViewFieldsSnapshot{changes: map[string]*attributeViewFieldChange{avID: {}}}