7.5 KiB
7.5 KiB
Frontend AI Analysis Integration
Overview
This document describes the complete integration of AI analysis functionality into the frontend, including real-time monitoring, progress tracking, and API gateway communication.
Architecture
Frontend → API Gateway → AI Analysis Service → Git Integration Service
↓ ↓ ↓ ↓
Real-time UI → HTTP API → Repository Info → Local File Access
↓ ↓ ↓ ↓
Progress → WebSocket → Analysis → Direct File System
Monitoring → Stream → Processing → Access
Components Implemented
1. API Routes (/app/api/ai/repository/)
/analyze/route.ts
- Purpose: Start AI analysis for a repository
- Method: POST
- Input:
{ repository_id, user_id, output_format, max_files } - Output: Analysis result with stats and report path
/stream/route.ts
- Purpose: Real-time streaming of analysis progress
- Method: GET
- Input:
repository_id,user_idas query parameters - Output: Server-Sent Events stream with progress updates
/report/[filename]/route.ts
- Purpose: Download analysis reports
- Method: GET
- Input: Filename as URL parameter
- Output: File download with appropriate headers
2. React Hooks (/hooks/useAIAnalysis.ts)
useAIAnalysis Hook
- State Management: Analysis progress, results, errors
- Functions:
startAnalysis(): Initiates analysis with optionsstopAnalysis(): Stops ongoing analysisresetAnalysis(): Resets all state
- Real-time Updates: Uses EventSource for streaming updates
3. UI Components (/components/ai/)
AnalysisMonitor.tsx
- Real-time Progress: Shows analysis progress with percentage
- Status Indicators: Loading, error, and completion states
- Statistics Display: File counts, quality scores, languages
- Download Functionality: Direct report download
AnalysisModal.tsx
- Modal Interface: Full-screen analysis interface
- Progress Tracking: Real-time progress updates
- Error Handling: User-friendly error messages
- Result Display: Comprehensive analysis results
4. Integration Points
GitHub Repos Page (/app/github/repos/page.tsx)
- AI Analysis Button: Triggers analysis modal
- Repository Context: Passes repository ID and name
- User Context: Handles user authentication
- Modal Integration: Seamless modal experience
Real-time Features
1. Progress Monitoring
interface AnalysisProgress {
current_chunk: number
total_chunks: number
processed_files: number
total_files: number
percentage: number
}
2. Status Updates
- Ready: Analysis not started
- Analyzing: In progress with real-time updates
- Complete: Analysis finished with results
- Error: Analysis failed with error message
3. Statistics Display
- File Metrics: Total files, lines of code
- Quality Scores: Overall code quality rating
- Language Breakdown: Programming languages detected
- Quality Distribution: High/medium/low quality files
API Gateway Integration
1. Service Communication
All communication flows through the API gateway:
Frontend → Next.js API Routes → External Services
2. Environment Configuration
# Service URLs
GIT_INTEGRATION_SERVICE_URL=http://git-integration:8012
AI_ANALYSIS_SERVICE_URL=http://ai-analysis-service:8022
# Public URLs (for client-side)
NEXT_PUBLIC_GIT_INTEGRATION_SERVICE_URL=http://localhost:8012
NEXT_PUBLIC_AI_ANALYSIS_SERVICE_URL=http://localhost:8022
3. Error Handling
- Service Unavailable: Graceful fallback messages
- Network Errors: Retry mechanisms
- Analysis Failures: User-friendly error display
User Experience Flow
1. Analysis Initiation
- User clicks "AI Analysis" button on repository card
- Modal opens with analysis interface
- User can start analysis or close modal
2. Real-time Progress
- Analysis starts with progress indicator
- Real-time updates show:
- Files processed
- Chunks processed
- Percentage complete
- User can stop analysis if needed
3. Results Display
- Analysis completes with success indicator
- Statistics displayed:
- Total files and lines
- Quality score
- Language breakdown
- Quality distribution
- Download button for report
4. Error Handling
- Error messages displayed clearly
- Retry options provided
- User can close and try again
Technical Implementation
1. State Management
const {
isAnalyzing, // Analysis in progress
progress, // Real-time progress
result, // Analysis results
error, // Error messages
startAnalysis, // Start function
stopAnalysis, // Stop function
resetAnalysis // Reset function
} = useAIAnalysis()
2. Real-time Updates
// EventSource for streaming updates
const eventSource = new EventSource(streamUrl)
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data)
// Update progress, handle completion, etc.
}
3. File Download
const handleDownloadReport = async () => {
const response = await fetch(`/api/ai/repository/report/${filename}`)
const blob = await response.blob()
// Create download link and trigger download
}
Security Considerations
1. Authentication
- User ID passed through all requests
- JWT tokens for service authentication
- Repository access validation
2. Input Validation
- Repository ID validation
- User ID validation
- File size limits
- Content type validation
3. Error Handling
- No sensitive information in error messages
- Graceful degradation on service failures
- User-friendly error display
Performance Optimizations
1. Caching
- Analysis results cached for 24 hours
- File content hashing for change detection
- Redis-based caching system
2. Rate Limiting
- 90 requests per minute to Claude API
- Request queuing and throttling
- Progress updates to prevent timeouts
3. Content Optimization
- Large files truncated intelligently
- Important code sections preserved
- Token limit compliance
Deployment Considerations
1. Environment Variables
# Required for production
GIT_INTEGRATION_SERVICE_URL=https://git-integration.yourdomain.com
AI_ANALYSIS_SERVICE_URL=https://ai-analysis.yourdomain.com
2. CORS Configuration
// API routes handle CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
3. Error Monitoring
- Console logging for debugging
- Error tracking for production
- Performance monitoring
Testing
1. Unit Tests
- Hook functionality testing
- Component rendering tests
- API route testing
2. Integration Tests
- End-to-end analysis flow
- Real-time update testing
- Error scenario testing
3. Performance Tests
- Large repository handling
- Concurrent analysis testing
- Memory usage monitoring
Future Enhancements
1. Advanced Features
- Batch analysis for multiple repositories
- Analysis scheduling
- Custom analysis parameters
2. UI Improvements
- Analysis history
- Comparison between repositories
- Advanced filtering and sorting
3. Performance
- Background processing
- Queue management
- Resource optimization
This integration provides a complete, production-ready AI analysis system with real-time monitoring, progress tracking, and seamless user experience through the API gateway architecture.