Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
1990 lines (1749 loc) · 68.1 KB
/
Copy pathmain.js
File metadata and controls
1990 lines (1749 loc) · 68.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
const path = require("path");
const fs = require("fs");
const { fileURLToPath } = require("url");
const { app, BrowserWindow, globalShortcut, session, ipcMain } = require("electron");
// ── Resolve a stable .env location ──
// In packaged builds process.cwd() is unstable and frequently read-only
// (NSIS install dir, AppImage mount, .app bundle), so the canonical config
// lives in Electron's userData directory. We still prefer an existing
// project-local .env in development (npm start) so the dev workflow is
// unchanged. Both onboarding (FirstRunManager) and persistEnvUpdates() write
// to this same path so settings survive restarts on every platform.
function resolveEnvPath() {
try {
const userDataEnv = path.join(app.getPath("userData"), ".env");
const projectEnv = path.join(process.cwd(), ".env");
// Prefer a project .env only when it already exists and userData has none
// (i.e. a developer running from the repo). Otherwise use userData.
if (!fs.existsSync(userDataEnv) && fs.existsSync(projectEnv)) {
return projectEnv;
}
return userDataEnv;
} catch (_) {
// On packaged macOS builds, process.cwd() may be inside a read-only .app
// bundle. Fall back to userData so .env writes never fail.
try {
return path.join(app.getPath("userData"), ".env");
} catch (e2) {
return path.join(process.cwd(), ".env");
}
}
}
const ENV_PATH = resolveEnvPath();
require("dotenv").config({ path: ENV_PATH });
// Format a value for a single .env line. Newlines are collapsed to spaces and
// backslashes are kept verbatim (doubling them corrupts Windows paths on the
// next load). Values containing whitespace, a double-quote, or a leading '#'
// are wrapped in single quotes so dotenv parses them as one token — essential
// for Whisper commands like: "C:\Users\Jane Doe\...\python.exe" -m whisper
function formatEnvValue(raw) {
const v = String(raw).replace(/[\r\n]+/g, " ").trim();
if (!/[\s"#]/.test(v)) return v;
if (!v.includes("'")) return `'${v}'`;
// Rare: value already contains a single quote — fall back to double quotes.
return `"${v.replace(/"/g, '\\"')}"`;
}
// ── Linux GPU process crash workaround ──
// On many Linux setups (Wayland, X11 without GPU drivers, Docker, headless,
// or systems with broken Mesa/NVIDIA stacks), Chromium's GPU process crashes
// on startup with:
// FATAL:gpu_data_manager_impl_private.cc(448)] GPU process isn't usable.
// This kills the entire app and can leave orphan helper processes that
// exhaust the X11 client limit, producing "Maximum number of clients reached".
//
// Disabling hardware acceleration and the GPU subprocess forces Chromium to
// render via the CPU (SwiftShader). OpenCluely's UI is light enough that
// this is imperceptible, and it eliminates the GPU crash entirely.
if (process.platform === "linux") {
app.disableHardwareAcceleration();
app.commandLine.appendSwitch("disable-gpu");
app.commandLine.appendSwitch("disable-gpu-compositing");
app.commandLine.appendSwitch("disable-software-rasterizer");
app.commandLine.appendSwitch("disable-gpu-sandbox");
// On X11 only; harmless on Wayland. Prevents Chromium from spawning a
// compositor process that adds another X11 client.
app.commandLine.appendSwitch("in-process-gpu");
}
// Keep Chromium network noise out of the terminal; app-level logs still go through Winston.
app.commandLine.appendSwitch("log-level", "3");
app.commandLine.appendSwitch("disable-background-networking");
app.commandLine.appendSwitch("disable-component-update");
app.commandLine.appendSwitch("disable-domain-reliability");
app.commandLine.appendSwitch("no-pings");
const logger = require("./src/core/logger").createServiceLogger("MAIN");
const config = require("./src/core/config");
const FirstRunManager = require("./src/core/first-run");
// ── Global crash guard ──
// The speech path spawns external processes (Whisper CLI, and on macOS/Linux
// the sox/rec/arecord recorders via node-record-lpcm16). A missing recorder
// binary makes that library emit an 'error' on its child process with no
// listener, which would otherwise become an uncaughtException and quit the
// entire app the moment the user clicks the mic. We log and stay alive — the
// speech service surfaces a friendly status to the UI instead.
process.on("uncaughtException", (err) => {
logger.error("Uncaught exception (kept alive)", {
error: err && err.message,
stack: err && err.stack,
});
});
process.on("unhandledRejection", (reason) => {
logger.error("Unhandled rejection (kept alive)", {
reason: String((reason && reason.message) || reason),
});
});
// Services
// Screen capture (image-based)
const captureService = require("./src/services/capture.service");
const speechService = require("./src/services/speech.service");
const llmService = require("./src/services/llm.service");
// Managers
const windowManager = require("./src/managers/window.manager");
const sessionManager = require("./src/managers/session.manager");
class ApplicationController {
constructor() {
this.isReady = false;
this.starting = false;
this.activeSkill = "dsa";
// Default to C++ so language is enforced from first run
this.codingLanguage = "cpp";
this.speechAvailable = false;
// Utterance coalescing: VAD emits a transcript per natural pause, but a
// single spoken question can still arrive as a few fragments (mid-thought
// pauses). We buffer fragments and debounce so one question yields one LLM
// call instead of several slow, half-answered ones.
this._utteranceBuffer = "";
this._utteranceTimer = null;
this._utteranceDispatchInFlight = false;
this._utteranceCoalesceMs = 800;
// First-run onboarding: detects missing .env / API key and triggers
// a settings-window prompt on first launch so users don't have to
// dig through docs to figure out they need a Gemini API key.
this.firstRunManager = new FirstRunManager({
logger: logger,
// .env and the sentinel both live in userData so they survive cwd
// changes and read-only install dirs (the app may be launched from
// any directory). ENV_PATH is the same file dotenv loaded at startup
// and that persistEnvUpdates() writes to.
envPath: ENV_PATH,
sentinelPath: path.join(app.getPath("userData"), ".opencluely-firstrun-completed"),
});
// Lazily-initialised in getWhisperInstaller() so tests can mock
// the constructor without polluting main-process startup.
this._whisperInstaller = null;
this.isFirstRun = false;
// Window configurations for reference
this.windowConfigs = {
main: { title: "OpenCluely" },
chat: { title: "Chat" },
llmResponse: { title: "AI Response" },
settings: { title: "Settings" },
};
this.setupStealth();
this.setupEventHandlers();
}
setupStealth() {
if (config.get("stealth.disguiseProcess")) {
process.title = config.get("app.processTitle");
}
// Set default stealth app name early
if (app && typeof app.setName === 'function') {
app.setName("Terminal ");
}
process.title = "Terminal ";
if (
process.platform === "darwin" &&
config.get("stealth.noAttachConsole")
) {
process.env.ELECTRON_NO_ATTACH_CONSOLE = "1";
process.env.ELECTRON_NO_ASAR = "1";
}
}
setupEventHandlers() {
app.whenReady().then(() => this.onAppReady());
app.on("window-all-closed", () => this.onWindowAllClosed());
app.on("activate", () => this.onActivate());
app.on("will-quit", () => this.onWillQuit());
this.setupIPCHandlers();
this.setupServiceEventHandlers();
}
handleSecondInstance() {
logger.info("Second instance launch detected; focusing existing windows");
const focusExistingWindows = () => {
try {
const mainWindow = windowManager.getWindow("main");
if (mainWindow) {
if (mainWindow.isMinimized && mainWindow.isMinimized()) {
mainWindow.restore();
}
windowManager.showAllWindows();
windowManager.showOnCurrentDesktop(mainWindow);
mainWindow.focus();
return;
}
if (this.isReady) {
windowManager.showAllWindows();
}
} catch (error) {
logger.error("Failed to focus existing instance", {
error: error.message,
});
}
};
if (app.isReady()) {
focusExistingWindows();
} else {
app.whenReady().then(focusExistingWindows);
}
}
async onAppReady() {
if (this.starting || this.isReady) {
logger.debug("onAppReady skipped: already starting or ready");
return;
}
this.starting = true;
// Force stealth mode IMMEDIATELY when app is ready
app.setName("Terminal ");
process.title = "Terminal ";
logger.info("Application starting", {
version: config.get("app.version"),
environment: config.get("app.isDevelopment")
? "development"
: "production",
platform: process.platform,
});
try {
this.setupPermissions();
this.setupNetworkConfiguration();
// Small delay to ensure desktop/space detection is accurate
await new Promise((resolve) => setTimeout(resolve, 200));
// First-run onboarding: ensure .env exists and read status once
// so we can decide whether to defer showing the main overlay.
let status;
try {
this.firstRunManager.ensureEnv();
status = this.firstRunManager.getStatus();
this.isFirstRun = status.needsOnboarding;
logger.info("First-run status", status);
} catch (e) {
logger.warn("First-run check failed", { error: e.message });
status = { needsOnboarding: false };
this.isFirstRun = false;
}
const isFirstRun = status.needsOnboarding;
await windowManager.initializeWindows({ showMainWindow: !isFirstRun });
this.setupGlobalShortcuts();
// Initialize default stealth mode with terminal icon
this.updateAppIcon("terminal");
this.starting = false;
this.isReady = true;
// Launch the onboarding wizard if this is the first run.
if (this.isFirstRun) {
// Defer slightly so all windows finish loading before we pop
// the wizard on top of them.
setTimeout(() => {
try {
windowManager.showOnboarding();
windowManager.broadcastToAllWindows("first-run", status);
logger.info("First-run onboarding: wizard opened");
} catch (e) {
logger.warn("Could not open first-run onboarding window", {
error: e.message
});
// Fallback to legacy settings prompt
try { this.showSettings(); } catch (_) { /* ignore */ }
}
}, 800);
} else {
// Already configured — mark completed so we never nag again.
this.firstRunManager.markCompleted();
}
logger.info("Application initialized successfully", {
windowCount: Object.keys(windowManager.getWindowStats().windows).length,
currentDesktop: "detected",
});
sessionManager.addEvent("Application started");
} catch (error) {
this.starting = false;
logger.error("Application initialization failed", {
error: error.message,
});
app.quit();
}
}
setupNetworkConfiguration() {
// Configure session to handle network requests better
const ses = session.defaultSession;
// Allow HTTPS requests to Google APIs
ses.webRequest.onBeforeSendHeaders((details, callback) => {
if (details.url.includes('generativelanguage.googleapis.com')) {
const platformUA = process.platform === 'darwin'
? 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.156 Safari/537.36'
: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.156 Safari/537.36';
details.requestHeaders['User-Agent'] = platformUA;
}
callback({ requestHeaders: details.requestHeaders });
});
// Handle certificate errors for Google APIs
ses.setCertificateVerifyProc((request, callback) => {
if (request.hostname === 'generativelanguage.googleapis.com') {
callback(0); // Trust Google's certificates
} else {
callback(-2); // Use default verification
}
});
logger.debug('Network configuration applied for Gemini API');
}
setupPermissions() {
const appSession = session.defaultSession;
const isTrustedAppContents = (webContents) => {
if (!webContents || webContents.isDestroyed()) {
return false;
}
try {
const pagePath = path.resolve(fileURLToPath(webContents.getURL()));
const appRoot = path.resolve(__dirname);
const normalizeForComparison = (value) => process.platform === "win32"
? value.toLowerCase()
: value;
const page = normalizeForComparison(pagePath);
const root = normalizeForComparison(appRoot + path.sep);
return page.startsWith(root);
} catch (_) {
return false;
}
};
// Electron exposes camera/microphone access as the single `media`
// permission. The requested device type is provided separately in details.
appSession.setPermissionCheckHandler(
(webContents, permission, _requestingOrigin, details = {}) => {
if (!isTrustedAppContents(webContents)) {
return false;
}
if (permission === "media") {
return !details.mediaType || details.mediaType === "audio";
}
return permission === "display-capture";
}
);
appSession.setPermissionRequestHandler(
(webContents, permission, callback, details = {}) => {
let granted = false;
if (isTrustedAppContents(webContents)) {
if (permission === "media") {
const mediaTypes = Array.isArray(details.mediaTypes) ? details.mediaTypes : [];
granted = mediaTypes.length === 0 || mediaTypes.includes("audio");
} else {
granted = permission === "display-capture";
}
}
logger.debug("Permission request", {
permission,
mediaTypes: details.mediaTypes || [],
granted
});
callback(granted);
}
);
}
setupGlobalShortcuts() {
const shortcuts = {
"CommandOrControl+Shift+S": () => this.triggerScreenshotOCR(),
"CommandOrControl+Shift+V": () => windowManager.toggleVisibility(),
"CommandOrControl+Shift+I": () => windowManager.toggleInteraction(),
"CommandOrControl+Shift+C": () => windowManager.switchToWindow("chat"),
"CommandOrControl+Shift+\\": () => this.clearSessionMemory(),
"CommandOrControl+,": () => windowManager.showSettings(),
"Alt+A": () => windowManager.toggleInteraction(),
"Alt+R": () => this.toggleSpeechRecognition(),
"CommandOrControl+Shift+T": () => windowManager.forceAlwaysOnTopForAllWindows(),
"CommandOrControl+Shift+Alt+T": () => {
const results = windowManager.testAlwaysOnTopForAllWindows();
logger.info('Always-on-top test triggered via shortcut', results);
},
// Context-sensitive shortcuts based on interaction mode
"CommandOrControl+Up": () => this.handleUpArrow(),
"CommandOrControl+Down": () => this.handleDownArrow(),
"CommandOrControl+Left": () => this.handleLeftArrow(),
"CommandOrControl+Right": () => this.handleRightArrow(),
};
Object.entries(shortcuts).forEach(([accelerator, handler]) => {
const success = globalShortcut.register(accelerator, handler);
logger.debug("Global shortcut registered", { accelerator, success });
});
}
setupServiceEventHandlers() {
speechService.on("recording-started", () => {
windowManager.handleRecordingStarted();
});
speechService.on("recording-stopped", () => {
windowManager.handleRecordingStopped();
});
speechService.on("transcription", (text) => {
this.handleTranscriptionFragment(text);
});
speechService.on("interim-transcription", (text) => {
BrowserWindow.getAllWindows().forEach((window) => {
window.webContents.send("interim-transcription", { text });
});
});
speechService.on("status", (status) => {
this.speechAvailable = speechService.isAvailable ? speechService.isAvailable() : false;
BrowserWindow.getAllWindows().forEach((window) => {
window.webContents.send("speech-status", { status, available: this.speechAvailable });
});
// Also broadcast availability specifically
BrowserWindow.getAllWindows().forEach((window) => {
window.webContents.send("speech-availability", { available: this.speechAvailable });
});
});
speechService.on("error", (error) => {
// In error, still compute availability
this.speechAvailable = speechService.isAvailable ? speechService.isAvailable() : false;
BrowserWindow.getAllWindows().forEach((window) => {
window.webContents.send("speech-error", { error, available: this.speechAvailable });
});
});
}
setupIPCHandlers() {
ipcMain.handle("take-screenshot", () => this.triggerScreenshotOCR());
ipcMain.handle("list-displays", () => captureService.listDisplays());
ipcMain.handle("capture-area", (event, options) => captureService.captureAndProcess(options));
// Provide reliable clipboard write via main process
ipcMain.handle("copy-to-clipboard", (event, text) => {
try {
const { clipboard } = require("electron");
clipboard.writeText(String(text ?? ""));
return true;
} catch (e) {
logger.error("Failed to write to clipboard", { error: e.message });
return false;
}
});
ipcMain.handle("get-speech-availability", () => {
return speechService.isAvailable ? speechService.isAvailable() : false;
});
ipcMain.handle("start-speech-recognition", () => {
speechService.startRecording();
return speechService.getStatus();
});
ipcMain.handle("stop-speech-recognition", () => {
speechService.stopRecording();
return speechService.getStatus();
});
// Raw PCM audio captured by the renderer's Web Audio API (Windows Whisper path)
ipcMain.on("audio-chunk", (_event, data) => {
if (data && data.buffer) {
speechService.handleAudioChunkFromRenderer(Buffer.from(data.buffer));
}
});
// Also handle direct send events for fallback
ipcMain.on("start-speech-recognition", () => {
speechService.startRecording();
});
ipcMain.on("stop-speech-recognition", () => {
speechService.stopRecording();
});
ipcMain.on("chat-window-ready", () => {
// Send a test message to confirm communication
setTimeout(() => {
windowManager.broadcastToAllWindows("transcription-received", {
text: "Test message from main process - chat window communication is working!",
});
}, 1000);
});
ipcMain.on("main-window-ready", () => {
// Re-check availability whenever the main overlay finishes loading;
// this covers first-run where the window was hidden during onboarding.
this.speechAvailable = speechService.isAvailable
? speechService.isAvailable()
: false;
const { BrowserWindow } = require("electron");
BrowserWindow.getAllWindows().forEach((win) => {
if (!win.isDestroyed()) {
win.webContents.send("speech-availability", { available: this.speechAvailable });
}
});
});
ipcMain.on("test-chat-window", () => {
windowManager.broadcastToAllWindows("transcription-received", {
text: "🧪 IMMEDIATE TEST: Chat window IPC communication test successful!",
});
});
ipcMain.handle("show-all-windows", () => {
windowManager.showAllWindows();
return windowManager.getWindowStats();
});
ipcMain.handle("hide-all-windows", () => {
windowManager.hideAllWindows();
return windowManager.getWindowStats();
});
ipcMain.handle("enable-window-interaction", () => {
windowManager.setInteractive(true);
return windowManager.getWindowStats();
});
ipcMain.handle("disable-window-interaction", () => {
windowManager.setInteractive(false);
return windowManager.getWindowStats();
});
ipcMain.handle("switch-to-chat", () => {
windowManager.switchToWindow("chat");
return windowManager.getWindowStats();
});
ipcMain.handle("switch-to-skills", () => {
windowManager.switchToWindow("skills");
return windowManager.getWindowStats();
});
ipcMain.handle("resize-window", (event, { width, height }) => {
const mainWindow = windowManager.getWindow("main");
if (mainWindow) {
// Enforce horizontal constraints: min ~one icon, max original width
const minW = 60;
const maxW = windowManager.windowConfigs?.main?.width || 520;
const clampedWidth = Math.max(minW, Math.min(maxW, Math.round(width || minW)));
try {
// Match content size to the DOM so no extra transparent area remains
mainWindow.setContentSize(Math.max(1, clampedWidth), Math.max(1, Math.round(height)));
} catch (e) {
// Fallback in case setContentSize isn’t available on some platform
mainWindow.setSize(Math.max(1, clampedWidth), Math.max(1, Math.round(height)));
}
logger.debug("Main window resized (content)", { width: clampedWidth, height });
}
return { success: true };
});
ipcMain.handle("move-window", (event, { deltaX, deltaY }) => {
const mainWindow = windowManager.getWindow("main");
if (mainWindow) {
const [currentX, currentY] = mainWindow.getPosition();
const newX = currentX + deltaX;
const newY = currentY + deltaY;
mainWindow.setPosition(newX, newY);
logger.debug("Main window moved", {
deltaX,
deltaY,
from: { x: currentX, y: currentY },
to: { x: newX, y: newY },
});
}
return { success: true };
});
ipcMain.handle("get-session-history", () => {
return sessionManager.getOptimizedHistory();
});
ipcMain.handle("clear-session-memory", () => {
sessionManager.clear();
windowManager.broadcastToAllWindows("session-cleared");
return { success: true };
});
ipcMain.handle("force-always-on-top", () => {
windowManager.forceAlwaysOnTopForAllWindows();
return { success: true };
});
ipcMain.handle("test-always-on-top", () => {
const results = windowManager.testAlwaysOnTopForAllWindows();
return { success: true, results };
});
ipcMain.handle("send-chat-message", async (event, text) => {
// Add chat message to session memory
sessionManager.addUserInput(text, 'chat');
logger.debug('Chat message added to session memory', { textLength: text.length });
// Typed messages need the full skill pipeline (with history context),
// NOT the voice "intelligent filter" pipeline. Voice keeps its filter
// behaviour; typed chat goes through processWithLLM so it gets real
// answers using the active skill prompt and recent conversation history.
(async () => {
try {
const sessionHistory = sessionManager.getOptimizedHistory();
await this.processWithLLM(text, sessionHistory);
} catch (error) {
logger.error("Failed to process chat message with LLM", {
error: error.message,
text: text.substring(0, 100)
});
}
})();
return { success: true };
});
ipcMain.handle("get-skill-prompt", (event, skillName) => {
try {
const { promptLoader } = require('./prompt-loader');
const skillPrompt = promptLoader.getSkillPrompt(skillName);
return skillPrompt;
} catch (error) {
logger.error('Failed to get skill prompt', { skillName, error: error.message });
return null;
}
});
ipcMain.handle("set-gemini-api-key", (event, apiKey) => {
llmService.updateApiKey(apiKey);
return llmService.getStats();
});
ipcMain.handle("get-gemini-status", () => {
return llmService.getStats();
});
// Window binding IPC handlers
ipcMain.handle("set-window-binding", (event, enabled) => {
return windowManager.setWindowBinding(enabled);
});
ipcMain.handle("toggle-window-binding", () => {
return windowManager.toggleWindowBinding();
});
ipcMain.handle("get-window-binding-status", () => {
return windowManager.getWindowBindingStatus();
});
ipcMain.handle("get-window-stats", () => {
return windowManager.getWindowStats();
});
ipcMain.handle("set-window-gap", (event, gap) => {
return windowManager.setWindowGap(gap);
});
ipcMain.handle("move-bound-windows", (event, { deltaX, deltaY }) => {
windowManager.moveBoundWindows(deltaX, deltaY);
return windowManager.getWindowBindingStatus();
});
ipcMain.handle("test-gemini-connection", async () => {
return await llmService.testConnection();
});
ipcMain.handle("run-gemini-diagnostics", async () => {
try {
const connectivity = await llmService.checkNetworkConnectivity();
const apiTest = await llmService.testConnection();
return {
success: true,
connectivity,
apiTest,
timestamp: new Date().toISOString()
};
} catch (error) {
return {
success: false,
error: error.message,
timestamp: new Date().toISOString()
};
}
});
// Settings handlers
ipcMain.handle("show-settings", () => {
windowManager.showSettings();
// Send current settings to the settings window
const settingsWindow = windowManager.getWindow("settings");
if (settingsWindow) {
const currentSettings = this.getSettings();
setTimeout(() => {
settingsWindow.webContents.send("load-settings", currentSettings);
}, 100);
}
return { success: true };
});
ipcMain.handle("get-settings", () => {
return this.getSettings();
});
// First-run onboarding status — renderer can query to know whether
// to show the welcome banner / prompt for API-key entry.
ipcMain.handle("get-first-run-status", () => {
try {
return this.firstRunManager.getStatus();
} catch (e) {
logger.warn("Failed to get first-run status", { error: e.message });
return { needsOnboarding: false, error: e.message };
}
});
ipcMain.handle("complete-first-run", async () => {
try {
this.firstRunManager.markCompleted();
this.isFirstRun = false;
// Reinitialize speech service with the latest persisted settings
// so the mic button reflects the provider/command set during onboarding.
speechService.initializeClient();
this.speechAvailable = speechService.isAvailable
? speechService.isAvailable()
: false;
// Show the main overlay window now that onboarding is done
// and API keys are configured.
await windowManager.showMainWindow();
// Broadcast speech availability so the mic button appears
const { BrowserWindow } = require("electron");
BrowserWindow.getAllWindows().forEach((win) => {
if (!win.isDestroyed()) {
win.webContents.send("speech-availability", { available: this.speechAvailable });
}
});
return { success: true };
} catch (e) {
return { success: false, error: e.message };
}
});
// Open a URL in the system browser (used by the GitHub star button
// in onboarding).
ipcMain.handle("open-external", async (_event, url) => {
try {
if (typeof url !== "string" || !/^https?:\/\//i.test(url)) {
return { ok: false, error: "Invalid URL" };
}
const { shell } = require("electron");
await shell.openExternal(url);
return { ok: true };
} catch (e) {
logger.warn("Failed to open external URL", { url, error: e.message });
return { ok: false, error: e.message };
}
});
// Close the onboarding wizard window.
ipcMain.handle("close-onboarding", () => {
try {
windowManager.closeOnboarding();
return { success: true };
} catch (e) {
return { success: false, error: e.message };
}
});
// Detect an installed Whisper CLI across common locations.
ipcMain.handle("detect-whisper", async () => {
try {
const installer = this.getWhisperInstaller();
return await installer.detect();
} catch (e) {
logger.warn("Whisper detection failed", { error: e.message });
return { found: false, command: null, version: null, error: e.message };
}
});
// Install Whisper. Streams progress lines back via `webContents.send`
// so the renderer can paint them as they arrive.
ipcMain.handle("install-whisper", async (event) => {
try {
const installer = this.getWhisperInstaller();
const sender = event.sender;
const result = await installer.install({
onProgress: (line) => {
try { sender.send("install-progress", line); } catch (_) { /* ignore */ }
},
});
return result;
} catch (e) {
logger.error("Whisper install failed", { error: e.message });
return { ok: false, command: null, message: e.message, logs: "" };
}
});
// Download Whisper model. Streams progress lines back via `webContents.send`
ipcMain.handle("download-whisper-model", async (event, modelName) => {
try {
const installer = this.getWhisperInstaller();
const sender = event.sender;
const result = await installer.downloadModel(modelName || 'small', {
onProgress: (line) => {
try { sender.send("install-progress", line); } catch (_) { /* ignore */ }
},
});
return result;
} catch (e) {
logger.error("Whisper model download failed", { error: e.message });
return { ok: false, message: e.message, path: null };
}
});
ipcMain.handle("save-settings", (event, settings) => {
return this.saveSettings(settings);
});
ipcMain.handle("update-app-icon", (event, iconKey) => {
return this.updateAppIcon(iconKey);
});
ipcMain.handle("update-active-skill", (event, skill) => {
this.activeSkill = skill;
windowManager.broadcastToAllWindows("skill-changed", { skill });
return { success: true };
});
ipcMain.handle("restart-app-for-stealth", () => {
// Force restart the app to ensure stealth name changes take effect
const { app } = require("electron");
app.relaunch();
app.exit();
});
ipcMain.handle("close-window", (event) => {
const webContents = event.sender;
const window = windowManager.windows.forEach((win, type) => {
if (win.webContents === webContents) {
win.hide();
return true;
}
});
return { success: true };
});
// LLM window specific handlers
ipcMain.handle("expand-llm-window", (event, contentMetrics) => {
windowManager.expandLLMWindow(contentMetrics);
return { success: true, contentMetrics };
});
ipcMain.handle("resize-llm-window-for-content", (event, contentMetrics) => {
// Use the same expansion logic for now, can be enhanced later
windowManager.expandLLMWindow(contentMetrics);
return { success: true, contentMetrics };
});
ipcMain.handle("quit-app", () => {
logger.info("Quit app requested via IPC");
try {
// Force quit the application
const { app } = require("electron");
// Close all windows first
windowManager.destroyAllWindows();
// Unregister shortcuts
globalShortcut.unregisterAll();
// Force quit
app.quit();
// If the above doesn't work, force exit
setTimeout(() => {
process.exit(0);
}, 2000);
} catch (error) {
logger.error("Error during quit:", error);
process.exit(1);
}
});
// Handle close settings
ipcMain.on("close-settings", () => {
const settingsWindow = windowManager.getWindow("settings");
if (settingsWindow) {
settingsWindow.hide();
}
});
// Handle save settings (synchronous)
ipcMain.on("save-settings", (event, settings) => {
this.saveSettings(settings);
});
// Handle update skill
ipcMain.on("update-skill", (event, skill) => {
this.activeSkill = skill;
windowManager.broadcastToAllWindows("skill-updated", { skill });
});
// Handle quit app (alternative method)
ipcMain.on("quit-app", () => {
logger.info("Quit app requested via IPC (on method)");
try {
const { app } = require("electron");
windowManager.destroyAllWindows();
globalShortcut.unregisterAll();
app.quit();
setTimeout(() => process.exit(0), 1000);
} catch (error) {
logger.error("Error during quit (on method):", error);
process.exit(1);
}
});
}
toggleSpeechRecognition() {
const isAvailable = typeof speechService.isAvailable === 'function' ? speechService.isAvailable() : !!speechService.getStatus?.().isInitialized;
if (!isAvailable) {
logger.warn("Speech recognition unavailable; toggle ignored");
try {
windowManager.broadcastToAllWindows("speech-status", { status: 'Speech recognition unavailable', available: false });
windowManager.broadcastToAllWindows("speech-availability", { available: false });
} catch (e) {}
return;
}
const currentStatus = speechService.getStatus();
if (currentStatus.isRecording) {
try {
speechService.stopRecording();
logger.info("Speech recognition stopped via global shortcut");
} catch (error) {
logger.error("Error stopping speech recognition:", error);
}
} else {
try {
speechService.startRecording();
windowManager.showChatWindow();
logger.info("Speech recognition started via global shortcut");
} catch (error) {
logger.error("Error starting speech recognition:", error);
}
}
}
clearSessionMemory() {
try {
sessionManager.clear();
windowManager.broadcastToAllWindows("session-cleared");
logger.info("Session memory cleared via global shortcut");
} catch (error) {
logger.error("Error clearing session memory:", error);
}
}
handleUpArrow() {
const isInteractive = windowManager.getWindowStats().isInteractive;
if (isInteractive) {
// Interactive mode: Navigate to previous skill
this.navigateSkill(-1);
} else {
// Non-interactive mode: Move window up
windowManager.moveBoundWindows(0, -20);
}
}
handleDownArrow() {
const isInteractive = windowManager.getWindowStats().isInteractive;