← back to Dear Bubbe Nextjs

archived/tests/test-voice-onboarding.js

171 lines

#!/usr/bin/env node

/**
 * Test script to verify voice activation after onboarding completion
 * This simulates the onboarding completion flow and checks if voice plays automatically
 */

const puppeteer = require('puppeteer');

async function testVoiceOnboardingCompletion() {
  console.log('🎙️ Testing voice activation after onboarding completion...');
  
  const browser = await puppeteer.launch({ 
    headless: false,
    args: [
      '--no-sandbox',
      '--disable-setuid-sandbox',
      '--disable-web-security',
      '--allow-running-insecure-content',
      '--autoplay-policy=no-user-gesture-required'
    ]
  });
  
  try {
    const page = await browser.newPage();
    
    // Set up console logging to catch voice-related logs
    page.on('console', msg => {
      if (msg.text().includes('[VOICE]') || 
          msg.text().includes('[ONBOARDING]') || 
          msg.text().includes('[AUDIO]')) {
        console.log('🔊', msg.text());
      }
    });

    // Enable audio context
    await page.evaluateOnNewDocument(() => {
      // Override browser autoplay policies for testing
      Object.defineProperty(HTMLMediaElement.prototype, 'play', {
        value: function() {
          console.log('[TEST] Audio.play() called');
          return Promise.resolve();
        }
      });
    });

    console.log('📱 Loading Dear Bubbe website...');
    await page.goto('http://45.61.58.125:3011', { waitUntil: 'networkidle0' });

    // Wait for page to fully load
    await page.waitForTimeout(2000);

    console.log('👤 Simulating user login (if needed)...');
    
    // Check if onboarding modal is present
    const onboardingExists = await page.$('.fixed.inset-0.z-50.bg-gradient-to-br.from-amber-50');
    
    if (onboardingExists) {
      console.log('✅ Onboarding modal found! Simulating completion...');
      
      // Simulate user interaction first (required for audio autoplay)
      await page.click('body');
      
      // Fill out onboarding form step by step
      await page.waitForSelector('input[placeholder="Your preferred name"]', { timeout: 5000 });
      await page.type('input[placeholder="Your preferred name"]', 'Test User');
      await page.click('button:contains("Next")');
      
      await page.waitForTimeout(1000);
      
      // Select gender
      await page.click('button:contains("👨 Male")');
      await page.click('button:contains("Next")');
      
      await page.waitForTimeout(1000);
      
      // Skip through remaining steps quickly for testing
      for (let i = 0; i < 8; i++) {
        try {
          await page.waitForSelector('button:contains("Next")', { timeout: 2000 });
          await page.click('button:contains("Next")');
          await page.waitForTimeout(500);
        } catch (e) {
          break;
        }
      }
      
      // Complete onboarding
      const finishButton = await page.$('button:contains("Let\'s talk!")');
      if (finishButton) {
        console.log('🎯 Completing onboarding - this should trigger voice welcome...');
        
        // Mark that we expect voice to play
        await page.evaluate(() => {
          window.__expectingVoiceWelcome = true;
        });
        
        await finishButton.click();
        
        // Wait for onboarding completion processing
        await page.waitForTimeout(3000);
        
        // Check if voice-related flags were set
        const voiceStatus = await page.evaluate(() => {
          return {
            hasUserInteraction: window.__hasUserInteraction,
            onboardingCompleted: window.__onboardingJustCompleted,
            lastVoiceText: window.__lastVoiceText,
            audioPlaybackSuccessful: window.__audioPlaybackSuccessful
          };
        });
        
        console.log('🔍 Voice status check:', voiceStatus);
        
        // Check if chat modal opened
        const chatModal = await page.$('[role="dialog"]');
        if (chatModal) {
          console.log('✅ Chat modal opened successfully');
          
          // Look for welcome message
          await page.waitForTimeout(2000);
          const messages = await page.$$eval('.space-y-4 .p-3', elements => 
            elements.map(el => el.textContent)
          );
          
          console.log('💬 Messages found:', messages.length);
          if (messages.length > 0) {
            console.log('📝 Latest message:', messages[messages.length - 1]?.substring(0, 100));
            console.log('✅ Voice welcome message should have played!');
          }
        }
        
      } else {
        console.log('❌ Could not find finish button');
      }
      
    } else {
      console.log('ℹ️ No onboarding modal found - user may already be onboarded');
      
      // Check if there's a talk button to test voice activation
      const talkButton = await page.$('button[class*="pulse"]');
      if (talkButton) {
        console.log('🎤 Found talk button, testing voice activation...');
        await talkButton.click();
        await page.waitForTimeout(2000);
        
        const voiceStatus = await page.evaluate(() => {
          return {
            hasUserInteraction: window.__hasUserInteraction,
            lastVoiceText: window.__lastVoiceText
          };
        });
        
        console.log('🔍 Voice status after talk button:', voiceStatus);
      }
    }

  } catch (error) {
    console.error('❌ Test failed:', error);
  } finally {
    await browser.close();
  }
}

// Run the test
testVoiceOnboardingCompletion().then(() => {
  console.log('🏁 Voice onboarding test completed');
}).catch(error => {
  console.error('💥 Test error:', error);
  process.exit(1);
});