An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:zap: Improve startup timing and mobile sync handling
Danieldf22f306780e
diff --git a/app/electron/main.js b/app/electron/main.jsindex 62e08f85ea..322bdd93a1 100644--- a/app/electron/main.js+++ b/app/electron/main.js@@ -81,6 +81,27 @@ const spellcheckContexts = new Map();const pendingSpellcheckRequests = new Map();const pendingNativeContextMenuRequests = new Map();const spellcheckContextMenuContents = new Set();+const startupStartedAt = Date.now();+let startupPreviousAt = startupStartedAt;+const startupStages = new Set();+const allowedFrontendStartupStages = new Set([+ "frontend-entry",+ "lute-ready",+ "plugins-ready",+ "layout-ready",+ "frontend-ready",+]);+const markStartup = (stage) => {+ if (startupStages.has(stage)) {+ return;+ }+ startupStages.add(stage);++ const now = Date.now();+ writeLog("startup timing [container=electron, stage=" + stage + ", elapsed=" + (now - startupStartedAt) ++ "ms, delta=" + (now - startupPreviousAt) + "ms]");+ startupPreviousAt = now;+};const normalizeClipboardText = (text) => text.replace(/\r\n?/g, "\n");const isOpenAsHidden = function () {return 1 === workspaces.length && openAsHidden;@@ -199,6 +220,12 @@ const bindSpellcheckContextMenu = (contents) => {remote.initialize();+ipcMain.on("siyuan-startup-stage", (event, stage) => {+ if (allowedFrontendStartupStages.has(stage)) {+ markStartup(stage);+ }+});+// Electron 相关文件夹名称改为 `SiYuan-Electron` https://github.com/siyuan-note/siyuan/issues/3349// getPath("userData") 会创建空的 SiYuan 目录,改为 app.getPath("appData")app.setPath("userData", path.join(app.getPath("appData"), app.getName() + "-Electron"));@@ -236,6 +263,7 @@ app.commandLine.appendSwitch("disable-features", "AutoupgradeMixedContent");// Support set Chromium command line arguments on the desktop https://github.com/siyuan-note/siyuan/issues/9696writeLog("app is packaged [" + app.isPackaged + "], command line args [" + process.argv.join(", ") + "]");+markStartup("electron-main-loaded");let argStart = 1;if (!app.isPackaged) {argStart = 2;@@ -932,6 +960,7 @@ const initMainWindow = (currentKernelPort = kernelPort) => {writeLog("initMainWindow: app not ready, skipping");return;}+ markStartup("main-window-init-started");// 恢复主窗体状态let oldWindowState = {};@@ -1026,6 +1055,7 @@ const initMainWindow = (currentKernelPort = kernelPort) => {titleBarStyle: "hidden",icon: path.join(appDir, "stage", "icon-large.png"),});+ markStartup("main-window-created");remote.enable(currentWindow.webContents);bindSpellcheckContextMenu(currentWindow.webContents);@@ -1041,6 +1071,7 @@ const initMainWindow = (currentKernelPort = kernelPort) => {// pending(既不 resolve 也不 reject),会导致 loadURL 永不执行,主窗口卡在启动页无法显示。// 这里无论 setProxy 是否完成,最多等待 5 秒后强制加载主界面。const loadMainURL = () => {+ markStartup("frontend-load-requested");currentWindow.loadURL(getServer(currentKernelPort) + "/stage/build/app/?v=" + Date.now());};net.fetch(getServer(currentKernelPort) + "/api/system/getNetwork", {method: "POST"}).then((response) => {@@ -1102,6 +1133,7 @@ const initMainWindow = (currentKernelPort = kernelPort) => {});currentWindow.webContents.on("did-finish-load", () => {+ markStartup("frontend-page-loaded");let siyuanOpenURL = process.argv.find((arg) => arg.startsWith("siyuan://"));if (siyuanOpenURL) {if (currentWindow.isMinimized()) {@@ -1164,6 +1196,7 @@ const initMainWindow = (currentKernelPort = kernelPort) => {}}, 60000);ipcMain.once("siyuan-ready-to-show", () => {+ markStartup("window-show-requested");clearTimeout(readyToShowTimeout); // 正常收到信号则取消超时兜底if (isOpenAsHidden()) {currentWindow.minimize();@@ -1194,6 +1227,7 @@ const showWindow = (wnd) => {const initKernel = (workspace, port, lang, safeMode) => {return new Promise(async (resolve) => {+ markStartup("kernel-init-started");bootWindow = new BrowserWindow({show: false,width: Math.floor(screen.getPrimaryDisplay().size.width / 2),@@ -1216,6 +1250,7 @@ const initKernel = (workspace, port, lang, safeMode) => {} else {bootWindow.show();}+ markStartup("boot-window-visible");const kernelName = "win32" === process.platform ? "SiYuan-Kernel.exe" : "SiYuan-Kernel";const kernelPath = path.join(appDir, "kernel", kernelName);@@ -1344,6 +1379,7 @@ const initKernel = (workspace, port, lang, safeMode) => {if (0 === apiData.code) {writeLog("got kernel version [" + apiData.data + "]");+ markStartup("kernel-http-serving");if (!isDevEnv && apiData.data !== appVer) {writeLog(`kernel [${apiData.data}] is running, shutdown it now and then start kernel [${appVer}]`);requestKernelExit(currentKernelPort);@@ -1371,8 +1407,10 @@ const initKernel = (workspace, port, lang, safeMode) => {const progressResult = await net.fetch(getServer(currentKernelPort) + "/api/system/bootProgress");const progressData = await progressResult.json();if (progressData.data.progress >= 100) {+ markStartup("kernel-ready");// 内核完成后等待动画快进收尾(200ms)再进入主窗口await sleep(200);+ markStartup("boot-animation-finished");resolve(currentKernelPort);progressing = true;} else {@@ -1395,6 +1433,7 @@ const initKernel = (workspace, port, lang, safeMode) => {};app.whenReady().then(() => {+ markStartup("electron-ready");// Trust self-signed TLS certificates for local HTTPS serversession.defaultSession.setCertificateVerifyProc((request, callback) => {if (request.hostname === "127.0.0.1" || request.hostname === "localhost") {diff --git a/app/src/constants.ts b/app/src/constants.tsindex 66947f61bf..91f166aae7 100644--- a/app/src/constants.ts+++ b/app/src/constants.ts@@ -42,6 +42,7 @@ export abstract class Constants {public static readonly SIYUAN_HOTKEY: string = "siyuan-hotkey";public static readonly SIYUAN_INIT: string = "siyuan-init";public static readonly SIYUAN_READY_TO_SHOW: string = "siyuan-ready-to-show";+ public static readonly SIYUAN_STARTUP_STAGE: string = "siyuan-startup-stage";public static readonly SIYUAN_SEND_WINDOWS: string = "siyuan-send-windows"; // 主窗口和各新窗口之间的通信public static readonly SIYUAN_SAVE_CLOSE: string = "siyuan-save-close";public static readonly SIYUAN_AUTO_LAUNCH: string = "siyuan-auto-launch";diff --git a/app/src/index.ts b/app/src/index.tsindex 2f37c79dd0..d337744a6c 100644--- a/app/src/index.ts+++ b/app/src/index.ts@@ -54,6 +54,17 @@ import {setTitle} from "./util/processTitle";import {ensureUILayout} from "./util/ensureUILayout";import {applyEntryVisibility} from "./config/entryVisibility/runtime";+type TStartupStage = "frontend-entry" | "lute-ready" | "plugins-ready" | "layout-ready" | "frontend-ready";++const reportStartupStage = (stage: TStartupStage) => {+ window.performance.mark(`siyuan-startup-${stage}`);+ /// #if !BROWSER+ ipcRenderer.send(Constants.SIYUAN_STARTUP_STAGE, stage);+ /// #endif+};++reportStartupStage("frontend-entry");+export class App {public plugins: import("./plugin").Plugin[] = [];public appId: string;@@ -273,6 +284,7 @@ export class App {const notebookPromise = setNoteBook();fetchPost("/api/system/getConf", {}, async (response) => {addScriptSync(`${Constants.PROTYLE_CDN}/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}`, "protyleLuteScript");+ reportStartupStage("lute-ready");addScript(`${Constants.PROTYLE_CDN}/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}`, "protyleWcHtmlScript");window.siyuan.config = response.data.conf;ensureUILayout();@@ -280,6 +292,7 @@ export class App {setBodyHighlight();await notebookPromise;await loadPlugins(this);+ reportStartupStage("plugins-ready");getLocalStorage(() => {fetchGet(`/appearance/langs/${window.siyuan.config.appearance.lang}.json?v=${Constants.SIYUAN_VERSION}`, (lauguages: IObject) => {window.siyuan.languages = lauguages;@@ -290,6 +303,7 @@ export class App {await ensureOnboarding();await setNoteBook();await onGetConfig(response.data.start, this);+ reportStartupStage("layout-ready");onSetaccount();setTitle("", true);initMessage();@@ -300,6 +314,7 @@ export class App {}/// #endifwindow.siyuan.isReady = true;+ reportStartupStage("frontend-ready");mainWs.flushMainMessages();});});diff --git a/app/src/mobile/index.ts b/app/src/mobile/index.tsindex ccb004c4bb..ea42a36449 100644--- a/app/src/mobile/index.ts+++ b/app/src/mobile/index.ts@@ -56,6 +56,15 @@ import {appearanceConfigApi} from "../config/tabs/appearanceRuntime";import {openByMobile} from "../editor/openLink";import {initHarmonyTextSelectionMenu} from "../util/harmonyTextSelectionMenu";+type TStartupStage = "frontend-entry" | "lute-ready" | "plugins-ready" | "loading-removed" | "frontend-ready";++const reportStartupStage = (stage: TStartupStage) => {+ window.performance.mark(`siyuan-startup-${stage}`);+ window.JSAndroid?.reportStartupStage?.(stage);+};++reportStartupStage("frontend-entry");+class App {public plugins: import("../plugin").Plugin[] = [];public appId: string;@@ -170,11 +179,13 @@ class App {});fetchPost("/api/system/getConf", {}, async (confResponse) => {addScriptSync(`${Constants.PROTYLE_CDN}/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}`, "protyleLuteScript");+ reportStartupStage("lute-ready");addScript(`${Constants.PROTYLE_CDN}/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}`, "protyleWcHtmlScript");window.siyuan.config = confResponse.data.conf;window.siyuan.isPublish = confResponse.data.isPublish;correctHotkey(siyuanApp);await loadPlugins(this);+ reportStartupStage("plugins-ready");getLocalStorage(() => {fetchGet(`/appearance/langs/${window.siyuan.config.appearance.lang}.json?v=${Constants.SIYUAN_VERSION}`, (lauguages: IObject) => {window.siyuan.languages = lauguages;@@ -183,7 +194,7 @@ class App {bootSync();appearanceConfigApi.apply(window.siyuan.config.appearance);initMessage();- initAssets();+ initAssets(() => reportStartupStage("loading-removed"));if (!isInMobileApp()) {if (isChromeBrowser()) {document.querySelector('meta[name="viewport"]').setAttribute("content", "width=device-width, height=device-height, interactive-widget=resizes-content, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, viewport-fit=cover");@@ -208,6 +219,7 @@ class App {initRightMenu(this);openChangelog();window.siyuan.isReady = true;+ reportStartupStage("frontend-ready");mainWs.flushMainMessages();} catch (error) {console.error("Failed to initialize mobile framework:", error);diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex e4a5f48c1c..f266906fbc 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -324,6 +324,7 @@ interface Window {sendNotification(channel: string, title: string, body: string, delayInSeconds: number): numbercancelNotification(id: number): voidlogInputEvent?(details: string): void+ reportStartupStage?(stage: string): void};JSHarmony: {openAuthURL(url: string): voiddiff --git a/app/src/util/assets.ts b/app/src/util/assets.tsindex ae5d2bc217..45f9463db1 100644--- a/app/src/util/assets.ts+++ b/app/src/util/assets.ts@@ -227,12 +227,15 @@ export const loadAssets = (data: Config.IAppearance) => {});};-export const initAssets = () => {+export const initAssets = (onLoadingRemoved?: () => void) => {const loadingElement = document.getElementById("loading");if (loadingElement) {setTimeout(() => {loadingElement.remove();+ onLoadingRemoved?.();}, 160);+ } else {+ onLoadingRemoved?.();}updateMobileTheme(window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", event => {diff --git a/kernel/api/sync.go b/kernel/api/sync.goindex 948614c912..4bddc3898f 100644--- a/kernel/api/sync.go+++ b/kernel/api/sync.go@@ -468,6 +468,10 @@ func performSync(c *gin.Context) {return}if mobileSwitch {+ if !util.IsBooted() {+ logging.LogDebugf("skip mobile switch sync while kernel is booting")+ return+ }if nil == model.Conf.GetUser() || !model.Conf.Sync.Enabled {return}diff --git a/kernel/cli/cmd/serve.go b/kernel/cli/cmd/serve.goindex bf75d56f2e..ea121fc084 100644--- a/kernel/cli/cmd/serve.go+++ b/kernel/cli/cmd/serve.go@@ -58,27 +58,40 @@ var serveCmd = &cobra.Command{return nil // bypass root's init — BootWithFlags() handles it},Run: func(cmd *cobra.Command, args []string) {+ startupTimer := util.NewStartupTimer()// --workspace 优先取 serve 自己的(rootCmd 的 persistent flag),兜底环境变量与默认值交给 util.BootWithFlags 内部处理(与原 Boot() 行为一致)。ws := workspacePathutil.BootWithFlags(ws, serveWdPath, servePort, serveReadOnly, serveAccessAuthCode, serveLang, serveMode, serveSSL, serveAttachUI, serveSafeMode, serveEnablePprof)+ startupTimer.Mark("workspace-ready")model.InitJwtKey()model.InitConf()+ startupTimer.Mark("configuration-ready")go server.Serve(false, model.Conf.CookieKey)+ startupTimer.Mark("http-server-requested")model.InitAppearance()+ startupTimer.Mark("appearance-ready")sql.InitDatabase(false)+ startupTimer.Mark("main-database-ready")sql.InitHistoryDatabase(false)+ startupTimer.Mark("history-database-ready")sql.InitAssetContentDatabase(false)+ startupTimer.Mark("asset-database-ready")sql.SetCaseSensitive(model.Conf.Search.CaseSensitive)sql.SetIndexAssetPath(model.Conf.Search.IndexAssetPath)model.BootSyncData()+ startupTimer.Mark("boot-sync-finished")model.InitBoxes()+ startupTimer.Mark("notebooks-ready")model.LoadFlashcards()+ startupTimer.Mark("flashcards-ready")util.LoadAssetsTexts()+ startupTimer.Mark("asset-texts-ready")util.SetBooted()+ startupTimer.Mark("kernel-ready")util.PushClearAllMsg()job.StartCron()diff --git a/kernel/harmony/kernel.go b/kernel/harmony/kernel.goindex c30422bb08..3fe7bcadb2 100644--- a/kernel/harmony/kernel.go+++ b/kernel/harmony/kernel.go@@ -126,28 +126,41 @@ func StartKernelFast(container, appDir, workspaceBaseDir, localIPs *C.char) {//export StartKernelfunc StartKernel(container, appDir, workspaceBaseDir, timezoneID, localIPs, lang, osVer *C.char) {+ startupTimer := util.NewStartupTimer()SetTimezone(container, appDir, timezoneID)util.Mode = "prod"util.MobileOSVer = C.GoString(osVer)util.SetLocalIPs(strings.Split(C.GoString(localIPs), ","))util.BootMobile(C.GoString(container), C.GoString(appDir), C.GoString(workspaceBaseDir), C.GoString(lang))+ startupTimer.Mark("workspace-ready")model.InitConf()+ startupTimer.Mark("configuration-ready")go server.Serve(false, model.Conf.CookieKey)+ startupTimer.Mark("http-server-requested")go func() {model.InitAppearance()+ startupTimer.Mark("appearance-ready")sql.InitDatabase(false)+ startupTimer.Mark("main-database-ready")sql.InitHistoryDatabase(false)+ startupTimer.Mark("history-database-ready")sql.InitAssetContentDatabase(false)+ startupTimer.Mark("asset-database-ready")sql.SetCaseSensitive(model.Conf.Search.CaseSensitive)sql.SetIndexAssetPath(model.Conf.Search.IndexAssetPath)model.BootSyncData()+ startupTimer.Mark("boot-sync-finished")model.InitBoxes()+ startupTimer.Mark("notebooks-ready")model.LoadFlashcards()+ startupTimer.Mark("flashcards-ready")util.LoadAssetsTexts()+ startupTimer.Mark("asset-texts-ready")util.SetBooted()+ startupTimer.Mark("kernel-ready")util.PushClearAllMsg()job.StartCron()diff --git a/kernel/mobile/kernel.go b/kernel/mobile/kernel.goindex 926ae64571..f598e46492 100644--- a/kernel/mobile/kernel.go+++ b/kernel/mobile/kernel.go@@ -267,28 +267,41 @@ func StartKernelFast(container, appDir, workspaceBaseDir, localIPs string) {}func StartKernel(container, appDir, workspaceBaseDir, timezoneID, localIPs, lang, osVer string) {+ startupTimer := util.NewStartupTimer()SetTimezone(container, appDir, timezoneID)util.Mode = "prod"util.MobileOSVer = osVerutil.SetLocalIPs(strings.Split(localIPs, ","))util.BootMobile(container, appDir, workspaceBaseDir, lang)+ startupTimer.Mark("workspace-ready")model.InitConf()+ startupTimer.Mark("configuration-ready")go server.Serve(false, model.Conf.CookieKey)+ startupTimer.Mark("http-server-requested")go func() {model.InitAppearance()+ startupTimer.Mark("appearance-ready")sql.InitDatabase(false)+ startupTimer.Mark("main-database-ready")sql.InitHistoryDatabase(false)+ startupTimer.Mark("history-database-ready")sql.InitAssetContentDatabase(false)+ startupTimer.Mark("asset-database-ready")sql.SetCaseSensitive(model.Conf.Search.CaseSensitive)sql.SetIndexAssetPath(model.Conf.Search.IndexAssetPath)model.BootSyncData()+ startupTimer.Mark("boot-sync-finished")model.InitBoxes()+ startupTimer.Mark("notebooks-ready")model.LoadFlashcards()+ startupTimer.Mark("flashcards-ready")util.LoadAssetsTexts()+ startupTimer.Mark("asset-texts-ready")util.SetBooted()+ startupTimer.Mark("kernel-ready")util.PushClearAllMsg()job.StartCron()diff --git a/kernel/util/working.go b/kernel/util/working.goindex 54f8bb1859..1839b583ee 100644--- a/kernel/util/working.go+++ b/kernel/util/working.go@@ -30,6 +30,7 @@ import ("strings""sync""sync/atomic"+ "time""github.com/88250/go-humanize""github.com/88250/gulu"@@ -76,6 +77,32 @@ var (SafeMode = false // 是否以安全模式启动:禁用代码片段、插件、自定义主题与图标)+// StartupTimer 记录启动阶段的累计耗时和阶段耗时。+type StartupTimer struct {+ lock sync.Mutex+ startedAt time.Time+ previousAt time.Time+}++func NewStartupTimer() *StartupTimer {+ now := time.Now()+ return &StartupTimer{startedAt: now, previousAt: now}+}++func (timer *StartupTimer) Mark(stage string) {+ if nil == timer {+ return+ }++ timer.lock.Lock()+ defer timer.lock.Unlock()++ now := time.Now()+ logging.LogInfof("startup timing [container=%s, stage=%s, elapsed=%dms, delta=%dms]", Container, stage,+ now.Sub(timer.startedAt).Milliseconds(), now.Sub(timer.previousAt).Milliseconds())+ timer.previousAt = now+}+// If a commandline parameter is empty, fallback to the env var.//// "empty" means the parameter is not set or set to an empty string.