fix
Browse filesFiles changed (2)
72 unmodified lines73747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018172 unmodified lines</div><!-- AI message --><div *ngIf="message.from === 'ai' && !message.pending" class="message-wrapper ai"><div class="profile-pic"><img src="assets/images/chat/natasha.png" alt="AI" /></div><div class="message structured-response"><div [innerHTML]="formatStructuredResponse(message.text)"></div><!-- Follow-ups --><div class="followups" *ngIf="message.suggestions?.length"><div class="followups-title">Follow-up suggestions</div><button class="followup-chip"*ngFor="let s of message.suggestions"(click)="selectHardcodedQuestion(s)"title="Ask this next">{{ s }}</button></div><div class="message-timestamp">{{ message.timestamp }}<!-- Copy --><button class="icon-btn" (click)="copyToClipboard(message.text, i)"[attr.aria-label]="copySuccessIndex === i ? 'Copied' : 'Copy message'"title="Copy message"><ng-container *ngIf="copySuccessIndex === i; else showCopy"><span class="copy-tick">✓</span></ng-container><ng-template #showCopy><img src="assets/images/chat/copy.png" alt="Copy" class="meta-icon" /></ng-template></button><!-- Audio: play / stop --><button class="icon-btn"*ngIf="message.audioUrl && isReadingIndex !== i"(click)="playServerAudioForMessage(i)"aria-label="Play audio" title="Play audio"><img src="assets/images/chat/speaker.png" alt="Play audio" class="meta-icon" /></button><button class="icon-btn"*ngIf="message.audioUrl && isReadingIndex === i"(click)="stopReadAloud()"aria-label="Stop audio" title="Stop audio"><img src="assets/images/chat/stop-button.png" alt="Stop audio" class="meta-icon" /></button><!-- Generate audio on demand --><button class="icon-btn"*ngIf="!message.audioUrl"(click)="synthesizeAudioAndPlay(i)"[disabled]="message.isSynthesizing"aria-label="Generate audio"title="Generate audio"><ng-container *ngIf="!message.isSynthesizing; else audioSpinner"><img src="assets/images/chat/speaker.png" alt="Generate audio" class="meta-icon" /></ng-container><ng-template #audioSpinner><img src="assets/images/chat/loading-spinner.gif" alt="Generating audio" class="meta-icon" /></ng-template></button><!-- Video: generate, play, stop --><!-- Show Generate when no cached video --><button class="icon-btn"*ngIf="!message.videoUrl && !message.isVideoSynthesizing"(click)="synthesizeVideoAndPlay(i)"aria-label="Generate video"title="Generate video"><img src="assets/images/chat/video.png" alt="Generate video" class="meta-icon" /></button><!-- Spinner while generating video --><button class="icon-btn" *ngIf="!message.videoUrl && message.isVideoSynthesizing" disabled><img src="assets/images/chat/loading-spinner.gif" alt="Generating video" class="meta-icon" /></button><!-- Toggle inline video (single button). Show video.png initially, switches to no-video.png when enabled --><button class="icon-btn"*ngIf="message.videoUrl"(click)="toggleMessageVideo(i)"[class.active]="isVideoEnabledIndex[i]"aria-label="Toggle video"title="Toggle video"><img [src]="isVideoEnabledIndex[i] ? 'assets/images/chat/no-video.png' : 'assets/images/chat/video.png'"alt="Video" class="meta-icon" /></button></div><!-- Inline video player --><video *ngIf="isVideoEnabledIndex[i] && message.playingVideoUrl"id="inline-video-{{i}}"class="tutor-video"[src]="message.playingVideoUrl"(ended)="onMessageVideoEnded(i)"controls autoplay></video></div></div></div><!-- Typing indicator --><div *ngIf="isTyping" class="typing-indicator" aria-live="polite">72 unmodified lines73747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118272 unmodified lines</div><!-- AI message --><div *ngIf="message.from === 'ai'" class="message-wrapper ai"><div class="profile-pic"><img src="assets/images/chat/natasha.png" alt="AI" /></div><div class="message structured-response"><div [innerHTML]="formatStructuredResponse(message.text)"></div><!-- Follow-ups --><div class="followups" *ngIf="message.suggestions?.length"><div class="followups-title">Follow-up suggestions</div><button class="followup-chip"*ngFor="let s of message.suggestions"(click)="selectHardcodedQuestion(s)"title="Ask this next">{{ s }}</button></div><div class="message-timestamp">{{ message.timestamp }}<!-- Copy --><button class="icon-btn" (click)="copyToClipboard(message.text, i)"[attr.aria-label]="copySuccessIndex === i ? 'Copied' : 'Copy message'"title="Copy message"><ng-container *ngIf="copySuccessIndex === i; else showCopy"><span class="copy-tick">✓</span></ng-container><ng-template #showCopy><img src="assets/images/chat/copy.png" alt="Copy" class="meta-icon" /></ng-template></button><!-- Audio: play / stop --><button class="icon-btn"*ngIf="message.audioUrl && isReadingIndex !== i"(click)="playServerAudioForMessage(i)"aria-label="Play audio" title="Play audio"><img src="assets/images/chat/speaker.png" alt="Play audio" class="meta-icon" /></button><button class="icon-btn"*ngIf="message.audioUrl && isReadingIndex === i"(click)="stopReadAloud()"aria-label="Stop audio" title="Stop audio"><img src="assets/images/chat/stop-button.png" alt="Stop audio" class="meta-icon" /></button><!-- Generate audio on demand --><button class="icon-btn"*ngIf="!message.audioUrl"(click)="synthesizeAudioAndPlay(i)"[disabled]="message.isSynthesizing"aria-label="Generate audio"title="Generate audio"><ng-container *ngIf="!message.isSynthesizing; else audioSpinner"><img src="assets/images/chat/speaker.png" alt="Generate audio" class="meta-icon" /></ng-container><ng-template #audioSpinner><img src="assets/images/chat/loading-spinner.gif" alt="Generating audio" class="meta-icon" /></ng-template></button><!-- Video: generate, play, stop --><!-- Show Generate when no cached video --><button class="icon-btn"*ngIf="!message.videoUrl && !message.isVideoSynthesizing"(click)="synthesizeVideoAndPlay(i)"aria-label="Generate video"title="Generate video"><img src="assets/images/chat/video.png" alt="Generate video" class="meta-icon" /></button><!-- Spinner while generating video --><button class="icon-btn" *ngIf="!message.videoUrl && message.isVideoSynthesizing" disabled><img src="assets/images/chat/loading-spinner.gif" alt="Generating video" class="meta-icon" /></button><!-- Toggle inline video (single button). Show video.png initially, switches to no-video.png when enabled --><button class="icon-btn"*ngIf="message.videoUrl"(click)="toggleMessageVideo(i)"[class.active]="isVideoEnabledIndex[i]"aria-label="Toggle video"title="Toggle video"><img [src]="isVideoEnabledIndex[i] ? 'assets/images/chat/no-video.png' : 'assets/images/chat/video.png'"alt="Video" class="meta-icon" /></button></div><!-- Inline video player --><video *ngIf="isVideoEnabledIndex[i] && message.playingVideoUrl"id="inline-video-{{i}}"class="tutor-video"[src]="message.playingVideoUrl"(ended)="onMessageVideoEnded(i)"controls autoplay></video></div></div></div><!-- Typing indicator --><div *ngIf="isTyping" class="typing-indicator" aria-live="polite">
283 unmodified lines2842852862872882892902912922932942952962975 unmodified lines30330430530630730830931031131231321 unmodified lines335336337338339340341342343344345346347217 unmodified lines56556656756856957024 unmodified lines59559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264314 unmodified lines6586596606616626636646656666676682 unmodified lines67167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570641 unmodified lines7487497507517527537547557567577587597608 unmodified lines769770771772773774775776777778779780781782783784785786787788789790791792283 unmodified lines}}//private storageHandler = (e: StorageEvent) => {// if (e.key === 'hasPDF') this.showRagModeAlert();//};//private showRagModeAlert(): void {// const ragEnabled = localStorage.getItem('rag_enabled') === '1' || localStorage.getItem('hasPDF') === 'true';// // No-op placeholder//}ngOnInit(): void {this.ensureGradeLevel();5 unmodified linesthis.loadVoices();}//ngAfterViewChecked() {// setTimeout(() => {// this.scrollToBottom();// }, 100);//}ngOnDestroy(): void {if (this.currentExplainSub) { this.currentExplainSub.unsubscribe(); this.currentExplainSub = null; }21 unmodified lines});}//scrollToBottom(): void {// try {// this.chatBox.nativeElement.scrollTo({ top: this.chatBox.nativeElement.scrollHeight, behavior: 'smooth' });// } catch (err) {// console.error('Scroll error:', err);// }//}scrollToBottom(): void {if (this.shouldAutoScroll) {217 unmodified linesthis.sendMessage();}/** Send question to backend for an answer */sendMessage(inputText?: string): void {const message = inputText ? inputText.trim() : this.userInput.trim();24 unmodified lines? response.source_ids.filter((s: any) => typeof s === 'string' && s.trim().length > 0): [];this.messages.push({from: 'ai',text: explanation,timestamp: new Date().toLocaleTimeString(),source_ids: sourceIds});this.cdr.detectChanges();this.shouldAutoScroll = true;this.scrollToBottom();this.lastQuestion = message;this.lastAnswer = explanation;this.lastSourceIds = sourceIds;// NEW: mark if the answer is grounded in textbook pagesconst notFound = /No information available in the provided textbook content/i.test(explanation);this.lastAnswerHasContext = !!sourceIds.length && !notFound;this.speakResponse(explanation);},error: (err) => {console.error('API Error:', err);this.isTyping = false;const errorMessage = 'Error: Could not get a response from the server.';this.messages.push({from: 'ai',text: errorMessage,timestamp: new Date().toLocaleTimeString(),source_ids: []});this.cdr.detectChanges();this.shouldAutoScroll = true;this.scrollToBottom();// NEW: ensure follow-ups are not attempted after an errorthis.lastAnswerHasContext = false;this.speakResponse(errorMessage);}});}displaySource(tag: string): string {14 unmodified lines}/** TTS helpers */animateAiResponse(responseText: string, targetIndex?: number): void {if (!responseText) { this.isAiResponding = false; return; }let aiIndex: number | null = null;if (typeof targetIndex === 'number' && this.messages[targetIndex] && this.messages[targetIndex].from === 'ai') {aiIndex = targetIndex;} else {for (let i = this.messages.length - 1; i >= 0; i--) {2 unmodified lines}if (aiIndex === null || aiIndex < 0 || !this.messages[aiIndex]) {this.messages.push({ from: 'ai', text: '', timestamp: new Date().toLocaleTimeString() } as any);aiIndex = this.messages.length - 1;this.isVideoEnabledIndex.push(false);}const aiMsg = this.messages[aiIndex] as any;if (this.aiResponseInterval) { clearInterval(this.aiResponseInterval); this.aiResponseInterval = null; }aiMsg.text = '';this.cdr.detectChanges();const words = responseText.split(' ');let idx = 0;this.aiResponseInterval = setInterval(() => {if (idx < words.length) {aiMsg.text = words.slice(0, idx + 1).join(' ');idx++;this.cdr.detectChanges();} else {clearInterval(this.aiResponseInterval);this.aiResponseInterval = null;aiMsg.text = responseText;aiMsg.pending = false;this.cdr.detectChanges();this.isAiResponding = false;}}, 280);}stopAiResponse(): void {if (this.currentExplainSub) { this.currentExplainSub.unsubscribe(); this.currentExplainSub = null; }if (this.currentFollowupsSub) { this.currentFollowupsSub.unsubscribe(); this.currentFollowupsSub = null; }41 unmodified linesspeakResponse(responseText: string): void {if (!responseText) return;this.stopAllVideo();const speech = new SpeechSynthesisUtterance();speech.text = responseText;speech.lang = 'en-US';speech.pitch = 1;speech.rate = 1;this.isSpeaking = true;const voices = window.speechSynthesis.getVoices();const preferred = ['Google UK English Female',8 unmodified linesif (found) { speech.voice = found; break; }}if (!speech.voice && voices.length) speech.voice = voices[0];speech.onend = () => { this.isSpeaking = false; this.cdr.detectChanges(); };window.speechSynthesis.speak(speech);}//pauseAudio(): void {// if (this.serverAudio && !this.serverAudio.paused) {// this.serverAudio.pause();// this.isAudioPaused = true;// if (this.serverAudioMessageIndex !== null) this.messages[this.serverAudioMessageIndex].isPlaying = false;// this.cdr.detectChanges();// return;// }// if (window.speechSynthesis && window.speechSynthesis.speaking && !window.speechSynthesis.paused) {// window.speechSynthesis.pause();// this.isAudioPaused = true;// this.cdr.detectChanges();// }//}resumeAudio(): void {if (this.serverAudio && this.serverAudio.paused) {283 unmodified lines2842852862872882892905 unmodified lines29629729829930030130221 unmodified lines324325326327328329330217 unmodified lines54854955055155255355424 unmodified lines57958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164214 unmodified lines6576586596606616626636646656666676686696706716726736746756766776786792 unmodified lines68268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873941 unmodified lines7817827837847857867877887897907917927937947957967977987998 unmodified lines808809810811812813814815816817818819820821822823824825826827828283 unmodified lines}}ngOnInit(): void {this.ensureGradeLevel();5 unmodified linesthis.loadVoices();}ngOnDestroy(): void {if (this.currentExplainSub) { this.currentExplainSub.unsubscribe(); this.currentExplainSub = null; }21 unmodified lines});}scrollToBottom(): void {if (this.shouldAutoScroll) {217 unmodified linesthis.sendMessage();}/** Send question to backend for an answer *//** Send question to backend for an answer */sendMessage(inputText?: string): void {const message = inputText ? inputText.trim() : this.userInput.trim();24 unmodified lines? response.source_ids.filter((s: any) => typeof s === 'string' && s.trim().length > 0): [];// Store question + source ids *now*.this.lastQuestion = message;this.lastSourceIds = sourceIds;const notFound = /No information available in the provided textbook content/i.test(explanation);const hasContext = !!sourceIds.length && !notFound;// IMPORTANT:// Do NOT set this.lastAnswer here.// We will set it only after the streaming animation has finished.this.streamAiAnswer(explanation, sourceIds, hasContext);},error: (err) => {console.error('API Error:', err);this.isTyping = false;const errorMessage = 'Error: Could not get a response from the server.';// We can still stream the error text (or you can show it directly if you prefer)this.streamAiAnswer(errorMessage, [], false);}});}/** Show AI answer word-by-word and start audio *//** Show AI answer word-by-word and start audio */private streamAiAnswer(explanation: string, sourceIds: string[], hasContext: boolean): void {const text = (explanation || '').trim() || 'No explanation available.';const timestamp = new Date().toLocaleTimeString();// Create an empty AI message firstconst aiIndex = this.messages.push({from: 'ai',text: '',timestamp,source_ids: sourceIds,pending: true} as any) - 1;this.isAiResponding = true;this.shouldAutoScroll = true;this.cdr.detectChanges();// Animate the text word by wordthis.animateAiResponse(text, aiIndex, () => {// When streaming is finished, we finally store lastAnswerthis.lastAnswer = text;this.lastAnswerHasContext = hasContext;});// Play audio at the same time (only if voice is enabled)this.speakResponse(text);}displaySource(tag: string): string {14 unmodified lines}/** TTS helpers *//** TTS helpers *//** TTS helpers + typing animation */animateAiResponse(responseText: string,targetIndex?: number,onDone?: () => void): void {if (!responseText) {this.isAiResponding = false;return;}// Find or create the AI message to animate intolet aiIndex: number | null = null;if (typeof targetIndex === 'number' &&this.messages[targetIndex] &&this.messages[targetIndex].from === 'ai') {aiIndex = targetIndex;} else {for (let i = this.messages.length - 1; i >= 0; i--) {2 unmodified lines}if (aiIndex === null || aiIndex < 0 || !this.messages[aiIndex]) {this.messages.push({from: 'ai',text: '',timestamp: new Date().toLocaleTimeString()} as any);aiIndex = this.messages.length - 1;this.isVideoEnabledIndex.push(false);}const aiMsg = this.messages[aiIndex] as any;if (this.aiResponseInterval) {clearInterval(this.aiResponseInterval);this.aiResponseInterval = null;}aiMsg.text = '';aiMsg.pending = true;this.isAiResponding = true;this.cdr.detectChanges();const words = responseText.split(/\s+/).filter(w => w.length);let idx = 0;// 1 word every 200 ms – you can tune thisconst speedMs = 200;this.aiResponseInterval = setInterval(() => {if (idx < words.length) {aiMsg.text = words.slice(0, idx + 1).join(' ');idx++;this.cdr.detectChanges();this.scrollToBottom(); // keep view at bottom while streaming} else {clearInterval(this.aiResponseInterval!);this.aiResponseInterval = null;aiMsg.text = responseText;aiMsg.pending = false;this.isAiResponding = false;if (onDone) {onDone();}this.cdr.detectChanges();this.scrollToBottom();}}, speedMs);}stopAiResponse(): void {if (this.currentExplainSub) { this.currentExplainSub.unsubscribe(); this.currentExplainSub = null; }if (this.currentFollowupsSub) { this.currentFollowupsSub.unsubscribe(); this.currentFollowupsSub = null; }41 unmodified linesspeakResponse(responseText: string): void {if (!responseText) return;// Only speak when the Voice toggle is ONif (!this.isVoiceEnabled) return;this.stopAllVideo();const speech = new SpeechSynthesisUtterance();speech.text = responseText;speech.lang = 'en-US';speech.pitch = 1;speech.rate = 1;this.isSpeaking = true;const voices = window.speechSynthesis.getVoices();const preferred = ['Google UK English Female',8 unmodified linesif (found) { speech.voice = found; break; }}if (!speech.voice && voices.length) speech.voice = voices[0];speech.onend = () => {this.isSpeaking = false;this.cdr.detectChanges();};try {window.speechSynthesis.speak(speech);} catch {this.isSpeaking = false;}}resumeAudio(): void {if (this.serverAudio && this.serverAudio.paused) {
src/app/chat/chat.component.html+99-98
src/app/chat/chat.component.ts+109-73