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: Show the main window after startup loading https://github.com/siyuan-note/siyuan/issues/20870
Daniel22e4e48c71f5
diff --git a/app/electron/bootWindow.test.js b/app/electron/bootWindow.test.jsindex 08e17c344f..1e923d8411 100644--- a/app/electron/bootWindow.test.js+++ b/app/electron/bootWindow.test.js@@ -146,6 +146,7 @@ const mainWindowSetup = () => {constructor() {super();this.webContents = Object.assign(new EventEmitter(), {id: ++windowId,+ send: (...args) => { this.messages = [...(this.messages || []), args]; },session: {webRequest: {onBeforeSendHeaders() {}, onHeadersReceived() {}}}});}isDestroyed() { return !!this.destroyed; }@@ -161,7 +162,8 @@ const mainWindowSetup = () => {fs: {readFileSync: () => "{}"}, windowStatePath: "state.json", path, appDir: "app", appVer: "3.8.6",screen: {getPrimaryDisplay: () => ({size: {width: 1000}, workAreaSize: {height: 800}})},BrowserWindow: Window, remote: {enable() {}}, bindSpellcheckContextMenu() {}, bindTopBarContextMenu() {},- rememberWindowKernelTarget() {}, windowNavigate() {}, writeLog() {}, process: {platform: "win32"},+ getTitleBarOverlayOptions: require("./windowControlsOverlay").getTitleBarOverlayOptions,+ rememberWindowKernelTarget() {}, windowNavigate() {}, writeLog() {}, process: {platform: "win32", argv: []},net: {fetch: () => new Promise(() => {})}, getServer: port => "https://127.0.0.1:" + port,setStartupApplicationMenu() {}, isOpenAsHidden: () => false, ipcMain,setTimeout: callback => { const key = {}; timers.set(key, callback); return key; },@@ -215,6 +217,43 @@ test("main window timeout and closure clean up their own boot windows and readinassert.equal(timers.size, 0);});+test("deep-link startup waits for the interface before showing the window and forwarding the link", () => {+ const {context, ipcMain, Window} = mainWindowSetup();+ const boot = new Window();+ context.localKernelStartups.set("workspace", {window: boot, workspace: "workspace", port: 6806});+ const url = "siyuan://blocks/20261025000000-abcdefg";+ context.process.argv.push(url);+ vm.runInContext("initMainWindow(6806)", context);+ const window = context.workspaces[0].browserWindow;+ window.webContents.emit("did-finish-load");+ assert.equal(window.shown, undefined);+ assert.equal(window.messages, undefined);+ assert.equal(boot.destroyed, undefined);+ ipcMain.emit("siyuan-ready-to-show", {sender: window.webContents});+ assert.equal(window.shown, true);+ assert.equal(boot.destroyed, true);+ assert.deepEqual(window.messages, [["siyuan-open-url", url]]);+});++test("ready hidden startup stays minimized and restores its saved maximized state later", () => {+ const {context, ipcMain, Window} = mainWindowSetup();+ const boot = new Window();+ context.isOpenAsHidden = () => true;+ context.fs.readFileSync = () => '{"isMaximized":true}';+ context.localKernelStartups.set("workspace", {window: boot, workspace: "workspace", port: 6806});+ vm.runInContext("initMainWindow(6806)", context);+ const window = context.workspaces[0].browserWindow;+ window.minimize = () => { window.minimized = true; };+ window.maximize = () => { window.maximized = true; };+ ipcMain.emit("siyuan-ready-to-show", {sender: window.webContents});+ assert.equal(window.minimized, true);+ assert.equal(window.shown, undefined);+ assert.equal(window.maximized, undefined);+ assert.equal(boot.destroyed, true);+ window.emit("restore");+ assert.equal(window.maximized, true);+});+test("system shutdown includes every booting workspace and closes only successful exits", async () => {for (const failedPort of [undefined, 6807]) {const {context, Window} = mainWindowSetup();diff --git a/app/electron/main.js b/app/electron/main.jsindex 73726150f4..8f11251851 100644--- a/app/electron/main.js+++ b/app/electron/main.js@@ -2371,17 +2371,6 @@ const initMainWindow = (kernel = kernelPort, remoteAuthenticated = true) => {}return;}- let siyuanOpenURL = process.argv.find((arg) => arg.startsWith("siyuan://"));- if (siyuanOpenURL) {- if (currentWindow.isMinimized()) {- currentWindow.restore();- }- currentWindow.show();- setTimeout(() => { // 等待界面js执行完毕- writeLog(siyuanOpenURL);- currentWindow.webContents.send("siyuan-open-url", siyuanOpenURL);- }, 2000);- }});if ("darwin" !== process.platform) {@@ -2410,10 +2399,17 @@ const initMainWindow = (kernel = kernelPort, remoteAuthenticated = true) => {workspaceDir: startup?.workspace,});if (startup) localKernelStartups.delete(getWorkspaceStartupKey(startup.workspace));- bindMainWindowReady(currentWindow, currentBootWindow, windowState);+ bindMainWindowReady(currentWindow, currentBootWindow, windowState, () => {+ if (kernelTarget.mode === "remote") return;+ const siyuanOpenURL = process.argv.find((arg) => arg.startsWith("siyuan://"));+ if (siyuanOpenURL) {+ writeLog(siyuanOpenURL);+ currentWindow.webContents.send("siyuan-open-url", siyuanOpenURL);+ }+ });};-const bindMainWindowReady = (currentWindow, currentBootWindow, windowState) => {+const bindMainWindowReady = (currentWindow, currentBootWindow, windowState, onReady) => {// loadURL 后设置超时兜底:前端 app bundle 加载或初始化异常导致 siyuan-ready-to-show 迟迟不发时,// 强制销毁 boot 窗口并显示主窗口,避免永久卡在启动页const readyToShowTimeout = setTimeout(() => {@@ -2452,6 +2448,7 @@ const bindMainWindowReady = (currentWindow, currentBootWindow, windowState) => {if (currentBootWindow && !currentBootWindow.isDestroyed()) {currentBootWindow.destroy();}+ onReady?.();};ipcMain.on("siyuan-ready-to-show", readyToShow);currentWindow.once("closed", () => {diff --git a/app/src/index.ts b/app/src/index.tsindex eee72de919..0b8f20bc22 100644--- a/app/src/index.ts+++ b/app/src/index.ts@@ -360,6 +360,10 @@ export class App {await ensureOnboarding();await setNoteBook();await initWindowWithLoading(() => onGetConfig(response.data.start, this), setTabPosition);+ /// #if !BROWSER+ // 加载遮罩移除后再显示主窗口,避免原生窗口按钮出现在启动界面上。+ ipcRenderer.send(Constants.SIYUAN_READY_TO_SHOW);+ /// #endifonSetaccount();setTitle("", true);initMessage();@@ -435,6 +439,4 @@ if (window.JSAndroid?.setWebViewFocusable) {} else if (window.JSHarmony?.setWebViewFocusable) {window.JSHarmony.setWebViewFocusable(true);}-/// #else-ipcRenderer.send(Constants.SIYUAN_READY_TO_SHOW);/// #endifdiff --git a/app/tests/mainWindowLoading.test.js b/app/tests/mainWindowLoading.test.jsindex ef937894e0..0dc92b2e20 100644--- a/app/tests/mainWindowLoading.test.js+++ b/app/tests/mainWindowLoading.test.js@@ -20,7 +20,8 @@ const runCase = async (sources, options) => {const snippets = deferred();const calls = [];const constants = {LOCAL_ZOOM: "zoom", SIZE_ZOOM: [{zoom: 1, position: {x: 8, y: 8}}],- SIYUAN_INIT: "init", TIMEOUT_SNIPPET_LOAD: 5000, TIMEOUT_TRANSITION: 300};+ SIYUAN_INIT: "init", SIYUAN_CMD: "cmd", SIYUAN_SAVE_CLOSE: "save-close",+ SIYUAN_READY_TO_SHOW: "siyuan-ready-to-show", TIMEOUT_SNIPPET_LOAD: 5000, TIMEOUT_TRANSITION: 300};window.siyuan = {languages: {loading: "Loading...", min: "Min", max: "Max", restore: "Restore", close: "Close"},storage: {zoom: 1}, dialogs: [], config: {appearance: {hideToolbar: options.fused, mode: options.dark ? 1 : 0},editor: {spellcheckLanguages: ["en-US"]}, system: {os: "windows"}}, menus: {menu: {element: document.createElement("div")}}};@@ -32,13 +33,25 @@ const runCase = async (sources, options) => {const getAllWnds = (_layout, wnds) => { if (wnd) wnds.push(wnd); };const functions = {isWindow: () => false, setToolbarLeftMac() {}};const tabs = load(sources.tabs, {"../util/functions": functions, "./getAll": {getAllWnds}});- const compatibility = {isMac: () => false, isWindows: () => true, applyPlatformClasses() {},+ const compatibility = {isMac: () => false, isWindows: () => true,+ applyPlatformClasses() { document.body.classList.add(options.native ? "body--windows" : "body--linux"); },initWindowOpenOverride() {}, initNativeDialogOverride() {}};- const electron = {ipcRenderer: {send() {}, on() {}, invoke: async (channel, data) => {+ const listeners = {};+ const electron = {ipcRenderer: {send(channel, data) {+ if (channel === constants.SIYUAN_READY_TO_SHOW) {+ assert.equal(document.getElementById("loading"), null, "native controls appear after the loading screen is removed");+ }+ if (channel === constants.SIYUAN_READY_TO_SHOW || channel === constants.SIYUAN_CMD) {+ require("electron").ipcRenderer.send(channel, data);+ }+ }, on(channel, callback) { listeners[channel] = callback; }, invoke: async (channel, data) => {if (channel === "init") return {};return data.cmd === "isFullScreen" ? state.promise : false;- }}, webFrame: {setZoomFactor() {}}};- const controls = load(sources.controls, {electron, "../constants": {Constants: constants}, "../util/functions": functions});+ }}, webFrame: require("electron").webFrame};+ const overlay = load(sources.overlay, {electron, "../constants": {Constants: constants},+ "../layout/util": {resizeTopBar() {}}});+ const controls = load(sources.controls, {electron, "../constants": {Constants: constants},+ "../util/functions": functions, "./windowControlsOverlay": overlay});const createLayout = () => {const element = document.createElement("div");element.className = "fn__flex-1 fn__flex";@@ -80,8 +93,15 @@ const runCase = async (sources, options) => {const {initWindowWithLoading} = load(sources.loading, {"../util/windowPaint": {waitForWindowPaint},"../constants": {Constants: constants}});let renderDone = false;+ let renderError;let done = false;- const result = initWindowWithLoading(() => onGetConfig(false, app).then(() => { renderDone = true; }), tabs.setTabPosition)+ const result = new Function("initWindowWithLoading", "onGetConfig", "response", "setTabPosition", "ipcRenderer", "Constants",+ "return (async function(){" + sources.ready[options.browser ? "browser" : "app"] + "}).call(this);")+ .call(app, initWindowWithLoading, (...args) => onGetConfig(...args).then(() => { renderDone = true; }, error => {+ renderError = error;+ throw error;+ }),+ {data: {start: false}}, tabs.setTabPosition, electron.ipcRenderer, constants).then(() => { done = true; });await new Promise(resolve => setTimeout(resolve, 40));window.releaseEmoji();@@ -92,12 +112,12 @@ const runCase = async (sources, options) => {assert.ok(document.getElementById("loading"), "loading is not removed after a fixed 160ms");gates[options.gate].resolve(false);await new Promise(resolve => setTimeout(resolve, 40));- assert.equal(renderDone, true);- if (!options.browser) {+ assert.equal(renderDone, true, renderError?.stack);+ if (!options.browser && !options.native) {const close = document.getElementById("closeWindow");const bounds = close.getBoundingClientRect();assert.ok(document.getElementById("loading").contains(document.elementFromPoint(bounds.x + bounds.width / 2,- bounds.y + bounds.height / 2)), "main loading covers native window buttons");+ bounds.y + bounds.height / 2)), "main loading covers self-drawn window buttons");}const modal = document.createElement("div");modal.className = "b3-dialog b3-dialog--open";@@ -127,7 +147,13 @@ const runCase = async (sources, options) => {assert.equal(wnd.element.classList.contains("layout__wnd--center"), options.fused);assert.equal(calls[0], "adjust");if (!options.browser) {- document.getElementById("closeWindow").click();+ if (options.native) {+ assert.equal(document.getElementById("closeWindow"), null);+ assert.ok(document.getElementById("windowControls").getBoundingClientRect().width > 0);+ listeners[constants.SIYUAN_SAVE_CLOSE]({}, true);+ } else {+ document.getElementById("closeWindow").click();+ }assert.equal(calls.at(-1), "close");}};@@ -135,7 +161,8 @@ const runCase = async (sources, options) => {};if (process.versions.electron && process.type === "browser") {- const {app, BrowserWindow} = require("electron");+ const {app, BrowserWindow, ipcMain} = require("electron");+ const {getTitleBarOverlayOptions, updateTitleBarOverlay} = require("../electron/windowControlsOverlay");const {createServer} = require("node:http");const {once} = require("node:events");app.on("window-all-closed", () => {});@@ -146,12 +173,30 @@ if (process.versions.electron && process.type === "browser") {const sources = {};const ts = require("typescript");for (const [key, file] of Object.entries({host: "boot/onGetConfig.ts", browserHost: "boot/onGetConfig.ts",- loading: "boot/loading.ts", paint: "util/windowPaint.ts", controls: "boot/windowControls.ts", tabs: "layout/tabUtil.ts"})) {+ loading: "boot/loading.ts", paint: "util/windowPaint.ts", controls: "boot/windowControls.ts",+ overlay: "boot/windowControlsOverlay.ts", tabs: "layout/tabUtil.ts"})) {const source = require("ifdef-loader/preprocessor").parse(fs.readFileSync(path.join(__dirname, "../src", file), "utf8"),{BROWSER: key === "browserHost", MOBILE: false}, false, true);sources[key] = ts.transpileModule(source, {compilerOptions: {module: ts.ModuleKind.CommonJS,target: ts.ScriptTarget.ES2022}}).outputText;}+ sources.ready = {};+ for (const [name, browser] of [["app", false], ["browser", true]]) {+ const source = require("ifdef-loader/preprocessor").parse(fs.readFileSync(path.join(__dirname, "../src/index.ts"), "utf8"),+ {BROWSER: browser, MOBILE: false}, false, true);+ const entry = ts.createSourceFile("index.ts", source, ts.ScriptTarget.Latest, true);+ assert.doesNotMatch(entry.statements.filter(statement => !ts.isClassDeclaration(statement))+ .map(statement => statement.getText(entry)).join("\n"), /ipcRenderer\.send\(Constants\.SIYUAN_READY_TO_SHOW/,+ "module evaluation must not show a window while its loading screen is present");+ sources.ready[name] = source.slice(source.indexOf("await initWindowWithLoading("), source.indexOf(" onSetaccount();"));+ }+ const main = fs.readFileSync(path.join(__dirname, "../electron/main.js"), "utf8");+ const bindReady = new Function("ipcMain", "isOpenAsHidden", "writeLog",+ main.slice(main.indexOf("const bindMainWindowReady ="), main.indexOf("const showWindow =")) + ";return bindMainWindowReady;")(+ ipcMain, () => false, () => {});+ ipcMain.on("cmd", (event, data) => {+ if (data?.cmd === "setTitleBarOverlay") updateTitleBarOverlay(BrowserWindow.fromWebContents(event.sender), data);+ });const css = require("sass").compile(path.join(__dirname, "../src/assets/scss/base.scss"), {logger: {warn() {}, debug() {}}}).css;const templates = Object.fromEntries(["app", "desktop"].map(name => [name,fs.readFileSync(path.join(__dirname, "../src/assets/template", name, "index.tpl"), "utf8")@@ -177,13 +222,24 @@ if (process.versions.electron && process.type === "browser") {});await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));let win;+ let boot;let code = 0;try {for (const options of [{fused: false, dark: false, browser: false, gate: "state"},{fused: true, dark: true, browser: false, gate: "appearance"},{fused: true, dark: false, browser: true, gate: "snippets"}]) {- win = new BrowserWindow({show: false, width: 640, height: 480,- webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});+ options.native = !options.browser && process.platform === "win32";+ boot = new BrowserWindow({show: false, frame: false});+ win = new BrowserWindow({show: false, width: 640, height: 480, frame: false,+ titleBarStyle: "hidden", titleBarOverlay: options.native ? getTitleBarOverlayOptions() : false,+ webPreferences: {nodeIntegration: true, contextIsolation: false, backgroundThrottling: false, offscreen: true}});+ win.webContents.on("console-message", event => {+ if (event.level === "error") console.error(event.message);+ });+ let shown = false;+ const show = win.show.bind(win);+ win.show = () => { shown = true; show(); };+ if (!options.browser) bindReady(win, boot, {});await win.loadURL(`http://127.0.0.1:${server.address().port}/stage/build/${options.browser ? "desktop" : "app"}/index.html`);// 渲染进程插入样式后,请求仍需异步到达主进程中的测试服务器。const themeRequested = once(server, "theme-request", {signal: AbortSignal.timeout(10000)});@@ -192,21 +248,33 @@ if (process.versions.electron && process.type === "browser") {themeRequested,]);assert.equal(pending.length, 1);+ assert.equal(win.isVisible(), false, "main window and native captions stay hidden during initialization");+ assert.equal(shown, false);+ assert.equal(boot.isDestroyed(), false, "the frameless boot window remains until the UI is ready");pending.pop().writeHead(200, {"Content-Type": "text/css"}).end(":root{--b3-font-size:14px;--b3-toolbar-left-mac:5px;--b3-body-background:#234567;--b3-theme-background:#234567;}");await new Promise(resolve => setTimeout(resolve, 300));assert.equal(await win.webContents.executeJavaScript('!!document.getElementById("loading")'), true);+ assert.equal(win.isVisible(), false, "appearance completion alone must not expose the loading screen captions");+ assert.equal(shown, false);await win.webContents.executeJavaScript("window.releaseDocument()");await win.webContents.executeJavaScript("window.mainLoadingResult");assert.equal(await win.webContents.executeJavaScript('!!document.getElementById("loading")'), false);assert.equal(await win.webContents.executeJavaScript('document.body.hasAttribute("aria-busy")'), false);await win.webContents.executeJavaScript("window.assertReady()");+ if (!options.browser) {+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(shown, true);+ assert.equal(boot.isDestroyed(), true);+ }win.destroy();+ if (!boot.isDestroyed()) boot.destroy();}console.log("Verified 3 main window loading cases");} catch (error) { console.error(error); code = 1; }finally {if (win && !win.isDestroyed()) win.destroy();+ if (boot && !boot.isDestroyed()) boot.destroy();pending.forEach(response => response.end());server.close();clearTimeout(watchdog);