---
id: tavus-text-chat-integration
title: Tavus Text Chat Integration
status: draft
priority: P3
created: 2025-10-01
updated: 2025-10-01
author: Claude + Lars
tags: [tavus, chat, webrtc, ui, text-messaging]
related_prds: []
source_documents:
  - Archived planning document (TAVUS_INTEGRATION_STRATEGY.md Phase 2)
estimated_effort: M (3-4 weeks)
---

# PRD: Tavus Text Chat Integration

## Overview

Add real-time text chat capabilities to Tavus video conversations, enabling users to send text messages during video interactions and view conversation transcripts. This enhances the conversation experience by supporting mixed-mode communication (text + video) and provides context history when switching between modes.

## Problem Statement

### Current State
- **Video-only communication**: Tavus conversations only support voice/video
- **No text fallback**: Users cannot send text messages if audio/video fails
- **No transcript visibility**: Users cannot see real-time transcripts during conversation
- **Lost context on mode switch**: No way to preserve chat history when moving to video

### Pain Points
1. **Poor accessibility**: Users with audio issues can't communicate
2. **Missing context**: Starting video conversation loses prior text chat context
3. **No transcript access**: Users can't review what was said during video
4. **Limited interaction options**: Can't share links, code, or formatted text during video

### User Impact
- **End users**: Want to send text messages during video for links, clarifications, or when audio fails
- **Developers**: Need seamless text+video integration for demos and testing
- **Accessibility**: Text chat provides essential fallback for users with disabilities

## Goals & Success Criteria

### Primary Goals
1. **Real-time text messaging**: Send/receive text messages during Tavus video conversations
2. **Transcript integration**: Display real-time transcripts as chat messages
3. **Seamless mode switching**: Preserve context when switching between text and video
4. **Unified chat interface**: Single chat pane shows both text messages and transcripts

### Success Criteria
- [ ] **Text messaging works**: Users can send/receive text during video calls
- [ ] **Transcript display**: Real-time transcripts appear as chat bubbles
- [ ] **Context preservation**: Chat history carries over when starting video
- [ ] **<1 second latency**: Text messages delivered within 1 second
- [ ] **Visual distinction**: Clear UI difference between text and transcript messages

### Non-Goals
- Not building a standalone text-only chat system (video-first)
- Not implementing advanced chat features (reactions, threads, etc.)
- Not replacing the video conversation experience

## Requirements

### Functional Requirements

#### FR1: Real-Time Text Messaging
- **FR1.1**: Users MUST be able to send text messages during active Tavus conversations
- **FR1.2**: Text messages MUST be delivered via Daily.js WebRTC data channels
- **FR1.3**: Messages MUST appear in chat pane within 1 second of sending
- **FR1.4**: Support multi-line messages (up to 1000 characters)
- **FR1.5**: Messages MUST include sender role (user/replica/system)
- **FR1.6**: Messages MUST be timestamped with ISO 8601 format

#### FR2: Transcript Integration
- **FR2.1**: Real-time Tavus transcripts MUST appear as chat messages
- **FR2.2**: Transcript messages MUST be visually distinguished from text messages
- **FR2.3**: Users MUST be able to toggle transcript visibility on/off
- **FR2.4**: Transcripts MUST include confidence scores when available
- **FR2.5**: Support both real-time and post-conversation transcript display
- **FR2.6**: Transcript messages MUST indicate speaker (user/replica)

#### FR3: Context History
- **FR3.1**: MUST send prior text chat history to Tavus when starting video
- **FR3.2**: Chat history MUST be formatted as conversation context
- **FR3.3**: Support up to 50 messages of context history
- **FR3.4**: Context MUST include message role, text, and timestamp
- **FR3.5**: Failed context sends MUST NOT block video conversation start

#### FR4: Mode Switching
- **FR4.1**: Support seamless switching from text-only to text+video mode
- **FR4.2**: Preserve all text messages when transitioning to video
- **FR4.3**: Add final transcript to chat history when ending video
- **FR4.4**: UI MUST clearly indicate current mode (text-only vs text+video)
- **FR4.5**: Mode switch MUST NOT lose any chat history

#### FR5: Chat UI Components
- **FR5.1**: Single unified chat pane for all message types
- **FR5.2**: Text input field with send button
- **FR5.3**: Message bubbles with role-based styling (user/replica)
- **FR5.4**: Transcript toggle button in chat header
- **FR5.5**: Visual indicators for transcript messages (badge, styling)
- **FR5.6**: Auto-scroll to latest message
- **FR5.7**: Confidence score display for transcripts (optional)

### Non-Functional Requirements

#### NFR1: Performance
- **NFR1.1**: Message delivery latency MUST be <1 second (P95)
- **NFR1.2**: UI MUST remain responsive with 500+ messages
- **NFR1.3**: Context history send MUST complete within 2 seconds
- **NFR1.4**: Transcript updates MUST NOT impact video performance

#### NFR2: Reliability
- **NFR2.1**: Text messaging MUST work even if video fails
- **NFR2.2**: Failed message sends MUST retry up to 3 times
- **NFR2.3**: Message order MUST be preserved
- **NFR2.4**: System MUST handle network reconnections gracefully

#### NFR3: Accessibility
- **NFR3.1**: Chat pane MUST be keyboard navigable
- **NFR3.2**: Screen readers MUST announce new messages
- **NFR3.3**: Text contrast MUST meet WCAG AA standards
- **NFR3.4**: Support high contrast mode

#### NFR4: Usability
- **NFR4.1**: Chat interface MUST be intuitive (no training required)
- **NFR4.2**: Clear visual feedback for message sent/failed
- **NFR4.3**: Timestamp format MUST be human-readable
- **NFR4.4**: Transcript toggle MUST be easily discoverable

## Architecture & Design

### System Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                      BuzzTrail Widget                        │
│  ┌───────────────────────────────────────────────────────┐  │
│  │           Unified Chat Pane Component                 │  │
│  │  - Text messages (blue bubbles)                       │  │
│  │  - Transcript messages (gray bubbles with badge)      │  │
│  │  - Timestamp display                                  │  │
│  │  - Confidence scores                                  │  │
│  └───────────────────────────────────────────────────────┘  │
│                          │                                   │
│                          │                                   │
│  ┌───────────────────────▼───────────────────────────────┐  │
│  │        ConversationModeManager                        │  │
│  │  - Mode switching (text ↔ text+video)                │  │
│  │  - Context history management                         │  │
│  │  - Transcript integration                             │  │
│  └───────────────────────────────────────────────────────┘  │
│           │                                  │                │
│           ▼                                  ▼                │
│  ┌──────────────────┐           ┌───────────────────────┐   │
│  │ TavusWebRTC      │           │  Tavus Video Widget   │   │
│  │ Transport        │           │  (Daily.js)           │   │
│  │                  │◄──────────┤                       │   │
│  │ - sendMessage()  │  WebRTC   │  - app-message        │   │
│  │ - onMessage()    │  Data     │  - transcripts        │   │
│  │ - sendContext()  │  Channel  │                       │   │
│  └──────────────────┘           └───────────────────────┘   │
└─────────────────────────────────────────────────────────────┘
```

### Data Models

```typescript
// Enhanced ChatMessage with transcript support
export interface ChatMessage {
  id: string;                    // Unique message ID
  role: ChatRole;                // 'user' | 'replica' | 'system'
  text: string;                  // Message text content
  ts: number;                    // Timestamp (milliseconds)

  // Transcript-specific metadata
  transcriptData?: {
    isTranscript: boolean;       // Is this a transcript message?
    originalRole?: 'user' | 'replica' | 'system';
    confidence?: number;         // Speech recognition confidence (0-1)
    timestamp?: string;          // Original transcript timestamp
  };
}

// Transport interface for text communication
export interface TavusTextTransport extends ChatTransport {
  // Core messaging
  sendMessage(message: string): Promise<void>;
  onMessage(callback: (message: ChatMessage) => void): void;

  // Tavus-specific features
  startTavusConversation(conversationId: string): Promise<void>;
  sendContextHistory(messages: ChatMessage[]): Promise<void>;

  // Transcript management
  getConversationTranscript(conversationId: string): Promise<ChatMessage[]>;
  enableRealTimeTranscripts(): void;
  onTranscriptUpdate?: (messages: ChatMessage[]) => void;
  onTranscriptComplete?: (transcript: ChatMessage[]) => void;
}

// Mode manager interface
export interface ConversationMode {
  type: 'text-only' | 'text-video' | 'video-only';
  chatEnabled: boolean;
  videoEnabled: boolean;
  transcriptsEnabled: boolean;
}
```

### Key Components

#### TavusWebRTCTransport Implementation

```typescript
// apps/extension/src/services/tavus-webrtc-transport.ts

export class TavusWebRTCTransport implements TavusTextTransport {
  private dailyCall: DailyCall;
  private messageHandlers: Set<(message: ChatMessage) => void> = new Set();
  private transcriptHandlers: Set<(messages: ChatMessage[]) => void> = new Set();

  constructor(conversationUrl: string) {
    this.dailyCall = DailyIframe.createFrame();
    this.setupMessageHandling();
    this.setupTranscriptHandling();
  }

  private setupMessageHandling(): void {
    // Listen for app-message events from Daily.js
    this.dailyCall.on('app-message', (event) => {
      const message = this.parseAppMessage(event.data);
      this.messageHandlers.forEach(handler => handler(message));
    });
  }

  private setupTranscriptHandling(): void {
    // Listen for transcript events from Tavus
    this.dailyCall.on('app-message', (event) => {
      if (event.data.type === 'transcript-update') {
        const transcriptMessage = this.parseTranscript(event.data);
        this.messageHandlers.forEach(handler => handler(transcriptMessage));
      }
    });
  }

  async sendMessage(message: string): Promise<void> {
    await this.dailyCall.sendAppMessage({
      type: 'chat-message',
      text: message,
      timestamp: Date.now(),
      messageId: generateId()
    });
  }

  async sendContextHistory(messages: ChatMessage[]): Promise<void> {
    // Send chat history to Tavus for context
    await this.dailyCall.sendAppMessage({
      type: 'conversation-context',
      messages: messages.slice(-50).map(msg => ({
        role: msg.role,
        text: msg.text,
        timestamp: msg.ts
      }))
    });
  }

  onMessage(callback: (message: ChatMessage) => void): void {
    this.messageHandlers.add(callback);
  }

  enableRealTimeTranscripts(): void {
    // Enable transcript streaming from Tavus
    this.dailyCall.sendAppMessage({
      type: 'enable-transcripts',
      realtime: true
    });
  }

  private parseAppMessage(data: any): ChatMessage {
    return {
      id: data.messageId || generateId(),
      role: data.role || 'user',
      text: data.text,
      ts: data.timestamp || Date.now()
    };
  }

  private parseTranscript(data: any): ChatMessage {
    return {
      id: generateId(),
      role: data.speaker === 'user' ? 'user' : 'replica',
      text: data.text,
      ts: Date.now(),
      transcriptData: {
        isTranscript: true,
        originalRole: data.speaker,
        confidence: data.confidence,
        timestamp: data.timestamp
      }
    };
  }
}
```

#### ConversationModeManager Implementation

```typescript
// apps/extension/src/services/conversation-mode-manager.ts

export class ConversationModeManager {
  private chatTransport: TavusTextTransport;
  private videoWidget: BuzzTrailWidget;
  private currentMode: ConversationMode;
  private chatHistory: ChatMessage[] = [];

  async switchToVideoMode(): Promise<void> {
    // 1. Save current chat history
    this.chatHistory = await this.chatTransport.getChatHistory();

    // 2. Send context to Tavus before starting video
    await this.chatTransport.sendContextHistory(this.chatHistory);

    // 3. Start Tavus video conversation
    const conversationId = await this.videoWidget.startTavusConversation();

    // 4. Enable real-time transcripts
    this.chatTransport.enableRealTimeTranscripts();
    this.chatTransport.onTranscriptUpdate = (messages) => {
      this.displayTranscriptMessages(messages);
    };

    // 5. Update mode
    this.currentMode = {
      type: 'text-video',
      chatEnabled: true,
      videoEnabled: true,
      transcriptsEnabled: true
    };

    // 6. Update UI
    this.updateUIForVideoMode();
  }

  async switchToTextMode(): Promise<void> {
    // 1. End video conversation
    await this.videoWidget.endTavusConversation();

    // 2. Get final transcript
    const transcript = await this.chatTransport.getConversationTranscript();

    // 3. Add transcript to chat history
    this.addTranscriptToHistory(transcript);

    // 4. Update mode
    this.currentMode = {
      type: 'text-only',
      chatEnabled: true,
      videoEnabled: false,
      transcriptsEnabled: false
    };

    // 5. Update UI
    this.updateUIForTextMode();
  }

  private addTranscriptToHistory(transcript: ChatMessage[]): void {
    this.chatHistory.push(...transcript.map(msg => ({
      ...msg,
      transcriptData: { ...msg.transcriptData, isTranscript: true }
    })));
  }
}
```

#### EnhancedChatPane Component

```tsx
// apps/extension/src/components/EnhancedChatPane.tsx

export function EnhancedChatPane(props: EnhancedChatPaneProps): React.ReactElement {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [showTranscripts, setShowTranscripts] = useState(true);
  const [inputText, setInputText] = useState('');

  const filteredMessages = showTranscripts
    ? messages
    : messages.filter(msg => !msg.transcriptData?.isTranscript);

  const renderMessage = (message: ChatMessage) => {
    const isTranscript = message.transcriptData?.isTranscript;
    const confidence = message.transcriptData?.confidence;

    return (
      <div key={message.id} className={`bt-chat-msg ${message.role} ${isTranscript ? 'transcript' : ''}`}>
        <div className="bt-chat-bubble">
          {message.text}

          {isTranscript && (
            <div className="bt-transcript-indicator">
              <span className="bt-transcript-badge">Transcript</span>
              {confidence && (
                <span className="bt-confidence">{(confidence * 100).toFixed(1)}%</span>
              )}
            </div>
          )}

          <div className="bt-timestamp">
            {formatTimestamp(message.ts)}
          </div>
        </div>
      </div>
    );
  };

  const handleSendMessage = async () => {
    if (!inputText.trim()) return;

    await props.transport.sendMessage(inputText);
    setInputText('');
  };

  return (
    <div className="bt-chat">
      <div className="bt-chat-header">
        <button
          className="bt-transcript-toggle"
          onClick={() => setShowTranscripts(!showTranscripts)}
        >
          {showTranscripts ? 'Hide' : 'Show'} Transcripts
        </button>
      </div>

      <div className="bt-chat-messages">
        {filteredMessages.map(renderMessage)}
      </div>

      <div className="bt-chat-input">
        <textarea
          value={inputText}
          onChange={(e) => setInputText(e.target.value)}
          placeholder="Type a message..."
          maxLength={1000}
          rows={3}
        />
        <button onClick={handleSendMessage}>Send</button>
      </div>
    </div>
  );
}
```

## Implementation Plan

### Phase 1: WebRTC Transport Layer (Week 1)
**Goal**: Implement core text messaging over Daily.js

**Tasks**:
- [ ] Create TavusWebRTCTransport class
- [ ] Implement sendMessage() using Daily.js app-message
- [ ] Implement onMessage() event handler
- [ ] Add message serialization/deserialization
- [ ] Write unit tests for transport layer
- [ ] Test message delivery latency

**Deliverables**:
- Working text messaging over WebRTC
- Message latency <1 second
- Test suite with 80%+ coverage

### Phase 2: Chat UI Components (Week 2)
**Goal**: Build unified chat pane UI

**Tasks**:
- [ ] Create EnhancedChatPane component
- [ ] Implement message bubbles with role-based styling
- [ ] Add text input field with send button
- [ ] Implement auto-scroll to latest message
- [ ] Add timestamp formatting
- [ ] Style transcript messages differently
- [ ] Add transcript toggle button
- [ ] Test UI with 500+ messages

**Deliverables**:
- Fully functional chat UI
- Visual distinction for transcripts
- Responsive with large message counts

### Phase 3: Transcript Integration (Week 2-3)
**Goal**: Integrate Tavus transcripts into chat

**Tasks**:
- [ ] Implement transcript event handling in transport
- [ ] Add transcriptData to ChatMessage interface
- [ ] Implement enableRealTimeTranscripts()
- [ ] Add confidence score display
- [ ] Implement getConversationTranscript()
- [ ] Test transcript display in chat pane

**Deliverables**:
- Real-time transcript display
- Post-conversation transcript retrieval
- Confidence score visualization

### Phase 4: Mode Switching & Context (Week 3)
**Goal**: Enable seamless mode transitions

**Tasks**:
- [ ] Create ConversationModeManager class
- [ ] Implement switchToVideoMode()
- [ ] Implement switchToTextMode()
- [ ] Add context history sending
- [ ] Implement chat history preservation
- [ ] Add UI mode indicators
- [ ] Test mode switching flows

**Deliverables**:
- Seamless text↔video switching
- Context preservation working
- Clear UI mode indicators

### Phase 5: Testing & Polish (Week 4)
**Goal**: Ensure production quality

**Tasks**:
- [ ] End-to-end testing of all flows
- [ ] Performance testing (latency, large messages)
- [ ] Accessibility audit (keyboard nav, screen readers)
- [ ] Error handling improvements
- [ ] Documentation and examples
- [ ] User acceptance testing

**Deliverables**:
- Production-ready feature
- Complete documentation
- Accessibility compliance

## Testing Strategy

### Unit Tests
- TavusWebRTCTransport message sending/receiving
- ChatMessage serialization/deserialization
- ConversationModeManager mode transitions
- Message filtering and display logic

### Integration Tests
- Full text messaging flow (send → receive → display)
- Transcript integration (receive → parse → display)
- Context history sending on video start
- Mode switching with history preservation

### E2E Tests
- Text-only conversation flow
- Text→video mode switch with context
- Video conversation with real-time transcripts
- Transcript visibility toggle

### Performance Tests
- Message delivery latency (<1 second)
- UI responsiveness with 500+ messages
- Context history send time (<2 seconds)

## Security Considerations

- **Message validation**: Sanitize all text messages to prevent XSS
- **Rate limiting**: Limit message send rate to prevent spam
- **Content filtering**: Optional profanity/content filtering
- **PII handling**: Ensure transcript data doesn't leak sensitive info

## Risks & Mitigations

| Risk | Impact | Mitigation |
|------|--------|------------|
| Daily.js app-message not reliable | High | Add retry logic, fallback to HTTP polling |
| Transcript API changes | Medium | Version API calls, handle gracefully |
| Message order not preserved | Medium | Add sequence numbers, reorder on client |
| High transcript latency | Low | Buffer transcripts, batch updates |
| Poor mobile UX for text input | Medium | Test on mobile, optimize input sizing |

## Open Questions

- [ ] Should we support rich text formatting (bold, links, etc.)?
  - **Recommendation**: Start with plain text, add formatting in v2
- [ ] How to handle very long transcripts (1000+ messages)?
  - **Recommendation**: Paginate, lazy load older messages
- [ ] Should transcript messages be editable/deletable?
  - **Recommendation**: No, transcripts are immutable records
- [ ] How to indicate typing status (user is typing...)?
  - **Recommendation**: Out of scope for v1

## Metrics & Monitoring

### Key Metrics
- **Message delivery latency**: P50, P95, P99
- **Message delivery success rate**: % of messages delivered
- **Transcript accuracy**: User-reported issues
- **Mode switch success rate**: % of successful transitions

### Alerts
- Message delivery latency >5 seconds (warning)
- Message delivery success rate <95% (critical)
- Transcript errors >10/hour (warning)

## Documentation Requirements

- [ ] TavusWebRTCTransport API reference
- [ ] ConversationModeManager usage guide
- [ ] Chat UI component documentation
- [ ] Integration guide for widget developers
- [ ] Troubleshooting guide

## Success Validation

### Week 2 Checkpoint
- [ ] Basic text messaging working
- [ ] Chat UI fully functional
- [ ] No critical bugs

### Week 3 Checkpoint
- [ ] Transcript integration complete
- [ ] Mode switching working
- [ ] Developer feedback positive

### Week 4 Completion
- [ ] All tests passing
- [ ] Documentation complete
- [ ] Production deployment ready
- [ ] User acceptance testing passed

---

**Status**: Draft
**Next Steps**: Review with team, validate Daily.js app-message capabilities, begin Phase 1 implementation
