Skip to content

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

:bug: Preserve global backlink retry controls and recycled row heights https://github.com/siyuan-note/siyuan/issues/19579

Danielfa1ed4d384a4
diff --git a/app/src/layout/dock/BacklinkContent.ts b/app/src/layout/dock/BacklinkContent.ts
index 65a9728e4c..770d82c965 100644
--- a/app/src/layout/dock/BacklinkContent.ts
+++ b/app/src/layout/dock/BacklinkContent.ts
@@ -957,8 +957,9 @@ export class BacklinkContent extends Model {
countElement.textContent = total.toString();
countElement.classList.toggle("fn__none", total === 0 && this.type !== "bottom");
if (this.type === "bottom") {
- this.element.classList.toggle("sy__backlink--backlinks-empty", total === 0 && !this.inputsElement[0].value);
- const empty = total === 0 && !this.inputsElement[0].value &&
+ const hideBacklinks = total === 0 && !this.inputsElement[0].value && !this.globalList?.hasError;
+ this.element.classList.toggle("sy__backlink--backlinks-empty", hideBacklinks);
+ const empty = hideBacklinks &&
this.element.classList.contains("sy__backlink--mentions-empty");
if (empty !== this.empty) { this.empty = empty; this.emptyChange?.(empty); }
}
@@ -2214,6 +2215,10 @@ export class BacklinkContent extends Model {
const bottomVisibility = this.type === "bottom" ?
getBottomBacklinkVisibility(data.linkRefsCount, data.mentionsCount, data.k, data.mk) : undefined;
if (bottomVisibility) {
+ if (this.globalList?.hasError) {
+ bottomVisibility.hideBacklinks = false;
+ bottomVisibility.hidePanel = false;
+ }
this.element.classList.toggle("sy__backlink--backlinks-empty", bottomVisibility.hideBacklinks);
this.element.classList.toggle("sy__backlink--mentions-empty", bottomVisibility.hideMentions);
}
diff --git a/app/src/layout/dock/GlobalBacklinkList.ts b/app/src/layout/dock/GlobalBacklinkList.ts
index b2f008659b..e38fad58c7 100644
--- a/app/src/layout/dock/GlobalBacklinkList.ts
+++ b/app/src/layout/dock/GlobalBacklinkList.ts
@@ -48,6 +48,7 @@ export class GlobalBacklinkList {
private frame = 0;
private destroyed = false;
private dirty = false;
+ private failed = false;
private composing = false;
private dragging = false;
private scrollVersion = 0;
@@ -139,6 +140,8 @@ export class GlobalBacklinkList {
public get count() { return this.total; }
+ public get hasError() { return this.failed; }
+
public setCollapsed(value: boolean) {
this.collapsed = value;
this.records.forEach(record => {
@@ -209,6 +212,7 @@ export class GlobalBacklinkList {
if (data.expired) { this.snapshot = ""; this.dirty = true; this.onFocusout(); return; }
this.snapshot = data.snapshot;
this.total = data.total;
+ this.failed = false;
this.options.count(this.total);
const anchor = this.captureAnchor();
this.addPage(data.offset, data.items);
@@ -221,6 +225,8 @@ export class GlobalBacklinkList {
this.onScroll();
} catch (error) {
if (generation === this.generation && !this.destroyed) {
+ this.failed = true;
+ this.options.count(this.total);
this.message.classList.remove("fn__none");
this.message.textContent = window.siyuan.languages.retry;
console.error(error);
@@ -352,6 +358,9 @@ export class GlobalBacklinkList {
throw new Error(response.msg);
}
if (response.data.expired) { this.dirty = true; this.onFocusout(); return; }
+ this.failed = false;
+ this.options.count(this.total);
+ this.message.classList.add("fn__none");
const anchor = this.captureAnchor();
const scrollVersion = this.scrollVersion;
for (const item of response.data.items || []) {
@@ -361,6 +370,7 @@ export class GlobalBacklinkList {
const rect = record.element.getBoundingClientRect();
if (rect.bottom <= viewport.top - 320 || rect.top >= viewport.bottom + 320 ||
Array.from(this.records.values()).filter(value => value.editor).length >= 16) { continue; }
+ record.body.style.minHeight = `${rect.height}px`;
record.body.replaceChildren();
record.body.setAttribute("data-defid", this.query.id);
record.body.setAttribute("data-ismention", "false");
@@ -396,6 +406,8 @@ export class GlobalBacklinkList {
if (scrollVersion === this.scrollVersion) { this.restoreAnchor(anchor); }
} catch (error) {
if (generation !== this.generation || this.destroyed) { return; }
+ this.failed = true;
+ this.options.count(this.total);
console.error(error);
this.message.classList.remove("fn__none");
this.message.textContent = window.siyuan.languages.retry;
@@ -413,15 +425,16 @@ export class GlobalBacklinkList {
record.releasing = false;
if (this.destroyed || this.composing || this.dragging || record.editor !== editor ||
record.element.contains(document.activeElement) || hasAVEditorSession(record.element)) { return; }
- const height = record.body.getBoundingClientRect().height;
+ const height = record.element.getBoundingClientRect().height;
unregisterViewFoldContext(editor.protyle);
this.options.editorRemoved(editor);
editor.destroy();
record.editor = undefined;
record.body.replaceChildren();
- record.body.style.minHeight = `${Math.max(height, 72)}px`;
record.body.textContent = record.item.anchor;
record.source.classList.remove("fn__none");
+ // 占位总高度包含重新显示的来源行,避免回收时重复增加面包屑的高度。
+ record.body.style.minHeight = `${Math.max(0, height - record.source.getBoundingClientRect().height)}px`;
this.onScroll();
}
@@ -448,6 +461,7 @@ export class GlobalBacklinkList {
this.clearPages();
this.snapshot = "";
this.total = 0;
+ this.failed = true;
this.top.style.height = this.bottom.style.height = "0px";
this.options.count(0);
this.message.classList.remove("fn__none");
diff --git a/app/tests/globalBacklinkList.test.js b/app/tests/globalBacklinkList.test.js
index 3e0adb90ed..ba4d4ee2aa 100644
--- a/app/tests/globalBacklinkList.test.js
+++ b/app/tests/globalBacklinkList.test.js
@@ -62,15 +62,16 @@ test("editor recycling waits for transactions and preserves the measured height"
const {list, finishTransaction} = setup();
let destroyed = 0;
const editor = {protyle: {}, destroy: () => destroyed++};
- const record = {editor, element: {contains: () => false}, body: {
+ const record = {editor, element: {contains: () => false, getBoundingClientRect: () => ({height: 280})}, body: {
style: {}, getBoundingClientRect: () => ({height: 280}), replaceChildren() {},
- }, source: {classList: {remove() {}}}, item: {anchor: "A1"}};
+ }, source: {classList: {remove() {}}, getBoundingClientRect: () => ({height: 28})}, item: {anchor: "A1"}};
const pending = list.release(record);
assert.equal(destroyed, 0);
finishTransaction();
await pending;
assert.equal(destroyed, 1);
- assert.equal(record.body.style.minHeight, "280px");
+ assert.equal(record.body.style.minHeight, "252px");
+ assert.equal(parseFloat(record.body.style.minHeight) + record.source.getBoundingClientRect().height, 280);
assert.equal(record.editor, undefined);
});
@@ -133,4 +134,5 @@ test("denied access clears content and invalidates other in-flight responses", a
assert.equal(list.snapshot, "");
assert.equal(list.loading, false);
assert.deepEqual(applied, [0]);
+ assert.equal(list.hasError, true);
});
diff --git a/app/tests/mobileBacklinks.test.js b/app/tests/mobileBacklinks.test.js
index 0a7f4440a4..164f929924 100644
--- a/app/tests/mobileBacklinks.test.js
+++ b/app/tests/mobileBacklinks.test.js
@@ -214,6 +214,55 @@ const runCases = async (sources) => {
assert.equal(globalElement.querySelector(".listCount").classList.contains("fn__none"), false);
assert.equal(registry.getMobileSecondaryEditors().length, 2);
const globalEditors = [...globalPanel.editors];
+ const globalList = globalPanel.globalList;
+ const firstRecord = globalList.records.get("first");
+ const originalHeight = firstRecord.element.getBoundingClientRect().height;
+ const originalScroll = globalList.onScroll;
+ globalList.onScroll = noop;
+ await globalList.release(firstRecord);
+ assert.ok(Math.abs(firstRecord.element.getBoundingClientRect().height - originalHeight) < 1,
+ "recycling must include the fallback path in the existing height");
+ const restoring = globalList.loadContexts([firstRecord]);
+ assert.equal(requests[0]?.url, "/api/ref/getGlobalBacklinkContexts");
+ requests.shift().reply({expired: false, items: [
+ {id: "first", revision: "first1", dom: "", blockPaths: [], expand: true},
+ ]});
+ await restoring;
+ assert.ok(Math.abs(firstRecord.element.getBoundingClientRect().height - originalHeight) < 1,
+ "restoring an editor must preserve the complete placeholder height");
+ globalEditors[0] = firstRecord.editor;
+ globalList.onScroll = originalScroll;
+ globalPanel.type = "bottom";
+ globalPanel.empty = true;
+ globalElement.classList.add("sy__backlink--backlinks-empty", "sy__backlink--mentions-empty");
+ globalList.clearUnavailable();
+ assert.equal(globalElement.classList.contains("sy__backlink--backlinks-empty"), false,
+ "a failed bottom list must keep its retry control visible");
+ assert.equal(globalPanel.empty, false);
+ assert.equal(globalList.message.textContent, "retry");
+ globalList.message.click();
+ await tick();
+ assert.equal(requests[0]?.url, "/api/ref/getGlobalBacklinks");
+ requests.shift().reply({snapshot: "empty", offset: 0, total: 0, items: []});
+ await tick();
+ assert.equal(globalList.hasError, false);
+ assert.equal(globalElement.classList.contains("sy__backlink--backlinks-empty"), true,
+ "a successful empty retry must restore normal empty handling");
+ globalPanel.type = "local";
+ globalList.search({...globalList.query, keyword: "restored"}, false);
+ await tick();
+ assert.equal(requests[0]?.url, "/api/ref/getGlobalBacklinks");
+ requests.shift().reply({snapshot: "restored", offset: 0, total: 1, items: [
+ {id: "first", rootID: "source1", box: "box", hPath: "/Source 1", anchor: "A1"},
+ ]});
+ for (let i = 0; i < 20 && requests.length === 0; i++) { await tick(); }
+ assert.equal(requests[0]?.url, "/api/ref/getGlobalBacklinkContexts");
+ requests.shift().reply({expired: false, items: [
+ {id: "first", revision: "first2", dom: "", blockPaths: [], expand: true},
+ ]});
+ await tick();
+ assert.equal(globalPanel.editors.length, 1);
+ globalEditors.splice(0, globalEditors.length, ...globalPanel.editors);
panels.removeMobileBacklinkContent({notebookId: "box"});
assert.equal(globalPanel.editors.length, 0);
assert.equal(registry.getMobileSecondaryEditors().length, 0);
diff --git a/app/tests/taskStatus.test.js b/app/tests/taskStatus.test.js
index db6726cc39..46904f2cd4 100644
--- a/app/tests/taskStatus.test.js
+++ b/app/tests/taskStatus.test.js
@@ -34,6 +34,8 @@ const sources = () => {
icons: ["unchecked", "in-progress", "canceled"].map(name =>
readFileSync(path.join(__dirname, `../src/assets/icon/task-${name}.svg`), "utf8")),
actions: extract("protyle/render/tabsRender.ts", ["getTabTask", "getTabItems", "hasTabsTasks"]) +
+ extract("protyle/render/listMindmap/model.ts", ["LIST_MINDMAP_META_ATTRIBUTE", "isRecord", "invalidMetadata",
+ "parseListMindmapMetadata", "cleanListMindmapDOM", "remapListMindmapIDs"]) +
extract("protyle/util/tabsCopy.ts", ["preserveTabTask", "preserveCopiedTabTask", "remapTabsDOMIDs", "wrapPastedTabItems"]) +
extract("protyle/wysiwyg/tabsRemoval.ts", ["repairActiveTab"]) +
extract("protyle/wysiwyg/taskListMarker.ts", ["getTaskListMarker", "isTaskListMarker", "nextTaskListMarker"]) +
diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.md
index 7be8212fd6..b3895a18fe 100644
--- a/docs/API-CONTRACTS.md
+++ b/docs/API-CONTRACTS.md
@@ -124,6 +124,8 @@ The global backlink endpoints use a separate flat list. `/api/ref/getGlobalBackl
`TestGlobalBacklink*`, `TestAPIContractGlobalBacklink`, `TestBacklinkAnchorSortContext`, and `TestBacklink2OptionalMentions` cover cross-document pagination, first-reference selection, snapshot stability after edits, reading-position lookup, ordinary and encrypted reads, source permissions, expiration, cache bounds, HTTP response contracts, and mention compatibility. They run in the full kernel CI command below; run the affected subset with `go test -tags "fts5 sqlcipher" ./model ./api ./apicontract/... -run 'Test(GlobalBacklink|Backlink|APIContractGlobalBacklink|APIContractBack|APIContractSetting|PublishReaderBack|PublishReaderSearchAndBacklink|RouteCoverage)' -count=1`. Frontend regression files `globalBacklinkPaging.test.ts`, `globalBacklinkList.test.js`, and `backlinkSort.test.js` run in the existing full frontend CI selection and cover window bounds, stale responses, pending edits, and mode switching.
+`TestGlobalBacklinkLargeDataset` creates 10,000 references across 100 real documents and indexes them in an isolated database. It checks natural order and absence of duplicate or missing entries across all 200 pages, then loads 16 editable contexts. It reports initial sorting, cached pagination, context loading, and snapshot size without imposing machine-dependent timing thresholds. Run it with `go test -tags "fts5 sqlcipher" ./model -run TestGlobalBacklinkLargeDataset -count=1 -v`; the existing `TestGlobalBacklink*` selection and full kernel CI include it. Frontend regressions also cover keeping the bottom-panel retry control visible after failure, restoring empty-state behavior after retry, and preserving the entire row height when recycling and recreating editors.
+
## File and streaming protocols
`RawSSEOptions` and `RawWebSocketOptions` declare byte-oriented broadcast protocols. Use `ValidateRawSSEEvent` and `ValidateRawWebSocketFrame` to check their event and frame metadata independently; JSON event and RPC message declarations retain their existing validation. Raw WebSocket failures are written by the upgrader rather than `RejectWebSocket`.
diff --git a/docs/API-CONTRACTS.zh-CN.md b/docs/API-CONTRACTS.zh-CN.md
index a0eafdfeb1..5512fa727a 100644
--- a/docs/API-CONTRACTS.zh-CN.md
+++ b/docs/API-CONTRACTS.zh-CN.md
@@ -124,6 +124,8 @@ SQL 查询契约保留成功信封顶层的 `limit` 和 `truncated`。`SuccessSQ
`TestGlobalBacklink*`、`TestAPIContractGlobalBacklink`、`TestBacklinkAnchorSortContext` 和 `TestBacklink2OptionalMentions` 覆盖跨文档分页、首个引用取值、编辑后的快照稳定性、阅读定位、普通和加密读取、来源权限、过期、缓存上限、实际 HTTP 响应契约及提及兼容性。它们包含在下方内核全量 CI 命令中,可单独运行 `go test -tags "fts5 sqlcipher" ./model ./api ./apicontract/... -run 'Test(GlobalBacklink|Backlink|APIContractGlobalBacklink|APIContractBack|APIContractSetting|PublishReaderBack|PublishReaderSearchAndBacklink|RouteCoverage)' -count=1`。前端的 `globalBacklinkPaging.test.ts`、`globalBacklinkList.test.js` 和 `backlinkSort.test.js` 已由现有全量 CI 自动发现,覆盖页窗口上限、迟到响应、待提交编辑和模式切换。
+`TestGlobalBacklinkLargeDataset` 在隔离数据库中创建并索引 100 篇真实文档、共 10,000 条引用,逐一检查全部 200 页的自然顺序及条目无重复、无遗漏,再加载 16 个可编辑上下文。测试报告首次排序、缓存分页、正文加载的耗时及快照大小,不设置依赖机器性能的时间阈值。可运行 `go test -tags "fts5 sqlcipher" ./model -run TestGlobalBacklinkLargeDataset -count=1 -v`;现有 `TestGlobalBacklink*` 筛选和内核全量 CI 均包含该测试。前端回归还覆盖底部面板请求失败后的重试入口、重试成功后的空状态恢复,以及编辑器回收与重建时整行高度保持稳定。
+
## 文件与流式协议
`RawSSEOptions` 和 `RawWebSocketOptions` 声明以字节为载荷的广播协议,通过 `ValidateRawSSEEvent` 和 `ValidateRawWebSocketFrame` 单独校验事件及帧元数据;JSON 事件与 RPC 消息保留各自既有校验。原始 WebSocket 的错误由升级器写出,不使用 `RejectWebSocket`。
diff --git a/kernel/model/backlink_global_fts5_test.go b/kernel/model/backlink_global_fts5_test.go
index c544cd31c6..735a7132fa 100644
--- a/kernel/model/backlink_global_fts5_test.go
+++ b/kernel/model/backlink_global_fts5_test.go
@@ -154,3 +154,73 @@ func TestGlobalBacklinkSnapshotBounds(t *testing.T) {
t.Fatal("notebook purge did not isolate affected source snapshots")
}
}
+
+// 使用真实文档和引用索引验证万条反链,耗时只作观测,避免按机器速度设置脆弱阈值。
+func TestGlobalBacklinkLargeDataset(t *testing.T) {
+ fixture := setupStructureTransactionTest(t)
+ setupFoldTransactionDatabase(t, fixture)
+ Conf.Search = conf.NewSearch()
+ t.Cleanup(func() { ClearGlobalBacklinkSnapshots("") })
+ const documents, perDocument = 100, 100
+ definition, err := LoadTreeByBlockID(fixture.sourceID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ sql.IndexTreeQueue(definition)
+ for doc := 0; doc < documents; doc++ {
+ tree := addFileOperationTestDoc(t, fixture, ast.NewNodeID(), fmt.Sprintf("Source%d", doc), false)
+ for tree.Root.FirstChild != nil {
+ tree.Root.FirstChild.Unlink()
+ }
+ for index := perDocument - 1; index >= 0; index-- {
+ p := treenode.NewParagraph(ast.NewNodeID())
+ p.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkBlockRefID: fixture.sourceID,
+ TextMarkBlockRefSubtype: "s", TextMarkTextContent: fmt.Sprintf("A%d", index*documents+doc+1)})
+ tree.Root.AppendChild(p)
+ }
+ if _, err := filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+ sql.IndexTreeQueue(tree)
+ sql.UpdateRefsTreeQueue(tree)
+ }
+ sql.FlushQueue()
+ query := GlobalBacklinkQuery{ID: fixture.sourceID, Sort: 1}
+ allow := func(string) bool { return true }
+ started := time.Now()
+ token, first, total, _, expired, err := GetGlobalBacklinks(query, "", 0, "", allow)
+ initialDuration := time.Since(started)
+ if err != nil || expired || total != documents*perDocument || len(first) != GlobalBacklinkPageSize {
+ t.Fatalf("large first page: %d %d %v %v", total, len(first), expired, err)
+ }
+ seen := map[string]bool{}
+ started = time.Now()
+ for offset := 0; offset < total; offset += GlobalBacklinkPageSize {
+ _, items, count, page, expired, err := GetGlobalBacklinks(query, token, offset, "", allow)
+ if err != nil || expired || count != total || page != offset {
+ t.Fatalf("large page %d: %v %v", offset, expired, err)
+ }
+ for index, item := range items {
+ if seen[item.ID] || item.Anchor != fmt.Sprintf("A%d", offset+index+1) {
+ t.Fatalf("duplicate or unsorted large result: %+v", item)
+ }
+ seen[item.ID] = true
+ }
+ }
+ pagesDuration := time.Since(started)
+ if len(seen) != total {
+ t.Fatalf("missing large results: %d of %d", len(seen), total)
+ }
+ var ids []string
+ for _, item := range first[:16] {
+ ids = append(ids, item.ID)
+ }
+ started = time.Now()
+ contexts, expired, err := GetGlobalBacklinkContexts(query, token, ids, allow)
+ if err != nil || expired || len(contexts) != len(ids) {
+ t.Fatalf("large contexts: %d %v %v", len(contexts), expired, err)
+ }
+ t.Logf("%d references / %d documents: initial=%s, %d cached pages=%s, 16 contexts=%s, snapshot=%d bytes",
+ total, documents, initialDuration, total/GlobalBacklinkPageSize, pagesDuration, time.Since(started), globalBacklinkSnapshots.values[token].bytes)
+}