import React, { useState, useEffect } from 'react'; import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from './ui/card'; import { Button } from './ui/button'; import { Badge } from './ui/badge'; import { Input } from './ui/input'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select'; import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs'; import { Alert, AlertDescription, AlertTitle } from './ui/alert'; import { Progress } from './ui/progress'; import { Separator } from './ui/separator'; import { Layers, Play, Pause, Square, Settings, Clock, TrendingUp, Activity, CheckCircle, AlertTriangle, XCircle, RefreshCw, Eye, Cpu, Zap, Target, BarChart3, Timer, DollarSign, Shield, Network, GitBranch, Box, ArrowRight, ArrowDown, MoreHorizontal } from 'lucide-react'; import { useToast } from '@/hooks/use-toast'; import { useWallet } from '@/hooks/use-wallet'; interface SubTask { subTaskId: string; parentTaskId: string; name: string; description: string; status: 'pending' | 'assigned' | 'in_progress' | 'completed' | 'failed' | 'cancelled'; assignedAgent?: string; dependencies: string[]; outputs: string[]; inputs: string[]; createdAt: string; startedAt?: string; completedAt?: string; errorMessage?: string; retryCount: number; maxRetries: number; requirements: { taskType: string; estimatedDuration: number; gpuTier: string; memoryRequirement: number; computeIntensity: number; dataSize: number; priority: number; maxCost?: number; }; } interface TaskDecomposition { originalTaskId: string; subTasks: SubTask[]; dependencyGraph: Record; executionPlan: string[][]; estimatedTotalDuration: number; estimatedTotalCost: number; confidenceScore: number; decompositionStrategy: string; createdAt: string; } interface TaskAggregation { aggregationId: string; parentTaskId: string; aggregationType: string; inputSubTasks: string[]; outputFormat: string; aggregationFunction: string; createdAt: string; } const TaskDecomposition: React.FC = () => { const { toast } = useToast(); const { isConnected, address } = useWallet(); const [decompositions, setDecompositions] = useState([]); const [selectedDecomposition, setSelectedDecomposition] = useState(null); const [aggregations, setAggregations] = useState([]); const [activeTab, setActiveTab] = useState('overview'); const [loading, setLoading] = useState(true); const [decomposing, setDecomposing] = useState(false); // Form states const [taskDescription, setTaskDescription] = useState(''); const [taskType, setTaskType] = useState('mixed_modal'); const [estimatedDuration, setEstimatedDuration] = useState('2'); const [gpuTier, setGpuTier] = useState('mid_range_gpu'); const [memoryRequirement, setMemoryRequirement] = useState('8'); const [dataSize, setDataSize] = useState('1000'); const [priority, setPriority] = useState('5'); const [maxCost, setMaxCost] = useState('0.5'); const [strategy, setStrategy] = useState('adaptive'); const [maxSubtasks, setMaxSubtasks] = useState('10'); // Mock data for demonstration const mockDecompositions: TaskDecomposition[] = [ { originalTaskId: 'task_001', subTasks: [ { subTaskId: 'subtask_001', parentTaskId: 'task_001', name: 'Data Preprocessing', description: 'Clean and preprocess input data', status: 'completed', assignedAgent: 'agent_001', dependencies: [], outputs: ['cleaned_data'], inputs: ['raw_data'], createdAt: '2024-01-26T14:00:00Z', startedAt: '2024-01-26T14:00:00Z', completedAt: '2024-01-26T14:30:00Z', retryCount: 0, maxRetries: 3, requirements: { taskType: 'data_analysis', estimatedDuration: 0.5, gpuTier: 'mid_range_gpu', memoryRequirement: 4, computeIntensity: 0.3, dataSize: 500, priority: 5, maxCost: 0.05 } }, { subTaskId: 'subtask_002', parentTaskId: 'task_001', name: 'Feature Extraction', description: 'Extract features from processed data', status: 'in_progress', assignedAgent: 'agent_002', dependencies: ['subtask_001'], outputs: ['features'], inputs: ['cleaned_data'], createdAt: '2024-01-26T14:30:00Z', startedAt: '2024-01-26T14:35:00Z', retryCount: 0, maxRetries: 3, requirements: { taskType: 'model_inference', estimatedDuration: 1.5, gpuTier: 'high_end_gpu', memoryRequirement: 8, computeIntensity: 0.8, dataSize: 300, priority: 7, maxCost: 0.15 } }, { subTaskId: 'subtask_003', parentTaskId: 'task_001', name: 'Result Aggregation', description: 'Aggregate and format results', status: 'pending', dependencies: ['subtask_002'], outputs: ['final_results'], inputs: ['features'], createdAt: '2024-01-26T14:30:00Z', retryCount: 0, maxRetries: 3, requirements: { taskType: 'data_analysis', estimatedDuration: 0.3, gpuTier: 'cpu_only', memoryRequirement: 2, computeIntensity: 0.2, dataSize: 100, priority: 3, maxCost: 0.02 } } ], dependencyGraph: { 'subtask_001': [], 'subtask_002': ['subtask_001'], 'subtask_003': ['subtask_002'] }, executionPlan: [ ['subtask_001'], ['subtask_002'], ['subtask_003'] ], estimatedTotalDuration: 2.3, estimatedTotalCost: 0.22, confidenceScore: 0.88, decompositionStrategy: 'sequential', createdAt: '2024-01-26T13:45:00Z' }, { originalTaskId: 'task_002', subTasks: [ { subTaskId: 'subtask_004', parentTaskId: 'task_002', name: 'Image Processing', description: 'Process input images', status: 'completed', assignedAgent: 'agent_003', dependencies: [], outputs: ['processed_images'], inputs: ['raw_images'], createdAt: '2024-01-26T12:00:00Z', startedAt: '2024-01-26T12:05:00Z', completedAt: '2024-01-26T13:05:00Z', retryCount: 0, maxRetries: 3, requirements: { taskType: 'image_processing', estimatedDuration: 1.0, gpuTier: 'high_end_gpu', memoryRequirement: 6, computeIntensity: 0.7, dataSize: 800, priority: 8, maxCost: 0.10 } }, { subTaskId: 'subtask_005', parentTaskId: 'task_002', name: 'Text Analysis', description: 'Analyze text content', status: 'completed', assignedAgent: 'agent_001', dependencies: [], outputs: ['text_features'], inputs: ['raw_text'], createdAt: '2024-01-26T12:00:00Z', startedAt: '2024-01-26T12:00:00Z', completedAt: '2024-01-26T12:45:00Z', retryCount: 0, maxRetries: 3, requirements: { taskType: 'text_processing', estimatedDuration: 0.75, gpuTier: 'mid_range_gpu', memoryRequirement: 4, computeIntensity: 0.4, dataSize: 200, priority: 6, maxCost: 0.04 } }, { subTaskId: 'subtask_006', parentTaskId: 'task_002', name: 'Multi-Modal Fusion', description: 'Combine image and text features', status: 'in_progress', assignedAgent: 'agent_004', dependencies: ['subtask_004', 'subtask_005'], outputs: ['fused_features'], inputs: ['processed_images', 'text_features'], createdAt: '2024-01-26T13:05:00Z', startedAt: '2024-01-26T13:10:00Z', retryCount: 0, maxRetries: 3, requirements: { taskType: 'mixed_modal', estimatedDuration: 1.5, gpuTier: 'premium_gpu', memoryRequirement: 12, computeIntensity: 0.9, dataSize: 1000, priority: 9, maxCost: 0.20 } } ], dependencyGraph: { 'subtask_004': [], 'subtask_005': [], 'subtask_006': ['subtask_004', 'subtask_005'] }, executionPlan: [ ['subtask_004', 'subtask_005'], ['subtask_006'] ], estimatedTotalDuration: 2.5, estimatedTotalCost: 0.34, confidenceScore: 0.92, decompositionStrategy: 'parallel', createdAt: '2024-01-26T11:50:00Z' } ]; const mockAggregations: TaskAggregation[] = [ { aggregationId: 'agg_001', parentTaskId: 'task_001', aggregationType: 'concat', inputSubTasks: ['subtask_001', 'subtask_002', 'subtask_003'], outputFormat: 'json', aggregationFunction: 'concatenate_results_json', createdAt: '2024-01-26T13:45:00Z' }, { aggregationId: 'agg_002', parentTaskId: 'task_002', aggregationType: 'merge', inputSubTasks: ['subtask_004', 'subtask_005', 'subtask_006'], outputFormat: 'array', aggregationFunction: 'merge_results_array', createdAt: '2024-01-26T11:50:00Z' } ]; useEffect(() => { // Load mock data setTimeout(() => { setDecompositions(mockDecompositions); setAggregations(mockAggregations); if (mockDecompositions.length > 0) { setSelectedDecomposition(mockDecompositions[0]); } setLoading(false); }, 1000); }, []); const handleDecomposeTask = async () => { if (!isConnected) { toast({ title: "Wallet Not Connected", description: "Please connect your wallet to decompose tasks", variant: "destructive" }); return; } if (!taskDescription || !taskType || !estimatedDuration) { toast({ title: "Missing Information", description: "Please fill in all required task details", variant: "destructive" }); return; } try { setDecomposing(true); toast({ title: "Decomposing Task", description: "Analyzing task and creating sub-tasks...", variant: "default" }); // Simulate decomposition await new Promise(resolve => setTimeout(resolve, 3000)); // Create new decomposition const newDecomposition: TaskDecomposition = { originalTaskId: `task_${Date.now()}`, subTasks: [ { subTaskId: `subtask_${Date.now()}_1`, parentTaskId: `task_${Date.now()}`, name: 'Initial Processing', description: 'Process initial task requirements', status: 'pending', dependencies: [], outputs: ['processed_data'], inputs: ['raw_input'], createdAt: new Date().toISOString(), retryCount: 0, maxRetries: 3, requirements: { taskType: taskType, estimatedDuration: parseFloat(estimatedDuration) * 0.3, gpuTier: gpuTier, memoryRequirement: parseInt(memoryRequirement) * 0.5, computeIntensity: 0.5, dataSize: parseInt(dataSize) * 0.3, priority: parseInt(priority), maxCost: parseFloat(maxCost) * 0.3 } }, { subTaskId: `subtask_${Date.now()}_2`, parentTaskId: `task_${Date.now()}`, name: 'Main Computation', description: 'Execute main task computation', status: 'pending', dependencies: [`subtask_${Date.now()}_1`], outputs: ['computed_results'], inputs: ['processed_data'], createdAt: new Date().toISOString(), retryCount: 0, maxRetries: 3, requirements: { taskType: taskType, estimatedDuration: parseFloat(estimatedDuration) * 0.6, gpuTier: gpuTier, memoryRequirement: parseInt(memoryRequirement), computeIntensity: 0.8, dataSize: parseInt(dataSize) * 0.6, priority: parseInt(priority), maxCost: parseFloat(maxCost) * 0.6 } }, { subTaskId: `subtask_${Date.now()}_3`, parentTaskId: `task_${Date.now()}`, name: 'Result Processing', description: 'Process and format results', status: 'pending', dependencies: [`subtask_${Date.now()}_2`], outputs: ['final_results'], inputs: ['computed_results'], createdAt: new Date().toISOString(), retryCount: 0, maxRetries: 3, requirements: { taskType: taskType, estimatedDuration: parseFloat(estimatedDuration) * 0.1, gpuTier: 'cpu_only', memoryRequirement: parseInt(memoryRequirement) * 0.3, computeIntensity: 0.2, dataSize: parseInt(dataSize) * 0.1, priority: parseInt(priority), maxCost: parseFloat(maxCost) * 0.1 } } ], dependencyGraph: { [`subtask_${Date.now()}_1`]: [], [`subtask_${Date.now()}_2`]: [`subtask_${Date.now()}_1`], [`subtask_${Date.now()}_3`]: [`subtask_${Date.now()}_2`] }, executionPlan: [ [`subtask_${Date.now()}_1`], [`subtask_${Date.now()}_2`], [`subtask_${Date.now()}_3`] ], estimatedTotalDuration: parseFloat(estimatedDuration), estimatedTotalCost: parseFloat(maxCost), confidenceScore: 0.85, decompositionStrategy: strategy, createdAt: new Date().toISOString() }; setDecompositions([newDecomposition, ...decompositions]); setSelectedDecomposition(newDecomposition); setActiveTab('decompositions'); // Reset form setTaskDescription(''); setTaskType('mixed_modal'); setEstimatedDuration('2'); setGpuTier('mid_range_gpu'); setMemoryRequirement('8'); setDataSize('1000'); setPriority('5'); setMaxCost('0.5'); setStrategy('adaptive'); setMaxSubtasks('10'); toast({ title: "Task Decomposed", description: `Task decomposed into ${newDecomposition.subTasks.length} sub-tasks`, variant: "default" }); } catch (error) { toast({ title: "Decomposition Failed", description: "There was an error decomposing the task", variant: "destructive" }); } finally { setDecomposing(false); } }; const getStatusColor = (status: string) => { switch (status) { case 'completed': return 'bg-green-500'; case 'in_progress': return 'bg-blue-500'; case 'pending': return 'bg-yellow-500'; case 'failed': return 'bg-red-500'; case 'cancelled': return 'bg-gray-500'; default: return 'bg-gray-400'; } }; const getOverallProgress = (decomposition: TaskDecomposition) => { const completedCount = decomposition.subTasks.filter(st => st.status === 'completed').length; return (completedCount / decomposition.subTasks.length) * 100; }; const renderExecutionPlan = (plan: string[][]) => { return (
{plan.map((stage, stageIndex) => (
{stageIndex + 1}
{stageIndex < plan.length - 1 && ( )}
{stage.map((subTaskId) => { const subTask = selectedDecomposition?.subTasks.find(st => st.subTaskId === subTaskId); return (
{subTask?.name || subTaskId}
); })}

{stage.length > 1 ? 'Parallel execution' : 'Sequential execution'}

))}
); }; if (loading) { return (

Loading task decomposition system...

); } return (

Task Decomposition

Intelligent task splitting and sub-task management system

{decompositions.length} Decompositions {aggregations.length} Aggregations
Overview Decompositions Decompose Task Aggregations {/* System Statistics */}
Total Decompositions
{decompositions.length}
Total Sub-tasks
{decompositions.reduce((sum, d) => sum + d.subTasks.length, 0)}
Avg Duration
{(decompositions.reduce((sum, d) => sum + d.estimatedTotalDuration, 0) / decompositions.length || 0).toFixed(1)}h
Avg Cost
{(decompositions.reduce((sum, d) => sum + d.estimatedTotalCost, 0) / decompositions.length || 0).toFixed(3)} AITBC
{/* Recent Decompositions */} Recent Task Decompositions Latest task decomposition activities
{decompositions.slice(0, 3).map((decomposition) => (
{decomposition.subTasks.length}

sub-tasks

{decomposition.originalTaskId}

{decomposition.decompositionStrategy} • {decomposition.estimatedTotalDuration.toFixed(1)}h • {decomposition.estimatedTotalCost.toFixed(3)} AITBC

{getOverallProgress(decomposition).toFixed(0)}%

{new Date(decomposition.createdAt).toLocaleDateString()}

))}
{/* Decomposition Selection */}
{/* Decompositions List */} Task Decompositions Available task decompositions
{decompositions.map((decomposition) => (
setSelectedDecomposition(decomposition)} >

{decomposition.originalTaskId}

{decomposition.decompositionStrategy} {(decomposition.confidenceScore * 100).toFixed(0)}% confidence
Sub-tasks: {decomposition.subTasks.length}
Duration: {decomposition.estimatedTotalDuration.toFixed(1)}h
Cost: {decomposition.estimatedTotalCost.toFixed(3)} AITBC
{getOverallProgress(decomposition).toFixed(0)}%
))}
{/* Decomposition Details */} {selectedDecomposition && ( {selectedDecomposition.originalTaskId} Detailed task decomposition information {/* Overview */}

Strategy

{selectedDecomposition.decompositionStrategy}

Confidence

{(selectedDecomposition.confidenceScore * 100).toFixed(1)}%

Total Duration

{selectedDecomposition.estimatedTotalDuration.toFixed(1)}h

Total Cost

{selectedDecomposition.estimatedTotalCost.toFixed(3)} AITBC

{/* Execution Plan */}

Execution Plan

{renderExecutionPlan(selectedDecomposition.executionPlan)}
{/* Sub-tasks */}

Sub-tasks

{selectedDecomposition.subTasks.map((subTask) => (
{subTask.name}

{subTask.description}

Type:

{subTask.requirements.taskType}

Duration:

{subTask.requirements.estimatedDuration}h

GPU:

{subTask.requirements.gpuTier.replace('_', ' ')}

Memory:

{subTask.requirements.memoryRequirement}GB

{subTask.assignedAgent && (
Assigned to:

{subTask.assignedAgent}

)}
))}
)}
{/* Task Decomposition Form */} Decompose New Task Create a new task decomposition with intelligent sub-task splitting