Skip to content

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

:zap: Improve backlink refresh and list query performance

Danielc6827652d837
diff --git a/app/src/layout/dock/BacklinkContent.ts b/app/src/layout/dock/BacklinkContent.ts
index b233246042..0cea32afc1 100644
--- a/app/src/layout/dock/BacklinkContent.ts
+++ b/app/src/layout/dock/BacklinkContent.ts
@@ -157,6 +157,7 @@ export class BacklinkContent extends Model {
private listQueryKey = "";
private renderedQueryKey = "";
private indexChangeVersion = 0;
+ private indexRefreshTimer?: number;
private pendingRootIDs = new Set<string>();
private pendingFull = false;
private ownerFocusoutListener?: (event: FocusEvent) => void;
@@ -1846,6 +1847,7 @@ export class BacklinkContent extends Model {
}
public prepareForBlock(blockId: string, rootId: string) {
+ this.clearIndexRefresh();
if (!this.showingLoading) {
this.saveStatus();
}
@@ -1865,6 +1867,7 @@ export class BacklinkContent extends Model {
}
public switchBlock(blockId: string, rootId: string, notebookId: string) {
+ this.clearIndexRefresh();
if (this.blockId) {
this.saveStatus();
}
@@ -1932,6 +1935,7 @@ export class BacklinkContent extends Model {
}
public refresh() {
+ this.clearIndexRefresh();
if (!this.blockId) {
return;
}
@@ -1993,6 +1997,7 @@ export class BacklinkContent extends Model {
return;
}
this.searchQueued = false;
+ this.clearIndexRefresh();
this.setRequesting(true);
// 解析当前反链面板所属 box:优先用已记录的 notebookId,首次为空时按 rootId 在已打开的编辑器里查找
let notebookId = this.notebookId;
@@ -2105,15 +2110,15 @@ export class BacklinkContent extends Model {
this.pendingFull = false;
this.dirty = false;
}
- if (this.type === "bottom" && this.dirty) {
- this.refreshIfVisible();
+ if (this.dirty) {
+ this.refreshAfterIndex();
}
}).finally(() => {
if (responseHandled || !this.finishRequest(requestID) || blockId !== this.blockId) {
return;
}
- if (!this.runQueuedRequest() && this.type === "bottom" && this.dirty) {
- this.refreshIfVisible();
+ if (!this.runQueuedRequest() && indexChangeVersion !== this.indexChangeVersion && this.dirty) {
+ this.refreshAfterIndex();
}
});
}
@@ -2412,20 +2417,34 @@ export class BacklinkContent extends Model {
}));
}
+ private clearIndexRefresh() {
+ window.clearTimeout(this.indexRefreshTimer);
+ this.indexRefreshTimer = undefined;
+ }
+
public refreshAfterIndex() {
- if (this.destroyed || !this.blockId || !this.dirty || this.element.contains(document.activeElement) ||
- hasAVEditorSession(this.element)) {
+ this.clearIndexRefresh();
+ if (this.destroyed || !this.blockId || !this.dirty) {
return;
}
- if (this.type === "bottom") {
- this.refreshIfVisible();
- } else if (this.element.isConnected && this.element.getClientRects().length > 0) {
- this.searchBacklinks();
- }
+ // 连续索引更新合并到空闲时处理;请求期间只保留脏标记,完成后再安排下一次刷新。
+ this.indexRefreshTimer = window.setTimeout(() => {
+ this.indexRefreshTimer = undefined;
+ if (this.destroyed || this.requesting || !this.dirty || this.element.contains(document.activeElement) ||
+ hasAVEditorSession(this.element)) {
+ return;
+ }
+ if (this.type === "bottom") {
+ this.refreshIfVisible();
+ } else if (this.element.isConnected && this.element.getClientRects().length > 0) {
+ this.searchBacklinks();
+ }
+ }, 1000);
}
public refreshIfVisible(ignoreFocus = false) {
- if (this.type !== "bottom" || !this.dirty) {
+ if (this.destroyed || this.type !== "bottom" || !this.dirty || this.requesting ||
+ (!ignoreFocus && this.indexRefreshTimer !== undefined)) {
return;
}
if (!this.element.isConnected || this.ownerProtyle.element.getClientRects().length === 0) {
@@ -2469,6 +2488,7 @@ export class BacklinkContent extends Model {
this.globalList?.destroy();
this.globalList = undefined;
this.destroyed = true;
+ this.clearIndexRefresh();
this.viewStateGeneration++;
this.clearReadingAnchorTimers();
cancelHeightAnimation(this.tree.element);
diff --git a/app/tests/backlinkRefresh.test.js b/app/tests/backlinkRefresh.test.js
new file mode 100644
index 0000000000..42d5d1db4b
--- /dev/null
+++ b/app/tests/backlinkRefresh.test.js
@@ -0,0 +1,119 @@
+const assert = require("node:assert/strict");
+const {readFileSync} = require("node:fs");
+const {test} = require("node:test");
+const {runInNewContext} = require("node:vm");
+const {ModuleKind, ScriptTarget, transpileModule} = require("typescript");
+
+const compiled = transpileModule(readFileSync("src/layout/dock/BacklinkContent.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+
+const setup = (type = "local") => {
+ const exports = {};
+ let clock = 0;
+ let timerID = 0;
+ let focused = false;
+ let visible = true;
+ const timers = new Map();
+ runInNewContext(compiled, {
+ exports,
+ require: () => ({Model: class {}, hasAVEditorSession: () => false,
+ shouldDeferBottomBacklinkRefresh: (focus, ignore) => focus && !ignore}),
+ document: {activeElement: {}},
+ window: {
+ setTimeout: (callback, delay) => {
+ timers.set(++timerID, {callback, due: clock + delay});
+ return timerID;
+ },
+ clearTimeout: id => timers.delete(id),
+ },
+ });
+ const panel = Object.create(exports.BacklinkContent.prototype);
+ const requests = [];
+ Object.assign(panel, {
+ type, blockId: "target", dirty: false, destroyed: false, requesting: false,
+ pendingFull: false, pendingRootIDs: new Set(), itemRecords: [new Map(), new Map()], indexChangeVersion: 0,
+ element: {contains: () => focused, isConnected: true, getClientRects: () => visible ? [{}] : []},
+ ownerProtyle: {element: {getClientRects: () => visible ? [{}] : []}}, empty: true,
+ searchBacklinks() { this.requesting = true; requests.push(this.indexChangeVersion); },
+ });
+ const advance = ms => {
+ clock += ms;
+ for (const [id, timer] of timers) {
+ if (timer.due <= clock) {
+ timers.delete(id);
+ timer.callback();
+ }
+ }
+ };
+ const change = rootID => {
+ panel.markIndexDirty({backlinkChanged: true, rootIDs: [rootID]});
+ panel.refreshAfterIndex();
+ };
+ return {panel, requests, timers, advance, change,
+ focus: value => { focused = value; }, show: value => { visible = value; }};
+};
+
+for (const type of ["local", "bottom"]) {
+ test(`${type} backlink refresh coalesces edits and retains every changed document`, () => {
+ const {panel, requests, advance, change} = setup(type);
+ change("one");
+ advance(700);
+ change("two");
+ panel.refreshIfVisible();
+ advance(700);
+ assert.equal(requests.length, 0);
+ advance(300);
+ assert.deepEqual(requests, [2]);
+ assert.deepEqual([...panel.pendingRootIDs], ["one", "two"]);
+ });
+
+ test(`${type} backlink refresh never queues searches behind a slow request`, () => {
+ const {panel, requests, advance, change} = setup(type);
+ change("one");
+ advance(1000);
+ for (let i = 0; i < 5; i++) {
+ change("two");
+ advance(1000);
+ panel.refreshIfVisible();
+ }
+ assert.equal(requests.length, 1);
+ assert.ok(!panel.searchQueued);
+ assert.equal(panel.dirty, true);
+ panel.requesting = false;
+ panel.refreshAfterIndex();
+ assert.equal(requests.length, 1);
+ advance(1000);
+ assert.equal(requests.length, 2);
+ });
+
+ test(`${type} backlink refresh rechecks visibility and focus after the delay`, () => {
+ const {panel, requests, advance, change, focus, show} = setup(type);
+ change("one");
+ focus(true);
+ advance(1000);
+ assert.equal(requests.length, 0);
+ focus(false);
+ show(false);
+ panel.refreshAfterIndex();
+ advance(1000);
+ assert.equal(requests.length, 0);
+ show(true);
+ panel.refreshAfterIndex();
+ advance(1000);
+ assert.equal(requests.length, 1);
+ });
+}
+
+test("cancelled and destroyed panels cannot issue a delayed refresh", () => {
+ const {panel, requests, timers, advance, change} = setup();
+ change("one");
+ panel.clearIndexRefresh();
+ assert.equal(timers.size, 0);
+ advance(1000);
+ assert.equal(requests.length, 0);
+ change("two");
+ panel.destroyed = true;
+ advance(1000);
+ assert.equal(requests.length, 0);
+});
diff --git a/app/tests/mobileBacklinks.test.js b/app/tests/mobileBacklinks.test.js
index d52f0d06f1..4d2b316ada 100644
--- a/app/tests/mobileBacklinks.test.js
+++ b/app/tests/mobileBacklinks.test.js
@@ -136,6 +136,7 @@ const runCases = async (sources) => {
assert.deepEqual(registry.getMobileSecondaryEditors(), [editor]);
panel.markIndexDirty({backlinkChanged: true, backlinkFull: true});
panel.refreshAfterIndex();
+ await new Promise(resolve => setTimeout(resolve, 1100));
const inFlight = requests.shift();
editor.protyle.wysiwyg.element.focus();
assert.equal(registry.getActiveMobileSecondaryEditor(), editor);
diff --git a/kernel/model/backlink.go b/kernel/model/backlink.go
index 13a2b6fe07..aba6d255b0 100644
--- a/kernel/model/backlink.go
+++ b/kernel/model/backlink.go
@@ -634,11 +634,7 @@ func GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword string, sortMode,
if nil != NormalizeBacklinkSourceFilter(sourceFilter) {
linkRefsCount = len(filteredLinkRefs)
}
- tmpBacklinks := toFlatTree(filteredLinkRefs, 0, "backlink", nil)
- for _, l := range tmpBacklinks {
- l.Blocks = nil
- backlinks = append(backlinks, l)
- }
+ backlinks = backlinkListPaths(filteredLinkRefs, boxID)
} else {
linkRefsCount = 0
}
@@ -667,11 +663,7 @@ func GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword string, sortMode,
if includeMentions {
mentionRefs, _ := buildTreeBackmentionInBox(sqlBlock, linkRefs, mentionKeyword, excludeBacklinkIDs, 12, boxID)
- tmpBackmentions := toFlatTree(mentionRefs, 0, "backlink", nil)
- for _, l := range tmpBackmentions {
- l.Blocks = nil
- backmentions = append(backmentions, l)
- }
+ backmentions = backlinkListPaths(mentionRefs, boxID)
}
sort.Slice(backmentions, func(i, j int) bool {
@@ -721,6 +713,34 @@ func GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword string, sortMode,
return
}
+// 反链和提及列表只需要文档元数据及命中数量,按笔记本读取索引,避免为每组加载和渲染整篇文档。
+func backlinkListPaths(blocks []*Block, boxID string) (ret []*Path) {
+ ret = []*Path{}
+ counts := map[string]int{}
+ var rootIDs []string
+ for _, block := range blocks {
+ if counts[block.RootID] == 0 {
+ rootIDs = append(rootIDs, block.RootID)
+ }
+ counts[block.RootID]++
+ }
+ for start := 0; start < len(rootIDs); start += 512 {
+ for _, root := range sql.GetBlocksInBox(rootIDs[start:min(start+512, len(rootIDs))], boxID) {
+ if root == nil {
+ continue
+ }
+ block := fromSQLBlock(root, "", 0)
+ ret = append(ret, &Path{
+ ID: block.ID, Box: block.Box, Name: path.Base(block.HPath), HPath: block.HPath,
+ NodeType: block.Type, Type: "backlink", SubType: block.SubType,
+ Count: counts[block.ID], Updated: block.IAL["updated"], Created: block.ID[:14],
+ })
+ }
+ }
+ sort.Slice(ret, func(i, j int) bool { return ret[i].ID > ret[j].ID })
+ return
+}
+
func buildLinkRefs(defRootID string, refs []*sql.Ref, keywords []string) (ret []*Block, refsCount int, excludeBacklinkIDs *hashset.Set, originalRefBlockIDs map[string]string) {
return buildLinkRefsInBox(defRootID, refs, keywords, "")
}
diff --git a/kernel/model/backlink_mention_fts5_test.go b/kernel/model/backlink_mention_fts5_test.go
index 788345879e..19dc8f5b22 100644
--- a/kernel/model/backlink_mention_fts5_test.go
+++ b/kernel/model/backlink_mention_fts5_test.go
@@ -118,6 +118,17 @@ func TestBacklinkMentionFilteredPagination(t *testing.T) {
sql.UpdateRefsTreeQueue(tree)
}
sql.FlushQueue()
+ groupedBlocks := []*Block{{RootID: fixture.targetID}, {RootID: fixture.sourceID}, {RootID: fixture.targetID}}
+ wantPaths := toFlatTree(groupedBlocks, 0, "backlink", nil)
+ for _, item := range wantPaths {
+ item.Blocks = nil
+ }
+ if got := backlinkListPaths(groupedBlocks, boxID); !reflect.DeepEqual(got, wantPaths) {
+ t.Fatalf("indexed document groups changed list metadata: got %+v, want %+v", got, wantPaths)
+ }
+ if got := backlinkListPaths(nil, boxID); got == nil || len(got) != 0 {
+ t.Fatalf("empty groups must remain an empty array: %+v", got)
+ }
query, args := buildBackmentionQuery(columnFilter()+`:("needle" OR "broad")`, fixture.sourceID, "", 64)
if candidates := sql.SelectBlocksRawStmtArgsInBox(query, args, 64, boxID); len(candidates) != len(ids) {
var candidateIDs []string