-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathelectron-main.js
More file actions
1682 lines (1571 loc) · 76.1 KB
/
electron-main.js
File metadata and controls
1682 lines (1571 loc) · 76.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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* guIDE 2.0 — Electron Main Process (IPC Architecture)
*
* All services run in-process. All communication via Electron IPC.
* No child process fork, no HTTP server, no WebSocket.
*
* This replaces the old electron-main.js that forked server/main.js.
*/
'use strict';
const { app, BrowserWindow, shell, ipcMain, dialog, safeStorage } = require('electron');
const path = require('path');
const fs = require('fs');
const fsP = require('fs').promises;
const os = require('os');
const http = require('http');
const { buildAppMenu } = require('./appMenu');
const { AutoUpdater } = require('./autoUpdater');
// ─── GPU / V8 flags ─────────────────────────────────────────────────
app.commandLine.appendSwitch('disable-gpu-sandbox');
app.commandLine.appendSwitch('ignore-gpu-blocklist');
app.commandLine.appendSwitch('js-flags', '--max-old-space-size=4096');
let mainWindow = null;
// ─── Paths ───────────────────────────────────────────────────────────
const ROOT_DIR = __dirname;
const MODELS_DIR = path.join(ROOT_DIR, 'models');
const FRONTEND_DIST = path.join(ROOT_DIR, 'frontend', 'dist');
// ─── Loading screen ──────────────────────────────────────────────────
const LOADING_HTML = `<!DOCTYPE html>
<html><head><meta charset="UTF-8">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Audiowide&display=swap" rel="stylesheet">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body {
height: 100%; background: #0d0d0d; color: #e5e7eb;
font-family: 'Audiowide', 'Courier New', monospace;
display: flex; align-items: center; justify-content: center;
flex-direction: column; gap: 20px;
-webkit-app-region: drag; user-select: none;
}
.logo { font-size: 26px; font-weight: 400; letter-spacing: 2px; color: #fff; }
.logo span { color: #4f9cf9; }
.spinner {
width: 28px; height: 28px;
border: 3px solid #2a2a2a; border-top-color: #4f9cf9;
border-radius: 50%; animation: spin 0.75s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
.sub { font-size: 12px; color: #4b5563; font-family: -apple-system, sans-serif; }
</style></head><body>
<div class="logo">gu<span>IDE</span></div>
<div class="spinner"></div>
<div class="sub">Loading...</div>
</body></html>`;
// ─── Create window ───────────────────────────────────────────────────
function createWindow() {
mainWindow = new BrowserWindow({
width: 1400,
height: 900,
minWidth: 900,
minHeight: 600,
title: 'guIDE',
icon: path.join(__dirname, 'build', 'icon.ico'),
backgroundColor: '#0d0d0d',
frame: false,
titleBarStyle: 'hidden',
autoHideMenuBar: true,
show: false,
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
sandbox: false,
preload: path.join(app.getAppPath(), 'preload.js'),
},
});
// Show loading screen while services initialize
mainWindow.loadURL('data:text/html,' + encodeURIComponent(LOADING_HTML));
mainWindow.once('ready-to-show', () => {
mainWindow.show();
mainWindow.focus();
});
mainWindow.on('closed', () => { mainWindow = null; });
// Forward maximize/unmaximize state to the renderer as an event so the
// TitleBar can subscribe instead of polling isMaximized() every 500ms.
const _emitWinState = () => {
if (!mainWindow || mainWindow.isDestroyed()) return;
const maximized = mainWindow.isMaximized();
try { mainWindow.webContents.send('win-state', { maximized }); } catch (_) {}
};
mainWindow.on('maximize', _emitWinState);
mainWindow.on('unmaximize', _emitWinState);
mainWindow.on('enter-full-screen', _emitWinState);
mainWindow.on('leave-full-screen', _emitWinState);
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
if (url.startsWith('file://')) return { action: 'allow' };
shell.openExternal(url);
return { action: 'deny' };
});
}
// ─── Window control IPC ─────────────────────────────────────────────
ipcMain.handle('win-minimize', () => { mainWindow?.minimize(); });
ipcMain.handle('win-maximize', () => {
if (mainWindow?.isMaximized()) mainWindow.unmaximize();
else mainWindow?.maximize();
});
ipcMain.handle('win-close', () => { mainWindow?.close(); });
ipcMain.handle('win-is-maximized', () => mainWindow?.isMaximized() ?? false);
// ─── New window ──────────────────────────────────────────────────────
ipcMain.handle('new-window', () => {
const { spawn } = require('child_process');
spawn(process.execPath, process.argv.slice(1), {
detached: true,
stdio: 'ignore',
env: { ...process.env },
}).unref();
});
// ─── Dialog IPC ─────────────────────────────────────────────────────
ipcMain.handle('dialog-open-folder', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openDirectory'],
title: 'Open Folder',
});
if (result.canceled || !result.filePaths.length) return null;
return result.filePaths[0];
});
ipcMain.handle('dialog-models-add', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openFile', 'multiSelections'],
title: 'Select Model Files',
filters: [
{ name: 'GGUF Models', extensions: ['gguf'] },
{ name: 'All Files', extensions: ['*'] },
],
});
if (result.canceled || !result.filePaths.length) return { success: false };
try {
await modelManager.addModels(result.filePaths);
return { success: true, filePaths: result.filePaths };
} catch (e) {
return { success: false, error: e.message };
}
});
ipcMain.handle('shell-show-item', (_event, fullPath) => {
if (typeof fullPath === 'string' && fullPath.length > 0) {
shell.showItemInFolder(fullPath);
}
});
ipcMain.handle('shell-open-external', (_event, url) => {
if (typeof url === 'string' && url.startsWith('http')) {
shell.openExternal(url);
}
});
// ─── Load modules ──────────────────────────────────────────
const userDataPath = app.getPath('userData');
const modelsBasePath = app.isPackaged ? userDataPath : ROOT_DIR;
// Ensure directories
for (const dir of [MODELS_DIR, userDataPath, path.join(userDataPath, 'sessions'), path.join(userDataPath, 'logs')]) {
try { fs.mkdirSync(dir, { recursive: true }); } catch (_) {}
}
const log = require('./logger');
log.installConsoleIntercepts();
const { ChatEngine, buildEngineLoadSettings } = require('./chatEngine');
const { resolveRuntimeDefaultsForModel } = require('./modelRuntimeDefaults');
/** Apply per-model runtime defaults (e.g. GLM-4.6V → thinking off) before load. */
function applyModelRuntimeDefaults(modelPath) {
const { thinkingMode, reason } = resolveRuntimeDefaultsForModel(modelPath);
const prev = settingsManager.get('thinkingMode');
if (thinkingMode !== prev) {
settingsManager.set('thinkingMode', thinkingMode);
settingsManager.flush();
console.log(`[Settings] model runtime default: thinkingMode "${prev}" -> "${thinkingMode}" (${reason}) file=${path.basename(modelPath)}`);
}
}
const { MCPToolServer } = require('./mcpToolServer');
const { ModelManager } = require('./modelManager');
const { MemoryStore } = require('./memoryStore');
const { LongTermMemory } = require('./longTermMemory');
const { RulesManager } = require('./rulesManager');
const { SessionStore } = require('./sessionStore');
const { CloudLLMService } = require('./cloudLLMService');
const { runCloudAgenticChat } = require('./cloudAgenticChat');
const { runOAuthInWindow } = require('./oauthFlow');
const { SettingsManager } = require('./settingsManager');
const { GitManager } = require('./gitManager');
const { BrowserManager } = require('./browserManager');
const { FirstRunSetup } = require('./firstRunSetup');
const { RAGEngine } = require('./ragEngine');
const { AccountManager } = require('./accountManager');
const { LicenseManager } = require('./licenseManager');
const { ExtensionManager } = require('./extensionManager');
const { DebugService } = require('./debugService');
const { ModelDownloader } = require('./server/modelDownloader');
const liveServer = require('./server/liveServer');
const WebSearch = require('./webSearch');
const { TEMPLATES } = require('./server/templateHandlers');
// ─── Initialize services ────────────────────────────────────────────
const llmEngine = new ChatEngine();
const webSearch = new WebSearch();
const ragEngine = new RAGEngine();
const mcpToolServer = new MCPToolServer({ projectPath: null, webSearch, ragEngine });
const gitManager = new GitManager();
const memoryStore = new MemoryStore();
const longTermMemory = new LongTermMemory();
const rulesManager = new RulesManager();
const modelManager = new ModelManager(modelsBasePath);
const sessionStore = new SessionStore(path.join(userDataPath, 'sessions'));
const cloudLLM = new CloudLLMService();
const modelDownloader = new ModelDownloader(path.join(ROOT_DIR, 'models'));
const settingsManager = new SettingsManager(userDataPath);
const firstRunSetup = new FirstRunSetup(settingsManager);
const accountManager = new AccountManager(settingsManager);
const licenseManager = new LicenseManager(settingsManager, accountManager);
const extensionManager = new ExtensionManager(userDataPath);
const debugService = new DebugService();
// BrowserManager needs mainWindow reference for event forwarding
const browserManager = new BrowserManager({
liveServer,
parentWindow: { webContents: { send: (e, d) => _send(e, d) }, isDestroyed: () => !mainWindow },
});
// Wire service cross-references
mcpToolServer.setBrowserManager(browserManager);
mcpToolServer.setGitManager(gitManager);
mcpToolServer.rulesManager = rulesManager;
mcpToolServer.onTodoUpdate = (todos) => _send('todo-update', todos);
mcpToolServer.onAskQuestion = (questionData) => {
return new Promise((resolve) => {
// Send question to frontend
_send('ask-question', questionData);
// Store the resolver so the answer IPC can pick it up
mcpToolServer._pendingQuestionResolve = resolve;
});
};
cloudLLM.setLicenseManager(licenseManager);
// Restore persisted API keys
const savedKeys = settingsManager.getAllApiKeys();
for (const [provider, key] of Object.entries(savedKeys)) {
if (key && key.trim()) {
cloudLLM.setApiKey(provider, key);
}
}
// License state already restored in LicenseManager constructor
// Initialize extensions (async, non-blocking)
extensionManager.initialize().catch(err => console.error('[Main] Extension init error:', err.message));
let currentSettings = settingsManager.getAll();
let currentProjectPath = null;
let agenticCancelled = false;
let autoUpdater = null;
async function openProjectPath(projectPath) {
console.log(`[electron-main] openProjectPath START: ${projectPath}`);
const resolved = path.resolve(projectPath);
if (!fs.existsSync(resolved)) {
console.error(`[electron-main] openProjectPath: directory not found ${resolved}`);
const error = new Error('Directory not found');
error.statusCode = 404;
throw error;
}
currentProjectPath = resolved;
ctx.currentProjectPath = resolved;
mcpToolServer.projectPath = resolved;
gitManager.setProjectPath(resolved);
memoryStore.initialize(resolved);
longTermMemory.initialize(resolved);
rulesManager.initialize(resolved);
ragEngine.indexProject(resolved).catch(e => console.warn('[Main] RAG indexing failed:', e.message));
_send('project-opened', { path: resolved });
console.log(`[electron-main] openProjectPath DONE: ${resolved}`);
return { path: resolved };
}
// Helper to send events to renderer
function _send(event, data) {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send(event, data);
}
// Drop silently during shutdown — window destroyed is expected, not an error.
}
const ctx = {
llmEngine,
mcpToolServer,
memoryStore,
longTermMemory,
modelManager,
sessionStore,
userDataPath,
get currentProjectPath() { return currentProjectPath; },
set currentProjectPath(v) { currentProjectPath = v; },
get agenticCancelled() { return agenticCancelled; },
set agenticCancelled(v) { agenticCancelled = v; },
getMainWindow: () => mainWindow,
cloudLLM,
playwrightBrowser: null,
browserManager,
ragEngine,
webSearch,
licenseManager,
_truncateResult: (result) => {
if (!result) return result;
const str = typeof result === 'string' ? result : JSON.stringify(result);
return str.length > 8000 ? str.substring(0, 8000) + '...[truncated]' : result;
},
_readConfig: () => currentSettings,
};
// ─── App metadata ───────────────────────────────────────────────────
ipcMain.handle('get-app-version', () => app.getVersion());
// ─── Rules/Skills API ───────────────────────────────────────────────
ipcMain.handle('rules-list', () => rulesManager.listRules());
ipcMain.handle('rules-save', (_e, name, content) => rulesManager.saveRule(name, content));
ipcMain.handle('rules-delete', (_e, name) => rulesManager.deleteRule(name));
// Register ai-chat handler for basic model chat
ipcMain.handle('ai-chat', async (_event, userMessage, chatContext) => {
console.log(`[electron-main] ai-chat START: userMessageLen=${String(userMessage).length}, cloudProvider=${chatContext?.cloudProvider || 'none'}`);
const cloudProvider = chatContext?.cloudProvider;
const cloudModel = chatContext?.cloudModel;
// ── Cloud provider path (agentic tools + same system/tool prompt as local) ──
if (cloudProvider) {
try {
console.log(`[electron-main] ai-chat: cloud path provider=${cloudProvider}`);
agenticCancelled = false;
const settings = chatContext?.params || chatContext?.settings || {};
const attachments = Array.isArray(chatContext?.attachments) ? chatContext.attachments : [];
const images = attachments.filter(a => (a.mimeType || a.type || '').startsWith('image/'));
const conversationHistory = [];
const chatMsgs = chatContext?.chatMessages || [];
const userText = String(userMessage).trim();
for (let i = 0; i < chatMsgs.length; i++) {
const m = chatMsgs[i];
if (m.role !== 'user' && m.role !== 'assistant') continue;
const isLast = i === chatMsgs.length - 1;
if (isLast && m.role === 'user' && String(m.content || '').trim() === userText) continue;
const content = String(m.content || '').trim();
if (!content) continue;
conversationHistory.push({ role: m.role, content: m.content });
}
console.log(
`[electron-main] cloud conversationHistory: ${conversationHistory.length} msgs from ${chatMsgs.length} chat bubbles`
);
const currentFile = chatContext?.currentFile;
let effectiveMessage = userMessage;
if (currentFile?.path && currentFile?.content != null) {
const MAX_FILE_CONTEXT = 4000;
const truncated = currentFile.content.length > MAX_FILE_CONTEXT
? currentFile.content.slice(0, MAX_FILE_CONTEXT) + '\n… [truncated — use read_file to see the full file]'
: currentFile.content;
effectiveMessage = userMessage + `\n\n[Current file: ${currentFile.path}]\n${truncated}`;
}
const askOnly = !!(settings.askOnly);
const planMode = !!(settings.planMode);
const enableSubAgents = !!(settings.enableSubAgents);
const executeToolFn = async (toolName, params) => {
if (toolName === 'spawn_subagent') {
return { success: false, error: 'Sub-agents require a loaded local model. Switch to local or disable sub-agents.' };
}
return await mcpToolServer.executeTool(toolName, params);
};
const result = await runCloudAgenticChat({
cloudLLM,
mcpToolServer,
ChatEngine,
userMessage: effectiveMessage,
cloudProvider,
cloudModel,
settings: { ...settings, askOnly, planMode, enableSubAgents, toolsEnabled: settings.toolsEnabled !== false },
conversationHistory,
images,
executeToolFn,
onToken: (token) => _send('llm-token', token),
onThinkingToken: (token) => _send('llm-thinking-token', token),
onStreamEvent: (eventName, data) => _send(eventName, data),
getCancelled: () => agenticCancelled,
});
if (result?.isQuotaError) {
return { isQuotaError: true, error: '__QUOTA_EXCEEDED__' };
}
return { text: result.text || '', toolCallCount: result.toolCallCount || 0 };
} catch (err) {
console.error(`[electron-main] ai-chat cloud ERROR: ${err.message}`);
if (err.isQuotaError) return { isQuotaError: true, error: '__QUOTA_EXCEEDED__' };
return { error: err.message };
}
}
// ── Local model path ─────────────────────────────────────────────────
if (llmEngine.isLoading || llmEngine.getStatus().loadState === 'loading' || llmEngine.getStatus().loadState === 'disposing') {
console.warn('[electron-main] ai-chat: model load in progress');
return { error: 'Model is loading — please wait and try again.' };
}
if (!llmEngine.isReady) {
console.warn('[electron-main] ai-chat: no model loaded');
return { error: 'No model loaded. Please load a model first.' };
}
try {
console.log('[electron-main] ai-chat: local model path');
agenticCancelled = false;
const settings = chatContext?.params || chatContext?.settings || {};
const askOnly = !!(settings.askOnly);
const planMode = !!(settings.planMode);
const enableSubAgents = !!(settings.enableSubAgents);
const autoLintFix = settings.autoLintFix !== false; // default true
// Build tool functions from enabled tool definitions
const toolDefs = mcpToolServer.getToolDefinitions();
const functions = askOnly ? {} : ChatEngine.convertToolDefs(toolDefs);
let toolPrompt = askOnly ? '' : mcpToolServer.getToolPrompt();
const compactToolParts = askOnly ? [] : mcpToolServer.getCompactToolHint('default');
let compactToolPrompt = compactToolParts.join('');
// Sub-agents: append spawn_subagent tool definition when enabled
if (enableSubAgents && toolPrompt) {
const subAgentTool = '\n- **spawn_subagent** — Delegate a focused sub-task to an isolated sub-agent that shares the same loaded model but runs in a fresh context. Use for long research tasks, code analysis, or any work that should not pollute the main context. Params: task (string, required) — description of what the sub-agent should do; contextSize (number, optional) — token budget for sub-agent.';
toolPrompt += subAgentTool;
compactToolPrompt += '\n- spawn_subagent(task): run focused sub-task in fresh context';
compactToolParts.push('\n- spawn_subagent(task): run focused sub-task in fresh context\n');
}
// Inject current file context into the user message so the model can see the active file
// Truncate to avoid consuming all context — model can use read_file for the full content
const currentFile = chatContext?.currentFile;
let effectiveMessage = userMessage;
if (currentFile?.path && currentFile?.content != null) {
const MAX_FILE_CONTEXT = 4000;
const truncated = currentFile.content.length > MAX_FILE_CONTEXT
? currentFile.content.slice(0, MAX_FILE_CONTEXT) + `\n… [truncated — use read_file to see the full file]`
: currentFile.content;
effectiveMessage = userMessage + `\n\n[Current file: ${currentFile.path}]\n${truncated}`;
}
console.log(`[electron-main] ai-chat: calling llmEngine.chat, effectiveMessageLen=${effectiveMessage.length}`);
const result = await llmEngine.chat(effectiveMessage, {
onToken: (token) => _send('llm-token', token),
onContextUsage: (data) => _send('context-usage', data),
onToolCall: (data) => _send('tool-call', data),
onStreamEvent: (eventName, data) => _send(eventName, data),
attachments: Array.isArray(chatContext?.attachments) ? chatContext.attachments : [],
functions,
toolPrompt,
compactToolPrompt,
compactToolParts,
executeToolFn: async (toolName, params) => {
if (toolName === 'spawn_subagent') {
if (!enableSubAgents) return { success: false, error: 'Sub-agents are disabled. Enable in Settings > Agentic Behavior.' };
return await llmEngine.spawnSubAgent(String(params?.task || ''), {
contextSize: params?.contextSize,
temperature: settings.temperature,
});
}
return await mcpToolServer.executeTool(toolName, params);
},
systemPrompt: settings.systemPrompt || undefined,
customInstructions: settings.customInstructions || undefined,
guideInstructionsPath: settings.guideInstructionsPath || undefined,
temperature: settings.temperature,
temperatureIsDefault: settings.temperature === settings._defaultTemperature,
maxTokens: settings.maxTokens || -1,
topP: settings.topP,
topK: settings.topK,
repeatPenalty: settings.repeatPenalty,
repeatPenaltyIsDefault: settings.repeatPenalty === settings._defaultRepeatPenalty,
seed: settings.seed >= 0 ? settings.seed : undefined,
thinkingBudget: settings.thinkingBudget,
enableThinkingFilter: settings.enableThinkingFilter,
toolsEnabled: settings.toolsEnabled !== false,
enableGrammar: settings.enableGrammar,
enableContextSummarizer: settings.enableContextSummarizer !== false,
maxIterations: settings.maxIterations || 0,
generationTimeoutSec: settings.generationTimeoutSec || 0,
reasoningEffort: settings.reasoningEffort || 'medium',
askOnly,
planMode,
autoLintFix,
});
// Sync guide instructions path to rulesManager so list_rules includes it
if (settings.guideInstructionsPath) {
rulesManager.setGuideInstructionsPath(settings.guideInstructionsPath);
}
console.log(`[electron-main] ai-chat DONE: toolCallCount=${result.toolCallCount}`);
return { text: result.text, toolCallCount: result.toolCallCount };
} catch (err) {
console.error(`[electron-main] ai-chat local ERROR: ${err.message}`);
return { error: err.message };
}
});
// Plan B: Revert backend context to match a truncated frontend message array.
// Called by pencil-edit submit and checkpoint-restore in ChatPanel.jsx.
ipcMain.handle('revert-context', (_e, messages) => {
llmEngine.revertContext(Array.isArray(messages) ? messages : []);
return { success: true };
});
// Swap chat wrapper mode on the fly without reloading the model.
// Resets conversation. Modes: 'C' (ThinkingOpen), 'B' (Jinja no prefix), 'auto', 'off'
ipcMain.handle('set-thinking-mode', async (_e, mode) => {
console.log(`[Settings] set-thinking-mode IPC START mode=${mode}`);
try {
const result = await llmEngine.setWrapperMode(mode);
console.log(`[Settings] set-thinking-mode IPC DONE mode=${mode} success=${!!result?.success}`);
return result;
} catch (err) {
console.error(`[Settings] set-thinking-mode IPC ERROR: ${err.message}`);
return { success: false, error: err.message };
}
});
ipcMain.handle('ui-log', (_e, msg) => {
console.log(`[UI] ${String(msg ?? '')}`);
});
// Handle answer from frontend for ask_question tool
ipcMain.handle('answer-question', (_e, answer) => {
if (mcpToolServer._pendingQuestionResolve) {
const resolve = mcpToolServer._pendingQuestionResolve;
mcpToolServer._pendingQuestionResolve = null;
resolve({ success: true, answer });
}
return { received: true };
});
ipcMain.handle('cancel-generation', async () => {
console.log('[electron-main] cancel-generation');
llmEngine.cancelGeneration('user');
try { mcpToolServer.killActiveChildren('user-cancel'); } catch (_) {}
return { success: true };
});
ipcMain.handle('agent-pause', async () => {
console.log('[electron-main] agent-pause');
llmEngine.cancelGeneration('user');
try { mcpToolServer.killActiveChildren('user-cancel'); } catch (_) {}
return { success: true };
});
ipcMain.handle('force-send-queued', async () => {
console.log('[electron-main] force-send-queued');
llmEngine.cancelGeneration('user');
try { mcpToolServer.killActiveChildren('user-cancel'); } catch (_) {}
return { success: true };
});
ipcMain.handle('inject-user-message', (_e, payload) => {
const text = typeof payload === 'string' ? payload : payload?.text;
console.log(`[electron-main] inject-user-message: len=${String(text ?? '').length}`);
llmEngine.injectUserMessage(text);
return { success: true };
});
// ─── Generic API-fetch IPC handler ──────────────────────────────────
// The frontend's fetch('/api/...') calls are intercepted and routed here.
// This replaces the entire Express REST API from server/main.js.
ipcMain.handle('api-fetch', async (_event, url, options) => {
const _apiT0 = Date.now();
const method = (options?.method || 'GET').toUpperCase();
let body = {};
if (options?.body) {
try { body = typeof options.body === 'string' ? JSON.parse(options.body) : options.body; } catch (_) {}
}
// Parse URL
const urlObj = new URL(url, 'http://localhost');
const p = urlObj.pathname;
const q = Object.fromEntries(urlObj.searchParams);
const _bodyLen = options?.body ? String(options.body).length : 0;
console.log(`[api-fetch] ENTRY ${method} ${p} bodyLen=${_bodyLen}`);
try {
// ── Models ──────────────────────────────────────────
if (p === '/api/models' && method === 'GET') {
return { models: modelManager.availableModels, status: llmEngine.getStatus() };
}
if (p === '/api/models/load' && method === 'POST') {
const { modelPath } = body;
if (!modelPath) return { _status: 400, error: 'modelPath required' };
applyModelRuntimeDefaults(modelPath);
const loadSettings = buildEngineLoadSettings(settingsManager.getAll());
console.log(`[Settings] model-load START path=${modelPath} thinkingMode=${loadSettings.thinkingMode} toolsEnabled=${settingsManager.get('toolsEnabled')} enableThinking=${loadSettings.enableThinking}`);
try { llmEngine.cancelGeneration('model-load'); } catch (_) {}
_send('model-loading', { path: modelPath });
await llmEngine.initialize(modelPath, loadSettings);
const info = llmEngine.modelInfo;
if (info) info.runtimeThinkingMode = settingsManager.get('thinkingMode');
settingsManager.set('lastModelPath', modelPath);
_send('model-loaded', info);
console.log(`[Settings] model-load DONE path=${modelPath} thinkingMode=${settingsManager.get('thinkingMode')}`);
console.log(`[api-fetch] DONE POST /api/models/load ms=${Date.now() - _apiT0}`);
return { success: true, modelInfo: info };
}
if (p === '/api/models/unload' && method === 'POST') {
await llmEngine.dispose();
return { success: true };
}
if (p === '/api/models/status' && method === 'GET') {
return llmEngine.getStatus();
}
if (p === '/api/models/scan' && method === 'POST') {
const models = await modelManager.scanModels();
return { models };
}
if (p === '/api/models/add' && method === 'POST') {
const { filePaths } = body;
if (!filePaths || !Array.isArray(filePaths)) return { _status: 400, error: 'filePaths array required' };
const added = await modelManager.addModels(filePaths);
return { added };
}
if (p === '/api/models/upload' && method === 'POST') {
// IPC file upload: expects body._files = [{ name, buffer }]
const files = body._files;
if (!files || !Array.isArray(files) || files.length === 0) {
return { _status: 400, error: 'No files provided' };
}
const saved = [];
for (const file of files) {
const filename = path.basename(file.name);
if (!filename.endsWith('.gguf')) continue;
const destPath = path.join(MODELS_DIR, filename);
await fsP.writeFile(destPath, Buffer.from(file.buffer));
saved.push(filename);
}
if (saved.length === 0) return { _status: 400, error: 'No .gguf files found in upload' };
await modelManager.scanModels();
return { success: true, saved };
}
if (p === '/api/models/recommend' && method === 'GET') {
let vramMB = 0;
try {
const { execSync } = require('child_process');
const out = execSync('nvidia-smi --query-gpu=memory.total --format=csv,noheader,nounits', { timeout: 5000 }).toString().trim();
vramMB = parseInt(out.split('\n')[0], 10) || 0;
} catch { /* no GPU */ }
const maxModelGB = vramMB > 0 ? Math.floor((vramMB * 0.85) / 1024) : 4;
const recommended = [
{ name: 'Qwen 3.5 0.8B', file: 'Qwen3.5-0.8B-Q8_0.gguf', size: 0.8, desc: 'Tiny, ultra-fast', downloadUrl: 'https://huggingface.co/unsloth/Qwen3.5-0.8B-GGUF/resolve/main/Qwen3.5-0.8B-Q8_0.gguf', tags: ['general'] },
{ name: 'Qwen 3.5 4B', file: 'Qwen3.5-4B-Q8_0.gguf', size: 4.5, desc: 'Great balance', downloadUrl: 'https://huggingface.co/unsloth/Qwen3.5-4B-GGUF/resolve/main/Qwen3.5-4B-Q8_0.gguf', tags: ['coding', 'general'] },
{ name: 'Qwen 3.5 9B', file: 'Qwen3.5-9B-Q4_K_M.gguf', size: 5.7, desc: 'Strong all-rounder', downloadUrl: 'https://huggingface.co/unsloth/Qwen3.5-9B-GGUF/resolve/main/Qwen3.5-9B-Q4_K_M.gguf', tags: ['coding', 'reasoning'] },
{ name: 'Qwen 3.5 27B', file: 'Qwen3.5-27B-Q4_K_M.gguf', size: 16.7, desc: 'High quality', downloadUrl: 'https://huggingface.co/unsloth/Qwen3.5-27B-GGUF/resolve/main/Qwen3.5-27B-Q4_K_M.gguf', tags: ['coding', 'reasoning'] },
{ name: 'Qwen 3.5 35B-A3B (MoE)', file: 'Qwen3.5-35B-A3B-Q4_K_M.gguf', size: 22.0, desc: 'MoE, fast for size', downloadUrl: 'https://huggingface.co/unsloth/Qwen3.5-35B-A3B-GGUF/resolve/main/Qwen3.5-35B-A3B-Q4_K_M.gguf', tags: ['coding', 'reasoning'] },
];
const fits = recommended.filter(m => m.size <= maxModelGB);
const other = recommended.filter(m => m.size > maxModelGB);
return { fits, other, maxModelGB, vramMB };
}
// ── HuggingFace model downloads ─────────────────────
if (p === '/api/models/hf/search' && method === 'GET') {
const query = q.q;
if (!query || !query.trim()) return { models: [] };
const models = await modelDownloader.searchModels(query.trim());
return { models };
}
if (p.startsWith('/api/models/hf/files/') && method === 'GET') {
const parts = p.replace('/api/models/hf/files/', '').split('/');
const repoId = parts.slice(0, 2).join('/');
const result = await modelDownloader.getRepoFiles(repoId);
return result;
}
if (p === '/api/models/hf/download' && method === 'POST') {
const { url: dlUrl, fileName } = body;
if (!dlUrl || !fileName) return { _status: 400, error: 'url and fileName required' };
const result = await modelDownloader.downloadModel(dlUrl, fileName);
return { success: true, ...result };
}
if (p === '/api/models/hf/cancel' && method === 'POST') {
const { id } = body;
if (!id) return { _status: 400, error: 'id required' };
return { success: modelDownloader.cancelDownload(id) };
}
if (p === '/api/models/hf/downloads' && method === 'GET') {
return { downloads: modelDownloader.getActiveDownloads() };
}
// ── GPU ─────────────────────────────────────────────
if (p === '/api/gpu' && method === 'GET') {
// Plan 8 instrumentation — track frequency of /api/gpu so we can identify
// any caller that polls more often than the StatusBar's 60s schedule.
// Logs once per call with the elapsed time since the previous call. The
// upstream caller stack lives in chatEngine.getGPUInfo (also instrumented).
try {
const _now = Date.now();
if (!global.__guideGpuApiLast) global.__guideGpuApiLast = 0;
const _delta = global.__guideGpuApiLast ? (_now - global.__guideGpuApiLast) : 0;
global.__guideGpuApiLast = _now;
console.log(`[Main] /api/gpu hit (delta=${_delta}ms since last)`);
} catch (_) {}
const info = await llmEngine.getGPUInfo();
const totalMem = os.totalmem();
const freeMem = os.freemem();
info.ramTotalGB = (totalMem / (1024 ** 3)).toFixed(1);
info.ramUsedGB = ((totalMem - freeMem) / (1024 ** 3)).toFixed(1);
const cpus = os.cpus();
let totalIdle = 0, totalTick = 0;
for (const cpu of cpus) {
for (const type in cpu.times) totalTick += cpu.times[type];
totalIdle += cpu.times.idle;
}
info.cpuUsage = Math.round(100 - (totalIdle / totalTick * 100));
if (llmEngine.modelInfo) {
if (typeof llmEngine.modelInfo.gpuLayers === 'number') {
info.gpuLayers = llmEngine.modelInfo.gpuLayers;
}
if (typeof llmEngine.modelInfo.contextSize === 'number') {
info.modelContextSize = llmEngine.modelInfo.contextSize;
}
if (typeof llmEngine.modelInfo.totalLayers === 'number') {
info.totalLayers = llmEngine.modelInfo.totalLayers;
}
}
return info;
}
// ── Project ─────────────────────────────────────────
if (p === '/api/project/open' && method === 'POST') {
const { projectPath } = body;
if (!projectPath) return { _status: 400, error: 'projectPath required' };
const openedProject = await openProjectPath(projectPath);
return { success: true, path: openedProject.path };
}
if (p === '/api/project/current' && method === 'GET') {
return { projectPath: currentProjectPath };
}
// ── Files ───────────────────────────────────────────
if (p === '/api/files/tree' && method === 'GET') {
const dirPath = q.path || currentProjectPath;
if (!dirPath) return { items: [] };
const items = await _readDirRecursive(dirPath, 0, 3);
return { items, root: dirPath };
}
if (p === '/api/files/read' && method === 'GET') {
const filePath = q.path;
if (!filePath) return { _status: 400, error: 'path required' };
const fullPath = path.isAbsolute(filePath) ? filePath : path.join(currentProjectPath || '', filePath);
try {
const content = fs.readFileSync(fullPath, 'utf8');
const ext = path.extname(fullPath).slice(1);
return { content, path: fullPath, extension: ext, name: path.basename(fullPath) };
} catch (err) {
if (err.code === 'ENOENT') {
return { content: null, path: fullPath, missing: true, name: path.basename(fullPath) };
}
throw err;
}
}
if (p === '/api/files/write' && method === 'POST') {
const { filePath, content } = body;
if (!filePath) return { _status: 400, error: 'filePath required' };
const fullPath = path.isAbsolute(filePath) ? filePath : path.join(currentProjectPath || '', filePath);
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
fs.writeFileSync(fullPath, content || '', 'utf8');
return { success: true, path: fullPath };
}
if (p === '/api/files/create' && method === 'POST') {
const { path: fp, content } = body;
if (!fp) return { _status: 400, error: 'path required' };
const fullPath = path.isAbsolute(fp) ? fp : path.join(currentProjectPath || '', fp);
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
if (fs.existsSync(fullPath)) return { _status: 409, error: 'File already exists' };
fs.writeFileSync(fullPath, content || '', 'utf8');
if (mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send('files-changed');
return { success: true, path: fullPath };
}
if (p === '/api/files/delete' && method === 'POST') {
const { path: fp } = body;
if (!fp) return { _status: 400, error: 'path required' };
const fullPath = path.isAbsolute(fp) ? fp : path.join(currentProjectPath || '', fp);
if (!fs.existsSync(fullPath)) return { _status: 404, error: 'Not found' };
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
fs.rmSync(fullPath, { recursive: true, force: true });
} else {
fs.unlinkSync(fullPath);
}
if (mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send('files-changed');
return { success: true };
}
if (p === '/api/files/rename' && method === 'POST') {
const { oldPath, newPath } = body;
if (!oldPath || !newPath) return { _status: 400, error: 'oldPath and newPath required' };
const fullOld = path.isAbsolute(oldPath) ? oldPath : path.join(currentProjectPath || '', oldPath);
const fullNew = path.isAbsolute(newPath) ? newPath : path.join(currentProjectPath || '', newPath);
if (!fs.existsSync(fullOld)) return { _status: 404, error: 'Source not found' };
fs.renameSync(fullOld, fullNew);
if (mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send('files-changed');
return { success: true, path: fullNew };
}
if (p === '/api/files/search' && method === 'GET') {
const basePath = q.path || currentProjectPath;
const query = q.query;
const semantic = q.semantic === 'true';
if (!basePath || !query) return { results: [] };
const results = [];
const maxResults = 200;
const searchDir = (dir, depth = 0) => {
if (depth > 6 || results.length >= maxResults) return;
let entries;
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch (_) { return; }
for (const entry of entries) {
if (results.length >= maxResults) break;
if (entry.name.startsWith('.') && entry.name !== '.env') continue;
if (['node_modules', '__pycache__', '.git', 'dist', 'build', '.next', 'target'].includes(entry.name)) continue;
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
searchDir(fullPath, depth + 1);
} else if (entry.isFile()) {
try {
const stat = fs.statSync(fullPath);
if (stat.size > 1024 * 1024) continue;
const content = fs.readFileSync(fullPath, 'utf8');
const lines = content.split('\n');
const lowerQuery = query.toLowerCase();
// Collect all matching lines with context
const matches = [];
for (let i = 0; i < lines.length && matches.length < 50; i++) {
if (lines[i].toLowerCase().includes(lowerQuery)) {
matches.push({ line: i + 1, text: lines[i].trim().substring(0, 200), lineText: lines[i] });
}
}
if (matches.length > 0) {
// Compute semantic score for the file
let semanticScore = matches.length; // base: more matches = more relevant
if (semantic) {
const lowerContent = content.toLowerCase();
const queryTerms = query.toLowerCase().split(/\s+/).filter(t => t.length > 1);
// TF-IDF-ish: boost if query terms appear in identifiers/definitions
for (const term of queryTerms) {
// Boost: function/class/method definitions containing the term
const defPattern = new RegExp(`(?:function|class|def|const|let|var|interface|type|enum)\\s+\\w*${term}\\w*`, 'gi');
const defMatches = lowerContent.match(defPattern);
if (defMatches) semanticScore += defMatches.length * 3;
// Boost: comments/docstrings containing the term
const commentPattern = new RegExp(`(?:\\/\\/|#|\\/\\*|\\*|"""|''')\\s*.*${term}`, 'gi');
const commentMatches = lowerContent.match(commentPattern);
if (commentMatches) semanticScore += commentMatches.length * 1.5;
// Boost: export/public API containing the term
const exportPattern = new RegExp(`(?:export|public|module\\.exports)\\s+\\w*${term}\\w*`, 'gi');
const exportMatches = lowerContent.match(exportPattern);
if (exportMatches) semanticScore += exportMatches.length * 2;
}
// Penalize very large files (diluted relevance)
if (lines.length > 500) semanticScore *= 0.7;
}
for (const m of matches) {
results.push({ file: fullPath, line: m.line, text: m.text, score: semanticScore });
}
}
} catch (_) {}
}
}
};
searchDir(basePath);
// Sort by semantic score (descending) if semantic mode, otherwise keep file order
if (semantic) {
results.sort((a, b) => (b.score || 0) - (a.score || 0));
}
return { results: results.slice(0, maxResults) };
}
// ── Settings ────────────────────────────────────────
if (p === '/api/settings' && method === 'GET') {
return settingsManager.getAll();
}
if (p === '/api/settings' && method === 'POST') {
console.log(`[Settings] POST /api/settings HANDLER START thinkingMode=${body?.thinkingMode} toolsEnabled=${body?.toolsEnabled}`);
settingsManager.setAll(body);
settingsManager.flush();
currentSettings = settingsManager.getAll();
console.log(`[Settings] POST /api/settings HANDLER DONE thinkingMode=${settingsManager.get('thinkingMode')}`);
console.log(`[api-fetch] DONE POST /api/settings ms=${Date.now() - _apiT0}`);
return { success: true };
}
// ── Cloud LLM ───────────────────────────────────────
if (p === '/api/cloud/status' && method === 'GET') {
return cloudLLM.getStatus();
}
if (p === '/api/cloud/providers' && method === 'GET') {
return { configured: cloudLLM.getConfiguredProviders(), all: cloudLLM.getAllProviders() };
}
if (p.startsWith('/api/cloud/models/') && method === 'GET') {
const provider = p.replace('/api/cloud/models/', '');
if (provider === 'openrouter') {
const models = await cloudLLM.fetchOpenRouterModels();
return { models };
} else if (provider === 'ollama') {
await cloudLLM.detectOllama();
return { models: cloudLLM.getOllamaModels() };
} else {
return { models: cloudLLM._getProviderModels(provider) };
}
}
if (p === '/api/cloud/provider' && method === 'POST') {
const { provider, model } = body;
if (!provider) return { _status: 400, error: 'provider required' };
cloudLLM.activeProvider = provider;
if (model) cloudLLM.activeModel = model;
return { success: true, activeProvider: cloudLLM.activeProvider, activeModel: cloudLLM.activeModel };
}
if (p === '/api/cloud/apikey' && method === 'POST') {
const { provider, key } = body;
if (!provider) return { _status: 400, error: 'provider required' };
cloudLLM.setApiKey(provider, key || '');
settingsManager.setApiKey(provider, key || '');
return { success: true, hasKey: !!(key && key.trim()) };
}
if (p.startsWith('/api/cloud/pool/') && method === 'GET') {
const provider = p.replace('/api/cloud/pool/', '');
return cloudLLM.getPoolStatus(provider);
}
if (p.startsWith('/api/cloud/test/') && method === 'GET') {
const provider = p.replace('/api/cloud/test/', '');
if (!provider) return { success: false, error: 'provider required' };
const key = cloudLLM.apiKeys[provider];
if (!key) return { success: false, error: 'No API key set' };
const models = cloudLLM._getProviderModels(provider);
const testModel = models[0]?.id;
if (!testModel) return { success: false, error: 'No models for provider' };
const prevProvider = cloudLLM.activeProvider;
const prevModel = cloudLLM.activeModel;
cloudLLM.activeProvider = provider;
cloudLLM.activeModel = testModel;
try {
await Promise.race([
cloudLLM.generate([{ role: 'user', content: 'Say hi' }], { maxTokens: 5, stream: false }),
new Promise((_, rej) => setTimeout(() => rej(new Error('Timeout after 15s')), 15000)),
]);
return { success: true };
} catch (e) {
return { success: false, error: e.message };
} finally {
cloudLLM.activeProvider = prevProvider;
cloudLLM.activeModel = prevModel;
}
}
// ── Git ──────────────────────────────────────────────
if (p === '/api/git/status' && method === 'GET') {
const basePath = q.path || currentProjectPath;
if (!basePath) return { error: 'No project path' };
try {
return gitManager.getStatus(basePath);
} catch (e) {
return { error: e.message, branch: '', staged: [], modified: [], untracked: [] };
}
}
if (p === '/api/git/stage' && method === 'POST') {
const basePath = body.path || currentProjectPath;
if (!basePath) return { _status: 400, error: 'No project path' };
if (body.all) {
gitManager.stageAll(basePath);
} else if (body.files && Array.isArray(body.files)) {
gitManager.stageFiles(body.files, basePath);
} else {
return { _status: 400, error: 'Provide files array or all:true' };
}
return { success: true };