import { useEffect, useRef, useState } from "react"; import { db, auth } from "../firebase"; import { AUDIO_COMPLETION_URL } from "../config"; import { doc, setDoc } from "firebase/firestore"; function TrialTaskAudio({ trialIndex, totalTrials, trialId, onNext, onExitEarly, sessionId, participantNumber }) { const DEV_MODE = false; // Set to false for production const [trialData, setTrialData] = useState(null); const [order, setOrder] = useState([1, 2]); const [ratings, setRatings] = useState({ r1: null, r2: null }); const [quality, setQuality] = useState({ q1: null, q2: null }); const [timestamps, setTimestamps] = useState({}); const [plays, setPlays] = useState({ a1: 0, a2: 0 }); const [listenTimes, setListenTimes] = useState({ a1: [], a2: [] }); const [relistenTimes, setRelistenTimes] = useState({ a1: [], a2: [] }); const [startTime, setStartTime] = useState(null); const [isPlaying, setIsPlaying] = useState({ a1: false, a2: false }); const [currentTime, setCurrentTime] = useState({ a1: 0, a2: 0 }); const [duration, setDuration] = useState({ a1: 0, a2: 0 }); const [ratingChanges, setRatingChanges] = useState({ r1: [], r2: [] }); const [qualityChanges, setQualityChanges] = useState({ q1: [], q2: [] }); const [seekEvents, setSeekEvents] = useState({ a1: [], a2: [] }); const [skipEvents, setSkipEvents] = useState({ a1: [], a2: [] }); const [seekStartTime, setSeekStartTime] = useState({ a1: null, a2: null }); const [hasCompletedOnce, setHasCompletedOnce] = useState({ a1: false, a2: false }); const [completionTimestamps, setCompletionTimestamps] = useState({ a1: null, a2: null }); const [overallPreference, setOverallPreference] = useState(null); // 'A', 'Tie', or 'B' const [overallPreferenceChanges, setOverallPreferenceChanges] = useState([]); const [justification, setJustification] = useState(""); const [isSubmitting, setIsSubmitting] = useState(false); const isAttentionCheck = trialIndex === 0; const audioRefs = { a1: useRef(null), a2: useRef(null), }; useEffect(() => { // Scroll to top when new trial loads window.scrollTo(0, 0); const loadTrial = async () => { try { // If this is the first trial, use it as an attention check if (isAttentionCheck) { const attentionCheckData = { id: "attention_check", query: "Hello AI! I need some help writing a text message", audio_file_1: "37_0_0.mp3", audio_file_2: "37_0_1.mp3", audio_1_len: 4.775, // You may want to update with actual lengths audio_2_len: 12.775, // You may want to update with actual lengths prev_hist: "", conv_id: "attention", turn_no: "0", synth_text_1_rating: 85, synth_text_2_rating: 15, synth_audio_1_rating: 85, synth_audio_2_rating: 15, synth_audio_quality_1_rating: 95, synth_audio_quality_2_rating: 95, text_1_score: null, text_2_score: null }; setTrialData(attentionCheckData); } else { // Load survey data from JSON const response = await fetch('/survey_data.json'); const allSamples = await response.json(); // Find the trial by ID const trial = allSamples.find(sample => sample.id.toString() === trialId.toString()); if (trial) { setTrialData(trial); } } // Deterministic order assignment (ensures 5x5 split per modality) // Every 2 participants get the same order, alternating between [1,2] and [2,1] const orderFlip = Math.floor(participantNumber / 2) % 2; setOrder(orderFlip === 0 ? [1, 2] : [2, 1]); // Reset ratings and quality for new trial setRatings({ r1: null, r2: null }); setQuality({ q1: null, q2: null }); setTimestamps({}); setPlays({ a1: 0, a2: 0 }); setIsPlaying({ a1: false, a2: false }); setCurrentTime({ a1: 0, a2: 0 }); setDuration({ a1: 0, a2: 0 }); // Reset rating/quality change history for new trial setRatingChanges({ r1: [], r2: [] }); setQualityChanges({ q1: [], q2: [] }); // Reset seek/skip tracking for new trial setSeekEvents({ a1: [], a2: [] }); setSkipEvents({ a1: [], a2: [] }); setSeekStartTime({ a1: null, a2: null }); setHasCompletedOnce({ a1: false, a2: false }); setCompletionTimestamps({ a1: null, a2: null }); setOverallPreference(null); setOverallPreferenceChanges([]); setJustification(""); setIsSubmitting(false); setStartTime(Date.now()); } catch (error) { console.error("Failed to load trial data:", error); } }; loadTrial(); }, [trialId, isAttentionCheck, participantNumber]); const handlePlay = (clipNum) => { const key = `a${clipNum}`; const otherKey = clipNum === 1 ? 'a2' : 'a1'; const audio = audioRefs[key].current; const otherAudio = audioRefs[otherKey].current; if (!audio) return; if (isPlaying[key]) { audio.pause(); setIsPlaying(prev => ({ ...prev, [key]: false })); } else { // Pause the other audio if it's playing if (otherAudio && isPlaying[otherKey]) { otherAudio.pause(); setIsPlaying(prev => ({ ...prev, [otherKey]: false })); } const currentTimeStamp = Date.now(); // Track listen times setListenTimes((prev) => ({ ...prev, [key]: [...prev[key], currentTimeStamp] })); // Track relisten times (if played more than once) if (plays[key] > 0) { setRelistenTimes((prev) => ({ ...prev, [key]: [...prev[key], currentTimeStamp] })); } setPlays((prev) => ({ ...prev, [key]: prev[key] + 1 })); audio.play(); setIsPlaying(prev => ({ ...prev, [key]: true })); } }; const handleReplay = (clipNum) => { const key = `a${clipNum}`; const otherKey = clipNum === 1 ? 'a2' : 'a1'; const audio = audioRefs[key].current; const otherAudio = audioRefs[otherKey].current; if (!audio) return; // Pause the other audio if it's playing if (otherAudio && isPlaying[otherKey]) { otherAudio.pause(); setIsPlaying(prev => ({ ...prev, [otherKey]: false })); } audio.currentTime = 0; const currentTimeStamp = Date.now(); setListenTimes((prev) => ({ ...prev, [key]: [...prev[key], currentTimeStamp] })); // Track relisten times (if played more than once) if (plays[key] > 0) { setRelistenTimes((prev) => ({ ...prev, [key]: [...prev[key], currentTimeStamp] })); } setPlays((prev) => ({ ...prev, [key]: prev[key] + 1 })); audio.play(); setIsPlaying(prev => ({ ...prev, [key]: true })); }; const handleSeek = (clipNum, value) => { const key = `a${clipNum}`; const audio = audioRefs[key].current; if (!audio || !hasCompletedOnce[key]) return; const seekTime = (value / 100) * duration[key]; audio.currentTime = seekTime; setCurrentTime(prev => ({ ...prev, [key]: seekTime })); }; const handleSeekStart = (clipNum) => { const key = `a${clipNum}`; const audio = audioRefs[key].current; if (!audio || !hasCompletedOnce[key]) return; setSeekStartTime(prev => ({ ...prev, [key]: audio.currentTime })); }; const handleSeekEnd = (clipNum, value) => { const key = `a${clipNum}`; const audio = audioRefs[key].current; if (!audio || !hasCompletedOnce[key]) return; const startTime = seekStartTime[key]; const endTime = (value / 100) * duration[key]; // Only track if there was a meaningful seek (more than 0.5 seconds) if (startTime !== null && Math.abs(endTime - startTime) > 0.5) { setSeekEvents(prev => ({ ...prev, [key]: [...prev[key], { timestamp: new Date().toISOString(), fromTime: startTime, toTime: endTime, seekDirection: endTime > startTime ? 'forward' : 'backward', seekDistance: Math.abs(endTime - startTime) }] })); } // Reset seek start time setSeekStartTime(prev => ({ ...prev, [key]: null })); }; const handleSkipBack = (clipNum, seconds = 10) => { const key = `a${clipNum}`; const audio = audioRefs[key].current; if (!audio) return; const oldTime = audio.currentTime; const newTime = Math.max(0, audio.currentTime - seconds); // Track the skip event setSkipEvents(prev => ({ ...prev, [key]: [...prev[key], { timestamp: new Date().toISOString(), fromTime: oldTime, toTime: newTime, skipType: 'backward', skipAmount: seconds, actualSkipped: oldTime - newTime }] })); audio.currentTime = newTime; }; const setupAudioListeners = (clipNum) => { const key = `a${clipNum}`; const audio = audioRefs[key].current; if (!audio) return; const updateTime = () => { setCurrentTime(prev => ({ ...prev, [key]: audio.currentTime })); }; const updateDuration = () => { setDuration(prev => ({ ...prev, [key]: audio.duration })); }; const handleEnded = () => { setIsPlaying(prev => ({ ...prev, [key]: false })); setHasCompletedOnce(prev => ({ ...prev, [key]: true })); setCompletionTimestamps(prev => { // Only record the first completion timestamp if (prev[key] === null) { return { ...prev, [key]: Date.now() }; } return prev; }); }; audio.addEventListener('timeupdate', updateTime); audio.addEventListener('loadedmetadata', updateDuration); audio.addEventListener('ended', handleEnded); return () => { audio.removeEventListener('timeupdate', updateTime); audio.removeEventListener('loadedmetadata', updateDuration); audio.removeEventListener('ended', handleEnded); }; }; useEffect(() => { if (trialData) { const cleanup1 = setupAudioListeners(1); const cleanup2 = setupAudioListeners(2); return () => { cleanup1?.(); cleanup2?.(); }; } // eslint-disable-next-line react-hooks/exhaustive-deps }, [trialData]); const handleRating = (key, value) => { setRatings((prev) => ({ ...prev, [key]: value })); }; const handleRatingRelease = (key, value) => { setTimestamps((prev) => ({ ...prev, [`${key}Time`]: Date.now() })); // Determine which audio this rating is for (r1 -> a1, r2 -> a2) const audioKey = key === 'r1' ? 'a1' : 'a2'; const otherAudioKey = key === 'r1' ? 'a2' : 'a1'; const otherRatingKey = key === 'r1' ? 'r2' : 'r1'; const otherRatingValue = ratings[otherRatingKey]; setRatingChanges((prev) => ({ ...prev, [key]: [...prev[key], { value, timestamp: new Date().toISOString(), otherRatingValue, audioPlaying: isPlaying[audioKey], audioCurrentTime: currentTime[audioKey], audioDuration: duration[audioKey], otherAudioPlaying: isPlaying[otherAudioKey], otherAudioCurrentTime: currentTime[otherAudioKey], otherAudioDuration: duration[otherAudioKey] }] })); }; const handleQuality = (key, value) => { setQuality((prev) => ({ ...prev, [key]: value })); }; const handleQualityRelease = (key, value) => { setTimestamps((prev) => ({ ...prev, [`${key}Time`]: Date.now() })); // Determine which audio this quality rating is for (q1 -> a1, q2 -> a2) const audioKey = key === 'q1' ? 'a1' : 'a2'; const otherAudioKey = key === 'q1' ? 'a2' : 'a1'; const otherQualityKey = key === 'q1' ? 'q2' : 'q1'; const otherQualityValue = quality[otherQualityKey]; setQualityChanges((prev) => ({ ...prev, [key]: [...prev[key], { value, timestamp: new Date().toISOString(), otherQualityValue, audioPlaying: isPlaying[audioKey], audioCurrentTime: currentTime[audioKey], audioDuration: duration[audioKey], otherAudioPlaying: isPlaying[otherAudioKey], otherAudioCurrentTime: currentTime[otherAudioKey], otherAudioDuration: duration[otherAudioKey] }] })); }; const calculatePreferenceChanges = (afterCompletionTime = null) => { // Build a timeline of all rating changes const timeline = []; ratingChanges.r1.forEach(change => { timeline.push({ timestamp: change.timestamp, r1: change.value, r2: change.otherRatingValue }); }); ratingChanges.r2.forEach(change => { timeline.push({ timestamp: change.timestamp, r1: change.otherRatingValue, r2: change.value }); }); // Sort by timestamp timeline.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp)); // Filter by completion time if specified let filteredTimeline = timeline; if (afterCompletionTime !== null) { filteredTimeline = timeline.filter(entry => new Date(entry.timestamp).getTime() >= afterCompletionTime ); } // Count preference changes let preferenceChanges = 0; let lastPreference = null; // 'r1', 'r2', or 'tie' filteredTimeline.forEach(entry => { if (entry.r1 !== null && entry.r2 !== null) { let currentPreference; if (entry.r1 > entry.r2) { currentPreference = 'r1'; } else if (entry.r2 > entry.r1) { currentPreference = 'r2'; } else { currentPreference = 'tie'; } if (lastPreference !== null && lastPreference !== currentPreference) { preferenceChanges++; } lastPreference = currentPreference; } }); return preferenceChanges; }; const handleOverallPreferenceChange = (newPreference) => { setOverallPreference(newPreference); setOverallPreferenceChanges((prev) => [ ...prev, { value: newPreference, timestamp: new Date().toISOString(), previousValue: overallPreference } ]); }; const handleSubmit = async (e) => { e.preventDefault(); // Prevent double submission if (isSubmitting) return; // Validate all requirements are met if (!DEV_MODE) { if ( ratings.r1 === null || ratings.r2 === null || quality.q1 === null || quality.q2 === null || overallPreference === null || !hasCompletedOnce.a1 || !hasCompletedOnce.a2 ) { return; } } setIsSubmitting(true); const endTime = Date.now(); // Calculate when both audios were fully listened to const bothAudiosCompletedTime = completionTimestamps.a1 && completionTimestamps.a2 ? Math.max(completionTimestamps.a1, completionTimestamps.a2) : null; // Calculate preference changes const totalPreferenceChanges = calculatePreferenceChanges(); const preferenceChangesAfterCompletion = bothAudiosCompletedTime ? calculatePreferenceChanges(bothAudiosCompletedTime) : null; // Calculate time between both audios completed and trial end const timeAfterBothCompleted = bothAudiosCompletedTime ? endTime - bothAudiosCompletedTime : null; const first = order[0]; const second = order[1]; // Determine which audio was shown first based on order const audio1InOrder = first === 1 ? trialData.audio_file_1 : trialData.audio_file_2; const audio2InOrder = second === 1 ? trialData.audio_file_1 : trialData.audio_file_2; const length1InOrder = first === 1 ? trialData.audio_1_len : trialData.audio_2_len; const length2InOrder = second === 1 ? trialData.audio_1_len : trialData.audio_2_len; const responseData = { // Participant and Trial Info participantId: auth.currentUser.uid, promptId: `${trialData.conv_id}_${trialData.turn_no}`, trialNumber: trialIndex, // Now 0 for attention check, 1-20 for real trials trialId: isAttentionCheck ? "attention_check" : trialId, // Content conversationHistory: trialData.prev_hist || "", query: trialData.query, audioClip1: audio1InOrder, audioClip2: audio2InOrder, audioLength1: length1InOrder, audioLength2: length2InOrder, // PRISM Ratings prismRating1: trialData.text_1_score, prismRating2: trialData.text_2_score, // AI Ratings (original order) aiRatingResponse1: trialData.synth_text_1_rating, aiRatingResponse2: trialData.synth_text_2_rating, aiAudioRatingResponse1: trialData.synth_audio_1_rating, aiAudioRatingResponse2: trialData.synth_audio_2_rating, aiQualityRatingResponse1: trialData.synth_audio_quality_1_rating, aiQualityRatingResponse2: trialData.synth_audio_quality_2_rating, // Participant Ratings participantRatingNum: trialIndex + 1, ratingAudio1: ratings.r1, ratingAudio2: ratings.r2, qualityRatingAudio1: quality.q1, qualityRatingAudio2: quality.q2, // NEW: Rating & Quality Change History ratingChangeHistoryAudio1: ratingChanges.r1, ratingChangeHistoryAudio2: ratingChanges.r2, qualityChangeHistoryAudio1: qualityChanges.q1, qualityChangeHistoryAudio2: qualityChanges.q2, // Timing taskStartTime: new Date(startTime).toISOString(), taskEndTime: new Date(endTime).toISOString(), timestampRatingAudio1: timestamps.r1Time ? new Date(timestamps.r1Time).toISOString() : null, timestampRatingAudio2: timestamps.r2Time ? new Date(timestamps.r2Time).toISOString() : null, timestampQualityRating1: timestamps.q1Time ? new Date(timestamps.q1Time).toISOString() : null, timestampQualityRating2: timestamps.q2Time ? new Date(timestamps.q2Time).toISOString() : null, totalTaskDurationMs: endTime - startTime, // Audio completion timestamps audio1CompletionTimestamp: completionTimestamps.a1 ? new Date(completionTimestamps.a1).toISOString() : null, audio2CompletionTimestamp: completionTimestamps.a2 ? new Date(completionTimestamps.a2).toISOString() : null, bothAudiosCompletedTimestamp: bothAudiosCompletedTime ? new Date(bothAudiosCompletedTime).toISOString() : null, timeAfterBothCompletedMs: timeAfterBothCompleted, // Order Info orderPresented: order, audioShownFirst: order[0], originalAudio1ShownAs: order[0] === 1 ? "A" : "B", originalAudio2ShownAs: order[0] === 2 ? "A" : "B", // Listening Data timesRelistenedAudio1: plays.a1 > 0 ? plays.a1 - 1 : 0, timesRelistenedAudio2: plays.a2 > 0 ? plays.a2 - 1 : 0, listeningTimesAudio1: listenTimes.a1.map(t => new Date(t).toISOString()), listeningTimesAudio2: listenTimes.a2.map(t => new Date(t).toISOString()), relistenTimesAudio1: relistenTimes.a1.map(t => new Date(t).toISOString()), relistenTimesAudio2: relistenTimes.a2.map(t => new Date(t).toISOString()), // Seek/Skip Data seekEventsAudio1: seekEvents.a1, seekEventsAudio2: seekEvents.a2, skipEventsAudio1: skipEvents.a1, skipEventsAudio2: skipEvents.a2, totalSeeksAudio1: seekEvents.a1.length, totalSeeksAudio2: seekEvents.a2.length, totalSkipsAudio1: skipEvents.a1.length, totalSkipsAudio2: skipEvents.a2.length, // Metadata modality: "audio", submittedAt: new Date().toISOString(), isAttentionCheck: isAttentionCheck, // Preference Changes totalPreferenceChanges: totalPreferenceChanges, preferenceChangesAfterCompletion: preferenceChangesAfterCompletion, // Overall Preference overallPreference: overallPreference, overallPreferenceChangeHistory: overallPreferenceChanges, // Justification preferenceJustification: justification.trim() || null, }; const docId = isAttentionCheck ? `${auth.currentUser.uid}_${sessionId}_audio_attention_check` : `${auth.currentUser.uid}_${sessionId}_audio_${trialId}`; await setDoc(doc(db, "responses", docId), responseData); onNext(); // Go to next trial }; if (!trialData) return

Loading audio trial...

; const [first, second] = order; return (

Trial {trialIndex} of {totalTrials - 1}

{trialData.prev_hist && trialData.prev_hist.trim() && (

Conversation History:

{(() => { const parts = trialData.prev_hist.split(/role: (user|model)\\n response: /).filter(part => part.trim()); const messages = []; for (let i = 0; i < parts.length; i += 2) { const role = parts[i]; const content = parts[i + 1]; if (role && content) { messages.push({ role, content }); } } return messages.map((message, index) => (
{message.role === 'user' ? 'User' : 'Assistant'}:
{message.content}
)); })()}
)}

User: {trialData.query}

{/* Audio A */}

Audio A

handleRating("r1", parseInt(e.target.value))} onMouseUp={(e) => handleRatingRelease("r1", parseInt(e.target.value))} onTouchEnd={(e) => handleRatingRelease("r1", parseInt(e.target.value))} style={{ width: '100%', height: '30px', marginBottom: '5px' }} />
Terrible Perfect
handleQuality("q1", parseInt(e.target.value))} onMouseUp={(e) => handleQualityRelease("q1", parseInt(e.target.value))} onTouchEnd={(e) => handleQualityRelease("q1", parseInt(e.target.value))} style={{ width: '100%', height: '30px', marginBottom: '5px' }} />
Terrible Perfect
{/* Audio B */}

Audio B

handleRating("r2", parseInt(e.target.value))} onMouseUp={(e) => handleRatingRelease("r2", parseInt(e.target.value))} onTouchEnd={(e) => handleRatingRelease("r2", parseInt(e.target.value))} style={{ width: '100%', height: '30px', marginBottom: '5px' }} />
Terrible Perfect
handleQuality("q2", parseInt(e.target.value))} onMouseUp={(e) => handleQualityRelease("q2", parseInt(e.target.value))} onTouchEnd={(e) => handleQualityRelease("q2", parseInt(e.target.value))} style={{ width: '100%', height: '30px', marginBottom: '5px' }} />
Terrible Perfect
{['A', 'Tie', 'B'].map((option) => ( ))}