import { useConversation } from "@elevenlabs/react"; import { useEffect, useRef, useState } from "react"; import { controlWsUrl, endSession, finishSession, startSession } from "../api"; import { useI18n } from "../i18n"; import type { Evaluation, StartSessionResponse, TranscriptTurn } from "../types"; interface Props { scenarioId: string; } type VoiceState = "idle" | "listening" | "talking"; // Seconds -> "m:ss" (e.g. 75 -> "1:15"). Used by the live call timer. function fmtElapsed(totalSeconds: number): string { const m = Math.floor(totalSeconds / 60); const s = totalSeconds % 60; return `${m}:${String(s).padStart(2, "0")}`; } export default function CallPanel({ scenarioId }: Props) { const { t, language } = useI18n(); const [session, setSession] = useState(null); const [busy, setBusy] = useState(false); const [scoring, setScoring] = useState(false); const [muted, setMuted] = useState(false); const [error, setError] = useState(null); const [warning, setWarning] = useState(null); const [evaluation, setEvaluation] = useState(null); // Live call timer: ticks once the call is connected, shown on the board. const [elapsed, setElapsed] = useState(0); const startedAtRef = useRef(null); const wsRef = useRef(null); // Captured conversation turns, accumulated live from the SDK and sent on End. // A ref (not state) so pushing a turn never triggers a re-render mid-call. const transcriptRef = useRef([]); // Mirrors `session` so the SDK callbacks (onDisconnect) read the current value. const sessionRef = useRef(null); // Ensures the finish/score flow runs at most once per call, no matter who // triggers it (user clicks End, the agent hangs up, or the socket drops). const finishingRef = useRef(false); // ElevenLabs Agents conversation. The SDK owns mic capture, STT, turn-taking, // barge-in and TTS playback — we only react to its lifecycle/mode + messages. const conversation = useConversation({ onConnect: () => sendStatus("listening"), onDisconnect: () => { sendStatus("idle"); // The agent ended the call (end_call) or the connection dropped on its // own. If a real exchange happened and we haven't already ended it, // auto-score it so the call doesn't appear stuck. if ( !finishingRef.current && sessionRef.current && transcriptRef.current.length > 0 ) { void finishAndScore(); } }, onError: (e: unknown) => setError(String(e)), onMessage: (props: { message: string; source: string }) => { const text = props?.message?.trim(); if (!text) return; // source "user" = the advisor speaking; anything else = the AI prospect. transcriptRef.current.push({ role: props.source === "user" ? "user" : "agent", text, }); }, }); // Derive the UI voice state from the SDK and mirror it to the control WS. useEffect(() => { if (conversation.status !== "connected") return; sendStatus(conversation.isSpeaking ? "talking" : "listening"); // eslint-disable-next-line react-hooks/exhaustive-deps }, [conversation.isSpeaking, conversation.status]); function sendStatus(state: VoiceState) { wsRef.current?.send(JSON.stringify({ type: "status", state })); } // Keep the ref in sync so SDK callbacks see the current session. useEffect(() => { sessionRef.current = session; }, [session]); // Drive the live call timer. Starts counting the moment the call connects and // ticks every second until the call ends (or this panel unmounts). const connected = !!session && conversation.status === "connected"; useEffect(() => { if (!connected) return; if (startedAtRef.current == null) startedAtRef.current = Date.now(); const tick = () => setElapsed(Math.floor((Date.now() - (startedAtRef.current ?? Date.now())) / 1000)); tick(); const id = window.setInterval(tick, 1000); return () => window.clearInterval(id); }, [connected]); // Reset everything if the advisor picks a different scenario mid-setup. useEffect(() => { return () => { void hardStop(); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [scenarioId]); async function handleStart() { setError(null); setWarning(null); setEvaluation(null); transcriptRef.current = []; finishingRef.current = false; startedAtRef.current = null; setElapsed(0); setBusy(true); try { // Use the currently selected language so the AI prospect speaks it. const resp = await startSession(scenarioId, language); setSession(resp); sessionRef.current = resp; // immediately, so an early disconnect sees it // Open the control WebSocket (status/mute/end orchestration). const ws = new WebSocket(controlWsUrl(resp.control_ws)); ws.onopen = () => ws.send(JSON.stringify({ type: "hello" })); ws.onerror = () => setError("Control socket error."); wsRef.current = ws; if (resp.signed_url) { // Connect the browser straight to the ElevenLabs agent (key stays // server-side; we only ever received a short-lived signed URL). await conversation.startSession({ signedUrl: resp.signed_url }); } else { // Graceful degradation: no keys yet -> no live call, clear message. setWarning(resp.warning ?? t("call.noKeys")); } } catch (e) { setError(String(e)); } finally { setBusy(false); } } function toggleMute() { const next = !muted; setMuted(next); // Optional SDK mic-mute if available in this version; cast to stay portable. (conversation as unknown as { setMicMuted?: (m: boolean) => void }).setMicMuted?.( next ); wsRef.current?.send(JSON.stringify({ type: "mute", muted: next })); } // Finish the call: tear down the control socket, score + save it, show the // scorecard. Runs once per call (guarded) whether triggered by the user, the // agent hanging up, or a dropped connection. async function finishAndScore() { const s = sessionRef.current; if (!s || finishingRef.current) return; finishingRef.current = true; // Close the control socket WITHOUT the "end" message — /finish does the // server-side teardown (and would 404 if the session were already deleted). wsRef.current?.close(); wsRef.current = null; try { if (s.signed_url) { setScoring(true); const result = await finishSession(s.session_id, transcriptRef.current); setEvaluation(result); } else { // No live call happened (missing keys) — just discard the session. await endSession(s.session_id).catch(() => {}); } } catch (e) { setError(String(e)); await endSession(s.session_id).catch(() => {}); } finally { setScoring(false); setSession(null); setMuted(false); setBusy(false); } } // Abandon a call WITHOUT scoring (used on unmount / scenario switch). async function hardStop() { finishingRef.current = true; // suppress the auto-finish on intentional teardown try { await conversation.endSession(); } catch { /* ignore */ } const s = sessionRef.current; if (s) { wsRef.current?.send(JSON.stringify({ type: "end" })); await endSession(s.session_id).catch(() => {}); } wsRef.current?.close(); wsRef.current = null; } // User clicked "End": stop the audio, then score + save via finishAndScore. async function handleEnd() { if (!sessionRef.current) return; setBusy(true); try { await conversation.endSession(); } catch { /* ignore */ } await finishAndScore(); } const live = !!session && conversation.status === "connected"; const voiceState: VoiceState = !live ? "idle" : conversation.isSpeaking ? "talking" : "listening"; return (
{scoring ? t("call.scoring") : !session ? t("call.notConnected") : conversation.status === "connected" ? voiceState === "talking" ? t("call.talking") : muted ? t("call.listeningMuted") : t("call.listening") : conversation.status === "connecting" ? t("call.connecting") : t("call.ready")} {session && ( {fmtElapsed(elapsed)} )}
{!session ? ( ) : ( <> )}
{!session && !evaluation && (

{t("call.langNote", { lang: t(`lang.${language}`) })}

)} {warning &&

{warning}

} {error &&

{error}

} {session && (

{t("call.session", { id: session.session_id.slice(0, 8), voice: `${session.voice.voice_id.slice(0, 8)}…`, })}

)} {evaluation && ( setEvaluation(null)} onRetry={() => { setEvaluation(null); void handleStart(); }} /> )}
); } // Post-call scorecard: score, pass/fail, summary, strengths, improvements. function CallResult({ evaluation, onClose, onRetry, }: { evaluation: Evaluation; onClose: () => void; onRetry: () => void; }) { const { t } = useI18n(); const { score, passed, summary, good_points, improvements, saved } = evaluation; const scored = score !== null && passed !== null; return (

{t("results.heading")}

{scored && ( {passed ? t("results.passed") : t("results.notPassed")} )}
{scored && (
{score} / 100
)} {summary && (

{summary}

)} {good_points.length > 0 && (

{t("results.goodPoints")}

    {good_points.map((g, i) => (
  • {g}
  • ))}
)} {improvements.length > 0 && (

{t("results.improvements")}

    {improvements.map((g, i) => (
  • {g}
  • ))}
)} {scored && !saved && (

{t("results.notSaved")}

)}
); }