File size: 15,855 Bytes
415b879 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 |
import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
MemorySystemState,
FileProcessingState,
PerformanceLogEntry,
MemoryItem,
ProcessingFile,
ProcessedFile,
FileMetadata
} from '../types';
import { MemoryService } from '../services/MemoryService';
import { FileProcessingService } from '../services/FileProcessingService';
import { PerformanceMonitor } from '../services/PerformanceMonitor';
import { useMemorySystem } from '../hooks/useMemorySystem';
import { useFileProcessing } from '../hooks/useFileProcessing';
import { usePerformanceMonitoring } from '../hooks/usePerformanceMonitoring';
interface IntegratedAISystemProps {
config?: {
memoryConfig?: {
compressionRatio?: number;
retentionThreshold?: number;
cleanupInterval?: number;
};
fileConfig?: {
maxFileSize?: number;
supportedExtensions?: string[];
processingQueueSize?: number;
};
performanceConfig?: {
enableLogging?: boolean;
logLevel?: 'debug' | 'info' | 'warn' | 'error';
metricsInterval?: number;
};
};
onMemoryUpdate?: (memoryState: MemorySystemState) => void;
onFileProcessed?: (file: ProcessedFile) => void;
onPerformanceAlert?: (alert: PerformanceLogEntry) => void;
}
export const IntegratedAISystem: React.FC<IntegratedAISystemProps> = ({
config = {},
onMemoryUpdate,
onFileProcessed,
onPerformanceAlert
}) => {
// Enhanced state management with better type safety and initialization
const [isInitialized, setIsInitialized] = useState(false);
const [systemStatus, setSystemStatus] = useState<'initializing' | 'running' | 'paused' | 'error'>('initializing');
const [errorState, setErrorState] = useState<string | null>(null);
// Custom hooks for modular state management
const {
memorySystem,
storeMemory,
retrieveMemories,
compressMemories,
getMemoryStats
} = useMemorySystem(config.memoryConfig);
const {
fileProcessing,
addFileToQueue,
processNextFile,
getProcessingStats,
clearProcessedFiles
} = useFileProcessing(config.fileConfig);
const {
performanceLog,
startMonitoring,
stopMonitoring,
getPerformanceMetrics,
detectAnomalies
} = usePerformanceMonitoring(config.performanceConfig);
// Service instances with dependency injection
const memoryServiceRef = useRef<MemoryService | null>(null);
const fileServiceRef = useRef<FileProcessingService | null>(null);
const performanceMonitorRef = useRef<PerformanceMonitor | null>(null);
// Advanced initialization with error handling and dependency setup
useEffect(() => {
const initializeSystem = async () => {
try {
setSystemStatus('initializing');
// Initialize services with configuration
memoryServiceRef.current = new MemoryService({
compressionRatio: config.memoryConfig?.compressionRatio || 0.7,
retentionThreshold: config.memoryConfig?.retentionThreshold || 0.8,
cleanupInterval: config.memoryConfig?.cleanupInterval || 300000
});
fileServiceRef.current = new FileProcessingService({
maxFileSize: config.fileConfig?.maxFileSize || 50 * 1024 * 1024, // 50MB
supportedExtensions: config.fileConfig?.supportedExtensions || [
'tsx', 'ts', 'jsx', 'js', 'py', 'cpp', 'html', 'css', 'md', 'pdf',
'json', 'csv', 'xml', 'yaml', 'png', 'jpg', 'mp4', 'wav'
],
processingQueueSize: config.fileConfig?.processingQueueSize || 100
});
performanceMonitorRef.current = new PerformanceMonitor({
enableLogging: config.performanceConfig?.enableLogging ?? true,
logLevel: config.performanceConfig?.logLevel || 'info',
metricsInterval: config.performanceConfig?.metricsInterval || 5000
});
// Start monitoring and background processes
await startMonitoring();
setIsInitialized(true);
setSystemStatus('running');
setErrorState(null);
} catch (error) {
console.error('Failed to initialize Integrated AI System:', error);
setErrorState(error instanceof Error ? error.message : 'Unknown initialization error');
setSystemStatus('error');
}
};
initializeSystem();
// Cleanup function
return () => {
stopMonitoring();
if (memoryServiceRef.current) {
memoryServiceRef.current.cleanup();
}
if (fileServiceRef.current) {
fileServiceRef.current.cleanup();
}
if (performanceMonitorRef.current) {
performanceMonitorRef.current.cleanup();
}
};
}, [config]);
// Enhanced memory management with semantic search and intelligent compression
const handleMemoryOperation = useCallback(async (
operation: 'store' | 'retrieve' | 'compress',
data?: any,
query?: string
) => {
if (!memoryServiceRef.current || !isInitialized) return;
try {
switch (operation) {
case 'store':
if (data) {
const memoryItem: MemoryItem = {
id: crypto.randomUUID(),
content: data,
timestamp: new Date(),
accessCount: 0,
importance: data.importance || 0.5,
tags: data.tags || [],
metadata: data.metadata || {}
};
await storeMemory(memoryItem);
onMemoryUpdate?.(memorySystem);
}
break;
case 'retrieve':
if (query) {
const results = await retrieveMemories(query, {
limit: 10,
threshold: 0.7,
includeArchived: false
});
return results;
}
break;
case 'compress':
await compressMemories();
onMemoryUpdate?.(memorySystem);
break;
}
} catch (error) {
console.error(`Memory operation '${operation}' failed:`, error);
performanceMonitorRef.current?.logEvent({
id: crypto.randomUUID(),
timestamp: new Date(),
eventType: 'memory_operation_error',
status: 'failure',
details: { operation, error: error instanceof Error ? error.message : 'Unknown error' },
resourceUsage: { cpu: 0, memory: 0, diskIO: 0, networkIO: 0 }
});
}
}, [memorySystem, storeMemory, retrieveMemories, compressMemories, onMemoryUpdate, isInitialized]);
// Advanced file processing with content analysis and metadata extraction
const handleFileUpload = useCallback(async (files: FileList) => {
if (!fileServiceRef.current || !isInitialized) return;
for (let i = 0; i < files.length; i++) {
const file = files[i];
try {
// Validate file before processing
const validation = await fileServiceRef.current.validateFile(file);
if (!validation.isValid) {
console.warn(`File validation failed for ${file.name}:`, validation.errors);
continue;
}
// Create processing file entry
const processingFile: ProcessingFile = {
id: crypto.randomUUID(),
name: file.name,
path: file.name, // In browser context, we use name as path
size: file.size,
type: file.type || 'application/octet-stream',
status: 'pending',
priority: 1
};
// Add to processing queue
await addFileToQueue(processingFile);
// Process file with content analysis
const processedFile = await fileServiceRef.current.processFile(file, {
extractMetadata: true,
performContentAnalysis: true,
generateSemanticTags: true,
enableSecurityScanning: true
});
onFileProcessed?.(processedFile);
// Store file metadata in memory system for future retrieval
await handleMemoryOperation('store', {
content: {
fileId: processedFile.id,
fileName: processedFile.name,
metadata: processedFile.metadata,
summary: processedFile.metadata.extractedText?.substring(0, 500)
},
importance: 0.6,
tags: ['file', 'processed', ...(processedFile.metadata.semanticTags || [])],
metadata: {
source: 'file_processing',
fileType: processedFile.type,
processedAt: new Date().toISOString()
}
});
} catch (error) {
console.error(`File processing failed for ${file.name}:`, error);
performanceMonitorRef.current?.logEvent({
id: crypto.randomUUID(),
timestamp: new Date(),
eventType: 'file_processing_error',
status: 'failure',
details: { fileName: file.name, error: error instanceof Error ? error.message : 'Unknown error' },
resourceUsage: { cpu: 0, memory: 0, diskIO: 0, networkIO: 0 }
});
}
}
}, [addFileToQueue, handleMemoryOperation, onFileProcessed, isInitialized]);
// Performance monitoring and anomaly detection
const handlePerformanceCheck = useCallback(async () => {
if (!performanceMonitorRef.current || !isInitialized) return;
try {
const metrics = await getPerformanceMetrics();
const anomalies = await detectAnomalies(metrics);
if (anomalies.length > 0) {
anomalies.forEach(anomaly => {
onPerformanceAlert?.(anomaly);
});
}
// Auto-optimize based on performance metrics
if (metrics.memory > 0.8) {
await handleMemoryOperation('compress');
}
if (metrics.cpu > 0.9) {
// Reduce processing queue size temporarily
fileServiceRef.current?.adjustProcessingRate(0.5);
}
} catch (error) {
console.error('Performance check failed:', error);
}
}, [getPerformanceMetrics, detectAnomalies, handleMemoryOperation, onPerformanceAlert, isInitialized]);
// Periodic performance monitoring
useEffect(() => {
if (!isInitialized || systemStatus !== 'running') return;
const performanceInterval = setInterval(handlePerformanceCheck, 30000); // Check every 30 seconds
return () => clearInterval(performanceInterval);
}, [isInitialized, systemStatus, handlePerformanceCheck]);
// System control functions
const pauseSystem = useCallback(() => {
setSystemStatus('paused');
stopMonitoring();
}, [stopMonitoring]);
const resumeSystem = useCallback(async () => {
setSystemStatus('running');
await startMonitoring();
}, [startMonitoring]);
const resetSystem = useCallback(async () => {
try {
setSystemStatus('initializing');
// Clear all data
memoryServiceRef.current?.reset();
fileServiceRef.current?.reset();
performanceMonitorRef.current?.reset();
// Restart monitoring
await startMonitoring();
setSystemStatus('running');
setErrorState(null);
} catch (error) {
console.error('System reset failed:', error);
setErrorState(error instanceof Error ? error.message : 'Reset failed');
setSystemStatus('error');
}
}, [startMonitoring]);
// Export system state and data
const exportSystemData = useCallback(async () => {
if (!isInitialized) return null;
try {
const exportData = {
timestamp: new Date().toISOString(),
memorySystem: memorySystem,
fileProcessing: {
...fileProcessing,
// Convert Maps to objects for JSON serialization
locations: Object.fromEntries(fileProcessing.locations),
encoding: Object.fromEntries(fileProcessing.encoding)
},
performanceLog: performanceLog.slice(-1000), // Last 1000 entries
systemStatus,
configuration: config
};
return exportData;
} catch (error) {
console.error('Export failed:', error);
return null;
}
}, [memorySystem, fileProcessing, performanceLog, systemStatus, config, isInitialized]);
// Render system status and controls
if (!isInitialized) {
return (
<div className="integrated-ai-system initializing">
<div className="status-indicator">
<div className="spinner"></div>
<span>Initializing Integrated AI System...</span>
</div>
</div>
);
}
if (systemStatus === 'error') {
return (
<div className="integrated-ai-system error">
<div className="error-display">
<h3>System Error</h3>
<p>{errorState}</p>
<button onClick={resetSystem}>Reset System</button>
</div>
</div>
);
}
return (
<div className="integrated-ai-system">
<div className="system-header">
<h2>Integrated AI System</h2>
<div className="system-controls">
<span className={`status-badge ${systemStatus}`}>{systemStatus}</span>
{systemStatus === 'running' && (
<button onClick={pauseSystem}>Pause</button>
)}
{systemStatus === 'paused' && (
<button onClick={resumeSystem}>Resume</button>
)}
<button onClick={resetSystem}>Reset</button>
<button onClick={exportSystemData}>Export Data</button>
</div>
</div>
<div className="system-dashboard">
<div className="memory-panel">
<h3>Memory System</h3>
<div className="memory-stats">
<div className="stat">
<label>Short-term:</label>
<span>{memorySystem.shortTerm.length}</span>
</div>
<div className="stat">
<label>Long-term:</label>
<span>{memorySystem.longTerm.length}</span>
</div>
<div className="stat">
<label>Archive:</label>
<span>{memorySystem.archive.length}</span>
</div>
<div className="stat">
<label>Compression Ratio:</label>
<span>{(memorySystem.compressionRatio * 100).toFixed(1)}%</span>
</div>
</div>
<button onClick={() => handleMemoryOperation('compress')}>
Compress Memories
</button>
</div>
<div className="file-processing-panel">
<h3>File Processing</h3>
<div className="file-stats">
<div className="stat">
<label>Queue:</label>
<span>{fileProcessing.queue.length}</span>
</div>
<div className="stat">
<label>Processed:</label>
<span>{fileProcessing.processed.length}</span>
</div>
<div className="categories">
{Object.entries(fileProcessing.categories).map(([category, data]) => (
<div key={category} className="category-stat">
<label>{category}:</label>
<span>{data.count}</span>
</div>
))}
</div>
</div>
<input
type="file"
multiple
onChange={(e) => e.target.files && handleFileUpload(e.target.files)}
accept="*/*"
/>
</div>
<div className="performance-panel">
<h3>Performance Monitor</h3>
<div className="performance-stats">
<div className="stat">
<label>Log Entries:</label>
<span>{performanceLog.length}</span>
</div>
<div className="stat">
<label>System Status:</label>
<span className={systemStatus}>{systemStatus}</span>
</div>
</div>
<button onClick={handlePerformanceCheck}>
Check Performance
</button>
</div>
</div>
</div>
);
};
export default IntegratedAISystem;
|