interplane.Get Omega
Read in your language

MojoLlama

Archived Mojo/MAX quantizer and serving research repository (read-only history)

Brought by drakestapleton

branch main Branches Tags History

MojoLlama / desktop / main.js

1093 lines · 32347 bytes Raw Blame History
1/**
2 * MojoLlama Studio — Electron Main Process
3 *
4 * Manages the desktop window, server lifecycle, menu, tray,
5 * settings persistence, and IPC communication.
6 */
7
8const { app, BrowserWindow, Menu, Tray, nativeImage, dialog, Notification, ipcMain, shell } = require('electron');
9const path = require('path');
10const fs = require('fs');
11const { spawn, execSync } = require('child_process');
12const http = require('http');
13
14// ─── Constants ───────────────────────────────────────────────────────────────
15
16const APP_NAME = 'MojoLlama Studio';
17const STUDIO_URL = '/studio.html';
18const CHAT_URL = '/chat.html';
19const SETTINGS_FILE = 'mojollama-settings.json';
20const DEFAULT_PORT = 8080;
21const DEFAULT_LLAMA_PORT = 8081;
22const DEFAULT_THREADS = 32;
23const POLL_INTERVAL = 2000; // ms between server health checks
24const MAX_LOG_LINES = 5000; // ring buffer for server output
25
26// ─── State ──────────────────────────────────────────────────────────────────
27
28let mainWindow = null;
29let tray = null;
30let serverProcess = null;
31let serverState = 'stopped'; // 'stopped' | 'starting' | 'running' | 'stopping' | 'error'
32let settings = {};
33let logBuffer = []; // ring buffer of { timestamp, level, text }
34let logWindows = new Set(); // set of BrowserWindow IDs for log windows
35let settingsWindow = null;
36let healthInterval = null;
37let serverPort = DEFAULT_PORT;
38let projectRoot = null; // auto-detected from app location
39
40// ─── Path resolution ────────────────────────────────────────────────────────
41
42/**
43 * Determine the project root directory.
44 * When running in dev: use the parent of the desktop/ directory.
45 * When running in production: use process.resourcesPath.
46 */
47function getProjectRoot() {
48 if (projectRoot) return projectRoot;
49
50 if (process.env.ELECTRON_DEV || process.env.NODE_ENV === 'development') {
51 // In dev, the project root is the parent of desktop/
52 projectRoot = path.resolve(__dirname, '..');
53 } else {
54 // In production (packaged app), resources are at process.resourcesPath
55 projectRoot = process.resourcesPath;
56 }
57
58 // Verify the project root has server.py
59 const serverPy = path.join(projectRoot, 'server.py');
60 if (!fs.existsSync(serverPy)) {
61 // Try alternative: some packagings put it in extraResources
62 const altRoot = path.resolve(__dirname, '..');
63 if (fs.existsSync(path.join(altRoot, 'server.py'))) {
64 projectRoot = altRoot;
65 }
66 }
67
68 return projectRoot;
69}
70
71/**
72 * Find the server script to execute.
73 * Returns the command and args array.
74 */
75function getServerCommand(overrides = {}) {
76 const root = getProjectRoot();
77 const serverPy = path.join(root, 'src', 'mojollama', 'server_moe.py');
78 const port = overrides.port || settings.serverPort || DEFAULT_PORT;
79 const modelPath = overrides.modelPath || settings.modelPath || '';
80
81 // Use python3 to run server_moe.py (positional args: model_path port)
82 const pythonCmd = findPython();
83 const resolvedModel = modelPath && fs.existsSync(modelPath)
84 ? modelPath
85 : path.join(root, 'models', 'Qwen3-30B-A3B-Instruct-2507-Q4_K_M.gguf');
86 const args = [serverPy, resolvedModel, String(port)];
87
88 // Add threads override if set in settings
89 if (settings.threads && settings.threads !== DEFAULT_THREADS) {
90 // server_moe reads OMP_NUM_THREADS from env
91 }
92
93 // Check for debug mode in settings
94 if (settings.debug) {
95 args.push('--debug');
96 }
97
98 return { cmd: pythonCmd, args, port, serverPy };
99}
100
101/**
102 * Find a working Python 3 executable.
103 */
104function findPython() {
105 const candidates = ['python3', 'python'];
106 for (const cmd of candidates) {
107 try {
108 const out = execSync(`${cmd} --version`, { encoding: 'utf8' });
109 if (out.toLowerCase().includes('python 3')) {
110 return cmd;
111 }
112 } catch (e) {
113 continue;
114 }
115 }
116 return 'python3'; // fallback
117}
118
119// ─── Settings persistence ────────────────────────────────────────────────────
120
121function getSettingsPath() {
122 const userDataPath = app.getPath('userData');
123 return path.join(userDataPath, SETTINGS_FILE);
124}
125
126function loadSettings() {
127 const settingsPath = getSettingsPath();
128 const defaults = {
129 serverPort: DEFAULT_PORT,
130 llamaPort: DEFAULT_LLAMA_PORT,
131 modelPath: '',
132 threads: DEFAULT_THREADS,
133 engine: 'server_batch_moe',
134 autoStart: true,
135 debug: false,
136 minimizeToTray: true,
137 notifications: true,
138 };
139
140 try {
141 if (fs.existsSync(settingsPath)) {
142 const data = fs.readFileSync(settingsPath, 'utf8');
143 const parsed = JSON.parse(data);
144 settings = { ...defaults, ...parsed };
145 } else {
146 settings = { ...defaults };
147 }
148 } catch (err) {
149 console.error('Failed to load settings:', err);
150 settings = { ...defaults };
151 }
152
153 serverPort = settings.serverPort || DEFAULT_PORT;
154 return settings;
155}
156
157function saveSettings(newSettings) {
158 settings = { ...settings, ...newSettings };
159 serverPort = settings.serverPort || DEFAULT_PORT;
160 const settingsPath = getSettingsPath();
161
162 try {
163 fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2), 'utf8');
164 return true;
165 } catch (err) {
166 console.error('Failed to save settings:', err);
167 return false;
168 }
169}
170
171// ─── Logging ─────────────────────────────────────────────────────────────────
172
173function appendLog(level, text) {
174 const entry = {
175 timestamp: new Date().toISOString(),
176 level,
177 text,
178 };
179 logBuffer.push(entry);
180 if (logBuffer.length > MAX_LOG_LINES) {
181 logBuffer = logBuffer.slice(-MAX_LOG_LINES);
182 }
183
184 // Broadcast to all log windows
185 for (const winId of logWindows) {
186 try {
187 const win = BrowserWindow.fromId(winId);
188 if (win && !win.isDestroyed()) {
189 win.webContents.send('server-log', entry);
190 }
191 } catch (e) {
192 logWindows.delete(winId);
193 }
194 }
195
196 // Also send to main window if it exists
197 if (mainWindow && !mainWindow.isDestroyed()) {
198 mainWindow.webContents.send('server-log', entry);
199 }
200}
201
202function getLogBuffer() {
203 return logBuffer;
204}
205
206function clearLogBuffer() {
207 logBuffer = [];
208 for (const winId of logWindows) {
209 try {
210 const win = BrowserWindow.fromId(winId);
211 if (win && !win.isDestroyed()) {
212 win.webContents.send('log-cleared');
213 }
214 } catch (e) {
215 logWindows.delete(winId);
216 }
217 }
218 if (mainWindow && !mainWindow.isDestroyed()) {
219 mainWindow.webContents.send('log-cleared');
220 }
221}
222
223// ─── Server management ───────────────────────────────────────────────────────
224
225function setServerState(newState) {
226 serverState = newState;
227 updateMenu();
228 updateTray();
229 broadcastServerStatus();
230}
231
232function broadcastServerStatus() {
233 const status = {
234 state: serverState,
235 port: serverPort,
236 pid: serverProcess ? serverProcess.pid : null,
237 };
238 if (mainWindow && !mainWindow.isDestroyed()) {
239 mainWindow.webContents.send('server-status', status);
240 }
241 for (const winId of logWindows) {
242 try {
243 const win = BrowserWindow.fromId(winId);
244 if (win && !win.isDestroyed()) {
245 win.webContents.send('server-status', status);
246 }
247 } catch (e) {
248 logWindows.delete(winId);
249 }
250 }
251}
252
253function startServer(overrides = {}) {
254 if (serverProcess) {
255 appendLog('warn', 'Server is already running or starting.');
256 return;
257 }
258
259 setServerState('starting');
260 appendLog('info', 'Starting MojoLlama server...');
261
262 const { cmd, args, port } = getServerCommand(overrides);
263 appendLog('debug', `Command: ${cmd} ${args.join(' ')}`);
264 serverPort = port;
265
266 const root = getProjectRoot();
267 const env = {
268 ...process.env,
269 PORT: String(port),
270 OMP_NUM_THREADS: String(settings.threads || DEFAULT_THREADS),
271 };
272
273 // If model path is set in settings, pass as environment variable
274 if (settings.modelPath) {
275 env.MODEL_PATH = settings.modelPath;
276 }
277
278 try {
279 serverProcess = spawn(cmd, args, {
280 cwd: root,
281 env,
282 stdio: ['pipe', 'pipe', 'pipe'],
283 });
284
285 serverProcess.stdout.on('data', (data) => {
286 const lines = data.toString().split('\n').filter(l => l.trim());
287 for (const line of lines) {
288 appendLog('info', line);
289 }
290 });
291
292 serverProcess.stderr.on('data', (data) => {
293 const lines = data.toString().split('\n').filter(l => l.trim());
294 for (const line of lines) {
295 // stderr might have warnings or errors
296 const isError = line.toLowerCase().includes('error') || line.toLowerCase().includes('traceback');
297 appendLog(isError ? 'error' : 'warn', line);
298 }
299 });
300
301 serverProcess.on('error', (err) => {
302 appendLog('error', `Failed to start server: ${err.message}`);
303 setServerState('error');
304 serverProcess = null;
305 showNotification('Server Error', `Failed to start: ${err.message}`);
306 });
307
308 serverProcess.on('exit', (code, signal) => {
309 const reason = signal ? `signal ${signal}` : `exit code ${code}`;
310 appendLog('info', `Server process exited (${reason})`);
311
312 if (serverState === 'stopping') {
313 appendLog('info', 'Server stopped gracefully.');
314 setServerState('stopped');
315 } else if (code !== 0) {
316 appendLog('error', `Server crashed with exit code ${code}`);
317 setServerState('error');
318 showNotification('Server Crashed', `Server exited with code ${code}. Check the log for details.`);
319 } else {
320 setServerState('stopped');
321 }
322
323 serverProcess = null;
324 stopHealthCheck();
325 });
326
327 // Start health check polling
328 startHealthCheck(port);
329
330 } catch (err) {
331 appendLog('error', `Failed to spawn server: ${err.message}`);
332 setServerState('error');
333 showNotification('Server Error', `Failed to start: ${err.message}`);
334 }
335}
336
337function stopServer() {
338 if (!serverProcess) {
339 appendLog('warn', 'Server is not running.');
340 return;
341 }
342
343 setServerState('stopping');
344 appendLog('info', 'Stopping MojoLlama server...');
345
346 // Send SIGTERM first, then SIGKILL after timeout
347 const killTimeout = setTimeout(() => {
348 if (serverProcess) {
349 appendLog('warn', 'Server did not stop gracefully, sending SIGKILL...');
350 serverProcess.kill('SIGKILL');
351 }
352 }, 8000);
353
354 serverProcess.once('exit', () => {
355 clearTimeout(killTimeout);
356 });
357
358 serverProcess.kill('SIGTERM');
359}
360
361function restartServer() {
362 appendLog('info', 'Restarting server...');
363 if (serverProcess) {
364 stopServer();
365 // Give it a moment to fully exit before restarting
366 const checkInterval = setInterval(() => {
367 if (!serverProcess) {
368 clearInterval(checkInterval);
369 // Small delay to let the port release
370 setTimeout(() => startServer(), 500);
371 }
372 }, 200);
373 } else {
374 startServer();
375 }
376}
377
378// ─── Health check ────────────────────────────────────────────────────────────
379
380function startHealthCheck(port) {
381 stopHealthCheck();
382 healthInterval = setInterval(() => {
383 checkServerHealth(port);
384 }, POLL_INTERVAL);
385}
386
387function stopHealthCheck() {
388 if (healthInterval) {
389 clearInterval(healthInterval);
390 healthInterval = null;
391 }
392}
393
394function checkServerHealth(port) {
395 const req = http.get(`http://127.0.0.1:${port}/v1/models`, (res) => {
396 if (res.statusCode === 200 && serverState === 'starting') {
397 appendLog('info', `Server is ready on port ${port}`);
398 setServerState('running');
399 showNotification('Server Ready', `MojoLlama server is running on port ${port}`);
400 // Auto-reload main window to show the studio page
401 if (mainWindow && !mainWindow.isDestroyed()) {
402 mainWindow.loadURL(`http://localhost:${port}${STUDIO_URL}`);
403 }
404 } else if (res.statusCode !== 200 && serverState === 'running') {
405 appendLog('warn', `Server health check returned ${res.statusCode}`);
406 }
407 });
408
409 req.on('error', () => {
410 // Don't log connection errors during startup — they're expected
411 if (serverState === 'running') {
412 appendLog('warn', 'Lost connection to server. Is it still running?');
413 }
414 });
415
416 req.setTimeout(3000, () => {
417 req.destroy();
418 });
419}
420
421// ─── Notifications ──────────────────────────────────────────────────────────
422
423function showNotification(title, body) {
424 if (!settings.notifications) return;
425 try {
426 const notif = new Notification({ title, body, icon: getIconPath() });
427 notif.show();
428 return notif;
429 } catch (err) {
430 console.error('Notification failed:', err);
431 }
432}
433
434function getIconPath() {
435 const iconPath = path.join(__dirname, 'icons', 'icon.png');
436 if (fs.existsSync(iconPath)) return iconPath;
437 return undefined;
438}
439
440// ─── Window creation ─────────────────────────────────────────────────────────
441
442function createMainWindow(url) {
443 const win = new BrowserWindow({
444 width: 1280,
445 height: 800,
446 minWidth: 900,
447 minHeight: 600,
448 title: APP_NAME,
449 icon: getIconPath(),
450 backgroundColor: '#0d1117',
451 show: false,
452 webPreferences: {
453 preload: path.join(__dirname, 'preload.js'),
454 contextIsolation: true,
455 nodeIntegration: false,
456 sandbox: false,
457 webviewTag: false,
458 },
459 });
460
461 // Center window
462 win.center();
463
464 // Load www/studio.html directly from disk (no server needed for static UI)
465 const studioPath = path.join(getProjectRoot(), 'www', 'studio.html');
466 if (fs.existsSync(studioPath)) {
467 win.loadFile(studioPath);
468 } else {
469 // Fallback: try loading from server if it's running
470 const targetUrl = url || getTargetUrl();
471 win.loadURL(targetUrl);
472 }
473
474 win.once('ready-to-show', () => {
475 win.show();
476 if (settings.autoStart && serverState === 'stopped') {
477 // Small delay to let the window render first
478 setTimeout(() => startServer(), 1000);
479 }
480 });
481
482 // Handle load failures gracefully (server not ready yet)
483 win.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
484 // Only show connecting page if server isn't running yet
485 if (serverState !== 'running' && validatedURL && validatedURL.includes('localhost')) {
486 win.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(`
487 <!DOCTYPE html>
488 <html lang="en">
489 <head><meta charset="UTF-8"><title>${APP_NAME}</title>
490 <style>
491 body {
492 background: #0d1117; color: #e6edf3; font-family: -apple-system, sans-serif;
493 display: flex; align-items: center; justify-content: center;
494 height: 100vh; margin: 0; flex-direction: column; gap: 20px;
495 }
496 .spinner {
497 width: 40px; height: 40px; border: 3px solid #30363d;
498 border-top-color: #58a6ff; border-radius: 50%;
499 animation: spin 0.8s linear infinite;
500 }
501 @keyframes spin { to { transform: rotate(360deg); } }
502 h2 { font-size: 18px; font-weight: 600; color: #e6edf3; }
503 p { font-size: 13px; color: #8b949e; text-align: center; max-width: 400px; line-height: 1.5; }
504 .btn { padding: 8px 20px; border: none; border-radius: 6px; cursor: pointer;
505 font-size: 13px; font-weight: 600; background: #58a6ff; color: #fff; }
506 .btn:hover { filter: brightness(1.15); }
507 .btn-start { background: #3fb950; }
508 .btn-start:hover { filter: brightness(1.15); }
509 </style>
510 </head>
511 <body>
512 <div class="spinner"></div>
513 <h2>MojoLlama server is not running</h2>
514 <p>Start the server to access the full Studio experience, or browse the UI in offline mode.</p>
515 <div style="display:flex; gap: 10px;">
516 <button class="btn btn-start" onclick="window.mojollama.serverStart()">Start Server</button>
517 <button class="btn" onclick="location.reload()">Retry</button>
518 </div>
519 </body>
520 </html>
521 `)}`).catch(() => {});
522 }
523 });
524
525 win.on('close', (event) => {
526 if (settings.minimizeToTray && tray) {
527 event.preventDefault();
528 win.hide();
529 }
530 });
531
532 win.on('closed', () => {
533 mainWindow = null;
534 });
535
536 // Handle external links
537 win.webContents.setWindowOpenHandler(({ url }) => {
538 shell.openExternal(url);
539 return { action: 'deny' };
540 });
541
542 mainWindow = win;
543 return win;
544}
545
546function getTargetUrl() {
547 // Allow overriding via command-line argument
548 const args = process.argv.slice(2);
549 for (let i = 0; i < args.length; i++) {
550 if (args[i] === '--url' && args[i + 1]) {
551 return args[i + 1];
552 }
553 // Accept a standalone URL as the first argument
554 if (args[i].startsWith('http://') || args[i].startsWith('https://')) {
555 return args[i];
556 }
557 }
558 return `http://localhost:${serverPort}/studio.html`;
559}
560
561function createSettingsWindow() {
562 if (settingsWindow && !settingsWindow.isDestroyed()) {
563 settingsWindow.focus();
564 return;
565 }
566
567 const win = new BrowserWindow({
568 width: 600,
569 height: 520,
570 resizable: false,
571 title: `${APP_NAME} — Settings`,
572 icon: getIconPath(),
573 parent: mainWindow,
574 modal: true,
575 backgroundColor: '#0d1117',
576 webPreferences: {
577 preload: path.join(__dirname, 'preload.js'),
578 contextIsolation: true,
579 nodeIntegration: false,
580 sandbox: false,
581 },
582 });
583
584 win.loadFile(path.join(__dirname, 'renderer', 'settings.html'));
585
586 win.on('closed', () => {
587 settingsWindow = null;
588 });
589
590 settingsWindow = win;
591}
592
593function createLogWindow() {
594 const win = new BrowserWindow({
595 width: 800,
596 height: 500,
597 title: `${APP_NAME} — Console Log`,
598 icon: getIconPath(),
599 backgroundColor: '#0d1117',
600 webPreferences: {
601 preload: path.join(__dirname, 'preload.js'),
602 contextIsolation: true,
603 nodeIntegration: false,
604 sandbox: false,
605 },
606 });
607
608 win.loadFile(path.join(__dirname, 'renderer', 'log.html'));
609
610 win.on('closed', () => {
611 logWindows.delete(win.id);
612 });
613
614 logWindows.add(win.id);
615 return win;
616}
617
618// ─── Menu bar ────────────────────────────────────────────────────────────────
619
620function createMenu() {
621 const template = [
622 {
623 label: 'File',
624 submenu: [
625 {
626 label: 'Open Studio',
627 accelerator: 'CmdOrCtrl+1',
628 click: () => {
629 if (mainWindow && !mainWindow.isDestroyed()) {
630 mainWindow.loadURL(`http://localhost:${serverPort}${STUDIO_URL}`);
631 mainWindow.show();
632 }
633 },
634 },
635 {
636 label: 'Open Chat',
637 accelerator: 'CmdOrCtrl+2',
638 click: () => {
639 if (mainWindow && !mainWindow.isDestroyed()) {
640 mainWindow.loadURL(`http://localhost:${serverPort}${CHAT_URL}`);
641 mainWindow.show();
642 }
643 },
644 },
645 { type: 'separator' },
646 {
647 label: 'Settings',
648 accelerator: 'CmdOrCtrl+,',
649 click: () => createSettingsWindow(),
650 },
651 { type: 'separator' },
652 {
653 label: 'Quit',
654 accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Alt+F4',
655 click: () => {
656 if (settings.minimizeToTray && tray) {
657 // Quit for real
658 if (serverProcess) {
659 stopServer();
660 }
661 app.quit();
662 } else {
663 app.quit();
664 }
665 },
666 },
667 ],
668 },
669 {
670 label: 'Server',
671 id: 'server-menu',
672 submenu: [
673 {
674 label: 'Start Server',
675 id: 'start-server',
676 accelerator: 'CmdOrCtrl+S',
677 click: () => startServer(),
678 },
679 {
680 label: 'Stop Server',
681 id: 'stop-server',
682 accelerator: 'CmdOrCtrl+Shift+S',
683 click: () => stopServer(),
684 },
685 {
686 label: 'Restart Server',
687 id: 'restart-server',
688 accelerator: 'CmdOrCtrl+R',
689 click: () => restartServer(),
690 },
691 { type: 'separator' },
692 {
693 label: 'Settings...',
694 click: () => createSettingsWindow(),
695 },
696 { type: 'separator' },
697 {
698 label: 'Console Log',
699 accelerator: 'CmdOrCtrl+L',
700 click: () => createLogWindow(),
701 },
702 ],
703 },
704 {
705 label: 'View',
706 submenu: [
707 { role: 'reload', label: 'Reload Window' },
708 { role: 'forceReload', label: 'Force Reload' },
709 { role: 'toggleDevTools', label: 'Toggle Developer Tools' },
710 { type: 'separator' },
711 { role: 'resetZoom', label: 'Actual Size' },
712 { role: 'zoomIn', label: 'Zoom In' },
713 { role: 'zoomOut', label: 'Zoom Out' },
714 { type: 'separator' },
715 { role: 'togglefullscreen', label: 'Toggle Fullscreen' },
716 ],
717 },
718 {
719 label: 'Window',
720 submenu: [
721 { role: 'minimize', label: 'Minimize' },
722 { role: 'zoom', label: 'Zoom' },
723 { role: 'close', label: 'Close' },
724 ],
725 },
726 {
727 label: 'Help',
728 submenu: [
729 {
730 label: 'About MojoLlama Studio',
731 click: () => {
732 dialog.showMessageBox({
733 type: 'info',
734 title: `About ${APP_NAME}`,
735 message: `${APP_NAME} v0.2.0`,
736 detail:
737 'MojoLlama Studio is a desktop wrapper for the MojoLlama LLM inference engine.\n\n' +
738 'Built with Electron + Flask + Mojo 🔥\n\n' +
739 'Features:\n' +
740 ' • Multi-backend inference (CPU, GPU, MAX)\n' +
741 ' • LoRA fine-tuning and merging\n' +
742 ' • Dataset creation and auto-labeling\n' +
743 ' • Benchmark suite\n' +
744 ' • HuggingFace to GGUF export\n\n' +
745 'https://git.bamse.cloud/a730/MojoLlama',
746 icon: getIconPath(),
747 });
748 },
749 },
750 { type: 'separator' },
751 {
752 label: 'Documentation',
753 click: () => shell.openExternal('https://git.bamse.cloud/a730/MojoLlama'),
754 },
755 {
756 label: 'Report Issue',
757 click: () => shell.openExternal('https://git.bamse.cloud/a730/MojoLlama/issues'),
758 },
759 { type: 'separator' },
760 {
761 label: 'Check for Updates...',
762 click: () => {
763 const { autoUpdater } = require('electron-updater');
764 autoUpdater.checkForUpdates();
765 dialog.showMessageBox({
766 type: 'info',
767 title: 'Checking for Updates',
768 message: 'Checking for updates...',
769 detail: 'If an update is available, it will be downloaded and installed automatically.',
770 });
771 },
772 },
773 ],
774 },
775 ];
776
777 const menu = Menu.buildFromTemplate(template);
778 Menu.setApplicationMenu(menu);
779 updateMenu();
780}
781
782function updateMenu() {
783 const menu = Menu.getApplicationMenu();
784 if (!menu) return;
785
786 const startItem = menu.getMenuItemById('start-server');
787 const stopItem = menu.getMenuItemById('stop-server');
788 const restartItem = menu.getMenuItemById('restart-server');
789
790 if (startItem) startItem.enabled = serverState === 'stopped' || serverState === 'error';
791 if (stopItem) stopItem.enabled = serverState === 'running' || serverState === 'starting';
792 if (restartItem) restartItem.enabled = serverState === 'running' || serverState === 'stopped' || serverState === 'error';
793}
794
795// ─── System tray ─────────────────────────────────────────────────────────────
796
797function createTray() {
798 const iconPath = getIconPath();
799 if (!iconPath) return;
800
801 // Create a proper tray icon (16x16 or 22x22)
802 const trayIcon = nativeImage.createFromPath(iconPath);
803 // Electron will resize appropriately on each platform
804
805 try {
806 tray = new Tray(trayIcon);
807 tray.setToolTip(APP_NAME);
808
809 updateTrayContextMenu();
810 } catch (err) {
811 console.error('Failed to create tray:', err.message);
812 }
813}
814
815function updateTray() {
816 if (!tray) return;
817 updateTrayContextMenu();
818 const statusText = serverState === 'running'
819 ? `Running on port ${serverPort}`
820 : serverState === 'starting' ? 'Starting...'
821 : serverState === 'stopping' ? 'Stopping...'
822 : serverState === 'error' ? 'Error'
823 : 'Stopped';
824 tray.setToolTip(`${APP_NAME} — ${statusText}`);
825}
826
827function updateTrayContextMenu() {
828 if (!tray) return;
829
830 const contextMenu = Menu.buildFromTemplate([
831 {
832 label: `${APP_NAME} (${serverState})`,
833 enabled: false,
834 },
835 { type: 'separator' },
836 {
837 label: 'Show Window',
838 click: () => {
839 if (mainWindow && !mainWindow.isDestroyed()) {
840 mainWindow.show();
841 mainWindow.focus();
842 } else {
843 createMainWindow();
844 }
845 },
846 },
847 {
848 label: 'Open Studio',
849 click: () => {
850 if (mainWindow && !mainWindow.isDestroyed()) {
851 mainWindow.loadURL(`http://localhost:${serverPort}${STUDIO_URL}`);
852 mainWindow.show();
853 }
854 },
855 },
856 {
857 label: 'Open Chat',
858 click: () => {
859 if (mainWindow && !mainWindow.isDestroyed()) {
860 mainWindow.loadURL(`http://localhost:${serverPort}${CHAT_URL}`);
861 mainWindow.show();
862 }
863 },
864 },
865 { type: 'separator' },
866 {
867 label: serverState === 'running' ? 'Stop Server' : 'Start Server',
868 click: () => {
869 if (serverState === 'running') {
870 stopServer();
871 } else {
872 startServer();
873 }
874 },
875 },
876 {
877 label: 'Restart Server',
878 enabled: serverState === 'running' || serverState === 'stopped' || serverState === 'error',
879 click: () => restartServer(),
880 },
881 { type: 'separator' },
882 {
883 label: 'Console Log',
884 click: () => createLogWindow(),
885 },
886 {
887 label: 'Settings...',
888 click: () => createSettingsWindow(),
889 },
890 { type: 'separator' },
891 {
892 label: 'Quit',
893 click: () => {
894 // Save any unsaved state
895 if (serverProcess) {
896 stopServer();
897 }
898 app.quit();
899 },
900 },
901 ]);
902
903 tray.setContextMenu(contextMenu);
904 tray.setToolTip(`${APP_NAME} — ${serverState}`);
905}
906
907// ─── IPC handlers ────────────────────────────────────────────────────────────
908
909function setupIPC() {
910 // Server control
911 ipcMain.handle('server:start', async (event, overrides) => {
912 startServer(overrides || {});
913 return { success: true };
914 });
915
916 ipcMain.handle('server:stop', async () => {
917 stopServer();
918 return { success: true };
919 });
920
921 ipcMain.handle('server:restart', async () => {
922 restartServer();
923 return { success: true };
924 });
925
926 ipcMain.handle('server:status', async () => {
927 return {
928 state: serverState,
929 port: serverPort,
930 pid: serverProcess ? serverProcess.pid : null,
931 };
932 });
933
934 // Settings
935 ipcMain.handle('settings:load', async () => {
936 return loadSettings();
937 });
938
939 ipcMain.handle('settings:save', async (event, newSettings) => {
940 const success = saveSettings(newSettings);
941 // If auto-start setting changed, handle accordingly
942 if (newSettings.autoStart !== undefined && newSettings.autoStart && serverState === 'stopped') {
943 startServer();
944 }
945 return { success };
946 });
947
948 // Logs
949 ipcMain.handle('log:get', async () => {
950 return getLogBuffer();
951 });
952
953 ipcMain.handle('log:clear', async () => {
954 clearLogBuffer();
955 return { success: true };
956 });
957
958 // Window management
959 ipcMain.handle('window:openLog', async () => {
960 createLogWindow();
961 return { success: true };
962 });
963
964 ipcMain.handle('window:openSettings', async () => {
965 createSettingsWindow();
966 return { success: true };
967 });
968
969 // App info
970 ipcMain.handle('app:info', async () => {
971 return {
972 name: APP_NAME,
973 version: app.getVersion(),
974 electronVersion: process.versions.electron,
975 nodeVersion: process.versions.node,
976 platform: process.platform,
977 arch: process.arch,
978 projectRoot: getProjectRoot(),
979 pythonPath: findPython(),
980 serverState,
981 serverPort,
982 };
983 });
984
985 // Open external link
986 ipcMain.handle('shell:openExternal', async (event, url) => {
987 if (typeof url === 'string' && (url.startsWith('http://') || url.startsWith('https://'))) {
988 shell.openExternal(url);
989 }
990 });
991}
992
993// ─── App lifecycle ───────────────────────────────────────────────────────────
994
995app.whenReady().then(() => {
996 loadSettings();
997 createMenu();
998 setupIPC();
999
1000 createMainWindow();
1001
1002 // Create tray after a small delay to let the app icon load
1003 setTimeout(() => {
1004 createTray();
1005 }, 500);
1006
1007 app.on('activate', () => {
1008 if (mainWindow === null) {
1009 createMainWindow();
1010 } else {
1011 mainWindow.show();
1012 }
1013 });
1014
1015 // Setup auto-updater
1016 if (!process.env.ELECTRON_DEV) {
1017 try {
1018 const { autoUpdater } = require('electron-updater');
1019 autoUpdater.logger = console;
1020 autoUpdater.autoDownload = true;
1021
1022 autoUpdater.on('update-available', (info) => {
1023 appendLog('info', `Update available: v${info.version}`);
1024 showNotification('Update Available', `Version ${info.version} is downloading...`);
1025 });
1026
1027 autoUpdater.on('update-downloaded', (info) => {
1028 appendLog('info', `Update v${info.version} downloaded`);
1029 dialog.showMessageBox({
1030 type: 'info',
1031 title: 'Update Ready',
1032 message: `Version ${info.version} has been downloaded.`,
1033 detail: 'Restart the application to install the update.',
1034 buttons: ['Restart Now', 'Later'],
1035 }).then(({ response }) => {
1036 if (response === 0) {
1037 autoUpdater.quitAndInstall();
1038 }
1039 });
1040 });
1041
1042 autoUpdater.on('error', (err) => {
1043 appendLog('error', `Auto-update error: ${err.message}`);
1044 });
1045
1046 // Check for updates on startup (with a delay)
1047 setTimeout(() => {
1048 autoUpdater.checkForUpdates().catch(err => {
1049 console.error('Update check failed:', err.message);
1050 });
1051 }, 10000);
1052 } catch (err) {
1053 console.error('Auto-updater setup failed:', err.message);
1054 }
1055 }
1056});
1057
1058app.on('window-all-closed', () => {
1059 // On macOS, keep the app running in the background (tray)
1060 if (process.platform !== 'darwin' && !tray) {
1061 if (serverProcess) {
1062 stopServer();
1063 }
1064 app.quit();
1065 }
1066});
1067
1068app.on('before-quit', () => {
1069 // Clean up before quitting
1070 if (serverProcess) {
1071 try {
1072 serverProcess.kill('SIGTERM');
1073 } catch (e) {
1074 // ignore
1075 }
1076 }
1077 stopHealthCheck();
1078
1079 // Close log windows
1080 for (const winId of logWindows) {
1081 try {
1082 const win = BrowserWindow.fromId(winId);
1083 if (win && !win.isDestroyed()) {
1084 win.close();
1085 }
1086 } catch (e) {}
1087 }
1088
1089 // Close settings window
1090 if (settingsWindow && !settingsWindow.isDestroyed()) {
1091 settingsWindow.close();
1092 }
1093});