import { useState, useEffect, useMemo } from 'react'; import { invoke } from '@tauri-apps/api/core'; import { AreaChart, Area, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid } from 'recharts'; import { Activity, Cpu, Server, Database, Play, Square, AlertTriangle, ArrowLeft, Shield, CheckSquare, Square as SquareIcon, Save, X } from 'lucide-react'; import { clsx } from 'clsx'; import { twMerge } from 'tailwind-merge'; // --- Types --- interface ProcessStats { pid: number; name: string; cpu_usage: number; memory: number; status: string; user_id?: string; } interface SystemStats { cpu_usage: number[]; total_memory: number; used_memory: number; processes: ProcessStats[]; is_recording: boolean; recording_duration: number; } interface TimelinePoint { time: string; avg_cpu: number; memory_gb: number; } interface ProcessHistoryPoint { time: string; cpu_usage: number; memory_mb: number; } interface AggregatedProcess { name: string; avg_cpu: number; peak_cpu: number; avg_memory_mb: number; peak_memory_mb: number; instance_count: number; warnings: string[]; history: ProcessHistoryPoint[]; } interface ProfilingReport { start_time: string; end_time: string; duration_seconds: number; timeline: TimelinePoint[]; aggregated_processes: AggregatedProcess[]; } function cn(...inputs: (string | undefined | null | false)[]) { return twMerge(clsx(inputs)); } function App() { const [view, setView] = useState<'dashboard' | 'report'>('dashboard'); const [stats, setStats] = useState(null); const [history, setHistory] = useState<{ time: string; cpu: number }[]>([]); const [excludeSelf, setExcludeSelf] = useState(true); const [report, setReport] = useState(null); useEffect(() => { const fetchStats = async () => { try { const isRecording = stats?.is_recording ?? false; const data = await invoke('get_system_stats', { excludeSelf, minimal: isRecording || view === 'report' }); setStats(data); const avgCpu = data.cpu_usage.reduce((a, b) => a + b, 0) / data.cpu_usage.length; setHistory(prev => { const newHistory = [...prev, { time: new Date().toLocaleTimeString(), cpu: avgCpu }]; if (newHistory.length > 60) newHistory.shift(); return newHistory; }); } catch (e) { console.error(e); } }; fetchStats(); const interval = setInterval(fetchStats, 1000); return () => clearInterval(interval); }, [excludeSelf, view, stats?.is_recording]); const toggleRecording = async () => { if (stats?.is_recording) { const reportData = await invoke('stop_profiling'); setReport(reportData); setView('report'); } else { await invoke('start_profiling'); } }; const killProcess = async (pid: number) => { try { await invoke('run_as_admin', { command: `kill -9 ${pid}` }); } catch (e) { alert(`Failed to kill process: ${e}`); } }; if (view === 'report' && report) { return ( setView('dashboard')} /> ); } if (!stats) return
Loading System Data...
; const avgCpu = stats.cpu_usage.reduce((a, b) => a + b, 0) / stats.cpu_usage.length; const memoryPercent = (stats.used_memory / stats.total_memory) * 100; return (
SysPulse
{stats.is_recording ? (

Profiling Active

{formatDuration(stats.recording_duration)}

CPU
{avgCpu.toFixed(1)}%
RAM
{memoryPercent.toFixed(1)}%

Minimal footprint mode enabled to ensure accurate results.

) : ( <>
CPU Load
{avgCpu.toFixed(1)} %
Memory
{(stats.used_memory / 1024 / 1024 / 1024).toFixed(1)} GB used
{memoryPercent.toFixed(1)}% {(stats.total_memory / 1024 / 1024 / 1024).toFixed(0)} GB
Tasks
{stats.processes.length} active
Profiling will merge child processes into their parents for consolidated analysis.

Live Process Feed

Top 50 Consumers
Name
PID
CPU
Memory
Action
{stats.processes.map((proc) => (
{proc.name}
{proc.pid}
{proc.cpu_usage.toFixed(1)}%
{(proc.memory / 1024 / 1024).toFixed(0)} MB
))}
)}
); } type SortField = 'name' | 'avg_cpu' | 'peak_cpu' | 'avg_memory_mb' | 'peak_memory_mb' | 'instance_count'; function ReportView({ report, onBack }: { report: ProfilingReport, onBack: () => void }) { const [sortField, setSortField] = useState('avg_cpu'); const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc'); const [selectedProcess, setSelectedProcess] = useState(null); const handleSort = (field: SortField) => { if (sortField === field) { setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc'); } else { setSortField(field); setSortOrder('desc'); } }; const sortedProcesses = useMemo(() => { return [...report.aggregated_processes].sort((a, b) => { const valA = a[sortField as keyof AggregatedProcess]; const valB = b[sortField as keyof AggregatedProcess]; if (typeof valA === 'string' && typeof valB === 'string') { return sortOrder === 'asc' ? valA.localeCompare(valB) : valB.localeCompare(valA); } const numA = (valA as number) ?? 0; const numB = (valB as number) ?? 0; return sortOrder === 'asc' ? numA - numB : numB - numA; }); }, [report, sortField, sortOrder]); const saveReport = async () => { try { const path = await invoke('save_report', { report }); alert(`Report saved to: ${path}`); } catch (e) { alert(`Failed to save: ${e}`); } }; return (
Profiling Report
Session Time
{formatDuration(report.duration_seconds)}
End of Session
{new Date(report.end_time).toLocaleTimeString()}
Uniques
{report.aggregated_processes.length}
Issue Alerts
{report.aggregated_processes.filter(p => p.warnings.length > 0).length}

Session Load Profile

Analysis Matrix

CLICK PROCESS TO INSPECT
handleSort('name')}> Process {sortField === 'name' && (sortOrder === 'asc' ? '↑' : '↓')}
handleSort('instance_count')}>Units
handleSort('avg_cpu')}>Avg CPU
handleSort('peak_cpu')}>Peak CPU
handleSort('avg_memory_mb')}>Avg Mem
handleSort('peak_memory_mb')}>Peak Mem
Insights
{sortedProcesses.map((proc, i) => (
setSelectedProcess(proc)} className="table-row grid grid-cols-[2fr_0.8fr_1fr_1fr_1fr_1fr_2fr] gap-2 px-4 py-3 border-b border-surface1/20 hover:bg-surface1/30 cursor-pointer transition-colors group" >
{proc.name}
{proc.instance_count}
{proc.avg_cpu.toFixed(1)}%
{proc.peak_cpu.toFixed(1)}%
{proc.avg_memory_mb.toFixed(0)}MB
{proc.peak_memory_mb.toFixed(0)}MB
{proc.warnings.map((w, idx) => ( {w} ))}
))}
{/* Process Detail Side Panel/Modal */} {selectedProcess && (
Process Inspector

{selectedProcess.name}

Instances Detected
{selectedProcess.instance_count}

Maximum concurrent processes seen with this name.

Average Impact
{selectedProcess.avg_cpu.toFixed(1)}%

Mean CPU usage across the entire session.

Resource History (Summed)

Profiling Insights

{selectedProcess.warnings.length > 0 ? selectedProcess.warnings.map((w, idx) => (
{w}
)) : (
Optimal Performance Profile
)}
)}
); } function formatDuration(seconds: number) { const m = Math.floor(seconds / 60); const s = Math.floor(seconds % 60); return `${m}:${s.toString().padStart(2, '0')}`; } export default App;