# User ID Priority System for LiveKit Agent

This guide explains how the LiveKit agent determines which user ID to use, with multiple fallback options for maximum flexibility.

## 🎯 **Priority Order**

The LiveKit agent checks for user ID in the following order:

1. **Participant Metadata** (Highest Priority)
2. **Room Metadata**
3. **Random Generation** (Fallback)

## 📋 **Detailed Priority System**

### **1. Participant Metadata (Priority 1)**

The agent first checks if any participant has user ID in their metadata:

```python
# In participant metadata (JSON)
{
    "userId": "user_1704067200000_abc123def456",
    "source": "chrome_extension",
    "capabilities": ["browser_automation"]
}
```

**How to set:**

```python
# When creating access token
token = api.AccessToken(api_key, api_secret)
    .with_metadata(json.dumps({"userId": "user_1704067200000_abc123"}))
    .to_jwt()

# Or update after connection
await room.local_participant.update_metadata(
    json.dumps({"userId": "user_1704067200000_abc123"})
)
```

### **2. Room Metadata (Priority 2)**

If no participant metadata found, checks room metadata:

```python
# In room metadata (JSON)
{
    "userId": "user_1704067200000_abc123def456",
    "createdBy": "chrome_extension",
    "timestamp": 1704067200000
}
```

**How to set:**

```python
# When creating room
await livekit_api.room.create_room(
    api.CreateRoomRequest(
        name="my-room",
        metadata=json.dumps({"userId": "user_1704067200000_abc123"})
    )
)
```

### **3. Random Generation (Fallback)**

If none of the above methods provide a user ID, generates a random one:

```python
# Format: user_{timestamp}_{random}
# Example: user_1704067200000_xyz789abc123
```

## 🔧 **Implementation Examples**

### **Chrome Extension Integration**

```javascript
// Chrome extension sends user ID via WebSocket
const connectionInfo = {
  type: 'connection_info',
  userId: 'user_1704067200000_abc123def456',
  userAgent: navigator.userAgent,
  timestamp: Date.now(),
  extensionId: chrome.runtime.id,
};

// Remote server creates LiveKit room with user ID in metadata
const roomMetadata = {
  userId: connectionInfo.userId,
  source: 'chrome_extension',
};
```

### **LiveKit Agent Manager**

```typescript
// Remote server spawns agent with user ID in environment
const agentProcess = spawn('python', ['livekit_agent.py', 'start'], {
  env: {
    ...process.env,
    CHROME_USER_ID: userId, // Priority 4
    LIVEKIT_URL: this.liveKitConfig.livekit_url,
    LIVEKIT_API_KEY: this.liveKitConfig.api_key,
    LIVEKIT_API_SECRET: this.liveKitConfig.api_secret,
  },
});
```

### **Direct LiveKit Room Creation**

```python
# Create room with user ID in metadata (Priority 2)
room = await livekit_api.room.create_room(
    api.CreateRoomRequest(
        name=f"mcp-chrome-user-{user_id}",  # Priority 3
        metadata=json.dumps({"userId": user_id})  # Priority 2
    )
)
```

## 🎮 **Usage Scenarios**

### **Scenario 1: Chrome Extension User**

1. Chrome extension generates user ID: `user_1704067200000_abc123`
2. Connects to remote server with user ID
3. Remote server creates room: `mcp-chrome-user-user_1704067200000_abc123`
4. Agent extracts user ID from room name (Priority 3)

### **Scenario 2: Direct LiveKit Integration**

1. Application creates room with user ID in metadata
2. Agent reads user ID from room metadata (Priority 2)
3. Uses provided user ID for session management

### **Scenario 3: Manual Agent Spawn**

1. Set `CHROME_USER_ID` environment variable
2. Start agent manually
3. Agent uses environment variable (Priority 4)

### **Scenario 4: Participant Metadata**

1. Client joins with user ID in participant metadata
2. Agent reads from participant metadata (Priority 1)
3. Highest priority - overrides all other sources

## 🔍 **Debugging User ID Resolution**

The agent logs which method was used:

```
✅ Using user ID from metadata: user_1704067200000_abc123
🔗 Using user ID from room name: user_1704067200000_abc123
🌍 Using user ID from environment: user_1704067200000_abc123
⚠️ No Chrome user ID detected, using random session
```

## 📝 **Best Practices**

1. **Use Participant Metadata** for dynamic user identification
2. **Use Room Metadata** for persistent room-based user association
3. **Use Room Name Pattern** for Chrome extension integration
4. **Use Environment Variable** for development and testing
5. **Random Generation** ensures the system always works

## 🚨 **Important Notes**

- User IDs should follow format: `user_{timestamp}_{random}`
- Metadata must be valid JSON
- Environment variables are set when agent starts
- Room name pattern is automatically detected
- Random generation ensures no session fails due to missing user ID

## 🔄 **Migration Guide**

If you're updating from a system that only used environment variables:

1. **No changes needed** - environment variable still works (Priority 4)
2. **Optional**: Add user ID to room/participant metadata for better integration
3. **Recommended**: Use room name pattern for Chrome extension compatibility
