Spaces:
Sleeping
Sleeping
Download frontend/src/components/CallPanel.tsx from vion-training/Vion: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/spaces/vion-training/Vion/resolve/main/frontend/src/components/CallPanel.tsx
- Command line
-
hf download hf://spaces/vion-training/Vion/frontend/src/components/CallPanel.tsx
-
curl -L -o CallPanel.tsx https://huggingface.co/spaces/vion-training/Vion/resolve/main/frontend/src/components/CallPanel.tsx
12.2 kB
| 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<StartSessionResponse | null>(null); | |
| const [busy, setBusy] = useState(false); | |
| const [scoring, setScoring] = useState(false); | |
| const [muted, setMuted] = useState(false); | |
| const [error, setError] = useState<string | null>(null); | |
| const [warning, setWarning] = useState<string | null>(null); | |
| const [evaluation, setEvaluation] = useState<Evaluation | null>(null); | |
| // Live call timer: ticks once the call is connected, shown on the board. | |
| const [elapsed, setElapsed] = useState(0); | |
| const startedAtRef = useRef<number | null>(null); | |
| const wsRef = useRef<WebSocket | null>(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<TranscriptTurn[]>([]); | |
| // Mirrors `session` so the SDK callbacks (onDisconnect) read the current value. | |
| const sessionRef = useRef<StartSessionResponse | null>(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 ( | |
| <div className="callpanel"> | |
| <div className="status-row"> | |
| <span className={`dot ${live ? "on" : "off"}`} /> | |
| <span className="status-text"> | |
| {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")} | |
| </span> | |
| {session && ( | |
| <span | |
| className="call-timer" | |
| role="timer" | |
| aria-label={t("call.elapsed", { time: fmtElapsed(elapsed) })} | |
| > | |
| {fmtElapsed(elapsed)} | |
| </span> | |
| )} | |
| </div> | |
| <div className="controls"> | |
| {!session ? ( | |
| <button className="primary" disabled={busy} onClick={handleStart}> | |
| {busy ? t("call.starting") : t("call.start")} | |
| </button> | |
| ) : ( | |
| <> | |
| <button onClick={toggleMute} disabled={!live}> | |
| {muted ? t("call.unmute") : t("call.mute")} | |
| </button> | |
| <button className="danger" disabled={busy} onClick={handleEnd}> | |
| {t("call.end")} | |
| </button> | |
| </> | |
| )} | |
| </div> | |
| {!session && !evaluation && ( | |
| <p className="lang-note"> | |
| {t("call.langNote", { lang: t(`lang.${language}`) })} | |
| </p> | |
| )} | |
| {warning && <p className="warning">{warning}</p>} | |
| {error && <p className="error">{error}</p>} | |
| {session && ( | |
| <p className="meta"> | |
| {t("call.session", { | |
| id: session.session_id.slice(0, 8), | |
| voice: `${session.voice.voice_id.slice(0, 8)}…`, | |
| })} | |
| </p> | |
| )} | |
| {evaluation && ( | |
| <CallResult | |
| evaluation={evaluation} | |
| onClose={() => setEvaluation(null)} | |
| onRetry={() => { | |
| setEvaluation(null); | |
| void handleStart(); | |
| }} | |
| /> | |
| )} | |
| </div> | |
| ); | |
| } | |
| // 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 ( | |
| <div className="call-result"> | |
| <div className="result-header"> | |
| <h3>{t("results.heading")}</h3> | |
| {scored && ( | |
| <span className={`badge ${passed ? "pass" : "fail"}`}> | |
| {passed ? t("results.passed") : t("results.notPassed")} | |
| </span> | |
| )} | |
| </div> | |
| {scored && ( | |
| <div className="score"> | |
| <span className="score-num">{score}</span> | |
| <span className="score-den">/ 100</span> | |
| </div> | |
| )} | |
| {summary && ( | |
| <p className="result-summary">{summary}</p> | |
| )} | |
| {good_points.length > 0 && ( | |
| <div className="result-section"> | |
| <h4>{t("results.goodPoints")}</h4> | |
| <ul> | |
| {good_points.map((g, i) => ( | |
| <li key={i}>{g}</li> | |
| ))} | |
| </ul> | |
| </div> | |
| )} | |
| {improvements.length > 0 && ( | |
| <div className="result-section"> | |
| <h4>{t("results.improvements")}</h4> | |
| <ul> | |
| {improvements.map((g, i) => ( | |
| <li key={i}>{g}</li> | |
| ))} | |
| </ul> | |
| </div> | |
| )} | |
| {scored && !saved && ( | |
| <p className="warning">{t("results.notSaved")}</p> | |
| )} | |
| <div className="result-actions"> | |
| <button className="retry" onClick={onRetry}> | |
| {t("results.retry")} | |
| </button> | |
| <button className="close" onClick={onClose}> | |
| {t("results.close")} | |
| </button> | |
| </div> | |
| </div> | |
| ); | |
| } | |