ai-debug-local-mcp
Version:
🎯 ENHANCED AI GUIDANCE v4.1.2: Dramatically improved tool descriptions help AI users choose the right tools instead of 'close enough' options. Ultra-fast keyboard automation (10x speed), universal recording, multi-ecosystem debugging support, and compreh
452 lines • 21.8 kB
JavaScript
/**
* Enhanced Error Handler
* Addresses Flutter feedback: "Generic error messages don't help diagnose root causes"
* Provides specific, actionable error messages with root cause analysis
*/
export class EnhancedErrorHandler {
errorPatterns = [];
constructor() {
this.initializeErrorPatterns();
}
/**
* Analyze error and provide detailed, actionable information
* Replaces generic "try starting new session" messages
*/
analyzeError(error, context) {
// Find matching error pattern
for (const pattern of this.errorPatterns) {
if (pattern.pattern.test(error.message)) {
return pattern.analyzer(error, context);
}
}
// Fallback for unknown errors
return this.createGenericErrorAnalysis(error, context);
}
/**
* Format error for user display with clear sections
*/
formatError(detailedError, context) {
const sections = [
`❌ **${detailedError.errorType}** (${detailedError.severity.toUpperCase()})`,
'',
`**Root Cause**: ${detailedError.rootCause}`,
`**Issue**: ${detailedError.specificMessage}`,
''
];
if (detailedError.actionableSteps.length > 0) {
sections.push('**💡 How to Fix:**');
detailedError.actionableSteps.forEach((step, index) => {
sections.push(`${index + 1}. ${step}`);
});
sections.push('');
}
if (detailedError.diagnosticCommands.length > 0) {
sections.push('**🔧 Diagnostic Commands:**');
detailedError.diagnosticCommands.forEach(cmd => {
sections.push(`\`${cmd}\``);
});
sections.push('');
}
if (detailedError.relatedDocumentation.length > 0) {
sections.push('**📚 Related Documentation:**');
detailedError.relatedDocumentation.forEach(doc => {
sections.push(`- ${doc}`);
});
sections.push('');
}
sections.push(`**Recovery**: ${detailedError.recoverable ? 'Automatically recoverable' : 'Manual intervention required'}`);
sections.push(`**Estimated Fix Time**: ${detailedError.estimatedFixTime} minutes`);
if (context?.sessionId) {
sections.push(`**Session ID**: ${context.sessionId}`);
}
return sections.join('\n');
}
/**
* Initialize comprehensive error patterns based on user feedback
*/
initializeErrorPatterns() {
// Flutter Accessibility Errors
this.errorPatterns.push({
pattern: /Failed to enable Flutter accessibility.*Target page, context or browser has been closed/i,
errorType: 'Flutter Accessibility Browser Connection Lost',
category: 'session',
analyzer: (error, context) => ({
errorType: 'Flutter Accessibility Browser Connection Lost',
rootCause: 'Browser connection terminated during accessibility initialization',
specificMessage: 'The browser tab or connection was closed while attempting to enable Flutter accessibility features',
actionableSteps: [
'Start a new debugging session with inject_debugging',
'Ensure Flutter app is running and accessible',
'Check browser console for JavaScript errors',
'Verify Flutter app has semantics enabled: flutter.engine.semanticsEnabled = true'
],
diagnosticCommands: [
'inject_debugging({ url: "your-flutter-app-url" })',
'flutter_health_check()',
'get_console_logs({ level: "error" })'
],
relatedDocumentation: [
'Flutter Accessibility Guide: https://docs.flutter.dev/development/accessibility-and-localization/accessibility',
'Browser Debugging Setup: Check that your Flutter app is running in debug mode'
],
severity: 'high',
category: 'session',
recoverable: true,
estimatedFixTime: 3
})
});
this.errorPatterns.push({
pattern: /Failed to enable Flutter accessibility.*timeout/i,
errorType: 'Flutter Accessibility Timeout',
category: 'configuration',
analyzer: (error, context) => ({
errorType: 'TIMEOUT_WAITING_FOR_FLUTTER_SEMANTICS',
rootCause: 'Flutter app does not have semantics/accessibility properly configured',
specificMessage: 'Timeout occurred waiting for Flutter accessibility tree to become available',
actionableSteps: [
'Ensure Flutter app has semantics enabled: flutter.engine.semanticsEnabled = true',
'Add Semantics() widgets to your Flutter app components',
'Check that your app is running in debug mode with --enable-semantics flag',
'Verify app is fully loaded before enabling accessibility'
],
diagnosticCommands: [
'flutter_health_check()',
'flutter run --web --enable-semantics',
'flutter.engine.semanticsEnabled = true // In browser console'
],
relatedDocumentation: [
'Flutter Semantics: https://api.flutter.dev/flutter/widgets/Semantics-class.html',
'Accessibility Testing: https://docs.flutter.dev/development/accessibility-and-localization/accessibility#testing'
],
severity: 'medium',
category: 'configuration',
recoverable: true,
estimatedFixTime: 10
})
});
// Quantum Debugging Errors
this.errorPatterns.push({
pattern: /Failed to analyze Flutter UI.*Quantum debugging session not initialized/i,
errorType: 'Flutter Quantum Debug Not Initialized',
category: 'tool',
analyzer: (error, context) => ({
errorType: 'Flutter Quantum Debug Prerequisites Missing',
rootCause: 'Quantum debugging requires accessibility to be enabled first',
specificMessage: 'flutter_quantum_analyze was called before establishing required prerequisites',
actionableSteps: [
'First run flutter_enable_accessibility and ensure it succeeds',
'Verify accessibility is working with flutter_health_check',
'Then initialize quantum debugging with flutter_quantum_analyze',
'Follow the recommended Flutter debugging workflow'
],
diagnosticCommands: [
'flutter_health_check()',
'flutter_enable_accessibility()',
'flutter_quantum_analyze()'
],
relatedDocumentation: [
'Flutter Debugging Workflow: Always enable accessibility before quantum analysis',
'Tool Dependencies: flutter_quantum_analyze requires flutter_enable_accessibility'
],
severity: 'medium',
category: 'tool',
recoverable: true,
estimatedFixTime: 5
})
});
// Session Management Errors
this.errorPatterns.push({
pattern: /Debug session .* not found/i,
errorType: 'Session Not Found',
category: 'session',
analyzer: (error, context) => ({
errorType: 'Debug Session Expired or Invalid',
rootCause: 'Session ID is invalid, expired, or was not properly created',
specificMessage: 'The debugging session you\'re trying to use no longer exists',
actionableSteps: [
'Create a new debugging session with inject_debugging',
'Ensure you\'re using the correct session ID from the response',
'Check that the session hasn\'t timed out (30-minute limit)',
'Verify browser tab is still open and responsive'
],
diagnosticCommands: [
'inject_debugging({ url: "your-app-url" })',
'get_session_info() // To verify session status'
],
relatedDocumentation: [
'Session Management: Sessions expire after 30 minutes of inactivity',
'Best Practice: Always check session validity before using tools'
],
severity: 'medium',
category: 'session',
recoverable: true,
estimatedFixTime: 2
})
});
// Network/Connection Errors
this.errorPatterns.push({
pattern: /ECONNREFUSED|connection refused|net::ERR_CONNECTION_REFUSED/i,
errorType: 'Application Connection Refused',
category: 'network',
analyzer: (error, context) => ({
errorType: 'Application Server Not Running',
rootCause: 'The application server is not running or not accessible at the specified URL',
specificMessage: 'Cannot connect to your application - the server appears to be down',
actionableSteps: [
'Verify your application is running (check terminal/console)',
'Confirm the correct URL and port number',
'Check if firewall or security software is blocking the connection',
'For Flutter web: run `flutter run -d web --web-port=PORT`',
'For React: run `npm start` or `yarn start`'
],
diagnosticCommands: [
'curl -I http://localhost:YOUR_PORT // Test if server responds',
'netstat -an | grep YOUR_PORT // Check if port is listening',
'flutter run -d web --web-port=8200 // Start Flutter web (AI-Debug reserved port)'
],
relatedDocumentation: [
'Flutter Web Setup: https://docs.flutter.dev/get-started/web',
'Local Development: Ensure your development server is running'
],
severity: 'high',
category: 'network',
recoverable: false,
estimatedFixTime: 5
})
});
// Python Backend Errors
this.errorPatterns.push({
pattern: /ModuleNotFoundError|No module named/i,
errorType: 'Python Module Import Error',
category: 'configuration',
analyzer: (error, context) => ({
errorType: 'Missing Python Dependencies',
rootCause: 'Required Python modules are not installed or not in the Python path',
specificMessage: error.message,
actionableSteps: [
'Install missing modules with pip: pip install MODULE_NAME',
'Check virtual environment is activated',
'Verify PYTHONPATH includes your project directory',
'For development dependencies: pip install -e .',
'Check requirements.txt for all dependencies'
],
diagnosticCommands: [
'pip list // Show installed packages',
'pip install -r requirements.txt // Install all requirements',
'python -c "import MODULE_NAME" // Test specific import',
'which python // Verify Python executable'
],
relatedDocumentation: [
'Python Virtual Environments: https://docs.python.org/3/tutorial/venv.html',
'Managing Dependencies: Use requirements.txt or pipenv'
],
severity: 'medium',
category: 'configuration',
recoverable: true,
estimatedFixTime: 10
})
});
// Pydantic Validation Errors
this.errorPatterns.push({
pattern: /validation error|ValidationError/i,
errorType: 'Pydantic Model Validation Failed',
category: 'framework',
analyzer: (error, context) => ({
errorType: 'Data Validation Error',
rootCause: 'Input data does not match the expected Pydantic model schema',
specificMessage: error.message,
actionableSteps: [
'Check field types in your Pydantic model definition',
'Verify input data matches expected format (JSON schema)',
'Check for required fields that might be missing',
'Validate field constraints (min/max values, string patterns)',
'Use model.parse_obj() for debugging validation issues'
],
diagnosticCommands: [
'validate_pydantic_models({ modelFilePath: "path/to/models.py" })',
'python -c "from models import YourModel; YourModel.parse_obj(test_data)"'
],
relatedDocumentation: [
'Pydantic Validation: https://pydantic-docs.helpmanual.io/usage/validators/',
'Field Types: https://pydantic-docs.helpmanual.io/usage/types/'
],
severity: 'medium',
category: 'framework',
recoverable: true,
estimatedFixTime: 15
})
});
// GenServer/Phoenix LiveView Errors
this.errorPatterns.push({
pattern: /no process.*the process is not alive|GenServer.*not alive/i,
errorType: 'GenServer Process Terminated',
category: 'framework',
analyzer: (error, context) => ({
errorType: 'Phoenix GenServer Lifecycle Issue',
rootCause: 'GenServer process terminated unexpectedly, likely due to an unhandled error or timeout',
specificMessage: 'A Phoenix GenServer process crashed or terminated during operation',
actionableSteps: [
'Check Phoenix logs for GenServer crash reasons',
'Review handle_info/2 and handle_call/3 implementations for errors',
'Verify supervisor tree configuration',
'Check for infinite loops or blocking operations in GenServer callbacks',
'Use monitor_realtime to watch process lifecycle during reproduction'
],
diagnosticCommands: [
'inject_debugging({ url: "http://localhost:8200" })',
'monitor_realtime({ events: ["process_lifecycle", "genserver_events"] })',
'simulate_user_action({ action: "navigate", path: "/admin/users" })'
],
relatedDocumentation: [
'GenServer Documentation: https://hexdocs.pm/elixir/GenServer.html',
'Phoenix LiveView Process Management: https://hexdocs.pm/phoenix_live_view/',
'OTP Supervisors: https://elixir-lang.org/getting-started/mix-otp/supervisor-and-application.html'
],
severity: 'high',
category: 'framework',
recoverable: true,
estimatedFixTime: 20
})
});
// Browser/Playwright Specific Errors
this.errorPatterns.push({
pattern: /page\..*is not a function|Cannot read prop.*of null/i,
errorType: 'Browser API Error',
category: 'session',
analyzer: (error, context) => ({
errorType: 'Browser Session Corrupted',
rootCause: 'Browser page object is no longer valid or accessible',
specificMessage: 'The browser automation connection has been lost or corrupted',
actionableSteps: [
'Restart the debugging session with inject_debugging',
'Ensure browser tab remains open and focused',
'Check for browser crashes or memory issues',
'Verify no other automation tools are interfering',
'Try using a different browser or incognito mode'
],
diagnosticCommands: [
'inject_debugging({ url: "your-app-url", forceRestart: true })',
'get_session_info()',
'take_screenshot() // Test basic browser functionality'
],
relatedDocumentation: [
'Browser Automation: Keep browser tab active during debugging',
'Session Management: Avoid navigating away from debugged page'
],
severity: 'high',
category: 'session',
recoverable: true,
estimatedFixTime: 3
})
});
}
/**
* Create analysis for unknown errors
*/
createGenericErrorAnalysis(error, context) {
const isTimeoutError = error.message.toLowerCase().includes('timeout');
const isConnectionError = error.message.toLowerCase().includes('connection') ||
error.message.toLowerCase().includes('network') ||
error.message.toLowerCase().includes('fetch');
if (isTimeoutError) {
return {
errorType: 'Timeout Error',
rootCause: 'Operation took longer than expected to complete',
specificMessage: error.message,
actionableSteps: [
'Increase timeout settings if possible',
'Check network connection stability',
'Verify target application is responsive',
'Try breaking operation into smaller steps'
],
diagnosticCommands: [
'ping target-server // Test network connectivity',
'curl -I target-url // Test HTTP response time'
],
relatedDocumentation: [
'Timeout Configuration: Check tool-specific timeout settings',
'Performance: Optimize target application response time'
],
severity: 'medium',
category: 'network',
recoverable: true,
estimatedFixTime: 5
};
}
if (isConnectionError) {
return {
errorType: 'Connection Error',
rootCause: 'Network or service connection failed',
specificMessage: error.message,
actionableSteps: [
'Check network connectivity',
'Verify target service is running and accessible',
'Check firewall or proxy settings',
'Retry the operation after ensuring connectivity'
],
diagnosticCommands: [
'ping target-host',
'telnet target-host port',
'curl -v target-url'
],
relatedDocumentation: [
'Network Troubleshooting: Check connectivity and DNS resolution',
'Service Status: Verify target service is running'
],
severity: 'high',
category: 'network',
recoverable: true,
estimatedFixTime: 10
};
}
// Generic unknown error
return {
errorType: 'Unknown Error',
rootCause: 'An unexpected error occurred that doesn\'t match known patterns',
specificMessage: error.message,
actionableSteps: [
'Check application logs for more details',
'Try restarting the debugging session',
'Verify all prerequisites are met for the operation',
'Report this error if it persists for investigation'
],
diagnosticCommands: [
'get_console_logs()',
'inject_debugging({ forceRestart: true })',
'get_session_info()'
],
relatedDocumentation: [
'Error Reporting: Include full error message and context',
'Debugging: Use diagnostic commands to gather more information'
],
severity: 'medium',
category: 'tool',
recoverable: true,
estimatedFixTime: 15
};
}
/**
* Add custom error pattern for specific use cases
*/
addErrorPattern(pattern) {
this.errorPatterns.unshift(pattern); // Add to beginning for priority
}
/**
* Get error statistics for monitoring
*/
getErrorStats() {
const categoryCounts = {};
const severityCounts = {};
// This would track actual errors in a real implementation
// For now, just return pattern statistics
this.errorPatterns.forEach(pattern => {
categoryCounts[pattern.category] = (categoryCounts[pattern.category] || 0) + 1;
});
return {
totalPatterns: this.errorPatterns.length,
categoryCounts,
severityCounts
};
}
}
//# sourceMappingURL=enhanced-error-handler.js.map