-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathelectron-main.js
More file actions
746 lines (680 loc) · 33.6 KB
/
electron-main.js
File metadata and controls
746 lines (680 loc) · 33.6 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
/**
* guIDE - AI-Powered Offline IDE
* Copyright (c) 2025-2026 Brendan Gray (GitHub: FileShot)
* All Rights Reserved. See LICENSE file for terms.
*
* Full-featured IDE with local LLM, RAG, MCP tools, browser automation,
* memory/context system, terminal, web search.
*/
const { app, BrowserWindow, ipcMain, Menu, shell, dialog, session, safeStorage } = require('electron');
const path = require('path');
const fs = require('fs').promises;
const fsSync = require('fs');
const os = require('os');
const https = require('https');
const { exec } = require('child_process');
// ─── Persistent Logging ──────────────────────────────────────────────
// Must be loaded FIRST before any other module so all console.log/warn/error
// calls across the entire app are captured to %APPDATA%/guide-ide/logs/guide-main.log
const log = require('./main/logger');
log.installConsoleIntercepts();
// Electron GPU stability flags (prevent Chromium GPU process crashes on some NVIDIA setups)
app.commandLine.appendSwitch('disable-gpu-sandbox');
app.commandLine.appendSwitch('ignore-gpu-blocklist');
// Use GPU-accelerated compositing for smoother UI; node-llama-cpp uses CUDA which is a separate GPU context
// If GPU conflicts arise, uncomment: app.disableHardwareAcceleration();
app.commandLine.appendSwitch('disable-gpu-vsync'); // Reduce input latency
// ── V8 Performance Flags ──
// Enable V8 code caching for faster require() on subsequent launches
// NOTE: --optimize-for-size is intentionally absent — it shrinks compiled machine code
// at the cost of execution speed, which is the wrong trade-off for a dev tool.
app.commandLine.appendSwitch('js-flags', '--max-old-space-size=4096');
// ─── Single Instance Lock ─────────────────────────────────────────────
// Prevent multiple instances from competing for config files, model files,
// terminal sessions, and port bindings.
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit();
} else {
app.on('second-instance', () => {
// Focus existing window when user tries to open a second instance
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
});
}
// ─── Main Process Modules ────────────────────────────────────────────
const { LLMEngine } = require('./main/llmEngine');
const { ModelManager } = require('./main/modelManager');
const { RAGEngine } = require('./main/ragEngine');
const { TerminalManager } = require('./main/terminalManager');
const { WebSearch } = require('./main/webSearch');
const { MCPToolServer } = require('./main/mcpToolServer');
const { BrowserManager } = require('./main/browserManager');
const { PlaywrightBrowser } = require('./main/playwrightBrowser');
const { MemoryStore } = require('./main/memoryStore');
const { CloudLLMService } = require('./main/cloudLLMService');
const { ImageGenerationService } = require('./main/imageGenerationService');
const { LocalImageEngine } = require('./main/localImageEngine');
const { GitManager } = require('./main/gitManager');
const LicenseManager = require('./main/licenseManager');
const { DebugService } = require('./main/debugService');
const { ConversationSummarizer } = require('./main/conversationSummarizer');
const { autoUpdater } = require('electron-updater');
// ─── Extracted Modules ───────────────────────────────────────────────
const { DEFAULT_SYSTEM_PREAMBLE, DEFAULT_COMPACT_PREAMBLE, DEFAULT_CHAT_PREAMBLE } = require('./main/constants');
const { createPathValidator } = require('./main/pathValidator');
const { createSettingsManager, registerSettingsHandlers } = require('./main/settingsManager');
const { encryptApiKey, decryptApiKey, loadSavedApiKeys } = require('./main/apiKeyStore');
const { _truncateResult, _detectGPU, getCpuUsage } = require('./main/mainUtils');
const { createMenu } = require('./main/appMenu');
const { register: registerAgenticChat } = require('./main/agenticChat');
const { runFirstRunSetup } = require('./main/firstRunSetup');
// IPC handler modules — Core (loaded eagerly at startup)
const { register: registerFileSystem } = require('./main/ipc/fileSystemHandlers');
const { register: registerDialogs } = require('./main/ipc/dialogHandlers');
const { register: registerTerminal } = require('./main/ipc/terminalHandlers');
const { register: registerLicense } = require('./main/ipc/licenseHandlers');
const { register: registerGit } = require('./main/ipc/gitHandlers');
const { register: registerMemory } = require('./main/ipc/memoryHandlers');
const { register: registerBrowser } = require('./main/ipc/browserHandlers');
const { register: registerLlm } = require('./main/ipc/llmHandlers');
const { register: registerModels } = require('./main/ipc/modelHandlers');
const { register: registerRag } = require('./main/ipc/ragHandlers');
const { register: registerMcp } = require('./main/ipc/mcpHandlers');
const { register: registerDebug } = require('./main/ipc/debugHandlers');
const { register: registerAgents } = require('./main/ipc/agentHandlers');
const { register: registerCloudLlm } = require('./main/ipc/cloudLlmHandlers');
const { register: registerEditor } = require('./main/ipc/editorHandlers');
const { register: registerUtility } = require('./main/ipc/utilityHandlers');
const { register: registerImageGen } = require('./main/ipc/imageGenHandlers');
const { register: registerBenchmark } = require('./main/ipc/benchmarkHandlers');
const { register: registerTemplates } = require('./main/ipc/templateHandlers');
const { register: registerTodoTree } = require('./main/ipc/todoTreeHandlers');
const { register: registerLiveServer } = require('./main/ipc/liveServerHandlers');
const { register: registerRestClient } = require('./main/ipc/restClientHandlers');
// IPC handler modules — Deferred (loaded after window shows for faster startup)
let _deferredRegistered = false;
function registerDeferredHandlers(ctx) {
if (_deferredRegistered) return;
_deferredRegistered = true;
const t0 = Date.now();
require('./main/ipc/databaseHandlers').register(ctx);
require('./main/ipc/codeReviewHandlers').register(ctx);
require('./main/ipc/profilerHandlers').register(ctx);
require('./main/ipc/smartSearchHandlers').register(ctx);
require('./main/ipc/docsHandlers').register(ctx);
require('./main/ipc/sshHandlers').register(ctx);
require('./main/ipc/pluginHandlers').register(ctx);
require('./main/ipc/collabHandlers').register(ctx);
require('./main/ipc/notebookHandlers').register(ctx);
console.log(`[IDE] Deferred handlers registered in ${Date.now() - t0}ms`);
}
// ─── Brand Identity (deeply embedded — do not remove) ────────────────
const _B = { n: '\x67\x75\x49\x44\x45', a: '\x42\x72\x65\x6e\x64\x61\x6e\x20\x47\x72\x61\x79', g: '\x46\x69\x6c\x65\x53\x68\x6f\x74', y: '2025-2026' };
const _V = () => [_B.n, _B.a, _B.g, _B.y].every(v => typeof v === 'string' && v.length > 0);
if (!_V()) { console.error('Integrity check failed.'); process.exit(1); }
// ─── Globals ─────────────────────────────────────────────────────────
let mainWindow;
const isDev = process.env.NODE_ENV === 'development';
const appBasePath = app.isPackaged ? path.dirname(process.execPath) : __dirname;
// User-writable directory for settings, memory, etc. (NOT Program Files)
const userDataPath = app.getPath('userData');
// For models, use user data folder when packaged (no admin rights needed)
const modelsBasePath = app.isPackaged ? userDataPath : __dirname;
// Service instances
const llmEngine = new LLMEngine();
let agenticCancelled = false; // Global flag to abort the agentic loop from outside
const modelManager = new ModelManager(modelsBasePath);
const ragEngine = new RAGEngine();
const terminalManager = new TerminalManager();
const webSearch = new WebSearch();
const browserManager = new BrowserManager();
const playwrightBrowser = new PlaywrightBrowser();
const memoryStore = new MemoryStore(userDataPath);
const cloudLLM = new CloudLLMService();
const imageGen = new ImageGenerationService();
const localImageEngine = new LocalImageEngine();
const gitManager = new GitManager();
const licenseManager = new LicenseManager();
// Restore persisted license state from disk immediately — without this call,
// isActivated stays false until the renderer explicitly calls licenseGetStatus,
// which reads only in-memory state (always null at process start).
licenseManager.loadLicense();
// Wire LicenseManager so cloudLLM can retrieve session token for server proxy routing
cloudLLM.setLicenseManager(licenseManager);
const debugService = new DebugService();
const mcpToolServer = new MCPToolServer({
webSearch,
ragEngine,
terminalManager,
});
mcpToolServer.setPlaywrightBrowser(playwrightBrowser);
mcpToolServer.setBrowserManager(browserManager);
mcpToolServer.setGitManager(gitManager);
mcpToolServer.setImageGen(imageGen);
// Wire TODO updates to renderer
mcpToolServer.onTodoUpdate = (todos) => {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('todo-update', todos);
}
};
// Wire subagent spawning (calls back into cloudLLM for independent conversation)
mcpToolServer._spawnSubagent = async (goal, context) => {
// Create a mini agentic loop for the subagent task
const subPrompt = `You are a subagent. Complete this task:\n\nGOAL: ${goal}\n\nCONTEXT: ${context || 'None provided'}\n\nRespond with the result of your work.`;
const result = await cloudLLM.chat([{ role: 'user', content: subPrompt }], { maxTokens: 2000 });
return result?.text || result?.content || 'Subagent completed without response';
};
// Wire permission gate for destructive tools (currently auto-approve, UI hookup later)
// To enable approval prompts, set this to an async function that sends IPC and awaits user choice
mcpToolServer.onPermissionRequest = null; // Auto-approve for now
// Current project state
let currentProjectPath = null;
// ─── Foundation Setup ────────────────────────────────────────────────
const isPathAllowed = createPathValidator(appBasePath, modelsBasePath, () => currentProjectPath);
const { _readConfig, _writeConfig } = createSettingsManager(userDataPath);
// ─── Shared Context for Modules ──────────────────────────────────────
const ctx = {
// Electron
getMainWindow: () => mainWindow,
get currentProjectPath() { return currentProjectPath; },
set currentProjectPath(v) { currentProjectPath = v; },
get agenticCancelled() { return agenticCancelled; },
set agenticCancelled(v) { agenticCancelled = v; },
// Paths & config
appBasePath, userDataPath, modelsBasePath, isDev,
isPathAllowed, _readConfig, _writeConfig,
encryptApiKey, decryptApiKey, loadSavedApiKeys,
// Services
llmEngine, modelManager, ragEngine, terminalManager,
webSearch, browserManager, playwrightBrowser,
memoryStore, cloudLLM, imageGen, localImageEngine, gitManager, licenseManager,
debugService, mcpToolServer, ConversationSummarizer,
// Utilities
_truncateResult, _detectGPU, getCpuUsage,
DEFAULT_SYSTEM_PREAMBLE, DEFAULT_COMPACT_PREAMBLE, DEFAULT_CHAT_PREAMBLE, _B,
// Functions shared between modules
createWindow,
autoIndexProject,
scheduleIncrementalReindex,
};
// ─── Register IPC Handlers ───────────────────────────────────────────
// Core handlers — registered immediately at startup
registerSettingsHandlers(ctx);
registerFileSystem(ctx);
registerDialogs(ctx);
registerTerminal(ctx);
registerLicense(ctx);
registerGit(ctx);
registerMemory(ctx);
registerBrowser(ctx);
registerLlm(ctx);
registerModels(ctx);
registerRag(ctx);
registerMcp(ctx);
registerDebug(ctx);
registerAgents(ctx);
registerCloudLlm(ctx);
registerEditor(ctx);
registerUtility(ctx);
registerImageGen(ctx);
registerBenchmark(ctx);
registerTemplates(ctx);
registerTodoTree(ctx);
registerLiveServer(ctx);
registerRestClient(ctx);
registerAgenticChat(ctx);
// ─── Auto-Update IPC ─────────────────────────────────────────────────
// Renderer calls this when user clicks "Restart to Install" in the update banner
ipcMain.handle('install-update', () => {
autoUpdater.quitAndInstall(false, true);
});
// ─── Title Bar Theming IPC ───────────────────────────────────────────
// Called by ThemeProvider whenever the theme changes — syncs the native
// Windows titlebar button color to match the active theme's titleBar color.
ipcMain.handle('set-titlebar-overlay', (_evt, opts) => {
if (mainWindow && !mainWindow.isDestroyed()) {
try { mainWindow.setTitleBarOverlay(opts); } catch (e) { /* unsupported platform */ }
}
});
// Deferred handlers — register after window shows (faster cold startup)
// This is safe because these IPC channels aren't called until the user navigates to their panels
// Register them via setImmediate so they load right after the event loop clears
setImmediate(() => registerDeferredHandlers(ctx));
// ─── Window Creation ─────────────────────────────────────────────────
function createWindow() {
mainWindow = new BrowserWindow({
width: 1600,
height: 1000,
minWidth: 1024,
minHeight: 700,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: true,
preload: path.join(__dirname, 'preload.js'),
webviewTag: false,
},
titleBarStyle: 'hidden',
titleBarOverlay: {
color: '#1e1e1e',
symbolColor: '#cccccc',
height: 32,
},
backgroundColor: '#1e1e1e',
show: false,
icon: path.join(__dirname, 'icon.png'),
});
if (isDev) {
mainWindow.loadURL('http://localhost:5174');
} else {
mainWindow.loadFile(path.join(__dirname, 'dist', 'index.html'));
}
mainWindow.once('ready-to-show', () => {
mainWindow.show();
if (isDev) mainWindow.webContents.openDevTools({ mode: 'detach' });
});
mainWindow.on('closed', () => {
mainWindow = null;
});
// Hide BrowserView when window loses focus (e.g., native menu opens) to prevent
// position bugs where the BrowserView jumps to the upper-left corner
let _browserWasVisible = false;
mainWindow.on('blur', () => {
if (browserManager.isVisible) {
_browserWasVisible = true;
browserManager.hide();
}
});
mainWindow.on('focus', () => {
if (_browserWasVisible) {
_browserWasVisible = false;
// Tell renderer to recalculate and re-show the BrowserView
mainWindow?.webContents.send('browser-restore');
}
});
// Also restore on resize (in case window is resized from menu)
mainWindow.on('resize', () => {
if (browserManager.isVisible) {
mainWindow?.webContents.send('browser-restore');
}
});
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
});
// Permission handlers — deny-by-default, whitelist only what we need
const ALLOWED_PERMISSIONS = new Set(['media', 'clipboard-read', 'clipboard-sanitized-write']);
session.defaultSession.setPermissionRequestHandler((webContents, permission, callback) => {
if (ALLOWED_PERMISSIONS.has(permission)) {
callback(true);
} else {
console.warn(`[Security] Denied permission request: ${permission}`);
callback(false);
}
});
session.defaultSession.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
return ALLOWED_PERMISSIONS.has(permission);
});
// ── Content Security Policy ───────────────────────────────────────
// In production builds, drop unsafe-eval to harden against XSS.
// In dev mode, Vite HMR requires unsafe-eval.
const scriptSrc = app.isPackaged
? "script-src 'self' 'unsafe-inline';"
: "script-src 'self' 'unsafe-inline' 'unsafe-eval';";
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
callback({
responseHeaders: {
...details.responseHeaders,
'Content-Security-Policy': [
"default-src 'self'; " +
scriptSrc + " " +
"style-src 'self' 'unsafe-inline'; " +
"font-src 'self' data:; " +
"img-src 'self' data: blob: https:; " +
"connect-src 'self' ws://localhost:* http://localhost:* https://*.cerebras.ai https://*.groq.com https://*.googleapis.com https://api.sambanova.ai https://openrouter.ai https://api.together.xyz https://api.fireworks.ai https://api.x.ai https://api.anthropic.com https://api.openai.com https://api.mistral.ai https://api.cohere.ai https://integrate.api.nvidia.com https://apifreellm.com; " +
"worker-src 'self' blob:; " +
"child-src 'none'; " +
"object-src 'none'; " +
"base-uri 'self';"
],
},
});
});
playwrightBrowser.initialize(mainWindow);
browserManager.initialize(mainWindow);
initializeServices();
createMenu(ctx);
}
// ─── Service Initialization ──────────────────────────────────────────
async function initializeServices() {
console.log('[IDE] Initializing services...');
// Parallelize independent service initialization
await Promise.all([
memoryStore.initialize(),
Promise.resolve(loadSavedApiKeys(userDataPath, cloudLLM)),
]);
// Load Pollinations API key for video generation (from saved config)
try {
const config = _readConfig();
if (config.apiKeys?.pollinations) {
const key = decryptApiKey(config.apiKeys.pollinations);
if (key) {
imageGen.addPollinationsKey(key);
console.log('[IDE] Loaded Pollinations API key for video generation');
}
}
// Also check if user saved it under userSettings
if (config.userSettings?.pollinationsApiKey) {
const key = config.userSettings.pollinationsApiKey.trim();
if (key) imageGen.addPollinationsKey(key);
}
} catch (_) {}
// Built-in Pollinations key pool — video generation works out of the box
// Keys use guIDE-built-in-2026 XOR scheme (different from cloudLLMService.js 0x5A scheme)
const _S = 'guIDE-built-in-2026';
const _d = (e) => { const b = Buffer.from(e, 'base64'); let r = ''; for (let i = 0; i < b.length; i++) r += String.fromCharCode(b[i] ^ _S.charCodeAt(i % _S.length)); return r; };
const _pk = [
_d('FB4WJiNlMUQwAjhADC1MX1oDVCggDSUXfCBBPAM1Zzk0X0Y='),
_d('FB4WFgtFLCwuX0VgIBRueEVeD1UHKhM9RTQMPBQyZg42Q1U='),
_d('FB4WMBxmEDI/BE1DOCtnc394B1U2OR42ZVEcOwEkSAIde3E='),
];
for (const k of _pk) imageGen.addPollinationsKey(k);
// Load GPU preference from saved settings
try {
const config = _readConfig();
if (config.userSettings?.gpuPreference) {
llmEngine.setGPUPreference(config.userSettings.gpuPreference);
}
if (typeof config.userSettings?.requireMinContextForGpu === 'boolean') {
llmEngine.setRequireMinContextForGpu(config.userSettings.requireMinContextForGpu);
}
} catch (_) {}
try {
await modelManager.initialize();
const models = modelManager.availableModels;
console.log(`[IDE] Found ${models.length} model(s)`);
mainWindow.webContents.on('did-finish-load', async () => {
console.log('[IDE] Page loaded, sending initial state...');
mainWindow.webContents.send('models-available', models);
mainWindow.webContents.send('memory-stats', memoryStore.getStats());
mainWindow.webContents.send('mcp-tools-available', mcpToolServer.getToolDefinitions());
// Auto-load last used model if persisted, otherwise show available model
const fs = require('fs');
const settingsPath = require('path').join(userDataPath, 'settings.json');
let lastUsedModel = null;
try {
const config = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
if (config.lastUsedModel && fs.existsSync(config.lastUsedModel)) {
lastUsedModel = config.lastUsedModel;
}
} catch {}
if (lastUsedModel) {
const modelName = require('path').basename(lastUsedModel).replace(/\.gguf$/i, '');
console.log(`[IDE] Auto-loading last used model: ${modelName}`);
mainWindow.webContents.send('llm-status', {
state: 'loading',
message: `Loading ${modelName}...`,
});
// Non-blocking auto-load — UI is usable while model loads
llmEngine.initialize(lastUsedModel).then((modelInfo) => {
console.log(`[IDE] Auto-loaded model: ${modelName}`);
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('llm-status', { state: 'ready', message: `Model loaded: ${modelName}` });
if (modelInfo?.contextSize) {
mainWindow.webContents.send('context-usage', { used: 0, total: modelInfo.contextSize });
}
mainWindow.webContents.send('model-auto-loaded', { path: lastUsedModel, name: modelName });
}
}).catch((err) => {
console.warn(`[IDE] Auto-load failed: ${err.message}`);
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('llm-status', { state: 'idle', message: `Auto-load failed. Click a model to load.` });
}
});
} else {
const defaultModel = modelManager.getDefaultModel();
if (defaultModel) {
console.log(`[IDE] Default model available: ${defaultModel.name} (not auto-loading)`);
mainWindow.webContents.send('llm-status', {
state: 'idle',
message: `Model ready: ${defaultModel.name}. Click to load.`,
});
} else {
mainWindow.webContents.send('llm-status', {
state: 'idle',
message: 'Cloud AI active (Cerebras/Groq). Download a .gguf model to enable local GPU inference.',
});
}
}
// Non-blocking: detect NVIDIA GPU and download CUDA backends in the background.
// App is fully usable via cloud AI while this runs (or if no GPU is found).
runFirstRunSetup(mainWindow, { userDataPath }).catch(err => {
console.error('[FirstRun] Setup error:', err.message);
});
});
} catch (e) {
console.error('[IDE] Failed to initialize model manager:', e);
}
// Forward events
llmEngine.on('status', (status) => {
if (mainWindow) mainWindow.webContents.send('llm-status', status);
});
// ── Dev Console: forward verbose logs to renderer ──
const _origConsoleLog = console.log;
const _origConsoleWarn = console.warn;
const _origConsoleError = console.error;
const _devLogPrefixRe = /\[(LLM|GPU|AI|Model|IDE|Cloud|RAG|MCP|Debug|Reset|Agentic|License)\]/i;
const _devLogKeywordRe = /model|context|token|generat|load|dispos|abort|session|layer|backend|flash/i;
const devLog = (level, ...args) => {
if (!mainWindow || mainWindow.isDestroyed()) return;
// Fast pre-check: test first string arg before expensive JSON.stringify
const firstStr = typeof args[0] === 'string' ? args[0] : '';
if (!_devLogPrefixRe.test(firstStr) && !_devLogKeywordRe.test(firstStr)) {
// Check remaining args only if first didn't match (rare path)
let found = false;
for (let i = 1; i < args.length; i++) {
if (typeof args[i] === 'string' && (_devLogPrefixRe.test(args[i]) || _devLogKeywordRe.test(args[i]))) { found = true; break; }
}
if (!found) return;
}
const text = args.map(a => typeof a === 'string' ? a : (typeof a === 'number' ? String(a) : JSON.stringify(a, null, 0))).join(' ');
mainWindow.webContents.send('dev-log', { level, text, timestamp: Date.now() });
};
console.log = (...args) => { _origConsoleLog(...args); devLog('info', ...args); };
console.warn = (...args) => { _origConsoleWarn(...args); devLog('warn', ...args); };
console.error = (...args) => { _origConsoleError(...args); devLog('error', ...args); };
modelManager.on('models-updated', (models) => {
if (mainWindow) mainWindow.webContents.send('models-available', models);
});
terminalManager.on('data', ({ id, data }) => {
if (mainWindow) mainWindow.webContents.send('terminal-data', { id, data });
});
terminalManager.on('exit', ({ id, exitCode }) => {
if (mainWindow) mainWindow.webContents.send('terminal-exit', { id, exitCode });
});
// Forward debug events to renderer
debugService.setEventCallback((event) => {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('debug-event', event);
}
});
// ── Auto-Update Setup ──────────────────────────────────────────────
// Only check for updates in production builds (not in dev mode)
if (app.isPackaged) {
autoUpdater.autoDownload = true;
autoUpdater.autoInstallOnAppQuit = true;
autoUpdater.on('update-available', (info) => {
console.log(`[AutoUpdater] Update available: ${info.version}`);
mainWindow?.webContents.send('update-available', info);
});
autoUpdater.on('update-downloaded', (info) => {
console.log(`[AutoUpdater] Update downloaded: ${info.version} — ready to install`);
mainWindow?.webContents.send('update-downloaded', info);
});
autoUpdater.on('error', (err) => {
console.error('[AutoUpdater] Error:', err.message);
});
// Delay first check by 15s so it doesn't compete with model loading / indexing at startup
setTimeout(() => {
autoUpdater.checkForUpdates().catch((err) => {
console.error('[AutoUpdater] checkForUpdates failed:', err.message);
});
}, 15000);
}
}
// ─── Auto-Index Project ──────────────────────────────────────────────
let _reindexTimer = null;
async function autoIndexProject(projectPath) {
if (!projectPath) return;
console.log(`[IDE] Auto-indexing project: ${projectPath}`);
try {
const result = await ragEngine.indexProject(projectPath, (progress, done, total) => {
if (mainWindow) mainWindow.webContents.send('rag-progress', { progress, done, total });
});
console.log(`[IDE] Indexing complete: ${result.totalFiles} files, ${result.totalChunks} chunks`);
memoryStore.learnFact('project_path', projectPath);
memoryStore.learnFact('project_files', `${result.totalFiles} files indexed`);
if (mainWindow) mainWindow.webContents.send('rag-status', ragEngine.getStatus());
} catch (e) {
console.error('[IDE] Auto-indexing failed:', e.message);
}
}
/**
* Debounced incremental re-index — called when files change via MCP tools.
* Waits 3s after last change to batch consecutive edits.
*/
function scheduleIncrementalReindex() {
if (_reindexTimer) clearTimeout(_reindexTimer);
_reindexTimer = setTimeout(async () => {
_reindexTimer = null;
if (!ragEngine.projectPath || ragEngine.isIndexing) return;
try {
const result = await ragEngine.reindexChanged();
if (result.updated || result.added || result.removed) {
console.log(`[IDE] Incremental re-index: ${result.updated} updated, ${result.added} added, ${result.removed} removed`);
if (mainWindow) mainWindow.webContents.send('rag-status', ragEngine.getStatus());
}
} catch (e) {
console.error('[IDE] Incremental re-index failed:', e.message);
}
}, 3000);
}
// ─── App Lifecycle ───────────────────────────────────────────────────
console.log('[IDE] App starting, NODE_ENV:', process.env.NODE_ENV);
process.on('uncaughtException', (err) => {
console.error('[IDE] Uncaught exception:', err);
// Write crash log
try {
const crashDir = path.join(app.getPath('userData'), 'crash-logs');
fsSync.mkdirSync(crashDir, { recursive: true });
const ts = new Date().toISOString().replace(/[:.]/g, '-');
fsSync.writeFileSync(path.join(crashDir, `crash-${ts}.txt`),
`Uncaught Exception at ${new Date().toISOString()}\n\n${err?.stack || err}\n`);
} catch (_) {}
// Attempt graceful cleanup before exit
try { playwrightBrowser.dispose(); } catch (_) {}
try { terminalManager.disposeAll(); } catch (_) {}
try { browserManager.dispose(); } catch (_) {}
// Show error dialog and exit — continuing after uncaughtException is unsafe
try {
dialog.showErrorBox('guIDE — Fatal Error',
`An unexpected error occurred. The application will restart.\n\n${err?.message || err}\n\nCrash details saved to:\n${path.join(app.getPath('userData'), 'crash-logs')}`);
} catch (_) {}
app.exit(1);
});
process.on('unhandledRejection', (reason) => {
console.error('[IDE] Unhandled rejection:', reason);
// Log but don't exit — unhandled rejections are recoverable
try {
const crashDir = path.join(app.getPath('userData'), 'crash-logs');
fsSync.mkdirSync(crashDir, { recursive: true });
const ts = new Date().toISOString().replace(/[:.]/g, '-');
fsSync.writeFileSync(path.join(crashDir, `rejection-${ts}.txt`),
`Unhandled Rejection at ${new Date().toISOString()}\n\n${reason?.stack || reason}\n`);
} catch (_) {}
});
app.whenReady().then(() => {
// ─── Startup Integrity & Watermark ───────────────────────────────
console.log('');
console.log(' ╔═══════════════════════════════════════════════════╗');
console.log(' ║ guIDE — AI-Powered Offline IDE ║');
console.log(' ║ Copyright © 2025-2026 Brendan Gray ║');
console.log(' ║ GitHub: github.com/FileShot ║');
console.log(' ║ Licensed under Source Available License ║');
console.log(' ║ Unauthorized redistribution/rebranding prohibited ║');
console.log(' ╚═══════════════════════════════════════════════════╝');
console.log('');
// Runtime integrity checks — verify branding was not tampered
const _appDir = app.getAppPath();
const integrityChecks = [
() => _B.n === 'guIDE',
() => _B.a === 'Brendan Gray',
() => _B.g === 'FileShot',
() => _B.y.startsWith('2025'),
() => {
try {
const pkg = JSON.parse(fsSync.readFileSync(path.join(_appDir, 'package.json'), 'utf8'));
return pkg.name === 'guide-ide' && (pkg.author || '').includes('Brendan');
} catch { return false; }
},
() => {
try {
const lic = fsSync.readFileSync(path.join(_appDir, 'LICENSE'), 'utf8');
return lic.includes('Brendan Gray') && lic.includes('guIDE');
} catch { return false; }
},
];
const passed = integrityChecks.filter(c => { try { return c(); } catch { return false; } }).length;
// Allow minor tolerance (5/6) — LICENSE or package.json may not always be present in all build configurations
if (passed < integrityChecks.length - 1) {
console.warn(`[guIDE] [!] Integrity: ${passed}/${integrityChecks.length} checks passed`);
dialog.showMessageBoxSync({
type: 'warning',
title: 'guIDE — Integrity Warning',
message: 'This copy of guIDE may have been tampered with.',
detail: 'guIDE is created by Brendan Gray (github.com/FileShot).\n\nRedistribution, rebranding, or resale is prohibited\nunder the Source Available License.\n\nVisit github.com/FileShot for the official release.',
});
}
console.log('[IDE] App ready, creating window...');
createWindow();
}).catch((err) => {
console.error('[IDE] Failed to create window:', err);
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
app.on('before-quit', () => {
// Synchronous cleanup — Electron does not await async before-quit handlers
try { playwrightBrowser.dispose(); } catch (_) {}
try { terminalManager.disposeAll(); } catch (_) {}
try { browserManager.dispose(); } catch (_) {}
try { modelManager.dispose(); } catch (_) {}
try { log.close(); } catch (_) {} // Flush persistent log file
// Fire-and-forget async cleanup with a hard deadline
const cleanupDone = Promise.all([
Promise.resolve(memoryStore.dispose()).catch(() => {}),
llmEngine.dispose().catch(() => {}),
]);
// Give async cleanup 3 seconds max, then force exit
const forceTimer = setTimeout(() => {
console.log('[IDE] Shutdown timeout — forcing exit');
process.exit(0);
}, 3000);
forceTimer.unref(); // Don't keep the process alive just for this timer
cleanupDone.then(() => clearTimeout(forceTimer)).catch(() => {});
});
app.on('web-contents-created', (_, contents) => {
contents.on('will-navigate', (event, url) => {
// Allow navigations in non-default sessions (OAuth windows, etc.)
// OAuth uses session.fromPartition('oauth-signin') which is non-persistent,
// so storagePath is null — compare by identity instead.
if (contents.session !== session.defaultSession) return;
event.preventDefault();
});
});