# Voice Demo System - Complete Data Flow Architecture

**Created**: 2025-10-17
**Purpose**: Comprehensive documentation of data flows between all system components
**Status**: Initial draft - needs code verification

---

## System Components Overview

### 1. Frontend (voice-demo-ui)
- **Location**: Running on localhost:3006 (dev) or production URL
- **Tech**: Angular + LiveKit React Components
- **Purpose**: Customer-facing UI for voice demos

### 2. Supabase Edge Function
- **Name**: `create-demo-session`
- **Runtime**: Deno on Supabase Edge Network
- **Purpose**: Session creation and orchestration

### 3. slide-system API (Railway Service #1)
- **URL**: https://slide-system-production-5813.up.railway.app
- **Tech**: Motia framework (Express-based)
- **Purpose**: Backend API for sessions, slides, bot management

### 4. voice-agent-livekit (Railway Service #2)
- **Tech**: Python + LiveKit Agents SDK
- **Purpose**: AI voice agent with tool calling

### 5. Supabase Database
- **Type**: PostgreSQL with Realtime
- **Tables**:
  - `conversation_sessions`
  - `slidev_decks`
  - `slide_control_commands`
  - `active_bots`

### 6. LiveKit Cloud
- **URL**: wss://buzztrail-fifa4bj6.livekit.cloud
- **Purpose**: WebRTC rooms for voice/video/screenshare

---

## Flow 1: Session Creation & Initialization

### Scenario: Customer clicks "Start Demo" button

#### Step 1.1: Frontend → slide-system API
**API Call**: `POST /api/sessions/voice-demo`

**Request**:
```json
{
  "customerName": "John Doe",
  "customerEmail": "john@example.com",
  "deckId": "t8on-0e7p-3dou"
}
```

**Code Reference**: voice-demo-ui/src/services/sessionService.ts:25-77

#### Step 1.2: slide-system → Supabase Database
**Database Insert**: `conversation_sessions` table

```sql
INSERT INTO conversation_sessions (
  id,
  session_type,
  customer_name,
  customer_email,
  status,
  livekit_room_id,
  livekit_room_name,
  deck_id
) VALUES (
  'c335972a-eae9-4f10-bb20-f902762babb9',
  'voice_demo',
  'John Doe',
  'john@example.com',
  'initiating',
  'room_abc123',
  'happy-demo-a3f2',
  't8on-0e7p-3dou'
);
```

**Code Reference**: apps/slide-system/steps/voice-demo-session-create.step.ts:99-111

#### Step 1.3: slide-system → LiveKit Cloud
**API Call**: LiveKit CreateRoom + Generate Tokens

**Request to LiveKit**:
```typescript
// Create room
await livekitClient.createRoom({
  name: "happy-demo-a3f2",
  emptyTimeout: 600, // 10 minutes
  maxParticipants: 3
});

// Generate 3 tokens
const customerToken = new AccessToken(apiKey, apiSecret, {
  identity: 'customer-john-doe',
  grants: {
    roomJoin: true,
    room: 'happy-demo-a3f2',
    canPublish: true,
    canSubscribe: true
  },
  ttl: '6h'
});
```

**Code Reference**: apps/slide-system/steps/voice-demo-session-create.step.ts:121-166

#### Step 1.4: slide-system → Frontend
**Response**: `201 Created`

```json
{
  "sessionId": "c335972a-eae9-4f10-bb20-f902762babb9",
  "roomName": "happy-demo-a3f2",
  "customerToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "agentToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "screenshareToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "livekitUrl": "wss://buzztrail-fifa4bj6.livekit.cloud",
  "deckUrl": "https://buzztrail.github.io/buzztrail-presentations/t8on-0e7p-3dou/",
  "message": "Voice demo session created successfully"
}
```

**Code Reference**: apps/slide-system/steps/voice-demo-session-create.step.ts:56-288

#### Step 1.5: Frontend → LiveKit Cloud
**WebSocket Connection**: Customer joins room

```typescript
// Frontend connects to LiveKit
const room = new Room({
  adaptiveStream: true,
  dynacast: true
});

await room.connect(
  'wss://buzztrail-fifa4bj6.livekit.cloud',
  customerToken
);

// Enable audio
await room.localParticipant.setMicrophoneEnabled(true);
```

**Code Reference**: voice-demo-ui/src/app/app.tsx:100-149

---

## Flow 2: Voice Agent Initialization

### Scenario: System spawns AI voice agent for the session

#### Step 2.1: slide-system Triggers Agent Job
**Internal Job Queue**: Motia background worker

**Job Payload**:
```json
{
  "jobType": "spawn-voice-agent",
  "sessionId": "c335972a-eae9-4f10-bb20-f902762babb9",
  "roomName": "happy-demo-a3f2",
  "agentToken": "eyJhbGciOiJIUzI1NiIs...",
  "livekitUrl": "wss://buzztrail-fifa4bj6.livekit.cloud"
}
```

**Code Reference**: apps/slide-system/steps/voice-demo-session-create.step.ts:56-288

#### Step 2.2: voice-agent Process Starts
**Process**: Python script launched via Railway

**Environment Variables Loaded**:
```bash
LIVEKIT_URL=wss://buzztrail-fifa4bj6.livekit.cloud
LIVEKIT_API_KEY=APIXLYPswBShpTX
LIVEKIT_API_SECRET=rh0tLEEKMpMiRByvf9Ofd13Yih5oECg44rp0H0J0aBsv
SLIDE_API_BASE_URL=https://slide-system-production-5813.up.railway.app
```

**Code Reference**: apps/voice-agent-livekit/src/voice_agent_livekit/agent.py:393-433

#### Step 2.3: voice-agent → LiveKit Cloud
**Connection**: Agent joins room as participant

```python
from livekit.agents import JobRequest, WorkerOptions
from voice_agent_livekit.agent import VoiceAgent

async def entrypoint(ctx: JobContext):
    # Connect to room
    await ctx.connect()

    # Initialize agent with tools
    agent = VoiceAgent(
        conversation_manager=conversation,
        tools=[
            generate_deck_tool,
            next_slide_tool,
            previous_slide_tool,
            go_to_slide_tool
        ]
    )

    # Start listening
    await agent.start()
```

**Code Reference**: apps/voice-agent-livekit/src/voice_agent_livekit/agent.py:119-391

#### Step 2.4: voice-agent Updates Database
**Database Update**: `conversation_sessions` table

```sql
UPDATE conversation_sessions
SET
  status = 'presenting',
  agent_connected_at = NOW()
WHERE id = 'c335972a-eae9-4f10-bb20-f902762babb9';
```

**Code Reference**: apps/voice-agent-livekit/src/voice_agent_livekit/agent.py:119-391

---

## Flow 3: Screenshare Bot Initialization

### Scenario: System spawns screenshare bot to display slides

#### Step 3.1: slide-system Triggers Screenshare Job
**Internal Job Queue**: Motia background worker

**Job Payload**:
```json
{
  "jobType": "spawn-screenshare-bot",
  "sessionId": "c335972a-eae9-4f10-bb20-f902762babb9",
  "roomName": "happy-demo-a3f2",
  "screenshareToken": "eyJhbGciOiJIUzI1NiIs...",
  "livekitUrl": "wss://buzztrail-fifa4bj6.livekit.cloud",
  "deckUrl": "https://buzztrail.github.io/buzztrail-presentations/t8on-0e7p-3dou/"
}
```

**Code Reference**: apps/slide-system/steps/voice-demo-session-create.step.ts:56-288

#### Step 3.2: screenshare-bot Process Starts
**Process**: Python bot with Playwright

```python
from screenshare_bot.bot import ScreenshareBot
from screenshare_bot.transports import LiveKitTransport

bot = ScreenshareBot(
    transport=LiveKitTransport(
        room_url="wss://buzztrail-fifa4bj6.livekit.cloud",
        token=screenshare_token
    ),
    deck_url="https://buzztrail.github.io/buzztrail-presentations/t8on-0e7p-3dou/",
    deck_id="t8on-0e7p-3dou"
)

await bot.start()
```

**Code Reference**: apps/slide-system/bots/screenshare-bot/bot.py:72-100

#### Step 3.3: screenshare-bot → Supabase Realtime
**Subscription**: Listen for slide control commands

```python
def handle_slide_command(payload):
    command = payload['new']['command']
    slide_id = payload['new']['slide_id']

    if command == 'next':
        await navigate_next()
    elif command == 'prev':
        await navigate_prev()
    elif command == 'goto':
        await navigate_to_slide(slide_id)

supabase.channel('slide-control') \
    .on('postgres_changes',
        event='INSERT',
        schema='public',
        table='slide_control_commands',
        filter=f'deck_id=eq.{deck_id}',
        callback=handle_slide_command
    ) \
    .subscribe()
```

**Code Reference**: apps/slide-system/bots/screenshare-bot/bot.py:116-161

#### Step 3.4: screenshare-bot → LiveKit Cloud
**Video Stream**: Publish screenshare track

```python
# Capture screenshot with Playwright
screenshot = await page.screenshot()

# Convert to video frame
video_frame = OutputImageRawFrame(
    data=screenshot,
    width=1920,
    height=1080,
    format='RGBA'
)

# Send to LiveKit at 10 FPS
await transport.send_frame(video_frame)
```

**Code Reference**: apps/slide-system/bots/screenshare-bot/bot.py:255-356

---

## Flow 4: Voice Command Processing

### Scenario: Customer says "Create a presentation about AI"

#### Step 4.1: Customer → LiveKit Cloud
**Audio Stream**: WebRTC audio track

```
Customer speaks: "Create a presentation about artificial intelligence"
  ↓
Microphone captures audio
  ↓
WebRTC encodes to Opus
  ↓
Sent to LiveKit room via WebSocket
```

**Code Reference**: voice-demo-ui/src/app/app.tsx:100-149

#### Step 4.2: LiveKit Cloud → voice-agent
**Audio Stream**: Agent receives audio track

```python
# Agent receives audio frames
async def on_track_subscribed(track: RemoteAudioTrack):
    # Speech-to-text with Deepgram
    async for event in stt_stream:
        if event.is_final:
            text = event.alternatives[0].transcript
            # "Create a presentation about artificial intelligence"
            await process_utterance(text)
```

**Code Reference**: apps/voice-agent-livekit/src/voice_agent_livekit/agent.py:119-391

#### Step 4.3: voice-agent → OpenAI GPT-4
**LLM API Call**: Function calling

**Request to OpenAI**:
```json
{
  "model": "gpt-4-turbo",
  "messages": [
    {
      "role": "system",
      "content": "You are a helpful presentation assistant. Use tools to control slides and create presentations."
    },
    {
      "role": "user",
      "content": "Create a presentation about artificial intelligence"
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "generate_deck_tool",
        "description": "Generate a new slide deck on a given topic",
        "parameters": {
          "type": "object",
          "properties": {
            "topic": {"type": "string"},
            "slides_count": {"type": "integer", "default": 5},
            "style": {"type": "string", "default": "professional"}
          },
          "required": ["topic"]
        }
      }
    }
  ]
}
```

**Response from OpenAI**:
```json
{
  "choices": [
    {
      "message": {
        "tool_calls": [
          {
            "id": "call_abc123",
            "type": "function",
            "function": {
              "name": "generate_deck_tool",
              "arguments": "{\"topic\": \"artificial intelligence\", \"slides_count\": 5, \"style\": \"professional\"}"
            }
          }
        ]
      }
    }
  ]
}
```

**Code Reference**: apps/voice-agent-livekit/src/voice_agent_livekit/agent.py:119-391

#### Step 4.4: voice-agent Executes Tool
**Function Call**: `generate_deck_tool()`
# that is the wrong URL it just goes to the Motia workbench
```python
async def generate_deck_tool(
    conversation: ConversationManager,
    topic: str,
    **kwargs: Any
) -> str:
    logger.info(f"[Tool] generate_deck_tool called with topic: {topic}")

    async with httpx.AsyncClient(timeout=30.0) as client:
        response = await client.post(
            "https://slide-system-production-5813.up.railway.app/api/slidev/generate",
            json={
                "topic": topic,
                "slides_count": kwargs.get("slides_count", 5),
                "style": kwargs.get("style", "professional")
            }
        )

        if response.status_code == 200:
            data = response.json()
            return f"I've created a presentation about {topic}. The deck is ready and will appear on screen shortly."
        else:
            return "I encountered an error generating the presentation."
```

**Code Reference**: apps/voice-agent-livekit/src/voice_agent_livekit/tools/api_tools.py:23-64

#### Step 4.5: voice-agent → slide-system API
**HTTP Request**: `POST /api/slidev/generate`

**Request**:
```json
{
  "topic": "artificial intelligence",
  "slides_count": 5,
  "style": "professional"
}
```

**Code Reference**: apps/slide-system/steps/slidev-generate.step.ts:62-450

#### Step 4.6: slide-system → External AI Service
**Slide Generation**: Use AI to create slides

```typescript
// Generate slide content with AI
const slides = await generateSlidesWithAI({
  topic: "artificial intelligence",
  count: 5,
  style: "professional"
});

// Create Slidev markdown
const markdown = `
---
theme: default
---

# Artificial Intelligence

An overview of AI technologies

---

# What is AI?

- Machine learning algorithms
- Neural networks
- Deep learning
...
`;

// Save to GitHub repo
const deckId = generateDeckId(); // "ai-demo-x7k2"
await saveToGitHub(deckId, markdown);
```

**Code Reference**: apps/slide-system/steps/slidev-generate.step.ts:62-450

#### Step 4.7: slide-system → Supabase Database
**Insert Deck Record**: `slidev_decks` table

```sql
INSERT INTO slidev_decks (
  deck_id,
  session_id,
  deck_url,
  topic,
  created_at
) VALUES (
  'ai-demo-x7k2',
  'c335972a-eae9-4f10-bb20-f902762babb9',
  'https://buzztrail.github.io/buzztrail-presentations/ai-demo-x7k2/',
  'artificial intelligence',
  NOW()
);
```

**Code Reference**: apps/slide-system/steps/slidev-generate.step.ts:62-450

#### Step 4.8: slide-system → voice-agent
**HTTP Response**: `200 OK`

```json
{
  "success": true,
  "deck_id": "ai-demo-x7k2",
  "deck_url": "https://buzztrail.github.io/buzztrail-presentations/ai-demo-x7k2/",
  "message": "Deck generated successfully"
}
```

**Code Reference**: apps/slide-system/steps/slidev-generate.step.ts:62-450

#### Step 4.9: voice-agent → OpenAI GPT-4
**Tool Result**: Send function result back

```json
{
  "model": "gpt-4-turbo",
  "messages": [
    ...previous messages...,
    {
      "role": "tool",
      "tool_call_id": "call_abc123",
      "content": "I've created a presentation about artificial intelligence. The deck is ready and will appear on screen shortly."
    }
  ]
}
```

**Response from OpenAI**:
```json
{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "Great! I've created a 5-slide presentation about artificial intelligence. You should see it on your screen now."
      }
    }
  ]
}
```

**Code Reference**: apps/voice-agent-livekit/src/voice_agent_livekit/agent.py:119-391

#### Step 4.10: voice-agent → ElevenLabs TTS
**Text-to-Speech**: Convert response to audio

**Request**:
```json
{
  "text": "Great! I've created a 5-slide presentation about artificial intelligence. You should see it on your screen now.",
  "voice_id": "21m00Tcm4TlvDq8ikWAM",
  "model_id": "eleven_turbo_v2"
}
```

**Response**: Audio stream (MP3/PCM)

**Code Reference**: apps/voice-agent-livekit/src/voice_agent_livekit/agent.py:119-391

#### Step 4.11: voice-agent → LiveKit Cloud
**Audio Stream**: Send TTS audio to room

```python
# Convert TTS output to audio frames
audio_frame = AudioFrame(
    data=audio_bytes,
    sample_rate=16000,
    num_channels=1
)

# Send to LiveKit
await room.local_participant.publish_audio(audio_frame)
```

**Code Reference**: apps/voice-agent-livekit/src/voice_agent_livekit/agent.py:119-391

#### Step 4.12: LiveKit Cloud → Frontend
**Audio Stream**: Customer hears agent response

```
Agent audio arrives at frontend
  ↓
WebRTC decodes Opus to PCM
  ↓
Browser plays through speakers
  ↓
Customer hears: "Great! I've created a 5-slide presentation..."
```

**Code Reference**: voice-demo-ui/src/app/app.tsx:100-149

---

## Flow 5: Slide Navigation Command

### Scenario: Customer says "Go to the next slide"

#### Step 5.1: Customer → voice-agent
(Same as Flow 4.1 - 4.3: Audio → STT → LLM)

**OpenAI Response**:
```json
{
  "tool_calls": [
    {
      "function": {
        "name": "next_slide_tool",
        "arguments": "{}"
      }
    }
  ]
}
```

**Code Reference**: apps/voice-agent-livekit/src/voice_agent_livekit/agent.py:119-391

#### Step 5.2: voice-agent Executes Tool
**Function Call**: `next_slide_tool()`

```python
async def next_slide_tool(
    conversation: ConversationManager,
    **kwargs: Any
) -> str:
    logger.info("[Tool] next_slide_tool called")

    async with httpx.AsyncClient(timeout=10.0) as client:
        response = await client.post(
            "https://slide-system-production-5813.up.railway.app/api/slidev/control",
            json={"action": "next"}
        )

        if response.status_code == 200:
            return "Moving to the next slide."
        else:
            return "I couldn't navigate to the next slide."
```

**Code Reference**: apps/voice-agent-livekit/src/voice_agent_livekit/tools/api_tools.py:67-97

#### Step 5.3: voice-agent → slide-system API
**HTTP Request**: `POST /api/slidev/control`

**Request**:
```json
{
  "action": "next",
  "deckId": "ai-demo-x7k2",
  "sessionId": "c335972a-eae9-4f10-bb20-f902762babb9"
}
```

**Code Reference**: apps/slide-system/steps/slidev-control.step.ts:32-237

#### Step 5.4: slide-system → Supabase Database
**Insert Command**: `slide_control_commands` table

```sql
INSERT INTO slide_control_commands (
  id,
  deck_id,
  command,
  slide_id,
  timestamp,
  session_id
) VALUES (
  gen_random_uuid(),
  'ai-demo-x7k2',
  'next',
  NULL,
  NOW(),
  'c335972a-eae9-4f10-bb20-f902762babb9'
);
```

**Code Reference**: apps/slide-system/steps/slidev-control.step.ts:32-237

#### Step 5.5: Supabase Realtime → screenshare-bot
**Broadcast**: Realtime change notification

```javascript
// Supabase Realtime broadcasts to all subscribers
{
  "event": "INSERT",
  "schema": "public",
  "table": "slide_control_commands",
  "record": {
    "id": "cmd-uuid-123",
    "deck_id": "ai-demo-x7k2",
    "command": "next",
    "slide_id": null,
    "timestamp": "2025-10-17T06:45:00.000Z",
    "session_id": "c335972a-eae9-4f10-bb20-f902762babb9"
  }
}
```

**Code Reference**: apps/slide-system/bots/screenshare-bot/bot.py:116-161

#### Step 5.6: screenshare-bot Processes Command
**Navigation**: Playwright executes slide change

```python
async def handle_command(payload):
    command = payload['record']['command']

    if command == 'next':
        # Click next button or press arrow key
        await page.keyboard.press('ArrowRight')

        # Wait for animation
        await page.wait_for_timeout(500)

        # Capture new screenshot
        screenshot = await page.screenshot()

        # Send to LiveKit
        await send_frame_to_livekit(screenshot)
```

**Code Reference**: apps/slide-system/bots/screenshare-bot/bot.py:116-161

#### Step 5.7: screenshare-bot → LiveKit Cloud
**Video Frame**: Updated slide display

```python
# Capture current slide
screenshot_bytes = await page.screenshot(type='png')

# Convert to video frame
frame = OutputImageRawFrame(
    data=screenshot_bytes,
    width=1920,
    height=1080,
    format='RGBA'
)

# Send to LiveKit (10 FPS continuous)
await transport.send_frame(frame)
```

**Code Reference**: apps/slide-system/bots/screenshare-bot/bot.py:255-356

#### Step 5.8: LiveKit Cloud → Frontend
**Video Stream**: Customer sees new slide

```
LiveKit receives video frame
  ↓
Encodes as VP8/H.264
  ↓
Sends via WebRTC to frontend
  ↓
Frontend decodes and renders
  ↓
Customer sees slide 2 on screen
```

**Code Reference**: voice-demo-ui/src/app/app.tsx:100-149

---

## Flow 6: Session Cleanup & Termination

### Scenario: Customer clicks "End Call" button

#### Step 6.1: Frontend → LiveKit Cloud
**Disconnect**: Leave room

```typescript
// Frontend disconnects from room
await room.disconnect();

// Cleanup local tracks
room.localParticipant.tracks.forEach(track => {
  track.stop();
});
```

**Code Reference**: voice-demo-ui/src/hooks/useVoiceDemo.ts:38-112

#### Step 6.2: Frontend → slide-system API
**HTTP Request**: `POST /api/sessions/:sessionId/end`

**Request**:
```json
{
  "sessionId": "c335972a-eae9-4f10-bb20-f902762babb9",
  "endReason": "customer_ended"
}
```

**Code Reference**: apps/slide-system/steps/voice-demo-session-create.step.ts:56-288

#### Step 6.3: slide-system → Supabase Database
**Update Session**: Mark as completed

```sql
UPDATE conversation_sessions
SET
  status = 'completed',
  ended_at = NOW(),
  duration_seconds = EXTRACT(EPOCH FROM (NOW() - created_at))
WHERE id = 'c335972a-eae9-4f10-bb20-f902762babb9';
```

**Code Reference**: apps/slide-system/steps/voice-demo-session-create.step.ts:56-288

#### Step 6.4: slide-system → voice-agent
**Signal**: Terminate agent process

```python
# Agent receives disconnect signal
@agent.on('participant_disconnected')
async def on_customer_left(participant):
    logger.info(f"Customer {participant.identity} left")

    # Cleanup
    await agent.stop()
    await room.disconnect()

    # Exit process
    sys.exit(0)
```

**Code Reference**: apps/voice-agent-livekit/src/voice_agent_livekit/agent.py:119-391

#### Step 6.5: slide-system → screenshare-bot
**Signal**: Terminate bot process

```bash
# Send SIGTERM to bot process
kill -TERM <bot-pid>
```

**Bot cleanup**:
```python
async def cleanup():
    # Close Playwright browser
    await browser.close()

    # Disconnect from LiveKit
    await transport.disconnect()

    # Unsubscribe from Supabase
    await supabase.channel.unsubscribe()

    logger.info("Bot terminated cleanly")
```

**Code Reference**: apps/slide-system/bots/screenshare-bot/bot.py:72-100

#### Step 6.6: slide-system → LiveKit Cloud
**API Call**: Close room

```typescript
await livekitClient.deleteRoom('happy-demo-a3f2');
```

**Code Reference**: apps/slide-system/steps/voice-demo-session-create.step.ts:56-288

---

## Error Scenarios

### Scenario: Voice agent fails to connect

#### Detection:
```python
# Agent connection timeout after 30s
try:
    await asyncio.wait_for(ctx.connect(), timeout=30)
except asyncio.TimeoutError:
    logger.error("Failed to connect to LiveKit room")
    # Update database
    await mark_session_failed(session_id, "agent_connection_timeout")
```

**Recovery**:
1. Update session status to 'failed'
2. Notify frontend via WebSocket
3. Show error message to customer
4. Offer retry button

**Code Reference**: apps/voice-agent-livekit/src/voice_agent_livekit/agent.py:119-391

### Scenario: Screenshare bot crashes

#### Detection:
```python
# Bot process exits unexpectedly
@bot.on('error')
async def on_error(error):
    logger.error(f"Bot error: {error}")

    # Update active_bots table
    await supabase.table('active_bots').update({
        'status': 'failed',
        'error_message': str(error)
    }).eq('bot_id', bot_id).execute()
```

**Recovery**:
1. Automatic restart (up to 3 attempts)
2. Reconnect to same LiveKit room
3. Resume from current slide position

**Code Reference**: apps/slide-system/bots/screenshare-bot/bot.py:72-100

---

## Data Persistence

### Session Data
**Stored in**: `conversation_sessions` table

**Fields**:
- `id`: UUID primary key
- `session_type`: 'voice_demo'
- `customer_name`: From frontend input
- `customer_email`: From frontend input
- `status`: initiating → presenting → completed/abandoned/failed
- `livekit_room_id`: Room UUID from LiveKit
- `livekit_room_name`: Human-readable room name
- `deck_id`: Currently displayed deck
- `created_at`, `ended_at`, `duration_seconds`

**Code Reference**: apps/slide-system/steps/voice-demo-session-create.step.ts:99-111

### Slide Commands History
**Stored in**: `slide_control_commands` table

**Purpose**: Reconstruct current slide position from command history

**Example Query**:
```sql
-- Calculate current slide position
WITH command_history AS (
  SELECT command, slide_id
  FROM slide_control_commands
  WHERE deck_id = 'ai-demo-x7k2'
  ORDER BY timestamp ASC
)
SELECT
  CASE
    WHEN command = 'next' THEN LAG(position, 1, 1) + 1
    WHEN command = 'prev' THEN LAG(position, 1, 1) - 1
    WHEN command = 'goto' THEN slide_id
  END as current_position
FROM command_history;
```

**Code Reference**: apps/slide-system/steps/slidev-control.step.ts:32-237

---

## Environment Variables Reference

### Frontend (voice-demo-ui)
```bash
VITE_API_URL=https://slide-system-production-5813.up.railway.app
VITE_LIVEKIT_URL=wss://buzztrail-fifa4bj6.livekit.cloud
```

### slide-system (Railway)
```bash
SUPABASE_URL=https://dwdytxxqcvlrmyemonxz.supabase.co
SUPABASE_SERVICE_KEY=eyJhbGciOiJIUzI1NiIs...
LIVEKIT_URL=wss://buzztrail-fifa4bj6.livekit.cloud
LIVEKIT_API_KEY=APIXLYPswBShpTX
LIVEKIT_API_SECRET=rh0tLEEKMpMiRByvf9Ofd13Yih5oECg44rp0H0J0aBsv
SLIDEV_API_KEY=<optional-for-external-control>
```

### voice-agent-livekit (Railway)
```bash
LIVEKIT_URL=wss://buzztrail-fifa4bj6.livekit.cloud
LIVEKIT_API_KEY=APIXLYPswBShpTX
LIVEKIT_API_SECRET=rh0tLEEKMpMiRByvf9Ofd13Yih5oECg44rp0H0J0aBsv
SLIDE_API_BASE_URL=https://slide-system-production-5813.up.railway.app
OPENAI_API_KEY=<openai-key>
ELEVENLABS_API_KEY=<elevenlabs-key>
DEEPGRAM_API_KEY=<deepgram-key>
```

---

## Next Steps: Code Verification

This document needs verification by examining actual code:

### Files to verify:
1. **Frontend**:
   - [ ] Session creation call
   - [ ] LiveKit connection logic
   - [ ] End call handler

2. **slide-system API**:
   - [ ] POST /api/sessions/voice-demo endpoint
   - [ ] POST /api/slidev/generate endpoint
   - [ ] POST /api/slidev/control endpoint
   - [ ] GET /api/slidev/current/:deckId endpoint

3. **voice-agent-livekit**:
   - [ ] Agent entrypoint and initialization
   - [ ] Tool function implementations
   - [ ] OpenAI integration
   - [ ] TTS integration

4. **screenshare-bot**:
   - [ ] Bot initialization and connection
   - [ ] Supabase Realtime subscription
   - [ ] Command processing logic
   - [ ] Playwright navigation

5. **Supabase**:
   - [ ] Database schema definitions
   - [ ] Edge function implementation (if exists)
   - [ ] Realtime channel configuration

---

## Document Status

**Created**: 2025-10-17
**Last Updated**: 2025-10-17
**Status**: ✅ VERIFIED - Code references added
**Next Action**: Maintain and update as system evolves
