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
404 lines • 18.5 kB
JavaScript
/**
* AI-Debug Repair Toolkit
*
* Comprehensive repair and recovery system that integrates diagnostics,
* enhanced framework detection, and automated fixes to restore AI-Debug
* functionality when browser sessions fail to initialize.
*/
import { AIDebugDiagnostics } from './ai-debug-diagnostics.js';
import { EnhancedFrameworkDetector } from './enhanced-framework-detector.js';
import { UserFriendlyLogger } from './user-friendly-logger.js';
import { lazyBrowser } from './lazy-dependencies.js';
export class AIDebugRepairToolkit {
logger;
diagnostics;
frameworkDetector;
activeSessions = new Map();
constructor() {
this.logger = new UserFriendlyLogger('AIDebugRepair');
this.diagnostics = new AIDebugDiagnostics();
this.frameworkDetector = new EnhancedFrameworkDetector();
}
/**
* Master repair function - attempts to fix all AI-Debug issues
*/
async repairAIDebugSession(targetUrl, options = {}) {
const sessionId = `repair-${Date.now()}`;
const { emergencyMode = false, maxRepairAttempts = 3, workingDirectory = process.cwd() } = options;
this.logger.info(`🔧 Starting AI-Debug repair session ${sessionId} for ${targetUrl}`);
const session = {
sessionId,
targetUrl,
startTime: Date.now(),
diagnosticsRun: false,
frameworkDetected: false,
repairAttempts: [],
finalStatus: 'in-progress'
};
this.activeSessions.set(sessionId, session);
try {
// Phase 1: Emergency recovery if requested
if (emergencyMode) {
this.logger.warn('🚑 Emergency mode activated - performing immediate recovery');
const emergencyResult = await this.diagnostics.emergencyRecovery();
session.repairAttempts.push({
timestamp: Date.now(),
action: 'emergency_recovery',
success: emergencyResult.success,
details: emergencyResult
});
if (!emergencyResult.success) {
this.logger.error('Emergency recovery failed, continuing with standard repair...');
}
}
// Phase 2: Comprehensive diagnostics
this.logger.info('🔍 Running comprehensive diagnostics...');
const diagnosticResult = await this.diagnostics.runComprehensiveDiagnostics(targetUrl);
session.diagnosticsRun = true;
session.repairAttempts.push({
timestamp: Date.now(),
action: 'comprehensive_diagnostics',
success: true,
details: {
healthCheck: diagnosticResult.healthCheck,
criticalIssues: diagnosticResult.diagnostics.filter(d => d.severity === 'critical').length,
autoFixesApplied: diagnosticResult.autoFixesApplied
}
});
// Phase 3: Enhanced framework detection
this.logger.info('🎯 Running enhanced framework detection...');
const frameworkResult = await this.frameworkDetector.detectFramework(targetUrl, null, // No page available yet
workingDirectory);
session.frameworkDetected = true;
session.repairAttempts.push({
timestamp: Date.now(),
action: 'framework_detection',
success: frameworkResult.framework !== 'unknown',
details: frameworkResult
});
// Phase 4: Targeted repairs based on diagnostics
const criticalIssues = diagnosticResult.diagnostics.filter(d => d.severity === 'critical' && d.detected);
const repairActions = [];
for (const issue of criticalIssues) {
if (issue.fix?.automated) {
try {
this.logger.info(`🔧 Applying automated fix for: ${issue.issue}`);
const success = await issue.fix.action();
session.repairAttempts.push({
timestamp: Date.now(),
action: `fix_${issue.issue.replace(/\s+/g, '_').toLowerCase()}`,
success,
details: { issue: issue.issue, category: issue.category }
});
if (success) {
repairActions.push(issue.fix.description);
}
}
catch (error) {
this.logger.warn(`Failed to apply fix for ${issue.issue}: ${error}`);
}
}
}
// Phase 5: Browser session test
this.logger.info('🌐 Testing browser session initialization...');
const browserTestResult = await this.testBrowserSessionInitialization(targetUrl, frameworkResult.framework);
session.repairAttempts.push({
timestamp: Date.now(),
action: 'browser_session_test',
success: browserTestResult.success,
details: browserTestResult
});
// Phase 6: Final validation
const remainingIssues = diagnosticResult.diagnostics.filter(d => d.detected && d.severity === 'critical');
const success = browserTestResult.success && remainingIssues.length === 0;
session.finalStatus = success ? 'repaired' : (repairActions.length > 0 ? 'partially-repaired' : 'failed');
// Generate recommendations
const recommendations = this.generateRepairRecommendations(diagnosticResult.diagnostics, frameworkResult, browserTestResult);
const result = {
success,
browserSessionEstablished: browserTestResult.success,
frameworkDetected: frameworkResult.framework,
repairActions,
remainingIssues,
recommendations,
session
};
this.logger.info(`✅ Repair session completed: ${session.finalStatus}`);
return result;
}
catch (error) {
session.finalStatus = 'failed';
session.repairAttempts.push({
timestamp: Date.now(),
action: 'repair_error',
success: false,
details: { error: error instanceof Error ? error.message : 'Unknown error' }
});
this.logger.error(`❌ Repair session failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
return {
success: false,
browserSessionEstablished: false,
frameworkDetected: 'unknown',
repairActions: [],
remainingIssues: [],
recommendations: ['Manual intervention required - contact support'],
session
};
}
}
/**
* Test browser session initialization with improved error handling
*/
async testBrowserSessionInitialization(targetUrl, framework) {
const startTime = Date.now();
let browserLaunchTime = 0;
let pageNavigationTime = 0;
let debuggingInjectionTime = 0;
try {
// Step 1: Browser launch test
this.logger.info('🚀 Testing browser launch...');
const browserStartTime = Date.now();
const playwright = await lazyBrowser.getPlaywright();
const browser = await playwright.chromium.launch({
headless: true,
args: ['--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu']
});
browserLaunchTime = Date.now() - browserStartTime;
this.logger.success(`✅ Browser launched in ${browserLaunchTime}ms`);
try {
// Step 2: Page navigation test
this.logger.info('🌐 Testing page navigation...');
const pageStartTime = Date.now();
const context = await browser.newContext();
const page = await context.newPage();
// Set up error capture
const errors = [];
page.on('pageerror', error => errors.push(error.message));
page.on('console', msg => {
if (msg.type() === 'error') {
errors.push(msg.text());
}
});
// Navigate with timeout
try {
await page.goto(targetUrl, {
waitUntil: 'domcontentloaded',
timeout: 15000
});
pageNavigationTime = Date.now() - pageStartTime;
this.logger.success(`✅ Page navigation completed in ${pageNavigationTime}ms`);
// Step 3: Basic debugging injection test
this.logger.info('💉 Testing debugging injection...');
const injectionStartTime = Date.now();
try {
// Simple injection test
await page.evaluate(() => {
// Create debugging namespace
window.aiDebug = {
initialized: true,
timestamp: Date.now(),
framework: 'test'
};
return true;
});
// Verify injection worked
const injectionResult = await page.evaluate(() => {
return window.aiDebug && window.aiDebug.initialized;
});
if (injectionResult) {
debuggingInjectionTime = Date.now() - injectionStartTime;
this.logger.success(`✅ Debugging injection successful in ${debuggingInjectionTime}ms`);
await browser.close();
return {
success: true,
browserLaunched: true,
pageNavigated: true,
debuggingInjected: true,
timing: {
browserLaunch: browserLaunchTime,
pageNavigation: pageNavigationTime,
debuggingInjection: debuggingInjectionTime,
total: Date.now() - startTime
}
};
}
else {
throw new Error('Debugging injection verification failed');
}
}
catch (injectionError) {
await browser.close();
return {
success: false,
browserLaunched: true,
pageNavigated: true,
debuggingInjected: false,
error: `Debugging injection failed: ${injectionError instanceof Error ? injectionError.message : 'Unknown error'}`,
timing: {
browserLaunch: browserLaunchTime,
pageNavigation: pageNavigationTime,
debuggingInjection: Date.now() - injectionStartTime,
total: Date.now() - startTime
}
};
}
}
catch (navigationError) {
await browser.close();
return {
success: false,
browserLaunched: true,
pageNavigated: false,
debuggingInjected: false,
error: `Page navigation failed: ${navigationError instanceof Error ? navigationError.message : 'Unknown error'}`,
timing: {
browserLaunch: browserLaunchTime,
pageNavigation: Date.now() - pageStartTime,
debuggingInjection: 0,
total: Date.now() - startTime
}
};
}
}
catch (contextError) {
await browser.close();
return {
success: false,
browserLaunched: true,
pageNavigated: false,
debuggingInjected: false,
error: `Browser context creation failed: ${contextError instanceof Error ? contextError.message : 'Unknown error'}`,
timing: {
browserLaunch: browserLaunchTime,
pageNavigation: 0,
debuggingInjection: 0,
total: Date.now() - startTime
}
};
}
}
catch (browserError) {
return {
success: false,
browserLaunched: false,
pageNavigated: false,
debuggingInjected: false,
error: `Browser launch failed: ${browserError instanceof Error ? browserError.message : 'Unknown error'}`,
timing: {
browserLaunch: Date.now() - startTime,
pageNavigation: 0,
debuggingInjection: 0,
total: Date.now() - startTime
}
};
}
}
/**
* Generate specific repair recommendations based on findings
*/
generateRepairRecommendations(diagnostics, frameworkResult, browserTest) {
const recommendations = [];
// Browser-specific recommendations
if (!browserTest.browserLaunched) {
recommendations.push('🔧 Reinstall Playwright: npm install playwright && npx playwright install');
recommendations.push('🔧 Check system dependencies: npx playwright install-deps');
}
else if (!browserTest.pageNavigated) {
recommendations.push('🌐 Verify target application is running and accessible');
recommendations.push('🔍 Check firewall and network connectivity');
}
else if (!browserTest.debuggingInjected) {
recommendations.push('💉 Browser security policies may be blocking script injection');
recommendations.push('⚙️ Try running with --disable-web-security flag (development only)');
}
// Framework-specific recommendations
if (frameworkResult.framework !== 'unknown') {
const frameworkRecs = this.frameworkDetector.getFrameworkSpecificRecommendations(frameworkResult.framework);
recommendations.push(...frameworkRecs.map(rec => `📦 ${rec}`));
}
// Diagnostic-specific recommendations
const criticalIssues = diagnostics.filter(d => d.severity === 'critical' && d.detected);
if (criticalIssues.length > 0) {
recommendations.push('🚨 Address critical issues first:');
for (const issue of criticalIssues.slice(0, 3)) {
if (issue.fix?.description) {
recommendations.push(` • ${issue.fix.description}`);
}
else {
recommendations.push(` • ${issue.issue}`);
}
}
}
// Performance recommendations
if (browserTest.timing?.total > 10000) {
recommendations.push('⚡ Browser initialization is slow - consider system resource optimization');
}
return recommendations;
}
/**
* Get repair session status
*/
getRepairSessionStatus(sessionId) {
return this.activeSessions.get(sessionId) || null;
}
/**
* Clear completed repair sessions
*/
cleanupCompletedSessions() {
const completed = Array.from(this.activeSessions.values())
.filter(session => session.finalStatus !== 'in-progress');
for (const session of completed) {
this.activeSessions.delete(session.sessionId);
}
return completed.length;
}
/**
* Quick health check - lighter version of full diagnostics
*/
async quickHealthCheck(targetUrl) {
try {
// Quick browser test
const playwright = await lazyBrowser.getPlaywright();
const browserSupport = !!playwright;
// Quick connectivity test
const targetReachable = await fetch(targetUrl, {
method: 'HEAD',
signal: AbortSignal.timeout(3000)
}).then(() => true).catch(() => false);
// Quick framework detection
const framework = await this.frameworkDetector.quickDetect(targetUrl);
// Determine overall health
let overall = 'healthy';
const recommendations = [];
if (!browserSupport) {
overall = 'critical';
recommendations.push('Install Playwright browsers');
}
else if (!targetReachable) {
overall = 'critical';
recommendations.push('Start your development server');
}
else if (framework === 'unknown') {
overall = 'degraded';
recommendations.push('Framework detection needs improvement');
}
return {
overall,
browserSupport,
targetReachable,
frameworkDetected: framework,
recommendations
};
}
catch (error) {
return {
overall: 'critical',
browserSupport: false,
targetReachable: false,
frameworkDetected: 'unknown',
recommendations: ['Run full diagnostics to identify issues']
};
}
}
}
//# sourceMappingURL=ai-debug-repair-toolkit.js.map