forked from op7418/CodePilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
779 lines (688 loc) · 24.1 KB
/
main.ts
File metadata and controls
779 lines (688 loc) · 24.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
import { app, BrowserWindow, nativeImage, dialog, session, utilityProcess, ipcMain } from 'electron';
import path from 'path';
import { execFileSync, spawn, ChildProcess } from 'child_process';
import fs from 'fs';
import net from 'net';
import os from 'os';
let mainWindow: BrowserWindow | null = null;
let serverProcess: Electron.UtilityProcess | null = null;
let serverPort: number | null = null;
let serverErrors: string[] = [];
let serverExited = false;
let serverExitCode: number | null = null;
let userShellEnv: Record<string, string> = {};
let isQuitting = false;
// --- Install orchestrator ---
interface InstallStep {
id: string;
label: string;
status: 'pending' | 'running' | 'success' | 'failed' | 'skipped';
error?: string;
}
interface InstallState {
status: 'idle' | 'running' | 'success' | 'failed' | 'cancelled';
currentStep: string | null;
steps: InstallStep[];
logs: string[];
}
let installState: InstallState = {
status: 'idle',
currentStep: null,
steps: [],
logs: [],
};
let installProcess: ChildProcess | null = null;
const isDev = !app.isPackaged;
/**
* Gracefully shut down the server process.
* Sends kill() (SIGTERM) first, waits up to 3s for exit,
* then force-kills via process.kill(pid, SIGKILL) as fallback.
*/
function killServer(): Promise<void> {
return new Promise((resolve) => {
if (!serverProcess) {
resolve();
return;
}
const pid = serverProcess.pid;
const timeout = setTimeout(() => {
// Force kill — on Windows use taskkill to kill the entire process tree
if (pid) {
try {
if (process.platform === 'win32') {
spawn('taskkill', ['/T', '/F', '/PID', String(pid)], { stdio: 'ignore' });
} else {
process.kill(pid, 'SIGKILL');
}
} catch { /* already dead */ }
}
serverProcess = null;
resolve();
}, 3000);
serverProcess.on('exit', () => {
clearTimeout(timeout);
serverProcess = null;
resolve();
});
// On Windows, SIGTERM is not supported — use taskkill to kill the tree
if (process.platform === 'win32' && pid) {
spawn('taskkill', ['/T', '/F', '/PID', String(pid)], { stdio: 'ignore' });
} else {
serverProcess.kill();
}
});
}
/**
* Verify that better_sqlite3.node in standalone resources is compatible
* with this Electron runtime's ABI. If it was built for a different
* Node.js ABI (e.g. system Node v22 ABI 127 vs Electron's ABI 143),
* show a clear error instead of a cryptic MODULE_NOT_FOUND crash.
*/
function checkNativeModuleABI(): void {
if (isDev) return; // Skip in dev mode
const standaloneDir = path.join(process.resourcesPath, 'standalone');
// Find better_sqlite3.node recursively
function findNodeFile(dir: string): string | null {
if (!fs.existsSync(dir)) return null;
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
const found = findNodeFile(fullPath);
if (found) return found;
} else if (entry.name === 'better_sqlite3.node') {
return fullPath;
}
}
return null;
}
const nodeFile = findNodeFile(path.join(standaloneDir, 'node_modules'));
if (!nodeFile) {
console.warn('[ABI check] better_sqlite3.node not found in standalone resources');
return;
}
try {
// Attempt to load the native module to verify ABI compatibility
process.dlopen({ exports: {} } as NodeModule, nodeFile);
console.log(`[ABI check] better_sqlite3.node ABI is compatible (${nodeFile})`);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
if (msg.includes('NODE_MODULE_VERSION')) {
console.error(`[ABI check] ABI mismatch detected: ${msg}`);
dialog.showErrorBox(
'CodePilot - Native Module ABI Mismatch',
`The bundled better-sqlite3 native module was compiled for a different Node.js version.\n\n` +
`${msg}\n\n` +
`This usually means the build process did not correctly recompile native modules for Electron.\n` +
`Please rebuild the application or report this issue.`
);
app.quit();
} else {
// Other load errors (missing dependencies, etc.) -- log but don't block
console.warn(`[ABI check] Could not verify better_sqlite3.node: ${msg}`);
}
}
}
/**
* Read the user's full shell environment by running a login shell.
* When Electron is launched from Dock/Finder (macOS) or desktop launcher
* (Linux), process.env is very limited and won't include vars from
* .zshrc/.bashrc (e.g. API keys, nvm PATH).
*/
function loadUserShellEnv(): Record<string, string> {
// Windows GUI apps inherit the full user environment
if (process.platform === 'win32') {
return {};
}
try {
const shell = process.env.SHELL || '/bin/zsh';
const result = execFileSync(shell, ['-ilc', 'env'], {
timeout: 5000,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
});
const env: Record<string, string> = {};
for (const line of result.split('\n')) {
const idx = line.indexOf('=');
if (idx > 0) {
const key = line.slice(0, idx);
const value = line.slice(idx + 1);
env[key] = value;
}
}
console.log(`Loaded ${Object.keys(env).length} env vars from user shell`);
return env;
} catch (err) {
console.warn('Failed to load user shell env:', err);
return {};
}
}
/**
* Build an expanded PATH that includes common locations for node, npm globals,
* claude, nvm, homebrew, etc. Shared by the server launcher and install orchestrator.
*/
function getExpandedShellPath(): string {
const home = os.homedir();
const shellPath = userShellEnv.PATH || process.env.PATH || '';
const sep = path.delimiter;
if (process.platform === 'win32') {
const appData = process.env.APPDATA || path.join(home, 'AppData', 'Roaming');
const localAppData = process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
const winExtra = [
path.join(appData, 'npm'),
path.join(localAppData, 'npm'),
path.join(home, '.npm-global', 'bin'),
path.join(home, '.local', 'bin'),
path.join(home, '.claude', 'bin'),
];
const allParts = [shellPath, ...winExtra].join(sep).split(sep).filter(Boolean);
return [...new Set(allParts)].join(sep);
} else {
const basePath = `/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin`;
const raw = `${basePath}:${home}/.npm-global/bin:${home}/.local/bin:${home}/.claude/bin:${shellPath}`;
const allParts = raw.split(':').filter(Boolean);
return [...new Set(allParts)].join(':');
}
}
function getPort(): Promise<number> {
return new Promise((resolve, reject) => {
const server = net.createServer();
server.unref();
server.on('error', reject);
server.listen(0, '127.0.0.1', () => {
const addr = server.address();
if (addr && typeof addr === 'object') {
const port = addr.port;
server.close(() => resolve(port));
} else {
server.close(() => reject(new Error('Failed to get port')));
}
});
});
}
async function waitForServer(port: number, timeout = 30000): Promise<void> {
const start = Date.now();
while (Date.now() - start < timeout) {
// If the server process already exited, fail fast
if (serverExited) {
throw new Error(
`Server process exited with code ${serverExitCode}.\n\n${serverErrors.join('\n')}`
);
}
try {
await new Promise<void>((resolve, reject) => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const req = require('http').get(`http://127.0.0.1:${port}/api/health`, (res: { statusCode?: number }) => {
if (res.statusCode === 200) resolve();
else reject(new Error(`Status ${res.statusCode}`));
});
req.on('error', reject);
req.setTimeout(1000, () => {
req.destroy();
reject(new Error('timeout'));
});
});
return;
} catch {
await new Promise(r => setTimeout(r, 200));
}
}
throw new Error(
`Server startup timeout after ${timeout / 1000}s.\n\n${serverErrors.length > 0 ? 'Server output:\n' + serverErrors.slice(-10).join('\n') : 'No server output captured.'}`
);
}
function startServer(port: number): Electron.UtilityProcess {
const standaloneDir = path.join(process.resourcesPath, 'standalone');
const serverPath = path.join(standaloneDir, 'server.js');
console.log(`Server path: ${serverPath}`);
console.log(`Standalone dir: ${standaloneDir}`);
serverErrors = [];
serverExited = false;
serverExitCode = null;
const home = os.homedir();
const constructedPath = getExpandedShellPath();
const env: Record<string, string> = {
...userShellEnv,
...(process.env as Record<string, string>),
// Ensure user shell env vars override (especially API keys)
...userShellEnv,
PORT: String(port),
HOSTNAME: '127.0.0.1',
CLAUDE_GUI_DATA_DIR: path.join(home, '.codepilot'),
HOME: home,
USERPROFILE: home,
PATH: constructedPath,
};
// Use Electron's utilityProcess to run the server in a child process
// without spawning a separate Dock icon on macOS.
const child = utilityProcess.fork(serverPath, [], {
env,
cwd: standaloneDir,
stdio: 'pipe',
serviceName: 'codepilot-server',
});
child.stdout?.on('data', (data: Buffer) => {
const msg = data.toString().trim();
console.log(`[server] ${msg}`);
serverErrors.push(msg);
});
child.stderr?.on('data', (data: Buffer) => {
const msg = data.toString().trim();
console.error(`[server:err] ${msg}`);
serverErrors.push(msg);
});
child.on('exit', (code) => {
console.log(`Server process exited with code ${code}`);
serverExited = true;
serverExitCode = code;
serverProcess = null;
});
return child;
}
function getIconPath(): string {
if (isDev) {
return path.join(process.cwd(), 'build', 'icon.png');
}
if (process.platform === 'win32') {
return path.join(process.resourcesPath, 'icon.ico');
}
if (process.platform === 'linux') {
return path.join(process.resourcesPath, 'icon.png');
}
return path.join(process.resourcesPath, 'icon.icns');
}
function createWindow(port: number) {
const windowOptions: Electron.BrowserWindowConstructorOptions = {
width: 1280,
height: 860,
minWidth: 800,
minHeight: 600,
icon: getIconPath(),
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
},
};
if (process.platform === 'darwin') {
windowOptions.titleBarStyle = 'hiddenInset';
} else if (process.platform === 'win32') {
windowOptions.titleBarStyle = 'hidden';
windowOptions.titleBarOverlay = {
color: '#00000000',
symbolColor: '#888888',
height: 44,
};
}
mainWindow = new BrowserWindow(windowOptions);
mainWindow.loadURL(`http://127.0.0.1:${port}`);
if (isDev) {
mainWindow.webContents.openDevTools();
}
mainWindow.on('closed', () => {
mainWindow = null;
});
}
app.whenReady().then(async () => {
// Load user's full shell environment (API keys, PATH, etc.)
userShellEnv = loadUserShellEnv();
// Verify native module ABI compatibility before starting the server
checkNativeModuleABI();
// Clear cache on version upgrade
const currentVersion = app.getVersion();
const versionFilePath = path.join(app.getPath('userData'), 'last-version.txt');
try {
const lastVersion = fs.existsSync(versionFilePath)
? fs.readFileSync(versionFilePath, 'utf-8').trim()
: '';
if (lastVersion && lastVersion !== currentVersion) {
console.log(`Version changed from ${lastVersion} to ${currentVersion}, clearing cache...`);
await session.defaultSession.clearCache();
await session.defaultSession.clearStorageData({
storages: ['cachestorage', 'serviceworkers'],
});
console.log('Cache cleared successfully');
}
fs.writeFileSync(versionFilePath, currentVersion, 'utf-8');
} catch (err) {
console.warn('Failed to check/clear version cache:', err);
}
// Set macOS Dock icon
if (process.platform === 'darwin' && app.dock) {
const iconPath = getIconPath();
app.dock.setIcon(nativeImage.createFromPath(iconPath));
}
// --- Install wizard IPC handlers ---
ipcMain.handle('install:check-prerequisites', async () => {
const expandedPath = getExpandedShellPath();
const execEnv = { ...process.env, ...userShellEnv, PATH: expandedPath };
const execOpts = { timeout: 5000, encoding: 'utf-8' as const, env: execEnv };
let hasNode = false;
let nodeVersion: string | undefined;
try {
const result = execFileSync('node', ['--version'], execOpts);
nodeVersion = result.trim();
hasNode = true;
} catch {
// node not found
}
let hasClaude = false;
let claudeVersion: string | undefined;
try {
const claudeOpts = process.platform === 'win32'
? { ...execOpts, shell: true }
: execOpts;
const result = execFileSync('claude', ['--version'], claudeOpts);
claudeVersion = result.trim();
hasClaude = true;
} catch {
// claude not found
}
return { hasNode, nodeVersion, hasClaude, claudeVersion };
});
ipcMain.handle('install:start', (_event: Electron.IpcMainInvokeEvent, options?: { includeNode?: boolean }) => {
if (installState.status === 'running') {
throw new Error('Installation is already running');
}
const needsNode = options?.includeNode === true;
// Reset state
const steps: InstallStep[] = [];
if (needsNode) {
steps.push({ id: 'install-node', label: 'Installing Node.js', status: 'pending' });
}
steps.push(
{ id: 'check-node', label: 'Checking Node.js', status: 'pending' },
{ id: 'install-claude', label: 'Installing Claude Code', status: 'pending' },
{ id: 'verify', label: 'Verifying installation', status: 'pending' },
);
installState = {
status: 'running',
currentStep: null,
steps,
logs: [],
};
const expandedPath = getExpandedShellPath();
const execEnv: Record<string, string> = {
...userShellEnv,
...(process.env as Record<string, string>),
...userShellEnv,
PATH: expandedPath,
};
function sendProgress() {
mainWindow?.webContents.send('install:progress', installState);
}
function setStep(id: string, status: InstallStep['status'], error?: string) {
const step = installState.steps.find(s => s.id === id);
if (step) {
step.status = status;
step.error = error;
}
installState.currentStep = id;
sendProgress();
}
function addLog(line: string) {
installState.logs.push(line);
sendProgress();
}
// Run the installation sequence asynchronously
(async () => {
try {
// Step 0 (optional): Install Node.js via package manager
if (needsNode) {
setStep('install-node', 'running');
const nodeInstalled = await new Promise<boolean>((resolve) => {
const isWin = process.platform === 'win32';
const isMac = process.platform === 'darwin';
let cmd: string;
let args: string[];
if (isMac) {
// Try Homebrew
const brewPaths = ['/opt/homebrew/bin/brew', '/usr/local/bin/brew'];
const brewPath = brewPaths.find(p => fs.existsSync(p));
if (!brewPath) {
addLog('Homebrew not found. Cannot auto-install Node.js on macOS without Homebrew.');
resolve(false);
return;
}
cmd = brewPath;
args = ['install', 'node'];
addLog(`Running: ${brewPath} install node`);
} else if (isWin) {
cmd = 'winget';
args = ['install', '-e', '--id', 'OpenJS.NodeJS.LTS', '--accept-source-agreements', '--accept-package-agreements'];
addLog('Running: winget install -e --id OpenJS.NodeJS.LTS');
} else {
// Linux — no universal package manager
addLog('Auto-install of Node.js is not supported on this platform.');
resolve(false);
return;
}
const child = spawn(cmd, args, {
env: execEnv,
shell: isWin,
stdio: ['ignore', 'pipe', 'pipe'],
});
installProcess = child;
child.stdout?.on('data', (data: Buffer) => {
for (const line of data.toString().split('\n').filter(Boolean)) {
addLog(line);
}
});
child.stderr?.on('data', (data: Buffer) => {
for (const line of data.toString().split('\n').filter(Boolean)) {
addLog(line);
}
});
child.on('error', (err) => {
addLog(`Error: ${err.message}`);
resolve(false);
});
child.on('close', (code) => {
installProcess = null;
resolve(code === 0);
});
});
if (installState.status === 'cancelled') {
setStep('install-node', 'failed', 'Cancelled');
return;
}
if (!nodeInstalled) {
setStep('install-node', 'failed', 'Could not auto-install Node.js.');
installState.status = 'failed';
sendProgress();
return;
}
setStep('install-node', 'success');
addLog('Node.js installation completed.');
}
// Step 1: Check node
setStep('check-node', 'running');
try {
const nodeResult = execFileSync('node', ['--version'], {
timeout: 5000,
encoding: 'utf-8',
env: execEnv,
});
addLog(`Node.js found: ${nodeResult.trim()}`);
setStep('check-node', 'success');
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
addLog(`Node.js not found: ${msg}`);
setStep('check-node', 'failed', 'Node.js is not installed. Please install Node.js first.');
installState.status = 'failed';
sendProgress();
return;
}
// Step 2: Install Claude Code via npm
setStep('install-claude', 'running');
addLog('Running: npm install -g @anthropic-ai/claude-code');
const npmInstallSuccess = await new Promise<boolean>((resolve) => {
const isWin = process.platform === 'win32';
const npmCmd = isWin ? 'npm.cmd' : 'npm';
const child = spawn(npmCmd, ['install', '-g', '@anthropic-ai/claude-code'], {
env: execEnv,
shell: isWin,
stdio: ['ignore', 'pipe', 'pipe'],
});
installProcess = child;
child.stdout?.on('data', (data: Buffer) => {
const lines = data.toString().split('\n').filter(Boolean);
for (const line of lines) {
addLog(line);
}
});
child.stderr?.on('data', (data: Buffer) => {
const lines = data.toString().split('\n').filter(Boolean);
for (const line of lines) {
addLog(line);
}
});
child.on('error', (err) => {
addLog(`npm error: ${err.message}`);
resolve(false);
});
child.on('close', (code) => {
installProcess = null;
if (code === 0) {
addLog('npm install completed successfully');
resolve(true);
} else if (installState.status === 'cancelled') {
addLog('Installation was cancelled');
resolve(false);
} else {
addLog(`npm install exited with code ${code}`);
resolve(false);
}
});
});
if (installState.status === 'cancelled') {
setStep('install-claude', 'failed', 'Cancelled');
return;
}
if (!npmInstallSuccess) {
setStep('install-claude', 'failed', 'npm install failed. Check logs for details.');
installState.status = 'failed';
sendProgress();
return;
}
setStep('install-claude', 'success');
// Step 3: Verify claude is available
setStep('verify', 'running');
try {
const verifyOpts = process.platform === 'win32'
? { timeout: 5000, encoding: 'utf-8' as const, env: execEnv, shell: true }
: { timeout: 5000, encoding: 'utf-8' as const, env: execEnv };
const claudeResult = execFileSync('claude', ['--version'], verifyOpts);
addLog(`Claude Code installed: ${claudeResult.trim()}`);
setStep('verify', 'success');
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
addLog(`Verification failed: ${msg}`);
setStep('verify', 'failed', 'Claude Code was installed but could not be verified.');
installState.status = 'failed';
sendProgress();
return;
}
installState.status = 'success';
installState.currentStep = null;
sendProgress();
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
addLog(`Unexpected error: ${msg}`);
installState.status = 'failed';
sendProgress();
}
})();
});
ipcMain.handle('install:cancel', () => {
if (installState.status !== 'running') {
return;
}
installState.status = 'cancelled';
installState.logs.push('Cancelling installation...');
if (installProcess) {
const pid = installProcess.pid;
try {
if (process.platform === 'win32' && pid) {
// Windows: kill entire process tree (shell: true spawns cmd.exe which
// spawns npm/winget — child.kill() only kills the shell, not the tree)
spawn('taskkill', ['/T', '/F', '/PID', String(pid)], { stdio: 'ignore' });
} else {
installProcess.kill();
}
} catch {
// already dead
}
installProcess = null;
installState.logs.push('Installation process terminated.');
}
mainWindow?.webContents.send('install:progress', installState);
});
ipcMain.handle('install:get-logs', () => {
return installState.logs;
});
// --- End install wizard IPC handlers ---
try {
let port: number;
if (isDev) {
port = 3000;
console.log(`Dev mode: connecting to http://127.0.0.1:${port}`);
} else {
port = await getPort();
console.log(`Starting server on port ${port}...`);
serverProcess = startServer(port);
await waitForServer(port);
console.log('Server is ready');
}
serverPort = port;
createWindow(port);
} catch (err) {
console.error('Failed to start:', err);
dialog.showErrorBox(
'CodePilot - Failed to Start',
`The internal server could not start.\n\n${err instanceof Error ? err.message : String(err)}\n\nPlease try restarting the application.`
);
app.quit();
}
});
app.on('window-all-closed', async () => {
await killServer();
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', async () => {
if (BrowserWindow.getAllWindows().length === 0) {
try {
if (!isDev && !serverProcess) {
const port = await getPort();
serverProcess = startServer(port);
await waitForServer(port);
serverPort = port;
}
createWindow(serverPort || 3000);
} catch (err) {
console.error('Failed to restart server:', err);
}
}
});
app.on('before-quit', async (e) => {
// Kill any running install process (tree-kill on Windows)
if (installProcess) {
const pid = installProcess.pid;
try {
if (process.platform === 'win32' && pid) {
spawn('taskkill', ['/T', '/F', '/PID', String(pid)], { stdio: 'ignore' });
} else {
installProcess.kill();
}
} catch { /* already dead */ }
installProcess = null;
}
if (serverProcess && !isQuitting) {
isQuitting = true;
e.preventDefault();
await killServer();
app.quit();
}
});