# Stream D Integration Guide

## Overview

Stream D provides session launcher, error handling, and device detection components for the Voice Demo UI. This guide shows how to integrate Stream D with Streams A, B, and C.

## Quick Start

### Basic Usage

```tsx
import { VoiceDemoLauncher } from './components/VoiceDemoLauncher';
import { LiveKitTokens } from './types';

function App() {
  const [tokens, setTokens] = useState<LiveKitTokens | null>(null);

  if (!tokens) {
    return (
      <VoiceDemoLauncher
        onSessionCreated={setTokens}
        showDeckIdInput={true}
      />
    );
  }

  // Session created, show LiveKit room (Stream B) and Voice Interface (Stream C)
  return <VoiceInterface tokens={tokens} />;
}
```

## Components

### 1. VoiceDemoLauncher

Main entry point for creating a voice demo session.

```tsx
import { VoiceDemoLauncher } from './components';

<VoiceDemoLauncher
  defaultDeckId="my-deck-123"
  onSessionCreated={(tokens) => {
    console.log('Session ready!', tokens);
    // Navigate to voice interface
  }}
  onTextOnlyMode={() => {
    console.log('User chose text-only mode');
    // Show text-only interface
  }}
  showDeckIdInput={true}
/>
```

**Props**:
- `defaultDeckId?: string` - Pre-populate deck ID field
- `onSessionCreated?: (tokens: LiveKitTokens) => void` - Called on success
- `onTextOnlyMode?: () => void` - Called when user chooses text fallback
- `showDeckIdInput?: boolean` - Show optional input form

### 2. ErrorScreen

Display user-friendly error messages with retry options.

```tsx
import { ErrorScreen } from './components';

<ErrorScreen
  error={new Error('Failed to create session')}
  onRetry={() => console.log('User clicked retry')}
  onDismiss={() => console.log('User dismissed error')}
  supportEmail="support@example.com"
/>
```

**Variants**:
- `ErrorScreen` - Generic error display
- `NetworkErrorScreen` - Network-specific errors with tips
- `ServerUnavailableScreen` - Server errors with countdown

### 3. PermissionPrompt

Request microphone permissions with browser-specific instructions.

```tsx
import { PermissionPrompt } from './components';

<PermissionPrompt
  onPermissionGranted={() => {
    console.log('Microphone access granted');
    // Continue to session creation
  }}
  onPermissionDenied={() => {
    console.log('Microphone access denied');
    // Show error or fallback
  }}
  onTextOnlyMode={() => {
    console.log('User chose text-only');
    // Switch to text interface
  }}
  showTextOnlyFallback={true}
/>
```

## Hooks

### useErrorRecovery

Automatic error recovery with retry logic.

```tsx
import { useErrorRecovery } from './hooks';
import { createVoiceSession } from './services/sessionService';

function MyComponent() {
  const { executeWithRetry, state, manualRetry } = useErrorRecovery({
    maxRetries: 3,
    retryDelays: [1000, 2000, 4000],
  });

  const handleCreateSession = async () => {
    try {
      const tokens = await executeWithRetry(() => createVoiceSession());
      console.log('Session created!', tokens);
    } catch (error) {
      console.error('Failed after retries:', error);
    }
  };

  return (
    <div>
      <button onClick={handleCreateSession}>Create Session</button>
      {state.isRetrying && <p>Retrying ({state.retryCount}/{state.maxRetries})...</p>}
      {state.lastError && state.canRetry && (
        <button onClick={manualRetry}>Try Again</button>
      )}
    </div>
  );
}
```

**Specialized Variants**:
- `useSessionErrorRecovery()` - For session creation (3 retries, manual)
- `useConnectionErrorRecovery()` - For WebRTC (5 retries, auto)

## Utils

### Device Detection

```tsx
import { getDeviceCapabilities, validateEnvironment } from './utils';

// Validate environment on app load
try {
  validateEnvironment();
} catch (error) {
  console.error('Environment not supported:', error);
  // Show error screen
}

// Check device capabilities
const capabilities = await getDeviceCapabilities();
console.log('Browser:', capabilities.browserInfo.name);
console.log('Microphone:', capabilities.hasMicrophone);
console.log('WebRTC:', capabilities.browserInfo.supportsWebRTC);
```

### Error Handling

```tsx
import { classifyError, formatErrorForDisplay, retryWithBackoff } from './utils';

// Classify an error
const classified = classifyError(error);
console.log('Error type:', classified.type); // 'network' | 'permission' | etc.
console.log('Can retry:', classified.isRetryable);

// Format for display
const formatted = formatErrorForDisplay(error);
console.log('Title:', formatted.title);
console.log('Message:', formatted.message);

// Retry with backoff
try {
  const result = await retryWithBackoff(
    () => fetch('/api/endpoint'),
    3, // max attempts
    [1000, 2000, 4000], // delays
    (attempt) => console.log(`Retry attempt ${attempt}`)
  );
} catch (error) {
  console.error('All retries failed');
}
```

## Integration Patterns

### Pattern 1: Simple Launcher

Minimal setup - just launch and handle success.

```tsx
function App() {
  const [tokens, setTokens] = useState<LiveKitTokens | null>(null);

  return tokens ? (
    <VoiceInterface tokens={tokens} />
  ) : (
    <VoiceDemoLauncher onSessionCreated={setTokens} />
  );
}
```

### Pattern 2: With Custom Error Handling

Handle errors with custom logic.

```tsx
function App() {
  const [tokens, setTokens] = useState<LiveKitTokens | null>(null);
  const [error, setError] = useState<Error | null>(null);
  const { executeWithRetry, state } = useErrorRecovery();

  const handleLaunch = async (config: VoiceSessionConfig) => {
    try {
      const result = await executeWithRetry(() => createVoiceSession(config));
      setTokens(result);
    } catch (err) {
      setError(err as Error);
    }
  };

  if (error) {
    return <ErrorScreen error={error} onRetry={() => setError(null)} />;
  }

  if (tokens) {
    return <VoiceInterface tokens={tokens} />;
  }

  return <VoiceDemoLauncher onSessionCreated={setTokens} />;
}
```

### Pattern 3: With Permission Flow

Explicit permission handling before launch.

```tsx
function App() {
  const [stage, setStage] = useState<'permission' | 'launcher' | 'session'>('permission');
  const [tokens, setTokens] = useState<LiveKitTokens | null>(null);

  if (stage === 'permission') {
    return (
      <PermissionPrompt
        onPermissionGranted={() => setStage('launcher')}
        onPermissionDenied={() => console.log('Permission denied')}
        onTextOnlyMode={() => console.log('Text mode')}
      />
    );
  }

  if (stage === 'launcher') {
    return (
      <VoiceDemoLauncher
        onSessionCreated={(t) => {
          setTokens(t);
          setStage('session');
        }}
      />
    );
  }

  return <VoiceInterface tokens={tokens!} />;
}
```

### Pattern 4: With Device Validation

Validate device capabilities before showing launcher.

```tsx
function App() {
  const [capabilities, setCapabilities] = useState<DeviceCapabilities | null>(null);
  const [tokens, setTokens] = useState<LiveKitTokens | null>(null);

  useEffect(() => {
    // Validate environment
    try {
      validateEnvironment();
    } catch (error) {
      console.error('Environment validation failed:', error);
      return;
    }

    // Check device capabilities
    getDeviceCapabilities().then(setCapabilities);
  }, []);

  if (!capabilities) {
    return <div>Checking device capabilities...</div>;
  }

  if (!capabilities.browserInfo.supportsWebRTC) {
    return (
      <ErrorScreen
        error={new Error('WebRTC not supported')}
        onDismiss={() => console.log('Dismissed')}
      />
    );
  }

  if (!capabilities.hasMicrophone) {
    return (
      <PermissionPrompt
        onPermissionGranted={() => {
          // Refresh capabilities
          getDeviceCapabilities().then(setCapabilities);
        }}
        onPermissionDenied={() => console.log('Denied')}
      />
    );
  }

  return tokens ? (
    <VoiceInterface tokens={tokens} />
  ) : (
    <VoiceDemoLauncher onSessionCreated={setTokens} />
  );
}
```

## Error Scenarios

Stream D handles these error scenarios:

1. **Network Errors** → `NetworkErrorScreen` with troubleshooting tips
2. **Permission Errors** → `PermissionPrompt` with browser instructions
3. **Server Errors** → `ServerUnavailableScreen` with retry countdown
4. **WebRTC Errors** → Automatic retry with exponential backoff
5. **Validation Errors** → `ErrorScreen` with clear message
6. **Unknown Errors** → `ErrorScreen` with generic message and details

## Testing

### Manual Testing Checklist

- [ ] Launch demo without inputs → Creates session
- [ ] Launch with deck ID → Passes to API
- [ ] Network failure → Shows NetworkErrorScreen
- [ ] Permission denied → Shows PermissionPrompt
- [ ] Server error → Shows ErrorScreen with retry
- [ ] Retry button → Executes manual retry
- [ ] Device status → Shows correct indicators
- [ ] Browser detection → Shows correct name/version
- [ ] HTTPS validation → Blocks non-HTTPS (except localhost)
- [ ] Text-only fallback → Calls onTextOnlyMode

### Simulating Errors

```tsx
// Simulate network error
const mockCreateSession = () => {
  throw new Error('fetch failed');
};

// Simulate permission error
const mockCreateSession = () => {
  throw new Error('Permission denied');
};

// Simulate server error
const mockCreateSession = () => {
  throw new Error('HTTP 500: Internal Server Error');
};
```

## TypeScript Types

All components and utilities are fully typed:

```tsx
import type {
  VoiceDemoLauncherProps,
  ErrorScreenProps,
  PermissionPromptProps,
  ErrorRecoveryState,
  UseErrorRecoveryReturn,
  DeviceCapabilities,
  BrowserInfo,
  ClassifiedError,
  FormattedError,
} from './components';
```

## Next Steps

1. **Import VoiceDemoLauncher** into your main App component
2. **Handle onSessionCreated** to receive LiveKit tokens
3. **Pass tokens to VoiceInterface** (Stream C) to start voice interaction
4. **Handle errors** with the provided error screens
5. **Customize** the launcher with your branding and copy

## Support

For issues or questions:
- Check the progress doc: `.claude/epics/voice-slide-show-livekit/updates/147/stream-D.md`
- Review error handling utils: `src/utils/errorHandling.ts`
- Check device detection: `src/utils/deviceDetection.ts`
