// Name: System Health Check // Description: Monitor system resources and performance metrics // Author: s3cr1z import '@johnlindquist/kit' import os from 'os' import { checkDiskSpace } from 'check-disk-space' interface SystemStats { cpuUsage: number memoryUsage: { total: number used: number free: number percentage: number } diskSpace: { total: number used: number free: number percentage: number } uptime: number loadAverage: number[] } const getCPUUsage = async (): Promise<number> => { const cpus = os.cpus() // Get initial CPU times const startTimes = cpus.map(cpu => { const times = cpu.times return { idle: times.idle, total: times.idle + times.user + times.nice + times.sys + times.irq } }) // Wait 100ms for measurement await wait(100) // Get CPU times after delay const endCpus = os.cpus() const endTimes = endCpus.map(cpu => { const times = cpu.times return { idle: times.idle, total: times.idle + times.user + times.nice + times.sys + times.irq } }) // Calculate CPU usage percentage let totalIdle = 0 let totalTick = 0 for (let i = 0; i < startTimes.length; i++) { const idleDiff = endTimes[i].idle - startTimes[i].idle const totalDiff = endTimes[i].total - startTimes[i].total totalIdle += idleDiff totalTick += totalDiff } const idle = totalIdle / startTimes.length const total = totalTick / startTimes.length const usage = 100 - ~~(100 * idle / total) return Math.max(0, Math.min(100, usage)) } const getSystemStats = async (): Promise<SystemStats> => { const cpuUsage = await getCPUUsage() const totalMemory = os.totalmem() const freeMemory = os.freemem() const usedMemory = totalMemory - freeMemory const memoryPercentage = (usedMemory / totalMemory) * 100 let diskInfo try { diskInfo = await checkDiskSpace(isMac ? '/' : 'C:') } catch (error) { // Fallback for systems where check-disk-space might not work diskInfo = { size: 0, free: 0, used: 0 } } const diskPercentage = diskInfo.size > 0 ? ((diskInfo.size - diskInfo.free) / diskInfo.size) * 100 : 0 return { cpuUsage, memoryUsage: { total: totalMemory, used: usedMemory, free: freeMemory, percentage: memoryPercentage }, diskSpace: { total: diskInfo.size, used: diskInfo.size - diskInfo.free, free: diskInfo.free, percentage: diskPercentage }, uptime: os.uptime(), loadAverage: os.loadavg() } } const formatBytes = (bytes: number): string => { const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'] if (bytes === 0) return '0 Bytes' const i = Math.floor(Math.log(bytes) / Math.log(1024)) return Math.round((bytes / Math.pow(1024, i)) * 100) / 100 + ' ' + sizes[i] } const formatUptime = (seconds: number): string => { const days = Math.floor(seconds / 86400) const hours = Math.floor((seconds % 86400) / 3600) const minutes = Math.floor((seconds % 3600) / 60) if (days > 0) { return `${days}d ${hours}h ${minutes}m` } else if (hours > 0) { return `${hours}h ${minutes}m` } else { return `${minutes}m` } } const getHealthStatus = (percentage: number): { status: string; color: string; emoji: string } => { if (percentage < 50) { return { status: 'Good', color: 'text-green-500', emoji: '✅' } } else if (percentage < 80) { return { status: 'Warning', color: 'text-yellow-500', emoji: '⚠️' } } else { return { status: 'Critical', color: 'text-red-500', emoji: '🚨' } } } const displayStats = async () => { const stats = await getSystemStats() const cpuHealth = getHealthStatus(stats.cpuUsage) const memoryHealth = getHealthStatus(stats.memoryUsage.percentage) const diskHealth = getHealthStatus(stats.diskSpace.percentage) const systemInfo = ` ## 🖥️ System Health Monitor ### CPU Usage ${cpuHealth.emoji} <div class="${cpuHealth.color} font-semibold"> ${stats.cpuUsage.toFixed(1)}% - ${cpuHealth.status} </div> **Load Average:** ${stats.loadAverage.map(load => load.toFixed(2)).join(', ')} ### Memory Usage ${memoryHealth.emoji} <div class="${memoryHealth.color} font-semibold"> ${formatBytes(stats.memoryUsage.used)} / ${formatBytes(stats.memoryUsage.total)} (${stats.memoryUsage.percentage.toFixed(1)}%) - ${memoryHealth.status} </div> **Available:** ${formatBytes(stats.memoryUsage.free)} ### Disk Space ${diskHealth.emoji} <div class="${diskHealth.color} font-semibold"> ${formatBytes(stats.diskSpace.used)} / ${formatBytes(stats.diskSpace.total)} (${stats.diskSpace.percentage.toFixed(1)}%) - ${diskHealth.status} </div> **Available:** ${formatBytes(stats.diskSpace.free)} ### System Information **Uptime:** ${formatUptime(stats.uptime)} **Platform:** ${os.platform()} ${os.arch()} **Node.js:** ${process.version} **CPU Cores:** ${os.cpus().length} --- *Last updated: ${new Date().toLocaleTimeString()}* ` await div({ html: md(systemInfo), shortcuts: [ { name: 'Refresh', key: 'r', onPress: () => { displayStats() }, bar: 'right' }, { name: 'Export Report', key: `${cmd}+e`, onPress: async () => { const reportPath = tmpPath(`system-health-${Date.now()}.md`) await writeFile(reportPath, systemInfo.replace(/### /g, '## ').replace(/## 🖥️/g, '# 🖥️')) await revealFile(reportPath) toast('Health report exported!') }, bar: 'right' } ] }) } await displayStats()// Name: System Health Check // Description: Monitor system resources and performance metrics with status indicators // Author: s3cr1z import '@johnlindquist/kit' import os from 'os' import { checkDiskSpace } from 'check-disk-space' interface SystemStats { cpuUsage: number memoryUsage: { total: number used: number free: number percentage: number } diskSpace: { total: number used: number free: number percentage: number } uptime: number loadAverage: number[] } interface HealthStatus { status: string color: string emoji: string indicator: string } /** * Calculates CPU usage percentage by measuring CPU times over a brief interval * @returns Promise<number> CPU usage percentage (0-100) */ const getCPUUsage = async (): Promise<number> => { try { const cpus = os.cpus() // Capture initial CPU times for all cores const startTimes = cpus.map(cpu => { const { idle, user, nice, sys, irq } = cpu.times return { idle, total: idle + user + nice + sys + irq } }) // Brief delay for measurement accuracy await wait(100) // Capture CPU times after delay const endCpus = os.cpus() const endTimes = endCpus.map(cpu => { const { idle, user, nice, sys, irq } = cpu.times return { idle, total: idle + user + nice + sys + irq } }) // Calculate average CPU usage across all cores let totalIdleDiff = 0 let totalTimeDiff = 0 for (let i = 0; i < startTimes.length; i++) { const idleDiff = endTimes[i].idle - startTimes[i].idle const totalDiff = endTimes[i].total - startTimes[i].total totalIdleDiff += idleDiff totalTimeDiff += totalDiff } if (totalTimeDiff === 0) return 0 const usage = 100 - (100 * totalIdleDiff / totalTimeDiff) return Math.max(0, Math.min(100, usage)) } catch (error) { console.warn('Failed to calculate CPU usage:', error) return 0 } } /** * Retrieves comprehensive system statistics * @returns Promise<SystemStats> Complete system metrics */ const getSystemStats = async (): Promise<SystemStats> => { // Set status to indicate data collection setStatus({ status: 'busy', message: '📊 Collecting system metrics...' }) const [cpuUsage] = await Promise.all([getCPUUsage()]) // Memory calculations const totalMemory = os.totalmem() const freeMemory = os.freemem() const usedMemory = totalMemory - freeMemory const memoryPercentage = (usedMemory / totalMemory) * 100 // Disk space with cross-platform support let diskInfo = { size: 0, free: 0 } try { const diskPath = process.platform === 'win32' ? 'C:' : '/' diskInfo = await checkDiskSpace(diskPath) } catch (error) { console.warn('Failed to get disk space:', error) } const diskUsed = diskInfo.size - diskInfo.free const diskPercentage = diskInfo.size > 0 ? (diskUsed / diskInfo.size) * 100 : 0 return { cpuUsage, memoryUsage: { total: totalMemory, used: usedMemory, free: freeMemory, percentage: memoryPercentage }, diskSpace: { total: diskInfo.size, used: diskUsed, free: diskInfo.free, percentage: diskPercentage }, uptime: os.uptime(), loadAverage: os.loadavg() } } /** * Formats bytes into human-readable units with proper precision * @param bytes Number of bytes to format * @returns Formatted string with appropriate unit */ const formatBytes = (bytes: number): string => { const units = ['B', 'KB', 'MB', 'GB', 'TB'] if (bytes === 0) return '0 B' const unitIndex = Math.floor(Math.log(bytes) / Math.log(1024)) const value = bytes / Math.pow(1024, unitIndex) const precision = unitIndex === 0 ? 0 : 1 return `${value.toFixed(precision)} ${units[unitIndex]}` } /** * Formats uptime seconds into human-readable duration * @param seconds Total uptime in seconds * @returns Formatted duration string */ const formatUptime = (seconds: number): string => { const units = [ { label: 'd', value: Math.floor(seconds / 86400) }, { label: 'h', value: Math.floor((seconds % 86400) / 3600) }, { label: 'm', value: Math.floor((seconds % 3600) / 60) } ] const nonZeroUnits = units.filter(unit => unit.value > 0) if (nonZeroUnits.length === 0) return '< 1m' return nonZeroUnits .slice(0, 2) // Show max 2 units for readability .map(unit => `${unit.value}${unit.label}`) .join(' ') } /** * Determines health status based on usage percentage with visual indicators * @param percentage Usage percentage (0-100) * @returns Health status object with styling and indicators */ const getHealthStatus = (percentage: number): HealthStatus => { if (percentage < 50) { return { status: 'Healthy', color: 'text-green-600', emoji: '💚', indicator: '🟢' } } else if (percentage < 80) { return { status: 'Warning', color: 'text-yellow-600', emoji: '💛', indicator: '🟡' } } else { return { status: 'Critical', color: 'text-red-600', emoji: '❤️', indicator: '🔴' } } } /** * Creates and displays the system health dashboard */ const displayStats = async (): Promise<void> => { try { const stats = await getSystemStats() // Determine health status for each metric const cpuHealth = getHealthStatus(stats.cpuUsage) const memoryHealth = getHealthStatus(stats.memoryUsage.percentage) const diskHealth = getHealthStatus(stats.diskSpace.percentage) // Update system tray with overall status const overallHealth = Math.max( stats.cpuUsage, stats.memoryUsage.percentage, stats.diskSpace.percentage ) const overallStatus = getHealthStatus(overallHealth) setStatus({ status: overallHealth > 80 ? 'warn' : 'ready', message: `${overallStatus.indicator} System ${overallStatus.status}` }) const systemReport = ` ## 🖥️ System Health Dashboard ### ${cpuHealth.indicator} CPU Performance <div class="${cpuHealth.color} font-bold text-lg"> ${stats.cpuUsage.toFixed(1)}% • ${cpuHealth.status} </div> <div class="text-sm text-gray-600 mt-1"> **Load Average:** ${stats.loadAverage.map(load => load.toFixed(2)).join(' • ')} </div> ### ${memoryHealth.indicator} Memory Usage <div class="${memoryHealth.color} font-bold text-lg"> ${formatBytes(stats.memoryUsage.used)} / ${formatBytes(stats.memoryUsage.total)} (${stats.memoryUsage.percentage.toFixed(1)}%) </div> <div class="text-sm text-gray-600 mt-1"> **Available:** ${formatBytes(stats.memoryUsage.free)} • **Status:** ${memoryHealth.status} </div> ### ${diskHealth.indicator} Storage Space <div class="${diskHealth.color} font-bold text-lg"> ${formatBytes(stats.diskSpace.used)} / ${formatBytes(stats.diskSpace.total)} (${stats.diskSpace.percentage.toFixed(1)}%) </div> <div class="text-sm text-gray-600 mt-1"> **Available:** ${formatBytes(stats.diskSpace.free)} • **Status:** ${diskHealth.status} </div> ### 📋 System Information **🕐 Uptime:** ${formatUptime(stats.uptime)} **💻 Platform:** ${os.platform()} ${os.arch()} **⚡ Node.js:** ${process.version} **🔧 CPU Cores:** ${os.cpus().length} --- <div class="text-xs text-gray-500 text-center"> Last updated: ${new Date().toLocaleString()} • Press 'r' to refresh </div> ` await div({ html: md(systemReport), shortcuts: [ { name: '🔄 Refresh', key: 'r', onPress: () => displayStats(), bar: 'right' }, { name: '📄 Export Report', key: `${cmd}+e`, onPress: async () => { try { const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-') const reportPath = tmpPath(`system-health-${timestamp}.md`) const cleanReport = systemReport .replace(/### /g, '## ') .replace(/## 🖥️/g, '# 🖥️') .replace(/<div[^>]*>/g, '') .replace(/<\/div>/g, '') await writeFile(reportPath, cleanReport) await revealFile(reportPath) toast('📊 Health report exported successfully!') } catch (error) { toast('❌ Failed to export report') console.error('Export error:', error) } }, bar: 'right' } ] }) } catch (error) { console.error('Failed to display system stats:', error) setStatus({ status: 'error', message: '❌ Failed to load system metrics' }) await div(md(` ## ❌ System Health Check Failed Unable to retrieve system metrics. Please try again. **Error:** ${error instanceof Error ? error.message : 'Unknown error'} `)) } } // Initialize the health check dashboard await displayStats()