Skip to content

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

:white_check_mark: Correct heading and undo fixtures and preserve math failure diagnostics

Daniel40e2f618bde7
diff --git a/app/src/protyle/util/undoReplayFocus.test.ts b/app/src/protyle/util/undoReplayFocus.test.ts
index bae711ff67..992356fc5b 100644
--- a/app/src/protyle/util/undoReplayFocus.test.ts
+++ b/app/src/protyle/util/undoReplayFocus.test.ts
@@ -241,8 +241,12 @@ const browserCases = async (source: string) => {
getSelection().removeAllRanges();
getSelection().addRange(range);
const mindmapSaved = api.getUndoFocusContext(editor, range, true);
+ check.equal(mindmapSaved.undoFocusStart, "3");
+ check.equal(mindmapSaved.undoFocusEnd, "1");
const fragmentRoot = document.createElement("div");
fragmentRoot.className = "protyle-wysiwyg";
+ // 桌面片段编辑器使用统一编辑根,否则 Chromium 会把文本选区截在第一个独立编辑宿主内。
+ fragmentRoot.contentEditable = "true";
document.body.append(fragmentRoot);
const unregisterText = api.registerListMindmapRoot(editor, noop,
(_id: string, ids: string[], selection: Record<string, string>, source: Element) => {
@@ -253,8 +257,13 @@ const browserCases = async (source: string) => {
});
check.equal(api.restoreUndoFocus(protyle, [{context: {undoFocusId: "child", undoFocusStart: "0", undoFocusEnd: "0",
undoFocusMindmapSelection: JSON.stringify(mindmapSaved)}}]), true);
- check.equal(getSelection().toString(), "BC中");
- check.equal(getSelection().getRangeAt(0).startOffset, 3);
+ const restoredRange = getSelection().getRangeAt(0);
+ // Range 的正文序列不包含 Selection 按渲染块边界附加的换行。
+ check.equal(restoredRange.toString(), "BC中");
+ check.equal(restoredRange.startContainer, fragmentRoot.firstElementChild.firstElementChild.firstChild);
+ check.equal(restoredRange.startOffset, 3);
+ check.equal(restoredRange.endContainer, fragmentRoot.lastElementChild.firstElementChild.firstChild.firstChild);
+ check.equal(restoredRange.endOffset, 1);
check.ok(fragmentRoot.contains(getSelection().anchorNode));
unregisterText();
fragmentRoot.remove();
diff --git a/app/tests/inlineMathSelection.test.js b/app/tests/inlineMathSelection.test.js
index 389953450d..12c6c6fd99 100644
--- a/app/tests/inlineMathSelection.test.js
+++ b/app/tests/inlineMathSelection.test.js
@@ -37,7 +37,7 @@ const setup = async (source, suffix) => {
return {before, after, end: {x: formulas[1].getBoundingClientRect().right + 30, y: before.y}};
};
-const setupEdge = async (mode) => {
+const setupEdge = async (mode, direction) => {
window.mathSelectionDiagnosticAbort?.abort();
document.body.innerHTML = '<div class="protyle-wysiwyg" contenteditable="false" data-readonly="false">' +
'<div data-node-id="20261010232335-t6hx5pb" data-type="NodeParagraph" class="p">' +
@@ -72,14 +72,18 @@ const setupEdge = async (mode) => {
const before = point(prefix.firstChild, prefix.textContent.length - 2);
const diagnosticAbort = new AbortController();
window.mathSelectionDiagnosticAbort = diagnosticAbort;
- window.mathSelectionDiagnostics = {mode, events: []};
+ const geometry = {mode, requestedWidth: editable.style.width, measuredPrefixWidth: width,
+ editable: editable.getBoundingClientRect().toJSON(), math: rect.toJSON(),
+ prefixLines: Array.from(prefix.getClientRects(), item => item.toJSON()),
+ fontsStatus: document.fonts.status, devicePixelRatio: window.devicePixelRatio};
+ window.mathSelectionDiagnostics = {mode, direction, geometry, events: []};
const recordSelection = (phase, event) => {
const selection = getSelection();
const describe = node => node ? {name: node.nodeName,
text: node.textContent?.slice(0, 180), parent: node.parentElement?.outerHTML.slice(0, 512)} : null;
const events = window.mathSelectionDiagnostics.events;
if (events.length >= 48) return;
- events.push({phase, text: selection?.toString(), collapsed: selection?.isCollapsed,
+ events.push({phase, text: selection?.toString().slice(0, 512), collapsed: selection?.isCollapsed,
anchor: describe(selection?.anchorNode), anchorOffset: selection?.anchorOffset,
focus: describe(selection?.focusNode), focusOffset: selection?.focusOffset,
pointer: event && typeof event.clientX === "number" ? {x: event.clientX, y: event.clientY,
@@ -98,14 +102,11 @@ const setupEdge = async (mode) => {
recordSelection("after-caret-normalization");
}
}, 0);
- }, {once: true});
+ }, {once: true, signal: diagnosticAbort.signal});
return {before, after, left: {x: rect.left + 0.5, y: after.y},
mathEnd: {x: rect.right + 1, y: after.y}, right: {x: rect.right + 1, y: before.y},
width: editable.clientWidth, mathLeft: rect.left, prefixLeft: prefix.getBoundingClientRect().left,
- geometry: {mode, requestedWidth: editable.style.width, measuredPrefixWidth: width,
- editable: editable.getBoundingClientRect().toJSON(), math: rect.toJSON(),
- prefixLines: Array.from(prefix.getClientRects(), item => item.toJSON()),
- fontsStatus: document.fonts.status, devicePixelRatio: window.devicePixelRatio}};
+ geometry};
};
const runElectron = async () => {
@@ -192,11 +193,13 @@ const runElectron = async () => {
return {...window.mathSelectionDiagnostics,
from: describePoint(${JSON.stringify(from)}), to: describePoint(${JSON.stringify(to)}),
math: math?.getBoundingClientRect().toJSON(), viewport: [innerWidth, innerHeight],
- selection: {text: getSelection().toString(), collapsed: getSelection().isCollapsed}};
+ selection: {text: getSelection().toString().slice(0, 512), collapsed: getSelection().isCollapsed}};
})()`);
- error.message += "\nSelection diagnostics: " + JSON.stringify(diagnostics);
- } catch {
+ // AssertionError 缓存 stack,仅改 message 不会出现在子进程 stderr 中。
+ console.error("Selection diagnostics: " + JSON.stringify(diagnostics));
+ } catch (diagnosticError) {
// 页面关闭或诊断失败时仍保留原始选区断言。
+ console.error("Selection diagnostics unavailable: " + String(diagnosticError).slice(0, 512));
}
throw error;
}
@@ -222,7 +225,8 @@ const runElectron = async () => {
'document.querySelectorAll("[data-type=inline-math]")[1].lastChild.textContent'), "\ufeff");
for (const mode of ["left", "right"]) {
for (const direction of mode === "left" ? ["forward", "backward", "cross-line"] : ["forward", "cross-line"]) {
- const points = await win.webContents.executeJavaScript(`(${setupEdge.toString()})(${JSON.stringify(mode)})`);
+ const points = await win.webContents.executeJavaScript(
+ `(${setupEdge.toString()})(${JSON.stringify(mode)}, ${JSON.stringify(direction)})`);
if (mode === "left") {
assert.ok(Math.abs(points.mathLeft - points.prefixLeft) < 1, JSON.stringify(points));
await drag(direction === "forward" ? points.left : direction === "backward" ? points.after : points.before,
@@ -247,7 +251,7 @@ const runElectron = async () => {
window.mathSelectionAPI.normalizeInlineMathCaret(range);
return {collapsed: getSelection().isCollapsed, outside: !math.contains(getSelection().anchorNode)};
})()`), {collapsed: true, outside: true});
- const points = await win.webContents.executeJavaScript(`(${setupEdge.toString()})("right")`);
+ const points = await win.webContents.executeJavaScript(`(${setupEdge.toString()})("right", "delete")`);
await drag(points.before, points.right, true);
assert.equal(await win.webContents.executeJavaScript(`document.execCommand("delete");
document.querySelectorAll('[data-type="inline-math"]').length;`), 0);
diff --git a/app/tests/inlineMathSelectionDiagnostics.test.js b/app/tests/inlineMathSelectionDiagnostics.test.js
new file mode 100644
index 0000000000..0ae3308fe6
--- /dev/null
+++ b/app/tests/inlineMathSelectionDiagnostics.test.js
@@ -0,0 +1,53 @@
+const assert = require("node:assert/strict");
+const {execFileSync} = require("node:child_process");
+const {readFileSync} = require("node:fs");
+const path = require("node:path");
+const test = require("node:test");
+const ts = require("typescript");
+
+const selectionFailure = (diagnosticFailure = false) => {
+ const file = path.join(__dirname, "inlineMathSelection.test.js");
+ const source = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true);
+ let drag;
+ const visit = node => {
+ if (ts.isVariableDeclaration(node) && node.name.getText(source) === "drag") {
+ drag = node.initializer.getText(source);
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ assert.ok(drag);
+ const script = `const assert = require("node:assert/strict");
+const win = {webContents: {executeJavaScript: async source => {
+ if (source === "getSelection().toString()") return "";
+ if (${diagnosticFailure} && source.includes("const describePoint")) throw new Error("Renderer disposed");
+ return {mode: "left", direction: "forward", events: [{phase: "mouseup", text: "", collapsed: true}]};
+}}};
+const send = async () => {};
+(${drag})({x: 32, y: 64}, {x: 48, y: 64}, true).catch(error => {
+ console.error(error);
+ process.exitCode = 1;
+});`;
+ let failure;
+ try {
+ execFileSync(process.execPath, ["-e", script], {encoding: "utf8", stdio: "pipe", timeout: 5000});
+ } catch (error) {
+ failure = error;
+ }
+ assert.equal(failure?.status, 1, "the native-selection assertion must remain a failure");
+ assert.match(failure.stderr, /AssertionError \[ERR_ASSERTION\]/);
+ assert.match(failure.stderr, /at drag|at eval|at \[eval\]/);
+ return failure.stderr;
+};
+
+test("inline math failures print selection diagnostics alongside the original assertion stack", () => {
+ const stderr = selectionFailure();
+ assert.match(stderr, /Selection diagnostics: /);
+ const diagnostics = JSON.parse(stderr.split("Selection diagnostics: ")[1].split("\n")[0]);
+ assert.deepEqual(diagnostics, {mode: "left", direction: "forward",
+ events: [{phase: "mouseup", text: "", collapsed: true}]});
+});
+
+test("inline math diagnostic collection failures retain the original selection assertion", () => {
+ assert.match(selectionFailure(true), /Selection diagnostics unavailable: Error: Renderer disposed/);
+});
diff --git a/kernel/api/contract_block_transaction_test.go b/kernel/api/contract_block_transaction_test.go
index 3d75b5189a..0f7ec5380a 100644
--- a/kernel/api/contract_block_transaction_test.go
+++ b/kernel/api/contract_block_transaction_test.go
@@ -107,9 +107,11 @@ func TestAPIContractHeadingTransactions(t *testing.T) {
tree := treenode.NewTree(box.ID, "/"+docID+".sy", "/Contract", "Contract")
paragraphID := tree.Root.FirstChild.ID
heading := &ast.Node{Type: ast.NodeHeading, ID: ast.NewNodeID(), HeadingLevel: 1}
+ heading.SetIALAttr("id", heading.ID)
heading.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Contract heading")})
tree.Root.AppendChild(heading)
child := &ast.Node{Type: ast.NodeHeading, ID: ast.NewNodeID(), HeadingLevel: 2}
+ child.SetIALAttr("id", child.ID)
child.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Contract child")})
tree.Root.AppendChild(child)
if _, err := filesys.WriteTree(tree); err != nil {
diff --git a/kernel/api/contract_insert_block_anchor_test.go b/kernel/api/contract_insert_block_anchor_test.go
index f9b9589090..44d40704cb 100644
--- a/kernel/api/contract_insert_block_anchor_test.go
+++ b/kernel/api/contract_insert_block_anchor_test.go
@@ -68,6 +68,8 @@ func testAPIContractInsertBlockAnchors(t *testing.T, boxID, docID, paragraphID s
{"missing", missingID, "not found"},
} {
t.Run("insert-anchor/"+dataType+"/"+field+"/"+anchor.name, func(t *testing.T) {
+ // 强制从源文件加载,避免缓存命中掩盖拒绝请求期间的落盘修改。
+ cache.RemoveTreeDataInBox(docID, boxID)
before := readDocument(t)
response := post(t, map[string]any{
"data": data, "dataType": dataType, "parentID": docID, field: anchor.id,
@@ -76,8 +78,8 @@ func testAPIContractInsertBlockAnchors(t *testing.T, boxID, docID, paragraphID s
!strings.Contains(response.Msg, anchor.message) || strings.Contains(response.Msg, "panic") {
t.Fatalf("expected explicit anchor error, got %+v", response)
}
- if !bytes.Equal(before, readDocument(t)) {
- t.Fatal("rejected insert changed the document")
+ if after := readDocument(t); !bytes.Equal(before, after) {
+ t.Fatalf("rejected insert changed the document:\nbefore: %s\nafter: %s", before, after)
}
})
}