-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
3027 lines (2570 loc) · 120 KB
/
Copy pathscript.js
File metadata and controls
3027 lines (2570 loc) · 120 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
// WeAD RedFlag - Psychological Safety Monitor
// ✅ MATCHING INDEX.HTML IMPLEMENTATION EXACTLY
// Global variables (matching index.html)
let recognition;
let isRecording = false;
let finalTranscript = '';
let websocket;
let currentSessionId = null;
let redFlagsDetected = false; // NEW: Track if red flags were detected
let forceStop = false; // Force stop flag for manual stop
// ✅ NEW: Mobile Navigation State
let currentMobileSection = 'voice';
let isMobileView = window.innerWidth <= 768;
// Debug logging function (matching index.html)
function debugLog(message, type = 'info') {
const timestamp = new Date().toLocaleTimeString();
const logArea = document.getElementById('debugLog');
if (logArea) {
logArea.value += `[${timestamp}] ${message}\n`;
logArea.scrollTop = logArea.scrollHeight;
}
console.log(`[${timestamp}] ${message}`);
}
// ✅ NEW: Mobile Navigation Functions
function initializeMobileNavigation() {
if (!isMobileView) return;
debugLog('📱 Initializing mobile navigation...');
const navTabs = document.querySelectorAll('.nav-tab');
const sections = document.querySelectorAll('.content-section');
navTabs.forEach(tab => {
tab.addEventListener('click', () => {
const targetSection = tab.getAttribute('data-section');
switchMobileSection(targetSection);
});
});
// Add touch/swipe support for mobile
addSwipeSupport();
debugLog('✅ Mobile navigation initialized');
}
function switchMobileSection(sectionName) {
if (currentMobileSection === sectionName) return;
debugLog(`🔄 Switching to section: ${sectionName}`);
// Update navigation tabs
document.querySelectorAll('.nav-tab').forEach(tab => {
tab.classList.remove('active');
if (tab.getAttribute('data-section') === sectionName) {
tab.classList.add('active');
}
});
// Update sections
document.querySelectorAll('.content-section').forEach(section => {
section.classList.remove('active');
if (section.getAttribute('data-section') === sectionName) {
section.classList.add('active');
}
});
currentMobileSection = sectionName;
// Smooth scroll to section
const targetSection = document.getElementById(`${sectionName}-section`);
if (targetSection) {
targetSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
// Update URL hash for bookmarking
window.location.hash = `#${sectionName}`;
debugLog(`✅ Switched to section: ${sectionName}`);
}
function addSwipeSupport() {
let startX = 0;
let startY = 0;
let endX = 0;
let endY = 0;
const controlPanel = document.querySelector('.control-panel');
if (!controlPanel) return;
controlPanel.addEventListener('touchstart', (e) => {
startX = e.touches[0].clientX;
startY = e.touches[0].clientY;
});
controlPanel.addEventListener('touchend', (e) => {
endX = e.changedTouches[0].clientX;
endY = e.changedTouches[0].clientY;
const diffX = startX - endX;
const diffY = startY - endY;
// Only handle horizontal swipes (ignore vertical scrolling)
if (Math.abs(diffX) > Math.abs(diffY) && Math.abs(diffX) > 50) {
if (diffX > 0) {
// Swipe left - next section
navigateToNextSection();
} else {
// Swipe right - previous section
navigateToPreviousSection();
}
}
});
}
function navigateToNextSection() {
const sections = ['voice', 'analysis', 'guide', 'settings', 'music'];
const currentIndex = sections.indexOf(currentMobileSection);
const nextIndex = (currentIndex + 1) % sections.length;
switchMobileSection(sections[nextIndex]);
}
function navigateToPreviousSection() {
const sections = ['voice', 'analysis', 'guide', 'settings', 'music'];
const currentIndex = sections.indexOf(currentMobileSection);
const prevIndex = currentIndex === 0 ? sections.length - 1 : currentIndex - 1;
switchMobileSection(sections[prevIndex]);
}
// ✅ NEW: Handle window resize for responsive behavior
function handleWindowResize() {
const wasMobile = isMobileView;
isMobileView = window.innerWidth <= 768;
if (wasMobile !== isMobileView) {
debugLog(`📱 View mode changed: ${isMobileView ? 'Mobile' : 'Desktop'}`);
if (isMobileView) {
// Switched to mobile - initialize navigation
initializeMobileNavigation();
// Check URL hash for initial section
const hash = window.location.hash.replace('#', '');
if (hash && ['voice', 'analysis', 'guide', 'settings', 'music'].includes(hash)) {
switchMobileSection(hash);
}
} else {
// Switched to desktop - show all sections
document.querySelectorAll('.mobile-section').forEach(section => {
section.classList.add('active');
});
}
}
}
// Update status indicator (matching index.html)
function updateStatus(elementId, status, message) {
const element = document.getElementById(elementId);
if (element) {
const statusText = element.querySelector('.status-text');
if (statusText) {
statusText.textContent = message;
}
// Update status color based on status
const statusIcon = element.querySelector('.status-icon');
if (statusIcon) {
switch(status) {
case 'success':
statusIcon.textContent = '✅';
break;
case 'error':
statusIcon.textContent = '❌';
break;
case 'warning':
statusIcon.textContent = '⚠️';
break;
default:
statusIcon.textContent = '🔄';
}
}
}
}
// ✅ NEW: Update system status indicator
function updateSystemStatus(state, message) {
const statusElement = document.getElementById('system-status');
const statusIcon = document.getElementById('status-icon');
const statusText = document.getElementById('status-text');
if (statusElement && statusIcon && statusText) {
// Remove all status classes
statusElement.classList.remove('status-ready', 'status-listening', 'status-analyzing');
// Add appropriate class and update content
switch(state) {
case 'ready':
statusElement.classList.add('status-ready');
statusIcon.textContent = '⏸️';
statusText.textContent = message || 'Ready to start';
break;
case 'listening':
statusElement.classList.add('status-listening');
statusIcon.textContent = '🎤';
statusText.textContent = message || 'Listening...';
break;
case 'analyzing':
statusElement.classList.add('status-analyzing');
statusIcon.textContent = '🧠';
statusText.textContent = message || 'AI Analyzing...';
break;
case 'transcribing':
statusElement.classList.add('status-listening');
statusIcon.textContent = '📝';
statusText.textContent = message || 'Transcribing...';
break;
default:
statusElement.classList.add('status-ready');
statusIcon.textContent = '⏸️';
statusText.textContent = message || 'Ready';
}
}
}
// Initialize system checks (matching index.html with mobile improvements)
function initializeSystem() {
debugLog('🚀 Initializing WeAD RedFlag Voice System...');
// ✅ NEW: Set initial system status
updateSystemStatus('ready', 'Initializing system...');
// Check if we're on mobile
const isMobile = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
if (isMobile) {
debugLog('📱 Mobile device detected - applying mobile optimizations');
}
// Check HTTPS
if (location.protocol === 'https:' || location.hostname === 'localhost') {
updateStatus('connection-status', 'success', 'Secure Connection');
debugLog('✅ HTTPS check passed', 'success');
} else {
updateStatus('connection-status', 'error', 'HTTPS Required');
debugLog('❌ HTTPS required for Speech Recognition API', 'error');
return;
}
// Check browser support
if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
updateStatus('speech-status', 'success', 'Voice Ready');
debugLog('✅ Browser supports Speech Recognition', 'success');
setupSpeechRecognition();
} else {
updateStatus('speech-status', 'error', 'Not Supported');
debugLog('❌ Browser does not support Speech Recognition', 'error');
return;
}
// Setup WebSocket for Claude AI
setupWebSocket();
// Setup UI event listeners
setupEventListeners();
// Set initial system status
updateSystemStatus('ready', 'Ready to start listening');
}
// Setup Speech Recognition (matching index.html with mobile improvements)
function setupSpeechRecognition() {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
if (!SpeechRecognition) {
debugLog('❌ Speech Recognition API not supported', 'error');
updateStatus('speech-status', 'error', 'Not Supported');
return;
}
recognition = new SpeechRecognition();
// Check if we're on mobile
const isMobile = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
// ✅ FIXED: Consistent settings for both mobile and desktop
recognition.continuous = true; // Enable continuous mode for both mobile and desktop
recognition.interimResults = true;
recognition.lang = document.getElementById('language')?.value || 'en-US';
recognition.maxAlternatives = 3; // Consistent for both mobile and desktop for better accuracy
// Mobile-specific optimizations
if (isMobile) {
debugLog('📱 Mobile: Using continuous mode like desktop for better user experience');
// iOS Safari specific settings
if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
debugLog('📱 iOS detected - applying iOS-specific settings');
// iOS can be more sensitive to silence, so we'll handle restarts more gracefully
}
// Android specific settings
if (/Android/i.test(navigator.userAgent)) {
debugLog('📱 Android detected - applying Android-specific settings');
// Android devices may need different handling for continuous mode
}
}
debugLog('🎙️ Speech Recognition configured');
recognition.onstart = function() {
debugLog('🎤 Speech recognition started', 'success');
isRecording = true;
forceStop = false; // Reset force stop when starting
const startBtn = document.getElementById('startListening');
const stopBtn = document.getElementById('stopListening');
const transcriptStatus = document.getElementById('transcript-status');
if (startBtn) startBtn.disabled = true;
if (stopBtn) stopBtn.disabled = false;
if (transcriptStatus) transcriptStatus.textContent = 'Listening...';
updateStatus('speech-status', 'success', 'Listening');
updateSystemStatus('listening', 'Listening for speech...');
};
recognition.onresult = function(event) {
let interimTranscript = '';
const isMobile = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
debugLog(`📝 Processing ${event.results.length} results (mobile: ${isMobile})`);
// Show transcribing status when we get results
updateSystemStatus('transcribing', 'Transcribing speech...');
for (let i = event.resultIndex; i < event.results.length; i++) {
const result = event.results[i];
const transcript = result[0].transcript;
const confidence = result[0].confidence || 0;
debugLog(`📝 Result ${i}: "${transcript}" (confidence: ${confidence}, final: ${result.isFinal})`);
if (result.isFinal) {
// Use same confidence threshold for both mobile and desktop
const minConfidence = 0.1; // Very low threshold to capture all speech
if (confidence > minConfidence) {
finalTranscript += transcript + ' ';
debugLog(`📝 Final: "${transcript}" (confidence: ${confidence})`, 'success');
// ✅ FIXED: Only analyze if we have enough text and WebSocket is available
if (websocket && websocket.readyState === WebSocket.OPEN && currentSessionId) {
const selectedLanguage = document.getElementById('language')?.value || 'en-US';
// Show analyzing status
updateSystemStatus('analyzing', 'AI analyzing psychological patterns...');
// Show MBTI loading indicator
showMBTILoading();
// 🔒 Include authentication information
const currentUser = simpleLogin?.currentUser || null;
const token = localStorage.getItem('wead_token');
websocket.send(JSON.stringify({
type: 'analyze_text',
text: transcript,
language: selectedLanguage,
sessionId: currentSessionId,
batteryLevel: navigator.getBattery ? 1.0 : 1.0,
connectionType: navigator.connection ? navigator.connection.effectiveType : 'unknown',
// 🔒 Include user authentication info
authenticated: !!token,
userId: currentUser?.id || null,
username: currentUser?.username || null
}));
debugLog(`📤 Sent text to WebSocket for analysis (language: ${selectedLanguage})`);
} else {
debugLog('⚠️ WebSocket not available for analysis - will analyze when connection is restored');
}
} else {
debugLog(`⚠️ Skipping low confidence result: "${transcript}" (confidence: ${confidence})`);
}
} else {
// Show interim results with same threshold for both mobile and desktop
const minInterimConfidence = 0.1; // Very low threshold to show all interim results
if (confidence > minInterimConfidence) {
interimTranscript += transcript;
debugLog(`📝 Interim: "${transcript}" (confidence: ${confidence})`);
}
}
}
// Update UI with better mobile handling
const interimElement = document.getElementById('interimText');
const finalElement = document.getElementById('finalText');
const placeholderElement = document.querySelector('.placeholder-text');
debugLog(`📱 UI Update - Interim: "${interimTranscript}", Final: "${finalTranscript}"`);
if (interimElement) {
interimElement.textContent = interimTranscript;
debugLog(`📱 Updated interim element: ${interimElement.textContent}`);
}
if (finalElement) {
finalElement.textContent = finalTranscript;
debugLog(`📱 Updated final element: ${finalElement.textContent}`);
}
if (placeholderElement) {
if (interimTranscript || finalTranscript) {
placeholderElement.style.display = 'none';
debugLog('📱 Hidden placeholder text');
} else {
placeholderElement.style.display = 'block';
debugLog('📱 Showed placeholder text');
}
}
// Force a UI update for mobile with enhanced visibility
if (isMobile && (interimTranscript || finalTranscript)) {
// Trigger a small delay to ensure UI updates
setTimeout(() => {
if (interimElement) {
interimElement.style.display = 'block';
interimElement.style.visibility = 'visible';
interimElement.style.opacity = '1';
interimElement.style.minHeight = '20px';
interimElement.style.marginBottom = '8px';
// Force a reflow
interimElement.offsetHeight;
}
if (finalElement) {
finalElement.style.display = 'block';
finalElement.style.visibility = 'visible';
finalElement.style.opacity = '1';
finalElement.style.minHeight = '20px';
finalElement.style.marginBottom = '8px';
// Force a reflow
finalElement.offsetHeight;
}
// Ensure transcript container is visible
const transcriptContainer = document.querySelector('.transcript-container');
if (transcriptContainer) {
transcriptContainer.style.display = 'block';
transcriptContainer.style.visibility = 'visible';
transcriptContainer.style.opacity = '1';
transcriptContainer.style.border = '2px solid #00d4aa';
transcriptContainer.style.background = 'rgba(0, 0, 0, 0.3)';
}
// Scroll to transcript on mobile
if (transcriptContainer) {
transcriptContainer.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
debugLog('📱 Mobile: Forced UI visibility update');
}, 100);
}
};
recognition.onerror = function(event) {
debugLog(`❌ Speech recognition error: ${event.error}`, 'error');
// Provide more helpful error messages for mobile
let errorMessage = event.error;
const isMobile = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
if (isMobile) {
switch(event.error) {
case 'not-allowed':
errorMessage = 'Microphone access denied. Please allow microphone access.';
break;
case 'no-speech':
errorMessage = 'No speech detected. Please try speaking louder or check your microphone.';
break;
case 'audio-capture':
errorMessage = 'Microphone not available. Please check your device microphone.';
break;
case 'network':
errorMessage = 'Network error. Please check your internet connection.';
break;
case 'service-not-allowed':
errorMessage = 'Speech recognition service not allowed. Please check your browser settings.';
break;
}
}
updateStatus('speech-status', 'error', `Error: ${errorMessage}`);
resetRecording();
};
recognition.onend = function() {
const isMobile = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
debugLog(`🛑 Speech recognition ended (mobile: ${isMobile}, forceStop: ${forceStop}, isRecording: ${isRecording})`);
// ✅ PRIORITY: If forceStop is true, don't restart regardless of other conditions
if (forceStop) {
debugLog('🛑 Force stop detected - not restarting recognition');
// Don't call resetRecording() here - let the stopRecording function handle it
return;
}
// ✅ CONTINUOUS MONITORING: Only restart if in continuous mode and not force stopped
if (isRecording && !forceStop) {
debugLog('🔄 Speech recognition ended while in continuous monitoring - restarting');
updateSystemStatus('listening', 'Restarting listening...');
// Small delay before restarting to prevent rapid restarts
setTimeout(() => {
if (isRecording && !forceStop && recognition) {
try {
debugLog('🔄 Restarting speech recognition for continuous monitoring');
recognition.start();
} catch (error) {
debugLog(`❌ Failed to restart recognition: ${error.message}`, 'error');
resetRecording();
}
}
}, 100);
} else {
debugLog('🛑 Speech recognition ended - recording was already stopped or force stopped');
// Don't update status here - let stopRecording handle it
}
};
}
// ✅ FIXED: Setup WebSocket connection with authentication
function setupWebSocket() {
try {
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${location.host}`;
console.log(`🔗 Attempting WebSocket connection to: ${wsUrl}`);
// 🔒 Include authentication token if available
const token = localStorage.getItem('wead_token');
const headers = {};
if (token) {
headers.authorization = `Bearer ${token}`;
debugLog('🔐 WebSocket: Including authentication token');
} else {
debugLog('👤 WebSocket: No token available, connecting as guest');
}
// WebSocket doesn't support custom headers in browser, so we'll send auth on first message
websocket = new WebSocket(wsUrl);
websocket.onopen = function() {
updateStatus('ai-status', 'success', 'AI Connected');
debugLog('🔗 WebSocket connected', 'success');
// Wait a moment before creating session to ensure connection is stable
setTimeout(() => {
const isMobile = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
if (isMobile) {
debugLog('📱 Mobile: WebSocket connected successfully');
}
// Double-check WebSocket is still open before creating session
if (websocket && websocket.readyState === WebSocket.OPEN) {
debugLog('✅ WebSocket confirmed open - creating session');
createSession();
} else {
debugLog('❌ WebSocket not ready when attempting to create session');
}
}, 1000);
};
websocket.onclose = function(event) {
updateStatus('ai-status', 'error', 'AI Disconnected');
debugLog(`🔗 WebSocket disconnected (code: ${event.code}, reason: ${event.reason})`, 'error');
currentSessionId = null;
// Attempt to reconnect after a delay
setTimeout(() => {
if (!websocket || websocket.readyState === WebSocket.CLOSED) {
debugLog('🔄 Attempting WebSocket reconnection...');
setupWebSocket();
}
}, 5000);
};
websocket.onerror = function(error) {
debugLog(`🔗 WebSocket error: ${error}`, 'error');
console.error('WebSocket error details:', error);
updateStatus('ai-status', 'error', 'Connection Error');
const isMobile = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
if (isMobile) {
debugLog('📱 Mobile: WebSocket connection failed - this may be due to network issues');
}
};
// ✅ FIXED: Proper message handling for analysis results (matching index.html)
websocket.onmessage = function(event) {
debugLog(`📨 Raw WebSocket message received: ${event.data}`);
try {
const data = JSON.parse(event.data);
debugLog(`📨 Parsed WebSocket message: ${data.type}`);
console.log('Full WebSocket message:', data);
switch(data.type) {
case 'session_created':
currentSessionId = data.session?.id || data.sessionId;
debugLog(`✅ Session created: ${currentSessionId}`);
break;
case 'analysis_result':
debugLog('🧠 Analysis result received');
if (data.analysis) {
displayAIAnalysis(data.analysis);
// ✅ FIXED: Don't automatically reset recording - let displayAIAnalysis handle the logic
// The displayAIAnalysis function will decide whether to stop or continue based on risk score
} else {
debugLog('❌ Analysis result missing analysis data', 'error');
updateSystemStatus('ready', 'Analysis failed - Ready to retry');
}
break;
case 'mobile_optimizations':
debugLog('📱 Mobile optimizations enabled');
break;
case 'error':
debugLog(`❌ WebSocket error: ${data.message}`, 'error');
// Hide MBTI loading indicator on error
hideMBTILoading();
// ✅ FIXED: Handle Error 2099 specifically
if (data.errorCode === '2099' || data.message.includes('Error 2099')) {
updateSystemStatus('ready', 'AI Analysis Failed - Please try again');
updateStatus('ai-status', 'error', 'AI Analysis Failed');
// Show error alert to user
const errorMessage = data.message || 'AI Analysis Failed (Error 2099)';
alert(`🚨 ${errorMessage}\n\nPlease check your internet connection and try again.`);
// Reset recording state
resetRecording();
} else {
debugLog(`❌ WebSocket error: ${data.message}`);
console.error('WebSocket error details:', data);
updateSystemStatus('ready', `Error: ${data.message || 'Unknown error'} - Ready to retry`);
}
break;
default:
debugLog(`📨 Unknown message type: ${data.type}`);
}
} catch (error) {
debugLog(`❌ Error parsing WebSocket message: ${error.message}`, 'error');
console.error('WebSocket message parsing error:', error);
updateSystemStatus('ready', 'Message parsing error - Ready to retry');
}
};
} catch (error) {
debugLog(`🔗 WebSocket setup failed: ${error}`, 'error');
updateStatus('ai-status', 'warning', 'Offline Mode');
// Fallback: try to create session without WebSocket
setTimeout(() => {
if (!currentSessionId) {
currentSessionId = 'offline-' + Date.now();
debugLog(`📱 Created offline session: ${currentSessionId}`);
}
}, 1000);
}
}
// ✅ NEW: Create session via WebSocket (matching index.html)
function createSession() {
debugLog('🔧 Attempting to create session...');
if (!websocket) {
debugLog('❌ WebSocket not initialized');
return;
}
if (websocket.readyState !== WebSocket.OPEN) {
debugLog(`❌ WebSocket not ready (state: ${websocket.readyState})`);
return;
}
try {
// 🔒 Include user information if authenticated
const currentUser = simpleLogin?.currentUser || null;
const token = localStorage.getItem('wead_token');
const sessionMessage = {
type: 'create_session',
isMobile: /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),
batteryLevel: 1.0, // Default
connectionType: 'unknown',
// 🔒 Include authentication info
authenticated: !!token,
userId: currentUser?.id || null,
username: currentUser?.username || null
};
debugLog(`📤 Sending session creation message: ${JSON.stringify(sessionMessage)}`);
websocket.send(JSON.stringify(sessionMessage));
debugLog('✅ Session creation request sent successfully');
} catch (error) {
debugLog(`❌ Error sending session creation message: ${error.message}`);
console.error('Session creation error:', error);
}
}
// Setup UI event listeners (matching index.html)
function setupEventListeners() {
// Voice control buttons
const startBtn = document.getElementById('startListening');
const stopBtn = document.getElementById('stopListening');
const clearBtn = document.getElementById('clearTranscript');
if (startBtn) {
startBtn.addEventListener('click', startRecording);
debugLog('✅ Start button event listener added');
} else {
debugLog('❌ Start button not found', 'error');
}
if (stopBtn) {
stopBtn.addEventListener('click', function() {
// ✅ FIXED: Use proper context and add null checks
const button = this;
if (button) {
// ✅ IMMEDIATE VISUAL FEEDBACK
button.style.transform = 'scale(0.95)';
button.style.opacity = '0.8';
// Call stopRecording
stopRecording();
// ✅ RESTORE BUTTON APPEARANCE AFTER SHORT DELAY
setTimeout(() => {
if (button) {
button.style.transform = '';
button.style.opacity = '';
}
}, 150);
}
});
debugLog('✅ Stop button event listener added');
} else {
debugLog('❌ Stop button not found', 'error');
}
if (clearBtn) {
clearBtn.addEventListener('click', clearTranscript);
debugLog('✅ Clear button event listener added');
} else {
debugLog('❌ Clear button not found', 'error');
}
// Tab switching
const tabBtns = document.querySelectorAll('.tab-btn');
if (tabBtns.length > 0) {
tabBtns.forEach(btn => {
btn.addEventListener('click', () => switchTab(btn.dataset.tab));
});
debugLog(`✅ Tab buttons event listeners added (${tabBtns.length} buttons)`);
} else {
debugLog('❌ Tab buttons not found', 'error');
}
// Settings
const languageSelect = document.getElementById('language');
if (languageSelect) {
languageSelect.addEventListener('change', (e) => {
if (recognition) {
recognition.lang = e.target.value;
debugLog(`🌐 Language changed to: ${e.target.value}`);
}
});
debugLog('✅ Language select event listener added');
} else {
debugLog('❌ Language select not found', 'error');
}
// Action buttons
const exportBtn = document.getElementById('export-data');
const resetBtn = document.getElementById('reset-session');
const saveBtn = document.getElementById('save-settings');
if (exportBtn) {
exportBtn.addEventListener('click', exportData);
debugLog('✅ Export button event listener added');
} else {
debugLog('❌ Export button not found', 'error');
}
if (resetBtn) {
resetBtn.addEventListener('click', resetSession);
debugLog('✅ Reset button event listener added');
} else {
debugLog('❌ Reset button not found', 'error');
}
if (saveBtn) {
saveBtn.addEventListener('click', saveSettings);
debugLog('✅ Save settings button event listener added');
} else {
debugLog('❌ Save settings button not found', 'error');
}
debugLog('✅ All event listeners setup completed');
}
// ✅ NEW: Continuous monitoring functions
function toggleContinuousMonitoring() {
const continuousBtn = document.getElementById('continuousMonitoring');
const startBtn = document.getElementById('startListening');
const stopBtn = document.getElementById('stopListening');
if (!forceStop) { // Only toggle if not force stopped
forceStop = true; // Force stop to break restart loop
// Update continuous button
continuousBtn.classList.remove('active');
continuousBtn.querySelector('.btn-text').textContent = 'Continuous Monitoring';
continuousBtn.querySelector('.btn-icon').textContent = '🔍';
// Re-enable normal recording buttons
if (startBtn) startBtn.disabled = false;
if (stopBtn) stopBtn.disabled = true; // Stop should be disabled when not recording
debugLog('🔍 Continuous monitoring mode DEACTIVATED', 'success');
updateStatus('speech-status', 'success', 'Voice Ready');
// Stop recording
if (isRecording) {
stopRecording();
}
} else {
// Start continuous monitoring
forceStop = false; // Reset force stop
// Update continuous button
continuousBtn.classList.add('active');
continuousBtn.querySelector('.btn-text').textContent = 'Stop Monitoring';
continuousBtn.querySelector('.btn-icon').textContent = '🛑';
// Disable normal recording buttons during continuous monitoring
if (startBtn) startBtn.disabled = true;
if (stopBtn) stopBtn.disabled = true;
debugLog('🔍 Continuous monitoring mode ACTIVATED', 'warning');
updateStatus('speech-status', 'warning', 'Continuous Monitoring Active');
// Start recording for continuous monitoring
startRecordingForContinuous();
}
}
// NEW: Separate function for starting recording in continuous mode
function startRecordingForContinuous() {
const isMobile = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
if (!recognition) {
debugLog('❌ Speech recognition not available', 'error');
return;
}
// Request microphone permission
navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true
}
})
.then(function(stream) {
updateStatus('speech-status', 'success', 'Continuous Monitoring Active');
debugLog('🎤 Microphone permission granted for continuous monitoring', 'success');
stream.getTracks().forEach(track => track.stop());
setTimeout(() => {
try {
recognition.start();
debugLog('🎤 Continuous monitoring recording started');
} catch (error) {
debugLog(`❌ Failed to start continuous monitoring: ${error.message}`, 'error');
updateStatus('speech-status', 'error', 'Failed to start monitoring');
}
}, 300);
})
.catch(function(error) {
debugLog(`🎤 Microphone error for continuous monitoring: ${error.message}`, 'error');
updateStatus('speech-status', 'error', `Mic Error: ${error.message}`);
});
}
// UPDATED: Start recording function - only for normal mode
function startRecording() {
if (isRecording) return;
forceStop = false;
redFlagsDetected = false;
const startBtn = document.getElementById('startListening');
const stopBtn = document.getElementById('stopListening');
if (startBtn) {
startBtn.disabled = true;
startBtn.querySelector('.btn-text').textContent = 'Listening...';
}
if (stopBtn) stopBtn.disabled = false;
const isMobile = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
if (!recognition) {
debugLog('❌ Speech recognition not available', 'error');
return;
}
// Additional check for mobile devices
if (isMobile) {
debugLog('📱 Mobile: Checking speech recognition state...');
if (!recognition.start) {
debugLog('❌ Mobile: Speech recognition start method not available', 'error');
updateStatus('speech-status', 'error', 'Speech recognition not properly initialized');
return;
}
}
if (isMobile) {
debugLog('📱 Mobile device detected - using mobile-optimized permission flow');
}
// Request microphone permission with better error handling
navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true
}
})
.then(function(stream) {
updateStatus('speech-status', 'success', 'Microphone Ready');
debugLog('🎤 Microphone permission granted', 'success');
// Stop the stream (we just needed permission)
stream.getTracks().forEach(track => track.stop());
// Small delay for mobile devices to ensure permission is fully processed
setTimeout(() => {
try {
// For mobile, we need to handle the start more carefully
if (isMobile) {
// Clear any existing recognition state
if (recognition && recognition.abort) {
recognition.abort();
}
// Small additional delay for mobile
setTimeout(() => {
recognition.start();
debugLog('🎤 Speech recognition started on mobile');
}, 200);
} else {
recognition.start();
debugLog('🎤 Speech recognition started on desktop');
}
} catch (error) {
debugLog(`❌ Failed to start recognition: ${error.message}`, 'error');
updateStatus('speech-status', 'error', 'Failed to start recognition');
}
}, isMobile ? 300 : 100);
})
.catch(function(error) {
let errorMessage = error.message;
// Provide more helpful error messages for mobile
if (isMobile) {
switch(error.name) {
case 'NotAllowedError':
errorMessage = 'Microphone access denied. Please allow microphone access in your browser settings.';
break;
case 'NotFoundError':
errorMessage = 'No microphone found. Please check your device has a microphone.';
break;
case 'NotReadableError':
errorMessage = 'Microphone is in use by another application. Please close other apps using the microphone.';
break;
case 'SecurityError':
errorMessage = 'Microphone access blocked for security reasons. Please check your browser settings.';
break;
}
}
updateStatus('speech-status', 'error', `Mic Error: ${errorMessage}`);
debugLog(`🎤 Microphone error: ${errorMessage}`, 'error');
});
}
// UPDATED: Stop recording function - works for both modes