Skip to content

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

:bug: Harden undo routing for embedded block edits https://github.com/siyuan-note/siyuan/issues/18423

Danieled7a13400718
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index c1d4d6f9c3..a15e0dbb70 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -16,7 +16,7 @@ import {isInAndroid, isInEdge, isInHarmony} from "../../protyle/util/compatibili
import {tabCodeBlock} from "../../protyle/wysiwyg/codeBlock";
import {callMobileAppShowKeyboard, canInput, keyboardLockUntil} from "./mobileAppUtil";
import {isNotEditBlock} from "../../protyle/wysiwyg/getBlock";
-import {getMirror, getUndoRootID} from "../../protyle/undo/globalUndo";
+import {getMirror, getUndoRootID, hasUndoStateMirror, initMirror} from "../../protyle/undo/globalUndo";
let renderKeyboardToolbarTimeout: number;
let scrollSelectionIntoViewTimeout: number;
@@ -364,8 +364,15 @@ const renderKeyboardToolbar = () => {
const protyle = getCurrentEditor().protyle;
protyle.toolbar.range = range;
if (!dynamicElements[0].classList.contains("fn__none")) {
- // 撤销权威栈在 kernel,本地按 rootID 读镜像设按钮态(零 fetch)
+ // 撤销权威栈在 kernel,本地按 rootID 读镜像设按钮态,首次进入嵌入源文档时按需初始化。
const undoRootID = getUndoRootID(protyle, range);
+ if (undoRootID && !hasUndoStateMirror(undoRootID)) {
+ initMirror(undoRootID).then((initialized) => {
+ if (initialized && getUndoRootID(protyle, protyle.toolbar.range) === undoRootID) {
+ renderKeyboardToolbar();
+ }
+ });
+ }
const undoState = undoRootID ? getMirror(undoRootID) : {
canUndo: false,
canRedo: false
diff --git a/app/src/protyle/undo/globalUndo.ts b/app/src/protyle/undo/globalUndo.ts
index 55145a87a2..1ffc9f2bc1 100644
--- a/app/src/protyle/undo/globalUndo.ts
+++ b/app/src/protyle/undo/globalUndo.ts
@@ -19,6 +19,7 @@ interface IUndoStateMirror {
}
const undoStateMirror = new Map<string, IUndoStateMirror>();
+const undoStateInitializers = new Map<string, Promise<boolean>>();
let isUndoing = false; // 防重入:撤销/重做进行中忽略后续触发
export const markMirror = (rootID: string, state: Partial<IUndoStateMirror>) => {
@@ -30,6 +31,8 @@ export const getMirror = (rootID: string): IUndoStateMirror => {
return undoStateMirror.get(rootID) || {canUndo: false, canRedo: false};
};
+export const hasUndoStateMirror = (rootID: string) => undoStateMirror.has(rootID);
+
const getRangeRootID = (protyle: IProtyle, range?: Range) => {
if (!range?.startContainer?.isConnected || !protyle.wysiwyg.element.contains(range.startContainer)) {
return;
@@ -75,23 +78,29 @@ export const syncMirrorFromBroadcast = (undoState: { [rootID: string]: { canUndo
};
// 文档打开时主动初始化镜像(低频,不在 selectionchange 热路径)
-export const initMirror = (rootID: string) => {
+export const initMirror = (rootID: string): Promise<boolean> => {
if (!rootID) {
- return;
+ return Promise.resolve(false);
}
- fetchPost("/api/transactions/undoState", {rootID}, (response) => {
+ const pending = undoStateInitializers.get(rootID);
+ if (pending) {
+ return pending;
+ }
+ const initializer = fetchPost("/api/transactions/undoState", {rootID}, (response) => {
const data = response.data;
if (data) {
undoStateMirror.set(rootID, {canUndo: !!data.canUndo, canRedo: !!data.canRedo});
}
+ }).then(() => {
+ return undoStateMirror.has(rootID);
+ }).finally(() => {
+ undoStateInitializers.delete(rootID);
});
+ undoStateInitializers.set(rootID, initializer);
+ return initializer;
};
-// 刷新指定 protyle 的撤销/重做按钮态(读镜像,零 fetch)
-export const refreshUndoButtons = (protyle: IProtyle, rootID = getUndoRootID(protyle)) => {
- if (!rootID) {
- return;
- }
+const applyUndoButtons = (protyle: IProtyle, rootID: string) => {
const state = getMirror(rootID);
if (protyle.breadcrumb) {
const parent = protyle.breadcrumb.element.parentElement;
@@ -114,6 +123,21 @@ export const refreshUndoButtons = (protyle: IProtyle, rootID = getUndoRootID(pro
}
};
+// 刷新指定 protyle 的撤销/重做按钮态;首次进入嵌入源文档时按需初始化其镜像。
+export const refreshUndoButtons = (protyle: IProtyle, rootID = getUndoRootID(protyle)) => {
+ if (!rootID) {
+ return;
+ }
+ applyUndoButtons(protyle, rootID);
+ if (!hasUndoStateMirror(rootID)) {
+ initMirror(rootID).then((initialized) => {
+ if (initialized && getUndoRootID(protyle) === rootID) {
+ applyUndoButtons(protyle, rootID);
+ }
+ });
+ }
+};
+
export const getActiveProtyle = (): IProtyle => {
/// #if MOBILE
const editor = getCurrentEditor();
@@ -145,16 +169,13 @@ export const getActiveProtyle = (): IProtyle => {
const resolveRootNames = async (rootIDs: string[]): Promise<string[]> => {
const names: string[] = [];
for (const id of rootIDs) {
- await new Promise<void>((resolve) => {
- fetchPost("/api/filetree/getHPathByID", {id}, (response: IWebSocketData) => {
- if (response.code === 0 && response.data) {
- names.push(response.data as string);
- } else {
- names.push(id);
- }
- resolve();
- });
+ let name = id;
+ await fetchPost("/api/filetree/getHPathByID", {id}, (response: IWebSocketData) => {
+ if (response.code === 0 && response.data) {
+ name = response.data as string;
+ }
});
+ names.push(name);
}
return names;
};
@@ -174,19 +195,39 @@ const focusRootIDs = (rootIDs: string[], focusBlockId?: string) => {
}
};
-const fetchUndoState = (rootID: string) => new Promise<{
+const fetchUndoState = async (rootID: string): Promise<{
canUndo: boolean;
canRedo: boolean;
peekMutatedRootIDs: string[];
-}>((resolve) => {
- fetchPost("/api/transactions/undoState", {rootID}, (response) => {
- resolve({
- canUndo: !!response.data?.canUndo,
- canRedo: !!response.data?.canRedo,
- peekMutatedRootIDs: response.data?.peekMutatedRootIDs || [],
- });
+} | undefined> => {
+ let state: {
+ canUndo: boolean;
+ canRedo: boolean;
+ peekMutatedRootIDs: string[];
+ };
+ await fetchPost("/api/transactions/undoState", {rootID}, (response) => {
+ if (response.data) {
+ state = {
+ canUndo: !!response.data?.canUndo,
+ canRedo: !!response.data?.canRedo,
+ peekMutatedRootIDs: response.data?.peekMutatedRootIDs || [],
+ };
+ }
});
-});
+ return state;
+};
+
+const fetchUndoOperation = async (path: "/api/transactions/undo" | "/api/transactions/redo", data: {
+ rootID: string;
+ app: string;
+ session: string;
+}) => {
+ let response: IWebSocketData | undefined;
+ await fetchPost(path, data, (fetchResponse) => {
+ response = fetchResponse;
+ });
+ return response;
+};
// 请求撤销:读取 kernel 权威状态 → 跨文档提示 → 调 kernel undo → 本地乐观应用 + 更新镜像
export const requestUndo = async (protyle: IProtyle, rootID?: string) => {
@@ -199,47 +240,52 @@ export const requestUndo = async (protyle: IProtyle, rootID?: string) => {
// 尽早置锁,阻止确认对话框期间触发新的撤销/重做(含 peek 与确认阶段)
isUndoing = true;
- await waitForPendingTransactions(protyle);
-
- // 等待输入事务提交后读取权威状态,避免本地镜像尚未更新时吞掉立即撤销。
- const state = await fetchUndoState(rootID);
- markMirror(rootID, {canUndo: state.canUndo, canRedo: state.canRedo});
- if (!state.canUndo) {
- isUndoing = false;
- refreshUndoButtons(protyle, rootID);
- return;
- }
+ try {
+ await waitForPendingTransactions(protyle);
- if (state.peekMutatedRootIDs.length > 1) {
- const names = await resolveRootNames(state.peekMutatedRootIDs);
- // 确认期间拦截当前编辑器的键盘输入(遮罩只挡鼠标点击,不挡键盘冒泡)
- const blockInput = (e: Event) => {
- e.stopImmediatePropagation();
- e.preventDefault();
- };
- protyle.wysiwyg.element.addEventListener("keydown", blockInput, true);
- protyle.wysiwyg.element.addEventListener("beforeinput", blockInput, true);
- const confirmed = await new Promise<boolean>((resolve) => {
- confirmDialog(`⚠️ ${window.siyuan.languages.undo}`,
- `${window.siyuan.languages.undoCrossDocConfirm}<div style="margin-top: 8px;">${names.map(n => `• ${n}`).join("<br>")}</div>`,
- () => resolve(true),
- () => resolve(false));
- });
- protyle.wysiwyg.element.removeEventListener("keydown", blockInput, true);
- protyle.wysiwyg.element.removeEventListener("beforeinput", blockInput, true);
- if (!confirmed) {
- isUndoing = false; // 拒绝,复位锁,栈与镜像不动
+ // 等待输入事务提交后读取权威状态,避免本地镜像尚未更新时吞掉立即撤销。
+ const state = await fetchUndoState(rootID);
+ if (!state) {
+ return;
+ }
+ markMirror(rootID, {canUndo: state.canUndo, canRedo: state.canRedo});
+ if (!state.canUndo) {
+ refreshUndoButtons(protyle, rootID);
return;
}
- }
- fetchPost("/api/transactions/undo", {
- rootID,
- app: Constants.SIYUAN_APPID,
- session: protyle.id,
- }, (response) => {
- isUndoing = false;
- const data = response.data;
+ if (state.peekMutatedRootIDs.length > 1) {
+ const names = await resolveRootNames(state.peekMutatedRootIDs);
+ // 确认期间拦截当前编辑器的键盘输入(遮罩只挡鼠标点击,不挡键盘冒泡)
+ const blockInput = (e: Event) => {
+ e.stopImmediatePropagation();
+ e.preventDefault();
+ };
+ protyle.wysiwyg.element.addEventListener("keydown", blockInput, true);
+ protyle.wysiwyg.element.addEventListener("beforeinput", blockInput, true);
+ let confirmed = false;
+ try {
+ confirmed = await new Promise<boolean>((resolve) => {
+ confirmDialog(`⚠️ ${window.siyuan.languages.undo}`,
+ `${window.siyuan.languages.undoCrossDocConfirm}<div style="margin-top: 8px;">${names.map(n => `• ${n}`).join("<br>")}</div>`,
+ () => resolve(true),
+ () => resolve(false));
+ });
+ } finally {
+ protyle.wysiwyg.element.removeEventListener("keydown", blockInput, true);
+ protyle.wysiwyg.element.removeEventListener("beforeinput", blockInput, true);
+ }
+ if (!confirmed) {
+ return;
+ }
+ }
+
+ const response = await fetchUndoOperation("/api/transactions/undo", {
+ rootID,
+ app: Constants.SIYUAN_APPID,
+ session: protyle.id,
+ });
+ const data = response?.data;
if (!data) {
return;
}
@@ -253,7 +299,7 @@ export const requestUndo = async (protyle: IProtyle, rootID?: string) => {
if (!data.undoOperations || data.undoOperations.length === 0) {
// 栈空或无可撤销
markMirror(rootID, {canUndo: !!data.canUndo, canRedo: !!data.canRedo});
- refreshUndoButtons(protyle);
+ refreshUndoButtons(protyle, rootID);
return;
}
markMirror(rootID, {canUndo: !!data.canUndo, canRedo: !!data.canRedo});
@@ -262,16 +308,18 @@ export const requestUndo = async (protyle: IProtyle, rootID?: string) => {
// 跨文档撤销:doOperations 的锚点分散在多个文档,当前 protyle 无法本地乐观应用。
// 改为靠 kernel 广播(含发起方)刷新所有涉及文档的 DOM。
// 这里不调 renderLocal,避免在错误 protyle 上应用跨文档 move 导致前后端不一致。
- refreshUndoButtons(protyle);
+ refreshUndoButtons(protyle, rootID);
// 广播会到达当前窗口(/undo 对跨文档用 PushModeBroadcast),触发 onTransaction 刷新 DOM
} else {
// 单文档撤销:发起窗口本地乐观应用 doOperations(kernel 实际执行的操作,如 insert 恢复块)
protyle.undo.renderLocal(protyle, data.doOperations);
- refreshUndoButtons(protyle);
+ refreshUndoButtons(protyle, rootID);
const focusBlockId = data.doOperations?.find((op: IOperation) => op.id)?.id;
focusRootIDs(mutatedRootIDs, focusBlockId);
}
- });
+ } finally {
+ isUndoing = false;
+ }
};
// 请求重做:对称,redo 不提示(其逆已在 undo 中确认)
@@ -284,21 +332,23 @@ export const requestRedo = async (protyle: IProtyle, rootID?: string) => {
}
isUndoing = true;
- await waitForPendingTransactions(protyle);
- const state = await fetchUndoState(rootID);
- markMirror(rootID, {canUndo: state.canUndo, canRedo: state.canRedo});
- if (!state.canRedo) {
- isUndoing = false;
- refreshUndoButtons(protyle, rootID);
- return;
- }
- fetchPost("/api/transactions/redo", {
- rootID,
- app: Constants.SIYUAN_APPID,
- session: protyle.id,
- }, (response) => {
- isUndoing = false;
- const data = response.data;
+ try {
+ await waitForPendingTransactions(protyle);
+ const state = await fetchUndoState(rootID);
+ if (!state) {
+ return;
+ }
+ markMirror(rootID, {canUndo: state.canUndo, canRedo: state.canRedo});
+ if (!state.canRedo) {
+ refreshUndoButtons(protyle, rootID);
+ return;
+ }
+ const response = await fetchUndoOperation("/api/transactions/redo", {
+ rootID,
+ app: Constants.SIYUAN_APPID,
+ session: protyle.id,
+ });
+ const data = response?.data;
if (!data) {
return;
}
@@ -311,19 +361,21 @@ export const requestRedo = async (protyle: IProtyle, rootID?: string) => {
}
if (!data.doOperations || data.doOperations.length === 0) {
markMirror(rootID, {canUndo: !!data.canUndo, canRedo: !!data.canRedo});
- refreshUndoButtons(protyle);
+ refreshUndoButtons(protyle, rootID);
return;
}
markMirror(rootID, {canUndo: !!data.canUndo, canRedo: !!data.canRedo});
const mutatedRootIDs: string[] = data.mutatedRootIDs || [];
if (mutatedRootIDs.length > 1) {
// 跨文档重做:锚点分散在多个文档,靠 kernel 广播(含发起方)刷新
- refreshUndoButtons(protyle);
+ refreshUndoButtons(protyle, rootID);
} else {
protyle.undo.renderLocal(protyle, data.doOperations);
- refreshUndoButtons(protyle);
+ refreshUndoButtons(protyle, rootID);
const focusBlockId = data.doOperations?.find((op: IOperation) => op.id)?.id;
focusRootIDs(mutatedRootIDs, focusBlockId);
}
- });
+ } finally {
+ isUndoing = false;
+ }
};
diff --git a/kernel/model/block.go b/kernel/model/block.go
index fe3ee0087e..c1b84c5f40 100644
--- a/kernel/model/block.go
+++ b/kernel/model/block.go
@@ -1367,16 +1367,7 @@ func getEmbeddedBlock(trees map[string]*parse.Tree, sqlBlock *sql.Block, heading
visibleNodes := cleanRenderNodes(nodes, true)
dom := renderBlockDOMByNodes(visibleNodes, luteEngine)
content := renderBlockContentByNodes(visibleNodes)
- block = &Block{
- Box: def.Box,
- Path: def.Path,
- HPath: b.HPath,
- ID: def.ID,
- RootID: b.RootID,
- Type: def.Type.String(),
- Content: dom,
- Markdown: content, // 这里使用 Markdown 字段来临时存储 content
- }
+ block = newEmbeddedBlock(def, b, dom, content)
if "" != sqlBlock.IAL {
block.IAL = map[string]string{}
@@ -1396,3 +1387,16 @@ func getEmbeddedBlock(trees map[string]*parse.Tree, sqlBlock *sql.Block, heading
}
return
}
+
+func newEmbeddedBlock(def *ast.Node, blockTree *treenode.BlockTree, dom, content string) *Block {
+ return &Block{
+ Box: def.Box,
+ Path: def.Path,
+ HPath: blockTree.HPath,
+ ID: def.ID,
+ RootID: blockTree.RootID,
+ Type: def.Type.String(),
+ Content: dom,
+ Markdown: content, // 这里使用 Markdown 字段来临时存储 content
+ }
+}
diff --git a/kernel/model/block_embed_test.go b/kernel/model/block_embed_test.go
index 167591ed0a..e87838f27c 100644
--- a/kernel/model/block_embed_test.go
+++ b/kernel/model/block_embed_test.go
@@ -20,6 +20,7 @@ import (
"net/http/httptest"
"testing"
+ "github.com/88250/lute/ast"
"github.com/gin-gonic/gin"
"github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/treenode"
@@ -77,3 +78,25 @@ func TestFilterEmbedBlocksByAccess(t *testing.T) {
t.Fatalf("authorized protected embed result should be returned: %+v", filtered)
}
}
+
+func TestNewEmbeddedBlockIncludesSourceRootID(t *testing.T) {
+ const (
+ blockID = "20260729150000-block01"
+ rootID = "20260729150001-root001"
+ )
+ def := &ast.Node{
+ ID: blockID,
+ Type: ast.NodeParagraph,
+ Box: "20260729150002-box0001",
+ Path: "/" + rootID + ".sy",
+ }
+ blockTree := &treenode.BlockTree{
+ RootID: rootID,
+ HPath: "/Source document",
+ }
+
+ block := newEmbeddedBlock(def, blockTree, "<div>content</div>", "content")
+ if rootID != block.RootID {
+ t.Fatalf("embedded block root ID = %q, want %q", block.RootID, rootID)
+ }
+}