# D&D 4e Virtual Tabletop - Information & Debugging Guide

**Date:** August 18, 2025  
**Purpose:** Quick reference for debugging, logging locations, and troubleshooting

## Log Locations & Debugging

### Server-Side Logging

#### Primary Server Log Location
- **File:** `/var/www/html/dungeon/server.log` (if running with output redirection)
- **Real-time:** Terminal where `npm run server:dev` is running
- **Console Command:** `tail -f server.log` (if log file exists)

#### Enhanced Server Logging Features (Added 2025-08-18)
**Location:** `/var/www/html/dungeon/server/index.js` (lines 165-227)

**What's Logged:**
- 💥 Uncaught exceptions with full stack traces
- 💥 Unhandled promise rejections
- 🚨 Server errors with detailed context
- ✅ Successful server startup with process info
- 🔍 Port conflict detection with process investigation
- 📋 Memory usage and Node.js version info

**Key Log Patterns to Look For:**
```
🚀 Server attempting to start on port 3002...
✅ SERVER STARTUP SUCCESS: { port, pid, memory }
🚨 SERVER ERROR: { code: 'EADDRINUSE', message, timestamp }
💥 UNCAUGHT EXCEPTION! Shutting down...
💥 UNHANDLED PROMISE REJECTION! Shutting down...
```

### Client-Side Logging

#### Browser Console Location
- **Access:** F12 → Console tab in any browser
- **Filter:** Use browser console filters to show only specific log types

#### Enhanced Client Logging Features (Added 2025-08-18)

**App.tsx Authentication Flow:**
- **Location:** `/var/www/html/dungeon/client/src/App.tsx` (lines 59-103)
- **What's Logged:**
  - 🔄 App initialization with timestamps
  - 🔑 Token verification attempts
  - ✅ Authentication success/failure
  - 🚫 Missing token notifications

**Key Patterns:**
```
🔄 APP INITIALIZATION - Starting authentication check
🔑 Token found, verifying with server...
✅ Authentication successful
❌ TOKEN VERIFICATION FAILED:
🚫 No token found - showing login form
```

**CampaignManager Component:**
- **Location:** `/var/www/html/dungeon/client/src/components/CampaignManager.tsx` (lines 68-117, 119-211)
- **What's Logged:**
  - 🏰 Component initialization
  - 📊 Sequential data fetching
  - 📋 Campaign API calls
  - 📨 Invitation API calls
  - 🧹 Component cleanup

**Key Patterns:**
```
🏰 CAMPAIGN MANAGER - Starting data fetch
📊 Fetching campaigns and invitations sequentially...
1️⃣ Fetching campaigns...
📋 Starting campaign fetch...
🔑 Making campaigns API call with token:
✅ Campaigns fetched successfully:
2️⃣ Fetching pending invitations...
📨 Starting pending invitations fetch...
✅ Invitations fetched successfully:
🧹 Campaign Manager cleanup - unmounting
```

## API Timeout Configuration

**All API calls now have timeouts configured:**
- Authentication: 10 seconds (`/api/auth/me`)
- Campaigns: 15 seconds (`/api/campaigns`)
- Invitations: 15 seconds (`/api/campaigns/invitations/pending`)

## Common Issues & Debugging Steps

### Issue: App Hangs on Refresh
1. **Check Browser Console** for client-side logs
2. **Look for:** Which step fails in the authentication flow
3. **Common patterns:**
   - Token verification timeout
   - Campaign fetch hanging
   - API endpoint not responding

### Issue: Server Won't Start (Port 3002 in use)
1. **Check Server Logs** for port conflict details
2. **Commands to investigate:**
   ```bash
   lsof -ti:3002                    # Find processes using port
   ps aux | grep node               # Check for running Node processes
   pkill -f "node.*server"          # Kill server processes if needed
   ```

### Issue: API Calls Timing Out
1. **Check Browser Console** for specific API call failures
2. **Check Server Logs** for incoming request handling
3. **Look for patterns:**
   - Network timeouts vs server errors
   - Authentication token issues
   - Database connection problems

## Network Configuration

### Vite Proxy Configuration
- **File:** `/var/www/html/dungeon/client/vite.config.ts`
- **Current Target:** `https://52.204.250.67:3002` (specific IP to avoid DNS issues)
- **Proxy Routes:**
  - `/api/*` → Backend server
  - `/uploads/*` → Static file server

### Backend Server Configuration
- **Port:** 3002 (HTTPS)
- **SSL Certificates:** `./certs/privkey.pem` & `./certs/fullchain.pem`
- **CORS Origins:** `https://tonypanariello.com:5173`

## Database Debugging

### Connection Details
- **Host:** localhost:3306
- **Database:** tabletop_simulator
- **User:** dnd4e_user
- **Test Command:** 
  ```bash
  mysql -u dnd4e_user -p'Gandalfthewhite1@' -h localhost tabletop_simulator -e "SELECT COUNT(*) FROM users;"
  ```

## Performance Monitoring

### Memory Usage
Server startup logs now include memory usage information:
```
memory: {
  rss: 123456789,
  heapTotal: 987654321,
  heapUsed: 456789123,
  external: 12345678
}
```

### Socket.io Connections
Look for these patterns in server logs:
```
User connected: [socket-id]
Socket [socket-id] joined campaign [campaign-id]
User disconnected: [socket-id]
```

## Quick Debugging Commands

### Server Health Check
```bash
curl -s https://52.204.250.67:3002/api/health
```

### Check Running Processes
```bash
ps aux | grep -E "(node|npm)" | grep -v grep
```

### View Recent Server Logs
```bash
tail -50 /var/www/html/dungeon/server.log
```

### Monitor Real-time Logs
```bash
# Server logs
tail -f /var/www/html/dungeon/server.log

# Or monitor the terminal where server is running
```

## File Modification History

### Key Files Modified for Enhanced Logging (2025-08-18):
1. **`/server/index.js`** - Enhanced server error handling and startup logging
2. **`/client/src/App.tsx`** - Authentication flow logging
3. **`/client/src/components/CampaignManager.tsx`** - API call and component lifecycle logging
4. **`/client/vite.config.ts`** - Proxy configuration to use specific IP

### Stable Codebase Reference
- **Snapshot:** `/var/www/html/dungeon/snapshot/stable-codebase-snapshot.md`
- **Use for:** Restoring to known working state if issues arise

## Emergency Restore

If logging becomes too verbose or causes issues:
1. Refer to `/snapshot/stable-codebase-snapshot.md`
2. Restore the original, simpler logging
3. Remove enhanced console.log statements from the key files listed above