-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathapp.js
More file actions
1529 lines (1364 loc) · 55.2 KB
/
Copy pathapp.js
File metadata and controls
1529 lines (1364 loc) · 55.2 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
/**
* Voice Live Avatar - Client-side JavaScript
* Handles audio capture (AudioWorklet 24kHz PCM16), WebSocket communication,
* WebRTC avatar video, and UI state management.
*/
// ===== State =====
let ws = null;
let audioContext = null;
let workletNode = null;
let mediaStream = null;
let playbackContext = null;
let playbackBufferQueue = [];
let nextPlaybackTime = 0;
let isConnected = false;
let isConnecting = false;
let isRecording = false;
let audioChunksSent = 0;
let isDeveloperMode = false;
let avatarEnabled = false;
let peerConnection = null;
let avatarVideoElement = null;
let isSpeaking = false;
let avatarOutputMode = 'webrtc';
let cachedIceServers = null;
let peerConnectionQueue = [];
// Volume animation state
let analyserNode = null;
let analyserDataArray = null;
let micAnalyserNode = null;
let micAnalyserDataArray = null;
let recordAnimationFrameId = null;
let playChunkAnimationFrameId = null;
// WebSocket video playback (MediaSource Extensions)
let mediaSource = null;
let sourceBuffer = null;
let videoChunksQueue = [];
let pendingWsVideoElement = null;
const clientId = 'client-' + Math.random().toString(36).substr(2, 9);
// ===== DOM Ready =====
document.addEventListener('DOMContentLoaded', () => {
setupUIBindings();
updateConditionalFields();
updateControlStates();
fetchServerConfig();
});
// ===== Server Config =====
async function fetchServerConfig() {
try {
const resp = await fetch('/api/config');
const config = await resp.json();
if (config.endpoint) document.getElementById('endpoint').value = config.endpoint;
if (config.model) {
const modelEl = document.getElementById('model');
modelEl.value = config.model;
modelEl.dispatchEvent(new Event('change'));
}
if (config.voice) document.getElementById('voiceName').value = config.voice;
} catch (e) {
console.log('No server config available, using defaults');
}
}
// ===== UI Bindings =====
function setupUIBindings() {
// Mode change
document.getElementById('mode').addEventListener('change', updateConditionalFields);
// Model change
document.getElementById('model').addEventListener('change', (e) => {
const voiceTypeEl = document.getElementById('voiceType');
if (e.target.value === 'azure-realtime') {
voiceTypeEl.value = 'azure-realtime-native';
const nativeEl = document.getElementById('nativeVoiceName');
if (nativeEl) nativeEl.value = 'ava';
} else if (voiceTypeEl.value === 'azure-realtime-native') {
voiceTypeEl.value = 'standard';
}
updateConditionalFields();
});
// Voice type change
document.getElementById('voiceType').addEventListener('change', updateConditionalFields);
// Voice name change
document.getElementById('voiceName').addEventListener('change', updateConditionalFields);
// Avatar enabled
document.getElementById('avatarEnabled').addEventListener('change', updateConditionalFields);
// Photo avatar
document.getElementById('isPhotoAvatar').addEventListener('change', updateConditionalFields);
// Custom avatar
document.getElementById('isCustomAvatar').addEventListener('change', updateConditionalFields);
// Developer mode
document.getElementById('developerMode').addEventListener('change', (e) => {
isDeveloperMode = e.target.checked;
updateDeveloperModeLayout();
});
// Turn detection type
document.getElementById('turnDetectionType').addEventListener('change', updateConditionalFields);
// SR Model
document.getElementById('srModel').addEventListener('change', updateConditionalFields);
// Range sliders - display values
setupRangeDisplay('temperature', 'tempValue', v => v);
setupRangeDisplay('voiceTemperature', 'voiceTempValue', v => v);
setupRangeDisplay('voiceSpeed', 'voiceSpeedValue', v => v + '%');
setupRangeDisplay('sceneZoom', 'sceneZoomLabel', v => 'Zoom: ' + v + '%');
setupRangeDisplay('scenePositionX', 'scenePositionXLabel', v => 'Position X: ' + v + '%');
setupRangeDisplay('scenePositionY', 'scenePositionYLabel', v => 'Position Y: ' + v + '%');
setupRangeDisplay('sceneRotationX', 'sceneRotationXLabel', v => 'Rotation X: ' + v + ' deg');
setupRangeDisplay('sceneRotationY', 'sceneRotationYLabel', v => 'Rotation Y: ' + v + ' deg');
setupRangeDisplay('sceneRotationZ', 'sceneRotationZLabel', v => 'Rotation Z: ' + v + ' deg');
setupRangeDisplay('sceneAmplitude', 'sceneAmplitudeLabel', v => 'Amplitude: ' + v + '%');
// Scene sliders: send real-time updates when connected
const sceneSliders = ['sceneZoom', 'scenePositionX', 'scenePositionY',
'sceneRotationX', 'sceneRotationY', 'sceneRotationZ', 'sceneAmplitude'];
sceneSliders.forEach(id => {
const el = document.getElementById(id);
if (el) el.addEventListener('input', throttledUpdateAvatarScene);
});
// Accordion behavior: only one settings group open at a time
const settingsGroups = document.querySelectorAll('.sidebar .settings-group');
settingsGroups.forEach(group => {
group.addEventListener('toggle', () => {
if (group.open) {
settingsGroups.forEach(other => {
if (other !== group && other.open) {
other.removeAttribute('open');
}
});
}
});
});
}
function setupRangeDisplay(sliderId, displayId, formatter) {
const slider = document.getElementById(sliderId);
const display = document.getElementById(displayId);
if (slider && display) {
slider.addEventListener('input', () => {
display.textContent = formatter(slider.value);
});
}
}
// ===== Photo Avatar Scene Update =====
let lastSceneUpdate = 0;
const SCENE_THROTTLE_MS = 50;
function throttledUpdateAvatarScene() {
const now = Date.now();
if (now - lastSceneUpdate < SCENE_THROTTLE_MS) return;
lastSceneUpdate = now;
updateAvatarScene();
}
function updateAvatarScene() {
if (!isConnected || !ws || ws.readyState !== WebSocket.OPEN) return;
if (!document.getElementById('isPhotoAvatar')?.checked) return;
if (!document.getElementById('avatarEnabled')?.checked) return;
const isCustom = document.getElementById('isCustomAvatar')?.checked || false;
const avatarName = isCustom
? document.getElementById('customAvatarName')?.value || ''
: document.getElementById('photoAvatarName')?.value || 'Anika';
const parts = avatarName.split('-');
const character = parts[0].toLowerCase();
const style = parts.slice(1).join('-') || undefined;
const scene = {
zoom: parseInt(document.getElementById('sceneZoom').value) / 100,
position_x: parseInt(document.getElementById('scenePositionX').value) / 100,
position_y: parseInt(document.getElementById('scenePositionY').value) / 100,
rotation_x: parseInt(document.getElementById('sceneRotationX').value) * Math.PI / 180,
rotation_y: parseInt(document.getElementById('sceneRotationY').value) * Math.PI / 180,
rotation_z: parseInt(document.getElementById('sceneRotationZ').value) * Math.PI / 180,
amplitude: parseInt(document.getElementById('sceneAmplitude').value) / 100,
};
const avatar = {
type: 'photo-avatar',
model: 'vasa-1',
character: character,
scene: scene,
};
if (isCustom) {
avatar.customized = true;
} else if (style) {
avatar.style = style;
}
ws.send(JSON.stringify({
type: 'update_scene',
avatar: avatar,
}));
}
// ===== Conditional Field Visibility =====
function updateConditionalFields() {
const mode = document.getElementById('mode').value;
const model = document.getElementById('model').value;
const voiceType = document.getElementById('voiceType').value;
const voiceName = document.getElementById('voiceName').value;
const avatarEnabled = document.getElementById('avatarEnabled').checked;
const isPhotoAvatar = document.getElementById('isPhotoAvatar').checked;
const isCustomAvatar = document.getElementById('isCustomAvatar').checked;
const turnDetectionType = document.getElementById('turnDetectionType').value;
const srModel = document.getElementById('srModel').value;
// Cascaded models
const cascadedModels = [
'gpt-5.4', 'gpt-5.3-chat', 'gpt-5.2', 'gpt-5.2-chat', 'gpt-5.1', 'gpt-5.1-chat',
'gpt-5', 'gpt-5-mini', 'gpt-5-nano', 'gpt-5-chat',
'gpt-4.1', 'gpt-4.1-mini', 'gpt-4.1-nano', 'gpt-4o', 'gpt-4o-mini',
];
const isCascaded = cascadedModels.includes(model);
const isRealtime = model && model.includes('realtime');
// Mode: agent vs model -> show/hide fields
const isAgent = mode === 'agent' || mode === 'agent-v2';
show('agentFields', isAgent);
show('modelField', !isAgent);
show('instructionsField', !isAgent);
show('temperatureField', !isAgent);
// Agent ID vs Agent Name
show('agentIdField', mode === 'agent');
show('agentNameField', mode === 'agent-v2');
// Subscription key vs Entra token (agents = entra, model = subscription key)
show('subscriptionKeyField', !isAgent);
show('entraTokenField', isAgent);
// Cascaded-only fields
show('srModelField', !isAgent && isCascaded);
show('recognitionLanguageField', !isAgent && isCascaded && srModel !== 'mai-ears-1');
show('eouDetectionField', !isAgent && isCascaded);
// Filler words (semantic VAD)
show('fillerWordsField', turnDetectionType === 'azure_semantic_vad');
// Voice type variants
show('standardVoiceField', voiceType === 'standard');
show('customVoiceFields', voiceType === 'custom');
show('personalVoiceFields', voiceType === 'personal');
show('nativeVoiceField', voiceType === 'azure-realtime-native');
// Voice temperature (DragonHD or personal voice)
const isDragonHD = voiceName && voiceName.includes('DragonHD');
const isPersonal = voiceType === 'personal';
show('voiceTempField', voiceType !== 'azure-realtime-native' && (isDragonHD || isPersonal));
show('voiceSpeedField', voiceType !== 'azure-realtime-native');
const nativeOpt = document.querySelector('#voiceType option[value="azure-realtime-native"]');
if (nativeOpt) nativeOpt.hidden = (model !== 'azure-realtime');
// Avatar settings
show('avatarSettings', avatarEnabled);
show('standardAvatarField', !isPhotoAvatar && !isCustomAvatar);
show('photoAvatarField', isPhotoAvatar && !isCustomAvatar);
show('customAvatarField', isCustomAvatar);
show('photoAvatarSceneSettings', isPhotoAvatar);
}
function show(id, visible) {
const el = document.getElementById(id);
if (el) el.style.display = visible ? '' : 'none';
}
// ===== Sidebar Toggle (mobile) =====
function toggleSidebar() {
document.getElementById('sidebar').classList.toggle('open');
}
// ===== Chat =====
function addMessage(role, text, isDev = false) {
if (isDev && !isDeveloperMode) return;
const messagesEl = document.getElementById('messages');
const msgDiv = document.createElement('div');
msgDiv.className = `message ${isDev ? 'dev' : role}`;
if (!isDev) {
const roleSpan = document.createElement('div');
roleSpan.className = 'message-role';
roleSpan.textContent = role === 'user' ? 'You' : role === 'assistant' ? 'Assistant' : 'System';
msgDiv.appendChild(roleSpan);
}
const contentDiv = document.createElement('div');
contentDiv.className = 'message-content';
contentDiv.textContent = text;
msgDiv.appendChild(contentDiv);
messagesEl.appendChild(msgDiv);
scrollChatToBottom();
updateClearChatButton();
return contentDiv;
}
function updateLastAssistantMessage(text) {
const messages = document.querySelectorAll('.message.assistant .message-content');
if (messages.length > 0) {
messages[messages.length - 1].textContent = text;
scrollChatToBottom();
}
}
function scrollChatToBottom() {
const chatArea = document.getElementById('chatArea');
chatArea.scrollTop = chatArea.scrollHeight;
}
function clearChat() {
const messages = document.getElementById('messages');
if (messages.children.length === 0) return;
messages.innerHTML = '';
updateClearChatButton();
}
function updateClearChatButton() {
const btn = document.getElementById('clearChatBtn');
const messages = document.getElementById('messages');
if (!btn || !messages) return;
const hasMessages = messages.children.length > 0;
btn.disabled = !hasMessages;
btn.style.opacity = hasMessages ? '' : '0.5';
}
// ===== Gather Config =====
function gatherConfig() {
const mode = document.getElementById('mode').value;
const model = document.getElementById('model').value;
const voiceType = document.getElementById('voiceType').value;
const isPhotoAvatar = document.getElementById('isPhotoAvatar').checked;
const isCustomAvatar = document.getElementById('isCustomAvatar').checked;
const voiceSpeed = parseFloat(document.getElementById('voiceSpeed').value) / 100;
const voiceName = voiceType === 'azure-realtime-native'
? document.getElementById('nativeVoiceName').value
: document.getElementById('voiceName').value;
const config = {
mode: mode,
model: model,
voiceType: voiceType,
voiceName: voiceName,
voiceSpeed: voiceSpeed,
voiceTemperature: parseFloat(document.getElementById('voiceTemperature').value),
voiceDeploymentId: document.getElementById('voiceDeploymentId').value,
customVoiceName: document.getElementById('customVoiceName').value,
personalVoiceName: document.getElementById('personalVoiceName').value,
personalVoiceModel: document.getElementById('personalVoiceModel').value,
avatarEnabled: document.getElementById('avatarEnabled').checked,
isPhotoAvatar: isPhotoAvatar,
isCustomAvatar: isCustomAvatar,
avatarName: isCustomAvatar
? document.getElementById('customAvatarName').value
: isPhotoAvatar
? document.getElementById('photoAvatarName').value
: document.getElementById('avatarName').value,
avatarOutputMode: document.getElementById('avatarOutputMode').value,
avatarBackgroundImageUrl: document.getElementById('avatarBackgroundImageUrl').value,
useNS: document.getElementById('useNS').checked,
useEC: document.getElementById('useEC').checked,
turnDetectionType: document.getElementById('turnDetectionType').value,
removeFillerWords: document.getElementById('removeFillerWords').checked,
srModel: document.getElementById('srModel').value,
recognitionLanguage: document.getElementById('recognitionLanguage').value,
eouDetectionType: document.getElementById('eouDetectionType').value,
instructions: document.getElementById('instructions').value,
temperature: parseFloat(document.getElementById('temperature').value),
enableProactive: document.getElementById('enableProactive').checked,
// Agent fields
agentId: document.getElementById('agentId').value,
agentName: document.getElementById('agentName').value,
agentProjectName: document.getElementById('agentProjectName').value,
};
// Photo avatar scene settings
if (isPhotoAvatar) {
config.photoScene = {
zoom: parseInt(document.getElementById('sceneZoom').value),
positionX: parseInt(document.getElementById('scenePositionX').value),
positionY: parseInt(document.getElementById('scenePositionY').value),
rotationX: parseInt(document.getElementById('sceneRotationX').value),
rotationY: parseInt(document.getElementById('sceneRotationY').value),
rotationZ: parseInt(document.getElementById('sceneRotationZ').value),
amplitude: parseInt(document.getElementById('sceneAmplitude').value),
};
}
return config;
}
// ===== Connection =====
async function toggleConnection() {
if (isConnecting) return;
if (isConnected) {
await disconnect();
} else {
await connectSession();
}
}
async function connectSession() {
const endpoint = document.getElementById('endpoint').value.trim();
const mode = document.getElementById('mode').value;
const isAgent = mode === 'agent' || mode === 'agent-v2';
if (!endpoint) {
addMessage('system', 'Please enter Azure AI Services Endpoint');
return;
}
// Validate credentials
const apiKey = document.getElementById('apiKey')?.value.trim();
const entraToken = document.getElementById('entraToken')?.value.trim();
if (!isAgent && !apiKey) {
addMessage('system', 'Please enter Subscription Key');
return;
}
if (isAgent && !entraToken) {
addMessage('system', 'Please enter Entra ID Token');
return;
}
setConnecting(true);
addMessage('system', 'Session started, click on the mic button to start conversation! debug id: connecting...');
try {
// Open WebSocket to Python backend
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
ws = new WebSocket(`${protocol}//${location.host}/ws/${clientId}`);
ws.onopen = () => {
const config = gatherConfig();
// Send credentials to server
config.endpoint = endpoint;
if (isAgent) {
config.entraToken = entraToken;
} else {
config.apiKey = apiKey;
}
ws.send(JSON.stringify({ type: 'start_session', config }));
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
handleServerMessage(msg);
};
ws.onerror = (err) => {
console.error('WebSocket error', err);
addMessage('system', 'WebSocket error');
setConnecting(false);
};
ws.onclose = () => {
console.log('WebSocket closed');
if (isConnected) {
addMessage('system', 'Disconnected');
}
handleDisconnect();
};
} catch (err) {
console.error('Connection error', err);
addMessage('system', 'Failed to connect: ' + err.message);
setConnecting(false);
}
}
async function disconnect() {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'stop_session' }));
}
handleDisconnect();
}
function handleDisconnect() {
isConnected = false;
isConnecting = false;
isRecording = false;
audioChunksSent = 0;
avatarEnabled = false;
stopAudioCapture();
stopAudioPlayback();
cleanupWebRTC();
cleanupWebSocketVideo();
updateSoundWaveAnimation();
// Prepare next peer connection for faster reconnection
if (cachedIceServers) {
preparePeerConnection(cachedIceServers);
}
if (ws) {
try { ws.close(); } catch (e) {}
ws = null;
}
updateConnectionUI();
updateDeveloperModeLayout();
}
// ===== Handle Server Messages =====
function handleServerMessage(msg) {
const type = msg.type;
switch (type) {
case 'session_started':
onSessionStarted(msg);
break;
case 'session_error':
addMessage('system', 'Error: ' + (msg.error || 'Unknown error'));
setConnecting(false);
break;
case 'ice_servers':
// Only setup WebRTC when avatar output mode is webrtc
if (avatarOutputMode === 'webrtc') {
setupWebRTC(msg.iceServers);
}
break;
case 'avatar_sdp_answer':
handleAvatarSdpAnswer(msg.serverSdp);
break;
case 'audio_data':
handleAudioDelta(msg.data);
break;
case 'transcript_done':
if (msg.role === 'user') {
// Update existing placeholder by itemId, or add new message
const itemId = msg.itemId;
if (itemId) {
const existing = document.querySelector(`.message.user[data-item-id="${itemId}"] .message-content`);
if (existing) {
existing.textContent = msg.transcript;
scrollChatToBottom();
break;
}
}
addMessage('user', msg.transcript);
} else if (msg.role === 'assistant') {
// Finalize the streaming assistant message (don't create a new one)
if (msg.transcript) {
const assistantMsgs = document.querySelectorAll('.message.assistant .message-content');
if (assistantMsgs.length > 0) {
assistantMsgs[assistantMsgs.length - 1].textContent = msg.transcript;
}
pendingAssistantText = '';
}
}
break;
case 'transcript_delta':
if (msg.role === 'assistant') {
onAssistantDelta(msg.delta);
}
break;
case 'text_delta':
onAssistantDelta(msg.delta);
break;
case 'text_done':
// Text response complete - already accumulated via deltas
break;
case 'speech_started':
onSpeechStarted(msg.itemId);
break;
case 'speech_stopped':
onSpeechStopped();
break;
case 'response_created':
pendingAssistantText = '';
addMessage('assistant', '');
isSpeaking = true;
break;
case 'response_done':
isSpeaking = false;
// Don't stop play-chunk animation here - the animation loop
// will self-terminate when all buffered audio finishes playing
break;
case 'session_closed':
addMessage('system', 'Session closed');
handleDisconnect();
break;
case 'avatar_connecting':
addMessage('system', 'Avatar connecting...');
break;
case 'video_data':
handleVideoChunk(msg.delta);
break;
default:
// Log unknown events in dev mode
if (isDeveloperMode) {
console.log('Unhandled:', type, msg);
}
}
}
let pendingAssistantText = '';
function onAssistantDelta(text) {
pendingAssistantText += text;
const messages = document.querySelectorAll('.message.assistant .message-content');
if (messages.length > 0) {
messages[messages.length - 1].textContent = pendingAssistantText;
scrollChatToBottom();
} else {
// Fallback: create new message if none exists
addMessage('assistant', pendingAssistantText);
}
}
async function onSessionStarted(msg) {
isConnected = true;
isConnecting = false;
updateConnectionUI();
// Update the "connecting..." status message with the real session ID
const sessionId = msg.sessionId || '';
const statusMessages = document.querySelectorAll('.message.system .message-content');
for (const el of statusMessages) {
if (el.textContent.includes('debug id: connecting...')) {
el.textContent = `Session started, click on the mic button to start conversation! debug id: ${sessionId || 'unknown'}`;
break;
}
}
// Show appropriate content area
avatarEnabled = msg.config?.avatarEnabled || false;
avatarOutputMode = msg.config?.avatarOutputMode || 'webrtc';
const isPhotoAvatarSession = document.getElementById('isPhotoAvatar')?.checked || false;
const avatarContainer = document.getElementById('avatarVideoContainer');
if (avatarContainer) {
avatarContainer.classList.toggle('photo-avatar', isPhotoAvatarSession);
}
updateDeveloperModeLayout();
// If avatar is enabled with websocket mode, set up MediaSource video playback
if (avatarEnabled && avatarOutputMode === 'websocket') {
setupWebSocketVideoPlayback(isPhotoAvatarSession);
}
// Show record button for non-dev mode
document.getElementById('recordContainer').style.display = '';
// Start audio capture but leave mic off by default
await startAudioCapture();
isRecording = false;
stopRecordAnimation();
resetVolumeCircle();
updateMicUI();
}
// ===== UI State =====
function setConnecting(connecting) {
isConnecting = connecting;
updateConnectionUI();
}
function updateConnectionUI() {
const btn = document.getElementById('connectBtn');
const text = document.getElementById('connectBtnText');
btn.classList.remove('connected', 'connecting');
if (isConnected) {
btn.classList.add('connected');
text.textContent = 'Disconnect';
} else if (isConnecting) {
btn.classList.add('connecting');
text.textContent = 'Connecting...';
} else {
text.textContent = 'Connect';
}
// Disable connect button while connecting
btn.disabled = isConnecting;
// Scene Settings title: show "(Live Adjustable)" when connected
const sceneTitle = document.getElementById('sceneSettingsTitle');
if (sceneTitle) {
sceneTitle.textContent = isConnected ? 'Scene Settings (Live Adjustable)' : 'Scene Settings';
}
// Update all control disabled states
updateControlStates();
// Mic buttons
updateMicUI();
}
// ===== Control Enable/Disable States =====
// Controls that should be disabled when connected (locked during session)
const SETTINGS_CONTROLS = [
// Connection Settings
'mode', 'endpoint', 'apiKey', 'entraToken',
'agentProjectName', 'agentId', 'agentName', 'model',
// Conversation Settings
'srModel', 'recognitionLanguage',
'useNS', 'useEC', 'turnDetectionType', 'removeFillerWords',
'eouDetectionType', 'instructions', 'enableProactive',
'temperature', 'voiceTemperature', 'voiceSpeed',
// Voice Configuration
'voiceType', 'voiceDeploymentId', 'customVoiceName',
'personalVoiceName', 'personalVoiceModel', 'voiceName',
// Avatar Configuration
'avatarEnabled', 'isPhotoAvatar', 'avatarOutputMode',
'isCustomAvatar', 'avatarName', 'photoAvatarName',
'customAvatarName', 'avatarBackgroundImageUrl',
];
// Controls that should be disabled when NOT connected (chat interaction)
const CHAT_CONTROLS = [
'textInput',
];
function updateControlStates() {
// Disable all settings controls when connected
for (const id of SETTINGS_CONTROLS) {
const el = document.getElementById(id);
if (el) el.disabled = isConnected;
}
// Disable chat controls when NOT connected
for (const id of CHAT_CONTROLS) {
const el = document.getElementById(id);
if (el) el.disabled = !isConnected;
}
// Mic button (developer mode) - disabled when not connected
const micBtn = document.getElementById('micBtn');
if (micBtn) micBtn.disabled = !isConnected;
// Send button - disabled when not connected
const sendBtns = document.querySelectorAll('.send-btn');
sendBtns.forEach(btn => btn.disabled = !isConnected);
// Record button (non-developer mode footer) - disabled when not connected
const recordBtn = document.getElementById('recordBtn');
if (recordBtn) recordBtn.disabled = !isConnected;
}
function updateDeveloperModeLayout() {
const contentArea = document.getElementById('contentArea');
const avatarVideoContainer = document.getElementById('avatarVideoContainer');
const volumeAnimation = document.getElementById('volumeAnimation');
const chatArea = document.getElementById('chatArea');
const inputArea = document.getElementById('inputArea');
const footerArea = document.getElementById('footerArea');
if (isDeveloperMode) {
// Developer mode: show input area, hide footer
inputArea.style.display = '';
footerArea.style.display = 'none';
if (isConnected && avatarEnabled) {
// Avatar + developer: side-by-side layout (avatar + chat)
contentArea.classList.add('developer-layout');
avatarVideoContainer.style.display = '';
chatArea.style.display = '';
volumeAnimation.style.display = 'none';
} else if (isConnected) {
// No avatar + developer: side-by-side layout (robot + chat)
contentArea.classList.add('developer-layout');
avatarVideoContainer.style.display = 'none';
chatArea.style.display = '';
volumeAnimation.style.display = '';
} else {
// Not connected: just show chat
contentArea.classList.remove('developer-layout');
avatarVideoContainer.style.display = 'none';
chatArea.style.display = '';
volumeAnimation.style.display = 'none';
}
} else {
// Normal mode: show footer, hide input area
inputArea.style.display = 'none';
footerArea.style.display = '';
contentArea.classList.remove('developer-layout');
if (isConnected && avatarEnabled) {
// Avatar + normal: only avatar video, no chat
avatarVideoContainer.style.display = '';
chatArea.style.display = 'none';
volumeAnimation.style.display = 'none';
} else if (isConnected) {
// No avatar + normal: only robot, no chat
avatarVideoContainer.style.display = 'none';
chatArea.style.display = 'none';
volumeAnimation.style.display = '';
} else {
// Not connected: show chat history
avatarVideoContainer.style.display = 'none';
chatArea.style.display = '';
volumeAnimation.style.display = 'none';
}
}
}
let soundWaveIntervalId = null;
function updateSoundWaveAnimation() {
const leftWave = document.getElementById('soundWaveLeft');
const rightWave = document.getElementById('soundWaveRight');
if (isConnected && avatarEnabled && isRecording && !isDeveloperMode) {
// Create sound wave bars if not already present
if (leftWave && leftWave.children.length === 0) {
for (let i = 0; i < 10; i++) {
const bar = document.createElement('div');
bar.className = 'bar';
bar.id = `item-${i}`;
bar.style.height = '2px';
leftWave.appendChild(bar);
}
}
if (rightWave && rightWave.children.length === 0) {
for (let i = 10; i < 20; i++) {
const bar = document.createElement('div');
bar.className = 'bar';
bar.id = `item-${i}`;
bar.style.height = '2px';
rightWave.appendChild(bar);
}
}
// Start animation
if (!soundWaveIntervalId) {
soundWaveIntervalId = setInterval(() => {
for (let i = 0; i < 20; i++) {
const ele = document.getElementById(`item-${i}`);
const height = 50 * Math.sin((Math.PI / 20) * i) * Math.random();
if (ele) {
ele.style.transition = 'height 0.15s ease';
ele.style.height = `${Math.max(2, height)}px`;
}
}
}, 150);
}
if (leftWave) leftWave.style.display = '';
if (rightWave) rightWave.style.display = '';
} else {
// Stop animation, hide waves
if (soundWaveIntervalId) {
clearInterval(soundWaveIntervalId);
soundWaveIntervalId = null;
}
if (leftWave) leftWave.style.display = 'none';
if (rightWave) rightWave.style.display = 'none';
}
}
function updateMicUI() {
const micBtn = document.getElementById('micBtn');
const recordBtn = document.getElementById('recordBtn');
// Toggle recording class
if (micBtn) micBtn.classList.toggle('recording', isRecording);
if (recordBtn) recordBtn.classList.toggle('recording', isRecording);
// Toggle icon visibility: show off-icon when not recording, on-icon when recording
document.querySelectorAll('.mic-off-icon').forEach(el => {
el.style.display = isRecording ? 'none' : '';
});
document.querySelectorAll('.mic-on-icon').forEach(el => {
el.style.display = isRecording ? '' : 'none';
});
// Update label text
const label = document.querySelector('.microphone-label');
if (label) {
label.textContent = isRecording ? 'Turn off microphone' : 'Turn on microphone';
}
// Update sound wave visibility
updateSoundWaveAnimation();
}
// ===== Audio Capture (24kHz PCM16 via AudioWorklet) =====
async function startAudioCapture() {
try {
mediaStream = await navigator.mediaDevices.getUserMedia({
audio: {
channelCount: 1,
sampleRate: 24000,
echoCancellation: true,
noiseSuppression: true,
}
});
audioContext = new AudioContext({ sampleRate: 24000 });
console.log('[Audio] AudioContext created, actual sampleRate:', audioContext.sampleRate);
// Register AudioWorklet processor inline via Blob
const processorCode = `
class PCM16Processor extends AudioWorkletProcessor {
constructor() {
super();
this.bufferSize = 2400; // 100ms at 24kHz
this.buffer = new Float32Array(this.bufferSize);
this.offset = 0;
}
process(inputs) {
const input = inputs[0];
if (!input || !input[0]) return true;
const data = input[0];
for (let i = 0; i < data.length; i++) {
this.buffer[this.offset++] = data[i];
if (this.offset >= this.bufferSize) {
const pcm16 = new Int16Array(this.bufferSize);
for (let j = 0; j < this.bufferSize; j++) {
const s = Math.max(-1, Math.min(1, this.buffer[j]));
pcm16[j] = s < 0 ? s * 0x8000 : s * 0x7FFF;
}
this.port.postMessage(pcm16.buffer, [pcm16.buffer]);
this.buffer = new Float32Array(this.bufferSize);
this.offset = 0;
}
}
return true;
}
}
registerProcessor('pcm16-processor', PCM16Processor);
`;
const blob = new Blob([processorCode], { type: 'application/javascript' });
const url = URL.createObjectURL(blob);
await audioContext.audioWorklet.addModule(url);
URL.revokeObjectURL(url);
const source = audioContext.createMediaStreamSource(mediaStream);
workletNode = new AudioWorkletNode(audioContext, 'pcm16-processor');
// Create analyser for mic volume visualization
const micAnalyser = audioContext.createAnalyser();
micAnalyser.fftSize = 2048;
micAnalyser.smoothingTimeConstant = 0.85;
const micDataArray = new Uint8Array(micAnalyser.frequencyBinCount);
workletNode.port.onmessage = (e) => {
if (!isConnected || !isRecording || !ws || ws.readyState !== WebSocket.OPEN) return;
const base64 = arrayBufferToBase64(e.data);
audioChunksSent++;
if (audioChunksSent <= 3 || audioChunksSent % 100 === 0) {
console.log(`[Audio] Sending chunk #${audioChunksSent}, size=${base64.length}`);
}
ws.send(JSON.stringify({ type: 'audio_chunk', data: base64 }));
};
source.connect(workletNode);
source.connect(micAnalyser);
workletNode.connect(audioContext.destination);
// Store mic analyser so volume animation can use it
micAnalyserNode = micAnalyser;
micAnalyserDataArray = micDataArray;
analyserNode = micAnalyser;
analyserDataArray = micDataArray;
startVolumeAnimation('record');
console.log('[Audio] Capture started (24kHz PCM16)');
} catch (err) {
console.error('Audio capture error', err);
addMessage('system', 'Microphone access denied or not available');
}
}
function stopAudioCapture() {
stopRecordAnimation();
micAnalyserNode = null;
micAnalyserDataArray = null;
if (workletNode) { try { workletNode.disconnect(); } catch (e) {} workletNode = null; }
if (audioContext) { try { audioContext.close(); } catch (e) {} audioContext = null; }
if (mediaStream) { mediaStream.getTracks().forEach(t => t.stop()); mediaStream = null; }
resetVolumeCircle();
}
// ===== Audio Playback (24kHz PCM16) =====
function handleAudioDelta(base64Data) {
if (!base64Data) return;
if (!playbackContext) {
playbackContext = new AudioContext({ sampleRate: 24000 });
// Create analyser for volume visualization
analyserNode = playbackContext.createAnalyser();
analyserNode.fftSize = 2048;
analyserNode.smoothingTimeConstant = 0.85;
analyserDataArray = new Uint8Array(analyserNode.frequencyBinCount);
analyserNode.connect(playbackContext.destination);
nextPlaybackTime = 0;
}
const arrayBuffer = base64ToArrayBuffer(base64Data);
const int16 = new Int16Array(arrayBuffer);
const float32 = new Float32Array(int16.length);
for (let i = 0; i < int16.length; i++) {
float32[i] = int16[i] / 32768;
}
const buffer = playbackContext.createBuffer(1, float32.length, 24000);