dotfiles bugabingas dorkfiles
owned by bugabinga
README Source History Refs Reviews Compare Notes Search Review guide CI runs feat(system): redesign system popup — fast graphical widget 191d141480d7365e6b1154a677d7c1348a21b06b
Oliver Jan Krylow <oliver@bugabinga.net > · 28 Jun 2026
unsigned
Browse files Compare with HEAD
Replace the slow, Canvas-based system popout with a graphical widget:
machine identity card + live stats card + proactive issues band.
Architecture (mirrors caldav.js):
- sysinfo.js: pure, node-tested parsing + detectIssues logic (dual-mode
export, no I/O). sysinfo.test.js covers parsers, issue thresholds,
battery-wear tiers, formatters, ring cap — ALL PASS.
- Resources.qml: thin I/O + cadence service over sysinfo.js. FileView
/proc + /sys hwmon reads (no shell spawn in the fast path); three
cadences (fast 2s always; slow 5s + rare on-open, gated on popoutOpen);
ring buffers capped at 32 (was 3600). Battery via UPower displayDevice,
throttle via PowerProfiles.degradationReason.
- PopoutHost.qml systemContent: full rewrite — two rounded cards
(machine identity / live metrics), MetricRow (label+value+fill-bar+
sparkline), issues band with severity accent + click-to-act, top-procs.
Deleted Canvas ResourceMeter, SystemMetric, mini-graph shader.
DI: UPower/PowerProfiles/Brightness injected at the Resources instance in
shell.qml; new `system` IPC target (state/selfTest), selfTest 16/16.
Review fixes folded in:
- parseDiskstats: skip partitions (were double-counting whole-disk +
partition lines -> ~2x disk rate).
- Sparkline: metric-aware scaleMax (cpu/mem=1, temp=tempHighC, net/disk
window-max) so bars match the fill-bar instead of all normalizing to
window max.
- Restore firestormTarget on Resources (continuous temp ramp) so
AuroraBackdrop's heat reaction keeps working after the rework.
- identity host: uname -n (hostname binary absent on host).
- issues band: solid dark card bg + severity left-accent (was a
near-transparent tint bleeding the light popup frame through).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Changed files (6) Diff layout Auto Unified Split
quickshell/nuguland/PopoutHost.qml Modified +568 / −303 text lines
3 3 import Quickshell.Waylandimport Quickshell.Wayland4 4 import "Util.js" as Util import "Util.js" as Util 5 5 import "caldav.js" as Ical import "caldav.js" as Ical
6 + import "sysinfo.js" as Sys 7 8 PanelWindow {PanelWindow {674 675 id : systemPanel id : systemPanel676 - readonly property var state: root.resourceService ? Util .parseJson(root.resourceService.systemWidgetState(), {679 + readonly property var rs: root.resourceService680 + readonly property var identity: rs ? rs.identity : ({693 - readonly property real cpuUsage : root.resourceService ? root.resourceService.cpuUsage : 0 694 - readonly property real memoryUsage : root.resourceService ? root.resourceService.memoryUsage : 0 695 - readonly property real swapUsage : root.resourceService ? root.resourceService.swapUsage : 0 696 - readonly property string memoryLabel : root.resourceService ? ` ${root.resourceService.formatBytes(Math .max (0 , root.resourceService.memTotal - root.resourceService.memAvailable))} / ${root.resourceService.formatBytes(root.resourceService.memTotal)}` : "--" 697 - readonly property string swapLabel : root.resourceService && root.resourceService.swapTotal > 0 ? ` ${root.resourceService.formatBytes(Math .max (0 , root.resourceService.swapTotal - root.resourceService.swapFree))} / ${root.resourceService.formatBytes(root.resourceService.swapTotal)}` : "off" 698 - readonly property string diskLabel : root.resourceService ? `R ${root.resourceService.formatRate(root.resourceService.diskReadRate)} W ${root.resourceService.formatRate(root.resourceService.diskWriteRate)}` : "R 0 B/s W 0 B/s" 699 - readonly property string tempLabel : root.resourceService ? root.resourceService.tempLabel : "n/a" 700 - readonly property color cpuColor : root.theme ? root.theme.ui.accent : "#d86dd8" 701 - readonly property color memoryColor : root.theme ? root.theme.ui.focus : "#9aabae" 702 - readonly property color swapColor : root.theme ? root.theme.warning : "#f0ee69" 703 - readonly property color diskColor : root.theme ? root.theme.ui.minor : "#9d9d9d" 704 - readonly property color tempColor : root.theme ? root.theme.error : "#ec6376" 684 + readonly property var issueList: {695 + rs.healthPercentage;707 700 width : parent ? parent.width : 0 width : parent ? parent.width : 0 712 - seriesSamples : root.resourceService ? root.resourceService.systemHistorySamples : []713 - seriesColors : [parent.cpuColor, parent.memoryColor, parent.swapColor, parent.diskColor, parent.tempColor]714 - normalizeSeries : true 715 - trackColor : root.theme ? root.theme.ui.minor : "black" 721 - valueText : ` ${Math .round (parent.cpuUsage * 100 )}%` 722 - value : parent.cpuUsage723 - barColor : parent.cpuColor729 - valueText : ` ${Math .round (parent.memoryUsage * 100 )}% · ${parent.memoryLabel}` 730 - value : parent.memoryUsage731 - barColor : parent.memoryColor737 - valueText : parent.swapLabel === "off" ? "off" : ` ${Math .round (parent.swapUsage * 100 )}% · ${parent.swapLabel}` 738 - value : parent.swapUsage739 - barColor : parent.swapColor703 + Component .onCompleted: {705 + rs.popoutOpen = true ;708 + Component .onDestruction: {710 + rs.popoutOpen = false ;743 - objectName : "systemDiskRow" 718 + readonly property real cardW : Math .max (1 , (width - spacing) / 2 )726 + width : cardRow.cardW727 + height : cardRow.height729 + color : root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, 0.55 ) : "#242424" 732 + anchors.fill: parent741 + color : root.theme ? root.theme.ui.accent : "white" 742 + font.family: "Symbols Nerd Font Mono" 757 + value : systemPanel.identity.host || "—" 763 + value : systemPanel.identity.model || "—" 769 + value : systemPanel.identity.distro || "—" 775 + value : systemPanel.identity.kernel || "—" 781 + value : systemPanel.identity.wm || "—" 787 + value : systemPanel.identity.packages ? ` ${systemPanel.identity.packages} packages` : "—" 793 + value : systemPanel.identity.shell || "—" 799 + value : systemPanel.identity.uptime || "—" 806 + visible : systemPanel.rs && systemPanel.rs.isLaptopBattery808 + if (! systemPanel.rs)811 + const h = systemPanel.rs.healthPercentage;812 + return (h === null || h === undefined ) ? "battery health n/a" : `battery health ${Math .round (Number (h))}%` ;755 - text : systemPanel.diskLabel756 - width : parent.width - 100 757 - elide : Text .ElideRight763 - objectName : "systemTempRow" 775 - text : systemPanel.tempLabel776 - width : parent.width - 100 777 - elide : Text .ElideRight822 + width : cardRow.cardW823 + height : cardRow.height825 + color : root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, 0.55 ) : "#242424" 828 + anchors.fill: parent837 + color : root.theme ? root.theme.ui.accent : "white" 838 + font.family: "Symbols Nerd Font Mono" 853 + value : systemPanel.rs ? ` ${Math .round (systemPanel.rs.cpuUsage * 100 )}%` : "—" 854 + fraction : systemPanel.rs ? systemPanel.rs.cpuUsage : 0 855 + barColor : root.theme ? root.theme.ui.accent : "#d86dd8" 856 + ring : systemPanel.rs ? systemPanel.rs.cpuRing : []863 + value : systemPanel.rs ? ` ${Math .round (systemPanel.rs.memoryUsage * 100 )}% · ${Sys .formatBytes(Math .max (0 , systemPanel.rs.memTotal - systemPanel.rs.memAvailable))}` : "—" 864 + fraction : systemPanel.rs ? systemPanel.rs.memoryUsage : 0 865 + barColor : root.theme ? root.theme.ui.focus : "#9aabae" 866 + ring : systemPanel.rs ? systemPanel.rs.memRing : []874 + if (! systemPanel.rs || systemPanel.rs.swapTotal <= 0 )877 + return ` ${Math .round (systemPanel.rs.swapUsage * 100 )}% · ${Sys .formatBytes(Math .max (0 , systemPanel.rs.swapTotal - systemPanel.rs.swapFree))}` ;879 + fraction : systemPanel.rs ? systemPanel.rs.swapUsage : 0 880 + barColor : root.theme ? root.theme.warning : "#f0ee69" 889 + if (! systemPanel.rs)892 + const t = systemPanel.rs.cpuTemperatureC;893 + const f = systemPanel.rs.fanRpm;894 + const ts = (t === null || t === undefined ) ? "n/a" : ` ${Math .round (Number (t))}°C` ;895 + const fs = (f === null || f === undefined ) ? "" : ` · ${Math .round (Number (f))} rpm` ;899 + if (! systemPanel.rs)902 + const t = systemPanel.rs.cpuTemperatureC;903 + if (t === null || t === undefined )906 + return Math .max (0 , Math .min (1 , Number (t) / Math .max (1 , systemPanel.rs.tempHighC)));908 + barColor : root.theme ? root.theme.error : "#ec6376" 910 + showSpark : systemPanel.rs && systemPanel.rs.cpuTemperatureC !== null 911 + ring : systemPanel.rs ? systemPanel.rs.tempRing : []912 + sparkScaleMax : systemPanel.rs ? Math .max (1 , systemPanel.rs.tempHighC) : 1 918 + value : systemPanel.rs ? `↓ ${Sys .formatRate(systemPanel.rs.networkRxRate)} ↑ ${Sys .formatRate(systemPanel.rs.networkTxRate)}` : "—" 921 + if (! systemPanel.rs)924 + const ring = systemPanel.rs.netRing || [];926 + for (let i = 0 ; i < ring.length; i++ ) m = Math .max (m, Number (ring[i]) || 0 )927 + const cur = systemPanel.rs.networkRxRate + systemPanel.rs.networkTxRate;928 + return m > 0 ? Math .min (1 , cur / m) : 0 ;930 + barColor : root.theme ? root.theme.info : "#3ec5e3" 931 + ring : systemPanel.rs ? systemPanel.rs.netRing : []937 + value : systemPanel.rs ? `R ${Sys .formatRate(systemPanel.rs.diskReadRate)} W ${Sys .formatRate(systemPanel.rs.diskWriteRate)}` : "—" 939 + if (! systemPanel.rs)942 + const ring = systemPanel.rs.diskRing || [];944 + for (let i = 0 ; i < ring.length; i++ ) m = Math .max (m, Number (ring[i]) || 0 )945 + const cur = systemPanel.rs.diskReadRate + systemPanel.rs.diskWriteRate;946 + return m > 0 ? Math .min (1 , cur / m) : 0 ;948 + barColor : root.theme ? root.theme.ui.minor : "#9d9d9d" 949 + ring : systemPanel.rs ? systemPanel.rs.diskRing : []955 + text : systemPanel.rs ? `load ${systemPanel.rs.loadOne.toFixed(2 )} · ${systemPanel.rs.loadFive.toFixed(2 )} · ${systemPanel.rs.loadFifteen.toFixed(2 )} ( ${systemPanel.rs.cores} cores)` : "load —" 783 - objectName : "systemProcessTable"
784 966 width : parent.width width : parent.width972 + visible : systemPanel.issueList.length === 0 788 973 width : parent.width width : parent.width976 + color : root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, 0.55 ) : "#242424" 979 + anchors.left: parent.left980 + anchors.leftMargin: 12 981 + anchors.verticalCenter: parent.verticalCenter802 - width : parent.width - 190 985 + anchors.verticalCenter: parent.verticalCenter988 + font.family: "Symbols Nerd Font Mono" 993 + anchors.verticalCenter: parent.verticalCenter996 + text : "disk · memory · battery · updates ok" 821 1003 Repeater { Repeater {822 - model : root.resourceService ? root.resourceService.processes : []1004 + model : systemPanel.issueList1006 + delegate : Rectangle {825 1009 required property var modelData required property var modelData
1011 + readonly property color sevColor : {1012 + const s = modelData.severity;1014 + return root.theme ? root.theme.error : "#ec6376" ;1016 + if (s === "warning" )1017 + return root.theme ? root.theme.warning : "#f0ee69" ;1019 + return root.theme ? root.theme.info : "#3ec5e3" ;827 1022 width : parent.width width : parent.width1026 + color : root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, 0.55 ) : "#242424" 833 - text : String (modelData.pid || 0 )1030 + anchors.left: parent.left1031 + anchors.top: parent.top1032 + anchors.bottom: parent.bottom1034 + color : issueCard.sevColor840 - text : String (modelData.name || "?" )841 - width : parent.width - 190 842 - elide : Text .ElideRight1040 + anchors.left: parent.left1041 + anchors.leftMargin: 14 1042 + anchors.verticalCenter: parent.verticalCenter1046 + color : issueCard.sevColor848 - text : ` ${Number (modelData.cpu || 0 ).toFixed(1 )}%` 1052 + anchors.left: sevDot.right1053 + anchors.leftMargin: 10 1054 + anchors.verticalCenter: parent.verticalCenter1055 + text : String (issueCard.modelData.icon || "" )1056 + color : issueCard.sevColor1057 + font.family: "Symbols Nerd Font Mono" 855 - text : ` ${Number (modelData.mem || 0 ).toFixed(1 )}%` 1062 + anchors.left: issGlyph.right1063 + anchors.leftMargin: 10 1064 + anchors.right: actBtn.visible ? actBtn.left : parent.right1065 + anchors.rightMargin: 10 1066 + anchors.verticalCenter: parent.verticalCenter1071 + width : parent.width1072 + text : String (issueCard.modelData.label || "" )1078 + width : parent.width1079 + text : String (issueCard.modelData.detail || "" )1087 + visible : !! issueCard.modelData.action1088 + anchors.right: parent.right1089 + anchors.rightMargin: 10 1090 + anchors.verticalCenter: parent.verticalCenter1094 + color : root.theme ? root.theme.withAlpha(issueCard.sevColor, 0.30 ) : "transparent" 1097 + anchors.centerIn: parent1104 + anchors.fill: parent1105 + cursorShape : Qt .PointingHandCursor1107 + if (systemPanel.rs)1108 + systemPanel.rs.runIssueAction(issueCard.modelData.id);866 1123 width : parent.width width : parent.width869 - color : root.theme ? root.theme.withAlpha(root.theme.ui.accent, 0.18 ) : "transparent" 871 - border.color: root.theme ? root.theme.ui.accent : "transparent" 874 - anchors.centerIn: parent1127 + model : systemPanel.rs ? systemPanel.rs.processes : []1129 + delegate : Rectangle {1132 + required property var modelData1135 + width : procRow.implicitWidth + 18 1137 + color : root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.16 ) : "transparent" 1142 + anchors.centerIn: parent1148 + text : String (procChip.modelData.name || "?" )1154 + color : root.theme ? root.theme.ui.accent : "white" 1155 + text : ` ${Number (procChip.modelData.cpu || 0 ).toFixed(0 )}%` 879 - color : root.theme ? root.theme.content.normal : "white" 880 - font.family: "Symbols Nerd Font Mono"
893 - anchors.fill: parent895 - if (root.resourceService)896 - root.resourceService.launchBtm();
1058 - component ResourceMeter : Canvas {1321 + component IdentityRow : Row {1061 - property var seriesSamples: []1062 - property var seriesColors: []1063 - property bool normalizeSeries : false 1064 - property color trackColor : "#000000" 1065 - property real graphBlend : 1 1066 - property var previousSeriesSamples: []1067 - property var currentSeriesSamples: []1324 + required property QtObject theme1325 + property string glyph : "" 1326 + property string value : "" 1069 - function clamp01 (n) {1070 - return Math .max (0 , Math .min (1 , Number (n)));1328 + width : parent ? parent.width : 0 1334 + color : irow.theme ? irow.theme.ui.minor : "white" 1335 + font.family: "Symbols Nerd Font Mono" 1073 - function sampleValue (sample, index) {1074 - if (Array .isArray (sample))1075 - return clamp01(sample[index] || 0 );1077 - return index === 0 ? clamp01(sample) : 0 ;1080 - function normalizedSampleValue (sample, index) {1081 - const value = sampleValue(sample, index);1082 - if (! normalizeSeries)1085 - const samples = seriesSamples || [];1088 - for (let i = 0 ; i < samples.length; i++ ) {1089 - const candidate = sampleValue(samples[i], index);1090 - low = Math .min (low, candidate);1091 - high = Math .max (high, candidate);1093 - const span = high - low;1094 - return span < 0.0001 ? 0.5 : (value - low) / span;1097 - function interpolatedSampleValue (samples, sampleIndex, series) {1098 - const current = normalizedSampleValue(samples[sampleIndex], series);1099 - if (graphBlend >= 1 || previousSeriesSamples.length === 0 )1102 - const previousIndex = Math .max (0 , previousSeriesSamples.length - samples.length + sampleIndex);1103 - const previous = normalizedSampleValue(previousSeriesSamples[previousIndex] || samples[sampleIndex], series);1104 - return previous + (current - previous) * graphBlend;1107 - onGraphBlendChanged : requestPaint()1108 - onSeriesSamplesChanged : {1109 - previousSeriesSamples = currentSeriesSamples.length > 0 ? currentSeriesSamples : seriesSamples;1110 - currentSeriesSamples = seriesSamples;1112 - graphAnimation.restart();1115 - onSeriesColorsChanged : requestPaint()1116 - onNormalizeSeriesChanged : requestPaint()1117 - onTrackColorChanged : requestPaint()1118 - onWidthChanged : requestPaint()1119 - onHeightChanged : requestPaint()1121 - const ctx = getContext("2d" );1122 - ctx.clearRect(0 , 0 , width, height);1123 - if (width <= 0 || height <= 0 )1126 - ctx.fillStyle = trackColor;1127 - ctx.globalAlpha = 0.18 ;1128 - const seriesCount = Math .max (1 , seriesColors.length || 1 );1129 - for (let row = 1 ; row < seriesCount; row++ ) ctx.fillRect(0 , Math .round (row * height / seriesCount), width, 1 )1130 - ctx.globalAlpha = 1 ;1131 - const samples = seriesSamples || [];1132 - if (samples.length < 2 )1135 - const dx = width / Math .max (samples.length - 1 , 1 );1136 - for (let series = 0 ; series < seriesCount; series++ ) {1137 - const laneTop = 4 + series * ((height - 8 ) / seriesCount);1138 - const laneSpan = (height - 12 ) / seriesCount;1141 - let previousY = Math .round (laneTop + laneSpan - interpolatedSampleValue(samples, 0 , series) * laneSpan);1142 - ctx.moveTo(previousX, previousY);1143 - for (let i = 1 ; i < samples.length; i++ ) {1145 - const y = Math .round (laneTop + laneSpan - interpolatedSampleValue(samples, i, series) * laneSpan);1146 - const midX = (previousX + x) * 0.5 ;1147 - const midY = (previousY + y) * 0.5 ;1148 - ctx.quadraticCurveTo(previousX, previousY, midX, midY);1152 - ctx.lineTo(previousX, previousY);1153 - ctx.strokeStyle = String (seriesColors[series] || "#ffffff" );1154 - ctx.lineWidth = series === 0 ? 2.4 : 1.8 ;1159 - NumberAnimation on graphBlend {1166 - easing.type: Easing .OutCubic1343 + width : Math .max (1 , parent.width - 27 )1171 - component SystemMetric : Column {1350 + component Sparkline : Item {1174 1353 required property QtObject theme required property QtObject theme1175 - property string label : "" 1176 - property string valueText : "" 1177 - property real value : 0 1354 + property var values: []1178 1355 property color barColor : theme ? theme.ui.accent : "white" property color barColor : theme ? theme.ui.accent : "white"
1358 + property real scaleMax : 0 1180 - width : parent ? parent.width : 0 1361 + readonly property int shown : Math .max (1 , Math .floor (width / 3 ))1362 + readonly property var slice: {1363 + const v = spark.values || [];1364 + return v.length > spark.shown ? v.slice(v.length - spark.shown) : v;1366 + readonly property real maxV : {1367 + if (spark.scaleMax > 0 )1368 + return spark.scaleMax;1369 + const v = spark.slice;1371 + for (let i = 0 ; i < v.length; i++ ) m = Math .max (m, Number (v[i]) || 0 )1184 - width : parent.width1376 + anchors.right: parent.right1377 + anchors.bottom: parent.bottom1378 + height : parent.height1188 - theme : metric.theme1385 + required property var modelData1388 + height : spark.height1391 + anchors.bottom: parent.bottom1392 + width : parent.width1394 + height : Math .max (1 , spark.height * (spark.maxV > 0 ? Math .min (1 , (Number (modelData) || 0 ) / spark.maxV) : 0 ))1395 + color : spark.barColor1194 - theme : metric.theme1195 - text : metric.valueText
1407 + component MetricRow : Item {1410 + required property QtObject theme1411 + property string label : "" 1412 + property string value : "" 1413 + property real fraction : 0 1414 + property color barColor : theme ? theme.ui.accent : "white" 1415 + property var ring: []1416 + property real sparkScaleMax : 0 1417 + property bool showSpark : true 1419 + width : parent ? parent.width : 0 1425 + anchors.left: parent.left1426 + anchors.verticalCenter: parent.verticalCenter1436 + anchors.left: mlabel.right1437 + anchors.leftMargin: 4 1438 + anchors.verticalCenter: parent.verticalCenter1448 + anchors.right: parent.right1449 + anchors.verticalCenter: parent.verticalCenter1451 + visible : mrow.showSpark1453 + scaleMax : mrow.sparkScaleMax1454 + barColor : mrow.barColor1200 1459 Rectangle { Rectangle {1201 - width : parent.width1204 - color : metric.theme ? metric.theme.ui.minor : "black" 1462 + anchors.left: mvalue.right1463 + anchors.leftMargin: 8 1464 + anchors.right: mspark.left1465 + anchors.rightMargin: 8 1466 + anchors.verticalCenter: parent.verticalCenter1469 + color : mrow.theme ? mrow.theme.withAlpha(mrow.theme.ui.minor, 0.28 ) : "#333333" 1206 1471 Rectangle { Rectangle {1207 - width : parent.width * Math .max (0 , Math .min (1 , metric .value ))1472 + width : parent.width * Math .max (0 , Math .min (1 , mrow .fraction ))1208 1473 height : parent.height height : parent.height1209 1474 radius : parent.radius radius : parent.radius1210 - color : metric .barColor1475 + color : mrow .barColor1212 1477 Behavior on width { Behavior on width {1213 1478 NumberAnimation { NumberAnimation {1214 - duration : metric .theme && metric .theme.lowPowerMode ? 0 : 180 1479 + duration : mrow .theme && mrow .theme.lowPowerMode ? 0 : 160 1215 1480 easing.type: Easing .OutCubic easing.type: Easing .OutCubic2372 2637 NuguText { NuguText {2373 2638 theme : root.theme theme : root.theme2374 - text : root.resourceService ? `↓ ${root . resourceService .formatRate(root.resourceService.networkRxRate)}` : "↓ 0 B/s" 2639 + text : root.resourceService ? `↓ ${Sys .formatRate(root.resourceService.networkRxRate)}` : "↓ 0 B/s" 2375 2640 color : root.theme ? root.theme.ui.accent : "white" color : root.theme ? root.theme.ui.accent : "white" 2378 2643 NuguText { NuguText {2379 2644 theme : root.theme theme : root.theme2380 - text : root.resourceService ? `↑ ${root . resourceService .formatRate(root.resourceService.networkTxRate)}` : "↑ 0 B/s" 2645 + text : root.resourceService ? `↑ ${Sys .formatRate(root.resourceService.networkTxRate)}` : "↑ 0 B/s" 2381 2646 color : root.theme ? root.theme.ui.focus : "white" color : root.theme ? root.theme.ui.focus : "white" quickshell/nuguland/Resources.qml Modified +599 / −391 text lines
1 1 import QtQuickimport QtQuick2 3 import Quickshell.Ioimport Quickshell.Io
4 + import "sysinfo.js" as Sys
13 + required property var upower 14 + required property var powerProfiles 15 + required property QtObject brightnessService 7 18 property real cpuUsage : 0 property real cpuUsage : 0 8 - property real previousIdle : 0 9 - property real previousTotal : 0 10 - readonly property int sampleIntervalMs : 2000 11 - readonly property int historyWindowSeconds : 7200 12 - readonly property int historySampleLimit : 3600 13 - property var cpuHistory: [0.12 , 0.24 , 0.38 , 0.72 ]14 - property var systemHistorySamples: []15 - property var networkHistorySamples: []
16 19 property real memoryUsage : 0 property real memoryUsage : 0 17 20 property real swapUsage : 0 property real swapUsage : 0 18 21 property real memTotal : 0 property real memTotal : 0 23 26 property real networkTxRate: 0 property real networkTxRate: 0 24 27 property real diskReadRate: 0 property real diskReadRate: 0 25 28 property real diskWriteRate: 0 property real diskWriteRate: 0 26 - property real previousNetworkRx: 0 27 - property real previousNetworkTx: 0 28 - property real previousDiskRead: 0 29 - property real previousDiskWrite: 0 30 - property real previousRateTime: 0 31 - property string tempLabel: "n/a" 32 - property real cpuTemperatureC: 0 33 - property var temperatureHistorySamples: []34 - readonly property int hotHoldSeconds: 10 35 - readonly property int coolHoldSeconds: 10 36 - readonly property real cpuTempSensorHighC: 87 37 - property int firestormHotSeconds: 0 38 - property int firestormCoolSeconds: 0 39 - property real firestormTarget: 0 30 + property var cpuTemperatureC: null 31 + property var fanRpm: null 32 + property real loadOne: 0 33 + property real loadFive: 0 34 + property real loadFifteen: 0 35 + property int cores: 1 38 + readonly property int ringCap: 32 39 + property var cpuRing: []40 + property var memRing: []41 + property var tempRing: []42 + property var netRing: []43 + property var diskRing: []46 + property var failedUnits: []47 + property var diskUsage: [] 48 + property var updateCount: null 49 + property bool swapGrowing: false 51 + property real tempHighC: 87 56 + readonly property real firestormTarget: {57 + if (cpuTemperatureC === null || cpuTemperatureC === undefined )59 + const t = Number (cpuTemperatureC);62 + const high = Math .max (1 , tempHighC);63 + const cool = high - 12 ;64 + return Math .max (0 , Math .min (1 , (t - cool) / (high - cool)));40 68 property var processes: [] property var processes: []41 - property var lastBtmAction: ({71 + property var identity: ({})72 + property bool identityLoaded: false 75 + property bool popoutOpen: false 80 + readonly property var healthPercentage: {81 + const d = upower ? upower.displayDevice : null ;82 + return (d && d.ready && d.isLaptopBattery && d.healthSupported) ? Number (d.healthPercentage) : null ;84 + readonly property bool isLaptopBattery: {85 + const d = upower ? upower.displayDevice : null ;86 + return !! (d && d.ready && d.isLaptopBattery);88 + readonly property var degradationReason: {92 + const r = powerProfiles.degradationReason;93 + return (r === null || r === undefined ) ? null : String (r);97 + property var lastAction: ({44 - function clamp01 (value) {45 - return Math .max (0 , Math .min (1 , Number (value)));101 + property var prevCpu: null 102 + property real prevNetRx: 0 103 + property real prevNetTx: 0 104 + property real prevDiskRead: 0 105 + property real prevDiskWrite: 0 106 + property real prevRateTime: 0 107 + property real prevSwapUsed: 0 108 + property var failedSystemUnits: []109 + property var failedUserUnits: []48 - function signalFor (value) {58 - function colorRoleFor (value) {59 - const signal = signalFor(value);60 - if (signal === "error" )63 - if (signal === "warning" )69 - function formatBytes (value) {70 - const bytes = Math .max (0 , Number (value));71 - if (bytes >= 1.07374e+09 )72 - return ` ${(bytes / 1073741824 ).toFixed(1 )} GiB` ;74 - if (bytes >= 1.04858e+06 )75 - return ` ${(bytes / 1048576 ).toFixed(1 )} MiB` ;78 - return ` ${(bytes / 1024 ).toFixed(1 )} KiB` ;80 - return ` ${Math .round (bytes)} B` ;83 - function formatRate (value) {84 - return ` ${formatBytes(value)}/s` ;114 + property var networkHistorySamples: []87 116 function networkRxLevel () { function networkRxLevel () {88 - return clamp01(networkRxRate / 262144 );117 + return Sys . clamp01(networkRxRate / 262144 );91 120 function networkTxLevel () { function networkTxLevel () {92 - return clamp01(networkTxRate / 262144 );95 - function diskLevel () {96 - return clamp01((diskReadRate + diskWriteRate) / 8.38861e+06 );99 - function temperatureLevel () {100 - return clamp01(cpuTemperatureC / Math .max (temperatureHighThresholdC(), 1 ));103 - function systemLoad () {104 - return Math .max (cpuUsage, memoryUsage, swapUsage);107 - function systemSignal (value) {108 - return signalFor(value);111 - function systemColorRole (value) {112 - return colorRoleFor(value);115 - function appendHistorySample (history, sample) {116 - const next = history.slice(Math .max (0 , history.length - historySampleLimit + 1 ));117 - next.push(sample.map((value) => {118 - return clamp01(value);123 - function appendNumericHistorySample (history, value) {124 - const next = history.slice(Math .max (0 , history.length - historySampleLimit + 1 ));125 - const numeric = Number (value);126 - if (Number .isFinite (numeric) && numeric > 0 )132 - function percentile (values, ratio) {133 - const sorted = (values || []).filter((value) => {134 - return Number .isFinite (Number (value)) && Number (value) > 0 ;135 - }).map(Number ).sort((a, b) => {138 - if (sorted.length === 0 )141 - const index = Math .max (0 , Math .min (sorted.length - 1 , Math .ceil ((sorted.length - 1 ) * ratio)));142 - return sorted[index];145 - function temperatureHighThresholdC () {146 - return Math .max (72 , Math .min (87 , percentile(temperatureHistorySamples, 0.95 ) + 8 ));149 - function temperatureCoolThresholdC () {150 - return temperatureHighThresholdC() - 5 ;153 - function updateFirestormState () {154 - const temp = Number (cpuTemperatureC);155 - if (! Number .isFinite (temp) || temp <= 0 )158 - const high = temperatureHighThresholdC();159 - const cool = temperatureCoolThresholdC();161 - firestormHotSeconds = Math .min (hotHoldSeconds, firestormHotSeconds + sampleIntervalMs / 1000 );162 - firestormCoolSeconds = 0 ;163 - } else if (temp <= cool) {164 - firestormCoolSeconds = Math .min (coolHoldSeconds, firestormCoolSeconds + sampleIntervalMs / 1000 );165 - firestormHotSeconds = 0 ;167 - if (firestormHotSeconds >= hotHoldSeconds)168 - firestormTarget = 1 ;170 - if (firestormCoolSeconds >= coolHoldSeconds)171 - firestormTarget = 0 ;175 - function systemHistorySample () {176 - return [cpuUsage, memoryUsage, swapUsage, diskLevel(), temperatureLevel()];179 - function networkHistorySample () {180 - return [networkRxLevel(), networkTxLevel(), 0 , 0 ];183 - function refreshHistories () {184 - systemHistorySamples = appendHistorySample(systemHistorySamples, systemHistorySample());185 - networkHistorySamples = appendHistorySample(networkHistorySamples, networkHistorySample());121 + return Sys .clamp01(networkTxRate / 262144 );188 124 function shaderHistoryObject (samples) { function shaderHistoryObject (samples) {190 - "windowSeconds" : historyWindowSeconds,191 - "sampleIntervalMs" : sampleIntervalMs,192 - "sampleLimit" : historySampleLimit,193 - "sampleCount" : samples.length126 + "windowSeconds" : 7200 ,127 + "sampleIntervalMs" : 2000 ,128 + "sampleLimit" : 3600 ,129 + "sampleCount" : ( samples || [ ] ) .length197 - function systemWidgetState () {198 - const load = systemLoad();134 + function refreshFast () {136 + const statText = statFile.text() || "" ;137 + const cd = Sys .cpuDelta(prevCpu, statText);138 + cpuUsage = cd.usage;140 + const coreLines = statText.match(/ ^ cpu[0-9]/ gm );141 + if (coreLines && coreLines.length > 0 )142 + cores = coreLines.length;144 + meminfoFile.reload();145 + const mem = Sys .parseMeminfo(meminfoFile.text() || "" );146 + if (mem.memTotal > 0 ) {147 + memTotal = mem.memTotal;148 + memAvailable = mem.memAvailable;149 + swapTotal = mem.swapTotal;150 + swapFree = mem.swapFree;151 + memoryUsage = mem.memoryUsage;152 + swapUsage = mem.swapUsage;153 + const swapUsed = Math .max (0 , mem.swapTotal - mem.swapFree);154 + swapGrowing = swapUsed > prevSwapUsed + 1 ;155 + prevSwapUsed = swapUsed;160 + const net = Sys .parseNetDev(netFile.text() || "" );161 + const disk = Sys .parseDiskstats(diskFile.text() || "" );162 + const now = Date .now ();163 + const seconds = prevRateTime > 0 ? Math .max (0.2 , (now - prevRateTime) / 1000 ) : 0 ;165 + networkRxRate = Sys .rate(prevNetRx, net.rx, seconds);166 + networkTxRate = Sys .rate(prevNetTx, net.tx, seconds);167 + diskReadRate = Sys .rate(prevDiskRead, disk.readBytes, seconds);168 + diskWriteRate = Sys .rate(prevDiskWrite, disk.writeBytes, seconds);172 + prevDiskRead = disk.readBytes;173 + prevDiskWrite = disk.writeBytes;177 + const loadText = loadFile.text() || "" ;178 + if (loadText.trim().length > 0 ) {179 + const la = Sys .parseLoadavg(loadText);182 + loadFifteen = la.fifteen;186 + if (tempFile.path) {188 + const t = Sys .parseTemp(tempFile.text() || "" );190 + cpuTemperatureC = t;195 + const f = Sys .parseFan(fanFile.text() || "" );201 + cpuRing = Sys .pushRing(cpuRing, cpuUsage, ringCap);202 + memRing = Sys .pushRing(memRing, memoryUsage, ringCap);203 + if (cpuTemperatureC !== null )204 + tempRing = Sys .pushRing(tempRing, cpuTemperatureC, ringCap);206 + netRing = Sys .pushRing(netRing, networkRxRate + networkTxRate, ringCap);207 + diskRing = Sys .pushRing(diskRing, diskReadRate + diskWriteRate, ringCap);208 + networkHistorySamples = Sys .pushRing(networkHistorySamples, Math .max (networkRxLevel(), networkTxLevel()), ringCap);212 + function refreshSlow () {216 + if (! failedSystemProc.running)217 + failedSystemProc.exec(["systemctl" , "--failed" , "--no-legend" , "--plain" ]);219 + if (! failedUserProc.running)220 + failedUserProc.exec(["systemctl" , "--user" , "--failed" , "--no-legend" , "--plain" ]);222 + if (! dfProc.running)223 + dfProc.exec(["df" , "-P" ]);225 + if (! psProc.running)226 + psProc.exec(["sh" , "-c" , "ps -eo pid=,comm=,pcpu=,pmem= --sort=-pcpu | head -n 5" ]);231 + function refreshRare () {232 + if (! identityLoaded && ! identityProc.running)233 + identityProc.exec(["sh" , "-c" , "printf 'host=%s\\n' \"$(uname -n)\"; printf 'kernel=%s\\n' \"$(uname -r)\"; ( . /etc/os-release 2>/dev/null; printf 'distro=%s\\n' \"${PRETTY_NAME:-Linux}\" ); printf 'model=%s\\n' \"$(cat /sys/devices/virtual/dmi/id/product_version 2>/dev/null || cat /sys/devices/virtual/dmi/id/product_name 2>/dev/null)\"; printf 'shell=%s\\n' \"$(basename \"${SHELL:-sh}\")\"; printf 'uptime=%s\\n' \"$(uptime -p 2>/dev/null | sed 's/^up //')\"; printf 'packages=%s\\n' \"$(pacman -Qq 2>/dev/null | wc -l)\"" ]);235 + if (! updatesProc.running)236 + updatesProc.exec(["checkupdates" ]);240 + function recomputeFailed () {241 + failedUnits = failedSystemUnits.concat(failedUserUnits);245 + function buildIssueState () {247 + "failedUnits" : failedUnits,248 + "cpuTemperatureC" : cpuTemperatureC,249 + "tempHighC" : tempHighC,250 + "degradationReason" : degradationReason,251 + "diskUsage" : diskUsage,252 + "memoryUsage" : memoryUsage,253 + "swapGrowing" : swapGrowing,254 + "healthPercentage" : healthPercentage,255 + "isLaptopBattery" : isLaptopBattery,258 + "updateCount" : updateCount264 + return Sys .detectIssues(buildIssueState());268 + function runIssueAction (id) {269 + const list = issues();271 + for (let i = 0 ; i < list.length; i++ ) {272 + if (list[i].id === id) {277 + if (! issue || ! issue.action)278 + return JSON .stringify ({280 + "reason" : "no-action" ,284 + const a = issue.action;286 + if (a.kind === "btm" )287 + argv = ["wezterm" , "start" , "--" , "btm" ];288 + else if (a.kind === "systemctl-status" ) {289 + const units = (a.units || []).join(" " );290 + argv = ["wezterm" , "start" , "--" , "sh" , "-c" , `systemctl status ${units}; systemctl --user status ${units}; exec "$SHELL"` ];291 + } else if (a.kind === "open-mount" )292 + argv = ["wezterm" , "start" , "--cwd" , String (a.target || "/" )];293 + else if (a.kind === "update" )294 + argv = ["wezterm" , "start" , "--" , "sh" , "-c" , "sudo pacman -Syu; exec \"$SHELL\"" ];297 + return JSON .stringify ({299 + "reason" : "unknown-action" ,309 + Quickshell .execDetached(argv);310 + return JSON .stringify (lastAction);314 + function stateJson () {315 + const memUsed = Math .max (0 , memTotal - memAvailable);316 + const swapUsed = Math .max (0 , swapTotal - swapFree);199 317 return JSON .stringify ({ return JSON .stringify ({200 318 "kind" : "system" , "kind" : "system" ,201 319 "title" : "system" , "title" : "system" ,203 - "percent" : Math .round (load * 100 ),204 - "signal" : systemSignal(load),205 - "colorRole" : systemColorRole(load),206 - "barLabel" : "system" ,208 - "kind" : "system-mini-graph" ,210 - "source" : "shaders/system-mini-graph.frag.qsb" ,211 - "priorArt" : "Shadertoy smoothstep and distance-to-segment line drawing primitives plus heat haze sine/noise thermal shimmer" ,212 - "values" : [cpuUsage, memoryUsage, swapUsage, diskLevel()],213 - "history" : shaderHistoryObject(systemHistorySamples),214 - "colors" : ["ui.accent" , "ui.focus" , "warning" , "ui.minor" , "error" ]320 + "popoutOpen" : popoutOpen,217 322 "usage" : cpuUsage, "usage" : cpuUsage,218 323 "percent" : Math .round (cpuUsage * 100 ) "percent" : Math .round (cpuUsage * 100 )220 325 "memory" : { "memory" : {221 326 "usage" : memoryUsage, "usage" : memoryUsage, 222 327 "percent" : Math .round (memoryUsage * 100 ), "percent" : Math .round (memoryUsage * 100 ), 223 - "used" : Math .max (0 , memTotal - memAvailable), 224 329 "total" : memTotal, "total" : memTotal, 225 - "label" : ` ${formatBytes(Math .max (0 , memTotal - memAvailable))} / ${formatBytes(memTotal)}` 330 + "label" : ` ${Sys .formatBytes(memUsed)} / ${Sys .formatBytes(memTotal)}` 227 332 "swap" : { "swap" : {228 333 "usage" : swapUsage, "usage" : swapUsage, 229 334 "percent" : Math .round (swapUsage * 100 ), "percent" : Math .round (swapUsage * 100 ), 230 - "used" : Math .max (0 , swapTotal - swapFree), 231 336 "total" : swapTotal, "total" : swapTotal, 232 - "label" : swapTotal > 0 ? ` ${formatBytes(Math . max ( 0 , swapTotal - swapFree ) )} / ${formatBytes(swapTotal)}` : "off" 337 + "label" : swapTotal > 0 ? ` ${Sys . formatBytes(swapUsed )} / ${Sys . formatBytes(swapTotal)}` : "off" 234 339 "network" : { "network" : {235 340 "rxRate" : networkRxRate, "rxRate" : networkRxRate, 236 341 "txRate" : networkTxRate, "txRate" : networkTxRate, 237 - "label" : `↓ ${formatRate(networkRxRate)} ↑ ${formatRate(networkTxRate)}` 342 + "label" : `↓ ${Sys . formatRate(networkRxRate)} ↑ ${Sys . formatRate(networkTxRate)}` 239 344 "disk" : { "disk" : {240 345 "readRate" : diskReadRate, "readRate" : diskReadRate, 241 346 "writeRate" : diskWriteRate, "writeRate" : diskWriteRate, 242 - "level" : diskLevel(), 243 - "label" : `R ${formatRate(diskReadRate)} W ${formatRate(diskWriteRate)}` 347 + "label" : `R ${Sys . formatRate(diskReadRate)} W ${Sys . formatRate(diskWriteRate)}` 245 349 "temperature" : { "temperature" : {247 350 "celsius" : cpuTemperatureC, "celsius" : cpuTemperatureC, 248 - "level" : temperatureLevel(), 249 - "highThresholdC" : temperatureHighThresholdC(), 250 - "coolThresholdC" : temperatureCoolThresholdC(), 251 - "firestormTarget" : firestormTarget351 + "highThresholdC" : tempHighC, 352 + "label" : cpuTemperatureC !== null ? ` ${Math .round (Number (cpuTemperatureC))}°C` : "n/a"
356 + "label" : fanRpm !== null ? ` ${Math .round (Number (fanRpm))} rpm` : "n/a" 361 + "fifteen" : loadFifteen, 365 + "healthPercentage" : healthPercentage, 366 + "isLaptopBattery" : isLaptopBattery368 + "identity" : identity, 369 + "updateCount" : updateCount, 253 370 "processes" : processes, "processes" : processes, 254 - "btmAction" : lastBtmAction372 + "lastAction" : lastAction258 - function resourceHeroCard (kind, value, samples) {259 - const name = String (kind || "system" );260 - const clamped = clamp01(value);261 - const boundedSamples = (samples || []).map((sample) => {262 - return clamp01(sample);264 - return JSON .stringify ({266 - "title" : name === "system" ? "System" : name.toUpperCase(),268 - "percent" : Math .round (clamped * 100 ),269 - "signal" : signalFor(clamped),270 - "role" : colorRoleFor(clamped),271 - "boundedHeroMeter" : {275 - "shape" : clamped >= 0.8 ? "burst" : (clamped >= 0.4 ? "sunny" : "plain" ),276 - "role" : colorRoleFor(clamped)279 - "fillOpacity" : 0.22 ,280 - "sampleCount" : boundedSamples.length,281 - "alignment" : "right" 283 - "sparklineSamples" : boundedSamples,284 - "helperProcesses" : [],285 - "widgetProcesses" : "forbidden" 377 + function systemWidgetState () {289 - function refreshCpu () {291 - const line = statFile.text().split("\n" )[0 ] || "" ;292 - const parts = line.trim().split(/\s + / ).slice(1 ).map(Number );293 - if (parts.length < 4 || parts.some((n) => {294 - return ! Number .isFinite (n);298 - const idle = parts[3 ] + (parts[4 ] || 0 );299 - const total = parts.reduce((sum, n) => {302 - const totalDelta = total - previousTotal;303 - const idleDelta = idle - previousIdle;304 - previousTotal = total;305 - previousIdle = idle;306 - if (totalDelta > 0 ) {307 - cpuUsage = clamp01(1 - idleDelta / totalDelta);308 - const nextHistory = cpuHistory.slice(- 23 );309 - nextHistory.push(cpuUsage);310 - cpuHistory = nextHistory;314 - function refreshMemory () {315 - meminfoFile.reload();318 - const lines = meminfoFile.text().split("\n" );319 - for (let i = 0 ; i < lines.length; i++ ) {320 - const match = lines[i].match(/ ^ ([A-Za-z_()] + ):\s + (\d + )/ );322 - values[match[1 ]] = Number (match[2 ]) * 1024 ;325 - memTotal = Number (values.MemTotal || 0 );326 - memAvailable = Number (values.MemAvailable || values.MemFree || 0 );327 - swapTotal = Number (values.SwapTotal || 0 );328 - swapFree = Number (values.SwapFree || 0 );329 - memoryUsage = memTotal > 0 ? clamp01((memTotal - memAvailable) / memTotal) : 0 ;330 - swapUsage = swapTotal > 0 ? clamp01((swapTotal - swapFree) / swapTotal) : 0 ;333 - function applyProcessSnapshot (text) {335 - const lines = String (text || "" ).trim().split("\n" );336 - for (let i = 0 ; i < lines.length; i++ ) {337 - const parts = lines[i].trim().split(/\s + / );338 - if (parts.length < 4 )342 - "pid" : Number (parts[0 ]),344 - "cpu" : Number (parts[2 ]) || 0 ,345 - "mem" : Number (parts[3 ]) || 0 383 + function selfTest () {385 + function ok (name, cond) {391 + function findIssue (list, id) {392 + for (let i = 0 ; i < list.length; i++ ) {393 + if (list[i].id === id)351 - function applyTemperature (text) {352 - tempLabel = String (text || "n/a" ).trim() || "n/a" ;353 - const match = tempLabel.match(/([0-9] + (?:\.[0-9] + ) ? )/ );354 - cpuTemperatureC = match ? Number (match[1 ]) : 0 ;355 - temperatureHistorySamples = appendNumericHistorySample(temperatureHistorySamples, cpuTemperatureC);356 - updateFirestormState();359 - function firestormState () {360 - return JSON .stringify ({361 - "temperatureC" : cpuTemperatureC,363 - "historySamples" : temperatureHistorySamples.length,364 - "historyP95C" : percentile(temperatureHistorySamples, 0.95 ),365 - "highThresholdC" : temperatureHighThresholdC(),366 - "coolThresholdC" : temperatureCoolThresholdC(),367 - "hotHoldSeconds" : hotHoldSeconds,368 - "coolHoldSeconds" : coolHoldSeconds,369 - "hotSeconds" : firestormHotSeconds,370 - "coolSeconds" : firestormCoolSeconds,371 - "firestormTarget" : firestormTarget,373 - "currentObservedC" : 61 ,374 - "coretempHighC" : cpuTempSensorHighC,375 - "coretempCritC" : 105
400 + "failedUnits" : failedUnits,401 + "cpuTemperatureC" : cpuTemperatureC,402 + "tempHighC" : tempHighC,403 + "diskUsage" : diskUsage,404 + "memoryUsage" : memoryUsage,405 + "swapGrowing" : swapGrowing,408 + "updateCount" : updateCount411 + const st = buildIssueState();412 + const keys = ["failedUnits" , "cpuTemperatureC" , "tempHighC" , "degradationReason" , "diskUsage" , "memoryUsage" , "swapGrowing" , "healthPercentage" , "isLaptopBattery" , "loadOne" , "cores" , "updateCount" ];414 + for (let k = 0 ; k < keys.length; k++ ) {415 + if (! (keys[k] in st))416 + missing.push(keys[k]);419 + ok("state-keys-present:" + missing.join("," ), missing.length === 0 );421 + failedUnits = ["app-Handy@autostart.service" ];422 + cpuTemperatureC = 95 ;425 + "source" : "/dev/sda3" ,434 + const list = root.issues();435 + ok("issues-is-array" , Array .isArray (list));436 + ok("failed-services" , !! findIssue(list, "failed-services" ));437 + const th = findIssue(list, "thermal" );438 + ok("thermal-warning" , th && th.severity === "warning" );439 + const dk = findIssue(list, "low-disk:/dev/sda3" );440 + ok("low-disk-error" , dk && dk.severity === "error" );441 + ok("mem-pressure" , !! findIssue(list, "mem-pressure" ));442 + ok("high-load" , !! findIssue(list, "high-load" ));443 + const up = findIssue(list, "updates" );444 + ok("updates-info" , up && up.severity === "info" );448 + cpuTemperatureC = 40 ;450 + "source" : "/dev/sda3" ,455 + swapGrowing = false ;458 + const clear = root.issues();459 + ok("failed-cleared" , ! findIssue(clear, "failed-services" ));460 + ok("thermal-cleared" , ! findIssue(clear, "thermal" ));461 + ok("disk-cleared" , ! findIssue(clear, "low-disk:/dev/sda3" ));462 + ok("mem-cleared" , ! findIssue(clear, "mem-pressure" ));463 + ok("load-cleared" , ! findIssue(clear, "high-load" ));464 + ok("updates-cleared" , ! findIssue(clear, "updates" ));466 + const sj = JSON .parse (root.stateJson());467 + ok("statejson-kind" , sj.kind === "system" );468 + ok("statejson-issues-array" , Array .isArray (sj.issues));470 + ok("threw:" + e, false );472 + failedUnits = saved.failedUnits;473 + cpuTemperatureC = saved.cpuTemperatureC;474 + tempHighC = saved.tempHighC;475 + diskUsage = saved.diskUsage;476 + memoryUsage = saved.memoryUsage;477 + swapGrowing = saved.swapGrowing;478 + loadOne = saved.loadOne;479 + cores = saved.cores;480 + updateCount = saved.updateCount;482 + const fail = cases.filter((c) => {485 + return JSON .stringify ({486 + "pass" : cases.length - fail,380 - function refreshDetails () {381 - if (! processScan.running)382 - processScan.exec(["sh" , "-c" , "ps -eo pid=,comm=,pcpu=,pmem= --sort=-pcpu | head -n 5" ]);384 - if (! tempScan.running)385 - tempScan.exec(["sh" , "-c" , "for f in /sys/class/thermal/thermal_zone*/temp /sys/class/hwmon/hwmon*/temp*_input; do [ -r \"$f\" ] || continue; v=$(cat \"$f\"); case \"$v\" in ''|*[!0-9]*) continue;; esac; awk -v v=\"$v\" 'BEGIN{printf \"%.0f°C\\n\", v/1000}'; exit; done; printf 'n/a\\n'" ]);389 - function launchBtm () {392 - "terminal" : "wezterm" ,393 - "argv" : ["wezterm" , "start" , "--" , "btm" ]395 - btmLaunch.exec(["wezterm" , "start" , "--" , "btm" ]);396 - return JSON .stringify (lastBtmAction);399 - function refreshRates () {404 - const netLines = netFile.text().split("\n" );405 - for (let i = 0 ; i < netLines.length; i++ ) {406 - const line = netLines[i];407 - if (line.indexOf(":" ) < 0 )410 - const pieces = line.split(":" );411 - const name = pieces[0 ].trim();415 - const fields = pieces[1 ].trim().split(/\s + / ).map(Number );416 - if (fields.length >= 16 ) {492 + onPopoutOpenChanged : {423 - const diskLines = diskFile.text().split("\n" );424 - for (let j = 0 ; j < diskLines.length; j++ ) {425 - const fields = diskLines[j].trim().split(/\s + / );426 - if (fields.length < 10 )429 - const name = fields[2 ] || "" ;430 - if (name.indexOf("loop" ) === 0 || name.indexOf("ram" ) === 0 )433 - const readSectors = Number (fields[5 ]);434 - const writeSectors = Number (fields[9 ]);435 - if (Number .isFinite (readSectors))436 - readBytes += readSectors * 512 ;438 - if (Number .isFinite (writeSectors))439 - writeBytes += writeSectors * 512 ;442 - const now = Date .now ();443 - const seconds = previousRateTime > 0 ? Math .max (0.2 , (now - previousRateTime) / 1000 ) : 0 ;445 - networkRxRate = Math .max (0 , (rx - previousNetworkRx) / seconds);446 - networkTxRate = Math .max (0 , (tx - previousNetworkTx) / seconds);447 - diskReadRate = Math .max (0 , (readBytes - previousDiskRead) / seconds);448 - diskWriteRate = Math .max (0 , (writeBytes - previousDiskWrite) / seconds);450 - previousNetworkRx = rx;451 - previousNetworkTx = tx;452 - previousDiskRead = readBytes;453 - previousDiskWrite = writeBytes;454 - previousRateTime = now;
457 - function refreshSystem () {499 + Component .onCompleted: {501 + hwmonResolve.exec(["sh" , "-c" , "for d in /sys/class/hwmon/hwmon*; do n=$(cat \"$d/name\" 2>/dev/null); if [ \"$n\" = coretemp ]; then for t in \"$d\"/temp*_label; do [ -r \"$t\" ] || continue; if grep -qi package \"$t\"; then b=${t%_label}; [ -r \"${b}_input\" ] && printf 'temp=%s\\n' \"${b}_input\"; if [ -r \"${b}_max\" ]; then printf 'high=%s\\n' \"$(cat ${b}_max)\"; elif [ -r \"${b}_crit\" ]; then printf 'high=%s\\n' \"$(cat ${b}_crit)\"; fi; break; fi; done; elif [ \"$n\" = thinkpad ]; then [ -r \"$d/fan1_input\" ] && printf 'fan=%s\\n' \"$d/fan1_input\"; fi; done" ]);465 505 FileView { FileView {466 506 id : statFile id : statFile494 534 printErrors: false printErrors: false
540 + path : "/proc/loadavg" 497 563 Process { Process {500 566 running : false running : false 502 568 stdout : StdioCollector { stdout : StdioCollector {503 569 waitForEnd : true waitForEnd : true 504 - onStreamFinished : root.applyProcessSnapshot(this.text)571 + const lines = String (this.text || "" ).split("\n" );572 + for (let i = 0 ; i < lines.length; i++ ) {573 + const line = lines[i].trim();574 + if (line.indexOf("temp=" ) === 0 )575 + tempFile.path = line.slice(5 );576 + else if (line.indexOf("fan=" ) === 0 )577 + fanFile.path = line.slice(4 );578 + else if (line.indexOf("high=" ) === 0 ) {579 + const v = Number (line.slice(5 ));580 + if (Number .isFinite (v) && v > 0 )581 + root.tempHighC = v / 1000 ;509 591 Process { Process {592 + id : failedSystemProc512 594 running : false running : false 514 596 stdout : StdioCollector { stdout : StdioCollector {515 597 waitForEnd : true waitForEnd : true 516 - onStreamFinished : root.applyTemperature(this.text)599 + root.failedSystemUnits = Sys .parseFailedUnits(this.text);600 + root.recomputeFailed();521 606 Process { Process {524 609 running : false running : false
611 + stdout : StdioCollector {614 + root.failedUserUnits = Sys .parseFailedUnits(this.text);615 + root.recomputeFailed();
626 + stdout : StdioCollector {629 + const parsed = Sys .parseDf(this.text);630 + if (parsed.length > 0 )631 + root.diskUsage = parsed;643 + stdout : StdioCollector {646 + const parsed = Sys .parsePsTop(this.text);647 + if (parsed.length > 0 )648 + root.processes = parsed;661 + stdout : StdioCollector {667 + const lines = String (this.text || "" ).split("\n" );668 + for (let i = 0 ; i < lines.length; i++ ) {669 + const eq = lines[i].indexOf("=" );673 + out[lines[i].slice(0 , eq)] = lines[i].slice(eq + 1 ).trim();676 + root.identity = out;677 + root.identityLoaded = true ;689 + stdout : StdioCollector {696 + onExited : (exitCode, exitStatus) => {697 + if (exitCode === 2 ) {698 + root.updateCount = 0 ;701 + if (exitCode !== 0 ) {702 + root.updateCount = null ;705 + const lines = String (updatesOut.text || "" ).split("\n" ).filter((l) => {706 + return l.trim().length > 0 ;708 + root.updateCount = lines.length;528 716 interval : 2000 interval : 2000 529 717 repeat : true repeat : true 530 718 running : true running : true 531 719 triggeredOnStart : true triggeredOnStart : true 532 - onTriggered : root.refreshSystem()720 + onTriggered : root.refreshFast()728 + running : root.popoutOpen729 + triggeredOnStart : true 730 + onTriggered : root.refreshSlow()738 + running : root.popoutOpen739 + triggeredOnStart : false 740 + onTriggered : root.refreshRare()quickshell/nuguland/SurfaceManager.qml Modified +5 / −2 text lines
70 70 "height" : heightBudget (580 ) "height" : heightBudget (580 )72 72 case "system" : case "system" :74 77 "width" : width, "width" : width, 75 - "height" : heightBudget(520 )78 + "height" : heightBudget(600 )77 80 case "notifications" : case "notifications" :189 192 "system" : { "system" : {190 193 "component" : "system-resources" , "component" : "system-resources" , 191 194 "source" : "Resources.qml" , "source" : "Resources.qml" , 192 - "visual" : ["cpu" , "memory" , "swap" , "disk-rate" , "temperature" , "process-table" , "btm-launch" ]195 + "visual" : ["identity-card" , "live-metrics" , "sparklines" , "issues-band" , "top-processes" ]194 197 "notifications" : { "notifications" : {195 198 "component" : "notification-history" , "component" : "notification-history" , quickshell/nuguland/shell.qml Modified +13 / −12 text lines
3 3 import Quickshell.Ioimport Quickshell.Io4 4 import Quickshell.Waylandimport Quickshell.Wayland5 5 import Quickshell.Widgetsimport Quickshell.Widgets
6 + import Quickshell.Services.UPower65 66 Resources { Resources {66 67 id : resources id : resources
72 + powerProfiles : PowerProfiles73 + brightnessService : brightness69 76 Notifications { Notifications {625 632 function refresh () : string { caldav.refresh(); return caldav.stateJson(); } function refresh () : string { caldav.refresh(); return caldav.stateJson(); }
637 + function state () : string { return resources.stateJson(); }638 + function selfTest () : string { return resources.selfTest(); }628 641 IpcHandler { IpcHandler {629 642 function ping () : string { function ping () : string {630 643 return "nuguland" ; return "nuguland" ;704 717 return surfaceManager.openRegisteredPopout("system" ); return surfaceManager.openRegisteredPopout("system" );707 - function resourceHeroCard (kind: string, value: real, samplesCsv: string) : string {708 - return resources.resourceHeroCard(kind, value, String (samplesCsv).split("," ).map(Number ));711 - function firestormState () : string {712 - return resources.firestormState();715 - function systemLaunchBtm () : string {716 - return resources.launchBtm();
719 720 function notificationWidgetState (attention: bool, active: bool) : string { function notificationWidgetState (attention: bool, active: bool) : string {720 721 return notifications.widgetState(attention, active); return notifications.widgetState(attention, active);quickshell/nuguland/sysinfo.js Added new file mode 100644+341 / −0 text lines
5 + function clamp01 (value) {6 + var n = Number (value);7 + if (! isFinite (n)) return 0 ;8 + return n < 0 ? 0 : (n > 1 ? 1 : n);14 + function cpuDelta (prev, curLine) {15 + var line = String (curLine == null ? "" : curLine).split(/\r ? \n/ )[0 ] || "" ;16 + var parts = line.trim().split(/\s + / ).slice(1 ).map(Number );17 + if (parts.length < 4 || parts.some(function (n) { return ! isFinite (n); })) {18 + return { usage: 0 , next: (prev && isFinite (prev.total)) ? prev : { idle: 0 , total: 0 } };20 + var idle = parts[3 ] + (parts[4 ] || 0 );21 + var total = parts.reduce(function (sum, n) { return sum + n; }, 0 );22 + var next = { idle: idle, total: total };23 + if (! prev || ! isFinite (prev.total)) return { usage: 0 , next: next };24 + var totalDelta = total - prev.total;25 + var idleDelta = idle - prev.idle;26 + var usage = totalDelta > 0 ? clamp01(1 - idleDelta / totalDelta) : 0 ;27 + return { usage: usage, next: next };31 + function parseMeminfo (text) {33 + var lines = String (text == null ? "" : text).split(/\r ? \n/ );34 + for (var i = 0 ; i < lines.length; i++ ) {35 + var m = lines[i].match(/ ^ ([A-Za-z_()] + ):\s + (\d + )/ );36 + if (m) values[m[1 ]] = Number (m[2 ]) * 1024 ;38 + var memTotal = Number (values.MemTotal || 0 );39 + var memAvailable = Number (values.MemAvailable != null ? values.MemAvailable : (values.MemFree || 0 ));40 + var swapTotal = Number (values.SwapTotal || 0 );41 + var swapFree = Number (values.SwapFree || 0 );44 + memAvailable: memAvailable,45 + swapTotal: swapTotal,47 + memoryUsage: memTotal > 0 ? clamp01((memTotal - memAvailable) / memTotal) : 0 ,48 + swapUsage: swapTotal > 0 ? clamp01((swapTotal - swapFree) / swapTotal) : 0 54 + function parseNetDev (text) {56 + var lines = String (text == null ? "" : text).split(/\r ? \n/ );57 + for (var i = 0 ; i < lines.length; i++ ) {58 + var colon = lines[i].indexOf(":" );59 + if (colon < 0 ) continue ;60 + var iface = lines[i].slice(0 , colon).trim();61 + if (! iface || iface === "lo" ) continue ;62 + var f = lines[i].slice(colon + 1 ).trim().split(/\s + / ).map(Number );63 + if (f.length < 9 || ! isFinite (f[0 ]) || ! isFinite (f[8 ])) continue ;67 + return { rx: rx, tx: tx };73 + function parseDiskstats (text) {74 + var readBytes = 0 , writeBytes = 0 ;75 + var lines = String (text == null ? "" : text).split(/\r ? \n/ );76 + for (var i = 0 ; i < lines.length; i++ ) {77 + var p = lines[i].trim().split(/\s + / );78 + if (p.length < 10 ) continue ;80 + if (/ ^ (loop | ram)\d * / .test(name)) continue ;83 + if (/ ^ sd[a-z] + \d +$|^ nvme\d + n\d + p\d +$|^ mmcblk\d + p\d +$|^ vd[a-z] + \d +$ / .test(name)) continue ;84 + var sread = Number (p[5 ]), swrite = Number (p[9 ]);85 + if (! isFinite (sread) || ! isFinite (swrite)) continue ;86 + readBytes += sread * 512 ;87 + writeBytes += swrite * 512 ;89 + return { readBytes: readBytes, writeBytes: writeBytes };94 + function rate (prev, cur, seconds) {95 + var p = Number (prev), c = Number (cur), s = Number (seconds);96 + if (! isFinite (p) || ! isFinite (c) || ! isFinite (s) || s <= 0 ) return 0 ;98 + return d > 0 ? d / s : 0 ;102 + function parseLoadavg (text) {103 + var p = String (text == null ? "" : text).trim().split(/\s + / );105 + one: Number (p[0 ]) || 0 ,106 + five: Number (p[1 ]) || 0 ,107 + fifteen: Number (p[2 ]) || 0 113 + function parseDf (text) {115 + var lines = String (text == null ? "" : text).split(/\r ? \n/ );116 + for (var i = 0 ; i < lines.length; i++ ) {117 + var line = lines[i].trim();118 + if (! line) continue ;119 + var p = line.split(/\s + / );120 + if (p.length < 6 ) continue ;122 + for (var j = 1 ; j < p.length; j++ ) {123 + if (/ ^ \d + % $ / .test(p[j])) { capIdx = j; break ; }125 + if (capIdx < 0 ) continue ; 128 + target: p.slice(capIdx + 1 ).join(" " ),129 + usedPercent: parseInt (p[capIdx], 10 )136 + function parseFailedUnits (text) {138 + var lines = String (text == null ? "" : text).split(/\r ? \n/ );139 + for (var i = 0 ; i < lines.length; i++ ) {140 + var line = lines[i].trim();141 + if (! line) continue ;142 + var name = line.split(/\s + / )[0 ];143 + if (name && name.indexOf("." ) > 0 ) out.push(name);150 + function parsePsTop (text) {152 + var lines = String (text == null ? "" : text).trim().split(/\r ? \n/ );153 + for (var i = 0 ; i < lines.length; i++ ) {154 + var p = lines[i].trim().split(/\s + / );155 + if (p.length < 4 ) continue ;156 + var pid = Number (p[0 ]);157 + if (! isFinite (pid)) continue ; 158 + out.push({ pid: pid, name: p[1 ], cpu: Number (p[2 ]) || 0 , mem: Number (p[3 ]) || 0 });164 + function parseTemp (text) {165 + var s = String (text == null ? "" : text).trim();166 + if (s === "" ) return null ;168 + return isFinite (v) ? v / 1000 : null ;172 + function parseFan (text) {173 + var s = String (text == null ? "" : text).trim();174 + if (s === "" ) return null ;176 + return isFinite (v) ? v : null ;180 + function formatBytes (value) {181 + var bytes = Math .max (0 , Number (value));182 + if (! isFinite (bytes)) bytes = 0 ;183 + if (bytes >= 1.07374e+09 ) return (bytes / 1073741824 ).toFixed(1 ) + " GiB" ;184 + if (bytes >= 1.04858e+06 ) return (bytes / 1048576 ).toFixed(1 ) + " MiB" ;185 + if (bytes >= 1024 ) return (bytes / 1024 ).toFixed(1 ) + " KiB" ;186 + return Math .round (bytes) + " B" ;189 + function formatRate (value) {190 + return formatBytes(value) + "/s" ;194 + function pushRing (buf, value, cap) {195 + var next = (buf || []).slice();197 + var limit = Math .max (0 , Number (cap) || 0 );198 + while (next.length > limit) next.shift();203 + function severityRank (s) {204 + return s === "error" ? 0 : (s === "warning" ? 1 : 2 );218 + function detectIssues (state) {219 + var st = state || {};223 + if (st.failedUnits != null && st.failedUnits.length > 0 ) {224 + var units = st.failedUnits.slice();226 + id: "failed-services" ,229 + label: units.length === 1 ? "Failed service" : (units.length + " failed services" ),230 + detail: units.join(", " ),231 + action: { kind: "systemctl-status" , units: units }237 + var tempHigh = isFinite (Number (st.tempHighC)) ? Number (st.tempHighC) : 87 ;238 + var degradeThermal = !! st.degradationReason && 239 + /thermal | temperature/ i .test(String (st.degradationReason));240 + var tempHot = st.cpuTemperatureC != null && Number (st.cpuTemperatureC) >= tempHigh;241 + if (degradeThermal || tempHot) {244 + severity: degradeThermal ? "error" : "warning" ,246 + label: degradeThermal ? "Thermal throttling" : "CPU running hot" ,247 + detail: st.cpuTemperatureC != null ? (Math .round (Number (st.cpuTemperatureC)) + "°C" ) : "thermal limit" ,248 + action: { kind: "btm" }253 + if (st.diskUsage != null ) {255 + for (var d = 0 ; d < st.diskUsage.length; d++ ) {256 + var m = st.diskUsage[d];257 + var pct = Number (m.usedPercent);258 + if (! isFinite (pct) || pct < 90 ) continue ;259 + var key = m.source || m.target;260 + if (! worst[key] || pct > worst[key].usedPercent) {261 + worst[key] = { usedPercent: pct, target: m.target, source: m.source };264 + var keys = Object .keys (worst);265 + for (var k = 0 ; k < keys.length; k++ ) {266 + var w = worst[keys[k]];268 + id: "low-disk:" + keys[k],269 + severity: w.usedPercent >= 95 ? "error" : "warning" ,271 + label: "Low disk space" ,272 + detail: w.target + " " + w.usedPercent + "%" ,273 + action: { kind: "open-mount" , target: w.target }279 + if (st.memoryUsage != null && Number (st.memoryUsage) >= 0.9 && st.swapGrowing === true ) {282 + severity: "warning" ,284 + label: "Memory pressure" ,285 + detail: Math .round (Number (st.memoryUsage) * 100 ) + "% used, swapping" ,286 + action: { kind: "btm" }291 + if (st.isLaptopBattery !== false && st.healthPercentage != null ) {292 + var health = Number (st.healthPercentage);293 + if (isFinite (health) && health < 80 ) {295 + id: "battery-health" ,296 + severity: health < 60 ? "error" : "warning" ,298 + label: "Battery wear" ,299 + detail: Math .round (health) + "% health" ,306 + if (st.loadOne != null && Number (st.cores) > 0 && Number (st.loadOne) > Number (st.cores)) {309 + severity: "warning" ,312 + detail: Number (st.loadOne).toFixed(2 ) + " on " + Number (st.cores) + " cores" ,313 + action: { kind: "btm" }318 + if (st.updateCount != null && Number (st.updateCount) > 0 ) {319 + var count = Number (st.updateCount);324 + label: count === 1 ? "1 update available" : (count + " updates available" ),325 + detail: "pending packages" ,326 + action: { kind: "update" }330 + issues.sort(function (a, b) { return severityRank(a.severity) - severityRank(b.severity); });334 + if (typeof module !== 'undefined' && module .exports ) {335 + module .exports = { clamp01: clamp01, cpuDelta: cpuDelta, parseMeminfo: parseMeminfo,336 + parseNetDev: parseNetDev, parseDiskstats: parseDiskstats, rate: rate,337 + parseLoadavg: parseLoadavg, parseDf: parseDf, parseFailedUnits: parseFailedUnits,338 + parsePsTop: parsePsTop, parseTemp: parseTemp, parseFan: parseFan,339 + formatBytes: formatBytes, formatRate: formatRate, pushRing: pushRing,340 + detectIssues: detectIssues };quickshell/nuguland/sysinfo.test.js Added new file mode 100644+291 / −0 text lines
1 + const assert = require ('assert' );2 + const S = require ('./sysinfo.js' );8 + const STAT0 = 'cpu 5430899 3815162 1035595 41251079 269664 239859 55955 0 0 0\ncpu0 1 2 3 4' ;10 + const STAT1 = 'cpu 5430899 3815162 1035695 41251179 269664 239859 55955 0 0 0\ncpu0 9 9 9 9' ;13 + 'MemTotal: 16176232 kB' ,14 + 'MemFree: 9155632 kB' ,15 + 'MemAvailable: 12945364 kB' ,17 + 'SwapTotal: 33554428 kB' ,18 + 'SwapFree: 26795148 kB' 22 + 'Inter-| Receive | Transmit' ,23 + ' face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed' ,24 + ' lo: 54663953 73730 0 0 0 0 0 0 54663953 73730 0 0 0 0 0 0' ,25 + 'enp0s25: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0' ,26 + ' wlan0: 2445277803 4752440 0 129580 0 0 0 0 5890720566 5360204 0 82 0 0 0 0' 30 + ' 8 0 sda 9645 2012 90857 763 42944 11803 281531 93778 0 74294 161809 0 0 0 0 39089 67268' ,31 + ' 8 1 sda1 234 2012 8145 99 12 1 11 3 0 56 102 0 0 0 0 0 0' ,32 + ' 7 0 loop0 10 0 80 1 0 0 0 0 0 0 0' ,33 + ' 259 0 nvme0n1 287018 21005 15602232 437312 519616 172971 20543952 3947826 0 1207756 4536137 13779 0 34278912 73655 19543 77343' 36 + const LOADAVG = '0.76 0.64 0.56 1/714 710938' ;39 + 'Filesystem 1-blocks Used Available Capacity Mounted on' ,40 + '/dev/sda3 590718976000 31650119680 556774883328 6% /' ,41 + 'tmpfs 8282230784 5876457472 2405773312 71% /tmp' ,42 + '/dev/sda1 1071624192 193921024 877703168 19% /boot' ,43 + '/dev/sda3 590718976000 31650119680 556774883328 6% /home' 46 + const FAILED_USER = 'app-Handy@autostart.service not-found failed failed app-Handy@autostart.service' ;47 + const FAILED_NONE = '' ;50 + ' PID COMMAND %CPU %MEM' ,51 + ' 710984 rtk 77.7 0.0' ,52 + ' 493586 claude 2.7 2.8' ,53 + ' 619330 firefox 1.7 2.9' 59 + let cd0 = S .cpuDelta(null , STAT0);60 + assert.strictEqual(cd0.usage, 0 , 'first call usage 0' );61 + assert.strictEqual(cd0.next.idle, 41251079 + 269664 , 'idle = idle + iowait' );62 + assert.strictEqual(cd0.next.total, 5430899 + 3815162 + 1035595 + 41251079 + 269664 + 239859 + 55955 , 'total = sum' );64 + let cd1 = S .cpuDelta(cd0.next, STAT1);65 + assert.strictEqual(cd1.usage, 0.5 , 'delta 200 total / 100 non-idle => 0.5' );67 + let cdg = S .cpuDelta(cd0.next, 'garbage no numbers here' );68 + assert.strictEqual(cdg.usage, 0 , 'garbage -> usage 0' );69 + assert.strictEqual(cdg.next, cd0.next, 'garbage keeps prev snapshot' );74 + let mem = S .parseMeminfo(MEMINFO);75 + assert.strictEqual(mem.memTotal, 16176232 * 1024 , 'memTotal bytes' );76 + assert.strictEqual(mem.memAvailable, 12945364 * 1024 , 'memAvailable bytes (prefers MemAvailable)' );77 + assert.strictEqual(mem.swapTotal, 33554428 * 1024 , 'swapTotal bytes' );78 + assert.strictEqual(mem.swapFree, 26795148 * 1024 , 'swapFree bytes' );79 + assert.ok(Math .abs (mem.memoryUsage - (16176232 - 12945364 ) / 16176232 ) < 1e-9 , 'memoryUsage ratio' );80 + assert.ok(Math .abs (mem.swapUsage - (33554428 - 26795148 ) / 33554428 ) < 1e-9 , 'swapUsage ratio' );82 + assert.strictEqual(S .parseMeminfo('MemTotal: 100 kB\nMemAvailable: 50 kB' ).swapUsage, 0 , 'no swap -> 0' );87 + let net = S .parseNetDev(NETDEV);88 + assert.strictEqual(net.rx, 0 + 2445277803 , 'rx sums enp0s25 + wlan0, excludes lo' );89 + assert.strictEqual(net.tx, 0 + 5890720566 , 'tx sums enp0s25 + wlan0, excludes lo' );94 + let disk = S .parseDiskstats(DISKSTATS);96 + assert.strictEqual(disk.readBytes, (90857 + 15602232 ) * 512 , 'readBytes whole-disk sum *512' );97 + assert.strictEqual(disk.writeBytes, (281531 + 20543952 ) * 512 , 'writeBytes whole-disk sum *512' );102 + assert.strictEqual(S .rate(1000 , 3000 , 2 ), 1000 , 'rate (3000-1000)/2' );103 + assert.strictEqual(S .rate(5000 , 1000 , 2 ), 0 , 'counter reset -> 0' );104 + assert.strictEqual(S .rate(0 , 100 , 0 ), 0 , 'zero interval -> 0' );109 + let la = S .parseLoadavg(LOADAVG);110 + assert.strictEqual(la.one, 0.76 );111 + assert.strictEqual(la.five, 0.64 );112 + assert.strictEqual(la.fifteen, 0.56 );117 + let df = S .parseDf(DF);118 + assert.strictEqual(df.length, 4 , 'four real rows, header skipped' );119 + assert.deepStrictEqual(df[0 ], { source: '/dev/sda3' , target: '/' , usedPercent: 6 });120 + assert.deepStrictEqual(df[1 ], { source: 'tmpfs' , target: '/tmp' , usedPercent: 71 });121 + assert.strictEqual(df[3 ].target, '/home' );126 + assert.deepStrictEqual(S .parseFailedUnits(FAILED_USER), ['app-Handy@autostart.service' ]);127 + assert.deepStrictEqual(S .parseFailedUnits(FAILED_NONE), [], 'empty -> no units' );132 + let ps = S .parsePsTop(PS);133 + assert.strictEqual(ps.length, 3 , 'header dropped' );134 + assert.deepStrictEqual(ps[0 ], { pid: 710984 , name: 'rtk' , cpu: 77.7 , mem: 0.0 });135 + assert.strictEqual(ps[1 ].name, 'claude' );140 + assert.strictEqual(S .parseTemp('65000' ), 65 , 'millidegrees -> C' );141 + assert.strictEqual(S .parseTemp('' ), null , 'empty temp -> null' );142 + assert.strictEqual(S .parseFan('3816' ), 3816 , 'fan rpm' );143 + assert.strictEqual(S .parseFan(' ' ), null , 'empty fan -> null' );148 + assert.strictEqual(S .formatBytes(512 ), '512 B' );149 + assert.strictEqual(S .formatBytes(2048 ), '2.0 KiB' );150 + assert.strictEqual(S .formatBytes(5 * 1048576 ), '5.0 MiB' );151 + assert.strictEqual(S .formatBytes(3 * 1073741824 ), '3.0 GiB' );152 + assert.strictEqual(S .formatBytes(- 5 ), '0 B' , 'negative clamps' );153 + assert.strictEqual(S .formatRate(2048 ), '2.0 KiB/s' );159 + for (let i = 1 ; i <= 5 ; i++ ) r = S .pushRing(r, i, 3 );160 + assert.deepStrictEqual(r, [3 , 4 , 5 ], 'capped to last 3' );162 + let r2 = S .pushRing(orig, 3 , 32 );163 + assert.deepStrictEqual(orig, [1 , 2 ], 'input not mutated' );164 + assert.deepStrictEqual(r2, [1 , 2 , 3 ], 'appended copy' );174 + cpuTemperatureC: 55 , tempHighC: 87 , degradationReason: null ,175 + diskUsage: [{ source: '/dev/sda3' , target: '/' , usedPercent: 6 }],176 + memoryUsage: 0.5 , swapGrowing: false ,177 + healthPercentage: 95 , isLaptopBattery: true ,178 + loadOne: 1.0 , cores: CORES,182 + function ids (state) { return S .detectIssues(state).map(function (i) { return i.id; }); }183 + function find (state, id) { return S .detectIssues(state).filter(function (i) { return i.id === id; })[0 ]; }186 + assert.deepStrictEqual(S .detectIssues(base()), [], 'healthy -> no issues' );187 + assert.deepStrictEqual(S .detectIssues({}), [], 'empty state -> no issues (all absent)' );191 + let s = base(); s.failedUnits = ['app-Handy@autostart.service' ];192 + let f = find(s, 'failed-services' );193 + assert.strictEqual(f.severity, 'error' , 'failed -> error' );194 + assert.deepStrictEqual(f.action, { kind: 'systemctl-status' , units: ['app-Handy@autostart.service' ] });195 + let absent = base(); delete absent.failedUnits;196 + assert.strictEqual(ids(absent).indexOf('failed-services' ), - 1 , 'no failedUnits -> skip' );201 + let absent = base(); absent.cpuTemperatureC = null ; absent.degradationReason = null ;202 + assert.strictEqual(ids(absent).indexOf('thermal' ), - 1 , 'no temp + no signal -> skip' );203 + let below = base(); below.cpuTemperatureC = 86 ;204 + assert.strictEqual(ids(below).indexOf('thermal' ), - 1 , '86 < 87 -> none' );205 + let at = base(); at.cpuTemperatureC = 87 ;206 + assert.strictEqual(find(at, 'thermal' ).severity, 'warning' , '87 >= 87 -> warning' );207 + let deg = base(); deg.cpuTemperatureC = 60 ; deg.degradationReason = 'ThermalLimit' ;208 + assert.strictEqual(find(deg, 'thermal' ).severity, 'error' , 'degradation thermal -> error even when cool' );209 + let degOther = base(); degOther.degradationReason = 'PowerSupply' ;210 + assert.strictEqual(ids(degOther).indexOf('thermal' ), - 1 , 'non-thermal degradation -> skip' );215 + let absent = base(); delete absent.diskUsage;216 + assert.strictEqual(ids(absent).indexOf('low-disk:/dev/sda3' ), - 1 , 'no diskUsage -> skip' );217 + function diskAt (pct) { let s = base(); s.diskUsage = [{ source: '/dev/sda3' , target: '/' , usedPercent: pct }]; return s; }218 + assert.strictEqual(S .detectIssues(diskAt(89 )).length, 0 , '89 -> none' );219 + assert.strictEqual(find(diskAt(90 ), 'low-disk:/dev/sda3' ).severity, 'warning' , '90 -> warning' );220 + assert.strictEqual(find(diskAt(94 ), 'low-disk:/dev/sda3' ).severity, 'warning' , '94 -> warning' );221 + assert.strictEqual(find(diskAt(95 ), 'low-disk:/dev/sda3' ).severity, 'error' , '95 -> error' );225 + { source: '/dev/sda3' , target: '/' , usedPercent: 91 },226 + { source: '/dev/sda3' , target: '/home' , usedPercent: 96 }228 + let dupIssues = S .detectIssues(dup).filter(function (i) { return i.id.indexOf('low-disk' ) === 0 ; });229 + assert.strictEqual(dupIssues.length, 1 , 'same device -> one disk issue' );230 + assert.strictEqual(dupIssues[0 ].severity, 'error' , 'worst mount wins' );235 + let high = base(); high.memoryUsage = 0.95 ; high.swapGrowing = true ;236 + assert.strictEqual(find(high, 'mem-pressure' ).severity, 'warning' , '0.95 + growing -> warning' );237 + let noGrow = base(); noGrow.memoryUsage = 0.95 ; noGrow.swapGrowing = false ;238 + assert.strictEqual(ids(noGrow).indexOf('mem-pressure' ), - 1 , 'high mem but no swap growth -> none' );239 + let low = base(); low.memoryUsage = 0.5 ; low.swapGrowing = true ;240 + assert.strictEqual(ids(low).indexOf('mem-pressure' ), - 1 , 'low mem -> none' );241 + let absent = base(); absent.memoryUsage = null ;242 + assert.strictEqual(ids(absent).indexOf('mem-pressure' ), - 1 , 'no mem reading -> skip' );247 + function bat (h) { let s = base(); s.healthPercentage = h; return s; }248 + assert.strictEqual(S .detectIssues(bat(80 )).filter(i => i.id === 'battery-health' ).length, 0 , '80 -> none' );249 + assert.strictEqual(find(bat(79 ), 'battery-health' ).severity, 'warning' , '79 -> warning' );250 + assert.strictEqual(find(bat(60 ), 'battery-health' ).severity, 'warning' , '60 -> warning' );251 + assert.strictEqual(find(bat(59 ), 'battery-health' ).severity, 'error' , '59 -> error' );252 + let absent = base(); absent.healthPercentage = null ;253 + assert.strictEqual(ids(absent).indexOf('battery-health' ), - 1 , 'no health -> skip' );254 + let desktop = bat(50 ); desktop.isLaptopBattery = false ;255 + assert.strictEqual(ids(desktop).indexOf('battery-health' ), - 1 , 'no laptop battery -> skip' );260 + let eq = base(); eq.loadOne = 4 ; eq.cores = 4 ;261 + assert.strictEqual(ids(eq).indexOf('high-load' ), - 1 , 'load == cores -> none (strict >)' );262 + let over = base(); over.loadOne = 4.1 ; over.cores = 4 ;263 + assert.strictEqual(find(over, 'high-load' ).severity, 'warning' , '4.1 > 4 -> warning' );264 + let absent = base(); absent.loadOne = null ;265 + assert.strictEqual(ids(absent).indexOf('high-load' ), - 1 , 'no load -> skip' );270 + let zero = base(); zero.updateCount = 0 ;271 + assert.strictEqual(ids(zero).indexOf('updates' ), - 1 , '0 updates -> none' );272 + let one = base(); one.updateCount = 1 ;273 + assert.strictEqual(find(one, 'updates' ).severity, 'info' , '1 update -> info' );274 + let absent = base(); absent.updateCount = null ;275 + assert.strictEqual(ids(absent).indexOf('updates' ), - 1 , 'updateCount n/a -> skip' );281 + s.failedUnits = ['x.service' ]; 282 + s.cpuTemperatureC = 90 ; 284 + let order = S .detectIssues(s).map(i => i.severity);285 + let ranks = order.map(sev => sev === 'error' ? 0 : sev === 'warning' ? 1 : 2 );286 + for (let i = 1 ; i < ranks.length; i++ ) assert.ok(ranks[i] >= ranks[i - 1 ], 'sorted error->warning->info' );287 + assert.strictEqual(order[0 ], 'error' );288 + assert.strictEqual(order[order.length - 1 ], 'info' );291 + console .log ('sysinfo.test.js: ALL PASS' );