Skip to content

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

:bug: Fix frontend initialization race conditions https://github.com/siyuan-note/siyuan/issues/18431

Daniel044e49495e0d
diff --git a/app/src/boot/onGetConfig.ts b/app/src/boot/onGetConfig.ts
index b14e7a30b6..09b07487ec 100644
--- a/app/src/boot/onGetConfig.ts
+++ b/app/src/boot/onGetConfig.ts
@@ -58,22 +58,25 @@ export const onGetConfig = (isStart: boolean, app: App) => {
ensureUILayout();
initWindowEvent(app);
const snippetReady = renderSnippet(Constants.TIMEOUT_SNIPPET_LOAD);
- fetchPost("/api/system/getEmojiConf", {}, response => {
- window.siyuan.emojis = response.data as IEmoji[];
- snippetReady.then(() => {
- try {
- JSONToLayout(app, isStart);
- setTimeout(() => {
- adjustLayout();
- }); // 等待 dock 中 !this.pin 的 setTimeout
- /// #if !BROWSER
- sendGlobalShortcut(app);
- /// #endif
- openChangelog();
- } catch (e) {
- resetLayout();
- }
- openDesktopOnboarding(app);
+ const layoutReady = new Promise<void>((resolve) => {
+ fetchPost("/api/system/getEmojiConf", {}, response => {
+ window.siyuan.emojis = response.data as IEmoji[];
+ snippetReady.then(() => {
+ try {
+ JSONToLayout(app, isStart);
+ setTimeout(() => {
+ adjustLayout();
+ }); // 等待 dock 中 !this.pin 的 setTimeout
+ /// #if !BROWSER
+ sendGlobalShortcut(app);
+ /// #endif
+ openChangelog();
+ } catch (e) {
+ resetLayout();
+ }
+ openDesktopOnboarding(app);
+ resolve();
+ });
});
});
initBar(app);
@@ -118,6 +121,7 @@ export const onGetConfig = (isStart: boolean, app: App) => {
});
}, Constants.TIMEOUT_RESIZE);
});
+ return layoutReady;
};
export const initWindow = async (app: App) => {
diff --git a/app/src/index.ts b/app/src/index.ts
index 566974ea56..696152e459 100644
--- a/app/src/index.ts
+++ b/app/src/index.ts
@@ -258,6 +258,8 @@ export class App {
window.siyuan = {
zIndex: 10,
+ isReady: false,
+ notebooks: [],
reqIds: {},
backStack: [],
layout: {},
@@ -269,6 +271,7 @@ export class App {
ws: mainWs,
};
+ const notebookPromise = setNoteBook();
fetchPost("/api/system/getConf", {}, async (response) => {
addScriptSync(`${Constants.PROTYLE_CDN}/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}`, "protyleLuteScript");
addScript(`${Constants.PROTYLE_CDN}/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}`, "protyleWcHtmlScript");
@@ -276,6 +279,7 @@ export class App {
ensureUILayout();
window.siyuan.isPublish = response.data.isPublish;
setBodyHighlight();
+ await notebookPromise;
await loadPlugins(this);
getLocalStorage(() => {
fetchGet(`/appearance/langs/${window.siyuan.config.appearance.lang}.json?v=${Constants.SIYUAN_VERSION}`, (lauguages: IObject) => {
@@ -285,23 +289,23 @@ export class App {
fetchPost("/api/setting/getCloudUser", {}, async userResponse => {
window.siyuan.user = userResponse.data;
await ensureOnboarding();
- setNoteBook(() => {
- onGetConfig(response.data.start, this);
- onSetaccount();
- setTitle("", true);
- initMessage();
- /// #if BROWSER && !MOBILE
- if (!isInMobileApp() && !window.siyuan.config.readonly && !window.siyuan.isPublish && !isChromeBrowser()
- && window.siyuan.config.appearance.notifications?.browserCompatibility !== false) {
- showMessage(window.siyuan.languages.useChrome, 0, "error");
- }
- /// #endif
- });
+ await setNoteBook();
+ await onGetConfig(response.data.start, this);
+ onSetaccount();
+ setTitle("", true);
+ initMessage();
+ /// #if BROWSER && !MOBILE
+ if (!isInMobileApp() && !window.siyuan.config.readonly && !window.siyuan.isPublish && !isChromeBrowser()
+ && window.siyuan.config.appearance.notifications?.browserCompatibility !== false) {
+ showMessage(window.siyuan.languages.useChrome, 0, "error");
+ }
+ /// #endif
+ window.siyuan.isReady = true;
+ mainWs.flushMainMessages();
});
});
});
});
- setNoteBook();
initBlockPopover(this);
}
}
diff --git a/app/src/layout/Model.ts b/app/src/layout/Model.ts
index 01ea3be294..346ab9c06e 100644
--- a/app/src/layout/Model.ts
+++ b/app/src/layout/Model.ts
@@ -17,6 +17,10 @@ interface IConnectOptions {
export class Model {
public ws: WebSocket;
public reqId: number;
+ private mainMessageQueue: {
+ data: string,
+ callback: (data: IWebSocketData) => void
+ }[] = [];
public parent:
@@ -34,6 +38,21 @@ export class Model {
this.app = options.app;
}
+ private processWebSocketMessage(data: string, callback: (data: IWebSocketData) => void) {
+ callback.call(this, processMessage(JSON.parse(data)));
+ }
+
+ public flushMainMessages() {
+ const messages = this.mainMessageQueue.splice(0);
+ messages.forEach((message) => {
+ try {
+ this.processWebSocketMessage(message.data, message.callback);
+ } catch (error) {
+ console.error("Failed to process queued WebSocket message:", error);
+ }
+ });
+ }
+
public connect(options: IConnectOptions) {
const websocketURL = `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.host}/ws`;
const ws = new WebSocket(`${websocketURL}?app=${Constants.SIYUAN_APPID}&id=${options.id}${options.type ? "&type=" + options.type : ""}`);
@@ -54,11 +73,19 @@ export class Model {
}
};
ws.onmessage = (event) => {
- if (options.msgCallback &&
- // 等待 config 加载完成才接受推送 https://github.com/siyuan-note/siyuan/issues/17508
- window.siyuan.config) {
- const data = processMessage(JSON.parse(event.data));
- options.msgCallback.call(this, data);
+ if (!options.msgCallback) {
+ return;
+ }
+ if (options.type === "main" && !window.siyuan.isReady) {
+ this.mainMessageQueue.push({
+ data: event.data,
+ callback: options.msgCallback,
+ });
+ return;
+ }
+ // 非主 WebSocket 在界面初始化后创建,保留配置保护以避免异常连接提前处理消息。
+ if (window.siyuan.config) {
+ this.processWebSocketMessage(event.data, options.msgCallback);
}
};
ws.onclose = (ev) => {
diff --git a/app/src/layout/util.ts b/app/src/layout/util.ts
index 8967252166..f6ef447ee0 100644
--- a/app/src/layout/util.ts
+++ b/app/src/layout/util.ts
@@ -136,6 +136,9 @@ export const resetLayout = () => {
let saveCount = 0;
export const saveLayout = () => {
+ if (!window.siyuan.layout?.layout) {
+ return;
+ }
const breakObj = {};
let layoutJSON: any = {};
if (isWindow()) {
diff --git a/app/src/mobile/index.ts b/app/src/mobile/index.ts
index e8ebfe0ff9..0b676a1ad6 100644
--- a/app/src/mobile/index.ts
+++ b/app/src/mobile/index.ts
@@ -78,6 +78,7 @@ class App {
window.siyuan = {
zIndex: 10,
+ isReady: false,
notebooks: [],
reqIds: {},
backStack: [],
@@ -98,8 +99,9 @@ class App {
};
// 不能使用 touchstart,否则会被 event.stopImmediatePropagation() 阻塞
window.addEventListener("click", (event: MouseEvent & { target: HTMLElement }) => {
- if (!window.siyuan.menus.menu.element.contains(event.target) && !hasClosestByAttribute(event.target, "data-menu", "true")) {
- window.siyuan.menus.menu.remove();
+ const menu = window.siyuan.menus?.menu;
+ if (menu && !menu.element.contains(event.target) && !hasClosestByAttribute(event.target, "data-menu", "true")) {
+ menu.remove();
}
const copyElement = hasTopClosestByClassName(event.target, "protyle-action__copy");
if (copyElement) {
@@ -151,10 +153,14 @@ class App {
};
}
window.addEventListener("beforeunload", () => {
- saveScroll(window.siyuan.mobile.editor.protyle);
+ if (window.siyuan.mobile.editor?.protyle) {
+ saveScroll(window.siyuan.mobile.editor.protyle);
+ }
}, false);
window.addEventListener("pagehide", () => {
- saveScroll(window.siyuan.mobile.editor.protyle);
+ if (window.siyuan.mobile.editor?.protyle) {
+ saveScroll(window.siyuan.mobile.editor.protyle);
+ }
}, false);
// 判断手机横竖屏状态
window.matchMedia("(orientation:portrait)").addEventListener("change", () => {
@@ -193,16 +199,18 @@ class App {
fetchPost("/api/setting/getCloudUser", {}, async userResponse => {
window.siyuan.user = userResponse.data;
await ensureOnboarding();
- fetchPost("/api/system/getEmojiConf", {}, emojiResponse => {
+ fetchPost("/api/system/getEmojiConf", {}, async emojiResponse => {
window.siyuan.emojis = emojiResponse.data as IEmoji[];
- setNoteBook(() => {
- initFramework(this, confResponse.data.start).then(() => {
- initRightMenu(this);
- openChangelog();
- }).catch((error) => {
- console.error("Failed to initialize mobile framework:", error);
- });
- });
+ await setNoteBook();
+ try {
+ await initFramework(this, confResponse.data.start);
+ initRightMenu(this);
+ openChangelog();
+ window.siyuan.isReady = true;
+ mainWs.flushMainMessages();
+ } catch (error) {
+ console.error("Failed to initialize mobile framework:", error);
+ }
});
});
});
@@ -268,7 +276,7 @@ window.reconnectWebSocket = () => {
tryPing(window.siyuan.mobile.popEditor?.protyle.ws);
};
window.lockscreenByMode = () => {
- if (window.siyuan.config.system.lockScreenMode === 1) {
+ if (window.siyuan.config?.system.lockScreenMode === 1) {
lockScreen(siyuanApp);
}
};
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index 89873e0b54..05a84173b2 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -549,6 +549,7 @@ interface INotebook {
interface ISiyuan {
zIndex: number
+ isReady?: boolean
storage?: {
[key: string]: any
},
diff --git a/app/src/util/pathName.ts b/app/src/util/pathName.ts
index 0f51aef5f6..911aab1332 100644
--- a/app/src/util/pathName.ts
+++ b/app/src/util/pathName.ts
@@ -763,12 +763,14 @@ export const getOpenNotebookCount = () => {
};
export const setNoteBook = (cb?: (notebook: INotebook[]) => void, flashcard = false) => {
- fetchPost("/api/notebook/lsNotebooks", {
+ return fetchPost("/api/notebook/lsNotebooks", {
flashcard
}, (response) => {
if (!flashcard) {
window.siyuan.notebooks = response.data.notebooks;
- window.siyuan.config.fileTree.boxDocEnabled = response.data.boxDocEnabled;
+ if (window.siyuan.config?.fileTree) {
+ window.siyuan.config.fileTree.boxDocEnabled = response.data.boxDocEnabled;
+ }
}
if (cb) {
cb(response.data.notebooks);
diff --git a/app/src/window/index.ts b/app/src/window/index.ts
index c7405e34ff..09a477cdb5 100644
--- a/app/src/window/index.ts
+++ b/app/src/window/index.ts
@@ -178,6 +178,8 @@ class App {
window.siyuan = {
zIndex: 10,
+ isReady: false,
+ notebooks: [],
reqIds: {},
backStack: [],
layout: {},
@@ -188,6 +190,7 @@ class App {
altIsPressed: false,
ws: mainWs,
};
+ const notebookPromise = setNoteBook();
fetchPost("/api/system/getConf", {}, async (response) => {
addScriptSync(`${Constants.PROTYLE_CDN}/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}`, "protyleLuteScript");
addScript(`${Constants.PROTYLE_CDN}/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}`, "protyleWcHtmlScript");
@@ -195,21 +198,23 @@ class App {
ensureUILayout();
setBodyHighlight();
window.siyuan.isPublish = response.data.isPublish;
+ await notebookPromise;
await loadPlugins(this);
getLocalStorage(() => {
fetchGet(`/appearance/langs/${window.siyuan.config.appearance.lang}.json?v=${Constants.SIYUAN_VERSION}`, (lauguages: IObject) => {
window.siyuan.languages = lauguages;
window.siyuan.menus = new Menus(this);
- fetchPost("/api/setting/getCloudUser", {}, userResponse => {
+ fetchPost("/api/setting/getCloudUser", {}, async userResponse => {
window.siyuan.user = userResponse.data;
- init(this);
+ await init(this);
setTitle("", true);
initMessage();
+ window.siyuan.isReady = true;
+ mainWs.flushMainMessages();
});
});
});
});
- setNoteBook();
initBlockPopover(this);
}
}
diff --git a/app/src/window/init.ts b/app/src/window/init.ts
index dceb03b5ab..33f65a3878 100644
--- a/app/src/window/init.ts
+++ b/app/src/window/init.ts
@@ -29,35 +29,38 @@ export const init = (app: App) => {
position
});
initWindowEvent(app);
- fetchPost("/api/system/getEmojiConf", {}, response => {
- window.siyuan.emojis = response.data as IEmoji[];
+ const layoutReady = new Promise<void>((resolve) => {
+ fetchPost("/api/system/getEmojiConf", {}, response => {
+ window.siyuan.emojis = response.data as IEmoji[];
- const layout = JSON.parse(sessionStorage.getItem("layout") || "{}");
- if (layout.layout) {
- JSONToCenter(app, layout.layout);
- window.siyuan.layout.centerLayout = window.siyuan.layout.layout;
- } else {
- const tabsJSON = JSON.parse(getSearch("json"));
- tabsJSON[tabsJSON.length - 1].active = true;
- JSONToCenter(app, {
- direction: "lr",
- resize: "lr",
- size: "auto",
- type: "center",
- instance: "Layout",
- children: [{
- instance: "Wnd",
- children: tabsJSON
- }]
- });
- window.siyuan.layout.centerLayout = window.siyuan.layout.layout;
- adjustLayout(window.siyuan.layout.centerLayout);
- }
- afterLayout(app);
- // 等待 dock 面板动画结束
- setTimeout(() => {
- setTabPosition();
- }, Constants.TIMEOUT_TRANSITION);
+ const layout = JSON.parse(sessionStorage.getItem("layout") || "{}");
+ if (layout.layout) {
+ JSONToCenter(app, layout.layout);
+ window.siyuan.layout.centerLayout = window.siyuan.layout.layout;
+ } else {
+ const tabsJSON = JSON.parse(getSearch("json"));
+ tabsJSON[tabsJSON.length - 1].active = true;
+ JSONToCenter(app, {
+ direction: "lr",
+ resize: "lr",
+ size: "auto",
+ type: "center",
+ instance: "Layout",
+ children: [{
+ instance: "Wnd",
+ children: tabsJSON
+ }]
+ });
+ window.siyuan.layout.centerLayout = window.siyuan.layout.layout;
+ adjustLayout(window.siyuan.layout.centerLayout);
+ }
+ afterLayout(app);
+ // 等待 dock 面板动画结束
+ setTimeout(() => {
+ setTabPosition();
+ }, Constants.TIMEOUT_TRANSITION);
+ resolve();
+ });
});
initStatus(true);
initWindow(app);
@@ -89,6 +92,7 @@ export const init = (app: App) => {
});
}, Constants.TIMEOUT_RESIZE);
});
+ return layoutReady;
};
const afterLayout = (app: App) => {