-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
3683 lines (3270 loc) · 134 KB
/
app.js
File metadata and controls
3683 lines (3270 loc) · 134 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
/**
* EchoLocate Phase 1 — app.js
*
* Dynamic voice clusters with 10-second room profiling and VTT export.
* Uses Web Speech API + Web Audio API + Meyda + HTMX + Service Worker local routes.
*/
'use strict';
const CFG = Object.freeze({
STORAGE_KEY: 'echolocate_v1',
PITCH_WINDOW: 24,
PITCH_HZ: 8,
WATCHDOG_MS: 10_000,
CARD_LIMIT: 500,
RESTART_DELAY: 150,
SIGNATURE_MATCH_SIMILARITY: 0.85,
SIGNATURE_HIGH_SIMILARITY: 0.93,
SIGNATURE_MED_SIMILARITY: 0.88,
HYSTERESIS_LOCK_MS: 400,
HYSTERESIS_MARGIN: 0.06,
MATCH_HISTORY_SIZE: 3,
ROOM_PROFILE_MS: 10_000,
MFCC_COEFFS: 13,
MAX_SPEAKERS: 6,
DEBUG_POINTS_MAX: 120,
DEBUG_LOG_MAX: 75,
NETWORK_MAX_RETRIES: 5,
NETWORK_ONLINE_MAX_RETRIES: 3,
NETWORK_BACKOFF_INIT_MS: 1_000,
NETWORK_BACKOFF_MAX_MS: 30_000,
// Sessions that end within this many milliseconds without producing any
// speech result are considered "quick ends" (e.g. Android Chrome firing
// no-speech immediately). Consecutive quick ends trigger exponential backoff
// so the restart loop doesn't spin at 150 ms on devices where recognition
// terminates instantly.
QUICK_RESTART_THRESHOLD_MS: 3_000,
// On mobile Chrome the recognition API often runs for the full ~5 s timeout
// and ends without ever firing onresult (no-speech is silently swallowed).
// After this many consecutive sessions that produce no result (and last longer
// than QUICK_RESTART_THRESHOLD_MS), apply exponential backoff and surface a
// helpful status message so the user knows to check their microphone.
NO_RESULT_BACKOFF_COUNT: 3,
// After this many consecutive no-result sessions on mobile (= NO_RESULT_BACKOFF_COUNT * 2),
// show the "speech not detected" help modal with actionable troubleshooting steps.
MOBILE_FAILURE_MODAL_COUNT: 6,
// Minimum RMS energy value (0–100 scale from channelEnergy()) to consider the
// microphone "active". Values above this threshold mean the waveform is moving
// and audio is reaching the AudioContext, which distinguishes mic-works-but-SR-silent
// from genuinely no audio.
MIC_ENERGY_ACTIVE_THRESHOLD: 1,
// Minimum ratio of system-audio energy to mic energy required to attribute
// a card to the computer source rather than the microphone. A value of 1.5
// means the computer audio must be 50 % louder than the mic before we call
// it "remote/computer" — empirically robust against mic-pickup of speakers.
SYSTEM_AUDIO_ENERGY_RATIO: 1.5,
});
function apiUrl(path) {
return new URL(`./api/${path}`, location.href).href;
}
const API = Object.freeze({
ADD_CARD: apiUrl('add-card'),
ADD_CHAT_MSG: apiUrl('add-chat-msg'),
});
const DEFAULT_RECOGNITION_LANG = '';
const TRANSLATION_MAX_TARGETS = 2;
const DEFAULT_TRANSLATION_TARGETS = Object.freeze([
{ code: 'ar', label: 'Arabic', flag: '🇸🇦' },
{ code: 'zh', label: 'Chinese (Simplified)', flag: '🇨🇳' },
{ code: 'cs', label: 'Czech', flag: '🇨🇿' },
{ code: 'da', label: 'Danish', flag: '🇩🇰' },
{ code: 'nl', label: 'Dutch', flag: '🇳🇱' },
{ code: 'fi', label: 'Finnish', flag: '🇫🇮' },
{ code: 'fr', label: 'French', flag: '🇫🇷' },
{ code: 'de', label: 'German', flag: '🇩🇪' },
{ code: 'hi', label: 'Hindi', flag: '🇮🇳' },
{ code: 'hu', label: 'Hungarian', flag: '🇭🇺' },
{ code: 'it', label: 'Italian', flag: '🇮🇹' },
{ code: 'ja', label: 'Japanese', flag: '🇯🇵' },
{ code: 'ko', label: 'Korean', flag: '🇰🇷' },
{ code: 'no', label: 'Norwegian', flag: '🇳🇴' },
{ code: 'pl', label: 'Polish', flag: '🇵🇱' },
{ code: 'pt', label: 'Portuguese', flag: '🇵🇹' },
{ code: 'ro', label: 'Romanian', flag: '🇷🇴' },
{ code: 'ru', label: 'Russian', flag: '🇷🇺' },
{ code: 'es', label: 'Spanish', flag: '🇪🇸' },
{ code: 'sv', label: 'Swedish', flag: '🇸🇪' },
{ code: 'tr', label: 'Turkish', flag: '🇹🇷' },
{ code: 'uk', label: 'Ukrainian', flag: '🇺🇦' },
]);
const LANGUAGE_OPTIONS = [
{ code: '', label: 'None (Auto)', flag: '🌐' },
{ code: 'en-US', label: 'English (US)', flag: '🇺🇸' },
{ code: 'en-GB', label: 'English (UK)', flag: '🇬🇧' },
{ code: 'es-ES', label: 'Spanish (Spain)', flag: '🇪🇸' },
{ code: 'es-MX', label: 'Spanish (Mexico)', flag: '🇲🇽' },
{ code: 'fr-FR', label: 'French', flag: '🇫🇷' },
{ code: 'de-DE', label: 'German', flag: '🇩🇪' },
{ code: 'it-IT', label: 'Italian', flag: '🇮🇹' },
{ code: 'pt-BR', label: 'Portuguese (Brazil)', flag: '🇧🇷' },
{ code: 'pt-PT', label: 'Portuguese (Portugal)', flag: '🇵🇹' },
{ code: 'nl-NL', label: 'Dutch', flag: '🇳🇱' },
{ code: 'sv-SE', label: 'Swedish', flag: '🇸🇪' },
{ code: 'no-NO', label: 'Norwegian', flag: '🇳🇴' },
{ code: 'da-DK', label: 'Danish', flag: '🇩🇰' },
{ code: 'fi-FI', label: 'Finnish', flag: '🇫🇮' },
{ code: 'pl-PL', label: 'Polish', flag: '🇵🇱' },
{ code: 'cs-CZ', label: 'Czech', flag: '🇨🇿' },
{ code: 'hu-HU', label: 'Hungarian', flag: '🇭🇺' },
{ code: 'ro-RO', label: 'Romanian', flag: '🇷🇴' },
{ code: 'ru-RU', label: 'Russian', flag: '🇷🇺' },
{ code: 'uk-UA', label: 'Ukrainian', flag: '🇺🇦' },
{ code: 'tr-TR', label: 'Turkish', flag: '🇹🇷' },
{ code: 'el-GR', label: 'Greek', flag: '🇬🇷' },
{ code: 'ar-SA', label: 'Arabic', flag: '🇸🇦' },
{ code: 'he-IL', label: 'Hebrew', flag: '🇮🇱' },
{ code: 'hi-IN', label: 'Hindi', flag: '🇮🇳' },
{ code: 'bn-BD', label: 'Bengali', flag: '🇧🇩' },
{ code: 'ta-IN', label: 'Tamil', flag: '🇮🇳' },
{ code: 'te-IN', label: 'Telugu', flag: '🇮🇳' },
{ code: 'th-TH', label: 'Thai', flag: '🇹🇭' },
{ code: 'vi-VN', label: 'Vietnamese', flag: '🇻🇳' },
{ code: 'id-ID', label: 'Indonesian', flag: '🇮🇩' },
{ code: 'ms-MY', label: 'Malay', flag: '🇲🇾' },
{ code: 'ja-JP', label: 'Japanese', flag: '🇯🇵' },
{ code: 'ko-KR', label: 'Korean', flag: '🇰🇷' },
{ code: 'cmn-Hans-CN', label: 'Chinese (Simplified)', flag: '🇨🇳' },
{ code: 'cmn-Hant-TW', label: 'Chinese (Traditional)', flag: '🇹🇼' },
];
const ISO3_TO_BCP47 = {
eng: 'en-US', spa: 'es-ES', fra: 'fr-FR', deu: 'de-DE', ita: 'it-IT', por: 'pt-BR',
nld: 'nl-NL', rus: 'ru-RU', ukr: 'uk-UA', tur: 'tr-TR', ell: 'el-GR', ara: 'ar-SA',
heb: 'he-IL', hin: 'hi-IN', ben: 'bn-BD', tam: 'ta-IN', tel: 'te-IN', tha: 'th-TH',
vie: 'vi-VN', ind: 'id-ID', msa: 'ms-MY', jpn: 'ja-JP', kor: 'ko-KR', cmn: 'cmn-Hans-CN',
};
const SPEAKER_TRANSLATION_PREFS_KEY = 'echolocate-speaker-translation-prefs';
const LLM_PROMPT_PREFIX =
`# Role
Act as a professional Executive Assistant and Expert Scribe. Your goal is to synthesize the following meeting transcript into a highly organized, concise summary.
# Context
The transcript may contain anonymous speakers (e.g., "Speaker 1", "Speaker A"). Even if names are not provided, maintain the distinction between these individuals to capture the "threaded" nature of the debate or discussion.
# Tasks
1. **Executive Summary**: A 2-3 sentence overview of the meeting's purpose and primary outcome.
2. **Threaded Discussion Points**: Organize the core of the meeting by "Topic Threads." For each thread:
- Identify the main topic.
- Summarize the back-and-forth, highlighting differing perspectives from specific speakers (e.g., "Speaker 1 proposed X, while Speaker 2 raised concerns about Y").
3. **Action Items**: Extract all tasks, deadlines, and owners mentioned. Use a checklist format. If an owner is not specified, label it "Unassigned."
4. **Decisions Made**: List any final conclusions or "dead ends" reached during the session.
# Constraints
- Be concise. Use bullet points.
- Remove filler words ("um," "uh," "like") and repetitive conversational loops.
- Use bolding for key terms and speaker identifiers.
# Transcript
`;
function normalizeTranslationTargets(input) {
return [...new Set(
(Array.isArray(input) ? input : [])
.map((code) => String(code || '').toLowerCase())
.filter((code) => /^[a-z]{2,8}$/.test(code))
)].slice(0, TRANSLATION_MAX_TARGETS);
}
function parseMaxSpeakers(raw) {
const n = parseInt(raw || '', 10);
return Math.min(CFG.MAX_SPEAKERS, Math.max(1, isNaN(n) ? CFG.MAX_SPEAKERS : n));
}
function loadTranslationTargets() {
try {
const raw = localStorage.getItem('echolocate-translation-targets');
if (!raw) return [];
const parsed = JSON.parse(raw);
if (!Array.isArray(parsed)) return [];
return parsed
.map((code) => String(code || '').toLowerCase())
.filter((code) => /^[a-z]{2,8}$/.test(code))
.slice(0, TRANSLATION_MAX_TARGETS);
} catch {
return [];
}
}
function loadSpeakerTranslationPrefs() {
try {
const raw = localStorage.getItem(SPEAKER_TRANSLATION_PREFS_KEY);
if (!raw) return {};
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
const out = {};
for (const [speakerId, pref] of Object.entries(parsed)) {
if (!/^s\d+$/.test(String(speakerId))) continue;
const mode = pref?.mode;
if (!['global', 'off', 'custom'].includes(mode)) continue;
out[speakerId] = {
mode,
targets: mode === 'custom' ? normalizeTranslationTargets(pref?.targets) : [],
};
}
return out;
} catch {
return {};
}
}
function persistSpeakerTranslationPrefs() {
try {
localStorage.setItem(SPEAKER_TRANSLATION_PREFS_KEY, JSON.stringify(State.speakerTranslationPrefs));
} catch {
// Ignore localStorage quota errors.
}
}
function getSpeakerTranslationPref(profileId) {
const pref = State.speakerTranslationPrefs[profileId];
if (!pref || !['global', 'off', 'custom'].includes(pref.mode)) {
return { mode: 'global', targets: [] };
}
return {
mode: pref.mode,
targets: pref.mode === 'custom' ? normalizeTranslationTargets(pref.targets) : [],
};
}
function setSpeakerTranslationPref(profileId, pref) {
if (!/^s\d+$/.test(String(profileId))) return;
const mode = pref?.mode;
if (!['global', 'off', 'custom'].includes(mode)) return;
State.speakerTranslationPrefs[profileId] = {
mode,
targets: mode === 'custom' ? normalizeTranslationTargets(pref?.targets) : [],
};
persistSpeakerTranslationPrefs();
}
function removeSpeakerTranslationPref(profileId) {
delete State.speakerTranslationPrefs[profileId];
persistSpeakerTranslationPrefs();
}
function getEffectiveTranslationTargetsForProfile(profile) {
if (!State.translationEnabled || State.translationCapability !== 'supported' || !profile) return [];
const pref = getSpeakerTranslationPref(profile.id);
if (pref.mode === 'off') return [];
if (pref.mode === 'custom') return normalizeTranslationTargets(pref.targets);
return normalizeTranslationTargets(State.translationTargets);
}
const State = {
isRunning: false,
pitchHistory: [],
utteranceSamples: [],
currentUtteranceStartedAt: null,
recognitionLang: localStorage.getItem('echolocate-rec-lang') ?? DEFAULT_RECOGNITION_LANG,
languageDetector: null,
supportedLanguages: [],
lastResultAt: 0,
languageHintTimer: null,
audioCtx: null,
analyser: null,
meydaAnalyzer: null,
latestSignatureFrame: null,
utteranceSignatureSamples: [],
profilingStartedAt: 0,
sampleTimer: null,
visualizer: null,
profiles: [], // [{id,label,color,lastSpokenAt,avgPitch,tone,el,cardsEl,count}]
activeSpeakerId: null,
speakerLock: null,
matchHistory: [],
nextSpeakerNum: 1,
micDiagnostics: null,
stereoEnabled: false,
stereoAnalyserL: null,
stereoAnalyserR: null,
stereoSamplesL: [],
stereoSamplesR: [],
debugEnabled: false,
debugPoints: [],
mediaSource: null,
// Audio source detection
audioInputDeviceId: localStorage.getItem('echolocate-audio-device') ?? '',
systemAudioEnabled: false,
systemAudioStream: null,
systemAudioAnalyser: null,
systemAudioSamples: [], // RMS energy samples during current utterance
micEnergySamples: [], // mic RMS samples for source comparison
speechSupported: true, // set to false by checkBrowserSupport() when API is absent
maxSpeakers: parseMaxSpeakers(localStorage.getItem('echolocate-max-speakers')),
// Translation
translationEnabled: localStorage.getItem('echolocate-translation-enabled') === '1',
translationTargets: loadTranslationTargets(),
speakerTranslationPrefs: loadSpeakerTranslationPrefs(),
translationCapability: 'checking', // checking | supported | unsupported
translatorStatus: 'idle', // idle | checking | available | downloading | unavailable | unsupported
};
const PALETTE = ['#4dabf7', '#cc5de8', '#f59f00', '#20c997', '#ff8787', '#74c0fc', '#ffd43b', '#b197fc'];
// ── Browser-based translation (Chrome Built-in AI Translator API) ─────────────
// Translation is progressive enhancement and off by default.
// Audio and transcripts stay in the browser; only language models are fetched
// from Chrome's servers on first use, then cached locally.
const Translation = {
_cache: new Map(), // "source:target" → Translator instance
isSupported() {
return !!(
window.Translator &&
typeof window.Translator.availability === 'function' &&
typeof window.Translator.create === 'function'
);
},
setStatus(text, statusClass = 'checking') {
const el = document.getElementById('translation-status');
if (!el) return;
if (!text) { el.textContent = ''; el.className = 'translation-status hidden'; return; }
el.textContent = text;
el.className = `translation-status translation-status--${statusClass}`;
},
sourceFromTag(tag) {
const s = String(tag || '').trim();
return s ? s.toLowerCase().split('-')[0] : 'en';
},
// ensurePair: get or create a cached Translator instance for one language pair.
// Calls the optional onProgress(pct) callback during model download.
// Returns null when the pair is unavailable or creation fails.
async ensurePair(source, target, { onProgress } = {}) {
const key = `${source}:${target}`;
if (this._cache.has(key)) return this._cache.get(key);
let availability;
try {
availability = await window.Translator.availability({ sourceLanguage: source, targetLanguage: target });
} catch {
return null;
}
if (availability === 'unavailable') return null;
try {
const translator = await window.Translator.create({
sourceLanguage: source,
targetLanguage: target,
monitor(m) {
m.addEventListener('downloadprogress', (e) => {
if (onProgress && e.total) onProgress(Math.round((e.loaded / e.total) * 100));
});
},
});
this._cache.set(key, translator);
return translator;
} catch (err) {
console.warn(`[EchoLocate] Translator.create failed (${source}→${target}):`, err);
return null;
}
},
// preWarmTranslators: kick off ALL selected pair downloads in parallel so
// models are ready before the user speaks. Shows live combined progress.
async preWarmTranslators(source, targets) {
if (!this.isSupported() || !targets.length) return;
const pairs = targets.filter((t) => t !== source);
if (!pairs.length) return;
const progress = Object.fromEntries(pairs.map((t) => [t, 0]));
const refreshStatus = () => {
const allReady = pairs.every((t) => this._cache.has(`${source}:${t}`));
if (allReady) return; // final status set below
const avg = Math.round(pairs.reduce((s, t) => s + (progress[t] || 0), 0) / pairs.length);
const waiting = pairs.filter((t) => !this._cache.has(`${source}:${t}`)).map((t) => t.toUpperCase());
this.setStatus(
`Downloading translation model${waiting.length > 1 ? 's' : ''} (${waiting.join(' + ')})${avg > 0 ? ` ${avg}%` : ''}… captions continue normally.`,
'downloading'
);
};
this.setStatus(
`Preparing translation model${pairs.length > 1 ? 's' : ''} (${pairs.map((t) => t.toUpperCase()).join(' + ')})… captions continue normally.`,
'downloading'
);
await Promise.allSettled(
pairs.map((target) =>
this.ensurePair(source, target, {
onProgress: (pct) => { progress[target] = pct; refreshStatus(); },
})
)
);
const ready = pairs.filter((t) => this._cache.has(`${source}:${t}`));
if (ready.length) {
State.translatorStatus = 'available';
this.setStatus(`Ready: ${ready.map((t) => t.toUpperCase()).join(' + ')}`, 'available');
} else {
this.setStatus('Translation unavailable for selected languages', 'unavailable');
}
},
// translateToTargets: translate final text into all selected targets in parallel.
// Returns [{lang, text}, …]. Never blocks the caption pipeline.
async translateToTargets(text, sourceTag, targets) {
if (!text || !this.isSupported()) return [];
const source = this.sourceFromTag(sourceTag);
const cleanTargets = [...new Set(
(Array.isArray(targets) ? targets : [])
.map((c) => String(c || '').toLowerCase())
.filter((c) => /^[a-z]{2,8}$/.test(c))
)].slice(0, TRANSLATION_MAX_TARGETS).filter((t) => t !== source);
if (!cleanTargets.length) return [];
const results = await Promise.allSettled(
cleanTargets.map(async (target) => {
const translator = await this.ensurePair(source, target);
if (!translator) return null;
const out = await translator.translate(text);
return out?.trim() ? { lang: target, text: out.trim() } : null;
})
);
return results
.filter((r) => r.status === 'fulfilled' && r.value)
.map((r) => r.value);
},
};
// ── Translation controls (opt-in + compact dropdown, max 2 targets) ──────────
async function initTranslationControls() {
const toggle = document.getElementById('translation-enabled-toggle');
const langBtn = document.getElementById('translation-lang-btn');
const dropdown = document.getElementById('translation-lang-dropdown');
const list = document.getElementById('translation-target-list');
const note = document.getElementById('translation-selection-note');
const help = document.getElementById('translation-config-help');
if (!toggle || !langBtn || !dropdown || !list || !note || !help) return;
State.translationCapability = Translation.isSupported() ? 'supported' : 'unsupported';
if (State.translationCapability === 'unsupported') {
State.translationEnabled = false;
localStorage.setItem('echolocate-translation-enabled', '0');
help.textContent = 'Translation requires Chrome 131+ with built-in AI features enabled in Chrome settings → AI features. Reload after enabling.';
help.classList.remove('hidden');
Translation.setStatus('Not available in this browser', 'unsupported');
} else {
help.textContent = 'First use downloads a small model (5–20 MB) locally. Captions continue normally during download.';
help.classList.remove('hidden');
}
// Build language checklist inside dropdown
list.innerHTML = '';
for (const lang of DEFAULT_TRANSLATION_TARGETS) {
const id = `translation-target-${lang.code}`;
const wrapper = document.createElement('label');
wrapper.className = 'translation-target-option';
wrapper.setAttribute('for', id);
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.id = id;
checkbox.value = lang.code;
checkbox.checked = State.translationTargets.includes(lang.code);
const span = document.createElement('span');
span.textContent = `${lang.flag} ${lang.label}`;
wrapper.appendChild(checkbox);
wrapper.appendChild(span);
list.appendChild(wrapper);
checkbox.addEventListener('change', () => {
const selected = Array.from(
list.querySelectorAll('input[type="checkbox"]:checked')
).map((el) => el.value);
if (selected.length > TRANSLATION_MAX_TARGETS) {
checkbox.checked = false;
note.textContent = `Choose up to ${TRANSLATION_MAX_TARGETS} languages.`;
note.classList.remove('hidden');
return;
}
note.classList.add('hidden');
State.translationTargets = selected;
localStorage.setItem('echolocate-translation-targets', JSON.stringify(selected));
Translation._cache.clear();
updateLangBtnLabel();
refreshAllLaneTranslationControls();
if (State.translationEnabled && State.translationCapability === 'supported' && selected.length) {
const src = Translation.sourceFromTag(State.recognitionLang);
Translation.preWarmTranslators(src, selected).catch(() => {});
}
});
}
// Sync persisted selection back to DOM state
const selectedNow = Array.from(
list.querySelectorAll('input[type="checkbox"]:checked')
).map((el) => el.value);
State.translationTargets = selectedNow.slice(0, TRANSLATION_MAX_TARGETS);
localStorage.setItem('echolocate-translation-targets', JSON.stringify(State.translationTargets));
// Button label: "NL · FR ▾" or "+ languages" when none selected
function updateLangBtnLabel() {
const btnText = document.getElementById('translation-lang-btn-text');
if (!btnText) return;
if (!State.translationTargets.length) {
btnText.textContent = '+ languages';
return;
}
const selected = DEFAULT_TRANSLATION_TARGETS.filter((l) => State.translationTargets.includes(l.code));
btnText.textContent = selected.map((l) => `${l.flag} ${l.code.toUpperCase()}`).join(' · ') + ' ▾';
}
// Dropdown open / close
function openDropdown() {
dropdown.classList.remove('hidden');
langBtn.setAttribute('aria-expanded', 'true');
// Move keyboard focus into the menu so users can immediately choose targets.
const firstFocusable = dropdown.querySelector('input[type="checkbox"]:checked')
|| dropdown.querySelector('input[type="checkbox"]');
if (firstFocusable) firstFocusable.focus();
}
function closeDropdown() {
dropdown.classList.add('hidden');
langBtn.setAttribute('aria-expanded', 'false');
}
langBtn.addEventListener('click', (e) => {
e.stopPropagation();
dropdown.classList.contains('hidden') ? openDropdown() : closeDropdown();
});
dropdown.addEventListener('click', (e) => e.stopPropagation());
document.addEventListener('click', closeDropdown);
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && !dropdown.classList.contains('hidden')) {
closeDropdown();
langBtn.focus();
}
});
toggle.checked = State.translationEnabled && State.translationCapability === 'supported';
toggle.disabled = State.translationCapability !== 'supported';
const syncEnabledState = () => {
const enabled = !!toggle.checked && State.translationCapability === 'supported';
State.translationEnabled = enabled;
localStorage.setItem('echolocate-translation-enabled', enabled ? '1' : '0');
refreshAllLaneTranslationControls();
if (!enabled) {
langBtn.hidden = true;
closeDropdown();
Translation.setStatus('', 'checking');
return;
}
langBtn.hidden = false;
updateLangBtnLabel();
if (!State.translationTargets.length) {
Translation.setStatus('Choose at least one target language', 'checking');
return;
}
// Pre-warm all selected pairs in the background immediately on enable
const src = Translation.sourceFromTag(State.recognitionLang);
Translation.preWarmTranslators(src, State.translationTargets).catch(() => {});
};
syncEnabledState();
toggle.addEventListener('change', syncEnabledState);
updateLangBtnLabel();
refreshAllLaneTranslationControls();
}
function checkSecureContext() {
if (!window.isSecureContext) {
document.getElementById('secure-warning').classList.remove('hidden');
}
}
function isEdgeBrowser() {
// Detect Chromium-based Edge (not legacy EdgeHTML / "Edge" 18 and earlier).
return /Edg\//.test(navigator.userAgent);
}
function isChromeBrowser() {
// Detect Chrome (including Chrome on Android), but not Edge (which also
// includes "Chrome/" in its UA string).
return /Chrome\//.test(navigator.userAgent) && !/Edg\//.test(navigator.userAgent);
}
function isMobileBrowser() {
// Detect mobile browsers (Android, iPhone, iPad, iPod).
return /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
}
function parseBrowserName() {
// Returns a short human-readable browser + platform label for debug reports,
// e.g. "Chrome 147 on Android", "Edge 125 on Windows", "Firefox 115".
const ua = navigator.userAgent;
if (/Edg\//.test(ua)) {
const m = ua.match(/Edg\/([\d]+)/);
return m ? `Edge ${m[1]}` : 'Edge';
}
if (/Chrome\//.test(ua)) {
const m = ua.match(/Chrome\/([\d]+)/);
const name = m ? `Chrome ${m[1]}` : 'Chrome';
if (/Android/.test(ua)) return `${name} on Android`;
if (/iPhone|iPad|iPod/.test(ua)) return `${name} on iOS`;
return name;
}
if (/Firefox\//.test(ua)) {
const m = ua.match(/Firefox\/([\d]+)/);
return m ? `Firefox ${m[1]}` : 'Firefox';
}
if (/Safari\//.test(ua) && !/Chrome\//.test(ua)) {
const m = ua.match(/Version\/([\d]+)/);
if (/iPhone|iPad|iPod/.test(ua)) return m ? `Safari ${m[1]} on iOS` : 'Safari on iOS';
return m ? `Safari ${m[1]}` : 'Safari';
}
return 'Unknown';
}
function checkBrowserSupport() {
const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
if (SR) {
// Web Speech API is present. For Edge users who have not yet seen the
// setup guide, show a proactive info modal so they know what to configure
// before pressing Start.
if (isEdgeBrowser() && !localStorage.getItem(EDGE_MODAL_DISMISSED_KEY)) {
// Defer to next microtask so the rest of boot() finishes first.
Promise.resolve().then(() => {
showSpeechHelpModal(
'⚠ Edge: enable online speech recognition',
EDGE_SETUP_HTML,
'info',
);
});
} else if (isMobileBrowser() && !localStorage.getItem(MOBILE_MODAL_DISMISSED_KEY)) {
// Mobile browsers report SR as available but often fail silently.
// Warn the user proactively so they know before they press Start.
Promise.resolve().then(() => {
showSpeechHelpModal(
'⚠ Mobile: speech recognition may be limited',
MOBILE_SPEECH_WARNING_HTML,
'info',
);
});
}
return true;
}
State.speechSupported = false;
// Switch the welcome screen to the "unsupported" message so the user is
// not told to press Start in a browser where it will never work.
const welcomeContent = document.getElementById('empty-stage-welcome');
const unsupportedContent = document.getElementById('empty-stage-unsupported');
if (welcomeContent) welcomeContent.classList.add('hidden');
if (unsupportedContent) unsupportedContent.classList.remove('hidden');
const stage = document.getElementById('empty-stage');
if (stage) stage.classList.remove('hidden');
const start = document.getElementById('btn-start');
const stop = document.getElementById('btn-stop');
if (start) start.disabled = true;
if (stop) stop.disabled = true;
setStatus('error', 'Web Speech API not supported');
// Show the inline banner as well as the modal so there is always a visible
// persistent reminder even after the modal is closed.
const warning = document.getElementById('speech-warning');
if (warning) warning.classList.remove('hidden');
Promise.resolve().then(() => {
const browserName = isEdgeBrowser() ? 'Microsoft Edge' : 'this browser';
showSpeechHelpModal(
'⚠ Speech recognition not available',
`<p><strong>${escapeHTML(browserName)}</strong> does not support the
Web Speech API required for live transcription.</p>
<p>For best results, use <strong>Google Chrome</strong> in a regular
(non-incognito) window.</p>
<p>Microsoft Edge also supports it, but requires
<strong>Use online speech recognition</strong> to be enabled in
<strong>Edge Settings → Privacy, search, and services → Services</strong>
(<code>edge://settings/privacy</code>).</p>`,
);
});
return false;
}
// ── Speech Help Modal ─────────────────────────────────────────────────────────
const EDGE_SETUP_HTML = `
<p>You are using <strong>Microsoft Edge</strong>, which requires
<strong>Use online speech recognition</strong> to be enabled before
EchoLocate can transcribe speech.</p>
<p><strong>To enable it in Edge:</strong></p>
<ol>
<li>Copy this address and paste it into a new Edge tab:<br>
<code>edge://settings/privacy</code></li>
<li>Scroll down to the <strong>Services</strong> section</li>
<li>Turn on <strong>Use online speech recognition</strong></li>
<li>Return here and press <strong>Start</strong></li>
</ol>
<p>If that option is missing, a browser or organization policy may be
blocking it — contact your IT administrator, or switch to
<strong>Google Chrome</strong>.</p>
<p>Speech recognition is also blocked in <strong>InPrivate</strong>
windows — open a regular Edge window instead.</p>
`;
const SPEECH_BLOCKED_HTML = `
<p>Speech recognition is blocked. This can happen in:</p>
<ol>
<li><strong>Private / Incognito windows</strong> — try a regular browser window</li>
<li><strong>Browsers with restricted settings</strong> — check that microphone
access is permitted for this site</li>
</ol>
<p>For the best experience, use <strong>Google Chrome</strong> in a
regular (non-incognito) window.</p>
`;
const MOBILE_SPEECH_WARNING_HTML = `
<p>You are using a <strong>mobile browser</strong>. Speech recognition
support on mobile devices is limited and may not work reliably.</p>
<p>On Android, Chrome's speech recognition requires a stable connection to
Google's servers. If nothing is transcribed:</p>
<ul>
<li>Grant <strong>microphone permission</strong> for this site in Chrome,
and also in <strong>Android Settings → Apps → Chrome → Permissions</strong></li>
<li>Ensure you have a <strong>stable internet connection</strong></li>
<li>Close other apps that may be using the microphone</li>
</ul>
<p>For the most reliable experience, use <strong>Google Chrome on a
desktop or laptop computer</strong>.</p>
`;
const MOBILE_SPEECH_FAILURE_HTML = `
<p>Speech recognition has not detected any audio for several sessions.
If the <strong>waveform bar at the bottom of the screen moves</strong> when
you speak, the microphone is working — but audio is not reaching the
recognition engine. This is a known conflict between the audio waveform
display and Chrome's speech recognition on some Android devices.</p>
<p><strong>Steps to try:</strong></p>
<ol>
<li>Press <strong>Stop</strong>, then <strong>Start</strong> and speak
as soon as the status shows <em>Starting…</em></li>
<li><strong>Reload the page</strong> and try again — this fully resets
the audio system</li>
<li>Check that Chrome has microphone permission in
<strong>Android Settings → Apps → Chrome → Permissions</strong></li>
<li>Close other apps that may be using the microphone (calls, video
apps, voice assistants)</li>
<li>Make sure you have a stable internet connection — Chrome on Android
sends audio to Google's servers for recognition</li>
</ol>
<p>If none of these help, try <strong>Google Chrome on a desktop or
laptop</strong> for the most reliable experience.</p>
`;
const MOBILE_CHROME_NETWORK_ERROR_HTML = `
<p>You are using <strong>Chrome on Android</strong>, which sends speech
audio to Google's servers over the internet. Network errors mean Chrome
could not reach those servers.</p>
<p><strong>Steps to try:</strong></p>
<ol>
<li>Check that you have a <strong>stable internet connection</strong>
(Wi-Fi or mobile data)</li>
<li>Make sure this site is <strong>not open in an Incognito window</strong>
— Chrome on Android blocks speech recognition in Incognito mode</li>
<li>Go to <strong>Android Settings → Apps → Chrome → Permissions</strong>
and confirm the <strong>Microphone</strong> permission is granted</li>
<li>Close any other apps that may be using the microphone (calls, video
apps, voice assistants)</li>
<li><strong>Reload the page</strong> and press <strong>Start</strong>
again</li>
</ol>
<p>If the problem persists, try <strong>Google Chrome on a desktop or
laptop</strong> for the most reliable experience.</p>
`;
const EDGE_MODAL_DISMISSED_KEY = 'echolocate-edge-modal-dismissed';
const MOBILE_MODAL_DISMISSED_KEY = 'echolocate-mobile-modal-dismissed';
// All callers must pass only trusted, pre-defined HTML strings — never user-
// controlled content. The bodyHTML parameter is always sourced from the
// module-level constants (EDGE_SETUP_HTML, SPEECH_BLOCKED_HTML) or inline
// literals built with escapeHTML() for any dynamic parts.
function showSpeechHelpModal(title, bodyHTML, level = 'error') {
const modal = document.getElementById('speech-help-modal');
if (!modal) return;
const titleEl = document.getElementById('speech-modal-title');
const bodyEl = document.getElementById('speech-modal-body');
if (titleEl) {
titleEl.textContent = title;
titleEl.className = level === 'info'
? 'speech-modal-title info'
: 'speech-modal-title';
}
if (bodyEl) bodyEl.innerHTML = bodyHTML;
if (!modal.open) modal.showModal();
}
function initSpeechHelpModal() {
const modal = document.getElementById('speech-help-modal');
const closeBtn = document.getElementById('speech-modal-close');
const okBtn = document.getElementById('speech-modal-ok');
if (!modal) return;
const handleClose = () => {
modal.close();
// Remember that the user has seen the proactive info so we don't show it every load.
if (isEdgeBrowser()) {
localStorage.setItem(EDGE_MODAL_DISMISSED_KEY, '1');
} else if (isMobileBrowser()) {
localStorage.setItem(MOBILE_MODAL_DISMISSED_KEY, '1');
}
};
if (closeBtn) closeBtn.addEventListener('click', handleClose);
if (okBtn) okBtn.addEventListener('click', handleClose);
// Close on backdrop click (click on the <dialog> element itself, not its contents).
// Registered once here; initSpeechHelpModal() must only be called once (from boot()).
modal.addEventListener('click', (e) => {
if (e.target === modal) handleClose();
});
}
// ── Theme ─────────────────────────────────────────────────────────────────────────────────
const THEME_KEY = 'echolocate-theme';
function applyTheme(theme, persist = true) {
document.documentElement.setAttribute('data-theme', theme);
const btn = document.getElementById('theme-toggle');
if (btn) {
btn.setAttribute('aria-label', theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode');
}
if (persist) localStorage.setItem(THEME_KEY, theme);
}
function initTheme() {
// inline script in <head> already set data-theme; here we sync aria-label
// and listen for OS preference changes when user hasn't made a manual choice.
const saved = localStorage.getItem(THEME_KEY);
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
applyTheme(saved || (prefersDark ? 'dark' : 'light'), !!saved);
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
if (!localStorage.getItem(THEME_KEY)) applyTheme(e.matches ? 'dark' : 'light', false);
});
}
async function registerServiceWorker() {
if (!('serviceWorker' in navigator)) {
console.warn('[EchoLocate] Service workers not supported in this browser — HTMX card fragments will not work.');
return;
}
try {
const reg = await navigator.serviceWorker.register('./sw.js');
console.log('[EchoLocate] Service worker registered (scope:', reg.scope, ')');
await navigator.serviceWorker.ready;
// navigator.serviceWorker.ready resolves when the SW is *active*, but
// clients.claim() inside the activate handler may not have completed yet,
// leaving a window where the SW is active but not yet controlling this page.
// If that happens the htmx API POSTs bypass the SW and hit GitHub Pages
// directly, which returns 405. Wait for the controller to be set first.
if (!navigator.serviceWorker.controller) {
await new Promise((resolve) => {
navigator.serviceWorker.addEventListener('controllerchange', resolve, { once: true });
});
}
console.log('[EchoLocate] Service worker active and controlling page.');
} catch (err) {
console.warn('[EchoLocate] SW registration skipped:', err.message);
}
}
class Visualizer {
constructor(canvasEl, analyserNode) {
this._canvas = canvasEl;
this._analyser = analyserNode;
this._ctx = canvasEl.getContext('2d');
this._rafId = null;
this._w = 0;
this._h = 0;
this._resize();
this._onResize = () => this._resize();
window.addEventListener('resize', this._onResize);
}
_resize() {
const dpr = window.devicePixelRatio || 1;
const rect = this._canvas.getBoundingClientRect();
this._canvas.width = rect.width * dpr;
this._canvas.height = rect.height * dpr;
this._ctx.setTransform(1, 0, 0, 1, 0, 0);
this._ctx.scale(dpr, dpr);
this._w = rect.width;
this._h = rect.height;
}
start() {
const tick = () => {
this._rafId = requestAnimationFrame(tick);
this._draw();
};
tick();
}
stop() {
if (this._rafId) cancelAnimationFrame(this._rafId);
this._rafId = null;
this._ctx.fillStyle = '#0d0d0d';
this._ctx.fillRect(0, 0, this._w, this._h);
}
_draw() {
const analyser = this._analyser;
const timeData = new Uint8Array(analyser.frequencyBinCount);
const freqData = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteTimeDomainData(timeData);
analyser.getByteFrequencyData(freqData);
const active = profileById(State.activeSpeakerId);
const accent = active ? active.color : '#4dabf7';
const ctx = this._ctx;
const W = this._w;
const H = this._h;
const bg = ctx.createLinearGradient(0, 0, W, H);
bg.addColorStop(0, '#0d0d0d');
bg.addColorStop(1, hexToRgba(accent, 0.14));
ctx.fillStyle = bg;
ctx.fillRect(0, 0, W, H);
// Three lightweight band meters (low/mid/high) tinted with active speaker color.
const seg = Math.floor(freqData.length / 3);
const low = avgByte(freqData, 0, seg);
const mid = avgByte(freqData, seg, seg * 2);
const high = avgByte(freqData, seg * 2, freqData.length);
drawBandMeter(ctx, 0, W / 3, H, low, accent);
drawBandMeter(ctx, W / 3, W / 3, H, mid, accent);
drawBandMeter(ctx, (W / 3) * 2, W / 3, H, high, accent);
ctx.lineWidth = 1.5;
ctx.strokeStyle = accent;
ctx.beginPath();
const slice = W / timeData.length;
let x = 0;
for (let i = 0; i < timeData.length; i++) {
const y = ((timeData[i] / 128) * H) / 2;
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
x += slice;
}
ctx.lineTo(W, H / 2);
ctx.stroke();
}
}
function spectralCentroid() {
if (!State.analyser || !State.audioCtx) return 0;
const freqData = new Float32Array(State.analyser.frequencyBinCount);
State.analyser.getFloatFrequencyData(freqData);
const nyquist = State.audioCtx.sampleRate / 2;
let weighted = 0;
let total = 0;
for (let i = 0; i < freqData.length; i++) {
const power = Math.pow(10, freqData[i] / 20);
const freq = (i / freqData.length) * nyquist;
weighted += freq * power;