// brightness.test.js — node test for the pure brightness module. Prints ALL PASS. var assert = require('assert'); var B = require('./brightness.js'); // clampLevel: range + null/NaN safety assert.strictEqual(B.clampLevel(-1), 0); assert.strictEqual(B.clampLevel(2), 1); assert.strictEqual(B.clampLevel(0.5), 0.5); assert.strictEqual(B.clampLevel(null), 0); assert.strictEqual(B.clampLevel(undefined), 0); assert.strictEqual(B.clampLevel("0.3"), 0.3); // levelPercent: rounded integer percent assert.strictEqual(B.levelPercent(0), 0); assert.strictEqual(B.levelPercent(0.5), 50); assert.strictEqual(B.levelPercent(1), 100); assert.strictEqual(B.levelPercent(2), 100); assert.strictEqual(B.levelPercent(0.014), 1); // levelRole: band boundaries (<=0.15 minor, >=0.85 warning, else accent) assert.strictEqual(B.levelRole(0.10), "ui.minor"); assert.strictEqual(B.levelRole(0.15), "ui.minor"); // inclusive low boundary assert.strictEqual(B.levelRole(0.16), "ui.accent"); assert.strictEqual(B.levelRole(0.5), "ui.accent"); assert.strictEqual(B.levelRole(0.84), "ui.accent"); assert.strictEqual(B.levelRole(0.85), "warning"); // inclusive high boundary assert.strictEqual(B.levelRole(1), "warning"); assert.strictEqual(B.levelRole(null), "ui.minor"); // 0 -> dim // displayRows: no fake built-in; unresolved external outputs get issue badges assert.deepStrictEqual(B.displayRows({ present: false, level: 0.55 }, { "DP-1": { model: "27E6QC" }, "DP-2": { model: "27E6QC" } }, {}), [ { id: "ddc:DP-1", name: "DP-1 · 27E6QC", kind: "ddc", level: null, controllable: false, issue: "needs setup" }, { id: "ddc:DP-2", name: "DP-2 · 27E6QC", kind: "ddc", level: null, controllable: false, issue: "needs setup" } ]); assert.deepStrictEqual(B.displayRows({ present: true, level: 0.55 }, {}, {}), [ { id: "backlight", name: "built-in", kind: "backlight", level: 0.55, controllable: true, issue: "" } ]); assert.deepStrictEqual(B.displayRows({ present: true, level: 0.75 }, [ { name: "DP-1", model: "27E6QC" } ], { "DP-1": { level: 0.25, controllable: true } }), [ { id: "backlight", name: "built-in", kind: "backlight", level: 0.75, controllable: true, issue: "" }, { id: "ddc:DP-1", name: "27E6QC", kind: "ddc", level: 0.25, controllable: true, issue: "" } ]); // A unique model names its display; a model that repeats the connector, or none, leaves the connector. assert.deepStrictEqual(B.displayRows({}, [{ name: "winit", model: "winit" }, { name: "DP-3", model: "Unknown" }, { name: "DP-4" }], {}).map(row => row.name), ["winit", "DP-3", "DP-4"]); // Internal panels never become DDC candidates, even without an available backlight. for (const connector of ['LVDS-1', 'eDP-1', 'DSI-1', 'eDP-2']) { const outputs = [{ name: connector, model: 'internal panel' }]; const ddc = { [connector]: { controllable: true, level: 0.25 } }; assert.deepStrictEqual(B.displayRows({ present: true, level: 0.5 }, outputs, ddc), [ { id: 'backlight', name: 'built-in', kind: 'backlight', level: 0.5, controllable: true, issue: '' } ]); assert.deepStrictEqual(B.displayRows({ present: false }, outputs, ddc), []); } // Docked laptops retain external DDC candidates in either output representation. const dockedOutputs = { 'LVDS-1': { model: 'internal' }, 'HDMI-A-1': { model: 'external' } }; const dockedRows = B.displayRows({ present: true, level: 0.5 }, dockedOutputs, {}); assert.deepStrictEqual(dockedRows.map(row => row.id), ['backlight', 'ddc:HDMI-A-1']); assert.strictEqual(dockedRows[1].issue, 'needs setup'); // globalState: none/synced/mixed from controllable displays only assert.deepStrictEqual(B.globalState([]), { mode: "none", level: 0, levels: [] }); assert.deepStrictEqual(B.globalState([{ controllable: false, level: 0.2 }]), { mode: "none", level: 0, levels: [] }); assert.deepStrictEqual(B.globalState([{ controllable: true, level: 0.5 }, { controllable: true, level: 0.5 }]), { mode: "synced", level: 0.5, levels: [0.5, 0.5] }); assert.deepStrictEqual(B.globalState([{ controllable: true, level: 0.75 }, { controllable: true, level: 0.25 }]), { mode: "mixed", level: 0.5, levels: [0.75, 0.25] }); // AMD DisplayPort AUX can use a different bus from the connector's sysfs ddc // link. Explicit ddcutil DRM connector pairs must win over that legacy link. assert.deepStrictEqual(B.parseDetection([ 'Display 1', ' I2C bus: /dev/i2c-6', ' DRM_connector: card1-DP-1', 'Display 2', ' I2C bus: /dev/i2c-7', ' DRM_connector: card1-DP-2' ].join('\n'), { 'DP-1': { bus: 1, accessible: true }, 'DP-2': { bus: 2, accessible: true } }), { 'DP-1': { bus: 6, controllable: false, error: '' }, 'DP-2': { bus: 7, controllable: false, error: '' } }); assert.deepStrictEqual(B.parseDetection('Display 1\n I2C bus: /dev/i2c-6\n DRM_connector: card1-DP-9', { 'DP-1': { bus: 6 } }), {}, 'an explicit unknown connector must not be reassigned by bus coincidence'); for (const bus of [undefined, null, -1, 65536, NaN, Infinity, 7.5, '7']) { const detected = bus === undefined ? '' : 'Display 1\n I2C bus: /dev/i2c-' + String(bus); assert.deepStrictEqual(B.parseDetection(detected, { 'DP-1': { bus } }), {}, 'invalid or missing fallback bus must not become a display: ' + String(bus)); } for (const bus of [0, 65535]) { assert.deepStrictEqual(B.parseDetection('Display 1\n I2C bus: /dev/i2c-' + bus, { 'DP-1': { bus } }), { 'DP-1': { bus, controllable: false, error: '' } }, 'valid fallback boundary bus: ' + bus); } // Package-native argument shaping and bounded unprivileged operations. assert.deepStrictEqual(B.ddcCommand('write', 7, 1.5, 200).slice(-6), ['--bus', '7', 'setvcp', '10', '200', '--verify']); assert.deepStrictEqual(B.ddcCommand('write', '7; touch /tmp/no', 0.5, 100), []); assert.deepStrictEqual(B.ddcCommand('read', -1), []); for (const kind of ['detect', 'read', 'write']) { const command = B.ddcCommand(kind, 8, 0.5, 100); assert.strictEqual(command[0], '/usr/bin/timeout'); assert.ok(command.includes('--noconfig')); assert.ok(!command.includes('/usr/bin/pkexec')); } const installed = B.parsePreflight('package=yes\nmodule=yes\nconnector=DP-1,7,yes\nconnector=DP-2,8,no'); assert.strictEqual(installed.needsPrivilege, true); assert.strictEqual(B.parsePreflight('package=yes\nmodule=yes\nconnector=DP-1,7,yes').needsPrivilege, false); assert.strictEqual(B.parsePreflight('package=no\nmodule=yes').needsPrivilege, true); assert.deepStrictEqual(B.parseDetection('Display 1\n I2C bus: /dev/i2c-7\nInvalid display\n I2C bus: /dev/i2c-8', installed.connectors), { 'DP-1': { bus: 7, controllable: false, error: '' }, 'DP-2': { bus: 8, controllable: false, error: '' } }); assert.deepStrictEqual(B.parseBrightness('VCP 10 C 30 200'), { level: 0.15, maximum: 200 }); for (const invalid of ['VCP 10 ERR', 'VCP 10 C 20 0', 'VCP 10 C 201 200', 'password=secret']) assert.strictEqual(B.parseBrightness(invalid), null); assert.strictEqual(B.diagnostic('password=secret TOKEN=abc /usr/bin/arbitrary --command'), ''); assert.strictEqual(B.processError(124, 'write failed'), 'timeout'); assert.strictEqual(B.processError(137, 'read failed'), 'timeout'); assert.strictEqual(B.processError(1, 'write failed'), 'write failed'); assert.strictEqual(B.displayRows({ present: true, level: 0.5, error: 'write failed' }, [], {})[0].issue, 'write failed'); const stages = B.stageState(B.initialStages(), 'reading', 'failed', 'read failed'); assert.strictEqual(stages.find(stage => stage.id === 'reading').error, 'read failed'); assert.strictEqual(stages.find(stage => stage.id === 'preflight').status, 'waiting'); // Setup summary: one line for the running step, else the stage that stopped setup. const summary = (list, running, error) => B.setupSummary(list, running, error || ''); const at = (id, status, error) => B.stageState(B.initialStages(), id, status, error); assert.deepStrictEqual(summary(at('preflight', 'running'), true), { status: 'running', text: 'step 1 of 7 · check system', detail: '' }); const detecting = B.stageState(B.stageState(at('preflight', 'done'), 'authorization', 'done'), 'detection', 'running'); assert.strictEqual(summary(detecting, true).text, 'step 4 of 7 · find monitors'); assert.deepStrictEqual(summary(stages, false, 'read failed'), { status: 'failed', text: 'read brightness failed · read failed', detail: 'read failed' }); const cancelled = at('detection', 'failed', 'cancelled'); assert.deepStrictEqual(summary(cancelled, false, 'cancelled'), { status: 'cancelled', text: 'find monitors cancelled', detail: 'cancelled' }); // A retry runs again while the earlier failure is still on record. assert.strictEqual(summary(B.stageState(stages, 'preflight', 'running'), true).text, 'step 1 of 7 · check system'); // An installation deadline fails its stage while the package process still exits. assert.strictEqual(summary(at('installation', 'failed', 'timeout'), true, 'timeout').text, 'install ddcutil failed · timeout'); // Cancellation between stages fails no stage; setup still says it stopped. assert.strictEqual(summary(at('preflight', 'done'), false, 'cancelled').text, 'setup cancelled'); assert.strictEqual(summary(at('preflight', 'done'), false, 'timeout').text, 'setup failed · timeout'); assert.strictEqual(summary(B.initialStages().map(stage => ({ ...stage, status: 'done' })), false).text, 'monitor control ready'); assert.strictEqual(B.stageLine(at('reading', 'failed', 'read failed').find(stage => stage.id === 'reading')), 'read brightness · failed · read failed'); assert.strictEqual(B.stageLine(cancelled.find(stage => stage.id === 'detection')), 'find monitors · cancelled'); assert.strictEqual(B.stageLine({ id: 'ready', status: 'waiting', error: '' }), 'monitor control · waiting'); // Execute the production service's JavaScript against inert Process/FileView // boundaries. No child command is executed, no host package or hardware access. // These are lifecycle tests, not QML load, compositor or polkit proof. const fs = require('fs'); const vm = require('vm'); const serviceSource = fs.readFileSync(__dirname + '/Brightness.qml', 'utf8'); const methods = [...serviceSource.matchAll(/^ function [\s\S]*?^ }/gm)].map(match => match[0]).join('\n'); function service(outputs = [{ name: 'DP-1' }]) { const deferred = []; const sent = []; const ctx = { Brightness: B, Qt: { callLater: fn => deferred.push(fn) }, adaptiveEnabled: true, adaptiveAvailable: false, adaptiveActive: false, adaptiveThresholds: [25, 100, 300], adaptiveBuckets: [], currentBucket: -1, adaptiveRaw: null, adaptiveSmoothed: null, adaptiveError: '', persistenceError: '', adaptiveGeneration: 0, adaptiveTransitions: {}, adaptiveTransitioning: false, writeOutput: '', osdService: { trigger: (event, value) => ({ event, value }) }, niriService: { outputList: () => outputs }, privilegeService: { polkitAgent: { isRegistered: true, isActive: false } }, devicePath: '/not-a-device', brightnessFile: { text: () => '' }, maxFile: { text: () => '' }, ddcDisplays: {}, lastAction: {}, lastOsd: {}, liveLevel: -1, nativeError: '', setupStages: B.initialStages(), setupRunning: false, setupExpanded: false, setupReady: false, cancelRequested: false, stopReason: '', setupEpoch: 0, setupStage: '', setupError: '', preflight: {}, readQueue: [], readingName: '', operation: '', operationPending: false, operationOutput: '', privilegedEntered: false, writeQueue: [], activeWrite: {}, writePending: false, setupProcess: { running: false, command: [], write: text => sent.push(text) }, writeProcess: { running: false, command: [] }, authorizationDeadline: { restart() {}, stop() {} }, installationDeadline: { restart() {}, stop() {} } }; Object.defineProperty(ctx, 'adaptiveRows', { get: () => B.displayRows({ present: ctx.backlightPresent(), level: ctx.levelFraction() }, outputs, ctx.ddcDisplays) }); // The panel-state bindings, evaluated live from the production source like Qt bindings. const bound = [...serviceSource.matchAll(/^ readonly property \w+ (displays|globalState|globalMode|globalLevel|globalLevels|setupNeeded|setupAvailable): ([\s\S]*?)\n(?= [a-z/])/gm)]; assert.strictEqual(bound.length, 7, 'every panel-state binding found'); for (const [, name, expression] of bound) Object.defineProperty(ctx, name, { get: () => vm.runInContext(`(${expression})`, ctx) }); vm.createContext(ctx); vm.runInContext(methods, ctx); ctx.flush = () => { while (deferred.length) deferred.shift()(); }; ctx.complete = (text, code = 0) => { text.split('\n').forEach(line => ctx.consumeOutput(line)); ctx.finishOperation(code); ctx.flush(); }; ctx.sent = sent; return ctx; } // Explicit setup only, duplicate submission guarded; cancellation wins even if // authorization succeeds after cancellation (two-phase root-side consent). let s = service(); assert.strictEqual(s.operationPending, false); s.setupDdc(); assert.strictEqual(s.operation, 'preflight'); s.complete('package=no\nmodule=no'); assert.strictEqual(s.setupStage, 'authorization'); const pendingCommand = s.setupProcess.command; s.setupDdc(); assert.strictEqual(s.setupProcess.command, pendingCommand); s.cancelSetup(); s.consumeOutput('nugu:authorized'); assert.ok(!s.sent.includes('continue\n')); assert.strictEqual(s.setupStages.find(stage => stage.id === 'installation').status, 'waiting'); s.finishOperation(126); assert.strictEqual(s.setupError, 'cancelled'); assert.strictEqual(s.setupRunning, false); // Cancellation in the deferred handoff is terminal; a new retry cannot revive // an old attempt's callback or overwrite the new preflight operation. s = service(); s.setupDdc(); s.consumeOutput('package=no'); s.finishOperation(0); // deliberately do not flush the authorization continuation s.cancelSetup(); s.flush(); assert.strictEqual(s.setupError, 'cancelled'); assert.strictEqual(s.setupRunning, false); assert.strictEqual(s.operation, 'preflight'); assert.strictEqual(s.setupStages.find(stage => stage.id === 'preflight').status, 'done'); s = service(); s.setupDdc(); s.consumeOutput('package=no'); s.finishOperation(0); s.cancelSetup(); s.retrySetup(); const retryCommand = s.setupProcess.command; s.flush(); assert.strictEqual(s.operation, 'retry-preflight'); assert.strictEqual(s.setupProcess.command, retryCommand); assert.strictEqual(s.operationPending, true); // Authorization expiry retains timeout diagnosis, including a late auth marker. s = service(); s.setupDdc(); s.complete('package=no\nmodule=no'); s.authorizationExpired(); s.consumeOutput('nugu:authorized'); s.finishOperation(126); assert.strictEqual(s.setupError, 'timeout'); assert.ok(!s.sent.includes('continue\n')); // Missing or busy native authorization stays visible, with no privilege launch. for (const [agent, expected] of [ [{ isRegistered: false, isActive: false }, 'authorization unavailable'], [{ isRegistered: true, isActive: true }, 'authorization busy'] ]) { s = service(); s.privilegeService.polkitAgent = agent; s.setupDdc(); s.complete('package=no'); assert.strictEqual(s.setupError, expected); assert.strictEqual(s.operation, 'preflight'); } // Deferred cancellation retains busy ownership throughout actual installation. s = service(); s.setupDdc(); s.complete('package=no\nmodule=no'); s.consumeOutput('nugu:authorized'); assert.deepStrictEqual(s.sent, ['continue\n']); s.cancelSetup(); assert.strictEqual(s.setupRunning, true); assert.strictEqual(s.operationPending, true); s.finishOperation(0); assert.strictEqual(s.setupError, 'cancelled'); assert.strictEqual(s.operation, 'privileged'); s.retrySetup(); assert.strictEqual(s.operation, 'retry-preflight'); s.complete('package=yes\nmodule=yes\nconnector=DP-1,7,yes'); assert.strictEqual(s.operation, 'detect'); assert.ok(!s.setupProcess.command.includes('/usr/bin/pkexec')); // Package deadline is observable, never releases busy ownership prematurely. s = service(); s.setupDdc(); s.complete('package=no\nmodule=no'); s.consumeOutput('nugu:authorized'); s.installationExpired(); assert.strictEqual(s.setupStages.find(stage => stage.id === 'installation').status, 'failed'); assert.strictEqual(s.setupError, 'timeout'); assert.strictEqual(s.setupRunning, true); s.finishOperation(124); assert.strictEqual(s.setupError, 'timeout'); assert.strictEqual(s.setupRunning, false); // Partial discovery/read failure leaves the working monitor usable. Retry // refreshes detection, recovers the second connector, preserves the first read. s = service([{ name: 'DP-1' }, { name: 'DP-2' }]); s.setupDdc(); s.complete('package=yes\nmodule=yes\nconnector=DP-1,7,yes\nconnector=DP-2,8,yes'); assert.strictEqual(s.operation, 'detect'); s.complete('Display 1\n I2C bus: /dev/i2c-7'); assert.strictEqual(s.readingName, 'DP-1'); s.complete('VCP 10 C 40 100'); assert.strictEqual(s.setupError, 'some displays unavailable'); assert.strictEqual(s.ddcDisplays['DP-1'].controllable, true); s.retrySetup(); assert.strictEqual(s.operation, 'retry-preflight'); s.complete('package=yes\nmodule=yes\nconnector=DP-1,7,yes\nconnector=DP-2,8,yes'); s.complete('Display 1\n I2C bus: /dev/i2c-7\nDisplay 2\n I2C bus: /dev/i2c-8'); assert.strictEqual(s.readingName, 'DP-2'); assert.strictEqual(s.ddcDisplays['DP-1'].level, 0.4); s.complete('VCP 10 C 80 200'); assert.strictEqual(s.setupReady, true); assert.strictEqual(s.setupExpanded, false); s.toggleSetup(); assert.strictEqual(s.setupExpanded, true); // Writes use the mapped bus, preserve the confirmed value and OSD on failure, // retain inline error, then recover only on successful completion. s.lastOsd = { event: 'brightness', value: '40' }; s.setDisplay('ddc:DP-2', 0.75); assert.ok(s.writeProcess.command.includes('8')); assert.strictEqual(s.ddcDisplays['DP-2'].level, 0.4); s.finishWrite(124); assert.strictEqual(s.ddcDisplays['DP-2'].level, 0.4); assert.strictEqual(s.ddcDisplays['DP-2'].error, 'timeout'); assert.strictEqual(s.lastOsd.value, '40'); s.flush(); s.setDisplay('ddc:DP-2', 0.75); s.finishWrite(0); s.flush(); assert.strictEqual(s.ddcDisplays['DP-2'].level, 0.75); assert.strictEqual(s.ddcDisplays['DP-2'].error, ''); assert.strictEqual(s.lastOsd.value, '75'); s = service([]); s.brightnessFile.text = () => '50'; s.maxFile.text = () => '100'; s.lastOsd = { value: '50' }; s.setDisplay('backlight', 0.7); s.finishWrite(1); assert.strictEqual(s.stateObject().displays[0].level, 0.5); assert.strictEqual(s.stateObject().displays[0].issue, 'write failed'); assert.strictEqual(s.lastOsd.value, '50'); // A shared absolute target does not preserve offsets or fabricate completed // values. One failed write leaves a genuinely mixed global state and row error. s = service([{ name: 'DP-1' }, { name: 'DP-2' }]); s.ddcDisplays = { 'DP-1': { bus: 7, maximum: 100, level: 0.4, controllable: true }, 'DP-2': { bus: 8, maximum: 100, level: 0.8, controllable: true } }; s.setAll(0.6); assert.deepStrictEqual(Array.from(s.stateObject().global.levels), [0.4, 0.8]); assert.ok(s.writeProcess.command.includes('7')); assert.strictEqual(s.writeProcess.command.at(-2), '60'); s.finishWrite(0); s.flush(); assert.deepStrictEqual(Array.from(s.stateObject().global.levels), [0.6, 0.8]); assert.ok(s.writeProcess.command.includes('8')); assert.strictEqual(s.writeProcess.command.at(-2), '60'); s.finishWrite(1); s.flush(); assert.strictEqual(s.stateObject().global.mode, 'mixed'); assert.deepStrictEqual(Array.from(s.stateObject().global.levels), [0.6, 0.8]); assert.strictEqual(s.ddcDisplays['DP-2'].error, 'write failed'); assert.strictEqual(s.lastOsd.value, '60'); s.setDisplay('ddc:DP-2', 0.6); s.finishWrite(0); s.flush(); assert.strictEqual(s.stateObject().global.mode, 'synced'); assert.deepStrictEqual(Array.from(s.stateObject().global.levels), [0.6, 0.6]); // Adaptive targets snap to device steps; a backlight never turns fully off, DDC may. s = service([]); s.maxFile.text = () => '7'; s.ddcDisplays = { 'DP-1': { maximum: 100 } }; assert.strictEqual(s.deviceLevel({ id: 'backlight', kind: 'backlight' }, 0), 1 / 7); assert.strictEqual(s.deviceLevel({ id: 'backlight', kind: 'backlight' }, 0.5), 4 / 7); assert.strictEqual(s.deviceLevel({ id: 'ddc:DP-1', kind: 'ddc' }, 0), 0); assert.strictEqual(s.deviceLevel({ id: 'ddc:DP-1', kind: 'ddc' }, 0.333), 0.33); // QML source contracts prove routing/safety conventions, not actual loading. assert.ok(!/execDetached|startDetached/.test(serviceSource)); assert.ok(serviceSource.includes('root.authorizationExpired()')); // The registry forwards its privilege host input to the service it creates. assert.match(fs.readFileSync(__dirname + '/../../Registry.qml', 'utf8'), /BrightnessFeature\.Brightness \{[^}]*\n privilegeService: root\.privilegeService\n/); const privileged = B.privilegedCommand(true); assert.strictEqual(privileged[0], '/usr/bin/pkexec'); assert.ok(privileged.includes('--disable-internal-agent')); assert.ok(privileged[privileged.length - 1].includes('read -r consent')); assert.ok(privileged[privileged.length - 1].indexOf('read -r consent') < privileged[privileged.length - 1].indexOf('/usr/bin/pacman -S')); assert.ok(!B.privilegedCommand(false).join(' ').includes('/usr/bin/pacman -S')); assert.ok(!/\/etc\/|chmod|usermod|modules-load\.d\//.test(privileged.join(' '))); // Harmless real subprocess proof of the exact authorization/consent prefix. // The mutation suffix is removed before execution, not stubbed via PATH. const { runIsolated } = require('../../test-fixtures/isolation.js'); const prefix = privileged[privileged.length - 1].split('/usr/bin/timeout --signal=INT')[0]; assert.ok(!/pacman|modprobe|udevadm/.test(prefix)); for (const [input, permitted] of [['cancel\n', false], ['continue\n', true], ['', false]]) { const run = runIsolated('/usr/bin/sh', ['-c', prefix + "printf 'stub:installation\\n'\n"], { input, encoding: 'utf8', timeout: 7000 }); assert.ifError(run.error); assert.ok(run.stdout.includes('nugu:authorized')); assert.strictEqual(run.stdout.includes('stub:installation'), permitted); assert.strictEqual(run.status === 0, permitted); } console.log('brightness.test.js: ALL PASS');