modern-winter-66316
12/02/2025, 6:46 PMtall-airline-16756
12/02/2025, 6:46 PMtall-airline-16756
12/02/2025, 6:46 PMmodern-winter-66316
12/02/2025, 6:46 PMtall-airline-16756
12/02/2025, 6:47 PMvoiceProvider, voice, startBtn, status, controls, muteBtn, endBtn? Also confirm the select options' values match the keys in voiceOptions (e.g., livekit, openai_realtime, gemini_realtime).
A couple of quick checks you can run now:
• Open the browser console and paste the full error text here.
• Add a safety check before using voiceOptions[provider], e.g.:
const opts = voiceOptions[provider];
if (!opts) { console.error('Unknown provider', provider); return; }
• Ensure your server /api/connect returns JSON with token and url.
Send the error text and the HTML snippet for your selects if you can — I’ll point to the exact fix.modern-winter-66316
12/02/2025, 6:53 PMError: LiveKitClient is not defined
This error occurs when the frontend JavaScript (app.js) tries to use the LiveKit client library before it has finished loading.
### Root Cause
Race Condition: The LiveKit client library is loaded asynchronously from a CDN, but app.js was executing before the library finished loading and exposing its global variables.
### Technical Details
1. Script Loading Order:
- index.html loads LiveKit from CDN: https://cdn.jsdelivr.net/npm/livekit-client@1.15.0/dist/livekit-client.umd.min.js
- app.js was executing immediately after DOM ready, potentially before LiveKit loaded
2. Global Variable Names:
- The UMD build may expose LiveKit as:
- window.LiveKit (uppercase K)
- window.LivekitClient (lowercase k)
- window.livekit (all lowercase)
- Our code was only checking for window.LiveKit
3. Timing Issues:
- Network latency can delay script loading
- Browser parsing/execution order is not guaranteed
- No explicit wait mechanism for library availability
### Fixes Applied
#### Fix 1: Initial Loading Detection
- Added polling mechanism to check for LiveKit availability
- Dispatched livekit-ready event when library loads
- Wrapped app initialization in IIFE that waits for both DOM and LiveKit
#### Fix 2: Comprehensive Variable Detection
- Check for all possible global variable names:
- window.LiveKit
- window.LiveKitClient
- window.LivekitClient
- window.livekit
- Set up aliases for compatibility
- Added better error logging to identify which variable is found
#### Fix 3: Enhanced Error Handling
- Added onerror handler to script tag
- Added livekit-failed event for timeout scenarios
- Console logging to help debug loading issues
- Fallback timeout (5 seconds) with clear error messages
### Current Status
✅ Fixed and Deployed - The latest version includes:
- Comprehensive variable name detection
- Better error logging
- Multiple fallback mechanisms
- Clear user-facing error messages
### How to Verify the Fix
1. Open Browser Console (F12)
2. Look for these log messages:
- "Found LiveKit (uppercase K)" or similar
- "LiveKit client loaded successfully, aliases set"
- "LiveKit detected, initializing app..."
- "Connecting to LiveKit room..."
3. If error persists, check console for:
- "LiveKit failed to load after X attempts"
- "Available window properties:" (shows what LiveKit-related variables exist)
- Any network errors loading the CDN script
### Debugging Steps
If the error still occurs:
1. Check Network Tab:
- Verify livekit-client.umd.min.js loads successfully (200 status)
- Check for CORS or network errors
2. Check Console:
- Look for the detection logs mentioned above
- Check if any JavaScript errors occur before LiveKit loads
3. Try Alternative CDN:
html
_<!-- Option 1: Current -->_
<script src="https://cdn.jsdelivr.net/npm/livekit-client@1.15.0/dist/livekit-client.umd.min.js"></script>
_<!-- Option 2: Unpkg -->_
<script src="https://unpkg.com/livekit-client@1.15.0/dist/livekit-client.umd.min.js"></script>
_<!-- Option 3: ESM import (if supported) -->_
<script type="module">
import { Room } from 'https://cdn.jsdelivr.net/npm/livekit-client@1.15.0/dist/livekit-client.esm.min.js';
window.LiveKit = { Room };
</script>
4. Check Browser Compatibility:
- LiveKit requires modern browser features
- Test in Chrome, Firefox, Safari, Edge
- Check for any browser console warnings
### Related Files
- index.html - Script loading and detection logic
- app.js - App initialization and LiveKit usage
- api/connect.js - Backend API for room creation
### Next Steps if Issue Persists
1. Verify CDN Availability: Test if jsdelivr CDN is accessible
2. Check Browser Extensions: Some ad blockers may interfere
3. Try Local Build: Bundle LiveKit client locally instead of CDN
4. Update Library Version: Try latest version of livekit-client
5. Check Vercel Deployment: Verify files are deployed correctly
### Error Logs to Collect
If reporting this issue, please provide:
1. Browser console logs (all messages)
2. Network tab showing LiveKit script loading
3. Browser name and version
4. Any browser extensions installed
5. Screenshot of the error messagetall-airline-16756
12/02/2025, 6:54 PMlivekit-ready event and the 5s timeout are good; they prevent app code from running before the library exists.
• Checking all likely globals and creating aliases (e.g., set window.LiveKitClient = window.LiveKitClient || window.LiveKit || window.livekit) will avoid mismatches across UMD builds.
• Adding onerror on the script tag and emitting livekit-failed with clear console messages gives actionable diagnostics—good for debugging CDN/network issues.
Optional improvement (recommended):
• Prefer using the script tag’s load event instead of polling when possible:
a. Create the script element dynamically.
b. Attach script.onload to dispatch livekit-ready.
c. Attach script.onerror to dispatch livekit-failed.
This avoids repeated checks and is reliable across browsers.
Verification checklist to confirm fix is complete:
• Browser console shows one of your success logs (e.g., "LiveKit client loaded successfully, aliases set").
• No "LiveKitClient is not defined" errors in console.
• Network tab shows the CDN script loaded (200).
• App initializes only after livekit-ready.
If you’d like, paste your updated index.html script-loading snippet and I’ll confirm it’s correct or suggest the exact onload/onerror code to use.modern-winter-66316
12/02/2025, 7:02 PMtall-airline-16756
12/02/2025, 7:02 PMlivekit-ready and livekit-failed gives clear signals for app initialization and diagnostics.
Two small improvements 1) Use a named custom event with detail for easier debugging:
window.dispatchEvent(new CustomEvent('livekit-ready', { detail: { alias: 'LiveKitGlobal' } }));
2) In your available-properties log, avoid scanning the entire window (can be noisy). Limit to likely names:
console.log('Available livekit globals:', ['LiveKit','LiveKitClient','LivekitClient','livekit'].map(n => ({name:n, defined: !!window[n]})));
Quick sanity checklist to confirm the fix
• Console shows one of the success logs (e.g., "LiveKit client loaded successfully, aliases set").
• No "LiveKitClient is not defined" errors.
• Network tab shows the CDN script loaded (200).
• app.js listens for livekit-ready before using LiveKit, e.g.:
window.addEventListener('livekit-ready', () => { /* initialize app */ });
If you want, paste your app.js init block and I’ll confirm it correctly waits for livekit-ready and DOM readiness.modern-winter-66316
12/02/2025, 7:07 PMAPI error: ${response.status} - ${errorText});
}
const data = await response.json();
if (data.error) {
throw new Error(data.error);
}
const { token, url } = data;
// Get LiveKit client - should already be set in initApp
const LiveKit = window.LiveKit || window.LiveKitClient;
if (!LiveKit) {
throw new Error("LiveKit client library not loaded. Please refresh the page.");
}
console.log('Connecting to LiveKit room...');
room = new LiveKit.Room();
await room.connect(url, token);
status.textContent = "Connected! Starting lesson...";
controls.style.display = "block";
await room.localParticipant.setMicrophoneEnabled(true);
room.on(LiveKit.RoomEvent.TrackSubscribed, (track) => {
if (track.kind === LiveKit.Track.Kind.Audio) {
const audioElement = track.attach();
document.body.appendChild(audioElement);
}
});
room.on(LiveKit.RoomEvent.Disconnected, () => {
status.textContent = "Call ended";
controls.style.display = "none";
startBtn.disabled = false;
});
} catch (error) {
status.textContent = `Error: ${error.message}`;
startBtn.disabled = false;
}
});
muteBtn.addEventListener("click", async () => {
if (room) {
isMuted = !isMuted;
await room.localParticipant.setMicrophoneEnabled(!isMuted);
muteBtn.textContent = isMuted ? "🔊 Unmute" : "🔇 Mute";
}
});
endBtn.addEventListener("click", async () => {
if (room) {
await room.disconnect();
}
});
// Initialize defaults
voiceProvider.dispatchEvent(new Event("change"));
}
// Wait for both DOM and LiveKit to be ready
function tryInit() {
const hasLiveKit = typeof window.LiveKit !== 'undefined' ||
typeof window.LiveKitClient !== 'undefined' ||
typeof window.LivekitClient !== 'undefined' ||
typeof window.livekit !== 'undefined';
if (hasLiveKit) {
console.log('LiveKit detected, initializing app...');
initApp();
return true;
}
return false;
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', function() {
if (!tryInit()) {
// Listen for livekit-ready event before using LiveKit
window.addEventListener('livekit-ready', function(event) {
console.log('Received livekit-ready event', event.detail);
initApp();
});
window.addEventListener('livekit-failed', function(event) {
console.error('Received livekit-failed event', event.detail);
const statusEl = document.getElementById('status');
if (statusEl) {
const reason = event.detail?.reason || 'unknown';
statusEl.textContent = `Error: LiveKit client library failed to load (${reason}). Please check console and refresh the page.`;
}
});
// Fallback timeout
setTimeout(function() {
if (!tryInit()) {
console.error('LiveKit failed to load after timeout');
const statusEl = document.getElementById('status');
if (statusEl) {
statusEl.textContent = 'Error: LiveKit client library failed to load. Please refresh the page.';
}
}
}, 5000);
}
});
} else {
// DOM already loaded, just wait for LiveKit
if (!tryInit()) {
// Listen for livekit-ready event before using LiveKit
window.addEventListener('livekit-ready', function(event) {
console.log('Received livekit-ready event', event.detail);
initApp();
});
window.addEventListener('livekit-failed', function(event) {
console.error('Received livekit-failed event', event.detail);
const statusEl = document.getElementById('status');
if (statusEl) {
const reason = event.detail?.reason || 'unknown';
statusEl.textContent = `Error: LiveKit client library failed to load (${reason}). Please check console and refresh the page.`;
}
});
// Fallback timeout
setTimeout(function() {
if (!tryInit()) {
console.error('LiveKit failed to load after timeout');
const statusEl = document.getElementById('status');
if (statusEl) {
statusEl.textContent = 'Error: LiveKit client library failed to load. Please refresh the page.';
}
}
}, 5000);
}
}
})();
Key features:
• IIFE wrapper to avoid global scope pollution
• Waits for LiveKit library to load before initializing
• Listens for livekit-ready and livekit-failed events
• Handles multiple possible global variable names
• Error handling with user-friendly messages
• Fallback timeout (5 seconds) if LiveKit doesn't load
• Room connection, mute/unmute, and disconnect functionality
Ready for review.tall-airline-16756
12/02/2025, 7:07 PM_voice_ but reference voice inside the loop. Change:
voiceOptions[provider].forEach((voice) => {
const option = document.createElement("option");
option.value = voice.value;
option.textContent = voice.label;
voiceSelect.appendChild(option);
});
1. Window-property logging callback typo: you wrote _k_ => k.toLowerCase().includes('live') — use the correct parameter name:
Object.keys(window).filter(k => k.toLowerCase().includes('live'))
1. Event handler references: inside your livekit-ready and livekit-failed listeners you log or read event.detail but the handler parameter is _event_ and you then use event. Replace uses of event with the actual parameter name, e.g.:
window.addEventListener('livekit-ready', function(event) {
console.log('Received livekit-ready event', event.detail);
initApp();
});
Optional improvements (recommended)
• Use CustomEvent with a detail payload when dispatching readiness/failure so listeners can log reason/version:
window.dispatchEvent(new CustomEvent('livekit-ready', { detail: { alias: 'LiveKitGlobal' } }));
• Prefer a single centralized initialization flow: call initApp() only from one place (either synchronous tryInit() path or the livekit-ready handler) to avoid double-inits. For example, in tryInit() return early if already initialized by setting a flag window.__appInitialized = true;.
Sanity checklist before deploying
• Console shows a success message (e.g., "LiveKit client loaded successfully, aliases set").
• No "LiveKitClient is not defined" errors.
• Network tab shows the LiveKit script loaded (200).
• App initializes once and controls appear as expected.
If you want, paste the updated snippets for the three fixes and I’ll quickly verify them or produce the corrected full block you can drop into your app.