Fix memory usage via /proc/meminfo on Linux

This commit is contained in:
Chris Wanstrath 2026-02-24 19:05:04 -08:00
parent 4d42b48c8f
commit 51e42dc538

View File

@ -1,7 +1,7 @@
import { allApps, APPS_DIR, onChange, TOES_DIR } from '$apps'
import { onHostLog } from '../tui'
import { Hype } from '@because/hype'
import { cpus, platform, totalmem } from 'os'
import { cpus, freemem, platform, totalmem } from 'os'
import { join } from 'path'
import { existsSync, mkdirSync, readFileSync, statfsSync, writeFileSync } from 'fs'
@ -68,37 +68,23 @@ function getCpuUsage(): number {
function getMemoryUsage(): { used: number, total: number, percent: number } {
const total = totalmem()
const apps = allApps().filter(a => a.proc?.pid)
let used = 0
if (platform() === 'linux') {
for (const app of apps) {
try {
const status = readFileSync(`/proc/${app.proc!.pid}/status`, 'utf-8')
const match = status.match(/VmRSS:\s+(\d+)/)
if (match) used += parseInt(match[1]!, 10) * 1024
} catch {}
}
} else {
// macOS: batch ps call for all pids
const pids = apps.map(a => a.proc!.pid).join(',')
if (pids) {
try {
const result = Bun.spawnSync(['ps', '-o', 'rss=', '-p', pids])
const output = result.stdout.toString()
for (const line of output.split('\n')) {
const kb = parseInt(line.trim(), 10)
if (kb) used += kb * 1024
}
} catch {}
}
try {
const meminfo = readFileSync('/proc/meminfo', 'utf-8')
const available = meminfo.match(/MemAvailable:\s+(\d+)/)
if (available) {
const availableBytes = parseInt(available[1]!, 10) * 1024
const used = total - availableBytes
return { used, total, percent: Math.round((used / total) * 100) }
}
} catch {}
}
return {
used,
total,
percent: used > 0 ? Math.max(1, Math.round((used / total) * 100)) : 0,
}
// macOS fallback
const free = freemem()
const used = total - free
return { used, total, percent: Math.round((used / total) * 100) }
}
function getDiskUsage(): { used: number, total: number, percent: number } {