repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by admin
quickshell/nuguland/features/brightness/adaptive-brightness-runtime.test.mjs
Rawimport 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 service, offscreen. Typed dependencies are explicit doubles;
// only command construction is replaced. No sensor, compositor or hardware I/O.
const directory = mkdtempSync(join(tmpdir(), "nuguland-adaptive-runtime-"));
try {
let source = readFileSync(new URL("Brightness.qml", import.meta.url), "utf8");
for (const [from, to] of [
[" property Osd osdService", " property var fixtureCommand\n property Osd osdService"],
["setupProcess.command = command;", "setupProcess.command = fixtureCommand();"],
["writeProcess.command = command;", "writeProcess.command = fixtureCommand();"],
["id: adaptiveTransitionTimer\n interval: 100", "id: adaptiveTransitionTimer\n interval: 5"]
]) {
assert.equal(source.split(from).length, 2, "fixture seam: " + from);
source = source.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"), source);
for (const file of ["brightness.js", "adaptive-brightness.js"])
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 { property var rows: [{name: "DP-1"}, {name: "DP-2"}]; function outputList() { return rows; } }`);
writeFileSync(join(directory, "Privilege.qml"), `import QtQuick
Item { property var polkitAgent: ({isRegistered: true, isActive: false}) }`);
writeFileSync(join(feature, "AmbientLight.qml"), `import QtQuick
Item {
property bool found: false
property bool busy: false
property string status: "idle"
property string readAt: ""
property real rawCount: -1
property string errorCode: ""
property string restorationStatus: "verified"
property string restoreError: ""
property string verificationError: ""
property string cleanupError: ""
property var effectiveSettings: ({channel: "white", frequencyPercent: 20, integrationTime: 100})
property int reads: 0
signal sampleFinished()
function requestRead() { reads++; busy = true; }
function sample(raw) { rawCount = raw; status = "ready"; readAt = new Date().toISOString(); busy = false; sampleFinished(); }
}`);
mkdirSync(join(directory, "backlight"));
writeFileSync(join(directory, "backlight", "max_brightness"), "7\n");
writeFileSync(join(directory, "backlight", "brightness"), "3\n");
writeFileSync(join(directory, "shell.qml"), `import QtQuick
import Quickshell
import "features/brightness"
ShellRoot {
id: test
property int phase: 0
property int tick: 0
property int readsBefore: 0
property real pollStartedAt: 0
property int writes: 0
property bool failed: false
property bool failWrites: false
property string failId: ""
property real previous1: 0.5
property real previous2: 0.5
property int down1: 0
property int down2: 0
property var savedConfig: ({})
property var history: []
property bool auditMotion: false
property string automaticTargets: ""
property real expectedAck: 0
property int expectedGeneration: 0
property int writesBefore: 0
property real since: 0
function motion(id, start, target) {
const levels = history.filter(write => write.id === id && write.success && write.source === "adaptive").map(write => write.confirmed);
test.check(levels.length > 2, "missing intermediate ACKs " + id);
let previous = start;
for (const level of levels) {
test.check(target >= start ? level >= previous : level <= previous, "nonmonotonic ACK " + id);
test.check(level >= Math.min(start, target) && level <= Math.max(start, target), "overshoot " + id);
previous = level;
}
test.check(previous === target, "final ACK target " + id);
}
function check(ok, message) { if (!ok) { failed = true; console.error("adaptive phase " + phase + ": " + message); Qt.quit(); } }
Niri { id: niri }
AmbientLight { id: sensor }
Brightness {
id: brightness
devicePath: "${directory}/no-device"
niriService: niri
ambientLightService: sensor
// Observe the edge, not a transient pending flag on the 20 ms driver:
// process completion and the driver timer can be dispatched in one turn.
onWritePendingChanged: {
if (test.phase === 42 && writePending) {
sensor.found = false;
test.check(!brightness.adaptiveTransitioning && !brightness.writeQueue.some(write => write.source === "adaptive"), "unplug retained ramps/queued auto");
test.phase = 43;
}
}
onLastActionChanged: {
if (test.auditMotion && lastAction.kind === "set-display") {
const row = adaptiveRows.find(display => display.id === lastAction.id);
test.history = test.history.concat([Object.assign({}, lastAction, {confirmed: row.level})]);
}
}
fixtureCommand: () => { test.writes++; return ["/usr/bin/timeout", "2s", "/usr/bin/sh", "-c", "sleep 0.05; " + (test.failWrites || brightness.activeWrite.id === test.failId ? "exit 1" : "printf '3\\\\n'")]; }
}
Timer {
interval: 20; repeat: true; running: true
onTriggered: {
test.tick++;
test.check(brightness.stateObject().adaptive.transitioning === brightness.adaptiveTransitioning, "transition diagnostics differ from service");
if (test.phase >= 30 && test.phase <= 32)
test.check(JSON.stringify(brightness.adaptiveConfig.targets) === test.automaticTargets, "automatic intermediate ACK learned");
test.check(brightness.writeQueue.length <= 2 && new Set(brightness.writeQueue.map(write => write.id)).size === brightness.writeQueue.length, "queue grew or duplicated display");
if (test.phase <= 2 || test.phase === 20 || test.phase === 21) {
const first = brightness.ddcDisplays["DP-1"];
const second = brightness.ddcDisplays["DP-2"];
if (first && second) {
test.check(first.level <= test.previous1 && second.level <= test.previous2, "initial ramp reversed");
if (first.level < test.previous1 && first.level > 2 / 7) test.down1++;
if (second.level < test.previous2 && second.level > 0.25) test.down2++;
test.previous1 = first.level; test.previous2 = second.level;
}
}
if (test.phase === 0 && brightness.persistenceReady) {
if (Quickshell.env("ADAPTIVE_RELOAD") === "1") {
test.check(!brightness.adaptiveEnabled && brightness.adaptiveThresholds[1] === 120 && brightness.adaptiveConfig.targets["ddc:DP-1"][0] === 4 / 7 && brightness.adaptiveConfig.targets.backlight[0] === 3 / 7, "persistence reload");
if (!test.failed) console.log("adaptive runtime: PASS reload");
Qt.quit();
return;
}
test.check(!brightness.adaptiveAvailable && test.writes === 0 && sensor.reads === 0, "ineligible startup");
// Sensor discovery: only while the popup is open or adaptive mode could run.
test.check(brightness.adaptiveEnabled && !brightness.sensorWanted, "closed ineligible popup still wants the sensor");
brightness.panelOpen = true;
test.check(brightness.sensorWanted, "open popup does not want the sensor");
brightness.panelOpen = false;
brightness.ddcDisplays = ({"DP-1": {bus: 1, maximum: 7, level: 0.5, controllable: true}, "DP-2": {bus: 2, maximum: 100, level: 0.5, controllable: true}});
sensor.found = true;
test.check(!brightness.adaptiveAvailable && !brightness.sensorWanted, "setup not ready");
brightness.setupReady = true;
test.check(brightness.sensorWanted, "enabled adaptive mode does not want the sensor");
const enabledConfig = brightness.adaptiveConfig;
brightness.adaptiveConfig = Object.assign({}, enabledConfig, {enabled: false});
test.check(!brightness.sensorWanted, "disabled adaptive mode still wants the sensor");
brightness.adaptiveConfig = enabledConfig;
test.phase = 1;
} else if (test.phase === 1 && sensor.reads > 0) {
test.check(brightness.currentBucket === -1, "no fresh sample");
test.readsBefore = sensor.reads;
test.pollStartedAt = Date.now();
test.phase = 20;
} else if (test.phase === 20 && Date.now() - test.pollStartedAt >= 2200) {
test.check(sensor.busy && sensor.reads === test.readsBefore, "busy sensor overlapped scheduled read");
sensor.sample(0);
test.phase = 21;
} else if (test.phase === 21 && sensor.reads > test.readsBefore) {
test.check(sensor.busy && sensor.reads === test.readsBefore + 1, "scheduled polling did not resume once idle");
test.phase = 2;
} else if (test.phase === 2 && !brightness.adaptiveTransitioning && !brightness.writePending && !brightness.writeQueue.length) {
test.check(brightness.currentBucket === 0 && test.writes > 2, "initial bucket eased writes");
test.check(brightness.ddcDisplays["DP-1"].level === 2 / 7 && brightness.ddcDisplays["DP-2"].level === 0.25, "initial exact quantized targets");
test.check(test.down1 > 0 && test.down2 > 1, "initial confirmed intermediate motion");
test.check(Object.keys(brightness.adaptiveConfig.targets).length === 0, "auto learned");
brightness.setDisplay("ddc:DP-1", 0.51);
brightness.setDisplay("ddc:DP-1", 0.6);
brightness.setDisplay("ddc:DP-1", 0.8);
sensor.sample(10000);
test.phase = 3;
} else if (test.phase === 3 && !brightness.adaptiveTransitioning && !brightness.writePending && !brightness.writeQueue.length) {
test.check(brightness.adaptiveConfig.targets["ddc:DP-1"][0] === 6 / 7, "quantized manual captured bucket/coalescing");
for (const error of ["restoreError", "verificationError", "cleanupError"]) {
brightness.writeQueue = [{id: "ddc:DP-2", source: "adaptive"}];
sensor[error] = "fixture-failure";
sensor.sampleFinished();
test.check(brightness.adaptiveUnsafe && !brightness.adaptiveSampling && !brightness.writeQueue.length && brightness.currentBucket === -1, error + " latch");
const reads = sensor.reads;
brightness.sampleAdaptive();
test.check(sensor.reads === reads, error + " kept sampling");
sensor[error] = "";
brightness.setAdaptiveEnabled(true);
test.check(!brightness.adaptiveUnsafe, "explicit retry");
}
sensor.sample(0);
sensor.found = false;
test.check(!brightness.adaptiveActive && brightness.currentBucket === -1 && !brightness.writeQueue.length, "unplug did not invalidate");
brightness.setAdaptiveEnabled(false);
sensor.found = true;
const reads = sensor.reads;
brightness.sampleAdaptive();
test.check(sensor.reads === reads, "disabled read");
test.phase = 4;
} else if (test.phase === 4 && !brightness.writePending) {
brightness.setAdaptiveEnabled(true);
sensor.sample(0);
brightness.devicePath = "${directory}/backlight";
test.phase = 5;
} else if (test.phase === 5 && !brightness.adaptiveTransitioning && !brightness.writePending && !brightness.writeQueue.length) {
sensor.sample(0);
brightness.setDisplay("backlight", 0.8);
test.phase = 6;
} else if (test.phase === 6 && !brightness.adaptiveTransitioning && !brightness.writePending && !brightness.writeQueue.length) {
test.check(brightness.liveLevel === 3 / 7 && brightness.adaptiveConfig.targets.backlight[0] === 3 / 7, "backlight learned requested instead of actual readback");
test.failWrites = true;
brightness.setAll(0.1);
test.phase = 7;
} else if (test.phase === 7 && !brightness.adaptiveTransitioning && !brightness.writePending && !brightness.writeQueue.length) {
test.check(brightness.adaptiveConfig.targets.backlight[0] === 3 / 7 && brightness.adaptiveConfig.targets["ddc:DP-1"][0] === 6 / 7, "failed writes taught");
test.failWrites = false;
// Make the request predating stale invalidation explicit.
brightness.sampleAdaptive();
brightness.adaptiveReadAt = Date.now() - 10001;
test.phase = 8;
} else if (test.phase === 8 && brightness.currentBucket === -1) {
test.check(brightness.adaptiveSmoothed === null && !brightness.adaptiveTransitioning && brightness.adaptiveError === "sensor sample stale", "stale sample");
sensor.sample(1000);
test.check(brightness.currentBucket === -1 && brightness.adaptiveSmoothed === null, "accepted read from before stale invalidation");
brightness.sampleAdaptive();
sensor.sample(1000);
test.check(brightness.currentBucket === 3 && brightness.adaptiveSmoothed === 1000, "recovery mixed stale EMA");
sensor.effectiveSettings = ({channel: "red", frequencyPercent: 100, integrationTime: 200});
sensor.sample(0);
test.check(brightness.currentBucket === 0 && brightness.adaptiveSmoothed === 0, "measurement signature not reset");
niri.rows = [];
test.check(!brightness.adaptiveAvailable && !brightness.adaptiveActive && !brightness.writeQueue.length, "output rows disappeared");
brightness.setAdaptiveThreshold(1, 120);
brightness.setAdaptiveEnabled(false);
test.phase = 9;
} else if (test.phase === 9 && !brightness.writePending) {
niri.rows = [{name: "DP-1"}, {name: "DP-2"}];
brightness.setAdaptiveEnabled(true);
sensor.sample(0);
test.failId = "ddc:DP-2";
brightness.setAll(0.6);
// Editing the inactive sunlight lower bound cannot move learning.
brightness.setAdaptiveThreshold(2, 400);
sensor.sample(10000);
test.phase = 10;
} else if (test.phase === 10 && !brightness.adaptiveTransitioning && !brightness.writePending && !brightness.writeQueue.length) {
test.check(brightness.adaptiveConfig.targets.backlight[0] === 3 / 7 && brightness.adaptiveConfig.targets["ddc:DP-1"][0] === 4 / 7 && brightness.adaptiveConfig.targets["ddc:DP-2"] === undefined, "shared success-only captured learning");
test.failId = "";
brightness.setDisplay("ddc:DP-1", 0.8);
test.phase = 11;
} else if (test.phase === 11 && !brightness.adaptiveTransitioning && !brightness.writePending && !brightness.writeQueue.length) {
const before = test.writes;
sensor.sample(10000);
test.check(test.writes === before && !brightness.writeQueue.length, "same bucket fought manual brightness");
sensor.errorCode = "read-failed";
sensor.sampleFinished();
test.check(brightness.currentBucket === -1 && brightness.adaptiveSmoothed === null && !brightness.writeQueue.length, "sample failure retained state");
sensor.errorCode = "";
brightness.sampleAdaptive();
test.check(sensor.busy, "recovery read missing");
sensor.found = false;
sensor.found = true;
sensor.sample(0);
test.check(brightness.currentBucket === -1, "accepted read from before unplug");
brightness.sampleAdaptive();
sensor.sample(0);
test.check(brightness.currentBucket === 0, "fresh recovery sample rejected");
brightness.setAdaptiveEnabled(false);
test.phase = 12;
} else if (test.phase === 12 && !brightness.writePending) {
test.savedConfig = brightness.adaptiveConfig;
brightness.devicePath = "${directory}/no-device";
brightness.ddcDisplays = ({"DP-1": {bus: 1, maximum: 7, level: 1 / 7, controllable: true}, "DP-2": {bus: 2, maximum: 100, level: 0.2, controllable: true}});
brightness.adaptiveConfig = {enabled: false, thresholds: [25, 100, 300], targets: {"ddc:DP-1": [1 / 7, 0.5, 0.75, 1], "ddc:DP-2": [0.2, 0.5, 0.75, 1]}};
test.auditMotion = true;
test.automaticTargets = JSON.stringify(brightness.adaptiveConfig.targets);
brightness.setAdaptiveEnabled(true);
sensor.sample(1000);
test.phase = 30;
} else if (test.phase === 30 && brightness.ddcDisplays["DP-2"].level > 0.2 && brightness.adaptiveTransitioning) {
const before = JSON.stringify(brightness.adaptiveTransitions);
const ema = brightness.adaptiveSmoothed;
const generation = brightness.adaptiveGeneration;
niri.rows = [{name: "DP-2"}, {name: "DP-1"}];
test.check(brightness.adaptiveSmoothed === ema && brightness.adaptiveGeneration === generation && JSON.stringify(brightness.adaptiveTransitions) === before, "output order reset EMA/ramp identity");
test.phase = 31;
} else if (test.phase === 31 && !brightness.adaptiveTransitioning && !brightness.writePending) {
test.motion("ddc:DP-1", 1 / 7, 1);
test.motion("ddc:DP-2", 0.2, 1);
test.check(brightness.adaptiveConfig.targets["ddc:DP-1"][0] === 1 / 7 && brightness.adaptiveConfig.targets["ddc:DP-2"][0] === 0.2, "up ramp learned");
test.history = [];
for (let i = 0; i < 30; i++) sensor.sample(0);
test.phase = 32;
} else if (test.phase === 32 && !brightness.adaptiveTransitioning && !brightness.writePending) {
test.motion("ddc:DP-1", 1, 1 / 7);
test.motion("ddc:DP-2", 1, 0.2);
test.history = [];
sensor.sample(10000);
test.phase = 33;
} else if (test.phase === 33 && brightness.ddcDisplays["DP-1"].level > 1 / 7 && brightness.ddcDisplays["DP-2"].level > 0.2) {
test.expectedAck = brightness.ddcDisplays["DP-2"].level;
brightness.setDisplay("ddc:DP-1", 0.6);
test.check(!brightness.adaptiveTransitions["ddc:DP-1"] && !!brightness.adaptiveTransitions["ddc:DP-2"] && !brightness.writeQueue.some(write => write.id === "ddc:DP-1" && write.source === "adaptive"), "manual did not cancel only its display");
test.phase = 47;
} else if (test.phase === 47 && brightness.ddcDisplays["DP-2"].level > test.expectedAck && brightness.adaptiveConfig.targets["ddc:DP-1"][3] === 4 / 7) {
test.check(brightness.currentBucket === 3 && brightness.adaptiveTransitions["ddc:DP-2"].target === 1, "other display did not ACK toward original target after manual override");
for (let i = 0; i < 30; i++) sensor.sample(0);
test.phase = 34;
} else if (test.phase === 34 && !brightness.adaptiveTransitioning && !brightness.writePending && !brightness.writeQueue.length) {
test.check(brightness.ddcDisplays["DP-1"].level === 1 / 7 && brightness.ddcDisplays["DP-2"].level === 0.2, "new bucket after confirmed manual did not use learned targets");
test.check(brightness.adaptiveConfig.targets["ddc:DP-1"][3] === 4 / 7 && brightness.adaptiveConfig.targets["ddc:DP-1"][0] === 1 / 7, "manual did not learn captured intent bucket");
sensor.sample(10000);
test.phase = 35;
} else if (test.phase === 35 && brightness.writePending && brightness.activeWrite.id === "ddc:DP-2" && brightness.activeWrite.source === "adaptive") {
test.expectedAck = brightness.activeWrite.level;
const confirmed = brightness.ddcDisplays["DP-2"].level;
for (let i = 0; i < 30; i++) sensor.sample(0);
test.expectedGeneration = brightness.adaptiveGeneration;
test.check(brightness.adaptiveTransitions["ddc:DP-2"].from === confirmed && brightness.writeQueue.every(write => write.source !== "adaptive" || write.generation === test.expectedGeneration), "retarget did not start from confirmed/drop obsolete queue");
test.phase = 36;
} else if (test.phase === 36 && brightness.ddcDisplays["DP-2"].level === test.expectedAck) {
test.check(brightness.adaptiveTransitions["ddc:DP-2"].from === test.expectedAck && brightness.adaptiveTransitions["ddc:DP-2"].generation === test.expectedGeneration, "in-flight ACK did not rebase retarget");
test.phase = 37;
} else if (test.phase === 37 && !brightness.adaptiveTransitioning && !brightness.writePending) {
test.check(brightness.ddcDisplays["DP-1"].level === 1 / 7 && brightness.ddcDisplays["DP-2"].level === 0.2, "retarget final levels");
sensor.sample(10000);
test.phase = 38;
} else if (test.phase === 38 && brightness.adaptiveTransitionStep > 3 && brightness.adaptiveTransitioning) {
brightness.setAdaptiveThreshold(2, 450);
test.check(!brightness.adaptiveTransitioning && brightness.adaptiveReapplyNeeded && !brightness.writeQueue.some(write => write.source === "adaptive"), "threshold edit retained half ramp");
sensor.sample(10000);
test.check(brightness.currentBucket === 3 && brightness.adaptiveTransitioning && !brightness.adaptiveReapplyNeeded, "same-bucket fresh sample did not reapply");
test.phase = 39;
} else if (test.phase === 39 && !brightness.adaptiveTransitioning && !brightness.writePending) {
test.check(brightness.ddcDisplays["DP-1"].level === 4 / 7 && brightness.ddcDisplays["DP-2"].level === 1, "threshold reapply final targets");
test.failId = "ddc:DP-2";
for (let i = 0; i < 30; i++) sensor.sample(0);
test.phase = 40;
} else if (test.phase === 40 && !brightness.adaptiveTransitioning && !brightness.writePending) {
test.check(brightness.ddcDisplays["DP-2"].level === 1 && !!brightness.ddcDisplays["DP-2"].error, "adaptive failure replaced confirmed level/error");
test.writesBefore = test.writes; test.since = Date.now();
sensor.sample(0);
test.phase = 41;
} else if (test.phase === 41 && Date.now() - test.since > 150) {
test.check(test.writes === test.writesBefore && !brightness.adaptiveTransitioning, "failed adaptive write retried");
test.failId = "";
test.phase = 42;
sensor.sample(10000);
} else if (test.phase === 43 && !brightness.writePending) {
test.writesBefore = test.writes; test.since = Date.now();
test.phase = 44;
} else if (test.phase === 44 && Date.now() - test.since > 150) {
test.check(test.writes === test.writesBefore, "unplug continued ramp");
brightness.devicePath = "${directory}/backlight";
sensor.found = true;
brightness.sampleAdaptive(); sensor.sample(10000);
test.phase = 45;
} else if (test.phase === 45 && !brightness.adaptiveTransitioning && !brightness.writePending) {
test.check(brightness.liveLevel === 3 / 7 && brightness.nativeError === "adaptive target not confirmed" && brightness.adaptiveError === "adaptive target not confirmed", "final ACK mismatch claimed target or omitted error");
test.writesBefore = test.writes; test.since = Date.now();
test.phase = 46;
} else if (test.phase === 46 && Date.now() - test.since > 150) {
test.check(test.writes === test.writesBefore && !brightness.adaptiveTransitioning, "final ACK mismatch retried");
brightness.adaptiveConfig = test.savedConfig;
brightness.setAdaptiveEnabled(false);
if (!test.failed) console.log("adaptive runtime: PASS");
Qt.quit();
}
}
}
Timer { interval: 30000; running: true; onTriggered: { console.error("adaptive runtime deadline phase " + test.phase); Qt.quit(); } }
}`);
const run = runOffscreen(join(directory, "shell.qml"), { directory, timeout: 35000 });
console.log(run.output.trim());
assertOffscreenPass(run, /adaptive runtime: PASS/);
const reload = runOffscreen(join(directory, "shell.qml"), { directory, timeout: 10000, env: { ADAPTIVE_RELOAD: "1" } });
console.log(reload.output.trim());
assertOffscreenPass(reload, /adaptive runtime: PASS reload/);
console.log("adaptive-brightness-runtime.test.mjs: PASS (isolated service, stubbed native boundaries, persisted reload)");
} finally {
rmSync(directory, { recursive: true, force: true });
}