Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/MojoLlama/blob/main/desktop/main.js # MojoLlama Archived Mojo/MAX quantizer and serving research repository (read-only history) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers 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 8 const { app, BrowserWindow, Menu, Tray, nativeImage, dialog, Notification, ipcMain, shell } = require('electron'); 9 const path = require('path'); 10 const fs = require('fs'); 11 const { spawn, execSync } = require('child_process'); 12 const http = require('http'); 13 14 // ─── Constants ─────────────────────────────────────────────────────────────── 15 16 const APP_NAME = 'MojoLlama Studio'; 17 const STUDIO_URL = '/studio.html'; 18 const CHAT_URL = '/chat.html'; 19 const SETTINGS_FILE = 'mojollama-settings.json'; 20 const DEFAULT_PORT = 8080; 21 const DEFAULT_LLAMA_PORT = 8081; 22 const DEFAULT_THREADS = 32; 23 const POLL_INTERVAL = 2000; // ms between server health checks 24 const MAX_LOG_LINES = 5000; // ring buffer for server output 25 26 // ─── State ────────────────────────────────────────────────────────────────── 27 28 let mainWindow = null; 29 let tray = null; 30 let serverProcess = null; 31 let serverState = 'stopped'; // 'stopped' | 'starting' | 'running' | 'stopping' | 'error' 32 let settings = {}; 33 let logBuffer = []; // ring buffer of { timestamp, level, text } 34 let logWindows = new Set(); // set of BrowserWindow IDs for log windows 35 let settingsWindow = null; 36 let healthInterval = null; 37 let serverPort = DEFAULT_PORT; 38 let 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 */ 47 function 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 */ 75 function 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 */ 104 function 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 121 function getSettingsPath() { 122 const userDataPath = app.getPath('userData'); 123 return path.join(userDataPath, SETTINGS_FILE); 124 } 125 126 function 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 157 function 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 173 function 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 202 function getLogBuffer() { 203 return logBuffer; 204 } 205 206 function 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 225 function setServerState(newState) { 226 serverState = newState; 227 updateMenu(); 228 updateTray(); 229 broadcastServerStatus(); 230 } 231 232 function 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 253 function 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 337 function 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 361 function 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 380 function startHealthCheck(port) { 381 stopHealthCheck(); 382 healthInterval = setInterval(() => { 383 checkServerHealth(port); 384 }, POLL_INTERVAL); 385 } 386 387 function stopHealthCheck() { 388 if (healthInterval) { 389 clearInterval(healthInterval); 390 healthInterval = null; 391 } 392 } 393 394 function 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 423 function 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 434 function 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 442 function 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 488 489
Start the server to access the full Studio experience, or browse the UI in offline mode.
515