The AgriTech Blog now includes a comprehensive debug system that tracks user interactions, API calls, performance metrics, and post-specific database interactions. This system is particularly powerful for debugging edit-post functionality and MongoDB operations.
The debug system now automatically detects when you're on an edit-post page and tracks:
- Post ID extraction from URL (
/edit-post/[id]) - MongoDB fetch operations for the specific post
- Database update attempts with success/failure status
- Post content metadata (title, published status, content length, tags)
- Response times for all database operations
- Error tracking for failed post operations
- Click tracking with CSS selectors and coordinates
- Form submissions and input changes
- API call monitoring with response times
- Navigation events and URL changes
- Performance metrics (page load, first contentful paint)
- π Database interactions with post-specific context
When on an edit-post page (/edit-post/[id]), the debugger shows:
- Post ID: Extracted from URL
- Fetch Attempts: Number of times the post was requested from MongoDB
- Update Attempts: Number of save operations attempted
- Last Successful Fetch: Complete post data including title, content length, tags
- Database Status: Success/failure of each MongoDB operation
- Response Times: Performance metrics for each database call
- Error Details: Specific error messages for failed operations
- Critical crashes: Error bursts, infinite loops
- High priority: API failures, slow responses
- Medium priority: Memory leaks, UI freezes
- π Database failures: Failed post fetches or updates
- Interactive timeline of user actions
- Color-coded events (green=success, red=error, orange=database, blue=navigation)
- π Post-related highlighting for database operations
- Export capabilities for documentation
Method 1: Keyboard Shortcut
Ctrl + Shift + D (Windows/Linux)
Cmd + Shift + D (Mac)
Method 2: Click the Debug Button
- Look for the purple "π Debug Flow" button in the bottom-right corner
Method 3: Console Commands
// Show debug overlay
debugTracker.showDebugOverlay()
// Get post-specific summary (only works on edit-post pages)
debugTracker.getCurrentPostSummary()
// Get all post-related events
debugTracker.getPostSpecificEvents()
// Export session data
debugTracker.exportSession()- Shows chronological flow of user actions
- π Database operations highlighted with database icons
- π Post-related events marked with file icons
- Color coding: Green (success), Red (error), Orange (database), Blue (navigation)
- Detailed event list with timestamps
- π Database interaction badges showing operation type
- π Post-related badges for post-specific events
- Error details and response times
- Post Information: ID, fetch/update attempts, last successful data
- Database Status: Success/failure of MongoDB operations
- Content Details: Title, published status, content length, tags
- Error Tracking: Specific database error messages
- Session overview and performance statistics
- π Database interaction count
- API response times and error counts
To debug post editing issues:
-
Navigate to edit page:
/edit-post/[id] -
Open debug interface:
Ctrl+Shift+D -
Check Post Details tab for:
- Whether the post was successfully fetched
- Post metadata (title, content, tags)
- Database response times
- Any error messages
-
Monitor database operations:
- Watch Timeline tab for
DB_INTERACTIONevents - Check for
fetch_post_for_editingoperations - Monitor
update_postattempts when saving
- Watch Timeline tab for
-
Identify issues:
- 404 errors: Post ID not found in database
- Slow responses: Database performance issues
- Failed updates: Permission or validation errors
- Network errors: Connection problems
// Start/stop tracking
debugTracker.start()
debugTracker.stop()
// Clear all events
debugTracker.clear()
// Get recent events
debugTracker.getRecentEvents(50)
// Get events by type
debugTracker.getEventsByType('db_interaction')
debugTracker.getEventsByType('error')// Get current post summary (edit-post pages only)
const postSummary = debugTracker.getCurrentPostSummary()
console.log('Post ID:', postSummary?.postId)
console.log('Fetch attempts:', postSummary?.fetchAttempts)
console.log('Last successful fetch:', postSummary?.lastSuccessfulFetch)
// Get all post-related events
const postEvents = debugTracker.getPostSpecificEvents()
console.log('Post-related events:', postEvents.length)
// Track custom post event
debugTracker.trackEvent('post_update', {
action: 'manual_save',
postId: 'your-post-id',
success: true
})// Get performance metrics
const metrics = debugTracker.getPerformanceMetrics()
console.log('Total events:', metrics.totalEvents)
console.log('DB interactions:', metrics.dbInteractions)
console.log('Average API time:', metrics.averageApiResponseTime)
// Export full session
const sessionData = debugTracker.exportSession()
console.log('Full session:', sessionData)// Generate user journey diagram
const mermaidDiagram = flowDiagramGenerator.generateUserJourneyDiagram()
console.log('Mermaid diagram:', mermaidDiagram)
// Generate crash flow diagram
const crashDiagram = flowDiagramGenerator.generateCrashFlowDiagram()
console.log('Crash flow:', crashDiagram)Symptoms:
- Edit page shows loading spinner indefinitely
- No post data appears in form fields
Debug Steps:
- Open debug interface (
Ctrl+Shift+D) - Check Post Details tab
- Look for failed
fetch_post_for_editingoperations - Check error messages in Timeline tab
Common Causes:
- Post ID doesn't exist in database
- Network connectivity issues
- MongoDB connection problems
- Incorrect API endpoint configuration
Symptoms:
- Save button appears to work but changes aren't persisted
- Error messages during save operations
Debug Steps:
- Monitor Timeline tab during save operation
- Look for
update_postdatabase interactions - Check response status and error messages
- Verify post ID consistency
Common Causes:
- Permission issues
- Validation errors
- Network timeouts
- Database write failures
Symptoms:
- Long delays when opening edit page
- Slow response times
Debug Steps:
- Check Metrics tab for average response times
- Monitor individual database operation times in Timeline
- Look for network-related delays
Common Causes:
- Large post content
- Database performance issues
- Network latency
- Multiple simultaneous requests
Symptoms:
- Connection errors in console
- Failed database operations
Debug Steps:
- Check Post Details tab for connection status
- Monitor error patterns in Timeline
- Look for specific error messages
Common Causes:
- MongoDB connection string issues
- Network connectivity problems
- Database server downtime
- Authentication failures
The crash detector automatically monitors database operations:
// Check crash detector status
crashDetector.getHealthReport()
// Monitor database-specific crashes
// Automatically detects:
// - Rapid database failures
// - Slow database responses
// - Connection issues// Export post-specific debug data
const postDebugData = {
postSummary: debugTracker.getCurrentPostSummary(),
postEvents: debugTracker.getPostSpecificEvents(),
mermaidDiagram: flowDiagramGenerator.generateUserJourneyDiagram()
}
// Save as JSON for bug reports
const blob = new Blob([JSON.stringify(postDebugData, null, 2)], { type: 'application/json' })
const url = URL.createObjectURL(blob)
// Download or share the debug data// Set up real-time monitoring for post operations
setInterval(() => {
const postSummary = debugTracker.getCurrentPostSummary()
if (postSummary?.lastFetch?.success === false) {
console.warn('Post fetch failed:', postSummary.lastFetch.error)
}
}, 5000)The debug system now provides comprehensive failure analysis when database operations fail, with specific troubleshooting steps for each type of error.
When a post fetch fails, the debugger automatically:
-
Categorizes the error type:
network- Connection issues, timeoutsid_mismatch- Post ID not found in databasedatabase- MongoDB query failurespermission- Authentication/authorization issuesunknown- Unexpected errors
-
Identifies the failure step:
api_request- Network/HTTP request failedid_resolution- Post ID couldn't be resolveddatabase_query- MongoDB query execution faileddata_formatting- Response parsing issues
-
Generates detailed diagnostics including:
- Specific issue description
- List of possible causes
- Step-by-step troubleshooting instructions
- Relevant project files to check
- Configuration items to verify
When a database operation fails, the Post Details tab now shows:
- Error Summary: Issue type, HTTP status, failure step
- π§ Troubleshooting Steps: Numbered list of specific actions to take
- π€ Possible Causes: Common reasons for this type of failure
- π Project Files to Check: Exact files in your codebase to examine
- βοΈ Configuration to Verify: Settings and environment variables to check
- π Quick Actions: One-click buttons for common fixes
π¨ Failure Analysis & Troubleshooting
Error Type: ID_MISMATCH
Issue: Post with ID "5641343461" not found in database
HTTP Status: 404
Failure Step: id_resolution
π§ Troubleshooting Steps:
1. Check if post exists: Open /admin page and verify post list
2. Compare ID in URL with post IDs in admin panel
3. Check MongoDB directly: Use MongoDB Compass or CLI
4. Verify ID generation in api/admin/blog-posts.ts
5. Check if you're on the right database (blog_database)
π€ Possible Causes:
β’ Post ID doesn't exist in MongoDB
β’ ID generation algorithm mismatch
β’ Post was deleted or never created
β’ Database collection is empty
β’ Wrong database being queried
π Project Files to Check:
api/admin/blog-posts.ts - ID resolution logic
server/mongodb-storage-updated.ts - Database queries
api/blog-post.ts - mapPostDocument function
shared/schema.ts - Data types
βοΈ Configuration to Verify:
β MongoDB collection "posts" exists
β Posts have consistent ID fields
β Database name matches MONGODB_DATABASE env var
β ID generation algorithm consistency
// Get detailed failure analysis for current post
const analysis = debugTracker.getCurrentPostSummary()
console.log('Failure Analysis:', analysis.failureAnalysis)
// Get troubleshooting guide
const guide = debugTracker.getDetailedTroubleshootingGuide()
console.log('Troubleshooting Guide:', guide)
// Export failure data for bug reports
const failureData = {
postId: analysis.postId,
error: analysis.lastFetch?.error,
diagnostics: analysis.lastFetch?.diagnostics,
troubleshootingSteps: guide?.troubleshootingSteps
}
console.log('Bug Report Data:', JSON.stringify(failureData, null, 2))Quick Fix: Check if development server is running
npm run dev
# Should show: Server serving on port 5001Quick Fix: Verify post ID exists in admin panel
- Open
/adminin browser - Check if the post ID matches what's in the URL
- If different, update the URL with correct ID
Quick Fix: Check MongoDB connection
# Check server logs for MongoDB connection status
# Should see: "Successfully connected to MongoDB"Quick Fix: Check authentication
- Ensure you're logged in as admin
- Clear browser cache and cookies
- Verify API endpoint format
The failure analysis works seamlessly with:
- Crash Detector: Automatically detects repeated database failures
- Flow Diagrams: Shows failure points in user journey visualization
- Export Functions: Includes diagnostics in exported debug data
- Real-time Monitoring: Updates analysis as new failures occur
// Generate comprehensive bug report
const bugReport = {
timestamp: new Date().toISOString(),
postId: debugTracker.getCurrentPostSummary()?.postId,
failureAnalysis: debugTracker.getCurrentPostSummary()?.failureAnalysis,
allEvents: debugTracker.getPostSpecificEvents(),
sessionMetrics: debugTracker.getPerformanceMetrics()
}
// Copy to clipboard for sharing
console.log('π Bug Report:', JSON.stringify(bugReport, null, 2))- Use project file suggestions to identify code areas needing attention
- Reference configuration checks for environment setup validation
- Include troubleshooting steps in documentation
- Verify each failure scenario has appropriate error handling
- Test troubleshooting steps to ensure they resolve issues
- Validate that error messages are helpful and actionable
- Use export functionality to include debug data with bug reports
- Share mermaid diagrams to visualize user flows
- Include post-specific metrics for database issues
- Monitor database response times
- Identify slow post operations
- Track user interaction patterns
- Verify post CRUD operations work correctly
- Test error handling scenarios
- Validate user experience flows
- Development Only: Debug tracker only runs in development mode
- No Sensitive Data: Passwords and sensitive content are not logged
- Local Storage: All debug data stays in browser memory
- Automatic Cleanup: Events are automatically limited to prevent memory issues
- Chrome/Edge: Full support
- Firefox: Full support
- Safari: Full support
- Mobile: Limited support (overlay may be difficult to use)
- Minimal Overhead: Designed for development use
- Memory Management: Automatic cleanup of old events
- Conditional Loading: Only active in development mode
- Background Operation: Doesn't interfere with normal app functionality
| Action | Command |
|---|---|
| Open Debug Interface | Ctrl+Shift+D |
| Show Debug Overlay | debugTracker.showDebugOverlay() |
| Get Post Summary | debugTracker.getCurrentPostSummary() |
| Export Session | debugTracker.exportSession() |
| Clear Events | debugTracker.clear() |
| Generate Flow Diagram | flowDiagramGenerator.generateUserJourneyDiagram() |
For immediate help with post editing issues, open the debug interface and check the Post Details tab!