-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer.js
More file actions
2322 lines (1969 loc) · 86.5 KB
/
renderer.js
File metadata and controls
2322 lines (1969 loc) · 86.5 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
/**
* Shadow Chatbot - Renderer Process
* Handles UI state, audio capture, and API interactions
*/
// ============================================
// State
// ============================================
const state = {
isListening: false,
transcripts: [],
responses: [],
audioContext: null,
mediaStream: null,
mediaRecorder: null,
audioChunks: [],
groqService: null,
demoInterval: null,
isDemoMode: false,
codeMode: false,
codeExtractor: new CodeExtractor(),
// Conversation context management
transcriptBuffer: [], // Buffer to accumulate chunks before responding
bufferDebounceTimer: null, // Timer to wait for speech pause
conversationHistory: [], // Full conversation history for AI context
lastResponseTime: 0, // Track when last response was generated
bufferWaitMs: 3000, // Wait 3 seconds of silence before responding
// Code translation
codeBlockCounter: 0,
codeTranslationCache: new Map(), // key: "{hash}:{targetLang}" -> translated code string
codeBlockRawMap: new Map(), // key: "code-block-{N}" -> { rawCode, currentLang }
// Feature: Action Items Tracker
actionItems: [], // { id, text, owner, deadline, done, timestamp }
actionItemsPanelOpen: false
};
// Initialize GroqService and load API keys from .env
state.groqService = new GroqService();
state.groqService.init(); // loads keys from .env via IPC (async, non-blocking)
// ============================================
// DOM Elements
// ============================================
const elements = {
statusDot: document.getElementById('status-dot'),
demoBadge: document.getElementById('demo-badge'),
transcriptCount: document.getElementById('transcript-count'),
transcriptionList: document.getElementById('transcription-list'),
transcriptEmpty: document.getElementById('transcript-empty'),
responseList: document.getElementById('response-list'),
responseEmpty: document.getElementById('response-empty'),
processingBar: document.getElementById('processing-bar'),
settingsModal: document.getElementById('settings-modal'),
apiKeyInput: document.getElementById('api-key'),
permissionStatus: document.getElementById('permission-status'),
// Buttons
btnClose: document.getElementById('btn-close'),
btnMinimize: document.getElementById('btn-minimize'),
btnMaximize: document.getElementById('btn-maximize'),
btnContext: document.getElementById('btn-context'),
btnSettings: document.getElementById('btn-settings'),
btnClear: document.getElementById('btn-clear'),
btnModalClose: document.getElementById('btn-modal-close'),
btnCancel: document.getElementById('btn-cancel'),
btnSave: document.getElementById('btn-save'),
// Opacity control
opacitySlider: document.getElementById('opacity-slider'),
opacityValue: document.getElementById('opacity-value'),
// Context modal
contextModal: document.getElementById('context-modal'),
contextBadge: document.getElementById('context-badge'),
btnContextClose: document.getElementById('btn-context-close'),
dropZone: document.getElementById('drop-zone'),
fileInput: document.getElementById('file-input'),
fileList: document.getElementById('file-list'),
contextPreview: document.getElementById('context-preview'),
contextText: document.getElementById('context-text'),
fileCount: document.getElementById('file-count'),
btnClearFiles: document.getElementById('btn-clear-files'),
btnApplyContext: document.getElementById('btn-apply-context'),
// Code mode
btnCodeMode: document.getElementById('btn-code-mode'),
// Manual question input
manualQuestionInput: document.getElementById('manual-question-input'),
sendQuestionBtn: document.getElementById('send-question-btn'),
// Screen capture
btnCapture: document.getElementById('btn-capture'),
// Code viewer badge
snippetBadge: document.getElementById('snippet-badge'),
// Download transcript
btnDownload: document.getElementById('btn-download'),
// Action Items
btnToggleActions: document.getElementById('btn-toggle-actions'),
actionItemsPanel: document.getElementById('action-items-panel'),
actionItemsList: document.getElementById('action-items-list'),
actionItemsCount: document.getElementById('action-items-count'),
actionItemsBadge: document.getElementById('action-items-badge'),
actionItemsEmpty: document.getElementById('action-items-empty'),
btnCopyActions: document.getElementById('btn-copy-actions'),
btnClearActions: document.getElementById('btn-clear-actions')
};
// ============================================
// Initialize
// ============================================
function init() {
updateUI();
bindEvents();
bindActionItemsEvents();
checkPermissions();
// Listen for context from the home/setup screen
window.electronAPI.onReceiveContext((data) => {
console.log('Received context from home screen:', data);
// Set session mode prompt on the groq service
if (data.modePrompt) {
state.groqService.setSessionMode(data.selectedMode, data.modePrompt);
console.log('Session mode set:', data.selectedMode);
}
// Set briefing text on the groq service
if (data.briefingText) {
state.groqService.setBriefingContext(data.briefingText);
console.log('Briefing context set:', data.briefingText.substring(0, 80) + '...');
}
// Pre-load files into contextService
if (data.files && data.files.length > 0) {
data.files.forEach(f => {
const fileInfo = {
id: Date.now() + Math.random().toString(36).substr(2, 9),
name: f.name,
type: f.type,
size: f.size,
content: f.content,
isImage: f.isImage || false,
base64: f.base64 || null,
status: 'ready'
};
contextService.files.push(fileInfo);
});
contextService.updateExtractedContext();
// Update the context badge in the overlay UI
if (elements.contextBadge) {
elements.contextBadge.textContent = contextService.getFileCount();
elements.contextBadge.classList.remove('hidden');
}
if (elements.btnContext) {
elements.btnContext.classList.add('has-files');
}
console.log(`Pre-loaded ${data.files.length} files from home screen`);
}
});
}
function updateUI() {
// Update demo badge visibility
if (state.isDemoMode) {
elements.demoBadge.classList.remove('hidden');
} else {
elements.demoBadge.classList.add('hidden');
}
// Update API key input
elements.apiKeyInput.value = state.apiKey;
}
function bindEvents() {
// Window controls
elements.btnClose.addEventListener('click', () => window.electronAPI.closeWindow());
elements.btnMinimize.addEventListener('click', () => window.electronAPI.minimizeWindow());
elements.btnMaximize.addEventListener('click', () => window.electronAPI.maximizeWindow());
// Opacity slider
elements.opacitySlider.addEventListener('input', (e) => {
const value = parseInt(e.target.value);
elements.opacityValue.textContent = value + '%';
window.electronAPI.setOpacity(value / 100);
});
// Settings modal
elements.btnSettings.addEventListener('click', openSettings);
elements.btnModalClose.addEventListener('click', closeSettings);
elements.btnCancel.addEventListener('click', closeSettings);
elements.btnSave.addEventListener('click', saveSettings);
// Clear history
elements.btnClear.addEventListener('click', clearHistory);
// Global hotkey from main process
window.electronAPI.onToggleListening(() => toggleListening());
// Close modal on overlay click
elements.settingsModal.addEventListener('click', (e) => {
if (e.target === elements.settingsModal) closeSettings();
});
// Context modal events
elements.btnContext.addEventListener('click', openContextModal);
elements.btnContextClose.addEventListener('click', closeContextModal);
elements.contextModal.addEventListener('click', (e) => {
if (e.target === elements.contextModal) closeContextModal();
});
// File upload events
elements.dropZone.addEventListener('click', () => elements.fileInput.click());
elements.fileInput.addEventListener('change', handleFileSelect);
// Drag and drop
elements.dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
elements.dropZone.classList.add('drag-over');
});
elements.dropZone.addEventListener('dragleave', () => {
elements.dropZone.classList.remove('drag-over');
});
elements.dropZone.addEventListener('drop', handleFileDrop);
// Context actions
elements.btnClearFiles.addEventListener('click', clearContextFiles);
elements.btnApplyContext.addEventListener('click', applyContext);
// Code mode toggle
elements.btnCodeMode.addEventListener('click', toggleCodeMode);
// Download transcript
elements.btnDownload.addEventListener('click', downloadTranscript);
}
async function checkPermissions() {
try {
const hasPermission = await window.electronAPI.checkScreenPermission();
const statusEl = elements.permissionStatus;
const dot = statusEl.querySelector('.permission-dot');
const text = statusEl.querySelector('span:last-child');
if (hasPermission) {
dot.classList.add('granted');
dot.classList.remove('denied');
text.textContent = 'Screen Recording: Granted';
} else {
dot.classList.add('denied');
dot.classList.remove('granted');
text.textContent = 'Screen Recording: Not Granted';
}
} catch (error) {
console.error('Permission check failed:', error);
}
}
// ============================================
// Listening Toggle
// ============================================
function toggleListening() {
state.isListening = !state.isListening;
if (state.isListening) {
startListening();
} else {
stopListening();
}
updateListeningUI();
}
function updateListeningUI() {
if (state.isListening) {
elements.statusDot.classList.add('active');
} else {
elements.statusDot.classList.remove('active');
}
}
// ============================================
// Manual Question Input
// ============================================
/**
* Send a manually typed question to the AI
*/
async function sendManualQuestion() {
const input = elements.manualQuestionInput;
const question = input.value.trim();
if (!question) return;
// Clear input immediately
input.value = '';
// Hide empty states
elements.transcriptEmpty.classList.add('hidden');
elements.responseEmpty.classList.add('hidden');
// Add question to transcript pane (left side) - marked as manual input
const messageId = `msg-${++messageIdCounter}`;
state.transcripts.push({ text: question, time: new Date(), id: messageId });
const bubble = document.createElement('div');
bubble.className = 'bubble bubble-transcript manual-input clickable';
bubble.id = `transcript-${messageId}`;
bubble.dataset.messageId = messageId;
bubble.innerHTML = `
<div class="bubble-text">${highlightKeywords(question)}</div>
<div class="bubble-meta">
<span class="manual-badge">⌨️ Typed</span>
<span>${formatTime(new Date())}</span>
<span class="link-hint">Click to see response →</span>
</div>
`;
// Add click handler to navigate to corresponding response
bubble.addEventListener('click', () => {
const responseEl = document.getElementById(`response-${messageId}`);
if (responseEl) {
// Remove previous highlights
document.querySelectorAll('.bubble.highlighted').forEach(el => {
el.classList.remove('highlighted');
});
// Scroll to response
responseEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
// Highlight both bubbles
bubble.classList.add('highlighted');
responseEl.classList.add('highlighted');
// Remove highlight after 3 seconds
setTimeout(() => {
bubble.classList.remove('highlighted');
responseEl.classList.remove('highlighted');
}, 3000);
}
});
elements.transcriptionList.appendChild(bubble);
elements.transcriptionList.scrollTop = elements.transcriptionList.scrollHeight;
elements.transcriptCount.textContent = state.transcripts.length;
// Add to conversation history
state.conversationHistory.push({
role: 'user',
content: question
});
// Generate AI response
showProcessing(true);
try {
// Skip history for standalone/conceptual questions to save tokens
const historyMessages = isStandaloneQuestion(question) ? [] : buildConversationContext();
const response = await state.groqService.generateResponseWithHistory(question, historyMessages);
// Add AI response to right pane
addResponse(question, response, messageId);
// Add to conversation history
state.conversationHistory.push({
role: 'assistant',
content: response
});
// Keep history manageable (8 exchanges = 16 messages)
if (state.conversationHistory.length > 16) {
state.conversationHistory = state.conversationHistory.slice(-16);
}
} catch (error) {
console.error('Error generating response:', error);
addResponse(question, `⚠️ Error: ${error.message}`, messageId);
} finally {
showProcessing(false);
}
}
// Add event listeners for manual input
if (elements.sendQuestionBtn) {
elements.sendQuestionBtn.addEventListener('click', sendManualQuestion);
}
if (elements.manualQuestionInput) {
elements.manualQuestionInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendManualQuestion();
}
});
}
// ============================================
// Screen Capture + OCR Analysis
// ============================================
/**
* Capture the current screen and send to AI for analysis
*/
async function captureScreen() {
try {
// Get screen source
const result = await window.electronAPI.getSources();
if (result.error) {
addTranscript('⚠️ Screen capture requires Screen Recording permission');
return;
}
const sources = result.sources || [];
const screenSource = sources.find(s =>
s.name.toLowerCase().includes('entire screen') ||
s.name.toLowerCase().includes('screen')
) || sources[0];
if (!screenSource) {
addTranscript('⚠️ No screen source found');
return;
}
// Show processing indicator (no text message needed, the bubble will appear)
showProcessing(true);
// Get the video stream
const stream = await navigator.mediaDevices.getUserMedia({
audio: false,
video: {
mandatory: {
chromeMediaSource: 'desktop',
chromeMediaSourceId: screenSource.id,
maxWidth: 1920,
maxHeight: 1080
}
}
});
// Create video element to capture frame
const video = document.createElement('video');
video.srcObject = stream;
await video.play();
// Wait a moment for video to stabilize
await new Promise(resolve => setTimeout(resolve, 100));
// Capture frame to canvas
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0);
// Stop the stream
stream.getTracks().forEach(track => track.stop());
// Convert to base64
const imageDataUrl = canvas.toDataURL('image/jpeg', 0.8);
// Add to transcript with thumbnail
const messageId = `msg-${++messageIdCounter}`;
const bubble = document.createElement('div');
bubble.className = 'bubble bubble-transcript screen-capture clickable';
bubble.id = `transcript-${messageId}`;
bubble.dataset.messageId = messageId;
bubble.innerHTML = `
<div class="capture-preview">
<img src="${imageDataUrl}" alt="Screen capture" style="max-width: 100%; border-radius: 8px;">
</div>
<div class="bubble-text">📷 Screen Capture - Analyzing content...</div>
<div class="bubble-meta">
<span class="capture-badge">🖥️ Screen</span>
<span>${formatTime(new Date())}</span>
<span class="link-hint">Click to see response →</span>
</div>
`;
// Add click handler
bubble.addEventListener('click', () => {
const responseEl = document.getElementById(`response-${messageId}`);
if (responseEl) {
document.querySelectorAll('.bubble.highlighted').forEach(el => el.classList.remove('highlighted'));
responseEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
bubble.classList.add('highlighted');
responseEl.classList.add('highlighted');
setTimeout(() => {
bubble.classList.remove('highlighted');
responseEl.classList.remove('highlighted');
}, 3000);
}
});
elements.transcriptionList.appendChild(bubble);
elements.transcriptionList.scrollTop = elements.transcriptionList.scrollHeight;
state.transcripts.push({ text: '[Screen Capture]', time: new Date(), id: messageId });
elements.transcriptCount.textContent = state.transcripts.length;
// Build analysis prompt based on session mode
let analysisPrompt;
const modeId = state.groqService.sessionModeId || 'general';
if (modeId === 'sde') {
analysisPrompt = `Look at this screen capture carefully. If it contains a coding problem, interview question, or LeetCode-style problem:
FOLLOW YOUR SYSTEM PROMPT INSTRUCTIONS EXACTLY — use the full 8-section structured format:
1. Clarifying Questions to Ask the Interviewer
2. Problem Breakdown
3. Naive / Brute Force Approach with Pseudocode
4. Two Test Case Walkthroughs for Naive + Complexity Analysis
5. Optimal Approach explanation
6. Complete Optimal Solution Code
7. Two Test Case Walkthroughs for Optimal + Complexity Analysis
8. Follow-up Discussion Points
Extract all visible text from the screen first, then solve the problem using the COMPLETE structured format. Do NOT skip any section. Do NOT abbreviate. Give the full, detailed response.
If it's a system design question, use the 7-step system design framework from your instructions.
If it's code that needs debugging, analyze it thoroughly and suggest fixes.`;
} else {
analysisPrompt = `Analyze this screen capture thoroughly. Extract all visible text.
If it contains a question or problem, help solve it using your specialized expertise for the current session mode.
If it's code, explain what it does, identify any bugs, and suggest improvements.
If it's a slide or document, summarize the key points.
Be thorough and detailed. Follow your system prompt instructions for formatting and structure.`;
}
const response = await analyzeImageWithVision(imageDataUrl, analysisPrompt);
// Update the bubble text
const bubbleText = bubble.querySelector('.bubble-text');
bubbleText.textContent = '📷 Screen Captured - See analysis →';
// Add response (just use the response directly, no label needed)
addResponse('📷 Screen Capture', response, messageId);
// Add to conversation history
state.conversationHistory.push({
role: 'user',
content: '[User captured screen for analysis]'
});
state.conversationHistory.push({
role: 'assistant',
content: response
});
} catch (error) {
console.error('Screen capture error:', error);
addTranscript(`⚠️ Capture failed: ${error.message}`);
} finally {
showProcessing(false);
}
}
/**
* Analyze image using Groq vision API with model fallback
*/
async function analyzeImageWithVision(imageDataUrl, prompt) {
// Try multiple vision models in order of preference
const visionModels = [
'meta-llama/llama-4-scout-17b-16e-instruct',
'llama-3.2-11b-vision-preview',
'llama-3.2-90b-vision-preview'
];
let lastError = null;
for (const model of visionModels) {
try {
console.log(`[Vision] Trying model: ${model}`);
const response = await fetch('https://api.groq.com/openai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${state.groqService.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: model,
messages: [
{
role: 'system',
content: state.groqService.getSystemPrompt()
},
{
role: 'user',
content: [
{ type: 'text', text: prompt },
{ type: 'image_url', image_url: { url: imageDataUrl } }
]
}
],
max_tokens: 8192,
temperature: 0.7
})
});
if (response.ok) {
const result = await response.json();
console.log(`[Vision] Success with model: ${model}`);
return result.choices?.[0]?.message?.content || 'Could not analyze the image';
}
const error = await response.json();
lastError = error.error?.message || `Model ${model} failed`;
console.log(`[Vision] Model ${model} failed:`, lastError);
// If it's a rate limit or non-model error, don't try other models
if (!lastError.includes('decommissioned') && !lastError.includes('not found')) {
throw new Error(lastError);
}
} catch (error) {
lastError = error.message;
console.log(`[Vision] Error with ${model}:`, error.message);
}
}
// If all vision models failed, provide a helpful fallback message
return `⚠️ **Vision Analysis Unavailable**
The screen was captured successfully, but vision AI analysis is currently unavailable (all Groq vision models are deprecated or rate-limited).
**Alternative Options:**
1. **Type your question** about what you see in the input box below
2. **Describe the code/content** you're looking at and ask for help
3. **Copy-paste the code** directly into the chat
The screenshot is saved above for your reference.
*Technical Note: ${lastError}*`;
}
// Add event listener for capture button
if (elements.btnCapture) {
elements.btnCapture.addEventListener('click', captureScreen);
}
function startListening() {
// Hide empty states
elements.transcriptEmpty.classList.add('hidden');
elements.responseEmpty.classList.add('hidden');
if (state.isDemoMode) {
startDemoMode();
} else {
startRealCapture();
}
}
function stopListening() {
if (state.isDemoMode) {
stopDemoMode();
} else {
stopRealCapture();
}
}
// ============================================
// Demo Mode
// ============================================
const demoData = [
{ q: "Hello, can you hear me?", a: "Yes, I can hear you clearly. How can I assist you today?" },
{ q: "What time is the meeting tomorrow?", a: "Based on what I heard, the meeting is scheduled for 10 AM tomorrow." },
{ q: "Can you summarize what was just said?", a: "The speaker discussed the Q3 project timeline and mentioned three key deliverables: the API integration, the dashboard redesign, and the mobile app update." },
{ q: "What are the action items from this call?", a: "From this discussion, the action items are: 1) Review the proposal by Friday, 2) Schedule a follow-up meeting, 3) Share the updated timeline with the team." },
{ q: "Is this window visible to others?", a: "No, this overlay window is configured to be invisible to screen sharing applications like Zoom, Meet, and Teams." }
];
let demoIndex = 0;
function startDemoMode() {
addTranscript("🎧 Demo Mode started - simulating audio...");
// First demo interaction immediately
setTimeout(() => {
if (state.isListening && state.isDemoMode) {
simulateDemoInteraction();
}
}, 1500);
// Continue with interval
state.demoInterval = setInterval(() => {
if (state.isListening && state.isDemoMode) {
simulateDemoInteraction();
}
}, 6000);
}
function stopDemoMode() {
if (state.demoInterval) {
clearInterval(state.demoInterval);
state.demoInterval = null;
}
}
function simulateDemoInteraction() {
const demo = demoData[demoIndex % demoData.length];
demoIndex++;
// Show processing
showProcessing(true);
// Add transcript
setTimeout(() => {
addTranscript(demo.q);
// Add response after delay
setTimeout(() => {
addResponse(demo.q, demo.a);
showProcessing(false);
}, 1200);
}, 500);
}
// ============================================
// Real Audio Capture (using AudioCaptureService)
// ============================================
let audioCaptureService = null;
async function startRealCapture() {
try {
// Get available sources
const result = await window.electronAPI.getSources();
// Check for errors
if (result.error) {
if (result.error === 'permission_denied') {
addTranscript(`⚠️ Screen Recording permission: ${result.status}`);
addTranscript("📋 To fix: System Preferences → Privacy & Security → Screen Recording → Enable 'Electron'");
addTranscript("💡 After enabling, FULLY QUIT the app (Cmd+Q) and restart");
} else {
addTranscript(`⚠️ Error: ${result.error}`);
}
// Fallback to demo mode
state.isDemoMode = true;
updateUI();
startDemoMode();
return;
}
const sources = result.sources || [];
if (sources.length === 0) {
addTranscript("⚠️ No audio sources found.");
addTranscript("📋 Make sure Screen Recording permission is enabled for 'Electron'");
// Fallback to demo mode
state.isDemoMode = true;
updateUI();
startDemoMode();
return;
}
// Get the first screen source (prefer "Entire Screen" - case insensitive)
const screenSource = sources.find(s =>
s.name.toLowerCase().includes('entire screen') ||
s.name.toLowerCase().includes('screen') ||
s.name.toLowerCase() === 'screen 1'
) || sources[0];
console.log('Selected audio source:', screenSource.name);
addTranscript(`🎙️ Connecting to: ${screenSource.name}...`);
// Create audio capture service - YOUTUBE CAPTIONS STYLE
// Short chunks (3s) for fast feedback, long silence (10s) to combine into one bubble
audioCaptureService = new AudioCaptureService({
chunkDuration: 3000, // 3 seconds - fast feedback like YouTube captions
onAudioChunk: handleAudioChunk,
onError: (error) => {
console.error('Audio capture error:', error);
}
});
// Start capturing
await audioCaptureService.start(screenSource.id);
addTranscript("✅ Audio capture active - listening for system audio...");
addTranscript("🔊 Play some audio (YouTube, Spotify, etc.) to test!");
} catch (error) {
console.error('Audio capture error:', error);
addTranscript(`⚠️ Capture failed: ${error.message}`);
// Fallback to demo mode
state.isDemoMode = true;
updateUI();
startDemoMode();
}
}
function stopRealCapture() {
if (audioCaptureService) {
audioCaptureService.stop();
audioCaptureService = null;
}
}
/**
* Handle incoming audio chunk (WAV format)
* Transcribes and adds to live streaming transcript
* @param {Blob} wavBlob - Audio data in WAV format
*/
async function handleAudioChunk(wavBlob) {
if (!state.groqService || !state.isListening) return;
showProcessing(true);
try {
// Transcribe the audio chunk
const transcript = await state.groqService.transcribe(wavBlob);
// Check if we got meaningful text
if (transcript && transcript.trim().length > 2) {
// Filter out common noise transcriptions
const noisePatterns = ['[BLANK_AUDIO]', '[ Silence ]', '[silence]', '[Music]', '[music]', 'you', 'Thanks for watching'];
const isNoise = noisePatterns.some(p => transcript.toLowerCase().includes(p.toLowerCase()));
const cleanText = transcript.trim();
const wordCount = cleanText.split(/\s+/).length;
const isTooShort = wordCount < 2;
// Filter out common filler phrases
const fillerPhrases = ['thank you', 'thanks', 'okay', 'um', 'uh', 'hmm', 'alright', 'right'];
const isFillerOnly = fillerPhrases.some(f => cleanText.toLowerCase() === f || cleanText.toLowerCase() === f + '.');
if (!isNoise && !isTooShort && !isFillerOnly) {
// Add to live streaming transcript (handles buffering internally)
addTranscript(cleanText);
}
}
} catch (error) {
console.error('Transcription error:', error);
if (!error.message.includes('rate limit')) {
console.error('Transcription error details:', error);
}
} finally {
showProcessing(false);
}
}
/**
* Process buffered transcripts and generate a single contextual response
*/
async function processBufferedTranscripts() {
if (state.transcriptBuffer.length === 0) return;
// Combine all buffered transcripts into one context
const combinedTranscript = state.transcriptBuffer.join(' ');
// Clear the buffer
state.transcriptBuffer = [];
// Feature: Extract action items from transcript
extractActionItems(combinedTranscript);
// Generate response with full conversation context
generateResponseWithContext(combinedTranscript);
}
/**
* Generate AI response with full conversation history for context
* @param {string} currentTranscript - The current user speech
*/
async function generateResponseWithContext(currentTranscript) {
try {
showProcessing(true);
// Skip history for standalone/conceptual questions to save tokens
const contextMessages = isStandaloneQuestion(currentTranscript)
? []
: buildConversationContext();
// Generate response with context
const response = await state.groqService.generateResponseWithHistory(
currentTranscript,
contextMessages
);
// Add to conversation history
state.conversationHistory.push({
role: 'user',
content: currentTranscript,
time: new Date()
});
state.conversationHistory.push({
role: 'assistant',
content: response,
time: new Date()
});
// Keep history manageable (8 exchanges = 16 messages)
if (state.conversationHistory.length > 16) {
state.conversationHistory = state.conversationHistory.slice(-16);
}
// Update last response time
state.lastResponseTime = Date.now();
addResponse(currentTranscript, response);
} catch (error) {
console.error('Response generation error:', error);
addResponse(currentTranscript, `⚠️ Error: ${error.message}`);
} finally {
showProcessing(false);
}
}
// ============================================
// Token-Optimized Conversation Context
// ============================================
/**
* Detect if a question is standalone/conceptual and doesn't need history.
* These are self-contained questions where prior conversation adds no value.
*/
function isStandaloneQuestion(text) {
if (!text || text.length < 5) return false;
const lower = text.toLowerCase().trim();
// Conceptual / definitional patterns
const standalonePatterns = [
/^what\s+is\s+(a|an|the)?\s/,
/^what\s+are\s/,
/^explain\s/,
/^define\s/,
/^describe\s+(what|the\s+concept)/,
/^(what'?s|whats)\s+the\s+difference\s+between/,
/^how\s+does\s+\w+\s+work/,
/^what\s+does\s+\w+\s+mean/,
/^tell\s+me\s+about\s+(the\s+concept|what)/,
/^(can you\s+)?compare\s+/,
/^when\s+(should|would)\s+(you|we|i)\s+use\s/
];
// Patterns that indicate it's a follow-up (NOT standalone)
const followUpPatterns = [
/^(what if|how about|can you also|and what|but what|what about)/,
/^(now|then|next|also|additionally)/,
/previous|earlier|above|before|last (answer|response|question)/,
/you (said|mentioned|showed|explained)/,
/the (code|solution|approach|algorithm) (you|we|above)/
];
// If it references prior conversation, it's NOT standalone
for (const pattern of followUpPatterns) {
if (pattern.test(lower)) return false;
}
// Check if it matches a standalone pattern
for (const pattern of standalonePatterns) {
if (pattern.test(lower)) {
console.log(`[TokenOpt] Standalone question detected, skipping history`);
return true;
}
}
return false;
}
/**
* Compress a user+assistant exchange into a short summary line.
* Keeps only the essence to maintain topical awareness.
*/
function summarizeExchange(userMsg, assistantMsg) {
// Extract the core topic from the user question
let topic = userMsg.length > 80
? userMsg.substring(0, 77) + '...'
: userMsg;
// Try to extract key info from assistant response
const response = assistantMsg || '';
let approach = '';
// Look for complexity mentions (coding problems)
const complexityMatch = response.match(/O\([^)]+\)/g);
if (complexityMatch) {
approach = `, ${complexityMatch[complexityMatch.length - 1]} optimal`;
}
// Look for approach/technique keywords
const techniqueMatch = response.match(/(?:using|via|with)\s+(hash\s*map|two\s*pointer|sliding\s*window|binary\s*search|DFS|BFS|dynamic\s*programming|greedy|stack|queue|trie|heap)/i);
if (techniqueMatch) {
approach = ` using ${techniqueMatch[1]}${approach}`;
}
return `Q: ${topic}${approach}`;
}
/**
* Build conversation context with token optimization.
* - Last 3 exchanges: sent verbatim (full context for recent conversation)
* - Older exchanges: compressed to 1-line summaries
* This reduces tokens by ~30-40% compared to sending all history verbatim.
*/
function buildConversationContext() {
const history = state.conversationHistory;
if (history.length === 0) return [];
const RECENT_MESSAGES = 6; // 3 exchanges verbatim