# Screenshare Bot with Pluggable Transport

A Python bot that joins video rooms (Daily.co or LiveKit) and shares a Slidev presentation deck. Supports pluggable transport backends via factory pattern. Includes comprehensive lifecycle management, error recovery, and remote slide control.

## Overview

This bot:
1. Joins a video room as a participant using pluggable transport (Daily.co or LiveKit)
2. Opens a Slidev deck in a headless browser (Playwright)
3. Continuously captures screenshots and streams them at 10 FPS
4. Listens for remote slide navigation commands via Supabase Realtime
5. Automatically manages lifecycle with inactivity timeouts and graceful shutdown
6. Recovers from browser crashes and network failures

This allows the presentation deck to appear as a video participant in the call, with full lifecycle management and error recovery.

## Lifecycle Management Architecture

### Overview

The bot lifecycle is managed by two integrated systems:

1. **Backend Spawn API** (TypeScript/Node.js) - Manages bot processes
2. **Bot Lifecycle Manager** (Python) - Manages bot behavior and termination

```
┌─────────────────────────────────────────────────────────────────┐
│                    Backend Spawn API                            │
│                  (Motia.dev TypeScript)                         │
│                                                                  │
│  POST /api/bots/screenshare/spawn                              │
│  POST /api/bots/screenshare/kill/:bot_id                       │
│  GET  /api/bots/screenshare/status/:bot_id                     │
│                                                                  │
│  - Spawns Python bot process (child_process.spawn)             │
│  - Tracks bot PIDs and status                                  │
│  - Handles process exit events                                 │
│  - Sends SIGTERM for graceful shutdown                         │
│                                                                  │
└───────────────────────────┬─────────────────────────────────────┘
                            │
                            │ spawns
                            ↓
┌─────────────────────────────────────────────────────────────────┐
│              Python Bot Process (bot.py)                        │
│                                                                  │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │         BotLifecycleManager                              │  │
│  │                                                           │  │
│  │  - Inactivity timeout monitoring (30 min default)       │  │
│  │  - Signal handlers (SIGTERM, SIGINT)                    │  │
│  │  - Graceful shutdown coordination                       │  │
│  │  - Termination notifications                            │  │
│  └────────────────────┬─────────────────────────────────────┘  │
│                       │                                          │
│                       │ manages                                 │
│                       ↓                                          │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │           ScreenshareBot                                 │  │
│  │                                                           │  │
│  │  - DailyTransport (Daily.co connection)                 │  │
│  │  - ScreenshotCapture (Playwright browser)               │  │
│  │  - SlideNavigator (keyboard control)                    │  │
│  │  - SlideControlListener (Supabase Realtime)             │  │
│  │  - Frame streaming loop (10 FPS)                        │  │
│  │                                                           │  │
│  │  Error Recovery:                                         │  │
│  │  - Browser crash → restart Playwright                   │  │
│  │  - Daily.co disconnect → 3 retries with backoff         │  │
│  │  - Frame capture errors → use last good frame           │  │
│  └──────────────────────────────────────────────────────────┘  │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘
```

### Termination Scenarios

The bot can terminate in three ways:

#### 1. Inactivity Timeout (30 minutes default)
- Lifecycle manager monitors for activity
- Checks every 60 seconds
- Terminates if inactive for configured duration
- Configurable via command-line argument

```python
# Default 30 minutes
python bot.py <room_url> <deck_url> <session_id>

# Custom timeout (e.g., 5 minutes)
python bot.py <room_url> <deck_url> <session_id> "" 5
```

#### 2. Manual Kill via API
- Backend sends SIGTERM to bot process
- Lifecycle manager catches signal
- Initiates graceful shutdown
- Force kill (SIGKILL) after 10 seconds if needed

```bash
curl -X POST http://localhost:3000/api/bots/screenshare/kill/{bot_id}
```

#### 3. Signal Handling (SIGTERM/SIGINT)
- Bot registers signal handlers on startup
- SIGTERM: Graceful shutdown (from API or system)
- SIGINT: Ctrl+C in terminal (development)
- Cleanup happens regardless of termination method

### Graceful Shutdown Process

When termination is triggered, the bot performs these steps in order:

1. **Stop accepting new work**
   - Set `is_running = False`
   - Cancel inactivity monitor task

2. **Send termination notification**
   - Log termination reason to Railway logs
   - Include runtime and last activity time

3. **Stop bot components** (via `bot.stop()`)
   - Stop Supabase Realtime listener
   - Stop slide navigator
   - Cleanup Daily.co transport connection
   - Stop screenshot capture (close Playwright browser)

4. **Restore signal handlers**
   - Restore original SIGTERM/SIGINT handlers

5. **Exit process cleanly**

### Error Recovery

#### Browser Crash Recovery
The bot automatically recovers from browser crashes:

```python
# In screenshot_capture.py
async def capture_frame(self):
    try:
        return await self._capture_with_retry()
    except Exception as e:
        # After 3 failed attempts, trigger recovery
        logger.error("Browser crash detected, recovering...")
        await self._recover_from_browser_crash()
        return await self.capture_frame()  # Retry once
```

Recovery process:
1. Detect persistent failures (3+ attempts)
2. Stop crashed browser instance
3. Start new browser instance
4. Reload deck at current slide
5. Resume frame capture

#### Daily.co Reconnection
Transport startup uses exponential backoff retry:

```python
# In bot.py
await retry_with_backoff(
    start_transport_impl,
    max_attempts=3,
    operation_name="Daily.co transport startup"
)
```

Retry timing: 1s, 2s, 4s (total 7 seconds)

#### Frame Capture Fallback
If frame capture fails temporarily:
- Bot continues streaming last successful frame
- Prevents black screen in Daily.co room
- Logs warning for monitoring

## How It Works

### Virtual Camera Approach

The bot uses Daily's virtual camera API to share the presentation:

```python
# Create virtual camera device
camera_device = Daily.create_camera_device(
    "screenshare_camera",
    width=1280,
    height=720,
    color_format="RGBA"
)

# Enable camera in call
client.update_inputs({
    "camera": {
        "isEnabled": True,
        "settings": {
            "deviceId": camera_device
        }
    }
})

# Write frames to virtual camera (in loop)
Daily.write_frame(camera_device, rgba_bytes)
```

### Frame Capture Loop

The bot runs an async loop that:
1. Captures a screenshot from the Playwright page (`page.screenshot()`)
2. Converts the PNG to a PIL Image
3. Converts to RGBA format if needed
4. Writes the raw RGBA bytes to the virtual camera
5. Waits for the frame interval (e.g., 100ms for 10 FPS)

## Installation

### Prerequisites

- Python 3.8+
- Daily.co account and room URL
- uv (Python package installer) or pip

### Install Dependencies

Using uv:
```bash
cd apps/slide-system/bots/screenshare-bot
uv venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
uv pip install -r requirements.txt
```

Using pip:
```bash
cd apps/slide-system/bots/screenshare-bot
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
pip install -r requirements.txt
```

### Install Playwright Browsers

After installing dependencies, install the Playwright browser:
```bash
playwright install chromium
```

## API Endpoints

The backend provides three REST API endpoints for bot management:

### POST /api/bots/screenshare/spawn-livekit

Spawn a new screenshare bot process using LiveKit transport (recommended for production).

**Request:**
```json
{
  "room_url": "wss://your-project.livekit.cloud/room-name",
  "deck_url": "https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/",
  "session_id": "550e8400-e29b-41d4-a716-446655440000",
  "meeting_token": "optional-livekit-token"
}
```

**Response (200 OK):**
```json
{
  "bot_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
  "status": "spawning",
  "pid": 12345,
  "estimated_join_time": "5s"
}
```

**Error Responses:**
- 400: Invalid request (missing fields, invalid URLs)
- 500: Spawn failed (bot process couldn't start)

### POST /api/bots/screenshare/spawn

Spawn a new screenshare bot process using Daily.co transport.

**Request:**
```json
{
  "room_url": "https://example.daily.co/room-name",
  "deck_url": "https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/",
  "session_id": "550e8400-e29b-41d4-a716-446655440000",
  "meeting_token": "optional-daily-token"
}
```

**Response (200 OK):**
```json
{
  "bot_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
  "status": "spawning",
  "pid": 12345,
  "estimated_join_time": "5s"
}
```

**Error Responses:**
- 400: Invalid request (missing fields, invalid URLs)
- 500: Spawn failed (bot process couldn't start)

### POST /api/bots/screenshare/kill/:bot_id

Gracefully terminate a bot by sending SIGTERM.

**Response (200 OK):**
```json
{
  "success": true,
  "bot_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
  "message": "SIGTERM sent to bot"
}
```

**Error Responses:**
- 400: Invalid bot_id format
- 404: Bot not found
- 500: Kill failed

### GET /api/bots/screenshare/status/:bot_id

Get status of a specific bot.

**Response (200 OK):**
```json
{
  "bot_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
  "session_id": "550e8400-e29b-41d4-a716-446655440000",
  "room_url": "https://example.daily.co/room-name",
  "deck_url": "https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/",
  "status": "running",
  "pid": 12345,
  "spawned_at": "2025-10-11T18:30:00.000Z",
  "stopped_at": null,
  "error": null
}
```

**Status values:**
- `spawning`: Process started, bot joining room
- `running`: Bot successfully joined room and streaming
- `stopping`: Termination initiated, cleanup in progress
- `stopped`: Bot terminated normally
- `error`: Bot terminated with error

### GET /api/bots/screenshare/status

Get status of all bots.

**Response (200 OK):**
```json
{
  "active_count": 3,
  "bots": [
    {
      "bot_id": "...",
      "session_id": "...",
      "status": "running",
      "pid": 12345,
      "spawned_at": "2025-10-11T18:30:00.000Z"
    }
  ]
}
```

## Usage

### Via API (Production)

Spawn a bot using the API (LiveKit - recommended):
```bash
curl -X POST https://slide-system-production-5813.up.railway.app/api/bots/screenshare/spawn-livekit \
  -H "Content-Type: application/json" \
  -d '{
    "room_url": "wss://yourproject.livekit.cloud/meeting",
    "deck_url": "https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/",
    "session_id": "550e8400-e29b-41d4-a716-446655440000"
  }'
```

Or using Daily.co:
```bash
curl -X POST https://slide-system-production-5813.up.railway.app/api/bots/screenshare/spawn \
  -H "Content-Type: application/json" \
  -d '{
    "room_url": "https://yourroom.daily.co/meeting",
    "deck_url": "https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/",
    "session_id": "550e8400-e29b-41d4-a716-446655440000"
  }'
```

Kill a bot:
```bash
curl -X POST https://slide-system-production-5813.up.railway.app/api/bots/screenshare/kill/{bot_id}
```

Check status:
```bash
curl https://slide-system-production-5813.up.railway.app/api/bots/screenshare/status/{bot_id}
```
### Direct Execution (Development)

Run the bot directly for testing:

```bash
python bot.py \
  "https://yourroom.daily.co/test" \
  "https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/" \
  "550e8400-e29b-41d4-a716-446655440000"
```

With custom inactivity timeout (5 minutes):

```bash
python bot.py \
  "https://yourroom.daily.co/test" \
  "https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/" \
  "550e8400-e29b-41d4-a716-446655440000" \
  "" \
  5
```

With meeting token (for private rooms):

```bash
python bot.py \
  "https://yourroom.daily.co/private" \
  "https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/" \
  "550e8400-e29b-41d4-a716-446655440000" \
  "your-meeting-token" \
  30
```

### Transport Configuration

The screenshare bot supports two transport backends via a pluggable architecture:

#### LiveKit (Recommended for Production)

```bash
export TRANSPORT_TYPE=livekit
export LIVEKIT_URL=wss://your-project.livekit.cloud
export LIVEKIT_API_KEY=your_api_key
export LIVEKIT_API_SECRET=your_api_secret
python bot.py <room_url> <deck_url> <session_id> <bot_id>
```

**Room URL format:** `wss://your-project.livekit.cloud` (room name extracted from bot parameters)

**Why LiveKit?**
- Better scalability and performance
- Lower latency
- More reliable connection handling
- Industry-standard WebRTC infrastructure

#### Daily.co

```bash
export TRANSPORT_TYPE=daily
export DAILY_PIPECAT_API_KEY=your_api_key
python bot.py <room_url> <deck_url> <session_id> <bot_id>
```

**Room URL format:** `https://your-domain.daily.co/room-name`

Both transports provide identical functionality:
- 10 FPS video streaming
- 1280x720 resolution
- Slide navigation via Supabase commands
- Graceful cleanup and error handling

### Environment Variables

Required environment variables:

```bash
# Transport Configuration
TRANSPORT_TYPE=daily  # Options: "daily" or "livekit"

# Daily.co Configuration (for TRANSPORT_TYPE=daily)
DAILY_PIPECAT_API_KEY=your_daily_api_key

# LiveKit Configuration (for TRANSPORT_TYPE=livekit)
LIVEKIT_URL=wss://your-project.livekit.cloud
LIVEKIT_API_KEY=your_livekit_api_key
LIVEKIT_API_SECRET=your_livekit_api_secret

# Supabase credentials (for slide control, required for both transports)
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_SERVICE_KEY=your_service_key
```

Create a `.env` file or set them in your deployment environment (Railway).

**Note:** Bot will run without Supabase credentials but slide control will be disabled.

## Architecture

```
┌─────────────────────────────────────────────┐
│          Screenshare Bot                    │
│                                             │
│  ┌─────────────┐      ┌─────────────────┐  │
│  │  Playwright │ ---> │  Screenshot     │  │
│  │   Browser   │      │  Capture Loop   │  │
│  │  (Headless) │      │  (10 FPS)       │  │
│  └─────────────┘      └────────┬────────┘  │
│                                 │           │
│                                 ↓           │
│                        ┌─────────────────┐  │
│                        │  PIL Image      │  │
│                        │  Processing     │  │
│                        │  (RGBA convert) │  │
│                        └────────┬────────┘  │
│                                 │           │
│                                 ↓           │
│                        ┌─────────────────┐  │
│                        │ Virtual Camera  │  │
│                        │ (Daily SDK)     │  │
│                        └────────┬────────┘  │
│                                 │           │
└─────────────────────────────────┼───────────┘
                                  │
                                  ↓
                        ┌─────────────────┐
                        │  Daily.co Room  │
                        │  (Video Stream) │
                        └─────────────────┘
```

## Configuration

### Frame Rate

- **Default:** 10 FPS (100ms per frame)
- **Low:** 5 FPS (200ms) - Lower CPU/bandwidth
- **High:** 15-20 FPS (50-67ms) - Smoother video

Trade-off: Higher FPS = smoother but more resource-intensive.

### Resolution

Currently fixed at **1280x720** (720p). This matches common video call resolutions and provides a good balance of quality and performance.

To change resolution, modify the browser viewport and camera device settings:

```python
# In start_screenshare()
self.browser = await self.playwright.chromium.launch(
    headless=True,
    args=['--window-size=1920,1080']  # Change here
)

context = await self.browser.new_context(
    viewport={'width': 1920, 'height': 1080}  # And here
)

# And camera device
self.camera_device = Daily.create_camera_device(
    "screenshare_camera",
    width=1920,  # And here
    height=1080,  # And here
    color_format="RGBA"
)
```

## Performance Considerations

### CPU Usage

- Screenshot capture: ~5-10% CPU per frame
- Image processing: ~2-5% CPU per frame
- Total: ~15-30% CPU at 10 FPS

### Memory

- Browser instance: ~200-300 MB
- Frame buffers: ~20-30 MB
- Total: ~250-350 MB

### Bandwidth

- 1280x720 @ 10 FPS: ~2-4 Mbps
- Video compression handled by Daily.co

## Integration with Backend

This bot can be spawned automatically by the backend API when a presentation is generated:

```python
# In backend API (when deck is generated)
import subprocess

deck_url = "https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/"
room_url = tavus_conversation_data['room_url']

# Spawn screenshare bot
subprocess.Popen([
    'python',
    'apps/slide-system/bots/screenshare-bot/screenshare_bot.py',
    room_url,
    deck_url
])
```

## Troubleshooting

### Bot joins but no video appears

1. Check that virtual camera was created successfully (look for log: "✅ Virtual camera created")
2. Verify camera is enabled in call (look for log: "✅ Camera enabled in call")
3. Check Daily.co room settings allow screen sharing

### High CPU usage

- Reduce frame rate: `fps=5` instead of `fps=10`
- Reduce resolution: Use 1024x576 instead of 1280x720

### Bot disconnects randomly

- Check network stability
- Ensure Daily.co room hasn't expired
- Check Daily API key is valid

### Browser fails to load deck

- Verify deck URL is accessible
- Check for JavaScript errors in deck
- Try with `headless=False` to see browser window

## Development

### Running in Development

For debugging, you can run the browser in headed mode:

```python
# Change in start_screenshare()
self.browser = await self.playwright.chromium.launch(
    headless=False,  # Show browser window
    args=['--window-size=1280,720']
)
```

### Logging

The bot uses Python's logging module. To increase verbosity:

```python
logging.basicConfig(
    level=logging.DEBUG,  # Show debug logs
    format='[%(asctime)s] %(levelname)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
```

## Testing

### Running Tests

The bot includes comprehensive test coverage for all components:

```bash
# Run all tests
cd apps/slide-system/bots/screenshare-bot
pytest

# Run specific test file
pytest tests/test_lifecycle_manager.py

# Run with verbose output
pytest -v -s

# Run specific test
pytest tests/test_lifecycle_integration.py::TestLifecycleIntegrationBasic::test_bot_starts_with_lifecycle_manager
```

### Test Coverage

1. **Unit Tests** - Individual component testing
   - `tests/test_lifecycle_manager.py` - Lifecycle manager (21 tests)
   - `tests/test_screenshot.py` - Screenshot capture
   - `tests/test_frame_processor.py` - Frame processing
   - `tests/test_slide_navigator.py` - Slide navigation
   - `tests/test_slide_control_listener.py` - Supabase listener

2. **Integration Tests** - Component interaction testing
   - `tests/test_lifecycle_integration.py` - End-to-end lifecycle tests
   - `tests/test_slide_control_integration.py` - Slide control integration

### Testing Lifecycle Features

#### Test Inactivity Timeout

Run bot with 1-minute timeout for testing:

```bash
python bot.py \
  "https://test.daily.co/room" \
  "https://example.com/deck/" \
  "test-session-id" \
  "" \
  1
```

Wait 1 minute and verify bot terminates with: `TERMINATING BOT: inactivity_timeout`

#### Test Manual Kill

```bash
# Terminal 1: Start bot
python bot.py <room> <deck> <session>

# Terminal 2: Get PID and send SIGTERM
ps aux | grep bot.py
kill -TERM <pid>

# Verify graceful shutdown in Terminal 1
```

#### Test Signal Handling

```bash
# Start bot
python bot.py <room> <deck> <session>

# Press Ctrl+C (sends SIGINT)
# Verify graceful shutdown with: TERMINATING BOT: signal_sigint
```

### Manual Testing After Deployment

Once deployed to Railway, perform these manual tests:

#### 1. Spawn API Test

```bash
# Spawn a bot
curl -X POST https://slide-system-production-5813.up.railway.app/api/bots/screenshare/spawn \
  -H "Content-Type: application/json" \
  -d '{
    "room_url": "https://yourroom.daily.co/test",
    "deck_url": "https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/",
    "session_id": "550e8400-e29b-41d4-a716-446655440000"
  }'

# Note the bot_id from response
```

**Expected:** Bot joins room within 5 seconds and starts streaming deck.

#### 2. Kill API Test
```bash
# Kill the bot
curl -X POST https://slide-system-production-5813.up.railway.app/api/bots/screenshare/kill/{bot_id}
```

**Expected:** Bot terminates within 2 seconds, disappears from Daily.co room, logs show "TERMINATING BOT: signal_sigterm".

#### 3. Status API Test
```bash
# Check bot status
curl https://slide-system-production-5813.up.railway.app/api/bots/screenshare/status/{bot_id}
```

**Expected:** Returns current status (spawning/running/stopping/stopped/error).

#### 4. Inactivity Timeout Test

```bash
# Spawn bot (defaults to 30 min timeout)
# Wait 30 minutes
# Check Railway logs
```

**Expected:** At exactly 30 minutes, bot logs "Inactivity timeout reached" and terminates cleanly.

#### 5. Browser Crash Recovery Test

```bash
# Spawn a bot
# Find Chromium process: ps aux | grep chromium
# Kill Chromium: kill -9 <chromium_pid>
# Watch Railway logs
```

**Expected:** Bot detects crash, logs "Browser crash detected", restarts browser, and continues streaming within 5 seconds.

#### 6. Concurrent Spawn Test

```bash
# Spawn 5 bots simultaneously
for i in {1..5}; do
  curl -X POST https://slide-system-production-5813.up.railway.app/api/bots/screenshare/spawn \
    -H "Content-Type: application/json" \
    -d "{
      \"room_url\": \"https://test.daily.co/room-$i\",
      \"deck_url\": \"https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/\",
      \"session_id\": \"session-$i\"
    }" &
done
wait
# Check all 5 bots are running
curl https://slide-system-production-5813.up.railway.app/api/bots/screenshare/status
```

**Expected:** All 5 bots spawn successfully, CPU usage ~75-150%, memory ~1-2GB, no errors.

#### 7. Resource Cleanup Test

```bash
# Before spawning
ssh railway-instance
ps aux | grep -E "(bot.py|chromium)" | wc -l

# Spawn 3 bots
# Kill all 3 bots
# Wait 10 seconds

# Check for zombie processes
ps aux | grep -E "(bot.py|chromium)" | wc -l
```

**Expected:** Process count returns to baseline (0 bot.py, 0 chromium), no zombie processes.

### Test Results Summary

From Task #116 implementation:

- **Lifecycle Manager Tests:** 21/21 passing
- **Integration Tests:** All passing
- **Browser Crash Recovery:** Validated in unit tests
- **Retry Logic:** Exponential backoff verified (1s, 2s, 4s)
- **Signal Handling:** SIGTERM/SIGINT tested
- **Resource Cleanup:** All resources freed on termination

## Related Files

- `tavus-tool-forwarder/bot.py` - Companion bot that listens for Tavus tool calls
- `../../src/routes/tavus-webhook-router.ts` - Backend webhook handler that spawns these bots

## Dynamic Deck URL Support

The bot supports dynamically generated deck URLs from the `/api/slidev/generate` endpoint, in addition to premade test deck URLs. This enables personalized presentation decks generated from conversation data.

### URL Validation Flow

When the bot starts, it validates the provided deck URL before beginning the stream:

1. **Validation Check**: Bot sends HTTP HEAD request to deck URL
2. **Status Check**: Verifies response status is 200 OK
3. **Timeout**: Validation times out after 5 seconds
4. **Fallback**: If validation fails, bot falls back to premade test deck
5. **Logging**: Bot logs which deck source is used for debugging

```python
from deck_url_validator import DeckURLValidator

# Validate deck URL
validator = DeckURLValidator()
is_valid = await validator.validate_url(deck_url)

if not is_valid:
    # Fall back to test deck
    deck_url = validator.get_fallback_deck_url()
```

### Supported URL Patterns

The bot supports multiple deck hosting patterns:

**GitHub Pages** (Primary):
```
https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/
https://buzztrail.github.io/buzztrail-presentations/session-abc123/
```

**Railway Hosting**:
```
https://slide-system-production-5813.up.railway.app/decks/session-xyz/
```

**Local Development**:
```
http://localhost:8080/
http://localhost:3030/session-123/
```

### Fallback Behavior

The bot implements a robust fallback strategy to ensure streaming continues even if deck generation fails:

1. **Primary**: Try provided deck URL first
2. **Fallback**: If validation fails (404, 500, timeout), use test deck
3. **Test Deck**: `https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/`
4. **Logging**: All fallback events are logged for debugging

**Fallback Triggers**:
- 404 Not Found (deck doesn't exist)
- 500 Server Error (generation failed)
- Network timeout (deck server unreachable)
- Connection errors (DNS, network issues)

### Runtime Deck URL Change

The bot supports changing the deck URL during an active session without restarting:

```python
# Change to new deck mid-session
await bot.change_deck_url(new_deck_url)
```

This enables:
- Switching between multiple presentation decks
- Updating to newly generated decks
- Recovering from failed deck loads

**Note**: New deck URL is validated before switching. If validation fails, the bot keeps the current deck.

### Integration with Slide Generation API

The bot integrates with the backend slide generation workflow:

```python
# Backend API workflow
# Step 1: Generate dynamic deck from conversation
response = await slidev_api.post('/api/slidev/generate', {
    'session_id': session_id,
    'conversation_data': conversation_data
})

dynamic_deck_url = response['slidev_url']
# Example: https://buzztrail.github.io/buzztrail-presentations/session-abc123/

# Step 2: Spawn screenshare bot with generated deck
await bot_api.post('/api/bots/screenshare/spawn', {
    'room_url': room_url,
    'deck_url': dynamic_deck_url,  # Use generated URL
    'session_id': session_id
})
```

### Performance Considerations

- **Validation Time**: HEAD request completes in < 1 second typically
- **Timeout**: 5 second timeout prevents hanging on slow servers
- **Deck Load Time**: Decks load within 5 seconds regardless of source
- **No Impact on FPS**: Validation runs once at startup, doesn't affect streaming

### Error Handling

The bot gracefully handles all deck URL errors:

| Error Type | Bot Response | User Impact |
|------------|--------------|-------------|
| Invalid URL | Fall back to test deck | Stream continues |
| 404 Not Found | Fall back to test deck | Stream continues |
| 500 Server Error | Fall back to test deck | Stream continues |
| Network Timeout | Fall back to test deck | Stream continues |
| Connection Error | Fall back to test deck | Stream continues |

All errors are logged for debugging:
```
[2025-10-11 18:30:15] WARNING: Deck URL invalid, falling back to test deck
[2025-10-11 18:30:15] INFO: Using deck URL: https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/
```

### Testing

Comprehensive tests are available in the `tests/` directory:

**Unit Tests** (`tests/test_deck_url_validator.py`):
- Valid URL validation (200 OK)
- Invalid URL handling (404, 500)
- Network timeout handling
- Fallback URL retrieval

**Integration Tests** (`tests/test_dynamic_deck_integration.py`):
- Bot with valid dynamic deck URL
- Bot with invalid URL falls back to test deck
- Runtime deck URL change
- Multiple dynamic deck URLs

Run tests with:
```bash
pytest tests/test_deck_url_validator.py -v
pytest tests/test_dynamic_deck_integration.py -v
```

## Future Enhancements

- [ ] Support for slide navigation commands (next/prev)
- [ ] Automatic slide advancement based on timing
- [ ] Audio narration support
- [ ] Recording capabilities
- [ ] Interactive pointer/annotation
- [ ] Lower latency with WebRTC direct streaming
- [ ] Deck URL health monitoring during session
- [ ] Multiple concurrent deck streams

## License

Part of the BuzzTrail project.
