Skip to content

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

:zap: Speed up initial document loading https://github.com/siyuan-note/siyuan/issues/18671

Daniel8484e446e970
diff --git a/app/src/mobile/editor.ts b/app/src/mobile/editor.ts
index 57efaa6a96..e23a086807 100644
--- a/app/src/mobile/editor.ts
+++ b/app/src/mobile/editor.ts
@@ -212,6 +212,7 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[
} else {
const getDocParam: IObject = {
id,
+ includeDocInfo: true,
size: actionList.includes(Constants.CB_GET_ALL) ? Constants.SIZE_GET_MAX : window.siyuan.config.editor.dynamicLoadBlocks,
mode: actionList.includes(Constants.CB_GET_CONTEXT) ? 3 : 0,
};
diff --git a/app/src/protyle/index.ts b/app/src/protyle/index.ts
index cf420a01b0..a114cad038 100644
--- a/app/src/protyle/index.ts
+++ b/app/src/protyle/index.ts
@@ -420,6 +420,7 @@ export class Protyle {
private getDoc(mergedOptions: IProtyleOptions) {
const getDocParam: Record<string, any> = {
id: mergedOptions.blockId,
+ includeDocInfo: true,
isBacklink: mergedOptions.action.includes(Constants.CB_GET_BACKLINK),
originalRefBlockIDs: mergedOptions.originalRefBlockIDs,
// 0: 仅当前 ID(默认值),1:向上 2:向下,3:上下都加载,4:加载最后
diff --git a/app/src/protyle/scroll/saveScroll.ts b/app/src/protyle/scroll/saveScroll.ts
index 201a455c34..8b97f7df44 100644
--- a/app/src/protyle/scroll/saveScroll.ts
+++ b/app/src/protyle/scroll/saveScroll.ts
@@ -79,6 +79,7 @@ export const getDocByScroll = (options: {
isValid?: () => boolean,
}) => {
const fetchDoc = (params: Record<string, any>, callback: (response: IWebSocketData) => void) => {
+ params.includeDocInfo = true;
let handled = false;
void fetchPost("/api/filetree/getDoc", params, (response) => {
handled = true;
diff --git a/app/src/protyle/util/docInfo.test.ts b/app/src/protyle/util/docInfo.test.ts
new file mode 100644
index 0000000000..4411139246
--- /dev/null
+++ b/app/src/protyle/util/docInfo.test.ts
@@ -0,0 +1,23 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {getEmbeddedDocInfoResponse} from "./docInfo";
+
+describe("getEmbeddedDocInfoResponse", () => {
+ it("wraps embedded document information as an API response", () => {
+ const docInfo = {id: "20260812000000-abcdefg", ial: {title: "Document"}};
+ assert.deepEqual(getEmbeddedDocInfoResponse({
+ code: 0,
+ msg: "",
+ data: {docInfo},
+ }), {
+ code: 0,
+ msg: "",
+ data: docInfo,
+ });
+ });
+
+ it("keeps the standalone API fallback when document information is absent", () => {
+ assert.equal(getEmbeddedDocInfoResponse({code: 0, msg: "", data: {}}), undefined);
+ assert.equal(getEmbeddedDocInfoResponse({code: 0, msg: "", data: {docInfo: null}}), undefined);
+ });
+});
diff --git a/app/src/protyle/util/docInfo.ts b/app/src/protyle/util/docInfo.ts
new file mode 100644
index 0000000000..40ffaee2e1
--- /dev/null
+++ b/app/src/protyle/util/docInfo.ts
@@ -0,0 +1,10 @@
+export const getEmbeddedDocInfoResponse = (response: IWebSocketData): IWebSocketData | undefined => {
+ if (!response.data?.docInfo) {
+ return undefined;
+ }
+ return {
+ code: 0,
+ msg: "",
+ data: response.data.docInfo,
+ };
+};
diff --git a/app/src/protyle/util/onGet.ts b/app/src/protyle/util/onGet.ts
index c1aa855a83..adcabfd071 100644
--- a/app/src/protyle/util/onGet.ts
+++ b/app/src/protyle/util/onGet.ts
@@ -28,6 +28,7 @@ import {
} from "./headingNumber";
import {updateDocumentBottomEof} from "./documentRange";
import {disabledWYSIWYG} from "./disabledWYSIWYG";
+import {getEmbeddedDocInfoResponse} from "./docInfo";
/// #if MOBILE
import {updateMobileTitleReadonly} from "./setEditMode";
/// #endif
@@ -155,13 +156,7 @@ export const onGet = (options: {
return;
}
- const docInfoParam: IObject = {
- id: options.protyle.block.rootID
- };
- if (isEncryptedBox(options.protyle.notebookId)) {
- docInfoParam.notebook = options.protyle.notebookId;
- }
- fetchPost("/api/block/getDocInfo", docInfoParam, (response) => {
+ const renderDoc = (response: IWebSocketData) => {
if (options.isValid && !options.isValid()) {
return;
}
@@ -188,7 +183,20 @@ export const onGet = (options: {
scrollPosition: options.scrollPosition
}, options.protyle);
removeLoading(options.protyle);
- });
+ };
+ const embeddedDocInfoResponse = getEmbeddedDocInfoResponse(options.data);
+ if (embeddedDocInfoResponse) {
+ renderDoc(embeddedDocInfoResponse);
+ return;
+ }
+
+ const docInfoParam: IObject = {
+ id: options.protyle.block.rootID
+ };
+ if (isEncryptedBox(options.protyle.notebookId)) {
+ docInfoParam.notebook = options.protyle.notebookId;
+ }
+ fetchPost("/api/block/getDocInfo", docInfoParam, renderDoc);
};
const setHTML = (options: {
diff --git a/kernel/api/filetree.go b/kernel/api/filetree.go
index 1ef60a2852..9b1f390bdd 100644
--- a/kernel/api/filetree.go
+++ b/kernel/api/filetree.go
@@ -1353,6 +1353,10 @@ func getDoc(c *gin.Context) {
ret.Msg = err.Error()
return
}
+ includeDocInfo, _ := arg["includeDocInfo"].(bool)
+ if includeDocInfo && model.IsReadOnlyRoleContext(c) {
+ includeDocInfo = isBlockPublishAccessible(c, id, requestedNotebook)
+ }
idx := arg["index"]
index := 0
if nil != idx {
@@ -1429,14 +1433,15 @@ func getDoc(c *gin.Context) {
var isBacklinkExpand bool
var keywords []string
var headingNumbers map[string]string
+ var docInfo *model.BlockInfo
var err error
// 加密笔记本的打开文档走 InBox 版(查加密 blocktree + content db)
if requestedNotebook != "" && model.IsEncryptedBox(requestedNotebook) {
- blockCount, content, parentID, parent2ID, rootID, typ, eof, scroll, boxID, docPath, isBacklinkExpand, keywords, headingNumbers, err =
- model.GetDocInBox(startID, endID, id, index, query, queryTypes, querySubTypes, queryMethod, mode, size, isBacklink, originalRefBlockIDs, highlight, requestedNotebook)
+ blockCount, content, parentID, parent2ID, rootID, typ, eof, scroll, boxID, docPath, isBacklinkExpand, keywords, headingNumbers, docInfo, err =
+ model.GetDocInBox(startID, endID, id, index, query, queryTypes, querySubTypes, queryMethod, mode, size, isBacklink, originalRefBlockIDs, highlight, includeDocInfo, requestedNotebook)
} else {
- blockCount, content, parentID, parent2ID, rootID, typ, eof, scroll, boxID, docPath, isBacklinkExpand, keywords, headingNumbers, err =
- model.GetDoc(startID, endID, id, index, query, queryTypes, querySubTypes, queryMethod, mode, size, isBacklink, originalRefBlockIDs, highlight)
+ blockCount, content, parentID, parent2ID, rootID, typ, eof, scroll, boxID, docPath, isBacklinkExpand, keywords, headingNumbers, docInfo, err =
+ model.GetDoc(startID, endID, id, index, query, queryTypes, querySubTypes, queryMethod, mode, size, isBacklink, originalRefBlockIDs, highlight, includeDocInfo)
}
if errors.Is(err, model.ErrBlockNotFound) {
ret.Code = 3
@@ -1462,9 +1467,16 @@ func getDoc(c *gin.Context) {
headingNumbers = nil
scroll = false // 避免长页面可通过滚动无限刷出多个锁
}
+ if nil != docInfo {
+ if publishAccessRequired {
+ docInfo = nil
+ } else {
+ docInfo = model.FilterBlockInfoByPublishAccess(c, publishAccess, docInfo)
+ }
+ }
}
- ret.Data = map[string]any{
+ data := map[string]any{
"id": id,
"mode": mode,
"parentID": parentID,
@@ -1484,6 +1496,10 @@ func getDoc(c *gin.Context) {
"publishAccessRequired": publishAccessRequired,
"reqId": arg["reqId"],
}
+ if nil != docInfo {
+ data["docInfo"] = docInfo
+ }
+ ret.Data = data
}
func setPublishAccess(c *gin.Context) {
diff --git a/kernel/api/filetree_test.go b/kernel/api/filetree_test.go
index 417a55f0ea..29f7be53fe 100644
--- a/kernel/api/filetree_test.go
+++ b/kernel/api/filetree_test.go
@@ -30,7 +30,9 @@ import (
"github.com/88250/lute/ast"
"github.com/88250/lute/parse"
"github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
"github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
@@ -495,13 +497,14 @@ func TestPublishReaderCannotBrowseEncryptedNotebook(t *testing.T) {
docRequest := httptest.NewRequest(
http.MethodPost,
"/api/filetree/getDoc",
- strings.NewReader(`{"id":"`+docID+`","notebook":"`+boxID+`"}`),
+ strings.NewReader(`{"id":"`+docID+`","notebook":"`+boxID+`","includeDocInfo":true}`),
)
docRequest.Header.Set("Content-Type", "application/json")
engine.ServeHTTP(docRecorder, docRequest)
docResponse := &struct {
- Code int `json:"code"`
+ Code int `json:"code"`
+ Data map[string]any `json:"data"`
}{}
if err := json.Unmarshal(docRecorder.Body.Bytes(), docResponse); err != nil {
t.Fatalf("unmarshal document response failed: %v", err)
@@ -509,6 +512,92 @@ func TestPublishReaderCannotBrowseEncryptedNotebook(t *testing.T) {
if docResponse.Code != 3 {
t.Fatalf("publish reader accessed encrypted document: %s", docRecorder.Body.String())
}
+ if _, ok := docResponse.Data["docInfo"]; ok {
+ t.Fatalf("publish reader received encrypted document info: %s", docRecorder.Body.String())
+ }
+}
+
+func TestGetDocOptionallyReturnsEmbeddedDocInfo(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ const boxID = "20260812000000-boxinfo"
+ originalConf := model.Conf
+ originalDataDir := util.DataDir
+ originalBlockTreeDBPath := util.BlockTreeDBPath
+ tempDir := t.TempDir()
+ util.DataDir = filepath.Join(tempDir, "data")
+ util.BlockTreeDBPath = filepath.Join(tempDir, "blocktree.db")
+ model.Conf = model.NewAppConf()
+ model.Conf.Editor = conf.NewEditor()
+ model.Conf.Export = conf.NewExport()
+ model.Conf.FileTree = conf.NewFileTree()
+ model.Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ model.Conf.Sync = conf.NewSync()
+
+ box := &model.Box{ID: boxID}
+ boxConf := conf.NewBoxConf()
+ boxConf.Name = "Embedded document info test"
+ boxConf.Closed = false
+ if err := box.SaveConf(boxConf); nil != err {
+ t.Fatalf("save test notebook config failed: %v", err)
+ }
+ treenode.InitBlockTree(true)
+ tree := treenode.NewTree(boxID, "/20260812000001-docinfo.sy", "/Document", "Document")
+ if _, err := filesys.WriteTree(tree); nil != err {
+ t.Fatalf("write test tree failed: %v", err)
+ }
+ treenode.UpsertBlockTree(tree)
+ t.Cleanup(func() {
+ cache.RemoveTreeData(tree.ID)
+ cache.RemoveDocIAL(tree.Path)
+ treenode.CloseDatabase()
+ model.Conf = originalConf
+ util.DataDir = originalDataDir
+ util.BlockTreeDBPath = originalBlockTreeDBPath
+ if "" != originalBlockTreeDBPath {
+ treenode.InitBlockTree(false)
+ }
+ })
+
+ engine := gin.New()
+ engine.POST("/api/filetree/getDoc", getDoc)
+ request := func(body string) (data map[string]json.RawMessage) {
+ t.Helper()
+ recorder := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPost, "/api/filetree/getDoc", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ engine.ServeHTTP(recorder, req)
+ response := &struct {
+ Code int `json:"code"`
+ Msg string `json:"msg"`
+ Data map[string]json.RawMessage `json:"data"`
+ }{}
+ if err := json.Unmarshal(recorder.Body.Bytes(), response); nil != err {
+ t.Fatalf("unmarshal document response failed: %v", err)
+ }
+ if 0 != response.Code {
+ t.Fatalf("get document failed with code %d and message %q: %s", response.Code, response.Msg, recorder.Body.String())
+ }
+ return response.Data
+ }
+
+ withoutInfo := request(`{"id":"` + tree.ID + `"}`)
+ if _, ok := withoutInfo["docInfo"]; ok {
+ t.Fatalf("document info should be absent by default: %s", withoutInfo["docInfo"])
+ }
+
+ withInfo := request(`{"id":"` + tree.Root.FirstChild.ID + `","includeDocInfo":true}`)
+ infoJSON, ok := withInfo["docInfo"]
+ if !ok {
+ t.Fatal("requested embedded document info is absent")
+ }
+ info := &model.BlockInfo{}
+ if err := json.Unmarshal(infoJSON, info); nil != err {
+ t.Fatalf("unmarshal embedded document info failed: %v", err)
+ }
+ if info.ID != tree.ID || info.RootID != tree.ID || info.Name != "Document" {
+ t.Fatalf("unexpected embedded document info: %#v", info)
+ }
}
func TestFilterFileTreePublishAccess(t *testing.T) {
diff --git a/kernel/model/blockinfo.go b/kernel/model/blockinfo.go
index d57aee5987..427138d887 100644
--- a/kernel/model/blockinfo.go
+++ b/kernel/model/blockinfo.go
@@ -71,7 +71,12 @@ func GetDocInfoInBox(blockID, boxID string) (ret *BlockInfo, err error) {
}
return
}
+ ret = getDocInfoByTree(blockID, tree)
+ return
+}
+func getDocInfoByTree(blockID string, tree *parse.Tree) (ret *BlockInfo) {
+ boxID := tree.Box
title := tree.Root.IALAttr("title")
ret = &BlockInfo{ID: blockID, RootID: tree.Root.ID, Name: title}
ret.IAL = parse.IAL2Map(tree.Root.KramdownIAL)
@@ -107,8 +112,12 @@ func GetDocInfoInBox(blockID, boxID string) (ret *BlockInfo, err error) {
}
bt := treenode.GetBlockTreeInBox(blockID, boxID)
- refDefs := queryBlockRefDefsInBox(bt, bt.BoxID)
- refDefs, _ = buildBacklinkListItemRefsInBox(refDefs, bt.BoxID)
+ refBoxID := boxID
+ if nil != bt {
+ refBoxID = bt.BoxID
+ }
+ refDefs := queryBlockRefDefsInBox(bt, refBoxID)
+ refDefs, _ = buildBacklinkListItemRefsInBox(refDefs, refBoxID)
var refIDs []string
for _, refDef := range refDefs {
refIDs = append(refIDs, refDef.RefID)
diff --git a/kernel/model/file.go b/kernel/model/file.go
index 493c4637ae..515735bd70 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -631,15 +631,15 @@ func ListDocTree(boxID, listPath string, sortMode int, flashcard, showHidden boo
return
}
-func GetDoc(startID, endID, id string, index int, query string, queryTypes, querySubTypes map[string]bool, queryMethod, mode int, size int, isBacklink bool, originalRefBlockIDs map[string]string, highlight bool) (
- blockCount int, dom, parentID, parent2ID, rootID, typ string, eof, scroll bool, boxID, docPath string, isBacklinkExpand bool, keywords []string, headingNumbers map[string]string, err error) {
- return GetDocInBox(startID, endID, id, index, query, queryTypes, querySubTypes, queryMethod, mode, size, isBacklink, originalRefBlockIDs, highlight, "")
+func GetDoc(startID, endID, id string, index int, query string, queryTypes, querySubTypes map[string]bool, queryMethod, mode int, size int, isBacklink bool, originalRefBlockIDs map[string]string, highlight, includeDocInfo bool) (
+ blockCount int, dom, parentID, parent2ID, rootID, typ string, eof, scroll bool, boxID, docPath string, isBacklinkExpand bool, keywords []string, headingNumbers map[string]string, docInfo *BlockInfo, err error) {
+ return GetDocInBox(startID, endID, id, index, query, queryTypes, querySubTypes, queryMethod, mode, size, isBacklink, originalRefBlockIDs, highlight, includeDocInfo, "")
}
// GetDocInBox 与 GetDoc 一致,但按 boxID 路由到加密 db 或全局 db。
// 加密笔记本打开文档时传入 boxID,blocktree/content 查询走加密 db;boxID 为空时 fall-through 全局 db。
-func GetDocInBox(startID, endID, id string, index int, query string, queryTypes, querySubTypes map[string]bool, queryMethod, mode int, size int, isBacklink bool, originalRefBlockIDs map[string]string, highlight bool, boxID string) (
- blockCount int, dom, parentID, parent2ID, rootID, typ string, eof, scroll bool, boxIDOut, docPath string, isBacklinkExpand bool, keywords []string, headingNumbers map[string]string, err error) {
+func GetDocInBox(startID, endID, id string, index int, query string, queryTypes, querySubTypes map[string]bool, queryMethod, mode int, size int, isBacklink bool, originalRefBlockIDs map[string]string, highlight, includeDocInfo bool, boxID string) (
+ blockCount int, dom, parentID, parent2ID, rootID, typ string, eof, scroll bool, boxIDOut, docPath string, isBacklinkExpand bool, keywords []string, headingNumbers map[string]string, docInfo *BlockInfo, err error) {
//os.MkdirAll("pprof", 0755)
//cpuProfile, _ := os.Create("pprof/GetDoc")
//pprof.StartCPUProfile(cpuProfile)
@@ -661,6 +661,9 @@ func GetDocInBox(startID, endID, id string, index int, query string, queryTypes,
err = ErrBlockNotFound
return
}
+ if includeDocInfo {
+ docInfo = getDocInfoByTree(tree.Root.ID, tree)
+ }
luteEngine := NewLute()
node := treenode.GetNodeInTree(tree, id)
diff --git a/kernel/model/file_test.go b/kernel/model/file_test.go
index 679d2001a8..22756dcf65 100644
--- a/kernel/model/file_test.go
+++ b/kernel/model/file_test.go
@@ -95,6 +95,37 @@ func setupFileOperationTest(t *testing.T) *fileOperationTestFixture {
}
}
+func TestGetDocOptionallyIncludesDocInfo(t *testing.T) {
+ fixture := setupFileOperationTest(t)
+ Conf.Editor = conf.NewEditor()
+ Conf.Export = conf.NewExport()
+ expected, err := GetDocInfo(fixture.sourceID)
+ if nil != err {
+ t.Fatalf("get standalone document info failed: %v", err)
+ }
+
+ _, _, _, _, rootID, _, _, _, boxID, _, _, _, _, embedded, err := GetDoc(
+ "", "", fixture.sourceID, 0, "", nil, nil, 0, 0, 102400, false, map[string]string{}, true, true)
+ if nil != err {
+ t.Fatalf("get document with embedded info failed: %v", err)
+ }
+ if rootID != fixture.sourceID || boxID != fixture.box.ID {
+ t.Fatalf("unexpected loaded document: root [%s], box [%s]", rootID, boxID)
+ }
+ if !reflect.DeepEqual(embedded, expected) {
+ t.Fatalf("embedded document info differs from standalone result:\nembedded: %#v\nstandalone: %#v", embedded, expected)
+ }
+
+ _, _, _, _, _, _, _, _, _, _, _, _, _, omitted, err := GetDoc(
+ "", "", fixture.sourceID, 0, "", nil, nil, 0, 0, 102400, false, map[string]string{}, true, false)
+ if nil != err {
+ t.Fatalf("get document without embedded info failed: %v", err)
+ }
+ if nil != omitted {
+ t.Fatalf("document info should be omitted unless requested: %#v", omitted)
+ }
+}
+
func TestRemoveDocRejectsInvalidPath(t *testing.T) {
fixture := setupFileOperationTest(t)