import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
Mic,
MicOff,
PhoneOff,
Settings,
Volume2,
X,
Check,
KeyRound,
RotateCcw,
AlertCircle,
Sparkles,
} from 'lucide-react';
/* ============================================================================
PART 1: CONFIG, GEMINI VOICE & CHAT ENGINE, AND ROBOT T.KOI AVATAR
============================================================================ */
const STORAGE_KEY = 'robot_tkoi_live_voice_settings_v3';
const DEFAULT_SETTINGS = {
robotName: 'Robot T.Koi',
badgeName: 'T.KOI',
apiKey: '',
useGeminiVoice: true,
voiceName: 'Puck',
personaNote:
'You are the cheerful, silly, encouraging robot version of Teacher Koi at KidsDuo! You LOVE Carbonara, Pizza, and saying "BABUBABU!" when excited. Chat with students in simple, fun, kid-friendly English.',
};
const MAGIC_BUTTONS = [
{
id: 'carbonara',
label: 'CARBONARA!',
emoji: 'ð',
gradient: 'from-amber-400 via-orange-500 to-orange-500',
shadow: 'shadow-[0_6px_0_#b45309]',
activeShadow: 'active:shadow-[0_2px_0_#b45309]',
lines: [
'CARBONARA! Oh yeah! Creamy, cheesy, yummy carbonara is the BEST pasta in the whole universe!',
'Did someone say CARBONARA?! My robot tummy is rumbling! Beep boop, pass me a giant fork!',
'CARBONARA power activated! Eat your carbonara and become a superstar today!',
],
},
{
id: 'pizza',
label: 'PIZZA!!!',
emoji: 'ð',
gradient: 'from-rose-500 via-red-500 to-red-600',
shadow: 'shadow-[0_6px_0_#991b1b]',
activeShadow: 'active:shadow-[0_2px_0_#991b1b]',
lines: [
'PIZZA!!! Extra cheese, extra yummy! Who wants a giant pizza party with Robot T.Koi?!',
'PIZZA!!! Beep boop! Even robots love hot, cheesy pizza! What is your favorite topping?',
'WHOA! PIZZA time! One slice for you, and ten slices for Robot T.Koi! Haha, just kidding!',
],
},
{
id: 'babubabu',
label: 'BABUBABU!',
emoji: 'ðĪŠ',
gradient: 'from-fuchsia-500 via-purple-500 to-purple-600',
shadow: 'shadow-[0_6px_0_#6b21a8]',
activeShadow: 'active:shadow-[0_2px_0_#6b21a8]',
lines: [
'BABUBABU! Hahaha! Oh no, you pressed the silly button! Babubabu beep boop!',
'BABUBABU! My robot circuits are going super silly! Say babubabu with me! BABUBABU!',
'WOOHOO! BABUBABU! That is the secret magic giggle word of Teacher Koi!',
],
},
];
const TAP_HEAD_LINES = [
'Hehe! That tickles my antenna! Beep boop!',
'Boing! Hey superstars, watch the hair! Haha!',
'Whoa! You booped Robot T.Koi! Babubabu!',
'Beep boop! High five! Ready to chat?',
];
const VOICE_OPTIONS = [
{ name: 'Puck', label: 'Puck (Upbeat & Fun)' },
{ name: 'Fenrir', label: 'Fenrir (Excitable)' },
{ name: 'Zephyr', label: 'Zephyr (Bright)' },
{ name: 'Kore', label: 'Kore (Clear & Firm)' },
{ name: 'Aoede', label: 'Aoede (Breezy)' },
];
// Convert raw signed 16-bit PCM from Gemini TTS into a playable WAV Blob
function base64ToUint8Array(base64) {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
function pcm16ToWavBlob(pcmBytes, sampleRate = 24000) {
const numChannels = 1;
const bitsPerSample = 16;
const byteRate = (sampleRate * numChannels * bitsPerSample) / 8;
const blockAlign = (numChannels * bitsPerSample) / 8;
const dataSize = pcmBytes.byteLength;
const buffer = new ArrayBuffer(44 + dataSize);
const view = new DataView(buffer);
const writeStr = (offset, str) => {
for (let i = 0; i < str.length; i++) {
view.setUint8(offset + i, str.charCodeAt(i));
}
};
writeStr(0, 'RIFF');
view.setUint32(4, 36 + dataSize, true);
writeStr(8, 'WAVE');
writeStr(12, 'fmt ');
view.setUint32(16, 16, true);
view.setUint16(20, 1, true); // PCM
view.setUint16(22, numChannels, true);
view.setUint32(24, sampleRate, true);
view.setUint32(28, byteRate, true);
view.setUint16(32, blockAlign, true);
view.setUint16(34, bitsPerSample, true);
writeStr(36, 'data');
view.setUint32(40, dataSize, true);
new Uint8Array(buffer, 44).set(pcmBytes);
return new Blob([buffer], { type: 'audio/wav' });
}
async function fetchWithBackoff(url, options, retries = 2) {
let delay = 800;
for (let attempt = 0; attempt <= retries; attempt++) {
const res = await fetch(url, options);
if (res.ok || (res.status !== 429 && res.status < 500) || attempt === retries) {
return res;
}
await new Promise((r) => setTimeout(r, delay));
delay *= 2;
}
throw new Error('Request failed');
}
function buildSystemInstruction(settings) {
return `You are ${settings.robotName}, the friendly, playful robot version of Teacher Koi!
You are having a live voice conversation with young students just for fun.
Rules:
- Keep every reply short, warm, energetic, and easy to understand (1 to 3 short sentences).
- Speak naturally with NO markdown, NO bullet points, NO asterisks, and NO emojis.
- Your 3 famous magic words are: "CARBONARA!", "PIZZA!!!", and "BABUBABU!". If a student says any of them, get super excited and joke about them!
- Occasionally ask a fun follow-up question to keep the student talking in English.
${settings.personaNote ? `Extra Teacher Notes: ${settings.personaNote}` : ''}`;
}
function generateLocalFallbackReply(userText, settings) {
const t = userText.toLowerCase();
if (t.includes('carbonara')) return MAGIC_BUTTONS[0].lines[0];
if (t.includes('pizza')) return MAGIC_BUTTONS[1].lines[0];
if (t.includes('babu')) return MAGIC_BUTTONS[2].lines[0];
if (t.includes('hello') || t.includes('hi') || t.includes('hey')) {
return `Hello superstar! I am ${settings.robotName}! How are you feeling today?`;
}
if (t.includes('name') || t.includes('who are you')) {
return `I am ${settings.robotName}, the robot version of Teacher Koi! Do you like pizza or carbonara?`;
}
if (t.includes('bye') || t.includes('goodbye') || t.includes('see you')) {
return `Bye bye superstar! Keep smiling and remember... BABUBABU! See you next time!`;
}
if (t.includes('food') || t.includes('hungry') || t.includes('eat')) {
return `Ooh, now I am hungry too! I love carbonara and pizza! What is your favorite food?`;
}
if (t.includes('joke') || t.includes('funny')) {
return `Why did the robot eat pizza? Because it wanted a mega-byte! Hahaha! Babubabu!`;
}
const defaults = [
`Whoa, that is super cool! Tell Robot T.Koi more about that!`,
`Awesome job speaking English, superstar! What else did you do today?`,
`Beep boop! I love chatting with you! Do you like carbonara or pizza better?`,
];
return defaults[Math.floor(Math.random() * defaults.length)];
}
async function askGeminiText(userText, history, settings) {
const apiKey = (settings.apiKey || '').trim();
const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent?key=${encodeURIComponent(apiKey)}`;
try {
const contents = [
...history.slice(-8).map((turn) => ({
role: turn.role === 'robot' ? 'model' : 'user',
parts: [{ text: turn.text }],
})),
{ role: 'user', parts: [{ text: userText }] },
];
const res = await fetchWithBackoff(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
systemInstruction: { parts: [{ text: buildSystemInstruction(settings) }] },
contents,
generationConfig: { temperature: 0.9, maxOutputTokens: 150 },
}),
});
if (!res.ok) throw new Error('Gemini text error');
const data = await res.json();
const reply = data?.candidates?.[0]?.content?.parts?.[0]?.text?.trim();
if (!reply) throw new Error('Empty reply');
return reply.replace(/[*_#`]/g, '');
} catch {
return generateLocalFallbackReply(userText, settings);
}
}
async function fetchGeminiTTSAudioUrl(text, settings) {
if (!settings.useGeminiVoice) return null;
const apiKey = (settings.apiKey || '').trim();
const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-tts:generateContent?key=${encodeURIComponent(apiKey)}`;
try {
const res = await fetchWithBackoff(
url,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [{ parts: [{ text: `Say cheerfully and playfully like a fun teacher robot: ${text}` }] }],
generationConfig: {
responseModalities: ['AUDIO'],
speechConfig: {
voiceConfig: {
prebuiltVoiceConfig: { voiceName: settings.voiceName || 'Puck' },
},
},
},
model: 'gemini-2.5-flash-preview-tts',
}),
},
1
);
if (!res.ok) return null;
const data = await res.json();
const part = data?.candidates?.[0]?.content?.parts?.[0];
const audioData = part?.inlineData?.data;
const mimeType = part?.inlineData?.mimeType || '';
if (!audioData || !mimeType.startsWith('audio/')) return null;
const rateMatch = mimeType.match(/rate=(\d+)/);
const sampleRate = rateMatch ? parseInt(rateMatch[1], 10) : 24000;
const pcmBytes = base64ToUint8Array(audioData);
const wavBlob = pcm16ToWavBlob(pcmBytes, sampleRate);
return URL.createObjectURL(wavBlob);
} catch {
return null;
}
}
function RobotTKoiCharacter({ status, isMuted, isHeadTapped, onTapHead, badgeName, inputLevel }) {
const [isBlinking, setIsBlinking] = useState(false);
useEffect(() => {
let t1;
let t2;
const blinkLoop = () => {
t1 = window.setTimeout(() => {
setIsBlinking(true);
t2 = window.setTimeout(() => {
setIsBlinking(false);
blinkLoop();
}, 140);
}, 2500 + Math.random() * 2800);
};
blinkLoop();
return () => {
window.clearTimeout(t1);
window.clearTimeout(t2);
};
}, []);
const isSpeaking = status === 'speaking';
const isListening = status === 'listening' && !isMuted;
const isThinking = status === 'thinking';
return (
{/* Listening Halo */}
{isListening && (
)}
{/* Robot T.Koi SVG matching the KidsDuo Teacher Koi look */}
);
}
/* ============================================================================
PART 2: TEACHER API KEY SETTINGS MODAL & MAIN LIVE CONVERSATION APP
============================================================================ */
function TeacherSettingsModal({ isOpen, onClose, settings, onSave }) {
const [robotName, setRobotName] = useState(settings.robotName);
const [badgeName, setBadgeName] = useState(settings.badgeName);
const [apiKey, setApiKey] = useState(settings.apiKey || '');
const [useGeminiVoice, setUseGeminiVoice] = useState(settings.useGeminiVoice);
const [voiceName, setVoiceName] = useState(settings.voiceName || 'Puck');
const [personaNote, setPersonaNote] = useState(settings.personaNote);
useEffect(() => {
if (isOpen) {
setRobotName(settings.robotName);
setBadgeName(settings.badgeName);
setApiKey(settings.apiKey || '');
setUseGeminiVoice(settings.useGeminiVoice);
setVoiceName(settings.voiceName || 'Puck');
setPersonaNote(settings.personaNote);
}
}, [isOpen, settings]);
if (!isOpen) return null;
const handleSave = (e) => {
e.preventDefault();
onSave({
robotName: robotName.trim() || DEFAULT_SETTINGS.robotName,
badgeName: badgeName.trim() || DEFAULT_SETTINGS.badgeName,
apiKey: apiKey.trim(),
useGeminiVoice,
voiceName,
personaNote: personaNote.trim(),
});
onClose();
};
const handleReset = () => {
setRobotName(DEFAULT_SETTINGS.robotName);
setBadgeName(DEFAULT_SETTINGS.badgeName);
setApiKey('');
setUseGeminiVoice(true);
setVoiceName(DEFAULT_SETTINGS.voiceName);
setPersonaNote(DEFAULT_SETTINGS.personaNote);
};
return (
Teacher Settings
Gemini API Key & Robot Voice
);
}
export default function App() {
const [settings, setSettings] = useState(() => {
try {
const saved = localStorage.getItem(STORAGE_KEY);
return saved ? { ...DEFAULT_SETTINGS, ...JSON.parse(saved) } : DEFAULT_SETTINGS;
} catch {
return DEFAULT_SETTINGS;
}
});
const [status, setStatus] = useState('idle'); // idle | listening | thinking | speaking
const [isMuted, setIsMuted] = useState(false);
const [showSettings, setShowSettings] = useState(false);
const [robotSpeech, setRobotSpeech] = useState('Hello superstars! I am Robot T.Koi!');
const [studentSpeech, setStudentSpeech] = useState('');
const [errorMsg, setErrorMsg] = useState('');
const [isHeadTapped, setIsHeadTapped] = useState(false);
const [burstEmoji, setBurstEmoji] = useState('');
const [inputLevel, setInputLevel] = useState(0);
const liveRef = useRef(false);
const mutedRef = useRef(false);
const statusRef = useRef('idle');
const settingsRef = useRef(settings);
const historyRef = useRef([]);
const recognitionRef = useRef(null);
const audioElRef = useRef(null);
const audioUrlRef = useRef(null);
const micStreamRef = useRef(null);
const audioCtxRef = useRef(null);
const rafRef = useRef(null);
useEffect(() => {
settingsRef.current = settings;
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
} catch {
// Ignore storage errors
}
}, [settings]);
useEffect(() => {
mutedRef.current = isMuted;
}, [isMuted]);
useEffect(() => {
statusRef.current = status;
}, [status]);
const stopAudioPlayback = useCallback(() => {
if (audioElRef.current) {
audioElRef.current.pause();
audioElRef.current = null;
}
if (audioUrlRef.current) {
URL.revokeObjectURL(audioUrlRef.current);
audioUrlRef.current = null;
}
if (window.speechSynthesis) {
window.speechSynthesis.cancel();
}
}, []);
const stopMicMeter = useCallback(() => {
if (rafRef.current) cancelAnimationFrame(rafRef.current);
rafRef.current = null;
if (micStreamRef.current) {
micStreamRef.current.getTracks().forEach((t) => t.stop());
micStreamRef.current = null;
}
if (audioCtxRef.current) {
audioCtxRef.current.close().catch(() => {});
audioCtxRef.current = null;
}
setInputLevel(0);
}, []);
const startMicMeter = useCallback(async () => {
try {
if (!navigator.mediaDevices?.getUserMedia) return;
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
micStreamRef.current = stream;
const AudioCtx = window.AudioContext || window.webkitAudioContext;
const ctx = new AudioCtx();
audioCtxRef.current = ctx;
const analyser = ctx.createAnalyser();
analyser.fftSize = 256;
const source = ctx.createMediaStreamSource(stream);
source.connect(analyser);
const data = new Uint8Array(analyser.frequencyBinCount);
const tick = () => {
if (!liveRef.current) return;
analyser.getByteFrequencyData(data);
const avg = data.reduce((a, b) => a + b, 0) / data.length / 160;
setInputLevel(mutedRef.current ? 0 : Math.min(1, avg));
rafRef.current = requestAnimationFrame(tick);
};
tick();
} catch {
// Optional visual meter
}
}, []);
const stopRecognition = useCallback(() => {
if (recognitionRef.current) {
recognitionRef.current.onend = null;
try {
recognitionRef.current.abort();
} catch {
// Ignore
}
recognitionRef.current = null;
}
}, []);
const startRecognition = useCallback(() => {
if (!liveRef.current || mutedRef.current) return;
const SpeechRec = window.SpeechRecognition || window.webkitSpeechRecognition;
if (!SpeechRec) {
setErrorMsg('Live microphone works best in Chrome, Edge, or Safari.');
return;
}
stopRecognition();
try {
const rec = new SpeechRec();
rec.lang = 'en-US';
rec.interimResults = true;
rec.continuous = false;
rec.onstart = () => {
if (liveRef.current) setStatus('listening');
};
rec.onresult = (event) => {
let interim = '';
let finalText = '';
for (let i = event.resultIndex; i < event.results.length; i++) {
const piece = event.results[i][0].transcript;
if (event.results[i].isFinal) finalText += piece;
else interim += piece;
}
setStudentSpeech(interim || finalText);
if (finalText.trim()) {
rec.stop();
handleStudentMessage(finalText.trim());
}
};
rec.onerror = (e) => {
if (e.error === 'not-allowed') {
setErrorMsg('Please allow microphone access so Robot T.Koi can hear you!');
endConversation();
}
};
rec.onend = () => {
if (liveRef.current && !mutedRef.current && statusRef.current === 'listening') {
setTimeout(() => {
if (liveRef.current && !mutedRef.current && statusRef.current === 'listening') {
try {
rec.start();
} catch {
// Already started
}
}
}, 250);
}
};
recognitionRef.current = rec;
rec.start();
} catch {
// Ignore start race
}
}, [stopRecognition]);
const speakText = useCallback(
async (text, resumeListeningAfter = true) => {
stopAudioPlayback();
stopRecognition();
setRobotSpeech(text);
setStatus('speaking');
const finishSpeaking = () => {
if (liveRef.current && resumeListeningAfter && !mutedRef.current) {
setStatus('listening');
startRecognition();
} else if (!liveRef.current) {
setStatus('idle');
} else {
setStatus('listening');
}
};
// Try Gemini Real Voice TTS first if enabled
const ttsUrl = await fetchGeminiTTSAudioUrl(text, settingsRef.current);
if (ttsUrl) {
audioUrlRef.current = ttsUrl;
const audio = new Audio(ttsUrl);
audioElRef.current = audio;
audio.onended = finishSpeaking;
audio.onerror = finishSpeaking;
try {
await audio.play();
return;
} catch {
// Fall back to browser speechSynthesis
}
}
if (window.speechSynthesis) {
const utter = new SpeechSynthesisUtterance(text);
utter.lang = 'en-US';
utter.rate = 1.03;
utter.pitch = 1.12;
utter.onend = finishSpeaking;
utter.onerror = finishSpeaking;
window.speechSynthesis.speak(utter);
} else {
setTimeout(finishSpeaking, 1600);
}
},
[stopAudioPlayback, stopRecognition, startRecognition]
);
const handleStudentMessage = useCallback(
async (spokenText) => {
setStatus('thinking');
historyRef.current = [...historyRef.current.slice(-10), { role: 'student', text: spokenText }];
const reply = await askGeminiText(spokenText, historyRef.current, settingsRef.current);
historyRef.current = [...historyRef.current.slice(-10), { role: 'robot', text: reply }];
speakText(reply, true);
},
[speakText]
);
const startConversation = async () => {
setErrorMsg('');
setStudentSpeech('');
liveRef.current = true;
setIsMuted(false);
mutedRef.current = false;
await startMicMeter();
const greeting = `Hello superstars! I am ${settings.robotName}! Let's chat! What is your name?`;
historyRef.current = [{ role: 'robot', text: greeting }];
speakText(greeting, true);
};
const endConversation = useCallback(() => {
liveRef.current = false;
setStatus('idle');
setStudentSpeech('');
stopRecognition();
stopAudioPlayback();
stopMicMeter();
}, [stopRecognition, stopAudioPlayback, stopMicMeter]);
const toggleMute = () => {
const next = !isMuted;
setIsMuted(next);
mutedRef.current = next;
if (next) {
stopRecognition();
} else if (liveRef.current && statusRef.current !== 'speaking') {
startRecognition();
}
};
const triggerBurst = (emoji) => {
setBurstEmoji(emoji);
setTimeout(() => setBurstEmoji(''), 1100);
};
const handleTapHead = () => {
setIsHeadTapped(true);
triggerBurst('âĻ');
setTimeout(() => setIsHeadTapped(false), 650);
const line = TAP_HEAD_LINES[Math.floor(Math.random() * TAP_HEAD_LINES.length)];
speakText(line, liveRef.current);
};
const handleMagicButton = (btn) => {
triggerBurst(btn.emoji);
const line = btn.lines[Math.floor(Math.random() * btn.lines.length)];
historyRef.current = [...historyRef.current.slice(-10), { role: 'robot', text: line }];
speakText(line, liveRef.current);
};
useEffect(() => () => endConversation(), [endConversation]);
const isLive = status !== 'idle';
const statusPillText =
status === 'speaking'
? `${settings.robotName} is talking! ð`
: status === 'thinking'
? 'Thinking... ð'
: status === 'listening'
? isMuted
? 'Mic Muted ð'
: 'Listening to you! ðĪ'
: 'Ready with Real Voice! ðĪ';
return (
{/* Main Warm Classroom Card */}
{/* Top Row: Status Pill, Tap Head Hint, Settings Gear */}
{statusPillText}
ð Tap head!
{/* Floating Emoji Burst on Magic Button / Head Tap */}
{burstEmoji && (
{burstEmoji}
)}
{/* Robot T.Koi Stage */}
{/* Speech Bubble Card (Just like the screenshot!) */}
{robotSpeech}
{studentSpeech && (
ðĪ You said: “{studentSpeech}”
)}
{/* Error Alert */}
{errorMsg && (
)}
{/* Live Voice Conversation Controls */}
{!isLive ? (
) : (
<>
>
)}
{/* T.KOI MAGIC BUTTONS (Exact 3 chunky buttons from the screenshot!) */}
T.KOI MAGIC BUTTONS
{MAGIC_BUTTONS.map((btn) => (
))}
setShowSettings(false)}
settings={settings}
onSave={setSettings}
/>
);
}