UNPKG

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

245 lines 9.69 kB
/** * Performance Coordinator * Consolidates all performance monitoring, metrics collection, and optimization capabilities * Extracted from LocalDebugEngine as part of coordinator pattern implementation */ export class PerformanceCoordinator { networkCoordinator; jsAnalysisCoordinator; flutterAnalysisCoordinator; nextjsEnhancedEngine; baselines = new Map(); metricsHistory = []; constructor(networkCoordinator, jsAnalysisCoordinator, flutterAnalysisCoordinator, nextjsEnhancedEngine) { this.networkCoordinator = networkCoordinator; this.jsAnalysisCoordinator = jsAnalysisCoordinator; this.flutterAnalysisCoordinator = flutterAnalysisCoordinator; this.nextjsEnhancedEngine = nextjsEnhancedEngine; } /** * Get comprehensive network performance metrics */ getNetworkMetrics() { try { if (!this.networkCoordinator) { console.debug('⚠️ Network coordinator not initialized - returning empty metrics'); return { totalRequests: 0, failedRequests: 0, averageResponseTime: 0 }; } return this.networkCoordinator.getNetworkMetrics(); } catch (error) { console.debug('⚠️ Error getting network metrics:', error); return { totalRequests: 0, failedRequests: 0, averageResponseTime: 0 }; } } /** * Get JavaScript performance profiling data */ async getJavaScriptPerformanceProfile() { try { if (!this.jsAnalysisCoordinator) { console.debug('⚠️ JavaScript analysis coordinator not initialized - returning empty profile'); return { executionTime: 0, memoryUsage: 0, functionCalls: [] }; } return await this.jsAnalysisCoordinator.getJavaScriptPerformanceProfile(); } catch (error) { console.debug('⚠️ Error getting JavaScript performance profile:', error); if (error.message.includes('Target page, context or browser has been closed')) { return { executionTime: 0, memoryUsage: 0, functionCalls: [], error: 'Browser context closed' }; } return { executionTime: 0, memoryUsage: 0, functionCalls: [], error: error.message }; } } /** * Get Flutter performance metrics */ async getFlutterPerformance() { return await this.flutterAnalysisCoordinator.getFlutterPerformance(); } /** * Get detailed Flutter performance metrics */ async getFlutterPerformanceMetrics() { return await this.flutterAnalysisCoordinator.getFlutterPerformanceMetrics(); } /** * Get Next.js performance score */ async getNextJSPerformanceScore() { if (!this.nextjsEnhancedEngine) { throw new Error('Enhanced Next.js engine not initialized'); } return await this.nextjsEnhancedEngine.getPerformanceScore(); } /** * Get Flutter performance baseline for comparison */ async getFlutterPerformanceBaseline() { return await this.flutterAnalysisCoordinator.getFlutterPerformanceBaseline(); } /** * Collect comprehensive performance metrics from all sources */ async collectPerformanceMetrics() { console.debug('📊 Collecting performance metrics...'); const metrics = { networkMetrics: this.getNetworkMetrics(), // Already handles errors javascriptProfile: await this.getJavaScriptPerformanceProfile(), // Already handles errors timestamp: Date.now() }; // Add Flutter metrics if available try { metrics.flutterMetrics = await this.getFlutterPerformanceMetrics(); console.debug('✅ Flutter metrics collected'); } catch (error) { console.debug('⚠️ Flutter metrics not available:', error); // Flutter not available in this session } // Add Next.js metrics if available try { metrics.nextjsScore = await this.getNextJSPerformanceScore(); console.debug('✅ Next.js metrics collected'); } catch (error) { console.debug('⚠️ Next.js metrics not available:', error); // Next.js not available in this session } // Store in history for trend analysis this.metricsHistory.push(metrics); if (this.metricsHistory.length > 100) { this.metricsHistory.shift(); // Keep last 100 measurements } console.debug(`✅ Performance metrics collected successfully (${Object.keys(metrics).length} categories)`); return metrics; } /** * Set performance baseline for comparison */ async setPerformanceBaseline(sessionId, url) { const metrics = await this.collectPerformanceMetrics(); const baseline = { metrics, capturedAt: Date.now(), sessionId, url }; this.baselines.set(sessionId, baseline); return baseline; } /** * Compare current performance with baseline */ async compareWithBaseline(sessionId) { const baseline = this.baselines.get(sessionId); if (!baseline) { return null; } const current = await this.collectPerformanceMetrics(); const improvements = []; const regressions = []; // Compare network metrics if (current.networkMetrics && baseline.metrics.networkMetrics) { const currentRequests = current.networkMetrics.totalRequests || 0; const baselineRequests = baseline.metrics.networkMetrics.totalRequests || 0; if (currentRequests < baselineRequests) { improvements.push(`Reduced network requests: ${baselineRequests} → ${currentRequests}`); } else if (currentRequests > baselineRequests) { regressions.push(`Increased network requests: ${baselineRequests} → ${currentRequests}`); } } // Calculate overall score (simplified) let score = 50; // baseline score score += improvements.length * 10; score -= regressions.length * 15; score = Math.max(0, Math.min(100, score)); // Clamp to 0-100 return { current, baseline, improvements, regressions, overallScore: score }; } /** * Generate performance optimization recommendations */ async getOptimizationRecommendations() { const recommendations = []; try { const metrics = await this.collectPerformanceMetrics(); // Network recommendations if (metrics.networkMetrics) { const requests = metrics.networkMetrics.totalRequests || 0; if (requests > 50) { recommendations.push('Consider reducing the number of network requests through bundling or caching'); } const failedRequests = metrics.networkMetrics.failedRequests || 0; if (failedRequests > 0) { recommendations.push(`Fix ${failedRequests} failed network requests to improve reliability`); } } // JavaScript recommendations if (metrics.javascriptProfile) { recommendations.push('Consider code splitting and lazy loading for better JavaScript performance'); } // Flutter-specific recommendations if (metrics.flutterMetrics) { recommendations.push('Monitor Flutter widget rebuild frequency to optimize rendering performance'); } // Next.js recommendations if (metrics.nextjsScore) { recommendations.push('Leverage Next.js optimization features like Image component and automatic static optimization'); } } catch (error) { recommendations.push('Unable to analyze performance metrics - ensure all debugging engines are properly initialized'); } return recommendations; } /** * Get performance trend analysis */ getPerformanceTrends() { if (this.metricsHistory.length < 2) { return { message: 'Insufficient data for trend analysis', dataPoints: this.metricsHistory.length }; } const recent = this.metricsHistory.slice(-10); // Last 10 measurements const networkRequestTrend = recent.map(m => m.networkMetrics?.totalRequests || 0); return { networkRequests: { trend: networkRequestTrend, average: networkRequestTrend.reduce((a, b) => a + b, 0) / networkRequestTrend.length, min: Math.min(...networkRequestTrend), max: Math.max(...networkRequestTrend) }, totalMeasurements: this.metricsHistory.length, timeSpan: recent.length > 1 ? recent[recent.length - 1].timestamp - recent[0].timestamp : 0 }; } /** * Clear performance history and baselines */ reset() { this.metricsHistory = []; this.baselines.clear(); } /** * Update Next.js enhanced engine when it becomes available */ setNextJSEngine(nextjsEnhancedEngine) { this.nextjsEnhancedEngine = nextjsEnhancedEngine; } /** * Cleanup resources */ cleanup() { this.reset(); } } //# sourceMappingURL=performance-coordinator.js.map