# Screenshare Bot Runbook

Incident response and troubleshooting guide for production operations.

## Table of Contents

- [Overview](#overview)
- [Architecture](#architecture)
- [Incident Response](#incident-response)
- [Common Issues](#common-issues)
- [Recovery Procedures](#recovery-procedures)
- [Health Checks](#health-checks)

---

## Overview

### What This Bot Does

The Screenshare Bot is a Python service that:
1. Joins Daily.co video rooms as a virtual participant
2. Opens Slidev presentation decks in a headless browser (Playwright)
3. Captures browser screenshots at 10 FPS
4. Streams screenshots as video frames via Pipecat DailyTransport
5. Responds to slide navigation commands (next/previous slide)

### Bot Lifecycle

```
┌─────────────────────────────────────────────────────────┐
│                    BOT LIFECYCLE                        │
└─────────────────────────────────────────────────────────┘

1. SPAWN REQUEST
   POST /api/tavus/bot/spawn
   └─> botManager.spawnBot()

2. BOT INITIALIZATION
   ├─> Load environment variables
   ├─> Validate deck URL (5s timeout)
   │   ├─> Valid: Use provided URL
   │   └─> Invalid: Fall back to test deck
   └─> Initialize PerformanceMonitor

3. JOIN DAILY ROOM
   ├─> Create DailyTransport
   ├─> Retry logic: 3 attempts with exponential backoff
   └─> Join room with meeting token

4. START STREAMING
   ├─> Generate/capture frames at 10 FPS
   ├─> Send OutputImageRawFrame to transport
   └─> Monitor performance metrics

5. TERMINATE
   ├─> Stop streaming loop
   ├─> Log performance summary
   ├─> Stop DailyTransport
   └─> Exit process
```

### Deployment Architecture

```
┌──────────────────────────────────────────────────────────┐
│                    RAILWAY PLATFORM                      │
│                                                          │
│  ┌────────────────────────────────────────────────┐    │
│  │         Slide System API (Node.js)             │    │
│  │                                                 │    │
│  │  ┌──────────────────────────────────────────┐  │    │
│  │  │      TavusBotManager Service             │  │    │
│  │  │  (spawns bot child processes)            │  │    │
│  │  └─────────────────┬────────────────────────┘  │    │
│  │                    │                            │    │
│  │                    │ spawn                      │    │
│  │                    ↓                            │    │
│  │  ┌──────────────────────────────────────────┐  │    │
│  │  │  Screenshare Bot (Python child process)  │  │    │
│  │  │  • bot.py                                 │  │    │
│  │  │  • Playwright browser                     │  │    │
│  │  │  • DailyTransport                         │  │    │
│  │  │  • PerformanceMonitor                     │  │    │
│  │  └──────────────────────────────────────────┘  │    │
│  └────────────────────────────────────────────────┘    │
│                                                          │
└──────────────────────────────────────────────────────────┘
                           │
                           │ Video Stream
                           ↓
                  ┌─────────────────┐
                  │  Daily.co Room  │
                  └─────────────────┘
```

---

## Incident Response

### Bot Won't Spawn

**Symptoms:**
- API returns 500 error on spawn request
- No bot process appears in Railway logs
- BotManager logs "Failed to spawn bot"

**Diagnostic Steps:**

```bash
# 1. Check Railway logs for spawn request
railway logs --service slide-system | grep "BotManager"

# 2. Look for Python path errors
railway logs --service slide-system | grep "python" | tail -20

# 3. Check for missing dependencies
railway logs --service slide-system | grep "ModuleNotFoundError"

# 4. Verify environment variables are set
railway vars --service slide-system | grep DAILY_API_KEY
```

**Common Causes:**

| Cause | Log Pattern | Fix |
|-------|-------------|-----|
| Python not found | `ENOENT: no such file or directory` | Check Python installation in Railway |
| Missing dependencies | `ModuleNotFoundError: No module named 'daily'` | Run `pip install -r requirements.txt` |
| Missing env vars | `DAILY_API_KEY not found` | Set env var in Railway dashboard |
| Script path wrong | `bot.py: No such file or directory` | Verify bot script path in botManager |

**Resolution:**

```bash
# If Python dependencies missing:
railway run --service slide-system "cd apps/slide-system/bots/screenshare-bot && pip install -r requirements.txt"

# If Playwright browsers missing:
railway run --service slide-system "playwright install chromium"

# Verify bot script exists:
railway run --service slide-system "ls -la apps/slide-system/bots/screenshare-bot/bot.py"
```

---

### Bot Crashes After Spawn

**Symptoms:**
- Bot spawns successfully (PID logged)
- Bot process exits immediately (exit code logged)
- No "Joining Daily.co room" log appears

**Diagnostic Steps:**

```bash
# 1. Check bot exit code
railway logs --service slide-system | grep "Bot process exited"

# Example: Bot process exited for conv-123 (code: 1)
# Exit code 1 = error, 0 = normal exit

# 2. Check stderr output
railway logs --service slide-system | grep "ERROR:"

# 3. Look for Python stack traces
railway logs --service slide-system | grep "Traceback"

# 4. Check if environment is loaded
railway logs --service slide-system | grep "load_dotenv"
```

**Common Causes:**

| Exit Code | Cause | Fix |
|-----------|-------|-----|
| 1 | Python exception | Check stack trace for details |
| 2 | Missing command-line args | Verify spawn command includes room_url |
| 137 | OOM killed | Increase Railway memory limit |
| 143 | SIGTERM received | Check for manual kill or timeout |

**Resolution:**

```bash
# If OOM (exit code 137):
# Increase memory in Railway dashboard: Settings > Memory Limit > 2GB

# If missing args:
# Check botManager spawn command includes room_url parameter
railway logs --service slide-system | grep "spawn.*bot.py"

# If persistent crashes, test bot locally:
cd apps/slide-system/bots/screenshare-bot
python bot.py "https://test.daily.co/test-room"
```

---

### Bot Won't Join Daily.co Room

**Symptoms:**
- Bot spawns and starts successfully
- "Joining Daily.co room" log appears
- Retry attempts logged
- All 3 attempts fail
- Error: "Failed to join room"

**Diagnostic Steps:**

```bash
# 1. Check join attempts and errors
railway logs --service slide-system | grep "Attempt"

# 2. Check for Daily API errors
railway logs --service slide-system | grep "DailyTransport"

# 3. Verify room URL format
railway logs --service slide-system | grep "Room URL:"

# 4. Check network/firewall issues
railway logs --service slide-system | grep "ConnectionError\|TimeoutError"
```

**Common Causes:**

| Error Pattern | Cause | Fix |
|---------------|-------|-----|
| `401 Unauthorized` | Invalid meeting token | Check Daily API key |
| `404 Not Found` | Room doesn't exist | Verify room URL is valid |
| `403 Forbidden` | Token doesn't match room | Generate new token for this room |
| `ConnectionError` | Network issue | Check Railway network status |
| `TimeoutError` | Daily.co unresponsive | Check Daily.co status page |

**Resolution:**

```bash
# 1. Verify Daily API key is set correctly
railway vars --service slide-system | grep DAILY_API_KEY

# 2. Test room URL manually
curl -I https://YOUR_DOMAIN.daily.co/YOUR_ROOM

# 3. Generate new meeting token if needed
# (See scripts/create_token.py)

# 4. Check Daily.co service status
# Visit: https://status.daily.co

# 5. Check Railway network status
# Visit: https://railway.app/status
```

---

### Bot Stops Streaming

**Symptoms:**
- Bot successfully joins room
- Streaming starts (frames logged)
- After some time, "Frame streaming error" logged
- Bot continues running but no frames sent

**Diagnostic Steps:**

```bash
# 1. Check when streaming stopped
railway logs --service slide-system | grep "Frame streaming stopped"

# 2. Look for frame pipeline errors
railway logs --service slide-system | grep "Frame streaming error"

# 3. Check for DailyTransport errors
railway logs --service slide-system | grep "transport.*error"

# 4. Check frame rate drops
railway logs --service slide-system | grep "Actual FPS:"
```

**Common Causes:**

| Error Pattern | Cause | Fix |
|---------------|-------|-----|
| `Transport disconnected` | Network interruption | Bot will retry (3 attempts) |
| `Frame capture timeout` | Browser hang | Restart bot |
| `Memory allocation failed` | Out of memory | Check memory usage |
| `Playwright context closed` | Browser crashed | Restart bot |

**Resolution:**

```bash
# 1. Check current bot status
curl http://localhost:3000/api/tavus/bot/status | jq

# 2. Kill and respawn bot if needed
curl -X POST http://localhost:3000/api/tavus/bot/kill \
  -H "Content-Type: application/json" \
  -d '{"conversation_id": "YOUR_CONV_ID"}'

curl -X POST http://localhost:3000/api/tavus/bot/spawn \
  -H "Content-Type: application/json" \
  -d '{"conversation_id": "YOUR_CONV_ID", "room_url": "YOUR_ROOM_URL"}'

# 3. If memory issue, check usage
railway logs --service slide-system | grep "Memory:"
```

---

### High Memory Usage

**Symptoms:**
- Bot memory usage > 500MB
- Performance monitoring logs show increasing memory
- Bot becomes sluggish or OOM killed

**Diagnostic Steps:**

```bash
# 1. Check current memory usage
railway logs --service slide-system | grep "Memory:"

# 2. Look for memory trend over time
railway logs --service slide-system | grep "Performance -" | tail -20

# 3. Check for memory leaks
# Look for continuously increasing memory with no decrease
railway logs --service slide-system | grep "Memory:" | awk '{print $NF}' | tail -50

# 4. Check number of active bots
railway logs --service slide-system | grep "Active bots:"
```

**Expected Memory Usage:**
- Single bot: 250-350 MB
- 3 concurrent bots: 750-1050 MB
- 5 concurrent bots: 1250-1750 MB

**Memory Leak Detection:**

If memory increases steadily over time without plateauing, suspect a leak:

```bash
# Sample over 10 minutes, look for pattern:
railway logs --service slide-system | grep "Memory:" | tail -50

# Example of healthy bot (memory plateaus):
[18:00] Memory: 280.2MB
[18:05] Memory: 285.1MB
[18:10] Memory: 283.5MB
[18:15] Memory: 287.0MB

# Example of memory leak (continuous increase):
[18:00] Memory: 280.2MB
[18:05] Memory: 350.5MB
[18:10] Memory: 420.8MB
[18:15] Memory: 495.2MB
```

**Resolution:**

```bash
# 1. If memory leak suspected:
# Kill and respawn bots to reclaim memory
curl -X POST http://localhost:3000/api/tavus/bot/kill -d '{"conversation_id": "..."}'

# 2. If Railway memory limit reached:
# Temporarily increase limit in Railway dashboard
# Settings > Memory Limit > 4GB (adjust as needed)

# 3. Reduce concurrent bots if needed:
# Limit spawns until memory issue resolved

# 4. If persistent leak:
# Check for unreleased Playwright resources
railway logs --service slide-system | grep "browser" | tail -50
```

---

### High CPU Usage

**Symptoms:**
- Bot CPU usage > 30% per bot
- Performance monitoring logs show high CPU
- Frame rate drops below target 10 FPS

**Diagnostic Steps:**

```bash
# 1. Check current CPU usage
railway logs --service slide-system | grep "CPU:"

# 2. Check frame capture time
railway logs --service slide-system | grep "Frame Capture:"

# 3. Check actual FPS vs target
railway logs --service slide-system | grep "Actual FPS:"

# 4. Check Railway CPU metrics
# Visit Railway dashboard > Metrics tab
```

**Expected CPU Usage:**
- Idle bot: 5-10%
- Streaming bot: 15-30%
- 3 concurrent bots: 45-90%
- 5 concurrent bots: 75-150%

**Performance Debugging:**

```bash
# 1. Check if frame capture is slow
railway logs --service slide-system | grep "Frame Capture:"

# Good: Frame Capture: 15-50ms
# Bad: Frame Capture: >100ms

# 2. Check if CPU bottlenecked
railway logs --service slide-system | grep "CPU:" | tail -20

# If CPU >80%: System is overloaded

# 3. Check frame rate stability
railway logs --service slide-system | grep "Actual FPS:"

# Target: 9.5-10.5 FPS
# Degraded: <9.0 FPS
```

**Resolution:**

```bash
# 1. Reduce frame rate temporarily (requires code change):
# In bot.py, change: self.frame_rate = 10 to self.frame_rate = 5

# 2. Reduce number of concurrent bots

# 3. Check for runaway browser processes
railway run --service slide-system "ps aux | grep chromium"

# 4. Restart service if CPU remains high
railway restart --service slide-system
```

---

## Common Issues

### Daily.co Room Not Found (404)

**Symptoms:**
- Bot logs: "HTTP 404 - Room not found"
- DailyTransport fails to join

**Causes:**
- Room URL is incorrect
- Room has been deleted
- Room expired (Daily.co rooms auto-expire)

**Resolution:**

```bash
# 1. Verify room exists
curl -H "Authorization: Bearer $DAILY_API_KEY" \
  https://api.daily.co/v1/rooms/YOUR_ROOM_NAME

# 2. Create new room if needed
# (See scripts/create_test_room.py)

# 3. Check room expiration settings in Daily.co dashboard
```

---

### Playwright Browser Fails to Start

**Symptoms:**
- Bot logs: "Error starting browser"
- "Browser executable not found"
- "Failed to launch browser"

**Causes:**
- Playwright browsers not installed
- Missing system dependencies (libglib, libnss, etc.)
- Railway system incompatibility

**Resolution:**

```bash
# 1. Install Playwright browsers
railway run --service slide-system "playwright install chromium"

# 2. Install system dependencies
railway run --service slide-system "playwright install-deps"

# 3. If issues persist, check Railway build logs
railway logs --service slide-system --deployment | grep "playwright"

# 4. Verify Playwright version
railway run --service slide-system "playwright --version"
```

---

### Supabase Connection Drops

**Symptoms:**
- Bot logs: "Supabase connection error"
- Slide navigation commands stop working
- "Failed to subscribe to realtime channel"

**Causes:**
- Network interruption
- Supabase API rate limit
- Invalid Supabase credentials

**Resolution:**

```bash
# 1. Check Supabase credentials
railway vars --service slide-system | grep SUPABASE

# 2. Test Supabase connection
curl -H "apikey: $SUPABASE_KEY" \
  https://YOUR_PROJECT.supabase.co/rest/v1/

# 3. Check Supabase status
# Visit: https://status.supabase.com

# 4. Check for rate limiting
railway logs --service slide-system | grep "429\|rate limit"
```

---

### Slide Deck URL Inaccessible

**Symptoms:**
- Bot logs: "Deck URL validation failed"
- Bot falls back to test deck
- "Using fallback deck URL"

**Causes:**
- Deck generation failed
- Deck URL is incorrect
- Deck server is down
- Network timeout (>5s)

**Resolution:**

```bash
# 1. Test deck URL manually
curl -I https://buzztrail.github.io/buzztrail-presentations/YOUR_DECK/

# 2. Check deck generation logs
railway logs --service slide-system | grep "slidev/generate"

# 3. Verify fallback behavior
railway logs --service slide-system | grep "fallback"

# Expected: Bot continues with test deck
# https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/

# 4. If persistent, investigate deck generation service
railway logs --service slide-system | grep "slidev"
```

---

## Recovery Procedures

### Manual Bot Restart

When you need to restart a specific bot without affecting others:

```bash
# Step 1: Get conversation ID
railway logs --service slide-system | grep "Active bots" -A 10

# Step 2: Kill the bot
curl -X POST http://localhost:3000/api/tavus/bot/kill \
  -H "Content-Type: application/json" \
  -d '{
    "conversation_id": "YOUR_CONVERSATION_ID"
  }'

# Step 3: Verify kill succeeded
railway logs --service slide-system | grep "Bot killed for YOUR_CONVERSATION_ID"

# Step 4: Respawn the bot
curl -X POST http://localhost:3000/api/tavus/bot/spawn \
  -H "Content-Type: application/json" \
  -d '{
    "conversation_id": "YOUR_CONVERSATION_ID",
    "room_url": "https://YOUR_DOMAIN.daily.co/YOUR_ROOM"
  }'

# Step 5: Verify spawn succeeded
railway logs --service slide-system | grep "Bot spawned for YOUR_CONVERSATION_ID"
```

---

### Force Kill Stuck Bot

When a bot won't respond to normal termination:

```bash
# Step 1: Find bot PID
railway logs --service slide-system | grep "Bot spawned" | tail -10
# Look for: Bot spawned for conv-123 (PID: 45678)

# Step 2: Connect to Railway shell
railway run --service slide-system bash

# Step 3: Force kill the process
kill -9 PID_NUMBER

# Step 4: Exit shell
exit

# Step 5: Verify process is gone
railway logs --service slide-system | grep "Bot process exited"

# Step 6: Clean up bot manager state
curl -X POST http://localhost:3000/api/tavus/bot/kill \
  -d '{"conversation_id": "YOUR_CONV_ID"}'
```

---

### Clear Bot State

When bot manager state is inconsistent (e.g., bot shows as active but process is dead):

```bash
# Step 1: Check current state
curl http://localhost:3000/api/tavus/bot/status | jq

# Step 2: Kill all bots
curl -X POST http://localhost:3000/api/tavus/bot/kill-all

# Step 3: Verify all processes terminated
railway logs --service slide-system | grep "Bot process exited"

# Step 4: Restart the slide-system service
railway restart --service slide-system

# Step 5: Verify service restarted
railway logs --service slide-system --tail

# Step 6: Verify bot manager reinitialized
railway logs --service slide-system | grep "BotManager.*Initialized"
```

---

### Rollback Deployment

When a deployment introduces critical issues:

```bash
# Step 1: Check recent deployments
railway deployments --service slide-system

# Output example:
# ID              Status    Created
# dep-abc123xyz   ACTIVE    2025-10-12 10:30
# dep-def456uvw   SUCCESS   2025-10-12 09:00
# dep-ghi789rst   SUCCESS   2025-10-11 14:00

# Step 2: Identify last known good deployment
# (Usually the deployment before ACTIVE)

# Step 3: Rollback to previous deployment
railway rollback --service slide-system dep-def456uvw

# Step 4: Verify rollback succeeded
railway logs --service slide-system --tail

# Step 5: Check bot functionality
curl http://localhost:3000/api/tavus/bot/status

# Step 6: Test spawn request
curl -X POST http://localhost:3000/api/tavus/bot/spawn \
  -H "Content-Type: application/json" \
  -d '{
    "conversation_id": "test-conv-123",
    "room_url": "https://test.daily.co/test-room"
  }'

# Step 7: Verify bot spawned successfully
railway logs --service slide-system | grep "test-conv-123"
```

**Post-Rollback Actions:**

1. Document the issue that caused rollback
2. Create incident ticket with reproduction steps
3. Notify team of rollback
4. Fix issue in development environment
5. Test thoroughly before re-deploying

---

## Health Checks

### How to Verify Bot is Healthy

A healthy bot exhibits these characteristics:

**1. Process Health:**
```bash
# Bot process is running
railway logs --service slide-system | grep "Bot spawned"
# Expected: Bot spawned for conv-123 (PID: 12345)

# No recent crash logs
railway logs --service slide-system | grep "Bot process exited" | tail -5
# Expected: No entries or only normal (code: 0) exits
```

**2. Connection Health:**
```bash
# Successfully joined Daily room
railway logs --service slide-system | grep "Successfully joined Daily.co room"

# Transport is active
railway logs --service slide-system | grep "DailyTransport initialized successfully"
```

**3. Streaming Health:**
```bash
# Frames are being sent
railway logs --service slide-system | grep "Frames:"
# Expected: Frames: 1000, Actual FPS: 10.02, Target FPS: 10

# Frame rate is stable (9.5-10.5 FPS)
railway logs --service slide-system | grep "Actual FPS:" | tail -10
```

**4. Performance Health:**
```bash
# Memory is within limits (<500MB per bot)
railway logs --service slide-system | grep "Memory:" | tail -5

# CPU is reasonable (<30% per bot)
railway logs --service slide-system | grep "CPU:" | tail -5

# Frame capture is fast (<50ms)
railway logs --service slide-system | grep "Frame Capture:" | tail -5
```

**Health Check Checklist:**

```
□ Bot process running (PID logged)
□ Joined Daily.co room successfully
□ Frames being sent (count increasing)
□ FPS stable (9.5-10.5)
□ Memory < 500MB per bot
□ CPU < 30% per bot
□ Frame capture < 50ms
□ No error logs in last 5 minutes
```

---

### Key Metrics to Monitor

| Metric | Target | Warning | Critical | Check Interval |
|--------|--------|---------|----------|----------------|
| **Bot Spawn Success Rate** | >95% | 90-95% | <90% | 5 min |
| **Join Latency** | <5s | 5-10s | >10s | Per spawn |
| **Frame Rate (FPS)** | 10±0.5 | 9.0-9.5 or 10.5-11.0 | <9.0 or >11.0 | 30 sec |
| **Memory per Bot** | <350MB | 350-450MB | >500MB | 30 sec |
| **CPU per Bot** | <25% | 25-35% | >40% | 30 sec |
| **Command Latency** | <500ms | 500-1000ms | >1000ms | Per command |
| **Bot Crash Rate** | 0 | 1-2/day | >3/day | 1 hour |
| **Active Bot Count** | Expected | ±1 | ±2+ | 5 min |

---

### Alert Thresholds

Configure Railway or external monitoring to alert on these conditions:

**Critical Alerts (Page On-Call):**
```yaml
- name: Bot Spawn Failures
  condition: spawn_success_rate < 90% over 10 minutes
  action: Page on-call engineer

- name: Service Down
  condition: no_log_entries_for > 5 minutes
  action: Page on-call engineer

- name: OOM Kills
  condition: exit_code = 137
  action: Page on-call engineer

- name: All Bots Crashed
  condition: active_bot_count = 0 AND expected_count > 0
  action: Page on-call engineer
```

**Warning Alerts (Notify Channel):**
```yaml
- name: High Memory Usage
  condition: memory > 450MB per bot
  action: Notify #ops-alerts

- name: High CPU Usage
  condition: cpu > 35% per bot over 5 minutes
  action: Notify #ops-alerts

- name: Low Frame Rate
  condition: fps < 9.0 over 2 minutes
  action: Notify #ops-alerts

- name: Frequent Restarts
  condition: bot_restarts > 2 per hour
  action: Notify #ops-alerts

- name: Join Latency High
  condition: join_latency > 10s
  action: Notify #ops-alerts
```

**Info Alerts (Log Only):**
```yaml
- name: Bot Spawned
  condition: log contains "Bot spawned"
  action: Log to metrics dashboard

- name: Bot Terminated
  condition: log contains "Bot process exited"
  action: Log to metrics dashboard

- name: Deck Validation Failed
  condition: log contains "Deck URL validation failed"
  action: Log to metrics dashboard
```

---

## Quick Reference

### Essential Commands

```bash
# Check bot status
curl http://localhost:3000/api/tavus/bot/status | jq

# Spawn bot
curl -X POST http://localhost:3000/api/tavus/bot/spawn \
  -H "Content-Type: application/json" \
  -d '{"conversation_id": "conv-123", "room_url": "https://test.daily.co/room"}'

# Kill bot
curl -X POST http://localhost:3000/api/tavus/bot/kill \
  -H "Content-Type: application/json" \
  -d '{"conversation_id": "conv-123"}'

# View logs (tail last 100 lines)
railway logs --service slide-system --tail -n 100

# View logs (follow in real-time)
railway logs --service slide-system --tail

# Restart service
railway restart --service slide-system

# Check environment variables
railway vars --service slide-system

# Connect to shell
railway run --service slide-system bash
```

### Log Patterns for Grep

```bash
# Bot spawn events
railway logs | grep "Bot spawned"

# Bot crashes
railway logs | grep "Bot process exited.*code: [^0]"

# Join failures
railway logs | grep "All.*attempts failed"

# Memory issues
railway logs | grep "Memory:.*MB" | awk '$NF > 500'

# Frame rate issues
railway logs | grep "Actual FPS:" | awk '$NF < 9.0'

# Errors
railway logs | grep "ERROR:\|❌"
```

### Emergency Contacts

```
On-Call Engineer: [Your rotation schedule]
Railway Status: https://railway.app/status
Daily.co Status: https://status.daily.co
Supabase Status: https://status.supabase.com
Team Slack: #ops-alerts
Incident Template: [Link to your incident template]
```

---

**Document Version:** 1.0
**Last Updated:** 2025-10-12
**Maintained By:** DevOps Team
