-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathmain.js
More file actions
1298 lines (1101 loc) · 40.6 KB
/
main.js
File metadata and controls
1298 lines (1101 loc) · 40.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
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
require("dotenv").config();
const { app, BrowserWindow, globalShortcut, session, ipcMain } = require("electron");
const logger = require("./src/core/logger").createServiceLogger("MAIN");
const config = require("./src/core/config");
// 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");
// 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.activeSkill = "dsa";
// Default to C++ so language is enforced from first run
this.codingLanguage = "cpp";
this.speechAvailable = 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() {
// 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));
await windowManager.initializeWindows();
this.setupGlobalShortcuts();
// Initialize default stealth mode with terminal icon
this.updateAppIcon("terminal");
this.isReady = true;
logger.info("Application initialized successfully", {
windowCount: Object.keys(windowManager.getWindowStats().windows).length,
currentDesktop: "detected",
});
sessionManager.addEvent("Application started");
} catch (error) {
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')) {
details.requestHeaders['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.156 Safari/537.36';
}
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() {
session.defaultSession.setPermissionRequestHandler(
(webContents, permission, callback) => {
const allowedPermissions = ["microphone", "camera", "display-capture"];
const granted = allowedPermissions.includes(permission);
logger.debug("Permission request", { permission, 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", () => {
BrowserWindow.getAllWindows().forEach((window) => {
window.webContents.send("recording-started");
});
});
speechService.on("recording-stopped", () => {
BrowserWindow.getAllWindows().forEach((window) => {
window.webContents.send("recording-stopped");
});
});
speechService.on("transcription", (text) => {
// Add transcription to session memory
sessionManager.addUserInput(text, 'speech');
const windows = BrowserWindow.getAllWindows();
windows.forEach((window) => {
window.webContents.send("transcription-received", { text });
});
// Automatically process transcription with LLM for intelligent response
setTimeout(async () => {
try {
const sessionHistory = sessionManager.getOptimizedHistory();
await this.processTranscriptionWithLLM(text, sessionHistory);
} catch (error) {
logger.error("Failed to process transcription with LLM", {
error: error.message,
text: text.substring(0, 100)
});
}
}, 500);
});
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();
});
// 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("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 });
// Process typed message with LLM in the same way as transcribed text
setTimeout(async () => {
try {
const sessionHistory = sessionManager.getOptimizedHistory();
await this.processTranscriptionWithLLM(text, sessionHistory);
} catch (error) {
logger.error("Failed to process chat message with LLM", {
error: error.message,
text: text.substring(0, 100)
});
}
}, 500);
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();
});
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();
windowManager.hideChatWindow();
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;
if (isInteractive) {
// Interactive mode: Navigate to next skill
this.navigateSkill(1);
} else {
// Non-interactive mode: Move window down
windowManager.moveBoundWindows(0, 20);
}
}
handleLeftArrow() {
const isInteractive = windowManager.getWindowStats().isInteractive;
if (!isInteractive) {
// Non-interactive mode: Move window left
windowManager.moveBoundWindows(-20, 0);
}
// Interactive mode: Left arrow does nothing
}
handleRightArrow() {
const isInteractive = windowManager.getWindowStats().isInteractive;
if (!isInteractive) {
// Non-interactive mode: Move window right
windowManager.moveBoundWindows(20, 0);
}
// Interactive mode: Right arrow does nothing
}
navigateSkill(direction) {
const availableSkills = [
"dsa",
];
const currentIndex = availableSkills.indexOf(this.activeSkill);
if (currentIndex === -1) {
logger.warn("Current skill not found in available skills", {
currentSkill: this.activeSkill,
availableSkills,
});
return;
}
// Calculate new index with wrapping
let newIndex = currentIndex + direction;
if (newIndex >= availableSkills.length) {
newIndex = 0; // Wrap to beginning
} else if (newIndex < 0) {
newIndex = availableSkills.length - 1; // Wrap to end
}
const newSkill = availableSkills[newIndex];
this.activeSkill = newSkill;
// Update session manager with the new skill
sessionManager.setActiveSkill(newSkill);
logger.info("Skill navigated via global shortcut", {
from: availableSkills[currentIndex],
to: newSkill,
direction: direction > 0 ? "down" : "up",
});
// Broadcast the skill change to all windows
windowManager.broadcastToAllWindows("skill-updated", { skill: newSkill });
}
async triggerScreenshotOCR() {
if (!this.isReady) {
logger.warn("Screenshot requested before application ready");
return;
}
const startTime = Date.now();
try {
windowManager.showLLMLoading();
const capture = await captureService.captureAndProcess();
if (!capture.imageBuffer || !capture.imageBuffer.length) {
windowManager.hideLLMResponse();
this.broadcastOCRError("Failed to capture screenshot image");
return;
}
// Use image directly with LLM and active skill; do not send chat messages here
const sessionHistory = sessionManager.getOptimizedHistory();
const skillsRequiringProgrammingLanguage = ['dsa'];
const needsProgrammingLanguage = skillsRequiringProgrammingLanguage.includes(this.activeSkill);
const llmResult = await llmService.processImageWithSkill(
capture.imageBuffer,
capture.mimeType || 'image/png',
this.activeSkill,
sessionHistory.recent,
needsProgrammingLanguage ? this.codingLanguage : null
);
// Record model response in session
sessionManager.addModelResponse(llmResult.response, {
skill: this.activeSkill,
processingTime: llmResult.metadata.processingTime,
usedFallback: llmResult.metadata.usedFallback,
isImageAnalysis: true
});
windowManager.showLLMResponse(llmResult.response, {
skill: this.activeSkill,
processingTime: llmResult.metadata.processingTime,
usedFallback: llmResult.metadata.usedFallback,
isImageAnalysis: true
});
this.broadcastLLMSuccess(llmResult);
} catch (error) {
logger.error("Screenshot OCR process failed", {
error: error.message,
duration: Date.now() - startTime,
});
windowManager.hideLLMResponse();
this.broadcastOCRError(error.message);
sessionManager.addConversationEvent({
role: 'system',
content: `Screenshot OCR failed: ${error.message}`,
action: 'ocr_error',
metadata: {
error: error.message
}
});
}
}
async processWithLLM(text, sessionHistory) {
try {
// Add user input to session memory
sessionManager.addUserInput(text, 'llm_input');
// Check if current skill needs programming language context
const skillsRequiringProgrammingLanguage = ['dsa'];
const needsProgrammingLanguage = skillsRequiringProgrammingLanguage.includes(this.activeSkill);
const llmResult = await llmService.processTextWithSkill(
text,
this.activeSkill,
sessionHistory.recent,
needsProgrammingLanguage ? this.codingLanguage : null
);
logger.info("LLM processing completed, showing response", {
responseLength: llmResult.response.length,
skill: this.activeSkill,
programmingLanguage: needsProgrammingLanguage ? this.codingLanguage : 'not applicable',
processingTime: llmResult.metadata.processingTime,
responsePreview: llmResult.response.substring(0, 200) + "...",
});
// Add LLM response to session memory
sessionManager.addModelResponse(llmResult.response, {
skill: this.activeSkill,
processingTime: llmResult.metadata.processingTime,
usedFallback: llmResult.metadata.usedFallback,
});
windowManager.showLLMResponse(llmResult.response, {
skill: this.activeSkill,
processingTime: llmResult.metadata.processingTime,
usedFallback: llmResult.metadata.usedFallback,
});
this.broadcastLLMSuccess(llmResult);
} catch (error) {
logger.error("LLM processing failed", {
error: error.message,
skill: this.activeSkill,
});
windowManager.hideLLMResponse();
sessionManager.addConversationEvent({
role: 'system',
content: `LLM processing failed: ${error.message}`,
action: 'llm_error',
metadata: {
error: error.message,
skill: this.activeSkill
}
});
this.broadcastLLMError(error.message);
}
}
async processTranscriptionWithLLM(text, sessionHistory) {
try {
// Validate input text
if (!text || typeof text !== 'string' || text.trim().length === 0) {
logger.warn("Skipping LLM processing for empty or invalid transcription", {
textType: typeof text,
textLength: text ? text.length : 0
});
return;
}
const cleanText = text.trim();
if (cleanText.length < 2) {
logger.debug("Skipping LLM processing for very short transcription", {
text: cleanText
});
return;
}
logger.info("Processing transcription with intelligent LLM response", {
skill: this.activeSkill,
textLength: cleanText.length,
textPreview: cleanText.substring(0, 100) + "..."
});
// Check if current skill needs programming language context
const skillsRequiringProgrammingLanguage = ['dsa'];
const needsProgrammingLanguage = skillsRequiringProgrammingLanguage.includes(this.activeSkill);
const llmResult = await llmService.processTranscriptionWithIntelligentResponse(
cleanText,
this.activeSkill,
sessionHistory.recent,
needsProgrammingLanguage ? this.codingLanguage : null
);
// Add LLM response to session memory
sessionManager.addModelResponse(llmResult.response, {
skill: this.activeSkill,
processingTime: llmResult.metadata.processingTime,
usedFallback: llmResult.metadata.usedFallback,
isTranscriptionResponse: true
});
// Send response to chat windows
this.broadcastTranscriptionLLMResponse(llmResult);
logger.info("Transcription LLM response completed", {
responseLength: llmResult.response.length,
skill: this.activeSkill,
programmingLanguage: needsProgrammingLanguage ? this.codingLanguage : 'not applicable',
processingTime: llmResult.metadata.processingTime
});
} catch (error) {
logger.error("Transcription LLM processing failed", {
error: error.message,
errorStack: error.stack,
skill: this.activeSkill,
text: text ? text.substring(0, 100) : 'undefined'
});
// Try to provide a fallback response
try {
const fallbackResult = llmService.generateIntelligentFallbackResponse(text, this.activeSkill);
sessionManager.addModelResponse(fallbackResult.response, {
skill: this.activeSkill,
processingTime: fallbackResult.metadata.processingTime,
usedFallback: true,
isTranscriptionResponse: true,
fallbackReason: error.message
});
this.broadcastTranscriptionLLMResponse(fallbackResult);
logger.info("Used fallback response for transcription", {
skill: this.activeSkill,
fallbackResponse: fallbackResult.response
});
} catch (fallbackError) {
logger.error("Fallback response also failed", {
fallbackError: fallbackError.message
});
sessionManager.addConversationEvent({
role: 'system',
content: `Transcription LLM processing failed: ${error.message}`,
action: 'transcription_llm_error',
metadata: {
error: error.message,
skill: this.activeSkill
}
});
}
}
}
broadcastOCRSuccess(ocrResult) {
windowManager.broadcastToAllWindows("ocr-completed", {
text: ocrResult.text,
metadata: ocrResult.metadata,
});
}
broadcastOCRError(errorMessage) {
windowManager.broadcastToAllWindows("ocr-error", {
error: errorMessage,
timestamp: new Date().toISOString(),
});
}
broadcastLLMSuccess(llmResult) {
const broadcastData = {
response: llmResult.response,
metadata: llmResult.metadata,
skill: this.activeSkill, // Add the current active skill to the top level
};