repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by admin
quickshell/nuguland/features/system/Resources.qml
Rawimport QtQuick
import Quickshell
import Quickshell.Io
import "sysinfo.js" as Sys
import "resources.js" as Res
import "system-problems.js" as Problems
// Thin I/O + cadence service over the pure sysinfo.js core.
// All parsing / issue-detection logic lives in sysinfo.js; this file only does
// file reads, process spawns, timers, and exposes reactive properties.
Item {
id: root
// --- injected services (DI via shell.qml; never singletons here) ---
required property var powerProfiles // PowerProfiles singleton (degradationReason)
// --- view-bound live properties (fast loop) ---
// Open-popup refresh cadence; isolated fixtures shorten it, production keeps 5 s.
property int slowRefreshMs: 5000
// Shown-sample cadence; isolated fixtures shorten it, production keeps 2 s.
property int liveSampleMs: 2000
// Closed cadences: cheap /proc and /sys reads for the backdrop and the bar chip,
// and the failed-service and disk check behind the chip's attention.
property int closedSampleMs: 10000
property int closedCheckMs: 60000
// Another surface shows the network rates (the connectivity panel): sample
// at the open cadence, without history.
property bool liveRates: false
property real cpuUsage: 0
property real memoryUsage: 0
property real swapUsage: 0
property real memTotal: 0
property real memAvailable: 0
property real swapTotal: 0
property real swapFree: 0
property real networkRxRate: 0
property real networkTxRate: 0
property real diskReadRate: 0
property real diskWriteRate: 0
// nullable: no sensor -> null (view shows n/a, thermal check skipped)
property var cpuTemperatureC: null
property var fanRpm: null
property real loadOne: 0
property real loadFive: 0
property real loadFifteen: 0
property int cores: 1
// --- ring buffers for sparklines, filled only while the popup is open and
// restarted on each opening (cap = samples the widest spark shows;
// 160 × 2s ≈ 5 min of history) ---
readonly property int ringCap: 160
property var cpuRing: []
property var memRing: []
property var tempRing: []
property var netRxRing: [] // download, for the directional net spark
property var netTxRing: [] // upload, for the directional net spark
property var diskReadRing: [] // read, for the directional disk spark
property var diskWriteRing: [] // write, for the directional disk spark
// --- issue inputs (slow / rare loops) ---
property var failedUnits: []
property var incidents: []
property string incidentStatus: "not checked"
property string agentIssueId: ""
property string agentError: ""
property var pendingAgent: ({})
signal agentDispatched
property bool agentPromptLoading: false
readonly property bool agentPending: agentPromptLoading || agentCheck.running
property var diskUsage: [] // [{source,target,usedPercent}]
property var updateCount: null // null = unknown / n/a
property bool swapGrowing: false
// thermal high threshold; resolved from sensor max/crit on start, default 87
property real tempHighC: 87
// aurora "firestorm" intensity, consumed by AuroraBackdrop.qml. A continuous
// 0..1 ramp as CPU temp climbs the last 12°C toward the thermal threshold —
// replaces the old hot/cool hysteresis counters. null temp => 0 (calm).
readonly property real firestormTarget: {
if (cpuTemperatureC === null || cpuTemperatureC === undefined)
return 0;
const t = Number(cpuTemperatureC);
if (!isFinite(t))
return 0;
const high = Math.max(1, tempHighC);
const cool = high - 12;
return Math.max(0, Math.min(1, (t - cool) / (high - cool)));
}
// --- top processes (slow loop, only while popup open) ---
property var processes: []
// --- identity facts (rare loop, cached) ---
property var identity: ({})
property bool identityLoaded: false
// --- popup lifecycle gate (set by the registry entry) ---
property bool popupOpen: false
// Power owns native battery shaping; the registry forwards these issue inputs.
// Null health / charge skips battery checks on desktops and unsupported devices.
property var healthPercentage: null
property bool isLaptopBattery: false
property var batteryPercent: null
property string batteryStatus: ""
readonly property var degradationReason: {
if (!powerProfiles)
return null;
const r = powerProfiles.degradationReason;
return (r === null || r === undefined) ? null : String(r);
}
// --- last issue action record (for IPC introspection) ---
property var lastAction: ({})
// --- internal delta state ---
property var prevCpu: null
property real prevNetRx: 0
property real prevNetTx: 0
property real prevDiskRead: 0
property real prevDiskWrite: 0
property real prevRateTime: 0
property real prevSwapUsed: 0
property var failedSystemUnits: []
property var failedUserUnits: []
// --- sample loop: pure /proc + /sys reads and deltas; every 2 s while shown,
// every 10 s while only the backdrop and bar chip read them; rings only while open ---
function refreshFast() {
statFile.reload();
const statText = statFile.text() || "";
const cd = Sys.cpuDelta(prevCpu, statText);
cpuUsage = cd.usage;
prevCpu = cd.next;
const coreLines = statText.match(/^cpu[0-9]/gm);
if (coreLines && coreLines.length > 0)
cores = coreLines.length;
meminfoFile.reload();
const mem = Sys.parseMeminfo(meminfoFile.text() || "");
if (mem.memTotal > 0) {
memTotal = mem.memTotal;
memAvailable = mem.memAvailable;
swapTotal = mem.swapTotal;
swapFree = mem.swapFree;
memoryUsage = mem.memoryUsage;
swapUsage = mem.swapUsage;
const swapUsed = Math.max(0, mem.swapTotal - mem.swapFree);
swapGrowing = swapUsed > prevSwapUsed + 1;
prevSwapUsed = swapUsed;
}
netFile.reload();
diskFile.reload();
const net = Sys.parseNetDev(netFile.text() || "");
const disk = Sys.parseDiskstats(diskFile.text() || "");
const now = Date.now();
const seconds = prevRateTime > 0 ? Math.max(0.2, (now - prevRateTime) / 1000) : 0;
if (seconds > 0) {
networkRxRate = Sys.rate(prevNetRx, net.rx, seconds);
networkTxRate = Sys.rate(prevNetTx, net.tx, seconds);
diskReadRate = Sys.rate(prevDiskRead, disk.readBytes, seconds);
diskWriteRate = Sys.rate(prevDiskWrite, disk.writeBytes, seconds);
}
prevNetRx = net.rx;
prevNetTx = net.tx;
prevDiskRead = disk.readBytes;
prevDiskWrite = disk.writeBytes;
prevRateTime = now;
loadFile.reload();
const loadText = loadFile.text() || "";
if (loadText.trim().length > 0) {
const la = Sys.parseLoadavg(loadText);
loadOne = la.one;
loadFive = la.five;
loadFifteen = la.fifteen;
}
// hwmon temp + fan; keep last-good on null/parse failure
if (tempFile.path) {
tempFile.reload();
const t = Sys.parseTemp(tempFile.text() || "");
if (t !== null)
cpuTemperatureC = t;
}
if (fanFile.path) {
fanFile.reload();
const f = Sys.parseFan(fanFile.text() || "");
if (f !== null)
fanRpm = f;
}
if (!popupOpen)
return;
cpuRing = Sys.pushRing(cpuRing, cpuUsage, ringCap);
memRing = Sys.pushRing(memRing, memoryUsage, ringCap);
if (cpuTemperatureC !== null)
tempRing = Sys.pushRing(tempRing, cpuTemperatureC, ringCap);
netRxRing = Sys.pushRing(netRxRing, networkRxRate, ringCap);
netTxRing = Sys.pushRing(netTxRing, networkTxRate, ringCap);
diskReadRing = Sys.pushRing(diskReadRing, diskReadRate, ringCap);
diskWriteRing = Sys.pushRing(diskWriteRing, diskWriteRate, ringCap);
}
// --- check loop: process spawns; failed services and disk use every 5 s while
// open and every minute while closed, for the bar chip; journal and top
// processes only while open ---
function refreshSlow() {
if (!failedSystemProc.running)
failedSystemProc.exec(["systemctl", "--failed", "--no-legend", "--plain"]);
if (!failedUserProc.running)
failedUserProc.exec(["systemctl", "--user", "--failed", "--no-legend", "--plain"]);
if (!dfProc.running)
dfProc.exec(["df", "-P"]);
if (!popupOpen)
return;
if (!incidentProc.running)
incidentProc.exec(Problems.journalCommand());
if (!psProc.running)
psProc.exec(["sh", "-c", "ps -eo pid=,comm=,pcpu=,pmem= --sort=-pcpu | head -n 5"]);
}
// --- rare loop: identity facts (cached) + checkupdates (async, on open) ---
function refreshRare() {
if (!identityLoaded && !identityProc.running)
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)\""]);
if (!updatesProc.running)
updatesProc.exec(["checkupdates"]);
}
function recomputeFailed() {
failedUnits = failedSystemUnits.concat(failedUserUnits);
}
// --- assemble detectIssues input (keys MUST match the sysinfo.js contract) ---
function buildIssueState() {
return {
"failedUnits": failedUnits,
"failedScopes": [
{
scope: "system",
units: failedSystemUnits
},
{
scope: "user",
units: failedUserUnits
}
],
"cpuTemperatureC": cpuTemperatureC,
"tempHighC": tempHighC,
"degradationReason": degradationReason,
"diskUsage": diskUsage,
"memoryUsage": memoryUsage,
"swapGrowing": swapGrowing,
"healthPercentage": healthPercentage,
"isLaptopBattery": isLaptopBattery,
"loadOne": loadOne,
"cores": cores,
"updateCount": updateCount
};
}
// Current conditions, re-derived when a metric they read changes.
readonly property var conditions: Sys.detectIssues(buildIssueState())
// The bar chip's emphasis: "error", "warning", or "" for none.
readonly property string attention: Sys.attention(conditions)
// Journal history, regrouped only when a journal refresh lands.
readonly property var incidentGroups: Problems.groupIncidents(incidents)
function issues() {
return conditions.concat(incidentGroups);
}
// The panel's retry after unreadable history: read the journal again now,
// pending until the result lands.
function retryIncidents(): void {
incidentStatus = "not checked";
if (!incidentProc.running)
incidentProc.exec(Problems.journalCommand());
}
// click-to-act: pure planner decides argv; QML only launches.
function runIssueAction(id) {
const result = Res.issueAction(issues(), id);
if (!result.ok)
return JSON.stringify(result);
lastAction = result;
Quickshell.execDetached(result.argv);
return JSON.stringify(lastAction);
}
function runIssueAgent(id) {
if (agentPending)
return;
const issue = issues().find(entry => entry.id === String(id));
if (!Res.agentAllowed(issue))
return;
agentIssueId = String(id);
agentError = "";
agentPromptLoading = true;
repairPrompt.reload();
}
function prepareIssueAgent(template: string): void {
const plan = Res.agentAction(issues(), agentIssueId, {
home: Quickshell.env("HOME"),
stateHome: Quickshell.env("XDG_STATE_HOME"),
observedAt: new Date().toISOString(),
identity: identity
}, template);
agentPromptLoading = false;
if (!plan.ok) {
agentError = plan.reason === "prompt-invalid" ? "repair prompt unavailable or invalid" : plan.reason === "home-unavailable" ? "home directory unavailable" : "issue no longer eligible";
return;
}
pendingAgent = plan;
// Fixed script only; no issue text ever enters shell syntax.
// File transport preserves all retained occurrences without Linux's
// per-argument size limit. Requests are private, immutable repair evidence.
agentCheck.stdinEnabled = true;
agentCheck.exec(["sh", "-c", "command -v pi || { cat >/dev/null; exit 75; }; command -v wezterm || { cat >/dev/null; exit 76; }; umask 077; mkdir -p -- \"$1\" && test -d \"$1\" && test -w \"$1\" && test -x \"$1\" || { cat >/dev/null; exit 73; }; request=$(mktemp -- \"$1/.request-XXXXXX.md\") || { cat >/dev/null; exit 74; }; cat >\"$request\" || { rm -- \"$request\"; exit 74; }; printf '%s\\n' \"${request##*/}\"", "nuguland-repairs", plan.argv[3]]);
}
// --- IPC and diagnostics contract ---
function stateJson() {
const memUsed = Math.max(0, memTotal - memAvailable);
const swapUsed = Math.max(0, swapTotal - swapFree);
return JSON.stringify({
"kind": "system",
"title": "system",
"popupOpen": popupOpen,
"cpu": {
"usage": cpuUsage,
"percent": Math.round(cpuUsage * 100)
},
"memory": {
"usage": memoryUsage,
"percent": Math.round(memoryUsage * 100),
"used": memUsed,
"total": memTotal,
"label": `${Sys.formatBytes(memUsed)} / ${Sys.formatBytes(memTotal)}`
},
"swap": {
"usage": swapUsage,
"percent": Math.round(swapUsage * 100),
"used": swapUsed,
"total": swapTotal,
"label": swapTotal > 0 ? `${Sys.formatBytes(swapUsed)} / ${Sys.formatBytes(swapTotal)}` : "off"
},
"network": {
"rxRate": networkRxRate,
"txRate": networkTxRate,
"label": `↓ ${Sys.formatRate(networkRxRate)} ↑ ${Sys.formatRate(networkTxRate)}`
},
"disk": {
"readRate": diskReadRate,
"writeRate": diskWriteRate,
"label": `R ${Sys.formatRate(diskReadRate)} W ${Sys.formatRate(diskWriteRate)}`
},
"temperature": {
"celsius": cpuTemperatureC,
"highThresholdC": tempHighC,
"label": cpuTemperatureC !== null ? `${Math.round(Number(cpuTemperatureC))}°C` : "n/a"
},
"fan": {
"rpm": fanRpm,
"label": fanRpm !== null ? `${Math.round(Number(fanRpm))} rpm` : "n/a"
},
"load": {
"one": loadOne,
"five": loadFive,
"fifteen": loadFifteen,
"cores": cores
},
"battery": {
"percent": batteryPercent,
"status": batteryStatus,
"healthPercentage": healthPercentage,
"isLaptopBattery": isLaptopBattery
},
"identity": identity,
"updateCount": updateCount,
"processes": processes,
"issues": issues(),
"lastAction": lastAction
});
}
Component.onCompleted: {
// resolve hwmon temp (coretemp package) + fan (thinkpad) paths once.
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"]);
}
// --- FileViews: pure reads, last-good on failure (printErrors off) ---
FileView {
id: statFile
path: "/proc/stat"
blockLoading: true
printErrors: false
}
FileView {
id: meminfoFile
path: "/proc/meminfo"
blockLoading: true
printErrors: false
}
FileView {
id: netFile
path: "/proc/net/dev"
blockLoading: true
printErrors: false
}
FileView {
id: diskFile
path: "/proc/diskstats"
blockLoading: true
printErrors: false
}
FileView {
id: loadFile
path: "/proc/loadavg"
blockLoading: true
printErrors: false
}
// paths resolved at runtime by hwmonResolve; empty until then.
FileView {
id: tempFile
path: ""
blockLoading: true
printErrors: false
}
FileView {
id: fanFile
path: ""
blockLoading: true
printErrors: false
}
// --- one-shot hwmon path resolution ---
Process {
id: hwmonResolve
running: false
stdout: StdioCollector {
waitForEnd: true
onStreamFinished: {
const lines = String(this.text || "").split("\n");
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (line.indexOf("temp=") === 0)
tempFile.path = line.slice(5);
else if (line.indexOf("fan=") === 0)
fanFile.path = line.slice(4);
else if (line.indexOf("high=") === 0) {
const v = Number(line.slice(5));
if (Number.isFinite(v) && v > 0)
root.tempHighC = v / 1000;
}
}
}
}
}
FileView {
id: repairPrompt
path: Qt.resolvedUrl("prompts/system-repair.md")
printErrors: false
onLoaded: if (root.agentPromptLoading)
root.prepareIssueAgent(repairPrompt.text())
onLoadFailed: {
if (root.agentPromptLoading) {
root.agentPromptLoading = false;
root.agentError = "repair prompt unavailable or invalid";
}
}
}
Process {
id: agentCheck
stdout: StdioCollector {
id: agentPaths
waitForEnd: true
}
function handleExit(exitCode: int): void {
const paths = String(agentPaths.text).trim().split("\n");
if (exitCode === 73) {
root.agentError = "repair directory unavailable or not writable";
return;
}
if (exitCode === 74) {
root.agentError = "repair context could not be saved";
return;
}
// A missing tool is named with its fix; the arrrgh button beside it retries.
if (exitCode === 75 || exitCode === 76) {
const tool = exitCode === 75 ? "pi" : "wezterm";
root.agentError = `${tool} not found · install ${tool} or add it to the session path, then retry`;
return;
}
if (exitCode !== 0 || paths.length !== 3 || paths[0][0] !== "/" || paths[1][0] !== "/" || !/^\.request-[A-Za-z0-9]+\.md$/.test(paths[2])) {
root.agentError = "repair launch check failed · retry";
return;
}
const argv = root.pendingAgent.argv.slice();
argv[0] = paths[1];
argv[5] = paths[0];
argv[argv.length - 1] = "@" + argv[3] + "/" + paths[2];
root.lastAction = {
id: root.pendingAgent.id,
kind: "agent",
status: "dispatched"
};
Quickshell.execDetached(argv);
root.pendingAgent = ({});
root.agentDispatched();
}
}
// --- slow-loop processes ---
Process {
id: incidentProc
stdout: StdioCollector {
id: incidentOut
waitForEnd: true
}
stderr: StdioCollector {
id: incidentErr
waitForEnd: true
}
function handleExit(exitCode: int): void {
// No-match with --grep exits 1. Diagnostics mean incomplete visibility.
const parsed = Problems.parseJournal(incidentOut.text);
const empty = !String(incidentOut.text).trim();
if ((exitCode === 0 || (exitCode === 1 && empty)) && !String(incidentErr.text).trim() && parsed.ok) {
root.incidents = parsed.issues;
root.incidentStatus = "ready";
} else {
root.incidentStatus = "history unavailable or incomplete";
}
}
}
Process {
id: failedSystemProc
running: false
stdout: StdioCollector {
id: failedSystemOut
waitForEnd: true
}
function handleExit(exitCode: int): void {
if (exitCode === 0) {
root.failedSystemUnits = Sys.parseFailedUnits(failedSystemOut.text);
root.recomputeFailed();
}
}
}
Process {
id: failedUserProc
running: false
stdout: StdioCollector {
id: failedUserOut
waitForEnd: true
}
function handleExit(exitCode: int): void {
if (exitCode === 0) {
root.failedUserUnits = Sys.parseFailedUnits(failedUserOut.text);
root.recomputeFailed();
}
}
}
Process {
id: dfProc
running: false
stdout: StdioCollector {
waitForEnd: true
onStreamFinished: {
const parsed = Sys.parseDf(this.text);
if (parsed.length > 0)
root.diskUsage = parsed;
}
}
}
Process {
id: psProc
running: false
stdout: StdioCollector {
waitForEnd: true
onStreamFinished: {
const parsed = Sys.parsePsTop(this.text);
if (parsed.length > 0)
root.processes = parsed;
}
}
}
// --- rare-loop processes ---
Process {
id: identityProc
running: false
stdout: StdioCollector {
waitForEnd: true
onStreamFinished: {
const out = {
"wm": "niri"
};
const lines = String(this.text || "").split("\n");
for (let i = 0; i < lines.length; i++) {
const eq = lines[i].indexOf("=");
if (eq <= 0)
continue;
out[lines[i].slice(0, eq)] = lines[i].slice(eq + 1).trim();
}
if (out.host) {
root.identity = out;
root.identityLoaded = true;
}
}
}
}
Process {
id: updatesProc
running: false
stdout: StdioCollector {
id: updatesOut
waitForEnd: true
}
// checkupdates: 0 = updates listed, 2 = none, other = error / no network.
function handleExit(exitCode: int): void {
if (exitCode === 2) {
root.updateCount = 0;
return;
}
if (exitCode !== 0) {
root.updateCount = null;
return;
}
const lines = String(updatesOut.text || "").split("\n").filter(l => {
return l.trim().length > 0;
});
root.updateCount = lines.length;
}
}
// Explicit Connections register real handlers without requiring the missing
// QProcess::ExitStatus enum in Quickshell's installed qmltypes metadata.
Connections {
target: agentCheck
function onStarted(): void {
const argv = root.pendingAgent.argv;
agentCheck.write(argv[argv.length - 1]);
agentCheck.stdinEnabled = false;
}
function onExited(exitCode: int): void {
agentCheck.handleExit(exitCode);
}
}
Connections {
target: incidentProc
function onExited(exitCode: int): void {
incidentProc.handleExit(exitCode);
}
}
Connections {
target: failedSystemProc
function onExited(exitCode: int): void {
failedSystemProc.handleExit(exitCode);
}
}
Connections {
target: failedUserProc
function onExited(exitCode: int): void {
failedUserProc.handleExit(exitCode);
}
}
Connections {
target: updatesProc
function onExited(exitCode: int): void {
updatesProc.handleExit(exitCode);
}
}
// --- cadence timers ---
// A changed interval restarts a running timer without triggering it;
// opening samples at once and restarts the sparkline history.
onPopupOpenChanged: {
if (!popupOpen)
return;
cpuRing = [];
memRing = [];
tempRing = [];
netRxRing = [];
netTxRing = [];
diskReadRing = [];
diskWriteRing = [];
refreshFast();
refreshSlow();
}
onLiveRatesChanged: if (liveRates)
refreshFast()
Timer {
id: fastTimer
interval: root.popupOpen || root.liveRates ? root.liveSampleMs : root.closedSampleMs
repeat: true
running: true
triggeredOnStart: true
onTriggered: root.refreshFast()
}
Timer {
id: slowTimer
interval: root.popupOpen ? root.slowRefreshMs : root.closedCheckMs
repeat: true
running: true
triggeredOnStart: true
onTriggered: root.refreshSlow()
}
Timer {
id: rareTimer
interval: 300000
repeat: true
running: root.popupOpen
triggeredOnStart: true
onTriggered: root.refreshRare()
}
}