# Manual CAPTCHA Interaction Guide

## Overview
The trading bot now supports manual CAPTCHA interaction when TradingView presents robot verification challenges. This allows you to manually solve CAPTCHAs while the automation continues.

## How It Works

### 1. Configuration
- **Environment Variable**: `ALLOW_MANUAL_CAPTCHA=true` (already configured in docker-compose.yml)
- **Display**: X11 forwarding is enabled for browser display
- **Browser Mode**: When CAPTCHA is detected, browser switches from headless to visible mode

### 2. Manual CAPTCHA Flow

#### Step 1: Trigger Analysis
Click the "Analyse" button in the UI, or use the test endpoint:
```bash
curl -X POST http://localhost:3000/api/test-captcha
```

#### Step 2: Automatic CAPTCHA Detection
The system will:
- Navigate to TradingView login page
- Fill in credentials automatically
- Detect CAPTCHA challenge
- Switch to manual intervention mode

#### Step 3: Manual Intervention Window
When CAPTCHA is detected, you'll see:
- Console messages indicating manual intervention is needed
- A browser window should appear on your desktop
- Instructions in the logs

#### Step 4: Solve CAPTCHA Manually
1. **Find the browser window** (should be visible on your desktop)
2. **Click the "I am not a robot" checkbox**
3. **Complete any additional challenges** (image selection, etc.)
4. **Do NOT click the login button** - automation handles this
5. **Wait for confirmation** in the logs

#### Step 5: Automation Continues
- System checks every 5 seconds if CAPTCHA is solved
- Once solved, automation continues with login
- Screenshots and analysis proceed normally

### 3. Troubleshooting

#### Browser Window Not Appearing?
```bash
# Check X11 forwarding
echo $DISPLAY
xhost +local:docker

# Verify Docker configuration
docker compose logs app --tail=10
```

#### CAPTCHA Still Failing?
- Check console logs for specific error messages
- Ensure you completed ALL CAPTCHA challenges
- Try refreshing and starting over
- Consider using a different IP/VPN if repeatedly challenged

#### Timeout Issues?
- Default timeout is 5 minutes for manual intervention
- Logs will show countdown of remaining time
- If timeout occurs, restart the process

### 4. Test Endpoints

#### Check Configuration
```bash
curl http://localhost:3000/api/test-captcha
```

#### Trigger Manual CAPTCHA Test
```bash
curl -X POST http://localhost:3000/api/test-captcha
```

### 5. Environment Variables

```bash
# Enable manual CAPTCHA support
ALLOW_MANUAL_CAPTCHA=true

# Display for X11 forwarding
DISPLAY=:0

# TradingView credentials (in .env file)
TRADINGVIEW_EMAIL=your_email@example.com
TRADINGVIEW_PASSWORD=your_password
```

### 6. Tips for Success

1. **Be Quick**: CAPTCHA challenges often have time limits
2. **Complete All Steps**: Some CAPTCHAs have multiple verification steps
3. **Don't Navigate Away**: Stay on the CAPTCHA page until solved
4. **Watch the Logs**: Console output shows progress and instructions
5. **Patient Waiting**: System checks every 5 seconds for completion

### 7. Security Notes

- Browser runs in privileged mode for X11 access
- Manual intervention requires desktop access
- CAPTCHA solving happens in real-time on your display
- Session data is preserved after successful login

## Browser State Management

### Automatic Recovery
The system now includes automatic browser state management:

- **Browser Validation**: Checks if browser, context, and page are still valid before operations
- **Automatic Reinitialization**: If browser is closed/invalid, automatically reinitializes
- **Session Preservation**: After manual CAPTCHA solving, session data is automatically saved
- **Re-authentication**: If session is lost after reinitialization, automatically re-authenticates

### What This Fixes
- **"Target page, context or browser has been closed" errors**
- **Browser state corruption after manual CAPTCHA interaction**
- **Failed navigation attempts on subsequent analysis**
- **Lost authentication state between operations**

### Retry Logic
- **Automatic Retries**: Failed navigation attempts are automatically retried (up to 2 times)
- **Smart Recovery**: Each retry includes browser validation and reinitialization if needed
- **Session Restoration**: Automatically attempts to restore authentication state

### Logs to Expect
```
🔄 Browser is not valid, reinitializing...
🔐 Re-authentication required after browser reinitialization...
💾 Session data saved after CAPTCHA solving
Navigation attempt 1 failed, retrying...
Reinitializing browser and retrying...
```

## Success Indicators

### Console Messages to Look For:
```
🤖 CAPTCHA/Robot verification detected!
🚀 Switching to manual intervention mode...
📋 Instructions: [manual steps listed]
⏳ Still waiting for CAPTCHA to be solved...
✅ CAPTCHA appears to be solved! Continuing with automation...
```

### Browser Window Should Show:
- TradingView login page with CAPTCHA challenge
- "I am not a robot" checkbox or image challenges
- Normal TradingView interface (not automation-detected view)

Now you can test this by clicking "Analyse" in your UI and manually solving any CAPTCHA that appears!
