An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Resolve stale tree caches and export renderer initialization
Danielc902a56eecf1
diff --git a/app/src/plugin/ProtyleMethod.test.ts b/app/src/plugin/ProtyleMethod.test.tsnew file mode 100644index 0000000000..292613563c--- /dev/null+++ b/app/src/plugin/ProtyleMethod.test.ts@@ -0,0 +1,38 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";++test("renderer methods wait for circular dependencies and preserve arguments and return values", () => {+ const source = readFileSync("src/plugin/ProtyleMethod.ts", "utf8");+ const compiled = transpileModule(source, {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText;+ let initialized = false;+ const calls: {name: string, args: unknown[]}[] = [];+ const result = Promise.resolve("rendered");+ const exports: {ProtyleMethod?: Record<string, (...args: unknown[]) => unknown>} = {};+ runInNewContext(compiled, {+ exports,+ require: () => new Proxy({}, {+ get: (_target, name: string) => {+ assert.equal(initialized, true, `read ${name} before its module finished initializing`);+ return (...args: unknown[]) => {+ calls.push({name, args});+ return result;+ };+ },+ }),+ });+ initialized = true;+ const methods = exports.ProtyleMethod!;+ const expected = ["tabsRender", "graphvizRender", "highlightRender", "mathRender", "mermaidRender",+ "flowchartRender", "chartRender", "abcRender", "mindmapRender", "plantumlRender", "avRender", "htmlRender"];+ assert.deepEqual(Object.keys(methods).sort(), expected.sort());+ for (const name of expected) {+ const element = {};+ assert.equal(methods[name](element, undefined, false), result);+ assert.deepEqual(calls.at(-1), {name, args: [element, undefined, false]});+ }+});diff --git a/app/src/plugin/ProtyleMethod.ts b/app/src/plugin/ProtyleMethod.tsindex a108e16660..c5127deb3b 100644--- a/app/src/plugin/ProtyleMethod.ts+++ b/app/src/plugin/ProtyleMethod.ts@@ -12,25 +12,26 @@ import { avRender } from "../protyle/render/av/render";import {tabsRender} from "../protyle/render/tabsRender";export class ProtyleMethod {- public static tabsRender = tabsRender;+ // 调用时再读取渲染函数,避免导出入口的循环依赖提前访问未初始化的绑定。+ public static tabsRender = (...args: Parameters<typeof tabsRender>) => tabsRender(...args);/** 对 graphviz 进行渲染 */- public static graphvizRender = graphvizRender;+ public static graphvizRender = (...args: Parameters<typeof graphvizRender>) => graphvizRender(...args);/** 为 element 中的代码块进行高亮渲染 */- public static highlightRender = highlightRender;+ public static highlightRender = (...args: Parameters<typeof highlightRender>) => highlightRender(...args);/** 对数学公式进行渲染 */- public static mathRender = mathRender;+ public static mathRender = (...args: Parameters<typeof mathRender>) => mathRender(...args);/** 流程图/时序图/甘特图渲染 */- public static mermaidRender = mermaidRender;+ public static mermaidRender = (...args: Parameters<typeof mermaidRender>) => mermaidRender(...args);/** flowchart.js 渲染 */- public static flowchartRender = flowchartRender;+ public static flowchartRender = (...args: Parameters<typeof flowchartRender>) => flowchartRender(...args);/** 图表渲染 */- public static chartRender = chartRender;+ public static chartRender = (...args: Parameters<typeof chartRender>) => chartRender(...args);/** 五线谱渲染 */- public static abcRender = abcRender;+ public static abcRender = (...args: Parameters<typeof abcRender>) => abcRender(...args);/** 脑图渲染 */- public static mindmapRender = mindmapRender;+ public static mindmapRender = (...args: Parameters<typeof mindmapRender>) => mindmapRender(...args);/** UML 渲染 */- public static plantumlRender = plantumlRender;- public static avRender = avRender;- public static htmlRender = htmlRender;+ public static plantumlRender = (...args: Parameters<typeof plantumlRender>) => plantumlRender(...args);+ public static avRender = (...args: Parameters<typeof avRender>) => avRender(...args);+ public static htmlRender = (...args: Parameters<typeof htmlRender>) => htmlRender(...args);}diff --git a/app/src/protyle/util/navigationHistory.test.ts b/app/src/protyle/util/navigationHistory.test.tsindex e62f3de346..8c5ca7e74a 100644--- a/app/src/protyle/util/navigationHistory.test.ts+++ b/app/src/protyle/util/navigationHistory.test.ts@@ -25,6 +25,7 @@ const navigate = (action: string[], tablet = true, suppressFocus = false) => {isPhablet: () => tablet,hasFocusOffsets: () => false,isInEmbedBlock: () => false,+ resolveVisibleListMindmapBlock: (): undefined => undefined,hasClosestByAttribute: () => false,getContenteditableElement: () => element,document: {createRange: () => range},@@ -46,6 +47,7 @@ const navigate = (action: string[], tablet = true, suppressFocus = false) => {block: {id: "block", rootID: "root"},wysiwyg: {element: {ownerDocument: {activeElement: null}, querySelectorAll: () => [element], firstElementChild: element}},contentElement: {addEventListener: () => {}},+ element: {addEventListener: () => {}},observer: {unobserve: () => {}},}, action, undefined, undefined, false, suppressFocus);return {records, focused};diff --git a/app/tests/avAttributeCarrier.test.js b/app/tests/avAttributeCarrier.test.jsindex 58509c0fb9..99b4fcf1f7 100644--- a/app/tests/avAttributeCarrier.test.js+++ b/app/tests/avAttributeCarrier.test.js@@ -139,7 +139,7 @@ const runCases = async () => {renderAVAttribute: (body, _id, _protyle, callback) => {pendingRenders.push(text => {const value = encodeURIComponent(JSON.stringify({block: {content: text}}));- body.innerHTML = `<div data-primary="true"><span data-cell-value="${value}">${text}</span></div>`;+ body.innerHTML = `<div data-av-id="database" data-primary="true"><span data-cell-value="${value}">${text}</span></div>`;callback(body);});},diff --git a/app/tests/tabsNavigation.test.js b/app/tests/tabsNavigation.test.jsindex bcb7d9c894..8957b3a782 100644--- a/app/tests/tabsNavigation.test.js+++ b/app/tests/tabsNavigation.test.js@@ -69,7 +69,7 @@ const cases = (source) => {(_protyle, target) => { scrolls++; target.dataset.tabsHidden = "false"; }, () => {}, () => {});root.innerHTML = '<div class="tab-item" data-node-id="target" data-tabs-hidden="false">Target</div>';const target = root.firstElementChild;- const protyle = {wysiwyg: {element: root}, contentElement: root,+ const protyle = {element: root, wysiwyg: {element: root}, contentElement: root,preview: {element: {classList: {contains: () => true}}}, toolbar: {}, block: {rootID: "doc"}};const editor = {editor: {protyle}, parent: {parent: {switchTab() {}, showHeading() {}}}};const start = () => {diff --git a/kernel/cache/tree.go b/kernel/cache/tree.goindex 3c6d39ed3b..433cc8a449 100644--- a/kernel/cache/tree.go+++ b/kernel/cache/tree.go@@ -23,7 +23,8 @@ import ()type treeCacheEntry struct {- raw []byte+ raw []byte+ generation uint64}var (@@ -32,8 +33,9 @@ var (MaxCost: 1024 * 1024 * 200,BufferItems: 64,})- treeCacheKeys = map[string]map[string]struct{}{}- treeCacheKeysMu sync.Mutex+ treeCacheKeys = map[string]map[string]uint64{}+ treeCacheKeysMu sync.Mutex+ treeCacheGeneration uint64)func treeCacheKey(rootID, boxID string) string {@@ -45,11 +47,18 @@ func GetTreeData(rootID string) (raw []byte, ok bool) {}func GetTreeDataInBox(rootID, boxID string) (raw []byte, ok bool) {- v, _ := treeCache.Get(treeCacheKey(rootID, boxID))+ treeCacheKeysMu.Lock()+ defer treeCacheKeysMu.Unlock()+ key := treeCacheKey(rootID, boxID)+ v, _ := treeCache.Get(key)if nil == v {return nil, false}e := v.(*treeCacheEntry)+ // 异步准入可能保留较早的写入,只接受当前版本,否则交由调用方读取源文件。+ if e.generation != treeCacheKeys[rootID][key] {+ return nil, false+ }return e.raw, true}@@ -62,24 +71,24 @@ func SetTreeDataInBox(rootID, boxID string, raw []byte) {return}key := treeCacheKey(rootID, boxID)- entry := &treeCacheEntry{raw: raw}- treeCache.Set(key, entry, int64(len(raw)))-treeCacheKeysMu.Lock()defer treeCacheKeysMu.Unlock()+ treeCacheGeneration+++ entry := &treeCacheEntry{raw: raw, generation: treeCacheGeneration}keys := treeCacheKeys[rootID]if keys == nil {- keys = map[string]struct{}{}+ keys = map[string]uint64{}treeCacheKeys[rootID] = keys}- keys[key] = struct{}{}+ keys[key] = entry.generation+ treeCache.Set(key, entry, int64(len(raw)))}func RemoveTreeData(rootID string) {treeCacheKeysMu.Lock()+ defer treeCacheKeysMu.Unlock()keys := treeCacheKeys[rootID]delete(treeCacheKeys, rootID)- treeCacheKeysMu.Unlock()treeCache.Del(rootID)treeCache.Del(treeCacheKey(rootID, ""))@@ -90,10 +99,9 @@ func RemoveTreeData(rootID string) {func RemoveTreeDataInBox(rootID, boxID string) {key := treeCacheKey(rootID, boxID)- treeCache.Del(key)-treeCacheKeysMu.Lock()defer treeCacheKeysMu.Unlock()+ treeCache.Del(key)if keys := treeCacheKeys[rootID]; keys != nil {delete(keys, key)if len(keys) == 0 {@@ -104,7 +112,7 @@ func RemoveTreeDataInBox(rootID, boxID string) {func ClearTreeCache() {treeCacheKeysMu.Lock()- treeCacheKeys = map[string]map[string]struct{}{}- treeCacheKeysMu.Unlock()+ defer treeCacheKeysMu.Unlock()+ treeCacheKeys = map[string]map[string]uint64{}treeCache.Clear()}diff --git a/kernel/cache/tree_test.go b/kernel/cache/tree_test.gonew file mode 100644index 0000000000..ff25e9ac90--- /dev/null+++ b/kernel/cache/tree_test.go@@ -0,0 +1,67 @@+package cache++import (+ "bytes"+ "testing"++ "github.com/dgraph-io/ristretto"+)++func TestTreeCacheRejectsStaleAsyncAdmission(t *testing.T) {+ original := treeCache+ entered, release := make(chan struct{}), make(chan struct{})+ controlled, err := ristretto.NewCache(&ristretto.Config{+ NumCounters: 100, MaxCost: 1 << 20, BufferItems: 64,+ Cost: func(value interface{}) int64 {+ close(entered)+ <-release+ return 1+ },+ })+ if err != nil {+ t.Fatal(err)+ }+ treeCache = controlled+ t.Cleanup(func() {+ ClearTreeCache()+ controlled.Close()+ treeCache = original+ })+ // 暂停准入线程,让同一文档的两次写入都在首次缓存建立前入队。+ SetTreeDataInBox("blocker", "box", []byte{})+ <-entered+ SetTreeDataInBox("document", "box", []byte("old"))+ SetTreeDataInBox("document", "box", []byte("latest"))+ close(release)+ controlled.Wait()+ if raw, ok := GetTreeDataInBox("document", "box"); ok && !bytes.Equal(raw, []byte("latest")) {+ t.Fatalf("returned stale document after a newer write: %q", raw)+ }+ // 未命中后重新读取源文件,可以恢复当前版本的缓存。+ SetTreeDataInBox("document", "box", []byte("latest"))+ controlled.Wait()+ if raw, ok := GetTreeDataInBox("document", "box"); !ok || !bytes.Equal(raw, []byte("latest")) {+ t.Fatalf("latest document was not cached: %q, %v", raw, ok)+ }+}++func TestTreeCacheRemovalKeepsNotebookIsolation(t *testing.T) {+ t.Cleanup(ClearTreeCache)+ for _, box := range []string{"", "plain", "encrypted"} {+ SetTreeDataInBox("document", box, []byte(box+" content"))+ }+ treeCache.Wait()+ RemoveTreeDataInBox("document", "encrypted")+ if _, ok := GetTreeDataInBox("document", "encrypted"); ok {+ t.Fatal("removed notebook cache remained readable")+ }+ if raw, ok := GetTreeDataInBox("document", "plain"); !ok || string(raw) != "plain content" {+ t.Fatal("removing another notebook changed the plain cache")+ }+ RemoveTreeData("document")+ for _, box := range []string{"", "plain", "encrypted"} {+ if _, ok := GetTreeDataInBox("document", box); ok {+ t.Fatalf("document cache remained readable in notebook %q", box)+ }+ }+}