Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/features/system/system-panel-reactivity.test.mjs

Raw
import assert from "node:assert/strict";
import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { assertOffscreenPass, runOffscreen } from "../../test-fixtures/offscreen.mjs";

const directory = mkdtempSync(join(tmpdir(), "nuguland-system-panel-reactivity-"));
try {
    // Shared controls at the shell root, the panel, its rows and its double in the feature directory.
    for (const file of ["Theme.qml", "nugu.json", "PopupCard.qml", "PopupButton.qml", "PopupToolTip.qml", "NuguText.qml", "PopupBadge.qml", "Util.js", "human.js"])
        copyFileSync(new URL("../../" + file, import.meta.url), join(directory, file));
    const feature = join(directory, "features", "system");
    mkdirSync(feature, { recursive: true });
    for (const file of [
        "SystemPanel.qml", "SystemIssueRow.qml", "IdentityRow.qml", "MetricRow.qml", "Sparkline.qml",
        "sysinfo.js", "system-problems.js", "resources.js"
    ])
        copyFileSync(new URL(file, import.meta.url), join(feature, file));

    copyFileSync(new URL("fixtures/services/Resources.qml", import.meta.url), join(feature, "Resources.qml"));
    // The double, deriving its issues with the production bindings and buildIssueState().
    const production = readFileSync(new URL("Resources.qml", import.meta.url), "utf8");
    function productionSource(pattern, name) {
        const match = new RegExp(pattern, "m").exec(production);
        assert(match, "missing production Resources." + name);
        return match[1] || match[0];
    }
    const binding = (name, type = "var") => productionSource("^    readonly property " + type + " " + name + ": (.+)$", name);
    writeFileSync(join(feature, "IssueResources.qml"), `import QtQuick
import "sysinfo.js" as Sys
import "system-problems.js" as Problems

Resources {
    readonly property var failedSystemUnits: failedUnits
    property var failedUserUnits: []
    property string degradationReason: ""
    failedUnits: []
    conditions: ${binding("conditions")}
    incidentGroups: ${binding("incidentGroups")}
    attention: ${binding("attention", "string")}

${productionSource("^    function buildIssueState\\(\\) \\{[\\s\\S]*?^    \\}", "buildIssueState")}
}
`);

    writeFileSync(join(directory, "shell.qml"), `import QtQuick
import QtQuick.Window
import Quickshell
import "features/system"

ShellRoot {
    id: test
    property int phase: 0
    property var panelIdentity: null
    property var row: null

    function fail(message) {
        console.error("ERROR system panel phase " + phase + ": " + message);
        Qt.quit();
    }

    function check(condition, message) {
        if (!condition)
            fail(message);
        return condition;
    }

    function tree(item) {
        let result = [item];
        for (const child of item.children || [])
            result = result.concat(tree(child));
        return result;
    }

    function effectivelyVisible(item) {
        for (let current = item; current; current = current.parent) {
            if (current.visible === false)
                return false;
        }
        return true;
    }

    function issueIds() {
        return tree(panel).filter(item => effectivelyVisible(item) && item.issue !== undefined).map(item => item.issue.id);
    }

    function issueRow(id) {
        return tree(panel).find(item => effectivelyVisible(item) && item.issue !== undefined && item.issue.id === id);
    }

    function visibleText() {
        return tree(panel).filter(item => effectivelyVisible(item) && item.text !== undefined).map(item => String(item.text));
    }

    function expectIssue(id, label, present) {
        const ids = issueIds();
        check(panel === panelIdentity, "panel was recreated");
        check(ids.includes(id) === present, (present ? "missing " : "stale ") + id + ": " + JSON.stringify(ids));
        check(visibleText().includes(label) === present, (present ? "missing visible label " : "stale visible label ") + label);
    }

    Theme { id: theme }
    IssueResources {
        id: resources
        powerProfiles: ({})
    }

    Window {
        visible: true
        width: 720
        height: 560
        SystemPanel {
            id: panel
            anchors.fill: parent
            theme: theme
            resourceService: resources
        }
    }

    // Each step checks the previous mutation, then makes the next one.
    readonly property var steps: [
        () => {
            panelIdentity = panel;
            check(issueIds().length === 0, "neutral fixture has issues");
            check(resources.attention === "", "neutral fixture asks for attention");
            resources.failedUnits = ["fixture.service"];
        },
        () => {
            expectIssue("failed-services", "fixture.service", true);
            check(resources.attention === "error", "a failed service is not an error for the bar chip");
            row = issueRow("failed-services");
            tree(row).find(item => item.text === "open failed service").forceActiveFocus();
            check(row.activeFocus || tree(row).some(item => item.activeFocus), "issue action took no focus");
            // Metrics re-derive equal issues every refresh; rows and their focus survive.
            resources.memoryUsage = 0.41;
        },
        () => {
            check(issueRow("failed-services") === row, "equal current issues rebuilt their rows");
            check(tree(row).find(item => item.text === "open failed service").activeFocus, "equal current issues dropped focus");
            resources.failedUnits = [];
        },
        () => {
            expectIssue("failed-services", "fixture.service", false);
            resources.incidents = [{ id: "fixture-incident", groupId: "fixture-incident", severity: "warning", label: "fixture process crashed", detail: "fixture", action: { kind: "journal-event" }, context: { source: "crash", timestamp: "2026-01-01T00:00:00.000Z", metadata: { comm: "fixture process", signal: "SIGSEGV", pid: "1" } } }];
        },
        () => {
            expectIssue("fixture-incident", "fixture process", true);
            check(resources.attention === "", "incident history asks for attention");
            row = issueRow("fixture-incident");
            // Every journal refresh delivers a new array with equal records.
            resources.incidents = JSON.parse(JSON.stringify(resources.incidents));
        },
        () => {
            check(issueRow("fixture-incident") === row, "equal incident history rebuilt its rows");
            resources.incidents = [];
        },
        () => {
            expectIssue("fixture-incident", "fixture process", false);
            resources.cpuTemperatureC = 90;
        },
        () => {
            expectIssue("thermal", "cpu running hot", true);
            check(resources.attention === "warning", "a hot cpu is not a warning for the bar chip");
            resources.cpuTemperatureC = 52;
        },
        () => {
            expectIssue("thermal", "cpu running hot", false);
            resources.diskUsage = [{ source: "/dev/fixture", target: "/", usedPercent: 91 }];
        },
        () => {
            expectIssue("low-disk:/dev/fixture", "low disk space", true);
            resources.diskUsage = [];
        },
        () => {
            expectIssue("low-disk:/dev/fixture", "low disk space", false);
            resources.updateCount = 2;
        },
        () => {
            expectIssue("updates", "2 updates available", true);
            check(resources.attention === "", "available updates ask for attention");
            // Same id, new content: the row shows it; whether the row is reused is not the contract.
            resources.updateCount = 3;
        },
        () => {
            expectIssue("updates", "3 updates available", true);
            check(!visibleText().includes("2 updates available"), "stale updates label");
            resources.updateCount = 0;
        },
        () => {
            expectIssue("updates", "2 updates available", false);
            resources.memoryUsage = 0.91;
        },
        () => {
            expectIssue("mem-pressure", "memory pressure", false);
            resources.swapGrowing = true;
        },
        () => {
            expectIssue("mem-pressure", "memory pressure", true);
            resources.memoryUsage = 0.4;
        },
        () => {
            expectIssue("mem-pressure", "memory pressure", false);
            resources.memoryUsage = 0.91;
        },
        () => {
            expectIssue("mem-pressure", "memory pressure", true);
            resources.swapGrowing = false;
        },
        () => {
            expectIssue("mem-pressure", "memory pressure", false);
            resources.healthPercentage = 70;
        },
        () => {
            expectIssue("battery-health", "battery wear", true);
            resources.healthPercentage = 95;
        },
        () => {
            expectIssue("battery-health", "battery wear", false);
            resources.loadOne = 5;
        },
        () => {
            expectIssue("high-load", "high load", true);
            resources.loadOne = 0.5;
        },
        () => expectIssue("high-load", "high load", false)
    ]

    Timer {
        interval: 25
        running: true
        repeat: true
        onTriggered: {
            if (phase < steps.length) {
                steps[phase]();
            } else {
                console.log("system panel reactivity qml: PASS");
                Qt.quit();
            }
            phase++;
        }
    }

    Timer {
        interval: 5000
        running: true
        onTriggered: test.fail("deadline")
    }
}
`);

    const run = runOffscreen(join(directory, "shell.qml"), { directory, cwd: directory, timeout: 10000 });
    assertOffscreenPass(run, /system panel reactivity qml: PASS/);
    console.log(run.output.trim());
    console.log("system-panel-reactivity.test.mjs: PASS (offscreen actual panel reactivity; not pointer, keyboard, or pixel proof)");
} finally {
    rmSync(directory, { recursive: true, force: true });
}