# WebRTC Error Resolution Guide

**Date:** January 13, 2026  
**Issue:** "Failed to create transport: Internal Server Error"

---

## Root Cause

The error occurs when trying to connect to a translator stream but **no active translators are available**.

### What Happened
1. User tried to view WebRTC translation stream
2. Backend returned 500 Internal Server Error when creating consumer transport
3. This happens because there are no active translators currently translating

### Current Status
```bash
curl -s https://ministryprogs.tniglobal.org/webrtc/public/active-translators
# Returns: {"translators":[]}
```

---

## Solutions Implemented

### ✅ 1. Enhanced Error Handling
- Added pre-connection validation to check if translator is active
- Improved error messages to clearly indicate when no translators are available
- Added backend error response parsing for better debugging

### ✅ 2. Better User Feedback
Updated error message from:
```
"Failed to create transport: Internal Server Error"
```

To:
```
"No active translators found. Please ensure at least one translator has started their translation session from the Translation Studio app."
```

### ✅ 3. Validation Before Connection
Added check in `WebRTCConsumer.connectToTranslator()`:
```typescript
// Step 0: Verify translator is active
const translatorStatus = await WebRTCConsumer.checkTranslatorStatus(translatorId);
if (!translatorStatus) {
  throw new Error(`Translator ${translatorId} is not currently active or translating.`);
}
```

---

## How to Test

### Option 1: Use Test Mode (Recommended for Development)
1. Open [/translations-webrtc](/translations-webrtc)
2. Click "Enable Test Mode" button
3. Test translators will be loaded for development

### Option 2: Wait for Live Translator
1. Ensure Translation Studio backend is running:
   ```bash
   cd ~/public_html/webrtc/browser-based-translation/backend
   pm2 status
   # Should show: tni-translation-studio (running)
   ```

2. Have a translator start their session from:
   - Translation Studio Web App: https://programs.tniglobal.org
   - They must click "Start Translation" and allow camera/microphone

3. Verify translator is active:
   ```bash
   curl -s https://ministryprogs.tniglobal.org/webrtc/public/active-translators
   ```
   Should return something like:
   ```json
   {
     "translators": [
       {
         "id": "69075dfdd06430e3c53cff74",
         "fullName": "John Smith",
         "language": "german",
         "isTranslating": true
       }
     ]
   }
   ```

### Option 3: Manual Backend Test
Test transport creation manually:
```bash
# First get active translator ID
TRANSLATOR_ID=$(curl -s https://ministryprogs.tniglobal.org/webrtc/public/active-translators | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)

# Try to create transport
curl -X POST https://ministryprogs.tniglobal.org/webrtc/public/create-consumer-transport \
  -H "Content-Type: application/json" \
  -d "{\"translatorId\":\"$TRANSLATOR_ID\",\"language\":\"german\"}"
```

---

## Expected Behavior

### When No Translators Active
- **List Page:** Shows message "No active translators found..."
- **Player Component:** Does not attempt connection
- **User Action:** Can enable Test Mode or wait for live event

### When Translators Active
- **List Page:** Shows active translators with language options
- **Player Component:** Connects successfully with <500ms latency
- **Connection Status:** Green badge shows "Connected • XXms"

---

## Backend Requirements Checklist

- [ ] **Backend Server Running**
  ```bash
  pm2 list | grep translation-studio
  # Should show: online status
  ```

- [ ] **Port 3001 Accessible**
  ```bash
  netstat -tulpn | grep 3001
  # Should show: LISTEN on port 3001
  ```

- [ ] **Nginx Proxy Configured**
  ```bash
  curl -I https://ministryprogs.tniglobal.org/webrtc/public/router-capabilities
  # Should return: 200 OK
  ```

- [ ] **CORS Configured for Your Domain**
  Check backend `server.js` includes:
  ```javascript
  cors({
    origin: [
      'https://livestream.tniglobal.org',  // Your production domain
      'http://localhost:3002',             // Your dev port
      // ... other origins
    ]
  })
  ```

- [ ] **At Least One Translator Active**
  ```bash
  curl https://ministryprogs.tniglobal.org/webrtc/public/active-translators
  # Should return: translators array with length > 0
  ```

---

## Troubleshooting Steps

### Error: "Failed to create transport: Internal Server Error"

**Diagnosis:**
```bash
# 1. Check backend logs
pm2 logs tni-translation-studio --lines 50

# 2. Check active translators
curl https://ministryprogs.tniglobal.org/webrtc/public/active-translators

# 3. Test router capabilities (confirms backend is responding)
curl https://ministryprogs.tniglobal.org/webrtc/public/router-capabilities
```

**Common Causes:**
1. ❌ No active translators → **Solution:** Enable Test Mode or wait for live translator
2. ❌ Backend server down → **Solution:** `pm2 restart tni-translation-studio`
3. ❌ Invalid translator ID → **Solution:** Use ID from active-translators endpoint
4. ❌ Translator stopped translating → **Solution:** Refresh translator list

### Error: "CORS Error: Backend server is not configured..."

**Solution:** Add your domain to backend CORS configuration
```javascript
// backend/server.js
app.use(cors({
  origin: [
    'https://your-domain.com',  // Add your domain here
    // ...
  ]
}));
```

### Error: "Device not initialized"

**Solution:** Initialize device before connecting
```typescript
const consumer = new WebRTCConsumer();
await consumer.initialize();  // Must call this first
await consumer.connectToTranslator(id, language);
```

---

## Production Deployment Checklist

Before deploying to production:

- [x] ✅ Enhanced error handling implemented
- [x] ✅ Pre-connection validation added
- [x] ✅ Better error messages for users
- [x] ✅ Test Mode available for development
- [x] ✅ Production build completed
- [ ] Backend CORS configured for production domain
- [ ] At least one translator ready for testing
- [ ] Cross-browser testing completed

---

## Quick Reference

### Key Files
- **Consumer Class:** `src/utils/webrtc-consumer.ts`
- **Player Component:** `src/components/livestream/WebRTCPlayer.tsx`
- **Page Component:** `src/pages/streamspace/GeneralStreamWebRTC.tsx`

### API Endpoints
- **Active Translators:** `GET /webrtc/public/active-translators`
- **Router Capabilities:** `GET /webrtc/public/router-capabilities`
- **Create Transport:** `POST /webrtc/public/create-consumer-transport`

### Backend Server
- **Location:** `~/public_html/webrtc/browser-based-translation/backend`
- **Port:** 3001
- **URL:** https://ministryprogs.tniglobal.org
- **Process Manager:** pm2 (tni-translation-studio)

---

## Support

If issues persist:
1. Check backend server logs: `pm2 logs tni-translation-studio`
2. Verify network connectivity to ministryprogs.tniglobal.org
3. Test with curl commands above
4. Enable debug logging in WebRTCConsumer: `new WebRTCConsumer(true)`

---

**Build Status:** ✅ Rebuilt with fixes (January 13, 2026)  
**Next Deploy:** Copy build folder to production server
