repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

feat(system): redesign system popup — fast graphical widget

191d141480d7365e6b1154a677d7c1348a21b06b

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare 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)

+1817 / −708 text lines

Diff layout

quickshell/nuguland/PopoutHost.qml

Modified

+568 / −303 text lines

33import Quickshell.Wayland
44import "Util.js" as Util
55import "caldav.js" as Ical
6import "sysinfo.js" as Sys
78PanelWindow {
89 id: root
673674 Column {
674675 id: systemPanel
676 readonly property var state: root.resourceService ? Util.parseJson(root.resourceService.systemWidgetState(), {
677 }) : ({
678 "cpu": {
679 "percent": 0,
680 "usage": 0
681 },
682 "memory": {
683 "percent": 0,
684 "usage": 0,
685 "label": "--"
686 },
687 "swap": {
688 "percent": 0,
689 "usage": 0,
690 "label": "off"
691 }
677 // service handle; identity facts and the live issue ARRAY come straight
678 // off Resources.qml (no per-frame JSON parse).
679 readonly property var rs: root.resourceService
680 readonly property var identity: rs ? rs.identity : ({
692681 })
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"
682 // touch the inputs so the band re-evaluates when the slow/rare loops
683 // mutate them; issues() itself is a plain function call.
684 readonly property var issueList: {
685 if (!rs)
686 return [];
706 spacing: 9
688 rs.failedUnits;
689 rs.cpuTemperatureC;
690 rs.diskUsage;
691 rs.updateCount;
692 rs.memoryUsage;
693 rs.swapGrowing;
694 rs.loadOne;
695 rs.healthPercentage;
696 return rs.issues();
697 }
699 spacing: 10
707700 width: parent ? parent.width : 0
709 ResourceMeter {
710 width: parent.width
711 height: 72
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"
716 }
718 SystemMetric {
719 theme: root.theme
720 label: "cpu"
721 valueText: `${Math.round(parent.cpuUsage * 100)}%`
722 value: parent.cpuUsage
723 barColor: parent.cpuColor
724 }
726 SystemMetric {
727 theme: root.theme
728 label: "memory"
729 valueText: `${Math.round(parent.memoryUsage * 100)}% · ${parent.memoryLabel}`
730 value: parent.memoryUsage
731 barColor: parent.memoryColor
732 }
734 SystemMetric {
735 theme: root.theme
736 label: "swap"
737 valueText: parent.swapLabel === "off" ? "off" : `${Math.round(parent.swapUsage * 100)}% · ${parent.swapLabel}`
738 value: parent.swapUsage
739 barColor: parent.swapColor
702 // popoutOpen is a WRITE contract: it gates the slow + rare loops.
703 Component.onCompleted: {
704 if (rs)
705 rs.popoutOpen = true;
707 }
708 Component.onDestruction: {
709 if (rs)
710 rs.popoutOpen = false;
740712 }
714 // ---- two equal rounded cards: identity | live ----
742715 Row {
743 objectName: "systemDiskRow"
744 width: parent.width
745 spacing: 8
716 id: cardRow
718 readonly property real cardW: Math.max(1, (width - spacing) / 2)
720 width: parent.width
721 height: 292
722 spacing: 10
724 // ===== MACHINE IDENTITY =====
725 Rectangle {
726 width: cardRow.cardW
727 height: cardRow.height
728 radius: 14
729 color: root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, 0.55) : "#242424"
731 Column {
732 anchors.fill: parent
733 anchors.margins: 14
734 spacing: 6
736 Row {
737 spacing: 8
739 Text {
740 text: ""
741 color: root.theme ? root.theme.ui.accent : "white"
742 font.family: "Symbols Nerd Font Mono"
743 font.pixelSize: 15
744 }
746 NuguText {
747 theme: root.theme
748 variant: "title"
749 text: "machine"
750 }
752 }
754 IdentityRow {
755 theme: root.theme
756 glyph: ""
757 value: systemPanel.identity.host || "—"
758 }
760 IdentityRow {
761 theme: root.theme
762 glyph: ""
763 value: systemPanel.identity.model || "—"
764 }
766 IdentityRow {
767 theme: root.theme
768 glyph: ""
769 value: systemPanel.identity.distro || "—"
770 }
772 IdentityRow {
773 theme: root.theme
774 glyph: ""
775 value: systemPanel.identity.kernel || "—"
776 }
778 IdentityRow {
779 theme: root.theme
780 glyph: ""
781 value: systemPanel.identity.wm || "—"
782 }
784 IdentityRow {
785 theme: root.theme
786 glyph: ""
787 value: systemPanel.identity.packages ? `${systemPanel.identity.packages} packages` : "—"
788 }
790 IdentityRow {
791 theme: root.theme
792 glyph: ""
793 value: systemPanel.identity.shell || "—"
794 }
796 IdentityRow {
797 theme: root.theme
798 glyph: ""
799 value: systemPanel.identity.uptime || "—"
800 }
802 IdentityRow {
803 theme: root.theme
804 glyph: ""
805 // battery row hidden entirely when there is no laptop battery
806 visible: systemPanel.rs && systemPanel.rs.isLaptopBattery
807 value: {
808 if (!systemPanel.rs)
809 return "—";
811 const h = systemPanel.rs.healthPercentage;
812 return (h === null || h === undefined) ? "battery health n/a" : `battery health ${Math.round(Number(h))}%`;
813 }
814 }
816 }
747 NuguText {
748 theme: root.theme
749 text: "disk"
750 width: 92
751818 }
753 NuguText {
754 theme: root.theme
755 text: systemPanel.diskLabel
756 width: parent.width - 100
757 elide: Text.ElideRight
758 }
760 }
762 Row {
763 objectName: "systemTempRow"
764 width: parent.width
765 spacing: 8
767 NuguText {
768 theme: root.theme
769 text: "temp"
770 width: 92
771 }
773 NuguText {
774 theme: root.theme
775 text: systemPanel.tempLabel
776 width: parent.width - 100
777 elide: Text.ElideRight
820 // ===== LIVE STATS =====
821 Rectangle {
822 width: cardRow.cardW
823 height: cardRow.height
824 radius: 14
825 color: root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, 0.55) : "#242424"
827 Column {
828 anchors.fill: parent
829 anchors.margins: 14
830 spacing: 8
832 Row {
833 spacing: 8
835 Text {
836 text: ""
837 color: root.theme ? root.theme.ui.accent : "white"
838 font.family: "Symbols Nerd Font Mono"
839 font.pixelSize: 15
840 }
842 NuguText {
843 theme: root.theme
844 variant: "title"
845 text: "live"
846 }
848 }
850 MetricRow {
851 theme: root.theme
852 label: "cpu"
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 : []
857 sparkScaleMax: 1
858 }
860 MetricRow {
861 theme: root.theme
862 label: "mem"
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 : []
867 sparkScaleMax: 1
868 }
870 MetricRow {
871 theme: root.theme
872 label: "swap"
873 value: {
874 if (!systemPanel.rs || systemPanel.rs.swapTotal <= 0)
875 return "off";
877 return `${Math.round(systemPanel.rs.swapUsage * 100)}% · ${Sys.formatBytes(Math.max(0, systemPanel.rs.swapTotal - systemPanel.rs.swapFree))}`;
878 }
879 fraction: systemPanel.rs ? systemPanel.rs.swapUsage : 0
880 barColor: root.theme ? root.theme.warning : "#f0ee69"
881 showSpark: false
882 ring: []
883 }
885 MetricRow {
886 theme: root.theme
887 label: "temp"
888 value: {
889 if (!systemPanel.rs)
890 return "n/a";
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`;
896 return ts + fs;
897 }
898 fraction: {
899 if (!systemPanel.rs)
900 return 0;
902 const t = systemPanel.rs.cpuTemperatureC;
903 if (t === null || t === undefined)
904 return 0;
906 return Math.max(0, Math.min(1, Number(t) / Math.max(1, systemPanel.rs.tempHighC)));
907 }
908 barColor: root.theme ? root.theme.error : "#ec6376"
909 // sparkline hidden when the sensor is unavailable (null)
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
913 }
915 MetricRow {
916 theme: root.theme
917 label: "net"
918 value: systemPanel.rs ? `↓ ${Sys.formatRate(systemPanel.rs.networkRxRate)} ↑ ${Sys.formatRate(systemPanel.rs.networkTxRate)}` : "—"
919 // net/disk have no natural ceiling: scale against the ring's own max
920 fraction: {
921 if (!systemPanel.rs)
922 return 0;
924 const ring = systemPanel.rs.netRing || [];
925 let m = 0;
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;
929 }
930 barColor: root.theme ? root.theme.info : "#3ec5e3"
931 ring: systemPanel.rs ? systemPanel.rs.netRing : []
932 }
934 MetricRow {
935 theme: root.theme
936 label: "disk"
937 value: systemPanel.rs ? `R ${Sys.formatRate(systemPanel.rs.diskReadRate)} W ${Sys.formatRate(systemPanel.rs.diskWriteRate)}` : "—"
938 fraction: {
939 if (!systemPanel.rs)
940 return 0;
942 const ring = systemPanel.rs.diskRing || [];
943 let m = 0;
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;
947 }
948 barColor: root.theme ? root.theme.ui.minor : "#9d9d9d"
949 ring: systemPanel.rs ? systemPanel.rs.diskRing : []
950 }
952 NuguText {
953 theme: root.theme
954 variant: "meta"
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 —"
956 }
958 }
778960 }
780962 }
964 // ---- issues band ----
782965 Column {
783 objectName: "systemProcessTable"
784966 width: parent.width
785 spacing: 4
967 spacing: 6
787 Row {
969 // all-clear: a single green check row (the service emits NO synthetic
970 // green issue — the view renders it when the array is empty).
971 Rectangle {
972 visible: systemPanel.issueList.length === 0
788973 width: parent.width
789 spacing: 6
974 height: 30
975 radius: 10
976 color: root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, 0.55) : "#242424"
791 NuguText {
792 theme: root.theme
793 variant: "meta"
794 text: "pid"
795 width: 52
796 }
978 Row {
979 anchors.left: parent.left
980 anchors.leftMargin: 12
981 anchors.verticalCenter: parent.verticalCenter
982 spacing: 8
798 NuguText {
799 theme: root.theme
800 variant: "meta"
801 text: "name"
802 width: parent.width - 190
803 }
984 Text {
985 anchors.verticalCenter: parent.verticalCenter
986 text: ""
987 color: "#8bd17a"
988 font.family: "Symbols Nerd Font Mono"
989 font.pixelSize: 14
990 }
805 NuguText {
806 theme: root.theme
807 variant: "meta"
808 text: "cpu"
809 width: 48
810 }
992 NuguText {
993 anchors.verticalCenter: parent.verticalCenter
994 theme: root.theme
995 variant: "meta"
996 text: "disk · memory · battery · updates ok"
997 }
812 NuguText {
813 theme: root.theme
814 variant: "meta"
815 text: "mem"
816 width: 48
817999 }
8211003 Repeater {
822 model: root.resourceService ? root.resourceService.processes : []
1004 model: systemPanel.issueList
1006 delegate: Rectangle {
1007 id: issueCard
824 delegate: Row {
8251009 required property var modelData
1011 readonly property color sevColor: {
1012 const s = modelData.severity;
1013 if (s === "error")
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";
1020 }
8271022 width: parent.width
828 spacing: 6
1023 height: 40
1024 radius: 10
1025 clip: true
1026 color: root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, 0.55) : "#242424"
830 NuguText {
831 theme: root.theme
832 variant: "meta"
833 text: String(modelData.pid || 0)
834 width: 52
1028 // severity-colored left accent bar (strong signal, matches card aesthetic)
1029 Rectangle {
1030 anchors.left: parent.left
1031 anchors.top: parent.top
1032 anchors.bottom: parent.bottom
1033 width: 4
1034 color: issueCard.sevColor
837 NuguText {
838 theme: root.theme
839 variant: "meta"
840 text: String(modelData.name || "?")
841 width: parent.width - 190
842 elide: Text.ElideRight
1037 Rectangle {
1038 id: sevDot
1040 anchors.left: parent.left
1041 anchors.leftMargin: 14
1042 anchors.verticalCenter: parent.verticalCenter
1043 width: 9
1044 height: 9
1045 radius: 4.5
1046 color: issueCard.sevColor
845 NuguText {
846 theme: root.theme
847 variant: "meta"
848 text: `${Number(modelData.cpu || 0).toFixed(1)}%`
849 width: 48
1049 Text {
1050 id: issGlyph
1052 anchors.left: sevDot.right
1053 anchors.leftMargin: 10
1054 anchors.verticalCenter: parent.verticalCenter
1055 text: String(issueCard.modelData.icon || "")
1056 color: issueCard.sevColor
1057 font.family: "Symbols Nerd Font Mono"
1058 font.pixelSize: 14
852 NuguText {
853 theme: root.theme
854 variant: "meta"
855 text: `${Number(modelData.mem || 0).toFixed(1)}%`
856 width: 48
1061 Column {
1062 anchors.left: issGlyph.right
1063 anchors.leftMargin: 10
1064 anchors.right: actBtn.visible ? actBtn.left : parent.right
1065 anchors.rightMargin: 10
1066 anchors.verticalCenter: parent.verticalCenter
1067 spacing: 1
1069 NuguText {
1070 theme: root.theme
1071 width: parent.width
1072 text: String(issueCard.modelData.label || "")
1073 }
1075 NuguText {
1076 theme: root.theme
1077 variant: "meta"
1078 width: parent.width
1079 text: String(issueCard.modelData.detail || "")
1080 }
1082 }
1084 Rectangle {
1085 id: actBtn
1087 visible: !!issueCard.modelData.action
1088 anchors.right: parent.right
1089 anchors.rightMargin: 10
1090 anchors.verticalCenter: parent.verticalCenter
1091 width: 66
1092 height: 26
1093 radius: 8
1094 color: root.theme ? root.theme.withAlpha(issueCard.sevColor, 0.30) : "transparent"
1096 NuguText {
1097 anchors.centerIn: parent
1098 theme: root.theme
1099 variant: "meta"
1100 text: "open"
1101 }
1103 MouseArea {
1104 anchors.fill: parent
1105 cursorShape: Qt.PointingHandCursor
1106 onClicked: {
1107 if (systemPanel.rs)
1108 systemPanel.rs.runIssueAction(issueCard.modelData.id);
1110 }
1111 }
865 Rectangle {
1121 // ---- compact top-processes row (chips) ----
1122 Flow {
8661123 width: parent.width
867 height: 28
868 radius: 9
869 color: root.theme ? root.theme.withAlpha(root.theme.ui.accent, 0.18) : "transparent"
870 border.width: 0
871 border.color: root.theme ? root.theme.ui.accent : "transparent"
1124 spacing: 8
873 Row {
874 anchors.centerIn: parent
875 spacing: 6
1126 Repeater {
1127 model: systemPanel.rs ? systemPanel.rs.processes : []
1129 delegate: Rectangle {
1130 id: procChip
1132 required property var modelData
1134 height: 22
1135 width: procRow.implicitWidth + 18
1136 radius: 8
1137 color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.16) : "transparent"
1139 Row {
1140 id: procRow
1142 anchors.centerIn: parent
1143 spacing: 6
1145 NuguText {
1146 theme: root.theme
1147 variant: "meta"
1148 text: String(procChip.modelData.name || "?")
1149 }
1151 NuguText {
1152 theme: root.theme
1153 variant: "meta"
1154 color: root.theme ? root.theme.ui.accent : "white"
1155 text: `${Number(procChip.modelData.cpu || 0).toFixed(0)}%`
1156 }
1158 }
877 Text {
878 text: ""
879 color: root.theme ? root.theme.content.normal : "white"
880 font.family: "Symbols Nerd Font Mono"
881 font.pixelSize: 13
884 NuguText {
885 theme: root.theme
886 variant: "meta"
887 text: "btm"
888 }
890 }
892 MouseArea {
893 anchors.fill: parent
894 onClicked: {
895 if (root.resourceService)
896 root.resourceService.launchBtm();
898 }
1058 component ResourceMeter: Canvas {
1059 id: meter
1321 component IdentityRow: Row {
1322 id: irow
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 theme
1325 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
1329 spacing: 9
1331 Text {
1332 width: 18
1333 text: irow.glyph
1334 color: irow.theme ? irow.theme.ui.minor : "white"
1335 font.family: "Symbols Nerd Font Mono"
1336 font.pixelSize: 13
1073 function sampleValue(sample, index) {
1074 if (Array.isArray(sample))
1075 return clamp01(sample[index] || 0);
1077 return index === 0 ? clamp01(sample) : 0;
1078 }
1080 function normalizedSampleValue(sample, index) {
1081 const value = sampleValue(sample, index);
1082 if (!normalizeSeries)
1083 return value;
1085 const samples = seriesSamples || [];
1086 let low = 1;
1087 let high = 0;
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);
1092 }
1093 const span = high - low;
1094 return span < 0.0001 ? 0.5 : (value - low) / span;
1095 }
1097 function interpolatedSampleValue(samples, sampleIndex, series) {
1098 const current = normalizedSampleValue(samples[sampleIndex], series);
1099 if (graphBlend >= 1 || previousSeriesSamples.length === 0)
1100 return current;
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;
1105 }
1107 onGraphBlendChanged: requestPaint()
1108 onSeriesSamplesChanged: {
1109 previousSeriesSamples = currentSeriesSamples.length > 0 ? currentSeriesSamples : seriesSamples;
1110 currentSeriesSamples = seriesSamples;
1111 graphBlend = 0;
1112 graphAnimation.restart();
1113 requestPaint();
1114 }
1115 onSeriesColorsChanged: requestPaint()
1116 onNormalizeSeriesChanged: requestPaint()
1117 onTrackColorChanged: requestPaint()
1118 onWidthChanged: requestPaint()
1119 onHeightChanged: requestPaint()
1120 onPaint: {
1121 const ctx = getContext("2d");
1122 ctx.clearRect(0, 0, width, height);
1123 if (width <= 0 || height <= 0)
1124 return ;
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)
1133 return ;
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;
1139 ctx.beginPath();
1140 let previousX = 0;
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++) {
1144 const x = i * dx;
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);
1149 previousX = x;
1150 previousY = y;
1151 }
1152 ctx.lineTo(previousX, previousY);
1153 ctx.strokeStyle = String(seriesColors[series] || "#ffffff");
1154 ctx.lineWidth = series === 0 ? 2.4 : 1.8;
1155 ctx.stroke();
1156 }
1157 }
1159 NumberAnimation on graphBlend {
1160 id: graphAnimation
1162 running: false
1163 from: 0
1164 to: 1
1165 duration: 320
1166 easing.type: Easing.OutCubic
1339 NuguText {
1340 theme: irow.theme
1341 variant: "meta"
1342 text: irow.value
1343 width: Math.max(1, parent.width - 27)
1171 component SystemMetric: Column {
1172 id: metric
1348 // thin rounded-Rectangle sparkline over a ring buffer (no Canvas, no shader).
1349 // bars fill from the right; each ring is scaled against its own max.
1350 component Sparkline: Item {
1351 id: spark
11741353 required property QtObject theme
1175 property string label: ""
1176 property string valueText: ""
1177 property real value: 0
1354 property var values: []
11781355 property color barColor: theme ? theme.ui.accent : "white"
1356 // absolute ceiling for bounded metrics (cpu/mem=1, temp=tempHighC); 0 = auto
1357 // window-max for unbounded metrics (net/disk). Keeps bars consistent with the fill-bar.
1358 property real scaleMax: 0
1180 width: parent ? parent.width : 0
1181 spacing: 3
1360 // keep a constant 2px bar pitch; show only the most recent samples that fit
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;
1365 }
1366 readonly property real maxV: {
1367 if (spark.scaleMax > 0)
1368 return spark.scaleMax;
1369 const v = spark.slice;
1370 let m = 0;
1371 for (let i = 0; i < v.length; i++) m = Math.max(m, Number(v[i]) || 0)
1372 return m;
1373 }
11831375 Row {
1184 width: parent.width
1185 spacing: 8
1376 anchors.right: parent.right
1377 anchors.bottom: parent.bottom
1378 height: parent.height
1379 spacing: 1
1187 NuguText {
1188 theme: metric.theme
1189 text: metric.label
1190 width: 92
1191 }
1381 Repeater {
1382 model: spark.slice
1384 delegate: Item {
1385 required property var modelData
1387 width: 2
1388 height: spark.height
1390 Rectangle {
1391 anchors.bottom: parent.bottom
1392 width: parent.width
1393 radius: 1
1394 height: Math.max(1, spark.height * (spark.maxV > 0 ? Math.min(1, (Number(modelData) || 0) / spark.maxV) : 0))
1395 color: spark.barColor
1396 }
1398 }
1193 NuguText {
1194 theme: metric.theme
1195 text: metric.valueText
1404 }
1406 // one live metric: label · value · rounded fill-bar (track + fill) · sparkline.
1407 component MetricRow: Item {
1408 id: mrow
1410 required property QtObject theme
1411 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
1420 height: 24
1422 NuguText {
1423 id: mlabel
1425 anchors.left: parent.left
1426 anchors.verticalCenter: parent.verticalCenter
1427 theme: mrow.theme
1428 variant: "meta"
1429 text: mrow.label
1430 width: 38
1431 }
1433 NuguText {
1434 id: mvalue
1436 anchors.left: mlabel.right
1437 anchors.leftMargin: 4
1438 anchors.verticalCenter: parent.verticalCenter
1439 theme: mrow.theme
1440 variant: "meta"
1441 text: mrow.value
1442 width: 132
1443 }
1445 Sparkline {
1446 id: mspark
1448 anchors.right: parent.right
1449 anchors.verticalCenter: parent.verticalCenter
1450 theme: mrow.theme
1451 visible: mrow.showSpark
1452 values: mrow.ring
1453 scaleMax: mrow.sparkScaleMax
1454 barColor: mrow.barColor
1455 width: 60
1456 height: 16
1457 }
12001459 Rectangle {
1201 width: parent.width
1202 height: 4
1203 radius: 2
1204 color: metric.theme ? metric.theme.ui.minor : "black"
1460 id: mtrack
1462 anchors.left: mvalue.right
1463 anchors.leftMargin: 8
1464 anchors.right: mspark.left
1465 anchors.rightMargin: 8
1466 anchors.verticalCenter: parent.verticalCenter
1467 height: 6
1468 radius: 3
1469 color: mrow.theme ? mrow.theme.withAlpha(mrow.theme.ui.minor, 0.28) : "#333333"
12061471 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))
12081473 height: parent.height
12091474 radius: parent.radius
1210 color: metric.barColor
1475 color: mrow.barColor
12121477 Behavior on width {
12131478 NumberAnimation {
1214 duration: metric.theme && metric.theme.lowPowerMode ? 0 : 180
1479 duration: mrow.theme && mrow.theme.lowPowerMode ? 0 : 160
12151480 easing.type: Easing.OutCubic
23722637 NuguText {
23732638 theme: root.theme
2374 text: root.resourceService ? `↓ ${root.resourceService.formatRate(root.resourceService.networkRxRate)}` : "↓ 0 B/s"
2639 text: root.resourceService ? `↓ ${Sys.formatRate(root.resourceService.networkRxRate)}` : "↓ 0 B/s"
23752640 color: root.theme ? root.theme.ui.accent : "white"
23782643 NuguText {
23792644 theme: root.theme
2380 text: root.resourceService ? `↑ ${root.resourceService.formatRate(root.resourceService.networkTxRate)}` : "↑ 0 B/s"
2645 text: root.resourceService ? `↑ ${Sys.formatRate(root.resourceService.networkTxRate)}` : "↑ 0 B/s"
23812646 color: root.theme ? root.theme.ui.focus : "white"

quickshell/nuguland/Resources.qml

Modified

+599 / −391 text lines

11import QtQuick
2import Quickshell
23import Quickshell.Io
4import "sysinfo.js" as Sys
6// Thin I/O + cadence service over the pure sysinfo.js core.
7// All parsing / issue-detection logic lives in sysinfo.js; this file only does
8// file reads, process spawns, timers, and exposes reactive properties.
49Item {
510 id: root
12 // --- injected services (DI via shell.qml; never singletons here) ---
13 required property var upower // UPower singleton (displayDevice bindings)
14 required property var powerProfiles // PowerProfiles singleton (degradationReason)
15 required property QtObject brightnessService // Brightness.qml (identity row reuse)
17 // --- view-bound live properties (fast loop) ---
718 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: []
1619 property real memoryUsage: 0
1720 property real swapUsage: 0
1821 property real memTotal: 0
2326 property real networkTxRate: 0
2427 property real diskReadRate: 0
2528 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
29 // nullable: no sensor -> null (view shows n/a, thermal check skipped)
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
37 // --- ring buffers (cap 32) for sparklines ---
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: []
45 // --- issue inputs (slow / rare loops) ---
46 property var failedUnits: []
47 property var diskUsage: [] // [{source,target,usedPercent}]
48 property var updateCount: null // null = unknown / n/a
49 property bool swapGrowing: false
50 // thermal high threshold; resolved from sensor max/crit on start, default 87
51 property real tempHighC: 87
53 // aurora "firestorm" intensity, consumed by AuroraBackdrop.qml. A continuous
54 // 0..1 ramp as CPU temp climbs the last 12°C toward the thermal threshold —
55 // replaces the old hot/cool hysteresis counters. null temp => 0 (calm).
56 readonly property real firestormTarget: {
57 if (cpuTemperatureC === null || cpuTemperatureC === undefined)
58 return 0;
59 const t = Number(cpuTemperatureC);
60 if (!isFinite(t))
61 return 0;
62 const high = Math.max(1, tempHighC);
63 const cool = high - 12;
64 return Math.max(0, Math.min(1, (t - cool) / (high - cool)));
65 }
67 // --- top processes (slow loop, only while popout open) ---
4068 property var processes: []
41 property var lastBtmAction: ({
70 // --- identity facts (rare loop, cached) ---
71 property var identity: ({})
72 property bool identityLoaded: false
74 // --- popout visibility gate (set by the view) ---
75 property bool popoutOpen: false
77 // --- battery / throttle (event-driven UPower bindings) ---
78 // healthPercentage is null when unsupported / no battery (NOT -1) so the
79 // detectIssues battery check is skipped rather than firing a false error.
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;
83 }
84 readonly property bool isLaptopBattery: {
85 const d = upower ? upower.displayDevice : null;
86 return !!(d && d.ready && d.isLaptopBattery);
87 }
88 readonly property var degradationReason: {
89 if (!powerProfiles)
90 return null;
92 const r = powerProfiles.degradationReason;
93 return (r === null || r === undefined) ? null : String(r);
94 }
96 // --- last issue action record (for IPC introspection) ---
97 property var lastAction: ({
4298 })
44 function clamp01(value) {
45 return Math.max(0, Math.min(1, Number(value)));
46 }
100 // --- internal delta state ---
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) {
49 if (value >= 0.9)
50 return "error";
52 if (value >= 0.7)
53 return "warning";
55 return "normal";
56 }
58 function colorRoleFor(value) {
59 const signal = signalFor(value);
60 if (signal === "error")
61 return "error";
63 if (signal === "warning")
64 return "warning";
66 return "ui.accent";
67 }
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`;
77 if (bytes >= 1024)
78 return `${(bytes / 1024).toFixed(1)} KiB`;
80 return `${Math.round(bytes)} B`;
81 }
83 function formatRate(value) {
84 return `${formatBytes(value)}/s`;
85 }
111 // --- network-widget compatibility shims (consumed by shell.qml
112 // networkWidgetState(); out of scope for the system redesign, kept so a
113 // working widget is not silently regressed). ---
114 property var networkHistorySamples: []
87116 function networkRxLevel() {
88 return clamp01(networkRxRate / 262144);
117 return Sys.clamp01(networkRxRate / 262144);
89118 }
91120 function networkTxLevel() {
92 return clamp01(networkTxRate / 262144);
93 }
95 function diskLevel() {
96 return clamp01((diskReadRate + diskWriteRate) / 8.38861e+06);
97 }
99 function temperatureLevel() {
100 return clamp01(cpuTemperatureC / Math.max(temperatureHighThresholdC(), 1));
101 }
103 function systemLoad() {
104 return Math.max(cpuUsage, memoryUsage, swapUsage);
105 }
107 function systemSignal(value) {
108 return signalFor(value);
109 }
111 function systemColorRole(value) {
112 return colorRoleFor(value);
113 }
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);
119 }));
120 return next;
121 }
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)
127 next.push(numeric);
129 return next;
130 }
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) => {
136 return a - b;
137 });
138 if (sorted.length === 0)
139 return 61;
141 const index = Math.max(0, Math.min(sorted.length - 1, Math.ceil((sorted.length - 1) * ratio)));
142 return sorted[index];
143 }
145 function temperatureHighThresholdC() {
146 return Math.max(72, Math.min(87, percentile(temperatureHistorySamples, 0.95) + 8));
147 }
149 function temperatureCoolThresholdC() {
150 return temperatureHighThresholdC() - 5;
151 }
153 function updateFirestormState() {
154 const temp = Number(cpuTemperatureC);
155 if (!Number.isFinite(temp) || temp <= 0)
156 return ;
158 const high = temperatureHighThresholdC();
159 const cool = temperatureCoolThresholdC();
160 if (temp >= high) {
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;
166 }
167 if (firestormHotSeconds >= hotHoldSeconds)
168 firestormTarget = 1;
170 if (firestormCoolSeconds >= coolHoldSeconds)
171 firestormTarget = 0;
173 }
175 function systemHistorySample() {
176 return [cpuUsage, memoryUsage, swapUsage, diskLevel(), temperatureLevel()];
177 }
179 function networkHistorySample() {
180 return [networkRxLevel(), networkTxLevel(), 0, 0];
181 }
183 function refreshHistories() {
184 systemHistorySamples = appendHistorySample(systemHistorySamples, systemHistorySample());
185 networkHistorySamples = appendHistorySample(networkHistorySamples, networkHistorySample());
121 return Sys.clamp01(networkTxRate / 262144);
186122 }
188124 function shaderHistoryObject(samples) {
189125 return {
190 "windowSeconds": historyWindowSeconds,
191 "sampleIntervalMs": sampleIntervalMs,
192 "sampleLimit": historySampleLimit,
193 "sampleCount": samples.length
126 "windowSeconds": 7200,
127 "sampleIntervalMs": 2000,
128 "sampleLimit": 3600,
129 "sampleCount": (samples || []).length
194130 };
195131 }
197 function systemWidgetState() {
198 const load = systemLoad();
133 // --- fast loop: pure /proc + /sys reads, deltas, rings (always on, 2s) ---
134 function refreshFast() {
135 statFile.reload();
136 const statText = statFile.text() || "";
137 const cd = Sys.cpuDelta(prevCpu, statText);
138 cpuUsage = cd.usage;
139 prevCpu = cd.next;
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;
156 }
158 netFile.reload();
159 diskFile.reload();
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;
164 if (seconds > 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);
169 }
170 prevNetRx = net.rx;
171 prevNetTx = net.tx;
172 prevDiskRead = disk.readBytes;
173 prevDiskWrite = disk.writeBytes;
174 prevRateTime = now;
176 loadFile.reload();
177 const loadText = loadFile.text() || "";
178 if (loadText.trim().length > 0) {
179 const la = Sys.parseLoadavg(loadText);
180 loadOne = la.one;
181 loadFive = la.five;
182 loadFifteen = la.fifteen;
183 }
185 // hwmon temp + fan; keep last-good on null/parse failure
186 if (tempFile.path) {
187 tempFile.reload();
188 const t = Sys.parseTemp(tempFile.text() || "");
189 if (t !== null)
190 cpuTemperatureC = t;
192 }
193 if (fanFile.path) {
194 fanFile.reload();
195 const f = Sys.parseFan(fanFile.text() || "");
196 if (f !== null)
197 fanRpm = f;
199 }
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);
209 }
211 // --- slow loop: process spawns, only while popout open (5s) ---
212 function refreshSlow() {
213 if (!popoutOpen)
214 return ;
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"]);
228 }
230 // --- rare loop: identity facts (cached) + checkupdates (async, on open) ---
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"]);
238 }
240 function recomputeFailed() {
241 failedUnits = failedSystemUnits.concat(failedUserUnits);
242 }
244 // --- assemble detectIssues input (keys MUST match the sysinfo.js contract) ---
245 function buildIssueState() {
246 return {
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,
256 "loadOne": loadOne,
257 "cores": cores,
258 "updateCount": updateCount
259 };
260 }
262 // returns the issue ARRAY (Repeater binds directly); not stringified.
263 function issues() {
264 return Sys.detectIssues(buildIssueState());
265 }
267 // click-to-act: resolve the issue's action and launch detached.
268 function runIssueAction(id) {
269 const list = issues();
270 let issue = null;
271 for (let i = 0; i < list.length; i++) {
272 if (list[i].id === id) {
273 issue = list[i];
274 break;
275 }
276 }
277 if (!issue || !issue.action)
278 return JSON.stringify({
279 "ok": false,
280 "reason": "no-action",
281 "id": id
282 });
284 const a = issue.action;
285 let argv = null;
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\""];
296 if (!argv)
297 return JSON.stringify({
298 "ok": false,
299 "reason": "unknown-action",
300 "kind": a.kind
301 });
303 lastAction = {
304 "ok": true,
305 "id": id,
306 "kind": a.kind,
307 "argv": argv
308 };
309 Quickshell.execDetached(argv);
310 return JSON.stringify(lastAction);
311 }
313 // --- trimmed IPC contract (KEEP — see nuguland-statejson-is-ipc-contract) ---
314 function stateJson() {
315 const memUsed = Math.max(0, memTotal - memAvailable);
316 const swapUsed = Math.max(0, swapTotal - swapFree);
199317 return JSON.stringify({
200318 "kind": "system",
201319 "title": "system",
202 "load": load,
203 "percent": Math.round(load * 100),
204 "signal": systemSignal(load),
205 "colorRole": systemColorRole(load),
206 "barLabel": "system",
207 "shader": {
208 "kind": "system-mini-graph",
209 "clipped": true,
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"]
215 },
320 "popoutOpen": popoutOpen,
216321 "cpu": {
217322 "usage": cpuUsage,
218323 "percent": Math.round(cpuUsage * 100)
220325 "memory": {
221326 "usage": memoryUsage,
222327 "percent": Math.round(memoryUsage * 100),
223 "used": Math.max(0, memTotal - memAvailable),
328 "used": memUsed,
224329 "total": memTotal,
225 "label": `${formatBytes(Math.max(0, memTotal - memAvailable))} / ${formatBytes(memTotal)}`
330 "label": `${Sys.formatBytes(memUsed)} / ${Sys.formatBytes(memTotal)}`
226331 },
227332 "swap": {
228333 "usage": swapUsage,
229334 "percent": Math.round(swapUsage * 100),
230 "used": Math.max(0, swapTotal - swapFree),
335 "used": swapUsed,
231336 "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"
233338 },
234339 "network": {
235340 "rxRate": networkRxRate,
236341 "txRate": networkTxRate,
237 "label": `↓ ${formatRate(networkRxRate)} ↑ ${formatRate(networkTxRate)}`
342 "label": `↓ ${Sys.formatRate(networkRxRate)} ↑ ${Sys.formatRate(networkTxRate)}`
238343 },
239344 "disk": {
240345 "readRate": diskReadRate,
241346 "writeRate": diskWriteRate,
242 "level": diskLevel(),
243 "label": `R ${formatRate(diskReadRate)} W ${formatRate(diskWriteRate)}`
347 "label": `R ${Sys.formatRate(diskReadRate)} W ${Sys.formatRate(diskWriteRate)}`
244348 },
245349 "temperature": {
246 "label": tempLabel,
247350 "celsius": cpuTemperatureC,
248 "level": temperatureLevel(),
249 "highThresholdC": temperatureHighThresholdC(),
250 "coolThresholdC": temperatureCoolThresholdC(),
251 "firestormTarget": firestormTarget
351 "highThresholdC": tempHighC,
352 "label": cpuTemperatureC !== null ? `${Math.round(Number(cpuTemperatureC))}°C` : "n/a"
252353 },
354 "fan": {
355 "rpm": fanRpm,
356 "label": fanRpm !== null ? `${Math.round(Number(fanRpm))} rpm` : "n/a"
357 },
358 "load": {
359 "one": loadOne,
360 "five": loadFive,
361 "fifteen": loadFifteen,
362 "cores": cores
363 },
364 "battery": {
365 "healthPercentage": healthPercentage,
366 "isLaptopBattery": isLaptopBattery
367 },
368 "identity": identity,
369 "updateCount": updateCount,
253370 "processes": processes,
254 "btmAction": lastBtmAction
371 "issues": issues(),
372 "lastAction": lastAction
255373 });
256374 }
258 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);
263 }).slice(-24);
264 return JSON.stringify({
265 "kind": name,
266 "title": name === "system" ? "System" : name.toUpperCase(),
267 "value": clamped,
268 "percent": Math.round(clamped * 100),
269 "signal": signalFor(clamped),
270 "role": colorRoleFor(clamped),
271 "boundedHeroMeter": {
272 "value": clamped,
273 "min": 0,
274 "max": 1,
275 "shape": clamped >= 0.8 ? "burst" : (clamped >= 0.4 ? "sunny" : "plain"),
276 "role": colorRoleFor(clamped)
277 },
278 "sparkline": {
279 "fillOpacity": 0.22,
280 "sampleCount": boundedSamples.length,
281 "alignment": "right"
282 },
283 "sparklineSamples": boundedSamples,
284 "helperProcesses": [],
285 "widgetProcesses": "forbidden"
286 });
376 // backward-compatible alias for the existing shell.qml "systemWidgetState" IPC
377 function systemWidgetState() {
378 return stateJson();
287379 }
289 function refreshCpu() {
290 statFile.reload();
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);
295 }))
296 return ;
298 const idle = parts[3] + (parts[4] || 0);
299 const total = parts.reduce((sum, n) => {
300 return sum + n;
301 }, 0);
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;
311 }
312 }
314 function refreshMemory() {
315 meminfoFile.reload();
316 const values = ({
317 });
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+)/);
321 if (match)
322 values[match[1]] = Number(match[2]) * 1024;
324 }
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;
331 }
333 function applyProcessSnapshot(text) {
334 const rows = [];
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)
339 continue;
341 rows.push({
342 "pid": Number(parts[0]),
343 "name": parts[1],
344 "cpu": Number(parts[2]) || 0,
345 "mem": Number(parts[3]) || 0
381 // --- integration selfTest: exercises the QML glue (buildIssueState keys,
382 // issues()/stateJson()), not sysinfo.js (already node-tested). ---
383 function selfTest() {
384 const cases = [];
385 function ok(name, cond) {
386 cases.push({
387 "name": name,
388 "pass": !!cond
346389 });
347390 }
348 processes = rows;
349 }
391 function findIssue(list, id) {
392 for (let i = 0; i < list.length; i++) {
393 if (list[i].id === id)
394 return list[i];
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();
357 }
359 function firestormState() {
360 return JSON.stringify({
361 "temperatureC": cpuTemperatureC,
362 "label": tempLabel,
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,
372 "sensorFacts": {
373 "currentObservedC": 61,
374 "coretempHighC": cpuTempSensorHighC,
375 "coretempCritC": 105
376396 }
397 return null;
398 }
399 const saved = {
400 "failedUnits": failedUnits,
401 "cpuTemperatureC": cpuTemperatureC,
402 "tempHighC": tempHighC,
403 "diskUsage": diskUsage,
404 "memoryUsage": memoryUsage,
405 "swapGrowing": swapGrowing,
406 "loadOne": loadOne,
407 "cores": cores,
408 "updateCount": updateCount
409 };
410 try {
411 const st = buildIssueState();
412 const keys = ["failedUnits", "cpuTemperatureC", "tempHighC", "degradationReason", "diskUsage", "memoryUsage", "swapGrowing", "healthPercentage", "isLaptopBattery", "loadOne", "cores", "updateCount"];
413 const missing = [];
414 for (let k = 0; k < keys.length; k++) {
415 if (!(keys[k] in st))
416 missing.push(keys[k]);
418 }
419 ok("state-keys-present:" + missing.join(","), missing.length === 0);
421 failedUnits = ["app-Handy@autostart.service"];
422 cpuTemperatureC = 95;
423 tempHighC = 87;
424 diskUsage = [{
425 "source": "/dev/sda3",
426 "target": "/",
427 "usedPercent": 96
428 }];
429 memoryUsage = 0.95;
430 swapGrowing = true;
431 loadOne = 9;
432 cores = 4;
433 updateCount = 3;
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");
446 // below threshold -> these checks clear (battery/throttle ignored: real device)
447 failedUnits = [];
448 cpuTemperatureC = 40;
449 diskUsage = [{
450 "source": "/dev/sda3",
451 "target": "/",
452 "usedPercent": 50
453 }];
454 memoryUsage = 0.5;
455 swapGrowing = false;
456 loadOne = 1;
457 updateCount = 0;
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));
469 } catch (e) {
470 ok("threw:" + e, false);
471 } finally {
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;
481 }
482 const fail = cases.filter((c) => {
483 return !c.pass;
484 }).length;
485 return JSON.stringify({
486 "pass": cases.length - fail,
487 "fail": fail,
488 "cases": cases
377489 });
378490 }
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'"]);
387 }
389 function launchBtm() {
390 lastBtmAction = {
391 "kind": "btm",
392 "terminal": "wezterm",
393 "argv": ["wezterm", "start", "--", "btm"]
394 };
395 btmLaunch.exec(["wezterm", "start", "--", "btm"]);
396 return JSON.stringify(lastBtmAction);
397 }
399 function refreshRates() {
400 netFile.reload();
401 diskFile.reload();
402 let rx = 0;
403 let tx = 0;
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)
408 continue;
410 const pieces = line.split(":");
411 const name = pieces[0].trim();
412 if (name === "lo")
413 continue;
415 const fields = pieces[1].trim().split(/\s+/).map(Number);
416 if (fields.length >= 16) {
417 rx += fields[0];
418 tx += fields[8];
419 }
492 onPopoutOpenChanged: {
493 if (popoutOpen) {
494 refreshRare();
495 refreshSlow();
420496 }
421 let readBytes = 0;
422 let writeBytes = 0;
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)
427 continue;
429 const name = fields[2] || "";
430 if (name.indexOf("loop") === 0 || name.indexOf("ram") === 0)
431 continue;
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;
441 }
442 const now = Date.now();
443 const seconds = previousRateTime > 0 ? Math.max(0.2, (now - previousRateTime) / 1000) : 0;
444 if (seconds > 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);
449 }
450 previousNetworkRx = rx;
451 previousNetworkTx = tx;
452 previousDiskRead = readBytes;
453 previousDiskWrite = writeBytes;
454 previousRateTime = now;
455497 }
457 function refreshSystem() {
458 refreshCpu();
459 refreshMemory();
460 refreshRates();
461 refreshHistories();
462 refreshDetails();
499 Component.onCompleted: {
500 // resolve hwmon temp (coretemp package) + fan (thinkpad) paths once.
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"]);
463502 }
504 // --- FileViews: pure reads, last-good on failure (printErrors off) ---
465505 FileView {
466506 id: statFile
494534 printErrors: false
495535 }
537 FileView {
538 id: loadFile
540 path: "/proc/loadavg"
541 blockLoading: true
542 printErrors: false
543 }
545 // paths resolved at runtime by hwmonResolve; empty until then.
546 FileView {
547 id: tempFile
549 path: ""
550 blockLoading: true
551 printErrors: false
552 }
554 FileView {
555 id: fanFile
557 path: ""
558 blockLoading: true
559 printErrors: false
560 }
562 // --- one-shot hwmon path resolution ---
497563 Process {
498 id: processScan
564 id: hwmonResolve
500566 running: false
502568 stdout: StdioCollector {
503569 waitForEnd: true
504 onStreamFinished: root.applyProcessSnapshot(this.text)
570 onStreamFinished: {
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;
583 }
584 }
585 }
505586 }
507588 }
590 // --- slow-loop processes ---
509591 Process {
510 id: tempScan
592 id: failedSystemProc
512594 running: false
514596 stdout: StdioCollector {
515597 waitForEnd: true
516 onStreamFinished: root.applyTemperature(this.text)
598 onStreamFinished: {
599 root.failedSystemUnits = Sys.parseFailedUnits(this.text);
600 root.recomputeFailed();
601 }
517602 }
519604 }
521606 Process {
522 id: btmLaunch
607 id: failedUserProc
524609 running: false
611 stdout: StdioCollector {
612 waitForEnd: true
613 onStreamFinished: {
614 root.failedUserUnits = Sys.parseFailedUnits(this.text);
615 root.recomputeFailed();
616 }
617 }
525619 }
621 Process {
622 id: dfProc
624 running: false
626 stdout: StdioCollector {
627 waitForEnd: true
628 onStreamFinished: {
629 const parsed = Sys.parseDf(this.text);
630 if (parsed.length > 0)
631 root.diskUsage = parsed;
633 }
634 }
636 }
638 Process {
639 id: psProc
641 running: false
643 stdout: StdioCollector {
644 waitForEnd: true
645 onStreamFinished: {
646 const parsed = Sys.parsePsTop(this.text);
647 if (parsed.length > 0)
648 root.processes = parsed;
650 }
651 }
653 }
655 // --- rare-loop processes ---
656 Process {
657 id: identityProc
659 running: false
661 stdout: StdioCollector {
662 waitForEnd: true
663 onStreamFinished: {
664 const out = {
665 "wm": "niri"
666 };
667 const lines = String(this.text || "").split("\n");
668 for (let i = 0; i < lines.length; i++) {
669 const eq = lines[i].indexOf("=");
670 if (eq <= 0)
671 continue;
673 out[lines[i].slice(0, eq)] = lines[i].slice(eq + 1).trim();
674 }
675 if (out.host) {
676 root.identity = out;
677 root.identityLoaded = true;
678 }
679 }
680 }
682 }
684 Process {
685 id: updatesProc
687 running: false
689 stdout: StdioCollector {
690 id: updatesOut
692 waitForEnd: true
693 }
695 // checkupdates: 0 = updates listed, 2 = none, other = error / no network.
696 onExited: (exitCode, exitStatus) => {
697 if (exitCode === 2) {
698 root.updateCount = 0;
699 return ;
700 }
701 if (exitCode !== 0) {
702 root.updateCount = null;
703 return ;
704 }
705 const lines = String(updatesOut.text || "").split("\n").filter((l) => {
706 return l.trim().length > 0;
707 });
708 root.updateCount = lines.length;
709 }
710 }
712 // --- cadence timers ---
527713 Timer {
714 id: fastTimer
528716 interval: 2000
529717 repeat: true
530718 running: true
531719 triggeredOnStart: true
532 onTriggered: root.refreshSystem()
720 onTriggered: root.refreshFast()
721 }
723 Timer {
724 id: slowTimer
726 interval: 5000
727 repeat: true
728 running: root.popoutOpen
729 triggeredOnStart: true
730 onTriggered: root.refreshSlow()
731 }
733 Timer {
734 id: rareTimer
736 interval: 300000
737 repeat: true
738 running: root.popoutOpen
739 triggeredOnStart: false
740 onTriggered: root.refreshRare()
533741 }

quickshell/nuguland/SurfaceManager.qml

Modified

+5 / −2 text lines

7070 "height": heightBudget(580)
7171 };
7272 case "system":
73 // two equal cards side-by-side + issues band + top-procs row; the
74 // golden-ratio width already gives ~840px here (room for both cards),
75 // so only the height budget grows for the stacked sections.
7376 return {
7477 "width": width,
75 "height": heightBudget(520)
78 "height": heightBudget(600)
7679 };
7780 case "notifications":
7881 return {
189192 "system": {
190193 "component": "system-resources",
191194 "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"]
193196 },
194197 "notifications": {
195198 "component": "notification-history",

quickshell/nuguland/shell.qml

Modified

+13 / −12 text lines

33import Quickshell.Io
44import Quickshell.Wayland
55import Quickshell.Widgets
6import Quickshell.Services.UPower
78ShellRoot {
89 id: shell
6566 Resources {
6667 id: resources
69 // DI (never singletons inside the service): UPower/PowerProfiles singletons
70 // for battery health + throttling, and the existing Brightness instance.
71 upower: UPower
72 powerProfiles: PowerProfiles
73 brightnessService: brightness
6774 }
6976 Notifications {
625632 function refresh() : string { caldav.refresh(); return caldav.stateJson(); }
626633 }
635 IpcHandler {
636 target: "system"
637 function state() : string { return resources.stateJson(); }
638 function selfTest() : string { return resources.selfTest(); }
639 }
628641 IpcHandler {
629642 function ping() : string {
630643 return "nuguland";
704717 return surfaceManager.openRegisteredPopout("system");
705718 }
707 function resourceHeroCard(kind: string, value: real, samplesCsv: string) : string {
708 return resources.resourceHeroCard(kind, value, String(samplesCsv).split(",").map(Number));
709 }
711 function firestormState() : string {
712 return resources.firestormState();
713 }
715 function systemLaunchBtm() : string {
716 return resources.launchBtm();
717 }
719720 function notificationWidgetState(attention: bool, active: bool) : string {
720721 return notifications.widgetState(attention, active);
721722 }

quickshell/nuguland/sysinfo.js

Added
new file mode 100644

+341 / −0 text lines

1// sysinfo.js — pure parsing + issue-detection logic for the system popup.
2// NO I/O. Dual-mode: node `require` (tests) + QML import. Same pattern as caldav.js.
3
4// --- clamp a value into 0..1 ---
5function clamp01(value) {
6 var n = Number(value);
7 if (!isFinite(n)) return 0;
8 return n < 0 ? 0 : (n > 1 ? 1 : n);
9}
11// --- /proc/stat first line: idle/total delta -> {usage, next}.
12// prev is the previous {idle, total} (null/empty on first call). curLine may be
13// the whole file or just the first line; only the leading "cpu " row is used. ---
14function 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 } };
19 }
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 };
28}
30// --- /proc/meminfo (kB) -> bytes + usage ratios ---
31function parseMeminfo(text) {
32 var values = {};
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;
37 }
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);
42 return {
43 memTotal: memTotal,
44 memAvailable: memAvailable,
45 swapTotal: swapTotal,
46 swapFree: swapFree,
47 memoryUsage: memTotal > 0 ? clamp01((memTotal - memAvailable) / memTotal) : 0,
48 swapUsage: swapTotal > 0 ? clamp01((swapTotal - swapFree) / swapTotal) : 0
49 };
50}
52// --- /proc/net/dev -> {rx, tx} cumulative bytes, summed over non-lo ifaces.
53// After the colon: rx_bytes(0) ... | tx_bytes(8) ... ---
54function parseNetDev(text) {
55 var rx = 0, tx = 0;
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;
64 rx += f[0];
65 tx += f[8];
66 }
67 return { rx: rx, tx: tx };
68}
70// --- /proc/diskstats -> {readBytes, writeBytes} cumulative.
71// fields: major minor name reads(3) rmerged(4) sectorsRead(5) ... writes(7) wmerged(8) sectorsWritten(9)
72// skip loop*/ram*; bytes = sectors * 512. Sums partitions too (literal). ---
73function 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;
79 var name = p[2];
80 if (/^(loop|ram)\d*/.test(name)) continue;
81 // skip partitions (sda1, nvme0n1p1, mmcblk0p1, vda1) — their I/O is already
82 // counted in the whole-disk line; summing both ~doubles the reported rate.
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;
88 }
89 return { readBytes: readBytes, writeBytes: writeBytes };
90}
92// --- generic per-second rate from two cumulative counters. Guards counter
93// reset (negative) and non-positive intervals -> 0. ---
94function 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;
97 var d = c - p;
98 return d > 0 ? d / s : 0;
99}
101// --- /proc/loadavg -> {one, five, fifteen} ---
102function parseLoadavg(text) {
103 var p = String(text == null ? "" : text).trim().split(/\s+/);
104 return {
105 one: Number(p[0]) || 0,
106 five: Number(p[1]) || 0,
107 fifteen: Number(p[2]) || 0
108 };
109}
111// --- `df -P` (or -B1) -> [{source, target, usedPercent}].
112// header + pseudo rows whose capacity column is not a percent are skipped. ---
113function parseDf(text) {
114 var out = [];
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;
121 var capIdx = -1;
122 for (var j = 1; j < p.length; j++) {
123 if (/^\d+%$/.test(p[j])) { capIdx = j; break; }
124 }
125 if (capIdx < 0) continue; // header / no percent column
126 out.push({
127 source: p[0],
128 target: p.slice(capIdx + 1).join(" "),
129 usedPercent: parseInt(p[capIdx], 10)
130 });
131 }
132 return out;
133}
135// --- `systemctl --failed --no-legend --plain` -> [unit]. First token per line. ---
136function parseFailedUnits(text) {
137 var out = [];
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);
144 }
145 return out;
146}
148// --- `ps -eo pid,comm,%cpu,%mem` -> [{pid, name, cpu, mem}]. Header skipped
149// (non-numeric pid). ---
150function parsePsTop(text) {
151 var out = [];
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; // header row
158 out.push({ pid: pid, name: p[1], cpu: Number(p[2]) || 0, mem: Number(p[3]) || 0 });
159 }
160 return out;
161}
163// --- parse a hwmon integer text (millidegrees -> °C) ---
164function parseTemp(text) {
165 var s = String(text == null ? "" : text).trim();
166 if (s === "") return null;
167 var v = Number(s);
168 return isFinite(v) ? v / 1000 : null;
169}
171// --- parse a hwmon fan integer text (rpm) ---
172function parseFan(text) {
173 var s = String(text == null ? "" : text).trim();
174 if (s === "") return null;
175 var v = Number(s);
176 return isFinite(v) ? v : null;
177}
179// --- binary formatters (verbatim thresholds from Resources.qml for visual parity) ---
180function 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";
187}
189function formatRate(value) {
190 return formatBytes(value) + "/s";
191}
193// --- ring buffer: append value, cap to last `cap` samples. Returns a new array. ---
194function pushRing(buf, value, cap) {
195 var next = (buf || []).slice();
196 next.push(value);
197 var limit = Math.max(0, Number(cap) || 0);
198 while (next.length > limit) next.shift();
199 return next;
200}
202// --- severity ranking for sort: error < warning < info ---
203function severityRank(s) {
204 return s === "error" ? 0 : (s === "warning" ? 1 : 2);
205}
207// --- detectIssues(state) -> sorted [{id, severity, icon, label, detail, action}].
208// A check whose input is absent (null/undefined) is skipped, never fired.
209// state fields (downstream contract):
210// failedUnits: [unit] | undefined
211// cpuTemperatureC: number | null tempHighC: number (default 87)
212// degradationReason: string | null (UPower PowerProfiles)
213// diskUsage: [{source,target,usedPercent}] | undefined
214// memoryUsage: 0..1 | null swapGrowing: bool
215// healthPercentage: number | null isLaptopBattery: bool
216// loadOne: number | null cores: number
217// updateCount: number | null
218function detectIssues(state) {
219 var st = state || {};
220 var issues = [];
222 // Failed services -> error
223 if (st.failedUnits != null && st.failedUnits.length > 0) {
224 var units = st.failedUnits.slice();
225 issues.push({
226 id: "failed-services",
227 severity: "error",
228 icon: "",
229 label: units.length === 1 ? "Failed service" : (units.length + " failed services"),
230 detail: units.join(", "),
231 action: { kind: "systemctl-status", units: units }
232 });
233 }
235 // Thermal -> error if power-profile reports thermal degradation, else
236 // warning when temp >= high threshold. Skipped if no temp and no signal.
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) {
242 issues.push({
243 id: "thermal",
244 severity: degradeThermal ? "error" : "warning",
245 icon: "",
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" }
249 });
250 }
252 // Low disk -> warning >= 90, error >= 95. Worst mount per source device.
253 if (st.diskUsage != null) {
254 var worst = {};
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 };
262 }
263 }
264 var keys = Object.keys(worst);
265 for (var k = 0; k < keys.length; k++) {
266 var w = worst[keys[k]];
267 issues.push({
268 id: "low-disk:" + keys[k],
269 severity: w.usedPercent >= 95 ? "error" : "warning",
270 icon: "",
271 label: "Low disk space",
272 detail: w.target + " " + w.usedPercent + "%",
273 action: { kind: "open-mount", target: w.target }
274 });
275 }
276 }
278 // Memory pressure -> warning when mem high AND swap actively growing.
279 if (st.memoryUsage != null && Number(st.memoryUsage) >= 0.9 && st.swapGrowing === true) {
280 issues.push({
281 id: "mem-pressure",
282 severity: "warning",
283 icon: "",
284 label: "Memory pressure",
285 detail: Math.round(Number(st.memoryUsage) * 100) + "% used, swapping",
286 action: { kind: "btm" }
287 });
288 }
290 // Battery health -> warning < 80, error < 60. Skipped if absent / no battery.
291 if (st.isLaptopBattery !== false && st.healthPercentage != null) {
292 var health = Number(st.healthPercentage);
293 if (isFinite(health) && health < 80) {
294 issues.push({
295 id: "battery-health",
296 severity: health < 60 ? "error" : "warning",
297 icon: "",
298 label: "Battery wear",
299 detail: Math.round(health) + "% health",
300 action: null
301 });
302 }
303 }
305 // High load -> warning when 1-min load exceeds core count.
306 if (st.loadOne != null && Number(st.cores) > 0 && Number(st.loadOne) > Number(st.cores)) {
307 issues.push({
308 id: "high-load",
309 severity: "warning",
310 icon: "",
311 label: "High load",
312 detail: Number(st.loadOne).toFixed(2) + " on " + Number(st.cores) + " cores",
313 action: { kind: "btm" }
314 });
315 }
317 // Pending updates -> info.
318 if (st.updateCount != null && Number(st.updateCount) > 0) {
319 var count = Number(st.updateCount);
320 issues.push({
321 id: "updates",
322 severity: "info",
323 icon: "",
324 label: count === 1 ? "1 update available" : (count + " updates available"),
325 detail: "pending packages",
326 action: { kind: "update" }
327 });
328 }
330 issues.sort(function (a, b) { return severityRank(a.severity) - severityRank(b.severity); });
331 return issues;
332}
334if (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 };
341}

quickshell/nuguland/sysinfo.test.js

Added
new file mode 100644

+291 / −0 text lines

1const assert = require('assert');
2const S = require('./sysinfo.js');
3
4// ============================================================================
5// Fixtures captured from the host (2012 ThinkPad X230) via /proc, df, systemctl, ps, hwmon.
6// ============================================================================
7
8const STAT0 = 'cpu 5430899 3815162 1035595 41251079 269664 239859 55955 0 0 0\ncpu0 1 2 3 4';
9// second snapshot: +100 system, +100 idle => totalDelta 200, idleDelta 100 => usage 0.5
10const STAT1 = 'cpu 5430899 3815162 1035695 41251179 269664 239859 55955 0 0 0\ncpu0 9 9 9 9';
12const MEMINFO = [
13 'MemTotal: 16176232 kB',
14 'MemFree: 9155632 kB',
15 'MemAvailable: 12945364 kB',
16 'Buffers: 680 kB',
17 'SwapTotal: 33554428 kB',
18 'SwapFree: 26795148 kB'
19].join('\n');
21const NETDEV = [
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'
27].join('\n');
29const DISKSTATS = [
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'
34].join('\n');
36const LOADAVG = '0.76 0.64 0.56 1/714 710938';
38const DF = [
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'
44].join('\n');
46const FAILED_USER = 'app-Handy@autostart.service not-found failed failed app-Handy@autostart.service';
47const FAILED_NONE = '';
49const PS = [
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'
54].join('\n');
56// ============================================================================
57// cpuDelta — first call (no prev), steady-state delta, garbage guard
58// ============================================================================
59let cd0 = S.cpuDelta(null, STAT0);
60assert.strictEqual(cd0.usage, 0, 'first call usage 0');
61assert.strictEqual(cd0.next.idle, 41251079 + 269664, 'idle = idle + iowait');
62assert.strictEqual(cd0.next.total, 5430899 + 3815162 + 1035595 + 41251079 + 269664 + 239859 + 55955, 'total = sum');
64let cd1 = S.cpuDelta(cd0.next, STAT1);
65assert.strictEqual(cd1.usage, 0.5, 'delta 200 total / 100 non-idle => 0.5');
67let cdg = S.cpuDelta(cd0.next, 'garbage no numbers here');
68assert.strictEqual(cdg.usage, 0, 'garbage -> usage 0');
69assert.strictEqual(cdg.next, cd0.next, 'garbage keeps prev snapshot');
71// ============================================================================
72// parseMeminfo — bytes (kB*1024) + usage ratios
73// ============================================================================
74let mem = S.parseMeminfo(MEMINFO);
75assert.strictEqual(mem.memTotal, 16176232 * 1024, 'memTotal bytes');
76assert.strictEqual(mem.memAvailable, 12945364 * 1024, 'memAvailable bytes (prefers MemAvailable)');
77assert.strictEqual(mem.swapTotal, 33554428 * 1024, 'swapTotal bytes');
78assert.strictEqual(mem.swapFree, 26795148 * 1024, 'swapFree bytes');
79assert.ok(Math.abs(mem.memoryUsage - (16176232 - 12945364) / 16176232) < 1e-9, 'memoryUsage ratio');
80assert.ok(Math.abs(mem.swapUsage - (33554428 - 26795148) / 33554428) < 1e-9, 'swapUsage ratio');
81// no-swap machine -> swapUsage 0, no divide-by-zero
82assert.strictEqual(S.parseMeminfo('MemTotal: 100 kB\nMemAvailable: 50 kB').swapUsage, 0, 'no swap -> 0');
84// ============================================================================
85// parseNetDev — sum non-lo
86// ============================================================================
87let net = S.parseNetDev(NETDEV);
88assert.strictEqual(net.rx, 0 + 2445277803, 'rx sums enp0s25 + wlan0, excludes lo');
89assert.strictEqual(net.tx, 0 + 5890720566, 'tx sums enp0s25 + wlan0, excludes lo');
91// ============================================================================
92// parseDiskstats — sectors*512, skip loop/ram AND partitions (avoid double-count)
93// ============================================================================
94let disk = S.parseDiskstats(DISKSTATS);
95// whole-disk only: sda=90857, nvme0n1=15602232 ; sda1 partition + loop0 skipped
96assert.strictEqual(disk.readBytes, (90857 + 15602232) * 512, 'readBytes whole-disk sum *512');
97assert.strictEqual(disk.writeBytes, (281531 + 20543952) * 512, 'writeBytes whole-disk sum *512');
99// ============================================================================
100// rate — per-second, guards reset + bad interval
101// ============================================================================
102assert.strictEqual(S.rate(1000, 3000, 2), 1000, 'rate (3000-1000)/2');
103assert.strictEqual(S.rate(5000, 1000, 2), 0, 'counter reset -> 0');
104assert.strictEqual(S.rate(0, 100, 0), 0, 'zero interval -> 0');
106// ============================================================================
107// parseLoadavg
108// ============================================================================
109let la = S.parseLoadavg(LOADAVG);
110assert.strictEqual(la.one, 0.76);
111assert.strictEqual(la.five, 0.64);
112assert.strictEqual(la.fifteen, 0.56);
114// ============================================================================
115// parseDf — skip header, parse percent, capture source + target
116// ============================================================================
117let df = S.parseDf(DF);
118assert.strictEqual(df.length, 4, 'four real rows, header skipped');
119assert.deepStrictEqual(df[0], { source: '/dev/sda3', target: '/', usedPercent: 6 });
120assert.deepStrictEqual(df[1], { source: 'tmpfs', target: '/tmp', usedPercent: 71 });
121assert.strictEqual(df[3].target, '/home');
123// ============================================================================
124// parseFailedUnits
125// ============================================================================
126assert.deepStrictEqual(S.parseFailedUnits(FAILED_USER), ['app-Handy@autostart.service']);
127assert.deepStrictEqual(S.parseFailedUnits(FAILED_NONE), [], 'empty -> no units');
129// ============================================================================
130// parsePsTop — skip header (non-numeric pid)
131// ============================================================================
132let ps = S.parsePsTop(PS);
133assert.strictEqual(ps.length, 3, 'header dropped');
134assert.deepStrictEqual(ps[0], { pid: 710984, name: 'rtk', cpu: 77.7, mem: 0.0 });
135assert.strictEqual(ps[1].name, 'claude');
137// ============================================================================
138// parseTemp / parseFan
139// ============================================================================
140assert.strictEqual(S.parseTemp('65000'), 65, 'millidegrees -> C');
141assert.strictEqual(S.parseTemp(''), null, 'empty temp -> null');
142assert.strictEqual(S.parseFan('3816'), 3816, 'fan rpm');
143assert.strictEqual(S.parseFan(' '), null, 'empty fan -> null');
145// ============================================================================
146// formatBytes / formatRate — verbatim thresholds
147// ============================================================================
148assert.strictEqual(S.formatBytes(512), '512 B');
149assert.strictEqual(S.formatBytes(2048), '2.0 KiB');
150assert.strictEqual(S.formatBytes(5 * 1048576), '5.0 MiB');
151assert.strictEqual(S.formatBytes(3 * 1073741824), '3.0 GiB');
152assert.strictEqual(S.formatBytes(-5), '0 B', 'negative clamps');
153assert.strictEqual(S.formatRate(2048), '2.0 KiB/s');
155// ============================================================================
156// pushRing — append + cap, returns new array, original untouched
157// ============================================================================
158let r = [];
159for (let i = 1; i <= 5; i++) r = S.pushRing(r, i, 3);
160assert.deepStrictEqual(r, [3, 4, 5], 'capped to last 3');
161let orig = [1, 2];
162let r2 = S.pushRing(orig, 3, 32);
163assert.deepStrictEqual(orig, [1, 2], 'input not mutated');
164assert.deepStrictEqual(r2, [1, 2, 3], 'appended copy');
166// ============================================================================
167// detectIssues — empty all-clear, then each rule: absent / below / above
168// ============================================================================
169const CORES = 4;
170function base() {
171 // a fully-healthy state: every check present and below threshold
172 return {
173 failedUnits: [],
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,
179 updateCount: 0
180 };
181}
182function ids(state) { return S.detectIssues(state).map(function (i) { return i.id; }); }
183function find(state, id) { return S.detectIssues(state).filter(function (i) { return i.id === id; })[0]; }
185// all-clear -> [] (no synthetic ok row; that's a view concern)
186assert.deepStrictEqual(S.detectIssues(base()), [], 'healthy -> no issues');
187assert.deepStrictEqual(S.detectIssues({}), [], 'empty state -> no issues (all absent)');
189// --- Failed services (error) ---
190{
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');
197}
199// --- Thermal: absent / below 87 / >=87 warning / degradation error ---
200{
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');
211}
213// --- Low disk: absent / 89 none / 90 warn / 94 warn / 95 error ; per-source dedupe ---
214{
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');
222 // same source mounted twice over threshold -> one issue (worst)
223 let dup = base();
224 dup.diskUsage = [
225 { source: '/dev/sda3', target: '/', usedPercent: 91 },
226 { source: '/dev/sda3', target: '/home', usedPercent: 96 }
227 ];
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');
231}
233// --- Memory pressure: needs >=0.9 AND swapGrowing ---
234{
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');
243}
245// --- Battery health tiers: 80 none, 79 warn, 60 warn, 59 error, absent/no-battery skip ---
246{
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');
256}
258// --- High load: loadOne > cores (strict) ---
259{
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');
266}
268// --- Updates: 0 none, 1 info, absent (n/a) skip ---
269{
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');
276}
278// --- Sort order: error -> warning -> info ---
279{
280 let s = base();
281 s.failedUnits = ['x.service']; // error
282 s.cpuTemperatureC = 90; // warning (thermal)
283 s.updateCount = 3; // info
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');
289}
291console.log('sysinfo.test.js: ALL PASS');