Repository navigation
Expand file tree
/
Copy pathApp.vue
More file actions
1487 lines (1300 loc) · 47.4 KB
/
Copy pathApp.vue
File metadata and controls
1487 lines (1300 loc) · 47.4 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
<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick, triggerRef } from 'vue';
import Chat from './components/Chat.vue';
import ChatTabs from './components/ChatTabs.vue';
import Progress from './components/Progress.vue';
import Settings from './components/Settings.vue';
import QuickSettings from './components/QuickSettings.vue';
import ArrowRightIcon from './components/icons/ArrowRightIcon.vue';
import StopIcon from './components/icons/StopIcon.vue';
import SettingsIcon from './components/icons/SettingsIcon.vue';
import MicrophoneIcon from './components/icons/MicrophoneIcon.vue';
import workerUrl from './worker.js?url';
import apiWorkerUrl from './apiWorker.js?url';
import sttWorkerUrl from './stt-worker.js?url';
import chatStorage from './services/chatStorage.js';
import { MicVAD } from '@ricky0123/vad-web';
import { useTTS } from './composables/useTTS.js';
import { segmentText } from './utils/clause-chunker.js';
import { phonemizeText, buildTokenIdsFromPhonemes } from './utils/phoneme-utils.js';
import { cleanTextForTTS } from './utils/textCleaner.js';
const isWebGpuAvailable = ref(false);
const STICKY_SCROLL_THRESHOLD = 120;
const EXAMPLES = [
'Solve the equation x^2 - 3x + 2 = 0',
'Lily is three times older than her son. In 15 years, she will be twice as old as him. How old was she when he was born, and how old is she now?',
'Write python code to compute the nth fibonacci number.',
];
const worker = ref(null);
const sttWorker = ref(null);
const textareaRef = ref(null);
const chatContainerRef = ref(null);
const chatRef = ref(null);
const bottomPaddingRef = ref(null);
const settingsOpen = ref(false);
const pendingClassification = ref(false);
const lastClassifiedText = ref('');
const vad = ref(null);
const isVoiceActive = ref(false);
const vadGate = ref(false);
const incompleteTimer = ref(null);
const lastIncompleteText = ref('');
const userStartedRecording = ref(false);
const currentSettings = ref({
provider: 'local',
localModel: 'onnx-community/Qwen3-4B-ONNX',
customApis: [],
selectedCustomApi: null,
defaultCustomApi: null,
systemPrompts: []
});
const status = ref(null);
const loadingMessage = ref('');
const progressItems = ref([]);
const isRunning = ref(false);
const input = ref('');
const messages = ref([]);
const tps = ref(null);
const numTokens = ref(null);
const lastAiMessageIndex = ref(-1);
const chats = ref([]);
const currentChatId = ref(null);
const sidebarCollapsed = ref(false);
const isLoadingHistory = ref(false);
const currentSystemPromptId = ref('');
const currentChatProvider = ref('local');
const currentChatSelectedCustomApi = ref(null);
// STT state
const isRecording = ref(false);
const sttStatus = ref(null);
const mediaRecorder = ref(null);
const audioStream = ref(null);
const audioChunks = ref([]);
const audioContext = ref(null);
const isSTTProcessing = ref(false);
const sttText = ref('');
// TTS state and helpers
const { init: initTTS, unlock: unlockTTS, flush: flushTTS, speakTokenIds, enqueueSilence, isReady: isTTSReady, isSpeaking: isTTSSpeaking } = useTTS();
const ttsModelSampleRate = 24000;
let currentTTSAbortController = null;
async function ensureTTSReady() {
try {
await initTTS({ modelUrl: '/tts-model/kitten_tts_nano_v0_1.onnx', voicesJsonUrl: '/tts-model/voices.json' });
await unlockTTS();
} catch (e) {
console.error('TTS init error:', e);
}
}
async function speakDelta(delta) {
try {
const clauses = segmentText(delta);
for (const c of clauses) {
const ph = await phonemizeText(c.text);
const phonemeString = Array.isArray(ph) ? ph.join(' ') : ph;
const tokenIds = buildTokenIdsFromPhonemes(phonemeString);
speakTokenIds(tokenIds, { speed: 1.0, modelSampleRate: ttsModelSampleRate });
if (c.pauseMs > 0) enqueueSilence(c.pauseMs);
}
} catch (e) {
console.error('speakDelta error:', e);
}
}
async function speakText(text) {
try {
// Cancel any existing TTS process
if (currentTTSAbortController) {
currentTTSAbortController.abort();
}
// Create new abort controller for this TTS session
currentTTSAbortController = new AbortController();
const abortSignal = currentTTSAbortController.signal;
await ensureTTSReady();
flushTTS();
// Clean the text for TTS (remove markdown, emojis, unwanted symbols)
const cleanedText = cleanTextForTTS(text);
console.log('Original text:', text.substring(0, 200) + '...');
console.log('Cleaned text:', cleanedText.substring(0, 200) + '...');
if (!cleanedText.trim()) {
console.log('No readable text found after cleaning');
return;
}
const segments = segmentText(cleanedText);
for (const c of segments) {
// Check if we've been cancelled
if (abortSignal.aborted) {
console.log('TTS cancelled');
return;
}
const ph = await phonemizeText(c.text);
const phonemeString = Array.isArray(ph) ? ph.join(' ') : ph;
const tokenIds = buildTokenIdsFromPhonemes(phonemeString);
speakTokenIds(tokenIds, { speed: 1.0, modelSampleRate: ttsModelSampleRate });
// Skip adding silence between segments to eliminate hiccups - natural pauses will come from punctuation
// if (c.pauseMs > 0) enqueueSilence(Math.min(c.pauseMs, 50)); // Commented out to test hiccup elimination
}
} catch (error) {
if (error.name === 'AbortError') {
console.log('TTS was cancelled');
} else {
console.error('Error speaking text:', error);
throw error;
}
}
}
function stopTTS() {
// Cancel the TTS processing loop
if (currentTTSAbortController) {
currentTTSAbortController.abort();
currentTTSAbortController = null;
}
// Flush the audio queue
flushTTS();
}
const onEnter = async (message) => {
const userMessage = { role: 'user', content: message };
const userMessageIndex = messages.value.length;
messages.value.push(userMessage);
if (currentChatId.value) {
try {
await chatStorage.saveMessage(currentChatId.value, userMessage);
await updateChatsList();
} catch (error) {
console.error('Failed to save user message:', error);
}
}
tps.value = null;
isRunning.value = true;
input.value = '';
// Stop recording and warm up STT worker before restarting
if (isRecording.value) {
stopContinuousRecording();
// Reset and warm up STT worker
if (sttWorker.value) {
sttWorker.value.postMessage({ type: 'reset' });
sttStatus.value = 'warming';
sttWorker.value.postMessage({ type: 'warmup' });
}
}
sttText.value = '';
// Scroll to the user's message after it's added
await nextTick();
scrollToUserMessage(userMessageIndex);
};
const handleEnter = () => {
if (input.value.length > 0 && !isRunning.value) {
onEnter(input.value);
}
};
const onInterrupt = () => {
worker.value.postMessage({ type: 'interrupt' });
};
const resizeInput = () => {
if (!textareaRef.value) return;
const target = textareaRef.value;
target.style.height = 'auto';
const newHeight = Math.min(Math.max(target.scrollHeight, 24), 200);
target.style.height = `${newHeight}px`;
};
const onMessageReceived = async (e) => {
switch (e.data.status) {
case 'loading':
status.value = 'loading';
loadingMessage.value = e.data.data;
break;
case 'initiate':
progressItems.value.push(e.data);
break;
case 'progress':
progressItems.value = progressItems.value.map((item) => {
if (item.file === e.data.file) {
return { ...item, ...e.data };
}
return item;
});
break;
case 'done':
progressItems.value = progressItems.value.filter(
(item) => item.file !== e.data.file
);
break;
case 'ready':
status.value = 'ready';
break;
case 'start':
messages.value.push({ role: 'assistant', content: '', reasoning: '' });
// Update last AI message index to the new message
lastAiMessageIndex.value = messages.value.length - 1;
if (isRecording.value) {
await ensureTTSReady();
flushTTS();
}
break;
case 'update':
const { output, reasoning, fullReasoning, tps: newTps, numTokens: newNumTokens, state } = e.data;
tps.value = newTps;
numTokens.value = newNumTokens;
const lastMessageIndex = messages.value.length - 1;
const lastMessage = messages.value[lastMessageIndex];
if (lastMessage.answerIndex === undefined && state === 'answering') {
lastMessage.answerIndex = lastMessage.content.length;
}
// Try multiple approaches to force Vue reactivity
const newContent = lastMessage.content + (output || '');
const newReasoning = fullReasoning || (lastMessage.reasoning + (reasoning || ''));
// Approach 1: Replace the entire array
messages.value = [
...messages.value.slice(0, lastMessageIndex),
{
...lastMessage,
content: newContent,
reasoning: newReasoning
}
];
// Force reactivity trigger
triggerRef(messages);
// Stream to TTS when mic is active
if (isRecording.value && isTTSReady.value) {
const delta = output || '';
if (delta) {
await speakDelta(delta);
}
}
// Test: Force a DOM update by changing a simple value
numTokens.value = newNumTokens;
break;
case 'complete':
isRunning.value = false;
if (isRecording.value && isTTSReady.value) enqueueSilence(120);
if (currentChatId.value && messages.value.length > 0) {
const lastMessage = messages.value[messages.value.length - 1];
if (lastMessage.role === 'assistant' && lastMessage.content) {
try {
await chatStorage.saveMessage(currentChatId.value, lastMessage);
await updateChatsList();
} catch (error) {
console.error('Failed to save assistant message:', error);
}
}
}
break;
case 'error':
isRunning.value = false;
// Replace the last assistant message (the placeholder) with the error message
const errorMessageIndex = messages.value.length - 1;
if (errorMessageIndex >= 0 && messages.value[errorMessageIndex].role === 'assistant') {
// Handle structured error from API worker
if (typeof e.data.data === 'object' && e.data.data.message) {
const errorData = e.data.data;
const errorMessage = {
role: 'assistant',
content: errorData.message,
isError: true,
isRetryable: errorData.isRetryable,
errorType: errorData.errorType,
errorDetails: errorData.details
};
// Replace the placeholder message
messages.value = [
...messages.value.slice(0, errorMessageIndex),
errorMessage
];
// Update last AI message index to the error message
lastAiMessageIndex.value = errorMessageIndex;
} else {
// Handle simple string errors (backward compatibility)
const errorMessage = {
role: 'assistant',
content: e.data.data || 'An unknown error occurred',
isError: true,
isRetryable: true,
errorType: 'unknown'
};
// Replace the placeholder message
messages.value = [
...messages.value.slice(0, errorMessageIndex),
errorMessage
];
// Update last AI message index to the error message
lastAiMessageIndex.value = errorMessageIndex;
}
// Save the error message to IndexedDB
if (currentChatId.value) {
try {
await chatStorage.saveMessage(currentChatId.value, messages.value[errorMessageIndex]);
await updateChatsList();
} catch (error) {
console.error('Failed to save error message:', error);
}
}
}
break;
}
};
const onErrorReceived = (e) => {
console.error('Worker error:', e);
};
// STT message handlers
const onSTTMessageReceived = (e) => {
switch (e.data.status) {
case 'loading':
sttStatus.value = 'loading';
break;
case 'ready':
sttStatus.value = 'ready';
// If user manually started recording and we were warming up after a message send, restart recording
if (userStartedRecording.value && !isRecording.value) {
startContinuousRecording();
}
break;
case 'start':
// STT generation started
isSTTProcessing.value = true;
break;
case 'update':
// Real-time STT text updates (streaming)
const { tps: sttTps } = e.data;
// Can show TPS if needed
break;
case 'complete':
// Generation complete - replace text completely
isSTTProcessing.value = false;
const output = e.data.output;
// Extract the text string from the array
const text = Array.isArray(output) ? output[0] : output || '';
sttText.value = text;
// Update input box to show STT text
if (isRecording.value) {
input.value = sttText.value;
resizeInput();
// Trigger classification on the newly transcribed text
if (sttText.value.trim()) {
console.log('Triggering classification for new transcription:', sttText.value);
tryClassification(sttText.value);
}
}
break;
case 'error':
console.error('STT Worker error:', e.data.data);
isSTTProcessing.value = false;
break;
}
};
const onSTTErrorReceived = (e) => {
console.error('STT Worker error:', e);
};
// STT constants and functions
const WHISPER_SAMPLING_RATE = 16000;
const MAX_AUDIO_LENGTH = 30; // seconds
const MAX_SAMPLES = WHISPER_SAMPLING_RATE * MAX_AUDIO_LENGTH;
const startContinuousRecording = async () => {
try {
if (isRecording.value) return;
// Initialize VAD-web
vad.value = await MicVAD.new({
onSpeechStart: () => {
console.log('🎤 Voice detected - starting utterance recording');
isVoiceActive.value = true;
vadGate.value = true;
// Clear any incomplete timeout
if (incompleteTimer.value) {
clearTimeout(incompleteTimer.value);
incompleteTimer.value = null;
}
// Reset for new utterance
sttText.value = '';
audioChunks.value = [];
// Start recording for this utterance
startWhisperRecording();
},
onSpeechEnd: () => {
console.log('🔇 Voice stopped - processing complete utterance');
isVoiceActive.value = false;
vadGate.value = false;
// Stop recording and process the complete utterance
stopAndProcessUtterance();
},
// Configuration
preSpeechPadFrames: 70,
positiveSpeechThreshold: 0.5,
negativeSpeechThreshold: 0.35,
redemptionFrames: 8,
});
// Start VAD
vad.value.start();
isRecording.value = true;
console.log('VAD-web initialized and started');
// Ensure TTS is unlocked and ready to speak
await ensureTTSReady();
} catch (error) {
console.error('Error starting VAD recording:', error);
}
};
const startWhisperRecording = async () => {
if (mediaRecorder.value && mediaRecorder.value.state === 'recording') return;
try {
// Get user media for Whisper (if not already available)
if (!audioStream.value) {
audioStream.value = await navigator.mediaDevices.getUserMedia({
audio: {
channelCount: 1,
echoCancellation: false,
noiseSuppression: true,
autoGainControl: false
}
});
}
// Create audio context with Whisper sampling rate (reuse if exists)
if (!audioContext.value || audioContext.value.state === 'closed') {
audioContext.value = new AudioContext({
sampleRate: WHISPER_SAMPLING_RATE,
});
}
// Create recorder with explicit options for better compatibility
const options = {};
if (MediaRecorder.isTypeSupported('audio/webm;codecs=opus')) {
options.mimeType = 'audio/webm;codecs=opus';
} else if (MediaRecorder.isTypeSupported('audio/webm')) {
options.mimeType = 'audio/webm';
} else if (MediaRecorder.isTypeSupported('audio/mp4')) {
options.mimeType = 'audio/mp4';
}
mediaRecorder.value = new MediaRecorder(audioStream.value, options);
mediaRecorder.value.onstart = () => {
console.log('Recording utterance started');
};
mediaRecorder.value.ondataavailable = (e) => {
// Collect all chunks for this utterance
if (e.data && e.data.size > 0) {
console.log('Audio chunk received:', e.data.size, 'bytes, type:', e.data.type);
audioChunks.value.push(e.data);
}
};
mediaRecorder.value.onerror = (e) => {
console.error('MediaRecorder error:', e.error);
};
// Start recording without timeslice - get one complete container
mediaRecorder.value.start();
} catch (error) {
console.error('Error starting Whisper recording:', error);
}
};
const stopAndProcessUtterance = async () => {
if (!mediaRecorder.value || mediaRecorder.value.state !== 'recording') return;
// Set up the onstop handler before stopping
mediaRecorder.value.onstop = async () => {
try {
console.log('Processing complete utterance with', audioChunks.value.length, 'chunks');
if (audioChunks.value.length === 0) {
console.warn('No audio chunks recorded');
return;
}
const mimeType = mediaRecorder.value.mimeType || audioChunks.value[0]?.type || 'audio/webm;codecs=opus';
const finalBlob = new Blob(audioChunks.value, { type: mimeType });
console.log('Final utterance blob:', finalBlob.size, 'bytes, type:', finalBlob.type);
if (finalBlob.size < 1000) {
console.warn('Utterance blob too small:', finalBlob.size);
return;
}
const arrayBuffer = await finalBlob.arrayBuffer();
if (!arrayBuffer.byteLength) {
console.warn('Empty utterance buffer');
return;
}
const decoded = await audioContext.value.decodeAudioData(arrayBuffer);
let audio = decoded.getChannelData(0);
console.log('Decoded utterance:', audio.length, 'samples at', decoded.sampleRate, 'Hz');
if (audio.length < 1600) {
console.warn('Utterance too short:', audio.length, 'samples');
return;
}
if (audio.length > MAX_SAMPLES) {
audio = audio.slice(-MAX_SAMPLES);
}
console.log('Sending complete utterance to STT:', audio.length, 'samples');
sttWorker.value.postMessage({
type: 'generate',
data: { audio, language: 'en' }
});
} catch (error) {
console.error('Error processing utterance:', error);
} finally {
// Clean up for next utterance
audioChunks.value = [];
}
};
// Stop the recording
mediaRecorder.value.stop();
};
const tryClassification = (text) => {
if (text !== lastClassifiedText.value && !pendingClassification.value) {
console.log('🔍 Classifying:', text);
pendingClassification.value = true;
lastClassifiedText.value = text;
// Simple rule-based classification for complete sentences
const isComplete = classifyMessageCompleteness(text);
setTimeout(() => {
pendingClassification.value = false;
if (isComplete && text.trim().length > 2) {
console.log('✅ Complete - auto-sending:', text);
// Clear any incomplete timer
if (incompleteTimer.value) {
clearTimeout(incompleteTimer.value);
incompleteTimer.value = null;
}
// Auto-send the message
onEnter(text);
} else {
// Handle incomplete message with 3s timeout
handleIncompleteMessage(text);
}
}, 500);
}
};
// Simple rule-based classifier to determine if a message is complete
const classifyMessageCompleteness = (text) => {
const trimmed = text.trim().toLowerCase();
// Skip blank audio or very short texts
if (trimmed.length < 2 || trimmed === '[blank_audio]' || trimmed === '') {
return false;
}
// Check for sentence-ending punctuation
if (/[.!?]\s*$/.test(trimmed)) {
return true;
}
// Check for common complete phrases/greetings
const completePatterns = [
/^(hello|hi|hey|good morning|good afternoon|good evening)$/,
/^(thank you|thanks|bye|goodbye|see you)$/,
/^(yes|no|ok|okay|sure|alright)$/,
/^(help|test|testing)$/,
/^what is/,
/^how do/,
/^can you/,
/^please/,
/^tell me/,
/^show me/,
/^explain/,
/^write/,
/^create/,
/^make/,
/^solve/,
/^calculate/,
/^find/
];
for (const pattern of completePatterns) {
if (pattern.test(trimmed)) {
return true;
}
}
// Check for questions (even without question marks)
if (/^(what|where|when|why|how|who|which|is|are|can|will|would|could|should|do|does|did)\b/.test(trimmed)) {
return true;
}
// Check for commands/requests
if (/^(let me|give me|send|open|close|start|stop|play|pause)\b/.test(trimmed)) {
return true;
}
// If it's a longer phrase (5+ words), likely complete
if (trimmed.split(/\s+/).length >= 5) {
return true;
}
return false;
};
const handleIncompleteMessage = (text) => {
console.log('❌ Message incomplete, setting 3s timeout...');
lastIncompleteText.value = text;
// Set 3-second timer to bypass classifier if no new speech
incompleteTimer.value = setTimeout(() => {
if (!isVoiceActive.value && lastIncompleteText.value === input.value) {
console.log('⏰ 3s timeout - sending incomplete message anyway:', text);
onEnter(text);
}
}, 3000);
};
const stopContinuousRecording = () => {
if (vad.value) {
vad.value.pause();
vad.value = null;
}
if (mediaRecorder.value) {
mediaRecorder.value.stop();
mediaRecorder.value = null;
}
if (audioStream.value) {
audioStream.value.getTracks().forEach(track => track.stop());
audioStream.value = null;
}
if (audioContext.value) {
audioContext.value.close().catch(() => {});
audioContext.value = null;
}
if (incompleteTimer.value) {
clearTimeout(incompleteTimer.value);
incompleteTimer.value = null;
}
isRecording.value = false;
isVoiceActive.value = false;
vadGate.value = false;
};
const toggleRecording = () => {
if (isRecording.value) {
userStartedRecording.value = false;
stopContinuousRecording();
flushTTS();
} else {
userStartedRecording.value = true;
startContinuousRecording();
}
};
const initializeWorker = () => {
if (worker.value) {
worker.value.removeEventListener('message', onMessageReceived);
worker.value.removeEventListener('error', onErrorReceived);
worker.value.terminate();
}
// Choose worker based on provider type
const workerType = effectiveSettings.value.provider === 'local' ? workerUrl : apiWorkerUrl;
worker.value = new Worker(workerType, {
type: 'module',
});
worker.value.addEventListener('message', onMessageReceived);
worker.value.addEventListener('error', onErrorReceived);
// Initialize STT worker if not already done
if (!sttWorker.value) {
sttWorker.value = new Worker(sttWorkerUrl, {
type: 'module',
});
sttWorker.value.addEventListener('message', onSTTMessageReceived);
sttWorker.value.addEventListener('error', onSTTErrorReceived);
// Load STT model
sttWorker.value.postMessage({ type: 'load' });
}
if (effectiveSettings.value.provider === 'local') {
worker.value.postMessage({ type: 'check' });
if (isWebGpuAvailable.value === true) {
loadModel();
}
} else {
// For API providers, initialize with settings including system prompt (convert to plain object)
const settingsWithPrompt = {
...effectiveSettings.value,
currentSystemPromptId: currentSystemPromptId.value,
currentSystemPrompt: getCurrentSystemPrompt.value
};
worker.value.postMessage({ type: 'init', data: JSON.parse(JSON.stringify(settingsWithPrompt)) });
}
};
const loadSettings = () => {
const stored = localStorage.getItem('ai-chat-settings');
if (stored) {
try {
const parsed = JSON.parse(stored);
currentSettings.value = { ...currentSettings.value, ...parsed };
} catch (e) {
console.warn('Failed to parse stored settings:', e);
}
}
};
const onSettingsChanged = (newSettings) => {
// Update current settings
currentSettings.value = newSettings;
// Always reinitialize worker when settings change from Settings modal
// This ensures the new settings take effect immediately
status.value = null;
initializeWorker();
};
const onQuickSettingsChanged = async (newSettings) => {
// Update per-chat provider settings
currentChatProvider.value = newSettings.provider;
currentChatSelectedCustomApi.value = newSettings.selectedCustomApi;
// Save the provider settings for the current chat
if (currentChatId.value) {
try {
await chatStorage.updateChatProvider(currentChatId.value, newSettings.provider, newSettings.selectedCustomApi);
} catch (error) {
console.error('Failed to save provider settings for chat:', error);
}
}
// Reinitialize worker with the new settings
status.value = null;
initializeWorker();
};
onMounted(async () => {
isWebGpuAvailable.value = !!navigator.gpu;
loadSettings();
await initializeChatStorage();
// Don't initialize worker here - it will be initialized when the first chat is selected/created
// Lazy-preload TTS model and voices; unlock will happen on mic start
initTTS({ modelUrl: '/tts-model/kitten_tts_nano_v0_1.onnx', voicesJsonUrl: '/tts-model/voices.json' }).catch(() => {});
// Scroll to bottom after initial load
await nextTick(() => {
scrollToBottom();
});
});
onUnmounted(() => {
if (worker.value) {
worker.value.removeEventListener('message', onMessageReceived);
worker.value.removeEventListener('error', onErrorReceived);
}
if (sttWorker.value) {
sttWorker.value.removeEventListener('message', onSTTMessageReceived);
sttWorker.value.removeEventListener('error', onSTTErrorReceived);
}
// Clean up recording
stopContinuousRecording();
});
watch(messages, () => {
// Don't trigger generation when loading history
if (isLoadingHistory.value) {
return;
}
if (messages.value.filter((x) => x.role === 'user').length === 0) {
return;
}
if (messages.value[messages.value.length - 1].role === 'assistant') {
return;
}
tps.value = null;
worker.value.postMessage({ type: 'generate', data: JSON.parse(JSON.stringify(messages.value)) });
}, { deep: true });
// Watch for when we finish loading history to scroll to bottom
watch(isLoadingHistory, (newVal, oldVal) => {
if (oldVal === true && newVal === false) {
// We just finished loading history, scroll to bottom
nextTick(() => {
scrollToBottom();
});
}
});
// Watch for messages changes to adjust padding during AI response
watch(messages, () => {
if (isRunning.value && chatContainerRef.value) {
// Adjust padding as AI response grows
adjustBottomPadding();
}
}, { deep: true });
watch([messages, isRunning], () => {
if (!chatContainerRef.value || !isRunning.value) return;
nextTick(() => {
const element = chatContainerRef.value;
if (
element.scrollHeight - element.scrollTop - element.clientHeight <
STICKY_SCROLL_THRESHOLD
) {
element.scrollTop = element.scrollHeight;
}
});
});
// Watch for chat changes to scroll to bottom
watch(currentChatId, () => {
nextTick(() => {
setTimeout(() => {
scrollToBottom();
}, 500);
});
});
const loadModel = () => {
const settingsWithPrompt = {
...effectiveSettings.value,
currentSystemPromptId: currentSystemPromptId.value,
currentSystemPrompt: getCurrentSystemPrompt.value
};
if (effectiveSettings.value.provider === 'local') {
worker.value.postMessage({
type: 'load',
data: effectiveSettings.value.localModel,
systemPrompt: JSON.parse(JSON.stringify(getCurrentSystemPrompt.value))
});
} else {
worker.value.postMessage({
type: 'init',
data: JSON.parse(JSON.stringify(settingsWithPrompt))
});
}
status.value = 'loading';
};
const reset = async () => {
worker.value.postMessage({ type: 'reset' });
messages.value = [];
if (currentChatId.value) {
await chatStorage.clearMessages(currentChatId.value);
}
};
const initializeChatStorage = async () => {
try {
await chatStorage.init();
await loadChats();
} catch (error) {
console.error('Failed to initialize chat storage:', error);
}
};
const loadChats = async () => {
try {
chats.value = await chatStorage.getAllChats();
if (chats.value.length === 0) {
await createNewChat();
} else {
// Load the first chat and its settings
await selectChat(chats.value[0].id);
// Ensure we scroll to bottom after loading
await nextTick();
scrollToBottom();
}
} catch (error) {
console.error('Failed to load chats:', error);
}
};
const loadCurrentChat = async () => {
if (!currentChatId.value) return;
try {
isLoadingHistory.value = true;
messages.value = await chatStorage.getMessages(currentChatId.value);
// Reset last AI message index
lastAiMessageIndex.value = -1;
// Find the last AI message if any
for (let i = messages.value.length - 1; i >= 0; i--) {
if (messages.value[i].role === 'assistant') {
lastAiMessageIndex.value = i;
break;
}
}
isLoadingHistory.value = false;
await nextTick();
scrollToBottom();
} catch (error) {
console.error('Failed to load chat messages:', error);
messages.value = [];
lastAiMessageIndex.value = -1;
isLoadingHistory.value = false;
}
};