> ## Documentation Index
> Fetch the complete documentation index at: https://docs.toughtongueai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Troubleshooting

> Common issues and solutions

Solutions to common issues when building with ToughTongue AI.

## Iframe Issues

<AccordionGroup>
  <Accordion title="Microphone not working" icon="microphone-slash">
    **Symptoms**: Microphone button is grayed out or not responding

    **Solutions**:

    1. **Ensure HTTPS**: Microphone access requires HTTPS in production
       * Use `http://localhost` for local development
       * Deploy to HTTPS-enabled hosting in production

    2. **Check Browser Permissions**:
       * Click the lock icon in the address bar
       * Ensure microphone permission is set to "Allow"

    3. **Verify iframe attributes**:
       ```html theme={null}
       <iframe
         src="..."
         allow="microphone"  ← Make sure this is present
       ></iframe>
       ```

    4. **Test in supported browsers**:
       * ✅ Chrome (recommended)
       * ✅ Firefox
       * ⚠️ Safari (limited support)
       * ❌ Internet Explorer (not supported)
  </Accordion>

  <Accordion title="Iframe not loading" icon="exclamation-triangle">
    **Symptoms**: Blank iframe or loading error

    **Solutions**:

    1. **Verify Scenario ID**: Check that your scenario ID is correct
       ```html theme={null}
       <!-- Wrong -->
       <iframe src=".../embed/abc123"></iframe>

       <!-- Right -->
       <iframe src=".../embed/YOUR_ACTUAL_SCENARIO_ID"></iframe>
       ```

    2. **Check is\_public setting**:
       * Scenario must have `is_public: true`
       * Check in dashboard or via API:
         ```javascript theme={null}
         const scenario = await fetch(`/api/scenarios/${id}`).then(r => r.json());
         console.log('is_public:', scenario.is_public);
         ```

    3. **Review browser console**:
       * Open DevTools (F12)
       * Check Console tab for errors
       * Look for CORS or CSP errors

    4. **Check Content Security Policy**:
       ```
       Content-Security-Policy: frame-src https://app.toughtongueai.com;
       ```
  </Accordion>

  <Accordion title="Events not firing" icon="bell-slash">
    **Symptoms**: Not receiving `onStart` or `onStop` events

    **Solutions**:

    1. **Verify origin check**:
       ```javascript theme={null}
       window.addEventListener('message', (event) => {
         // Don't be too strict with origin check during debugging
         console.log('Received from:', event.origin);
         
         if (event.origin !== 'https://app.toughtongueai.com') {
           console.warn('Origin mismatch!');
           // return;  // Comment out during debugging
         }
         
         console.log('Event data:', event.data);
       });
       ```

    2. **Check event listener timing**:
       * Ensure listener is set up before iframe loads
       * Or set up in `DOMContentLoaded` or `useEffect`

    3. **Verify iframe URL**:
       * Events only work with embed URLs
       * Not regular app URLs
  </Accordion>
</AccordionGroup>

## API Issues

<AccordionGroup>
  <Accordion title="401 Unauthorized" icon="lock">
    **Symptoms**: API returns 401 error

    **Solutions**:

    1. **Check Authorization header**:
       ```javascript theme={null}
       // Wrong
       headers: { 'Authorization': 'YOUR_TOKEN' }

       // Right
       headers: { 'Authorization': 'Bearer YOUR_TOKEN' }
       ```

    2. **Verify token is valid**:
       ```bash theme={null}
       curl -X POST https://api.toughtongueai.com/api/public/test \
         -H "Authorization: Bearer YOUR_TOKEN" \
         -H "Content-Type: application/json" \
         -d '{"message": "test"}'
       ```

    3. **Check token hasn't expired**:
       * Tokens don't expire by default
       * But can be manually revoked
       * Create a new token if needed

    4. **Ensure token is from correct environment**:
       * Development vs. production tokens
       * Organization-scoped tokens
  </Accordion>

  <Accordion title="CORS errors" icon="ban">
    **Symptoms**: CORS policy blocks request

    **Solutions**:

    1. **Use backend proxy** (recommended):
       ```javascript theme={null}
       // Frontend: Call your backend
       fetch('/api/analyze', { method: 'POST', body: ... });

       // Backend: Proxy to ToughTongue AI
       app.post('/api/analyze', async (req, res) => {
         const response = await fetch('https://api.toughtongueai.com/...', {
           headers: { 'Authorization': `Bearer ${process.env.TTAI_TOKEN}` }
         });
         res.json(await response.json());
       });
       ```

    2. **Never call API directly from frontend**:
       * ❌ Exposes your API token
       * ❌ CORS issues
       * ✅ Always use backend proxy
  </Accordion>

  <Accordion title="429 Rate limit exceeded" icon="gauge-high">
    **Symptoms**: Too many requests error

    **Solutions**:

    1. **Implement retry with backoff**:
       ```javascript theme={null}
       async function fetchWithRetry(url, options, maxRetries = 3) {
         for (let i = 0; i < maxRetries; i++) {
           const response = await fetch(url, options);
           
           if (response.status === 429) {
             const retryAfter = response.headers.get('Retry-After') || 60;
             await new Promise(resolve => 
               setTimeout(resolve, retryAfter * 1000)
             );
             continue;
           }
           
           return response;
         }
         throw new Error('Max retries exceeded');
       }
       ```

    2. **Cache responses**:
       * Cache scenario data (rarely changes)
       * Cache session analysis results
  </Accordion>
</AccordionGroup>

## Session Issues

<AccordionGroup>
  <Accordion title="Session not found" icon="search">
    **Symptoms**: 404 when fetching session

    **Solutions**:

    1. **Wait for session to be saved**:
       * Session may not be immediately available after `onStop`
       * Add a small delay (1-2 seconds) before fetching
    2. **Verify session ID**:
       * Check you're using the full session ID
       * Not a truncated version
    3. **Check permissions**:
       * Ensure API token has access to the session
       * Organization-scoped tokens may have limited access
  </Accordion>

  <Accordion title="Analysis not available" icon="chart-simple">
    **Symptoms**: Analysis endpoint returns empty or incomplete data

    **Solutions**:

    1. **Wait for analysis to complete**:
       * Analysis can take 5-30 seconds
       * Implement polling or show loading state
    2. **Check if analysis is restricted**:
       * Scenario may have `restrict_analysis: true`
       * Check scenario settings
    3. **Verify session completed**:
       * Session must be in "completed" status
       * Not "terminated" or "failed"
  </Accordion>
</AccordionGroup>

## Development Issues

<AccordionGroup>
  <Accordion title="Environment variables not loading" icon="gear">
    **Solutions**:

    1. **Check .env file location**:
       * Should be in project root
       * Not committed to git

    2. **Restart development server**:
       * Changes to .env require restart

    3. **Verify variable names**:
       ```bash theme={null}
       # Flask
       TTAI_TOKEN=...

       # Next.js
       TOUGH_TONGUE_API_KEY=...
       NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=...  # For client-side
       ```

    4. **Check loading method**:
       ```javascript theme={null}
       // Node.js
       require('dotenv').config();

       // Next.js (automatic in .env.local)
       process.env.TOUGH_TONGUE_API_KEY
       ```
  </Accordion>

  <Accordion title="Build errors" icon="code">
    **Flask**:

    * Check Python version: `python --version` (need 3.9+)
    * Reinstall dependencies: `pip install -r requirements.txt`
    * Check for conflicting packages

    **Next.js**:

    * Check Node version: `node --version` (need 18+)
    * Clear cache: `rm -rf .next node_modules pnpm-lock.yaml`
    * Reinstall: `pnpm install`
    * Check TypeScript errors: `pnpm build`
  </Accordion>
</AccordionGroup>

## Best Practices

<Check>Always use HTTPS in production</Check>
<Check>Verify iframe message origins</Check>
<Check>Store API tokens in environment variables</Check>
<Check>Use backend proxy for API calls</Check>
<Check>Implement proper error handling</Check>
<Check>Add loading states for async operations</Check>
<Check>Cache API responses when appropriate</Check>
<Check>Test in multiple browsers</Check>

## Still Having Issues?

<CardGroup cols={3}>
  <Card title="Discord Community" icon="discord" href="https://discord.com/invite/jfq2wVAP">
    Ask the community for help
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/overview">
    Test API endpoints
  </Card>

  <Card title="Email Support" icon="envelope" href="mailto:help@getarchieai.com">
    Contact our support team
  </Card>
</CardGroup>

## Debug Checklist

When debugging issues, gather this information:

* [ ] Browser and version
* [ ] Error messages from console
* [ ] Network tab showing failed requests
* [ ] Scenario ID being used
* [ ] API token validity (test endpoint)
* [ ] Environment (local, staging, production)
* [ ] Steps to reproduce the issue

Include this information when asking for help for faster resolution.
