Skip to content

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

:bug: Prevent embed hints from hanging on failed searches https://github.com/siyuan-note/siyuan/issues/20702

Daniel1fccdf905572
diff --git a/app/src/protyle/hint/bindingLoading.test.ts b/app/src/protyle/hint/bindingLoading.test.ts
index 0574c89710..fb03a58cd0 100644
--- a/app/src/protyle/hint/bindingLoading.test.ts
+++ b/app/src/protyle/hint/bindingLoading.test.ts
@@ -4,13 +4,14 @@ import {join} from "node:path";
import {test} from "node:test";
import {runInNewContext} from "node:vm";
import {createSourceFile, isClassDeclaration, ScriptTarget, transpileModule} from "typescript";
+import {getCreateTargetContext, isSameCreateTargetContext} from "./createTargetContext";
test("panel binding loads at its field and dismisses only on outside pointer events", () => {
const source = createSourceFile("index.ts", readFileSync(join(__dirname, "index.ts"), "utf8"), ScriptTarget.Latest);
const declaration = source.statements.find(node => isClassDeclaration(node) && node.name.text === "Hint");
assert.ok(declaration && isClassDeclaration(declaration));
const methods = declaration.members.filter(member =>
- ["genLoading", "cancelLoadingAnimation", "destroy"].includes(member.name?.getText(source)))
+ ["loadingID", "genLoading", "cancelLoadingAnimation", "destroy"].includes(member.name?.getText(source)))
.map(member => member.getText(source)).join("\n");
const document = new EventTarget();
const classes = new Set(["fn__none"]);
@@ -29,14 +30,14 @@ test("panel binding loads at its field and dismisses only on outside pointer eve
${methods}
}
new Hint();`, {compilerOptions: {target: ScriptTarget.ES2020}}).outputText, {
- document, AbortController, mobilePositions,
+ document, AbortController, mobilePositions, getCreateTargetContext, isSameCreateTargetContext,
getAVBindingCell: () => ({dataset: {rowId: "item"},
getBoundingClientRect: () => ({left: 100, top: 200, bottom: 234, height: 34})}),
getSelectionPosition: () => { throw new Error("Detached editor has no selection"); },
setPosition: (_element: unknown, ...position: number[]) => positions.push(position),
});
hint.element = element;
- const protyle = {toolbar: {range: {}}, wysiwyg: {element: {}}};
+ const protyle = {block: {rootID: "root"}, toolbar: {range: {}}, wysiwyg: {element: {}}};
hint.genLoading(protyle, 0, "av");
assert.deepEqual(positions, [[100, 234, 34]]);
assert.deepEqual(JSON.parse(JSON.stringify(mobilePositions)), [[200, 234]]);
diff --git a/app/src/protyle/hint/extend.ts b/app/src/protyle/hint/extend.ts
index 9737b1d182..c9b3f6041e 100644
--- a/app/src/protyle/hint/extend.ts
+++ b/app/src/protyle/hint/extend.ts
@@ -828,7 +828,7 @@ export const hintEmbed = (key: string, protyle: IProtyle): IHintData[] => {
if (key.endsWith("}}") || key.endsWith("」」")) {
return [];
}
- protyle.hint.genLoading(protyle);
+ const isCurrent = protyle.hint.genLoading(protyle, 0, "hint");
const nodeElement = hasClosestBlock(getEditorRange(protyle.wysiwyg.element).startContainer);
const embedParam: import("../../types/api").SearchRefBlockRequestInput = {
k: key,
@@ -840,9 +840,16 @@ export const hintEmbed = (key: string, protyle: IProtyle): IHintData[] => {
if (isEncryptedBox(protyle.notebookId)) {
embedParam.notebook = protyle.notebookId;
}
- fetchPost("/api/search/searchRefBlock", embedParam, (response) => {
+ searchRef(embedParam).then((response) => {
+ if (!isCurrent()) {
+ return;
+ }
+ if (!response) {
+ protyle.hint.genHTML([], protyle, true, "hint");
+ return;
+ }
const dataList: IHintData[] = [];
- response.data.blocks.forEach((item: IBlock) => {
+ response.blocks.forEach((item: IBlock) => {
dataList.push({
value: `{{select * from blocks where id='${item.id}'}}`,
html: genHintItemHTML(item),
@@ -855,6 +862,10 @@ export const hintEmbed = (key: string, protyle: IProtyle): IHintData[] => {
});
}
protyle.hint.genHTML(dataList, protyle, true, "hint");
+ }).catch(() => {
+ if (isCurrent()) {
+ protyle.hint.genHTML([], protyle, true, "hint");
+ }
});
return [];
};
diff --git a/app/src/protyle/hint/fillCommand.test.ts b/app/src/protyle/hint/fillCommand.test.ts
index 7955a8b582..8b91198661 100644
--- a/app/src/protyle/hint/fillCommand.test.ts
+++ b/app/src/protyle/hint/fillCommand.test.ts
@@ -65,48 +65,56 @@ test("daily note completion retains its original insertion target while awaiting
}
});
-test("mobile reference command inserts at the saved caret and resets stale hint context", () => {
- for (const [text, offset] of [["", 0], ["text", 0], ["text", 2], ["text", 4]] as const) {
- for (const source of ["av", "search", "hint"]) {
- let content: string = text;
- let focused = false;
- let queried = false;
- const block = {outerHTML: "paragraph", getAttribute: () => "paragraph"};
- const range = {
- startContainer: block,
- deleteContents() {},
- insertNode: (node: {textContent: string}) => {
- content = text.substring(0, offset) + node.textContent + text.substring(offset);
- },
- setEnd: (_node: unknown, value: number) => assert.equal(value, 2),
- collapse: (toStart: boolean) => assert.equal(toStart, false),
- };
- const hint = runInNewContext(code, {
- Constants: {BLOCK_HINT_KEYS: ["(("]},
- hideElements() {}, isProtyleListItemFragment: () => false,
- hasClosestBlock: () => block, hasClosestByAttribute: (): null => null,
- getEditorRange: () => { throw new Error("reference insertion replaced the saved caret"); },
- shouldCaptureHintUndoFocus, getUndoFocusContext: () => ({}),
- document: {createTextNode: (textContent: string) => ({textContent})},
- hintRef: (key: string, _protyle: unknown, value: string) => {
- assert.equal(key, "");
- assert.equal(value, "hint");
- queried = true;
- },
- focusByRange: (value: unknown) => { assert.equal(value, range); focused = true; },
- });
- Object.assign(hint, {source, splitChar: "#", lastIndex: 12, hashTagSearchElement: {}});
- const protyle = {toolbar: {range}, wysiwyg: {element: {}}};
- hint.fillCommand("((", protyle, false);
- assert.equal(content, text.substring(0, offset) + "((" + text.substring(offset));
- assert.equal(queried && focused, true);
- assert.equal(hint.source, "hint");
- assert.equal(hint.splitChar, "((");
- assert.equal(hint.lastIndex, 0);
- assert.equal(hint.hashTagSearchElement, undefined);
+for (const command of ["((", "{{"]) {
+ test(`mobile ${command} command inserts at the saved caret and resets stale hint context`, () => {
+ for (const [text, offset] of [["", 0], ["text", 0], ["text", 2], ["text", 4]] as const) {
+ for (const source of ["av", "search", "hint"]) {
+ let content: string = text;
+ let focused = false;
+ let queried = false;
+ const block = {outerHTML: "paragraph", getAttribute: () => "paragraph"};
+ const range = {
+ startContainer: block,
+ deleteContents() {},
+ insertNode: (node: {textContent: string}) => {
+ content = text.substring(0, offset) + node.textContent + text.substring(offset);
+ },
+ setEnd: (_node: unknown, value: number) => assert.equal(value, 2),
+ collapse: (toStart: boolean) => assert.equal(toStart, false),
+ };
+ const hint = runInNewContext(code, {
+ Constants: {BLOCK_HINT_KEYS: [command]},
+ hideElements() {}, isProtyleListItemFragment: () => false,
+ hasClosestBlock: () => block, hasClosestByAttribute: (): null => null,
+ getEditorRange: () => { throw new Error("block insertion replaced the saved caret"); },
+ shouldCaptureHintUndoFocus, getUndoFocusContext: () => ({}),
+ document: {createTextNode: (textContent: string) => ({textContent})},
+ hintRef: (key: string, _protyle: unknown, value: string) => {
+ assert.equal(command, "((");
+ assert.equal(key, "");
+ assert.equal(value, "hint");
+ queried = true;
+ },
+ hintEmbed: (key: string) => {
+ assert.equal(command, "{{");
+ assert.equal(key, "");
+ queried = true;
+ },
+ focusByRange: (value: unknown) => { assert.equal(value, range); focused = true; },
+ });
+ Object.assign(hint, {source, splitChar: "#", lastIndex: 12, hashTagSearchElement: {}});
+ const protyle = {toolbar: {range}, wysiwyg: {element: {}}};
+ hint.fillCommand(command, protyle, false);
+ assert.equal(content, text.substring(0, offset) + command + text.substring(offset));
+ assert.equal(queried && focused, true);
+ assert.equal(hint.source, "hint");
+ assert.equal(hint.splitChar, command);
+ assert.equal(hint.lastIndex, 0);
+ assert.equal(hint.hashTagSearchElement, undefined);
+ }
}
- }
-});
+ });
+}
for (const scenario of ["database shortcut", "database mobile toolbar", "tag search"]) {
test(`direct table insertion ignores residual ${scenario} context`, () => {
diff --git a/app/src/protyle/hint/hintEmbed.test.ts b/app/src/protyle/hint/hintEmbed.test.ts
new file mode 100644
index 0000000000..58ff5832a0
--- /dev/null
+++ b/app/src/protyle/hint/hintEmbed.test.ts
@@ -0,0 +1,187 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {join} from "node:path";
+import {test} from "node:test";
+import {setImmediate} from "node:timers/promises";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, isClassDeclaration, isVariableStatement, ScriptTarget, transpileModule} from "typescript";
+import {getCreateTargetContext, isSameCreateTargetContext} from "./createTargetContext";
+
+const extend = createSourceFile("extend.ts", readFileSync(join(__dirname, "extend.ts"), "utf8"), ScriptTarget.Latest);
+const functions = ["genHintItemHTML", "hintEmbed"].map(name => extend.statements.find(statement =>
+ isVariableStatement(statement) && statement.declarationList.declarations.some(item => item.name.getText(extend) === name))
+ .getText(extend).replace("export ", ""));
+const index = createSourceFile("index.ts", readFileSync(join(__dirname, "index.ts"), "utf8"), ScriptTarget.Latest);
+const hintClass = index.statements.find(statement => isClassDeclaration(statement) && statement.name.text === "Hint");
+assert.ok(hintClass && isClassDeclaration(hintClass));
+const members = hintClass.members.filter(member =>
+ ["loadingID", "genLoading", "genHTML", "cancelLoadingAnimation", "destroy"].includes(member.name?.getText(index)))
+ .map(member => member.getText(index)).join("\n");
+const searchSource = readFileSync(join(__dirname, "searchRef.ts"), "utf8")
+ .replace(/^import .*;\r?\n/gm, "").replace("export ", "");
+const code = transpileModule(`${searchSource}\n${functions.join("\n")}\nclass Hint { ${members} }\n({hintEmbed, Hint});`, {
+ compilerOptions: {target: ScriptTarget.ES2020},
+}).outputText;
+
+const fixture = (encrypted = false, hasBlock = true) => {
+ const requests: Array<{params: Record<string, unknown>, callback: (response: unknown) => void,
+ resolve: () => void, reject: (error: Error) => void}> = [];
+ const classes = new Set(["fn__none"]);
+ let html = "";
+ let loadingElement: object | undefined;
+ const element = {
+ isConnected: true,
+ classList: {contains: (name: string) => classes.has(name),
+ add: (name: string) => classes.add(name), remove: (name: string) => classes.delete(name)},
+ get innerHTML() { return html; },
+ set innerHTML(value: string) { html = value; loadingElement = value.includes("fn__loading") ? {} : undefined; },
+ querySelector: (selector: string) => selector === ".fn__loading" ? loadingElement : {},
+ contains: (node: object) => !!loadingElement && node === loadingElement,
+ insertAdjacentHTML: (_position: string, value: string) => { html += value; loadingElement = {}; },
+ };
+ const block = {getAttribute: () => "block"};
+ const rendered: IHintData[][] = [];
+ const api = runInNewContext(code, {
+ window: {siyuan: {languages: {emptyContent: "Empty", ref: "Reference"}}},
+ getCreateTargetContext, isSameCreateTargetContext,
+ getEditorRange: () => ({startContainer: block}), hasClosestBlock: () => hasBlock && block,
+ isEncryptedBox: () => encrypted, getIconByType: () => "iconFile", unicode2Emoji: () => "icon",
+ getSelectionPosition: () => ({left: 0, top: 0}), setPosition() {}, isAbnormalItem: () => false,
+ fetchPost: (url: string, params: Record<string, unknown>, callback: (response: unknown) => void) => {
+ assert.equal(url, "/api/search/searchRefBlock");
+ return new Promise<void>((resolve, reject) => requests.push({params, callback, resolve, reject}));
+ },
+ });
+ const hint = new api.Hint();
+ Object.assign(hint, {
+ element, destroyEmojiPanel() {}, bindUploadEvent() {}, setMobilePosition() {},
+ getMobileSelectionBounds: () => ({top: 0, bottom: 0}),
+ getHTMLByData(data: IHintData[]) { rendered.push(data); return "results"; },
+ });
+ const protyle = {notebookId: "box", path: "/root.sy", element: {clientWidth: 320},
+ block: {rootID: "root", parentID: "parent"}, wysiwyg: {element: {}}, hint};
+ return {requests, element, rendered, hint, protyle,
+ start(key = "", toolbar = false) {
+ const data = api.hintEmbed(key, protyle);
+ if (!toolbar) {
+ hint.genHTML(data, protyle, false, "hint");
+ }
+ },
+ async respond(response: unknown, request = 0, callback = true) {
+ if (response instanceof Error) {
+ requests[request].reject(response);
+ } else {
+ if (callback) {
+ requests[request].callback(response);
+ }
+ requests[request].resolve();
+ }
+ await setImmediate();
+ },
+ };
+};
+
+const candidate = {id: "target", type: "NodeDocument", ial: {}, content: "Target", hPath: "/Target"};
+const success = (blocks: unknown = [candidate]) => ({code: 0, data: {k: "", newDoc: false, blocks}});
+
+test("embed loading ends on empty, invalid, failed and discarded responses from both entry points", async () => {
+ for (const toolbar of [false, true]) {
+ for (const response of ["", undefined, null, {code: -1, data: null}, {code: 0, data: {reqId: 1}},
+ success("invalid"), {code: 0, data: {blocks: [candidate], newDoc: false}}, new Error("network")]) {
+ const f = fixture();
+ f.start("", toolbar);
+ await f.respond(response, 0, response !== undefined);
+ assert.equal(f.element.classList.contains("fn__none"), true);
+ }
+ }
+});
+
+test("embed search shows empty candidates and recovers on the next keyword query", async () => {
+ const emptyCandidates: Array<null[] | null> = [[], null, [null]];
+ for (const blocks of emptyCandidates) {
+ const f = fixture();
+ f.start();
+ await f.respond(success(blocks));
+ assert.equal(f.element.classList.contains("fn__none"), false);
+ assert.equal(f.element.querySelector(".fn__loading"), undefined);
+ assert.equal(f.rendered[0][0].html, "Empty");
+ }
+ const f = fixture();
+ f.start();
+ await f.respond("");
+ f.start("Target");
+ await f.respond(success(), 1);
+ assert.equal(f.requests[1].params.k, "Target");
+ assert.equal(f.element.classList.contains("fn__none"), false);
+ assert.equal(f.rendered[0][0].value, "{{select * from blocks where id='target'}}");
+});
+
+test("embed search preserves block context and encrypted notebook routing", async () => {
+ for (const encrypted of [false, true]) {
+ for (const hasBlock of [false, true]) {
+ const f = fixture(encrypted, hasBlock);
+ f.start("Target", true);
+ assert.equal(f.requests[0].params.id, hasBlock ? "block" : "parent");
+ assert.equal(f.requests[0].params.rootID, "root");
+ assert.equal(f.requests[0].params.isDatabase, false);
+ assert.equal(f.requests[0].params.notebook, encrypted ? "box" : undefined);
+ const response = success([null, candidate]);
+ response.data.newDoc = true;
+ await f.respond(response);
+ assert.equal(f.rendered[0].length, 1);
+ assert.equal(f.rendered[0][0].value, "{{select * from blocks where id='target'}}");
+ }
+ }
+});
+
+test("obsolete embed successes and failures leave newer loading and results intact", async () => {
+ for (const response of [success(), "", new Error("network"), undefined]) {
+ for (const pending of [false, true]) {
+ const f = fixture();
+ f.start();
+ f.start("Target");
+ if (!pending) {
+ await f.respond(success(), 1);
+ }
+ const before = f.element.innerHTML;
+ await f.respond(response, 0, response !== undefined);
+ assert.equal(f.element.innerHTML, before);
+ assert.equal(f.element.classList.contains("fn__none"), false);
+ if (pending) {
+ await f.respond(success(), 1);
+ }
+ assert.equal(f.rendered.length, 1);
+ }
+ }
+});
+
+test("embed responses do not reopen dismissed panels or update a changed document or panel", async () => {
+ for (const change of [
+ (f: ReturnType<typeof fixture>) => f.element.classList.add("fn__none"),
+ (f: ReturnType<typeof fixture>) => { f.element.isConnected = false; },
+ (f: ReturnType<typeof fixture>) => { f.protyle.notebookId = "other"; },
+ (f: ReturnType<typeof fixture>) => { f.protyle.path = "/other.sy"; },
+ (f: ReturnType<typeof fixture>) => { f.protyle.block.rootID = "other"; },
+ (f: ReturnType<typeof fixture>) => f.hint.destroy(),
+ (f: ReturnType<typeof fixture>) => f.hint.genHTML([{value: "other", html: "Other"}], f.protyle, true, "hint"),
+ (f: ReturnType<typeof fixture>) => f.hint.genLoading(f.protyle, 0, "search"),
+ ]) {
+ for (const response of [success(), "", new Error("network")]) {
+ const f = fixture();
+ f.start();
+ change(f);
+ const before = f.element.innerHTML;
+ const count = f.rendered.length;
+ await f.respond(response);
+ assert.equal(f.element.innerHTML, before);
+ assert.equal(f.rendered.length, count);
+ }
+ }
+});
+
+test("embed loading ends when a candidate cannot be rendered", async () => {
+ const f = fixture();
+ f.start();
+ await f.respond(success([{id: "target", type: "NodeDocument"}]));
+ assert.equal(f.element.classList.contains("fn__none"), true);
+});
diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.ts
index 50561042d4..a4ebdd5d5d 100644
--- a/app/src/protyle/hint/index.ts
+++ b/app/src/protyle/hint/index.ts
@@ -152,6 +152,7 @@ export class Hint {
private emojiPanel?: EmojiPanelController;
private emojiBrowseMode = false;
private loadingAnimation?: Animation;
+ private loadingID = 0;
private bindingDismissController?: AbortController;
constructor(protyle: IProtyle) {
@@ -209,6 +210,7 @@ export class Hint {
}
public destroy() {
+ this.loadingID++;
this.bindingDismissController?.abort();
this.cancelLoadingAnimation();
this.destroyEmojiPanel();
@@ -664,6 +666,9 @@ export class Hint {
}
public genLoading(protyle: IProtyle, delay = 0, source = this.source) {
+ const loadingID = ++this.loadingID;
+ const context = getCreateTargetContext(protyle);
+ const rootID = protyle.block.rootID;
this.source = source;
this.bindingDismissController?.abort();
if (source === "av" && getAVBindingCell(protyle.toolbar.range)?.dataset.rowId) {
@@ -716,6 +721,11 @@ export class Hint {
{visibility: "hidden"},
], {duration: delay});
}
+ const loadingElement = this.element.querySelector(".fn__loading");
+ // 仅允许当前文档中仍可见的本次加载更新候选,避免旧请求影响后续面板。
+ return () => this.loadingID === loadingID && isSameCreateTargetContext(context, protyle) &&
+ protyle.block.rootID === rootID && this.element.isConnected &&
+ !this.element.classList.contains("fn__none") && this.element.contains(loadingElement);
}
public bindUploadEvent(protyle: IProtyle, element: HTMLElement) {