-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
1465 lines (1271 loc) · 50.8 KB
/
app.js
File metadata and controls
1465 lines (1271 loc) · 50.8 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
// Deepgram API is now proxied through the backend to keep API key secure
// DOM elements
const notesInput = document.getElementById('notesInput');
const formatBtn = document.getElementById('formatBtn');
const resultSection = document.getElementById('resultSection');
const resultContent = document.getElementById('resultContent');
const errorMessage = document.getElementById('errorMessage');
const loadingOverlay = document.getElementById('loadingOverlay');
const loadingMessage = document.getElementById('loadingMessage');
const recordBtn = document.getElementById('recordBtn');
const recordTabBtn = document.getElementById('recordTabBtn');
const recordBothBtn = document.getElementById('recordBothBtn');
const settingsBtn = document.getElementById('settingsBtn');
const backBtn = document.getElementById('backBtn');
const mainPage = document.getElementById('mainPage');
const settingsPage = document.getElementById('settingsPage');
const darkModeToggle = document.getElementById('darkModeToggle');
const audioInputSelect = document.getElementById('audioInputSelect');
const refreshDevicesBtn = document.getElementById('refreshDevicesBtn');
const generateEmailBtn = document.getElementById('generateEmailBtn');
const emailPage = document.getElementById('emailPage');
const emailBackBtn = document.getElementById('emailBackBtn');
const emailRecipient = document.getElementById('emailRecipient');
const generateEmailSubmitBtn = document.getElementById('generateEmailSubmitBtn');
const emailResultSection = document.getElementById('emailResultSection');
const emailResultContent = document.getElementById('emailResultContent');
const emailErrorMessage = document.getElementById('emailErrorMessage');
// Speech-to-text state
let isRecording = false;
let isRecordingTab = false;
let isRecordingBoth = false;
let mediaRecorder = null;
let audioStream = null;
let selectedFormat = null;
let segmentChunks = [];
let recordingMode = 'mic'; // 'mic', 'tab', or 'both'
let audioContext = null;
let micStream = null;
let tabStream = null;
// Support for bullet points and indentation in textarea
notesInput.addEventListener('keydown', (e) => {
// Handle Tab key for indentation
if (e.key === 'Tab') {
e.preventDefault();
const start = notesInput.selectionStart;
const end = notesInput.selectionEnd;
const value = notesInput.value;
if (e.shiftKey) {
// Shift+Tab: Unindent
const linesBefore = value.substring(0, start).split('\n');
const currentLineIndex = linesBefore.length - 1;
const currentLine = linesBefore[currentLineIndex];
if (currentLine.startsWith(' ') || currentLine.startsWith('\t')) {
const newValue = value.substring(0, start - (currentLine.startsWith(' ') ? 2 : 1)) +
value.substring(start);
notesInput.value = newValue;
notesInput.selectionStart = notesInput.selectionEnd = start - (currentLine.startsWith(' ') ? 2 : 1);
}
} else {
// Tab: Indent
const linesBefore = value.substring(0, start).split('\n');
const currentLineIndex = linesBefore.length - 1;
// If there's a selection spanning multiple lines, indent all selected lines
if (start !== end) {
const selectedText = value.substring(start, end);
const lines = selectedText.split('\n');
const indentedLines = lines.map(line => ' ' + line);
const newValue = value.substring(0, start) + indentedLines.join('\n') + value.substring(end);
notesInput.value = newValue;
notesInput.selectionStart = start;
notesInput.selectionEnd = start + indentedLines.join('\n').length;
} else {
// Just indent current line
const newValue = value.substring(0, start) + ' ' + value.substring(start);
notesInput.value = newValue;
notesInput.selectionStart = notesInput.selectionEnd = start + 2;
}
}
}
// Handle Enter key to continue bullet points
if (e.key === 'Enter') {
const start = notesInput.selectionStart;
const value = notesInput.value;
const linesBefore = value.substring(0, start).split('\n');
const currentLine = linesBefore[linesBefore.length - 1];
// Check if current line starts with a bullet point
const bulletPattern = /^(\s*)([-•*]\s|[-•*]|\d+\.\s)/;
const match = currentLine.match(bulletPattern);
if (match) {
e.preventDefault();
const indent = match[1]; // Preserve indentation
const bullet = match[2]; // Get the bullet character
// Determine next bullet (for numbered lists, increment)
let nextBullet = bullet;
const numberedMatch = bullet.match(/^(\d+)\.\s?/);
if (numberedMatch) {
const num = parseInt(numberedMatch[1]);
nextBullet = (num + 1) + '. ';
} else {
// Keep the same bullet character (•, -, or *)
nextBullet = bullet.trim() + ' ';
}
const newValue = value.substring(0, start) + '\n' + indent + nextBullet + value.substring(start);
notesInput.value = newValue;
const newPos = start + 1 + indent.length + nextBullet.length;
notesInput.selectionStart = notesInput.selectionEnd = newPos;
}
}
});
// Convert HTML to plain text with bullet points
function convertHtmlToPlainText(html) {
// Create a temporary div to parse HTML
const tempDiv = document.createElement('div');
tempDiv.innerHTML = html;
// Function to count nesting level (how many ul/ol parents)
function getNestingLevel(node) {
let level = 0;
let parent = node.parentElement;
while (parent) {
if (parent.tagName?.toLowerCase() === 'ul' || parent.tagName?.toLowerCase() === 'ol') {
level++;
}
parent = parent.parentElement;
}
return level;
}
// Function to process a node and convert to plain text
function processNode(node, indent = '') {
let result = '';
if (node.nodeType === Node.TEXT_NODE) {
// Text node - preserve whitespace
const text = node.textContent || '';
return text;
}
if (node.nodeType === Node.ELEMENT_NODE) {
const tagName = node.tagName?.toLowerCase();
if (tagName === 'ul' || tagName === 'ol') {
// List container - process children (don't add extra indent here)
const children = Array.from(node.childNodes);
children.forEach((child) => {
result += processNode(child, indent);
});
} else if (tagName === 'li') {
// List item - add bullet point with proper indentation
const nestingLevel = getNestingLevel(node);
const indentSpaces = ' '.repeat(nestingLevel - 1); // -1 because root level is 0 indent
// Determine bullet type
const isOrdered = node.parentElement?.tagName?.toLowerCase() === 'ol';
let bullet = '• ';
if (isOrdered) {
// Count previous li siblings at same level to get number
const parentList = node.parentElement;
const siblings = Array.from(parentList.children);
const index = siblings.indexOf(node);
bullet = (index + 1) + '. ';
}
// Process children to get text content
const children = Array.from(node.childNodes);
let itemText = '';
let hasNestedList = false;
children.forEach(child => {
if (child.nodeType === Node.ELEMENT_NODE) {
const childTag = child.tagName?.toLowerCase();
if (childTag === 'ul' || childTag === 'ol') {
hasNestedList = true;
// Process nested list with increased indent
itemText += processNode(child, indentSpaces + ' ');
} else {
// Other elements (p, span, etc.)
itemText += processNode(child, '');
}
} else {
itemText += processNode(child, '');
}
});
// Clean up the item text
itemText = itemText.trim();
if (itemText || hasNestedList) {
// If there's a nested list, don't add the bullet on the same line
if (hasNestedList) {
// Add the main item text if it exists
if (itemText && !itemText.includes('•') && !itemText.match(/^\d+\./)) {
result += indentSpaces + bullet + itemText.split('\n')[0] + '\n';
}
// The nested list will be added by processNode
result += itemText;
} else {
result += indentSpaces + bullet + itemText + '\n';
}
}
} else if (tagName === 'p' || tagName === 'div') {
// Paragraph or div - process children and add newline
const children = Array.from(node.childNodes);
let paraText = '';
children.forEach(child => {
paraText += processNode(child, indent);
});
paraText = paraText.trim();
if (paraText) {
result += indent + paraText + '\n';
}
} else if (tagName === 'br') {
// Line break
result += '\n';
} else {
// Other elements - process children
const children = Array.from(node.childNodes);
children.forEach(child => {
result += processNode(child, indent);
});
}
}
return result;
}
// Process all nodes
let text = '';
const children = Array.from(tempDiv.childNodes);
children.forEach(child => {
text += processNode(child);
});
// Clean up extra newlines but preserve structure
return text.replace(/\n{3,}/g, '\n\n').trim();
}
// Handle paste to preserve formatting and convert HTML bullets
notesInput.addEventListener('paste', (e) => {
e.preventDefault();
const clipboardData = e.clipboardData || window.clipboardData;
let paste = clipboardData.getData('text/plain');
const htmlPaste = clipboardData.getData('text/html');
// If HTML is available and contains lists, convert it
if (htmlPaste && (htmlPaste.includes('<ul') || htmlPaste.includes('<ol') || htmlPaste.includes('<li'))) {
paste = convertHtmlToPlainText(htmlPaste);
}
// Preserve the text (white-space: pre-wrap will handle formatting)
const start = notesInput.selectionStart;
const end = notesInput.selectionEnd;
const value = notesInput.value;
const newValue = value.substring(0, start) + paste + value.substring(end);
notesInput.value = newValue;
// Set cursor position after pasted text
const newPos = start + paste.length;
notesInput.selectionStart = notesInput.selectionEnd = newPos;
// Trigger input event for any listeners
notesInput.dispatchEvent(new Event('input'));
});
// Audio format selection
function selectBestAudioFormat() {
const formatOptions = [
'audio/webm;codecs=opus',
'audio/webm',
'audio/ogg;codecs=opus',
'audio/mp4',
'audio/wav'
];
for (const format of formatOptions) {
if (MediaRecorder.isTypeSupported(format)) {
return format;
}
}
return null; // Fallback to browser default
}
// Transcribe audio with Deepgram (via backend proxy)
async function transcribeWithDeepgram(audioBlob) {
// Check blob size - too small might be invalid
if (audioBlob.size < 100) {
console.log('Skipping too small audio chunk:', audioBlob.size, 'bytes');
return null;
}
try {
// Send audio blob directly as binary to backend
const response = await fetch('/api/transcribe', {
method: 'POST',
body: audioBlob
// Don't set Content-Type - let browser set it automatically
});
if (!response.ok) {
const error = await response.json();
if (response.status === 401 || response.status === 500) {
throw new Error(error.message || 'Invalid Deepgram API key. Please check your configuration.');
} else if (response.status === 400) {
console.warn('Deepgram rejected audio chunk (possibly incomplete):', error.message);
return null; // Don't throw, just skip this chunk
}
throw new Error(error.message || `Transcription error: ${response.status}`);
}
const result = await response.json();
// Extract transcript from Deepgram response
if (result.results && result.results.channels && result.results.channels.length > 0) {
const channel = result.results.channels[0];
if (channel.alternatives && channel.alternatives.length > 0) {
const transcript = channel.alternatives[0].transcript;
if (transcript && transcript.trim()) {
return transcript.trim();
}
}
}
return null;
} catch (error) {
console.error('Transcription error:', error);
throw error;
}
}
// Add transcription to textarea
function addTranscription(transcript) {
const currentText = notesInput.value;
const cursorPos = notesInput.selectionStart;
// Add space before if there's existing text and it doesn't end with space/newline
const prefix = currentText && !currentText.match(/[\s\n]$/) ? ' ' : '';
// Insert transcript at cursor position or append to end
const newText = currentText.substring(0, cursorPos) + prefix + transcript + currentText.substring(cursorPos);
notesInput.value = newText;
// Move cursor to end of inserted text
const newCursorPos = cursorPos + prefix.length + transcript.length;
notesInput.selectionStart = notesInput.selectionEnd = newCursorPos;
// Trigger input event
notesInput.dispatchEvent(new Event('input'));
}
// Start recording from microphone
async function startRecording() {
try {
stopAllRecordings(); // Stop any active recording
// Use selected audio device if available
const constraints = { audio: true };
if (selectedAudioDeviceId) {
constraints.audio = { deviceId: { exact: selectedAudioDeviceId } };
}
audioStream = await navigator.mediaDevices.getUserMedia(constraints);
recordingMode = 'mic';
await setupRecording();
} catch (error) {
console.error('Error starting microphone recording:', error);
showError(`Failed to start microphone recording: ${error.message}`);
isRecording = false;
recordBtn.classList.remove('recording');
}
}
// Combine two audio streams into one
async function combineAudioStreams(micStream, tabStream) {
try {
// Create audio context
audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Create source nodes from both streams
const micSource = audioContext.createMediaStreamSource(micStream);
const tabSource = audioContext.createMediaStreamSource(tabStream);
// Create a destination node to mix both streams
const destination = audioContext.createMediaStreamDestination();
// Connect both sources to the destination (mixing)
micSource.connect(destination);
tabSource.connect(destination);
// Return the mixed stream
return destination.stream;
} catch (error) {
console.error('Error combining audio streams:', error);
throw error;
}
}
// Start recording from both microphone and tab audio
async function startBothRecording() {
try {
stopAllRecordings(); // Stop any active recording
// Use selected audio device if available
const micConstraints = { audio: true };
if (selectedAudioDeviceId) {
micConstraints.audio = { deviceId: { exact: selectedAudioDeviceId } };
}
const [mic, tab] = await Promise.all([
navigator.mediaDevices.getUserMedia(micConstraints),
navigator.mediaDevices.getDisplayMedia({
video: true,
audio: {
echoCancellation: false,
noiseSuppression: false,
autoGainControl: false,
suppressLocalAudioPlayback: false
}
})
]);
// Check if tab audio track exists
const tabAudioTracks = tab.getAudioTracks();
if (tabAudioTracks.length === 0) {
// User didn't share audio
mic.getTracks().forEach(track => track.stop());
tab.getTracks().forEach(track => track.stop());
showError('No audio track detected in tab. Please make sure to check "Share tab audio" when selecting a tab.');
isRecordingBoth = false;
recordBothBtn.classList.remove('recording');
return;
}
// Stop video track if present (we only need audio)
const videoTracks = tab.getVideoTracks();
videoTracks.forEach(track => track.stop());
// Store individual streams for cleanup
micStream = mic;
tabStream = tab;
// Combine the two audio streams
audioStream = await combineAudioStreams(mic, tab);
recordingMode = 'both';
await setupRecording();
// Handle user stopping sharing from browser UI
tabAudioTracks[0].addEventListener('ended', () => {
if (isRecordingBoth) {
stopBothRecording();
}
});
} catch (error) {
console.error('Error starting both recording:', error);
if (error.name === 'NotAllowedError') {
showError('Permission denied. Please allow microphone and tab sharing to record audio.');
} else {
showError(`Failed to start recording: ${error.message}`);
}
isRecordingBoth = false;
recordBothBtn.classList.remove('recording');
// Clean up streams if they were created
if (micStream) {
micStream.getTracks().forEach(track => track.stop());
micStream = null;
}
if (tabStream) {
tabStream.getTracks().forEach(track => track.stop());
tabStream = null;
}
if (audioContext) {
audioContext.close();
audioContext = null;
}
}
}
// Start recording from tab audio
async function startTabRecording() {
try {
// Request tab audio capture
audioStream = await navigator.mediaDevices.getDisplayMedia({
video: true,
audio: {
echoCancellation: false,
noiseSuppression: false,
autoGainControl: false,
suppressLocalAudioPlayback: false
}
});
// Check if audio track exists
const audioTracks = audioStream.getAudioTracks();
if (audioTracks.length === 0) {
// User didn't share audio
audioStream.getTracks().forEach(track => track.stop());
showError('No audio track detected. Please make sure to check "Share tab audio" when selecting a tab.');
isRecordingTab = false;
recordTabBtn.classList.remove('recording');
return;
}
// Stop video track if present (we only need audio)
const videoTracks = audioStream.getVideoTracks();
videoTracks.forEach(track => track.stop());
recordingMode = 'tab';
await setupRecording();
// Handle user stopping sharing from browser UI
audioTracks[0].addEventListener('ended', () => {
if (isRecordingTab) {
stopTabRecording();
}
});
} catch (error) {
console.error('Error starting tab recording:', error);
if (error.name === 'NotAllowedError') {
showError('Permission denied. Please allow tab sharing to record audio.');
} else {
showError(`Failed to start tab recording: ${error.message}`);
}
isRecordingTab = false;
recordTabBtn.classList.remove('recording');
}
}
// Setup recording (shared logic for both mic and tab)
async function setupRecording() {
try {
// Select best audio format
selectedFormat = selectBestAudioFormat();
if (!selectedFormat) {
throw new Error('No supported audio format found');
}
console.log('Using audio format:', selectedFormat);
// Create MediaRecorder
mediaRecorder = new MediaRecorder(audioStream, {
mimeType: selectedFormat,
audioBitsPerSecond: 128000
});
segmentChunks = [];
// Handle data available
mediaRecorder.ondataavailable = (event) => {
if (event.data && event.data.size > 0) {
segmentChunks.push(event.data);
}
};
// Handle recording stop
mediaRecorder.onstop = async () => {
if (segmentChunks.length > 0) {
const audioBlob = new Blob(segmentChunks, {
type: selectedFormat || 'audio/webm'
});
// Only send if large enough (reduced threshold for live transcription)
if (audioBlob.size > 8000) {
try {
const transcription = await transcribeWithDeepgram(audioBlob);
if (transcription && transcription.trim()) {
addTranscription(transcription);
}
} catch (error) {
console.error('Transcription error:', error);
// Don't show error to user for individual chunk failures
}
}
segmentChunks = []; // Clear for next segment
// Restart if still recording (reduced delay for live transcription)
const stillRecording = (recordingMode === 'mic' && isRecording) ||
(recordingMode === 'tab' && isRecordingTab) ||
(recordingMode === 'both' && isRecordingBoth);
if (stillRecording && mediaRecorder && mediaRecorder.state === 'inactive') {
setTimeout(() => {
const stillRecordingCheck = (recordingMode === 'mic' && isRecording) ||
(recordingMode === 'tab' && isRecordingTab) ||
(recordingMode === 'both' && isRecordingBoth);
if (stillRecordingCheck && mediaRecorder) {
mediaRecorder.start();
// Stop after 2 seconds for live transcription
setTimeout(() => {
if (mediaRecorder && mediaRecorder.state === 'recording') {
mediaRecorder.stop();
}
}, 2000);
}
}, 200); // Reduced delay between segments
}
}
};
// Start first segment (use 2 seconds for live transcription)
mediaRecorder.start();
setTimeout(() => {
if (mediaRecorder && mediaRecorder.state === 'recording') {
mediaRecorder.stop();
}
}, 2000); // Reduced to 2 seconds for live transcription
if (recordingMode === 'mic') {
isRecording = true;
recordBtn.classList.add('recording');
} else if (recordingMode === 'tab') {
isRecordingTab = true;
recordTabBtn.classList.add('recording');
} else if (recordingMode === 'both') {
isRecordingBoth = true;
recordBothBtn.classList.add('recording');
}
} catch (error) {
console.error('Error setting up recording:', error);
showError(`Failed to setup recording: ${error.message}`);
if (recordingMode === 'mic') {
isRecording = false;
recordBtn.classList.remove('recording');
} else if (recordingMode === 'tab') {
isRecordingTab = false;
recordTabBtn.classList.remove('recording');
} else if (recordingMode === 'both') {
isRecordingBoth = false;
recordBothBtn.classList.remove('recording');
}
if (audioStream) {
audioStream.getTracks().forEach(track => track.stop());
audioStream = null;
}
if (micStream) {
micStream.getTracks().forEach(track => track.stop());
micStream = null;
}
if (tabStream) {
tabStream.getTracks().forEach(track => track.stop());
tabStream = null;
}
if (audioContext) {
audioContext.close();
audioContext = null;
}
}
}
// Stop microphone recording
function stopRecording() {
isRecording = false;
recordBtn.classList.remove('recording');
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
}
if (audioStream) {
audioStream.getTracks().forEach(track => track.stop());
audioStream = null;
}
mediaRecorder = null;
segmentChunks = [];
}
// Stop tab recording
function stopTabRecording() {
isRecordingTab = false;
recordTabBtn.classList.remove('recording');
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
}
if (audioStream) {
audioStream.getTracks().forEach(track => track.stop());
audioStream = null;
}
mediaRecorder = null;
segmentChunks = [];
}
// Stop both recording
function stopBothRecording() {
isRecordingBoth = false;
recordBothBtn.classList.remove('recording');
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
}
// Stop all streams
if (micStream) {
micStream.getTracks().forEach(track => track.stop());
micStream = null;
}
if (tabStream) {
tabStream.getTracks().forEach(track => track.stop());
tabStream = null;
}
if (audioStream) {
audioStream.getTracks().forEach(track => track.stop());
audioStream = null;
}
// Close audio context
if (audioContext) {
audioContext.close();
audioContext = null;
}
mediaRecorder = null;
segmentChunks = [];
}
// Stop all recording modes
function stopAllRecordings() {
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
}
if (audioStream) {
audioStream.getTracks().forEach(track => track.stop());
audioStream = null;
}
if (micStream) {
micStream.getTracks().forEach(track => track.stop());
micStream = null;
}
if (tabStream) {
tabStream.getTracks().forEach(track => track.stop());
tabStream = null;
}
if (audioContext) {
audioContext.close();
audioContext = null;
}
isRecording = false;
isRecordingTab = false;
isRecordingBoth = false;
recordBtn.classList.remove('recording');
recordTabBtn.classList.remove('recording');
recordBothBtn.classList.remove('recording');
mediaRecorder = null;
segmentChunks = [];
}
// Record button handlers
recordBtn.addEventListener('click', () => {
// Stop tab recording if active
if (isRecordingTab) {
stopTabRecording();
}
if (isRecording) {
stopRecording();
} else {
startRecording();
}
});
recordTabBtn.addEventListener('click', () => {
// Stop other recordings if active
if (isRecording) {
stopRecording();
}
if (isRecordingBoth) {
stopBothRecording();
}
if (isRecordingTab) {
stopTabRecording();
} else {
startTabRecording();
}
});
recordBothBtn.addEventListener('click', () => {
// Stop other recordings if active
if (isRecording) {
stopRecording();
}
if (isRecordingTab) {
stopTabRecording();
}
if (isRecordingBoth) {
stopBothRecording();
} else {
startBothRecording();
}
});
// Loading messages to cycle through
const loadingMessages = [
'Reading Notes...',
'Performing Analysis On Notes...',
'Extracting Key Details...',
'Formatting Notes...',
'Finalizing Results...'
];
let loadingMessageIndex = 0;
let loadingMessageInterval = null;
let allMessagesShown = false;
let requestCompleted = false;
// Format button handler
formatBtn.addEventListener('click', async () => {
const rawNotes = notesInput.value.trim();
if (!rawNotes) {
showError('Please enter some notes to format');
return;
}
formatBtn.disabled = true;
formatBtn.querySelector('.btn-text').style.display = 'none';
formatBtn.querySelector('.btn-loader').style.display = 'inline';
hideError();
resultSection.style.display = 'none';
// Show loading overlay with rotating messages
showLoadingOverlay();
try {
// Create an AbortController with a 5 minute timeout for long-running workflows
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5 * 60 * 1000); // 5 minutes
const response = await fetch('/api/format', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
raw_notes: rawNotes
}),
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'Failed to format notes');
}
const data = await response.json();
displayResult(data.formatted_notes, data.is_structured);
} catch (error) {
if (error.name === 'AbortError') {
showError('Request timed out. The workflow is still running - please check Scout logs and try again.');
} else {
showError(`Error: ${error.message}`);
}
} finally {
// Mark request as completed, but wait for all messages to show
requestCompleted = true;
tryHideLoadingOverlay();
formatBtn.disabled = false;
formatBtn.querySelector('.btn-text').style.display = 'inline';
formatBtn.querySelector('.btn-loader').style.display = 'none';
}
});
// Display formatted result
function displayResult(formattedText, isStructured = false) {
// Clean up the text - remove markdown code blocks if present
let cleanText = formattedText;
if (typeof cleanText === 'string') {
// Handle: ```json { ... } ```
cleanText = cleanText
.replace(/^```json\s*\{/i, '{') // ```json { at start
.replace(/\}\s*```$/g, '}') // } ``` at end
.replace(/^```json\s*\n?/i, '') // ```json\n at start
.replace(/^```\s*\n?/i, '') // ```\n at start
.replace(/\n?\s*```$/g, '') // ``` at end
.replace(/^```json\s*/i, '') // ```json at start (no newline)
.replace(/\s*```$/g, '') // ``` at end (no newline)
.trim();
}
// Try to parse as JSON to see if it's structured meeting synthesis
// (Try even if server didn't mark it as structured, as a fallback)
try {
const data = JSON.parse(cleanText);
if (data.bluf && data.meeting_recap) {
// Render structured meeting synthesis
renderMeetingSynthesis(data);
resultSection.style.display = 'block';
resultSection.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
return;
}
} catch (e) {
// Not JSON, continue to plain text rendering
if (isStructured) {
console.warn('Failed to parse structured JSON:', e);
} else {
console.warn('Could not parse as JSON:', e);
}
}
// Fallback to plain text
// Add a header with copy button for plain text output
const plainTextHtml = `
<div class="plain-text-header">
<h2>Formatted Notes</h2>
<div class="synthesis-actions">
<button class="btn-copy" onclick="copyFormattedOutput(event)">Copy Formatted Output</button>
</div>
</div>
<div class="plain-text-content">${escapeHtml(cleanText)}</div>
`;
resultContent.innerHTML = plainTextHtml;
// Store plain text globally for copy function
window.formattedPlainText = cleanText;
// Show email generation button if we have structured data
const resultActions = document.getElementById('resultActions');
if (resultActions) {
resultActions.style.display = 'none'; // Hide by default
}
resultSection.style.display = 'block';
resultSection.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
// Render structured meeting synthesis
function renderMeetingSynthesis(data) {
const { bluf, meeting_recap } = data;
const { first_level, second_level, third_level } = meeting_recap || {};
let html = `
<div class="meeting-synthesis">
<div class="synthesis-header">
<h2>Meeting Synthesis</h2>
<div class="synthesis-actions">
<button class="btn-copy" onclick="copySynthesisJSON(event)">Copy JSON</button>
<button class="btn-download" onclick="downloadSynthesisJSON()">Download JSON</button>
<button class="btn-copy" onclick="copyFormattedOutput(event)">Copy Formatted Output</button>
</div>
</div>
<div class="synthesis-content">
<h1>${formatTitle('Bluf')}</h1>
${renderBody(bluf)}
<h1>${formatTitle('Meeting_recap')}</h1>
<h2>${formatTitle('First_level')}</h2>
<p class="body-label">${formatTitle('What_was_covered')}</p>
${renderBulletArray(first_level?.what_was_covered || [])}
<p class="body-label">${formatTitle('Commitments_made')}</p>
${renderBulletArray(first_level?.commitments_made || [])}
<p class="body-label">${formatTitle('New_information')}</p>
${renderBulletArray(first_level?.new_information || [])}
<p class="body-label">${formatTitle('Customer_uncertainties')}</p>
${renderBulletArray(first_level?.customer_uncertainties || [])}
<p class="body-label">${formatTitle('Open_items')}</p>
${renderBulletArray(first_level?.open_items || [])}
<h2>${formatTitle('Second_level')}</h2>
<p class="body-label">${formatTitle('Mental_model_gaps')}</p>
${renderBody(second_level?.mental_model_gaps)}
<p class="body-label">${formatTitle('Customer_confidence_signals')}</p>
${renderBody(second_level?.customer_confidence_signals)}
<p class="body-label">${formatTitle('Approach_limitations')}</p>