feat: add HTTP server and port argument support for electron

This commit is contained in:
2026-03-19 14:49:25 +08:00
parent 7c7b9ea1c6
commit 2f24b0f522
2 changed files with 134 additions and 6 deletions

43
.trae/documents/plan.md Normal file
View File

@@ -0,0 +1,43 @@
# 修复 XCSDD 启动缓慢及黑屏问题的实施计划
## 1. 问题分析 (Current State Analysis)
根据您提供的启动日志导致软件启动缓慢5秒黑屏以及输出大量错误信息的原因主要有以下三点
1. **生产环境默认开启了开发者工具 (DevTools)**
- **日志现象**5秒后输出的错误`Unknown VE context`, `Request Autofill.enable failed` 等)全部来自 `devtools://devtools/...`
- **原因**:在 `electron/main.mjs` 中,只要不是 headless 模式,就会自动执行 `mainWindow.webContents.openDevTools()`。在打包后的生产环境(`win-unpacked`)中,加载庞大的 DevTools 会严重阻塞主线程和渲染进程,是导致 5 秒黑屏的**最主要原因**。
2. **GPU 缓存目录权限冲突**
- **日志现象**`Unable to move the cache: 拒绝访问。 (0x5)``Gpu Cache Creation failed: -2`
- **原因**Chromium 尝试在当前执行目录(或被锁定的临时目录)写入 GPU 着色器磁盘缓存,但没有写入权限。这会导致 GPU 进程初始化时发生等待/重试,进一步拖慢了启动速度。考虑到您的项目使用了 `@react-three/fiber`3D 蓝图查看器),我们**不能**直接禁用硬件加速,否则 3D 渲染会极其卡顿。最优解是禁用 GPU 的**磁盘缓存**。
3. **窗口显示时机过早 (未应用 ready-to-show)**
- **原因**:目前 `new BrowserWindow({ show: !args.headless })` 会在窗口创建的瞬间直接显示。此时 React 尚未完成 DOM 渲染,因此用户会先看到一个纯黑/纯白的背景,直到页面加载完毕。
## 2. 拟定修改方案 (Proposed Changes)
我们将修改 `electron/main.mjs` 文件来彻底解决上述问题:
### 修改 1按环境按需加载 DevTools
-`devTools: true` 修改为 `devTools: !app.isPackaged`
- 将自动打开控制台的逻辑修改为:`if (!app.isPackaged && !args.headless)`
- **目的**:确保在您打包发布后,不会再加载开发者工具,从而消除 5 秒的额外加载时间和相关报错。
### 修改 2优雅地显示窗口 (防止黑屏闪烁)
- 窗口初始化时强制设置为 `show: false`
- 监听 `ready-to-show` 事件,当渲染进程准备好第一帧画面时,再调用 `mainWindow.show()`
- **目的**:用户点击图标后,应用会在后台默默渲染,等画面准备好后瞬间弹出,实现“秒开”的视觉体验。
### 修改 3禁用 GPU 磁盘缓存以消除权限报错
-`app.whenReady()` 之前,添加代码:`app.commandLine.appendSwitch('disable-gpu-shader-disk-cache');`
- **目的**:解决 `Unable to move the cache (0x5)` 报错,同时保留 WebGL 硬件加速,确保 3D 蓝图流畅运行。
## 3. 假设与决策 (Assumptions & Decisions)
- **假设**:您的项目 `app.isPackaged``win-unpacked` 下能正确识别为生产环境(通常为 `true`)。
- **决策**:不使用 `app.disableHardwareAcceleration()`,以保证 `three.js` 的性能。
## 4. 验证步骤 (Verification steps)
1. 实施计划后,重新运行 `npm run electron:build` 并在 `win-unpacked` 目录中启动 `XCSDD.exe`
2. 观察控制台输出,确认不再有 `cache_util_win.cc``devtools` 相关的 ERROR。
3. 观察启动过程,确认应用在短暂等待后直接显示完整的 UI不再有长达 5 秒的黑屏阶段。

View File

@@ -2,11 +2,15 @@ import { app, BrowserWindow, ipcMain } from 'electron';
import path from 'path'; import path from 'path';
import { fileURLToPath } from 'url'; import { fileURLToPath } from 'url';
import fs from 'fs'; import fs from 'fs';
import http from 'http';
app.commandLine.appendSwitch('disable-gpu-shader-disk-cache');
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename); const __dirname = path.dirname(__filename);
let mainWindow = null; let mainWindow = null;
let httpServer = null;
const LOG_FILE = app.isPackaged const LOG_FILE = app.isPackaged
? path.join(app.getPath('userData'), 'electron.log') ? path.join(app.getPath('userData'), 'electron.log')
: path.join(__dirname, '..', 'electron.log'); : path.join(__dirname, '..', 'electron.log');
@@ -20,7 +24,7 @@ function log(...args) {
} }
function parseArgs() { function parseArgs() {
const args = { docs: null, headless: false }; const args = { docs: null, headless: false, port: null };
const docsIndex = process.argv.indexOf('--docs'); const docsIndex = process.argv.indexOf('--docs');
if (docsIndex !== -1 && process.argv[docsIndex + 1]) { if (docsIndex !== -1 && process.argv[docsIndex + 1]) {
args.docs = process.argv[docsIndex + 1]; args.docs = process.argv[docsIndex + 1];
@@ -28,6 +32,10 @@ function parseArgs() {
if (process.argv.includes('--headless')) { if (process.argv.includes('--headless')) {
args.headless = true; args.headless = true;
} }
const portIndex = process.argv.indexOf('--port');
if (portIndex !== -1 && process.argv[portIndex + 1]) {
args.port = parseInt(process.argv[portIndex + 1], 10);
}
return args; return args;
} }
@@ -40,6 +48,64 @@ function getIndexPath() {
return path.join(__dirname, '..', 'dist', 'index.html'); return path.join(__dirname, '..', 'dist', 'index.html');
} }
function startHttpServer(port) {
const distPath = app.isPackaged
? path.join(__dirname, '..', 'dist')
: path.join(__dirname, '..', 'dist');
const mimeTypes = {
'.html': 'text/html',
'.js': 'application/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.eot': 'application/vnd.ms-fontobject',
};
const server = http.createServer((req, res) => {
let filePath = path.join(distPath, req.url === '/' ? 'index.html' : req.url);
const ext = path.extname(filePath);
const contentType = mimeTypes[ext] || 'application/octet-stream';
fs.readFile(filePath, (err, content) => {
if (err) {
if (err.code === 'ENOENT') {
fs.readFile(path.join(distPath, 'index.html'), (err2, content2) => {
if (err2) {
res.writeHead(404);
res.end('Not Found');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content2);
}
});
} else {
res.writeHead(500);
res.end('Server Error');
}
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content);
}
});
});
server.listen(port, '0.0.0.0', () => {
log(`HTTP server running at http://localhost:${port}/`);
});
return server;
}
function createWindow() { function createWindow() {
const indexPath = getIndexPath(); const indexPath = getIndexPath();
log('Creating window, indexPath:', indexPath); log('Creating window, indexPath:', indexPath);
@@ -48,18 +114,28 @@ function createWindow() {
log('index.html exists:', fs.existsSync(indexPath)); log('index.html exists:', fs.existsSync(indexPath));
mainWindow = new BrowserWindow({ mainWindow = new BrowserWindow({
show: !args.headless, show: false,
width: 1200, width: 1200,
height: 800, height: 800,
webPreferences: { webPreferences: {
preload: path.join(__dirname, 'preload.cjs'), preload: path.join(__dirname, 'preload.cjs'),
contextIsolation: true, contextIsolation: true,
nodeIntegration: false, nodeIntegration: false,
devTools: true, devTools: !app.isPackaged,
}, },
}); });
mainWindow.loadFile(indexPath); if (args.port) {
mainWindow.loadURL(`http://localhost:${args.port}/`);
} else {
mainWindow.loadFile(indexPath);
}
mainWindow.on('ready-to-show', () => {
if (!args.headless) {
mainWindow.show();
}
});
mainWindow.webContents.on('did-fail-load', (_event, errorCode, errorDesc) => { mainWindow.webContents.on('did-fail-load', (_event, errorCode, errorDesc) => {
log('FAIL LOAD:', errorCode, errorDesc); log('FAIL LOAD:', errorCode, errorDesc);
@@ -69,7 +145,7 @@ function createWindow() {
log('Page finished loading'); log('Page finished loading');
}); });
if (!args.headless) { if (!app.isPackaged && !args.headless) {
mainWindow.webContents.openDevTools(); mainWindow.webContents.openDevTools();
} }
@@ -119,7 +195,13 @@ ipcMain.on('renderer-log', (_event, level, ...args) => {
}); });
app.whenReady().then(() => { app.whenReady().then(() => {
log('App ready, creating window'); log('App ready, parsing args:', args);
if (args.port) {
log('Starting HTTP server on port', args.port);
httpServer = startHttpServer(args.port);
}
createWindow(); createWindow();
app.on('activate', () => { app.on('activate', () => {
@@ -133,6 +215,9 @@ app.whenReady().then(() => {
}); });
app.on('window-all-closed', () => { app.on('window-all-closed', () => {
if (httpServer) {
httpServer.close();
}
if (process.platform !== 'darwin') { if (process.platform !== 'darwin') {
app.quit(); app.quit();
} }