Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/features/brightness/brightness-runtime.test.mjs

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

// Production QML lifecycle with real, harmless subprocesses. Only native command
// construction and typed service dependencies are substituted in the temp copy.
// No compositor input, package transaction, polkit registration or device I/O.
const directory = mkdtempSync(join(tmpdir(), "nuguland-brightness-runtime-"));
try {
    const source = readFileSync(new URL("Brightness.qml", import.meta.url), "utf8");
    let fixture = source;
    for (const [from, to] of [
        ["    property Osd osdService", "    property var fixtureCommand\n    property Osd osdService"],
        ["setupProcess.command = command;", "setupProcess.command = fixtureCommand(kind, command);"],
        ["writeProcess.command = command;", "writeProcess.command = fixtureCommand(\"write\");"],
        ["interval: 370000", "interval: 40"]
    ]) {
        // Fail closed before launching QML if a production seam ever changes.
        assert.equal(fixture.split(from).length, 2, "missing or ambiguous fixture substitution: " + from);
        fixture = fixture.replace(from, to);
    }
    // The feature keeps its directory; root types (Niri, Privilege) and the OSD are stubs.
    const feature = join(directory, "features", "brightness");
    mkdirSync(feature, { recursive: true });
    writeFileSync(join(feature, "Brightness.qml"), fixture);
    for (const file of ["brightness.js", "adaptive-brightness.js", "AmbientLight.qml"])
        writeFileSync(join(feature, file), readFileSync(new URL(file, import.meta.url)));
    mkdirSync(join(directory, "features", "osd"), { recursive: true });
    writeFileSync(join(directory, "features", "osd", "Osd.qml"), `import QtQuick
Item { function trigger(event, value) { return {event: event, value: value}; } }
`);
    writeFileSync(join(directory, "Niri.qml"), `import QtQuick
Item { function outputList() { return [{name: "DP-1"}, {name: "DP-2"}]; } }
`);
    writeFileSync(join(directory, "Privilege.qml"), `import QtQuick
Item { property var polkitAgent: ({isRegistered: true, isActive: false}) }
`);
    writeFileSync(join(directory, "shell.qml"), `import QtQuick
import Quickshell
import "features/brightness"
import "features/osd"
ShellRoot {
    id: test
    property int phase: 0
    property bool installed: false
    property bool secondDetected: false
    property bool writeSucceeds: false
    property bool activationFails: false
    property bool moduleReady: true
    property bool readFails: false
    property int authorizations: 0
    property int preflights: 0
    property bool lastInstallRequested: false
    function check(ok, message) {
        if (!ok) { console.error("brightness runtime phase " + phase + ": " + message); Qt.quit(); }
    }
    function command(kind, nativeCommand) {
        let script = "";
        if (kind === "preflight" || kind === "refresh" || kind === "retry-preflight") {
            preflights++;
        }
        if (kind === "preflight" || kind === "refresh" || kind === "retry-preflight")
            script = "printf 'package=" + (installed ? "yes" : "no") + "\\nmodule=" + (moduleReady ? "yes" : "no") + "\\nconnector=DP-1,1,yes\\nconnector=DP-2,2,yes\\n'";
        else if (kind === "privileged") {
            authorizations++;
            lastInstallRequested = nativeCommand.join(" ").indexOf("pacman -S") >= 0;
            script = "sleep 0.2; printf 'nugu:authorized\\n'; read -r consent; test \\\"$consent\\\" = continue || exit 1; printf 'stub:installation\\n'";
            if (phase === 6) script += "; sleep 0.3";
            if (activationFails) script += "; exit 1";
            if (phase === 9) moduleReady = true;
        }
        else if (kind === "detect")
            script = "printf 'Display 1\\n I2C bus: /dev/i2c-7\\n DRM_connector: card1-DP-1\\n" + (secondDetected ? "Display 2\\n I2C bus: /dev/i2c-8\\n DRM_connector: card1-DP-2\\n" : "") + "'";
        else if (kind === "read")
            script = readFails && nativeCommand.indexOf("8") >= 0 ? "exit 1" : "printf 'VCP 10 C 40 100\\n'";
        else if (kind === "write")
            script = writeSucceeds ? "exit 0" : "exit 1";
        return ["/usr/bin/timeout", "--kill-after=1s", "3s", "/usr/bin/sh", "-c", script];
    }
    Niri { id: niri }
    Privilege { id: privilege }
    Osd { id: osd }
    Brightness {
        id: brightness
        devicePath: "${directory}/no-device"
        niriService: niri
        privilegeService: privilege
        osdService: osd
        fixtureCommand: (kind, command) => test.command(kind, command)
    }
    Component.onCompleted: brightness.setupDdc()
    Timer {
        interval: 10
        running: true
        repeat: true
        onTriggered: {
            if (test.phase === 0 && brightness.operation === "privileged") {
                brightness.cancelSetup();
                test.phase = 1;
            } else if (test.phase === 1 && !brightness.setupRunning) {
                test.check(brightness.setupError === "cancelled", "cancel diagnosis");
                test.check(brightness.operationOutput.indexOf("stub:installation") < 0, "cancelled setup installed");
                test.installed = true;
                brightness.retrySetup();
                test.phase = 2;
            } else if (test.phase === 2 && !brightness.setupRunning) {
                test.check(brightness.setupError === "some displays unavailable", "partial verification");
                test.check(brightness.ddcDisplays["DP-1"].controllable, "partial success lost");
                test.secondDetected = true;
                brightness.retrySetup();
                test.phase = 3;
            } else if (test.phase === 3 && !brightness.setupRunning) {
                test.check(brightness.setupReady && !brightness.setupExpanded, "ready collapse");
                brightness.lastOsd = ({value: "40"});
                brightness.setDisplay("ddc:DP-2", 0.75);
                test.phase = 4;
            } else if (test.phase === 4 && !brightness.writePending) {
                test.check(brightness.ddcDisplays["DP-2"].level === 0.4, "failed write changed value");
                test.check(brightness.ddcDisplays["DP-2"].error === "write failed", "missing inline error");
                test.check(brightness.lastOsd.value === "40", "failed write emitted osd");
                test.writeSucceeds = true;
                brightness.setDisplay("ddc:DP-2", 0.75);
                test.phase = 5;
            } else if (test.phase === 5 && !brightness.writePending) {
                test.check(brightness.ddcDisplays["DP-2"].level === 0.75, "successful write value");
                test.check(brightness.lastOsd.value === "75", "successful write osd");
                test.installed = false;
                test.phase = 6;
                brightness.setupDdc();
            } else if (test.phase === 6 && brightness.setupError === "timeout") {
                test.check(brightness.setupRunning && brightness.operationPending, "deadline released running child");
                test.check(brightness.setupStages.find(stage => stage.id === "installation").status === "failed", "deadline not visible");
                test.phase = 7;
            } else if (test.phase === 7 && !brightness.setupRunning) {
                test.check(brightness.setupError === "timeout", "deadline diagnosis overwritten on exit");
                test.phase = 8;
                test.activationFails = true;
                brightness.setupDdc();
            } else if (test.phase === 8 && !brightness.setupRunning) {
                test.check(test.lastInstallRequested, "initial installation missing");
                test.check(brightness.setupStage === "installation", "activation failure stage");
                // Pacman succeeded, activation failed: actual package now exists.
                test.installed = true;
                test.moduleReady = false;
                test.activationFails = false;
                test.phase = 9;
                brightness.retrySetup();
                test.check(brightness.operation === "retry-preflight", "retry skipped fresh prerequisites");
            } else if (test.phase === 9 && !brightness.setupRunning) {
                test.check(test.authorizations === 4, "incomplete session activation skipped authorization");
                test.check(!test.lastInstallRequested, "retained package requested installation again");
                test.check(brightness.setupReady, "retained package retry not ready");
                test.readFails = true;
                brightness.ddcDisplays = ({});
                test.phase = 10;
                brightness.setupDdc();
            } else if (test.phase === 10 && !brightness.setupRunning) {
                test.check(brightness.setupStage === "reading", "failed read blamed verification");
                test.check(brightness.setupStages.find(stage => stage.id === "reading").status === "failed", "reading falsely completed");
                test.check(brightness.setupStages.find(stage => stage.id === "verification").status === "waiting", "verification ran after read failure");
                test.check(brightness.ddcDisplays["DP-1"].controllable, "working display lost on read failure");
                test.check(!brightness.ddcDisplays["DP-2"].controllable, "failed display enabled");
                test.readFails = false;
                test.phase = 11;
                brightness.retrySetup();
            } else if (test.phase === 11 && !brightness.setupRunning) {
                test.check(brightness.setupReady && brightness.ddcDisplays["DP-1"].controllable && brightness.ddcDisplays["DP-2"].controllable, "read retry recovery");
                console.log("brightness runtime: PASS");
                Qt.quit();
            }
        }
    }
    Timer { interval: 8000; running: true; onTriggered: { console.error("brightness runtime deadline phase " + test.phase); Qt.quit(); } }
}
`);
    const run = runOffscreen(join(directory, "shell.qml"), { directory, timeout: 12000 });
    assertOffscreenPass(run, /brightness runtime: PASS/);
    console.log(run.output.trim());
    console.log("brightness-runtime.test.mjs: PASS (stubbed native boundaries; not polkit or UI proof)");
} finally {
    rmSync(directory, { recursive: true, force: true });
}