← back to Dear Bubbe Nextjs

archived/tests/verify-voice-fix.js

206 lines

#!/usr/bin/env node

/**
 * Verify that the voice activation fix is working properly
 * Tests the API endpoints and logic flow
 */

const http = require('http');

function makeRequest(options, postData = null) {
  return new Promise((resolve, reject) => {
    const req = http.request(options, (res) => {
      let data = '';
      res.on('data', (chunk) => {
        data += chunk;
      });
      res.on('end', () => {
        try {
          const parsed = res.headers['content-type']?.includes('application/json') 
            ? JSON.parse(data) 
            : data;
          resolve({ status: res.statusCode, headers: res.headers, body: parsed });
        } catch (e) {
          resolve({ status: res.statusCode, headers: res.headers, body: data });
        }
      });
    });
    
    req.on('error', reject);
    
    if (postData) {
      req.write(postData);
    }
    req.end();
  });
}

async function verifyVoiceFix() {
  console.log('🔍 Verifying voice activation fix...\n');
  
  const baseUrl = 'http://45.61.58.125:3011';
  
  // Test 1: Check if main page loads
  console.log('1️⃣ Testing main page accessibility...');
  try {
    const response = await makeRequest({
      hostname: '45.61.58.125',
      port: 3011,
      path: '/',
      method: 'GET',
      headers: { 'Accept': 'text/html' }
    });
    
    if (response.status === 200) {
      console.log('✅ Main page loads successfully');
    } else {
      console.log('❌ Main page failed to load:', response.status);
      return;
    }
  } catch (error) {
    console.log('❌ Error loading main page:', error.message);
    return;
  }
  
  // Test 2: Check chat API for profile completion
  console.log('\n2️⃣ Testing profile completion flow...');
  try {
    const testProfile = {
      preferredName: 'Test User',
      gender: 'male',
      relationshipStatus: 'single',
      birthYear: '1990',
      bubbeVoice: 'yU6e7uJLZCE8eA26VAqb',
      triggerVoiceWelcome: true
    };
    
    const postData = JSON.stringify({
      message: '__profile_complete__',
      userId: 'test_user_voice_fix',
      mode: 'bubbe',
      userProfile: testProfile
    });
    
    const response = await makeRequest({
      hostname: '45.61.58.125',
      port: 3011,
      path: '/api/chat',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData)
      }
    }, postData);
    
    if (response.status === 200 && response.body.response) {
      console.log('✅ Profile completion API works');
      console.log('📝 Generated welcome message:', response.body.response.substring(0, 100) + '...');
      
      // Test 3: Check if voice synthesis works with the message
      console.log('\n3️⃣ Testing voice synthesis for welcome message...');
      
      const voiceData = JSON.stringify({
        text: response.body.response,
        mode: 'bubbe',
        voiceId: testProfile.bubbeVoice
      });
      
      const voiceResponse = await makeRequest({
        hostname: '45.61.58.125',
        port: 3011,
        path: '/api/bubbe-voice',
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Content-Length': Buffer.byteLength(voiceData)
        }
      }, voiceData);
      
      if (voiceResponse.status === 200 && voiceResponse.headers['content-type']?.includes('audio')) {
        console.log('✅ Voice synthesis works for welcome message');
        console.log('🎵 Audio size:', voiceResponse.headers['content-length'], 'bytes');
      } else {
        console.log('❌ Voice synthesis failed:', voiceResponse.status);
      }
      
    } else {
      console.log('❌ Profile completion API failed:', response.status, response.body);
    }
  } catch (error) {
    console.log('❌ Error testing profile completion:', error.message);
  }
  
  // Test 4: Verify code changes are in place
  console.log('\n4️⃣ Verifying code fixes are implemented...');
  
  const fs = require('fs');
  const pageContent = fs.readFileSync('/root/Projects/dear-bubbe-nextjs/app/page.tsx', 'utf8');
  
  const checks = [
    { name: 'User interaction flag set', search: '__hasUserInteraction = true' },
    { name: 'Onboarding completion flag', search: '__onboardingJustCompleted = true' },
    { name: 'Voice welcome trigger check', search: 'profileData.triggerVoiceWelcome' },
    { name: 'Voice settings application', search: 'localStorage.setItem(\'bubbeVoice\', profileData.bubbeVoice)' },
    { name: 'Error handling for voice playback', search: 'catch (voiceError)' },
    { name: 'Pending audio fallback', search: '__pendingOnboardingAudio' }
  ];
  
  let allChecksPass = true;
  
  checks.forEach(check => {
    if (pageContent.includes(check.search)) {
      console.log(`✅ ${check.name}`);
    } else {
      console.log(`❌ ${check.name}`);
      allChecksPass = false;
    }
  });
  
  // Test 5: Check UserOnboarding component
  console.log('\n5️⃣ Checking UserOnboarding component...');
  
  try {
    const onboardingContent = fs.readFileSync('/root/Projects/dear-bubbe-nextjs/components/UserOnboarding.tsx', 'utf8');
    
    if (onboardingContent.includes('triggerVoiceWelcome: true')) {
      console.log('✅ UserOnboarding sets triggerVoiceWelcome flag');
    } else {
      console.log('❌ UserOnboarding missing triggerVoiceWelcome flag');
      allChecksPass = false;
    }
    
    if (onboardingContent.includes('bubbeVoice')) {
      console.log('✅ Voice selection is included in onboarding');
    } else {
      console.log('❌ Voice selection missing from onboarding');
      allChecksPass = false;
    }
    
  } catch (error) {
    console.log('❌ Error checking UserOnboarding component:', error.message);
    allChecksPass = false;
  }
  
  // Summary
  console.log('\n' + '='.repeat(50));
  console.log('🏆 VOICE ACTIVATION FIX VERIFICATION SUMMARY');
  console.log('='.repeat(50));
  
  if (allChecksPass) {
    console.log('✅ ALL CHECKS PASSED! Voice activation should work properly after onboarding completion.');
    console.log('\n📋 What was fixed:');
    console.log('• Added proper user interaction flag for audio autoplay');
    console.log('• Implemented onboarding completion detection');
    console.log('• Added voice settings application from profile data');
    console.log('• Enhanced error handling with fallback mechanisms');
    console.log('• Added timeout delays to ensure UI is ready');
    console.log('• Included pending audio playback for blocked autoplay');
    console.log('\n🎯 The voice welcome message should now play automatically when users complete onboarding!');
  } else {
    console.log('❌ Some checks failed. Please review the implementation.');
  }
  
  console.log('\n🔗 Test the fix at: http://45.61.58.125:3011');
}

verifyVoiceFix().catch(console.error);