repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

power: real session actions, drop fake profile selector + dead history/shader

5c50cf13b5b49c046a9871fea9ef4dcb619dfe3f

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Redesign the power popup to the audio/brightness/network pattern: pure
node-tested power.js (battery shaping + the session-action routing table) +
thin Power.qml owning UPower natives and the exec sink + washout-fixed view.

- Session actions now actually execute. power.js#actionPlan is a pure routing
  table: lock->lockService, monitor->niri, logout->`niri quit
  --skip-confirmation`, suspend/reboot/poweroff->`systemctl <verb>` via
  execDetached. Previously suspend/logout/reboot/poweroff were advertised but
  ran nothing. argv are discrete token arrays (no shell-injection surface);
  logout/reboot/poweroff keep the two-step confirm, suspend fires immediately.
- Delete the fake power-profile selector: setProfile only set a local string
  and this host has no power-profiles-daemon; PowerProfiles exposes no clean
  availability property, so an always-shown selector would silently no-op.
- Delete dead code: powerHistorySamples + its 2s Timer (no renderer) and the
  power-gradient shader descriptor (the .qsb does not exist). Strip narration
  (powerPanelContract/backend/usesUPower/boundedActions/lowPowerPolicy).
- Keep lowPowerMode() — load-bearing; shell.qml binds nuguTheme.lowPowerMode
  to it to gate animations UI-wide.
- Washout fix: PowerPanel cards use a solid ui.backdrop base with the role
  colour on the border, never the fill; destructive actions get an error
  border, pending a thicker warning border.
- IPC: powerSetProfile replaced by powerSelfTest.

Verified: node power.test.js (50 assertions) pass, qmlcache clear + restart
clean, powerSelfTest ok 9/9, real battery state, popup screenshot clean.
Destructive actions verified by confirm-gating only (poweroff sets pending,
returns confirmed:false; never fired during verification).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

Changed files (6)

quickshell/nuguland/PopoutHost.qml

Modified
3354 3354 property var state: powerService ? Util.parseJson(powerService.stateJson(), {
3355 3355 "battery": {
3357 - "externalDevices": [],
3358 - "powerPanelContract": {
3359 - },
3360 - "session": {
3357 + "externalDevices": []
3362 3358 }) : ({
3363 3359 "battery": {
3365 - "externalDevices": [],
3366 - "powerPanelContract": {
3367 - },
3368 - "session": {
3361 + "externalDevices": []
3371 3363 readonly property var battery: state.battery || ({
3373 3365 readonly property var devices: state.externalDevices || []
3374 - readonly property var panel: state.powerPanelContract || ({
3375 - })
3376 - readonly property var sessionActions: ["lock", "suspend", "monitor-off", "monitor-on", "logout", "reboot", "poweroff"]
3377 - readonly property var profileRows: ["power-saver", "balanced", "performance"]
3366 + readonly property var sessionActions: state.sessionActions || ["lock", "suspend", "monitor-off", "monitor-on", "logout", "reboot", "poweroff"]
3380 3369 function refreshFrom(text) {
3381 3370 state = Util.parseJson(text, state);
3384 - function setProfile(profile) {
3385 - if (powerService)
3386 - refreshFrom(powerService.setProfile(profile));
3390 3373 function runSession(action) {
3391 3374 if (powerService)
3392 3375 refreshFrom(powerService.sessionAction(action));
3446 3429 width: parent.width
3447 3430 height: 78
3448 3431 radius: 15
3449 - color: root.theme ? root.theme.withAlpha(root.roleColor(root.battery.role || "ui.accent"), 0.16) : "transparent"
3450 - border.width: 0
3451 - border.color: root.roleColor(root.battery.role || "ui.accent")
3432 + color: root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, 0.55) : "transparent"
3433 + border.width: 1
3434 + border.color: root.theme ? root.theme.withAlpha(root.roleColor(root.battery.role || "ui.accent"), 0.7) : "transparent"
3453 3436 Column {
3454 3437 anchors.fill: parent
3522 - Row {
3523 - objectName: "powerProfileSelector"
3524 - width: parent.width
3525 - spacing: 6
3527 - Repeater {
3528 - model: root.profileRows
3530 - delegate: Rectangle {
3531 - id: profileButton
3533 - required property string modelData
3534 - readonly property bool active: root.state.profile === modelData
3536 - width: Math.floor((root.width - 12) / 3)
3537 - height: 30
3538 - radius: 10
3539 - color: root.theme ? root.theme.withAlpha(active ? root.theme.ui.focus : root.theme.ui.minor, active ? 0.28 : 0.12) : "transparent"
3540 - border.width: 0
3541 - border.color: root.theme ? (active ? root.theme.ui.focus : root.theme.ui.accent) : "transparent"
3543 - NuguText {
3544 - anchors.centerIn: parent
3545 - theme: root.theme
3546 - variant: "meta"
3547 - selected: profileButton.active
3548 - text: profileButton.modelData
3551 - MouseArea {
3552 - anchors.fill: parent
3553 - onClicked: root.setProfile(profileButton.modelData)
3562 3505 Column {
3563 3506 objectName: "externalDeviceBatteryRows"
3564 3507 width: parent.width
3576 3519 width: root.width
3577 3520 height: 32
3578 3521 radius: 10
3579 - color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.1) : "transparent"
3580 - border.width: 0
3581 - border.color: root.theme ? root.theme.ui.accent : "transparent"
3522 + color: root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, 0.55) : "transparent"
3523 + border.width: 1
3524 + border.color: root.theme ? root.theme.withAlpha(root.theme.ui.accent, 0.45) : "transparent"
3583 3526 NuguText {
3584 3527 anchors.left: parent.left
3623 3566 readonly property bool destructive: ["logout", "reboot", "poweroff"].indexOf(modelData) >= 0
3624 3567 readonly property bool pending: root.state.pendingConfirmation === modelData
3569 + readonly property color accent: root.theme ? (pending ? root.theme.warning : destructive ? root.theme.error : root.theme.ui.accent) : "transparent"
3626 3570 width: Math.floor((root.width - 18) / 4)
3627 3571 height: 38
3628 3572 radius: pending ? 14 : 11
3629 - color: root.theme ? root.theme.withAlpha(pending ? root.theme.warning : destructive ? root.theme.error : root.theme.ui.accent, pending ? 0.28 : 0.14) : "transparent"
3630 - border.width: 0
3631 - border.color: root.theme ? (pending ? root.theme.warning : destructive ? root.theme.error : root.theme.ui.accent) : "transparent"
3573 + color: root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, pending ? 0.82 : 0.55) : "transparent"
3574 + border.width: pending ? 2 : 1
3575 + border.color: root.theme ? actionButton.accent : "transparent"
3633 3577 NuguText {
3634 3578 anchors.centerIn: parent
3654 3598 width: parent.width
3655 3599 height: root.state.pendingConfirmation ? 36 : 26
3656 3600 radius: 11
3657 - color: root.theme ? root.theme.withAlpha(root.state.pendingConfirmation ? root.theme.warning : root.theme.ui.minor, root.state.pendingConfirmation ? 0.2 : 0.1) : "transparent"
3658 - border.width: 0
3659 - border.color: root.theme ? (root.state.pendingConfirmation ? root.theme.warning : root.theme.ui.minor) : "transparent"
3601 + color: root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, 0.55) : "transparent"
3602 + border.width: 1
3603 + border.color: root.theme ? root.theme.withAlpha(root.state.pendingConfirmation ? root.theme.warning : root.theme.ui.minor, 0.6) : "transparent"
3661 3605 NuguText {
3662 3606 anchors.left: parent.left

quickshell/nuguland/Power.qml

Modified
1 1 import QtQuick
2 2 import Quickshell
3 3 import Quickshell.Services.UPower
4 +import "power.js" as Power
6 +// Power service: battery/device status from UPower (native) + session actions.
7 +// Pure shaping and the action routing table live in power.js; this file owns
8 +// only what must touch native objects: reading UPower devices and executing
9 +// the chosen action (lock / niri / systemctl). DI per shell.qml — no singletons
10 +// declared here.
5 11 Item {
6 12 id: root
8 14 property QtObject lockService
9 15 property QtObject niriService
10 - property string selectedProfile: "balanced"
11 16 property string pendingConfirmation: ""
12 - property var powerHistorySamples: []
13 - property var lastAction: ({
14 - })
15 - readonly property bool nativeActionRoute: true
16 - readonly property bool usesUPower: true
17 - readonly property bool powerProfilesAvailable: false
18 - readonly property var boundedActions: ["lock", "logout", "suspend", "reboot", "poweroff", "monitor-off", "monitor-on", "set-profile", "confirm", "cancel"]
19 - readonly property var destructiveActions: ["logout", "reboot", "poweroff"]
17 + property var lastAction: ({})
21 - function normalizeProfile(value) {
22 - const text = String(value).toLowerCase();
23 - if (text.indexOf("performance") >= 0)
24 - return "performance";
19 + // --- Battery / devices (native UPower) ---------------------------------
26 - if (text.indexOf("saver") >= 0)
27 - return "power-saver";
29 - return "balanced";
30 - }
32 - function currentProfile() {
33 - return selectedProfile;
34 - }
36 - function normalizePercent(value) {
37 - const n = Number(value || 0);
38 - if (n > 0 && n <= 1)
39 - return Math.round(n * 100);
41 - return Math.round(n);
42 - }
44 - function deviceState(device) {
45 - return String(UPowerDeviceState.toString(device.state || UPowerDeviceState.Unknown)).toLowerCase().replace(/\s+/g, "").replace("fullycharged", "full");
46 - }
48 - function minutesToLabel(seconds) {
49 - const value = Math.max(0, Math.round(Number(seconds || 0) / 60));
50 - if (value <= 0)
51 - return "unknown";
53 - const hours = Math.floor(value / 60);
54 - const minutes = value % 60;
55 - if (hours <= 0)
56 - return `${minutes}m`;
58 - if (minutes <= 0)
59 - return `${hours}h`;
61 - return `${hours}h ${minutes}m`;
62 - }
64 - function nativeBatteryObject() {
21 + function nativeBattery() {
65 22 const device = UPower.displayDevice;
66 23 if (!device || !device.ready)
67 - return {
68 - "id": "display",
69 - "percent": 0,
70 - "state": "unknown",
71 - "timeEstimate": "unknown",
72 - "health": -1,
73 - "profile": currentProfile()
74 - };
24 + return { "id": "display", "percent": 0, "state": "unknown", "timeEstimate": "unknown", "health": -1 };
76 - const state = deviceState(device);
77 - const timeEstimate = state === "charging" ? minutesToLabel(device.timeToFull) : minutesToLabel(device.timeToEmpty);
26 + const state = Power.cleanState(UPowerDeviceState.toString(device.state || UPowerDeviceState.Unknown));
78 27 return {
79 28 "id": String(device.nativePath || "display"),
80 - "percent": normalizePercent(device.percentage),
29 + "percent": Power.normalizePercent(device.percentage),
81 30 "state": state,
82 - "timeEstimate": timeEstimate,
83 - "health": device.healthSupported ? Math.round(Number(device.healthPercentage || 0)) : -1,
84 - "profile": currentProfile()
31 + "timeEstimate": Power.timeEstimateLabel(state, device.timeToFull, device.timeToEmpty),
32 + "health": device.healthSupported ? Math.round(Number(device.healthPercentage || 0)) : -1
88 - function displayBattery() {
89 - return nativeBatteryObject();
36 + function batteryObject() {
37 + const b = nativeBattery();
38 + b.role = Power.batteryRole(b.percent);
39 + return b;
92 - function nativeExternalDevices() {
42 + function externalDevices() {
93 43 const rows = [];
94 44 const devices = UPower.devices.values || [];
95 45 for (let i = 0; i < devices.length; i++) {
101 51 "id": String(device.nativePath || device.model || `device-${i}`),
102 52 "name": String(device.model || UPowerDeviceType.toString(device.type)),
103 53 "type": String(UPowerDeviceType.toString(device.type)).toLowerCase(),
104 - "percent": normalizePercent(device.percentage),
105 - "state": deviceState(device)
54 + "percent": Power.normalizePercent(device.percentage),
55 + "state": Power.cleanState(UPowerDeviceState.toString(device.state || UPowerDeviceState.Unknown))
108 58 return rows;
111 - function externalDevices() {
112 - return nativeExternalDevices();
113 - }
115 - function externalDevicesById() {
116 - const indexed = {
117 - };
118 - const devices = externalDevices();
119 - for (let i = 0; i < devices.length; i++) {
120 - const device = devices[i];
121 - indexed[device.id] = {
122 - "id": device.id,
123 - "name": device.name,
124 - "type": device.type,
125 - "percent": device.percent,
126 - "state": device.state
127 - };
128 - }
129 - return indexed;
130 - }
132 - function batteryRole(battery) {
133 - if (battery.percent <= 10)
134 - return "error";
136 - if (battery.percent <= 25)
137 - return "warning";
139 - return "ui.accent";
140 - }
142 - function batteryFraction() {
143 - return Math.max(0, Math.min(1, Number(displayBattery().percent || 0) / 100));
144 - }
146 - function appendPowerHistorySample() {
147 - const next = powerHistorySamples.slice(Math.max(0, powerHistorySamples.length - 3599));
148 - next.push([batteryFraction(), chargingValue(), profileValue(), healthFraction(), 0]);
149 - powerHistorySamples = next;
150 - }
152 - function chargingValue() {
153 - return displayBattery().state === "charging" ? 1 : 0;
154 - }
156 - function profileValue() {
157 - const profile = currentProfile();
158 - if (profile === "performance")
159 - return 1;
161 - if (profile === "power-saver")
162 - return 0;
164 - return 0.5;
165 - }
167 - function healthFraction() {
168 - const health = Number(displayBattery().health || 0);
169 - return health > 0 ? Math.max(0, Math.min(1, health / 100)) : 1;
170 - }
61 + // lowPowerMode() drives global animation throttling (shell.qml binds
62 + // nuguTheme.lowPowerMode to it). Keep it lean — it is read every frame.
172 63 function lowPowerMode() {
173 - const state = String(displayBattery().state || "").toLowerCase();
174 - return state.indexOf("discharging") >= 0 || state.indexOf("pendingdischarge") >= 0;
64 + return Power.isLowPower(nativeBattery().state);
177 - function batteryObject() {
178 - const battery = displayBattery();
179 - return {
180 - "id": battery.id,
181 - "percent": battery.percent,
182 - "state": battery.state,
183 - "timeEstimate": battery.timeEstimate,
184 - "health": battery.health,
185 - "profile": battery.profile,
186 - "role": batteryRole(battery)
187 - };
188 - }
190 - function powerPanelContract() {
191 - return {
192 - "source": "Nuguland session Content.qml plus Nuguland SessionScreen.qml plus Nuguland Power.qml",
193 - "ownedBy": "PopoutHost.qml inline PowerPanel",
194 - "upowerSessionPanel": true,
195 - "batteryHero": true,
196 - "externalDeviceBatteryRows": true,
197 - "powerProfileSelector": true,
198 - "keyboardActionGrid": true,
199 - "confirmationStrip": true,
200 - "destructiveTwoStep": true,
201 - "serviceActionsOnly": true,
202 - "safeDefault": "lock",
203 - "actions": ["lock", "suspend", "monitor-off", "monitor-on", "logout", "reboot", "poweroff"],
204 - "profileRows": ["power-saver", "balanced", "performance"]
205 - };
206 - }
67 + // --- State (IPC contract) ----------------------------------------------
208 69 function stateObject() {
209 70 const battery = batteryObject();
210 - const devices = externalDevices();
211 71 return {
212 - "backend": "Power.qml",
213 - "usesUPower": usesUPower,
214 - "nativeActionRoute": nativeActionRoute,
215 - "helperProcesses": [],
216 - "serviceOwnedActions": true,
217 - "boundedActions": boundedActions,
218 - "powerPanelContract": powerPanelContract(),
219 - "profile": currentProfile(),
220 - "powerProfilesAvailable": powerProfilesAvailable,
221 - "lowPowerMode": lowPowerMode(),
222 - "lowPowerPolicy": {
223 - "trigger": "battery-discharge",
224 - "shaders": false,
225 - "animations": false
226 - },
227 72 "battery": battery,
228 - "externalDevices": devices.map((device) => {
229 - return ({
230 - "id": device.id,
231 - "name": device.name,
232 - "type": device.type,
233 - "percent": device.percent,
234 - "state": device.state
235 - });
236 - }),
237 - "externalDevicesById": externalDevicesById(),
238 - "session": {
239 - "safeDefault": "lock",
240 - "requiresConfirmation": destructiveActions,
241 - "keyboardFocus": true,
242 - "escapeCancels": true,
243 - "routes": {
244 - "lock": "Lock.qml",
245 - "monitor": "Niri.qml"
246 - }
247 - },
73 + "externalDevices": externalDevices(),
74 + "sessionActions": Power.SESSION_ACTIONS,
75 + "destructiveActions": Power.DESTRUCTIVE_ACTIONS,
248 76 "compact": {
249 77 "label": "Power",
250 78 "role": battery.role,
251 79 "charging": battery.state === "charging"
253 - "shader": {
254 - "kind": "power-gradient",
255 - "clipped": true,
256 - "source": "shaders/power-gradient.frag.qsb",
257 - "priorArt": "Made by Evan fwidth/smoothstep antialiased line ideas adapted to a foreground-only battery history sparkline",
258 - "values": [batteryFraction(), chargingValue(), profileValue(), healthFraction()],
259 - "colors": ["ui.accent", "ui.focus", "ui.minor", "ui.backdrop", "warning", "error"]
260 - },
261 81 "pendingConfirmation": pendingConfirmation,
262 82 "lastAction": lastAction
267 87 return JSON.stringify(stateObject());
270 - function setProfile(name) {
271 - const selected = normalizeProfile(name);
272 - selectedProfile = selected;
273 - pendingConfirmation = "";
274 - lastAction = {
275 - "kind": "set-profile",
276 - "profile": selected,
277 - "nativeActionRoute": nativeActionRoute
278 - };
279 - return stateJson();
280 - }
90 + // --- Session actions ----------------------------------------------------
282 - function requiresConfirmation(kind) {
283 - return destructiveActions.indexOf(kind) >= 0;
284 - }
286 - function executeSessionAction(actionName) {
287 - if (actionName === "lock" && lockService)
92 + // Dispatch a resolved action plan (from power.js) to the native sink.
93 + function runPlan(plan) {
94 + if (plan.via === "lock" && lockService)
288 95 lockService.request();
289 - else if (actionName === "monitor-off" && niriService)
290 - niriService.action(["power-off-monitors"]);
291 - else if (actionName === "monitor-on" && niriService)
292 - niriService.action(["power-on-monitors"]);
96 + else if (plan.via === "niri" && niriService)
97 + niriService.action(plan.args);
98 + else if (plan.via === "exec")
99 + Quickshell.execDetached(plan.argv);
295 102 function sessionAction(kind) {
296 - const actionName = String(kind);
297 - if (requiresConfirmation(actionName)) {
298 - pendingConfirmation = actionName;
299 - lastAction = {
300 - "kind": actionName,
301 - "nativeActionRoute": nativeActionRoute,
302 - "confirmed": false
303 - };
103 + const action = String(kind);
104 + if (Power.requiresConfirmation(action)) {
105 + pendingConfirmation = action;
106 + lastAction = { "kind": action, "confirmed": false };
304 107 } else {
305 108 pendingConfirmation = "";
306 - executeSessionAction(actionName);
307 - lastAction = {
308 - "kind": actionName,
309 - "nativeActionRoute": nativeActionRoute,
310 - "confirmed": true
311 - };
109 + runPlan(Power.actionPlan(action));
110 + lastAction = { "kind": action, "confirmed": true };
313 112 return stateJson();
316 115 function confirmAction(kind) {
317 - const actionName = String(kind);
318 - const confirmed = pendingConfirmation === actionName && requiresConfirmation(actionName);
116 + const action = String(kind);
117 + const confirmed = pendingConfirmation === action && Power.requiresConfirmation(action);
319 118 pendingConfirmation = "";
320 119 if (confirmed)
321 - executeSessionAction(actionName);
120 + runPlan(Power.actionPlan(action));
323 - lastAction = {
324 - "kind": actionName,
325 - "nativeActionRoute": nativeActionRoute,
326 - "confirmed": confirmed
327 - };
122 + lastAction = { "kind": action, "confirmed": confirmed };
328 123 return stateJson();
331 126 function cancelAction() {
332 127 pendingConfirmation = "";
333 - lastAction = {
334 - "kind": "cancel"
335 - };
128 + lastAction = { "kind": "cancel" };
336 129 return stateJson();
339 - Component.onCompleted: appendPowerHistorySample()
132 + // selfTest() — exercises the pure routing/shaping without touching native
133 + // state or executing anything. Gate-checks power.js via IPC.
134 + function selfTest() {
135 + const cases = [];
136 + function check(name, got, want) { cases.push({ "name": name, "pass": JSON.stringify(got) === JSON.stringify(want), "got": got }); }
341 - Timer {
342 - interval: 2000
343 - repeat: true
344 - running: true
345 - onTriggered: root.appendPowerHistorySample()
138 + check("poweroff routes to systemctl", Power.actionPlan("poweroff"), { "via": "exec", "argv": ["systemctl", "poweroff"] });
139 + check("logout routes to niri quit", Power.actionPlan("logout"), { "via": "niri", "args": ["quit", "--skip-confirmation"] });
140 + check("lock routes to lockService", Power.actionPlan("lock"), { "via": "lock" });
141 + check("unknown is no-op", Power.actionPlan("bogus"), { "via": "none" });
142 + check("poweroff confirms", Power.requiresConfirmation("poweroff"), true);
143 + check("suspend immediate", Power.requiresConfirmation("suspend"), false);
144 + check("batteryRole critical", Power.batteryRole(8), "error");
145 + check("normalizePercent fraction", Power.normalizePercent(0.5), 50);
146 + check("low power on discharge", Power.isLowPower("Discharging"), true);
148 + const failed = cases.filter((c) => !c.pass);
149 + return JSON.stringify({ "ok": failed.length === 0, "total": cases.length, "failed": failed });

quickshell/nuguland/docs/superpowers/specs/2026-06-29-power-popup-redesign-design.md

Added
new file mode 100644
1 +# Power popup redesign — design
3 +Popup 4 of 4 in the nuguland popup redesign sweep (audio → brightness →
4 +network → **power**). Same architecture as the prior three: a pure,
5 +node-tested `.js` module + a thin QML service that owns native objects + a
6 +pure graphical view.
8 +## Goal
10 +Make the power popup honest and lean: real session actions, real battery
11 +status, no fake features, no dead code, washout-fixed cards.
13 +## What was wrong (recon)
15 +- **Fake session actions.** `executeSessionAction` only handled
16 + lock/monitor-off/monitor-on. `suspend`, `logout`, `reboot`, `poweroff`
17 + were advertised in the grid but executed **nothing** (destructive ones got
18 + a confirm prompt, then a silent no-op).
19 +- **Fake power-profile selector.** `setProfile` only set a local
20 + `selectedProfile` string; no daemon write. This host has no
21 + power-profiles-daemon at all (`org.freedesktop.UPower.PowerProfiles … not
22 + activatable`).
23 +- **Dead code.** `powerHistorySamples` grew every 2s via a `Timer` toward
24 + 3599 entries with no renderer; a `power-gradient` shader descriptor pointed
25 + at a `.qsb` file that does not exist.
26 +- **Narration.** `powerPanelContract`, `backend`, `usesUPower`,
27 + `nativeActionRoute`, `helperProcesses`, `boundedActions`,
28 + `lowPowerPolicy` — self-describing JSON nothing consumed.
30 +## Decisions
32 +- **Session actions → real.** Routing table in `power.js#actionPlan`:
33 + - `lock` → `lockService.request()`
34 + - `monitor-off/on` → `niriService.action(["power-off-monitors" | "power-on-monitors"])`
35 + - `logout` → `niriService.action(["quit", "--skip-confirmation"])` (popup
36 + already two-step confirms, so skip niri's own Enter prompt)
37 + - `suspend` → `Quickshell.execDetached(["systemctl", "suspend"])`
38 + - `reboot` → `["systemctl", "reboot"]`
39 + - `poweroff` → `["systemctl", "poweroff"]`
40 + - argv/args are discrete token arrays — never a shell string, no injection
41 + surface. logind polkit allows the active session to run these without
42 + sudo.
43 +- **Confirm gating.** `logout`/`reboot`/`poweroff` are two-step
44 + (`requiresConfirmation`); `suspend` is recoverable so it fires
45 + immediately; `lock`/monitor are immediate.
46 +- **Profile selector → deleted.** Quickshell's `PowerProfiles` exposes no
47 + clean "daemon available" property (only `hasPerformanceProfile`, which is
48 + wrong for a balanced-only ppd host). On this host there is no ppd at all,
49 + so an always-shown selector would silently no-op — the same dishonesty
50 + being removed. Cut whole, per the standing "less code / no fake features"
51 + directive. Revisit if the host adopts ppd.
52 +- **`lowPowerMode()` kept** — load-bearing: `shell.qml` binds
53 + `nuguTheme.lowPowerMode` to it, which gates every animation across the UI.
55 +## Module surface
57 +`power.js` (pure, dual-mode export, `node power.test.js` → ALL PASS):
58 +`normalizePercent`, `minutesToLabel`, `cleanState`, `batteryRole`,
59 +`timeEstimateLabel`, `isLowPower`, `SESSION_ACTIONS`, `DESTRUCTIVE_ACTIONS`,
60 +`requiresConfirmation`, `actionPlan`, `actionLabel`.
62 +`Power.qml` (native): UPower `displayDevice`/`devices` reads,
63 +`UPowerDeviceState`/`Type` enums, the action sink (`runPlan`), the confirm
64 +state machine, `lowPowerMode()`, `selfTest()`.
66 +## State (IPC contract)
68 +`stateJson()` → `{ battery{id,percent,state,timeEstimate,health,role},
69 +externalDevices[], sessionActions[], destructiveActions[],
70 +compact{label,role,charging}, pendingConfirmation, lastAction }`.
71 +IPC handlers: `powerState`, `powerSessionAction`, `powerConfirmAction`,
72 +`powerCancelAction`, `powerSelfTest` (replaced `powerSetProfile`).
74 +## View (PopoutHost PowerPanel)
76 +Battery hero + external-device rows + 4-col action grid + confirm strip.
77 +Washout fix (popup frame is light): cards use a solid
78 +`withAlpha(ui.backdrop, 0.55)` base (0.82 when pending) with the role colour
79 +on the **border**, never the fill. Destructive actions carry an `error`
80 +border; pending carries a thicker `warning` border.
82 +## Verification
84 +`node power.test.js` (50 assertions) → clear qmlcache → restart →
85 +journal clean → `powerSelfTest` `{ok:true,9/9}` → `powerState` real battery
86 +→ open popout + screenshot. **Destructive actions verified by gating only**
87 +(`powerSessionAction poweroff` sets `pendingConfirmation` and returns
88 +`confirmed:false`; the action is never fired during verification).

quickshell/nuguland/power.js

Added
new file mode 100644
1 +// power.js — pure power/session shaping + action routing. NO I/O, no UPower.
2 +// Dual-mode: node `require` (tests) + QML import ("power.js" as Power).
3 +// Same pattern as audio.js / brightness.js / network.js. No `.pragma library`.
4 +//
5 +// The native side (Power.qml) owns UPower devices and the actual exec; this
6 +// module owns the plain-data transforms and — crucially — actionPlan(), the
7 +// single routing table that says HOW each session action is carried out. That
8 +// table is pure, so the dangerous part (which argv runs for "poweroff") is
9 +// unit-tested instead of buried in QML.
11 +// --- Battery / device shaping ----------------------------------------------
13 +// normalizePercent(value) — UPower percentage may arrive 0..1 or 0..100.
14 +function normalizePercent(value) {
15 + var n = Number(value || 0);
16 + if (n > 0 && n <= 1) return Math.round(n * 100);
17 + return Math.round(n);
20 +// minutesToLabel(seconds) — "unknown" / "45m" / "2h" / "1h 20m".
21 +function minutesToLabel(seconds) {
22 + var value = Math.max(0, Math.round(Number(seconds || 0) / 60));
23 + if (value <= 0) return "unknown";
24 + var hours = Math.floor(value / 60);
25 + var minutes = value % 60;
26 + if (hours <= 0) return minutes + "m";
27 + if (minutes <= 0) return hours + "h";
28 + return hours + "h " + minutes + "m";
31 +// cleanState(raw) — collapse a UPowerDeviceState.toString() value to a compact
32 +// token: "Fully charged" -> "full", "Pending charge" -> "pendingcharge".
33 +function cleanState(raw) {
34 + return String(raw == null ? "unknown" : raw)
35 + .toLowerCase().replace(/\s+/g, "").replace("fullycharged", "full");
38 +// batteryRole(percent) — theme token by charge level.
39 +function batteryRole(percent) {
40 + var p = Number(percent || 0);
41 + if (p <= 10) return "error";
42 + if (p <= 25) return "warning";
43 + return "ui.accent";
46 +// timeEstimateLabel(state, secsToFull, secsToEmpty) — charging counts up to
47 +// full, otherwise down to empty.
48 +function timeEstimateLabel(state, secsToFull, secsToEmpty) {
49 + return cleanState(state) === "charging"
50 + ? minutesToLabel(secsToFull)
51 + : minutesToLabel(secsToEmpty);
54 +// isLowPower(state) — running on battery (drives global animation throttling).
55 +function isLowPower(state) {
56 + var s = cleanState(state);
57 + return s.indexOf("discharging") >= 0 || s.indexOf("pendingdischarge") >= 0;
60 +// --- Session actions -------------------------------------------------------
62 +var SESSION_ACTIONS = ["lock", "suspend", "monitor-off", "monitor-on", "logout", "reboot", "poweroff"];
63 +var DESTRUCTIVE_ACTIONS = ["logout", "reboot", "poweroff"];
65 +// requiresConfirmation(action) — irreversible session actions are two-step.
66 +// suspend is recoverable, so it fires immediately.
67 +function requiresConfirmation(action) {
68 + return DESTRUCTIVE_ACTIONS.indexOf(String(action)) >= 0;
71 +// actionPlan(action) — the routing table. Returns how Power.qml executes it:
72 +// { via: "lock" } -> lockService.request()
73 +// { via: "niri", args: [...] } -> niriService.action(args)
74 +// { via: "exec", argv: [...] } -> Quickshell.execDetached(argv)
75 +// { via: "none" } -> unknown action, do nothing
76 +// argv/args are discrete tokens (never a shell string) — no injection surface.
77 +function actionPlan(action) {
78 + switch (String(action)) {
79 + case "lock": return { via: "lock" };
80 + case "monitor-off": return { via: "niri", args: ["power-off-monitors"] };
81 + case "monitor-on": return { via: "niri", args: ["power-on-monitors"] };
82 + // niri owns the session; quit ends it. --skip-confirmation because the
83 + // popup already two-step confirms (avoids niri's own Enter prompt).
84 + case "logout": return { via: "niri", args: ["quit", "--skip-confirmation"] };
85 + case "suspend": return { via: "exec", argv: ["systemctl", "suspend"] };
86 + case "reboot": return { via: "exec", argv: ["systemctl", "reboot"] };
87 + case "poweroff": return { via: "exec", argv: ["systemctl", "poweroff"] };
88 + default: return { via: "none" };
89 + }
92 +// actionLabel(action) — short grid label.
93 +function actionLabel(action) {
94 + if (action === "monitor-off") return "mon off";
95 + if (action === "monitor-on") return "mon on";
96 + if (action === "poweroff") return "power";
97 + return String(action);
100 +if (typeof module !== 'undefined' && module.exports) {
101 + module.exports = {
102 + normalizePercent: normalizePercent,
103 + minutesToLabel: minutesToLabel,
104 + cleanState: cleanState,
105 + batteryRole: batteryRole,
106 + timeEstimateLabel: timeEstimateLabel,
107 + isLowPower: isLowPower,
108 + SESSION_ACTIONS: SESSION_ACTIONS,
109 + DESTRUCTIVE_ACTIONS: DESTRUCTIVE_ACTIONS,
110 + requiresConfirmation: requiresConfirmation,
111 + actionPlan: actionPlan,
112 + actionLabel: actionLabel
113 + };

quickshell/nuguland/power.test.js

Added
new file mode 100644
1 +// power.test.js — node test for the pure power module.
2 +// Run: node power.test.js (must print "power.test.js: ALL PASS")
3 +var assert = require('assert');
4 +var P = require('./power.js');
6 +var passed = 0;
7 +function eq(got, want, msg) { assert.strictEqual(got, want, msg); passed++; }
8 +function deep(got, want, msg) { assert.deepStrictEqual(got, want, msg); passed++; }
9 +function ok(cond, msg) { assert(cond, msg); passed++; }
11 +// --- normalizePercent ------------------------------------------------------
12 +eq(P.normalizePercent(0.42), 42, 'fraction 0..1 -> percent');
13 +eq(P.normalizePercent(73), 73, 'already-percent passes through');
14 +eq(P.normalizePercent(1), 100, '1.0 -> 100');
15 +eq(P.normalizePercent(null), 0, 'null -> 0');
16 +eq(P.normalizePercent(99.6), 100, 'rounds');
18 +// --- minutesToLabel --------------------------------------------------------
19 +eq(P.minutesToLabel(0), 'unknown', 'zero seconds unknown');
20 +eq(P.minutesToLabel(2700), '45m', '45 minutes');
21 +eq(P.minutesToLabel(7200), '2h', 'exact hours drop minutes');
22 +eq(P.minutesToLabel(4800), '1h 20m', 'hours and minutes');
23 +eq(P.minutesToLabel(-50), 'unknown', 'negative clamps to unknown');
25 +// --- cleanState ------------------------------------------------------------
26 +eq(P.cleanState('Fully charged'), 'full', 'fully charged -> full');
27 +eq(P.cleanState('Discharging'), 'discharging', 'lowercased');
28 +eq(P.cleanState('Pending charge'), 'pendingcharge', 'spaces stripped');
29 +eq(P.cleanState(null), 'unknown', 'null -> unknown');
31 +// --- batteryRole -----------------------------------------------------------
32 +eq(P.batteryRole(8), 'error', 'critical');
33 +eq(P.batteryRole(10), 'error', 'boundary 10');
34 +eq(P.batteryRole(20), 'warning', 'low');
35 +eq(P.batteryRole(25), 'warning', 'boundary 25');
36 +eq(P.batteryRole(60), 'ui.accent', 'healthy');
38 +// --- timeEstimateLabel -----------------------------------------------------
39 +eq(P.timeEstimateLabel('Charging', 3600, 0), '1h', 'charging uses time-to-full');
40 +eq(P.timeEstimateLabel('Discharging', 0, 5400), '1h 30m', 'discharging uses time-to-empty');
42 +// --- isLowPower ------------------------------------------------------------
43 +eq(P.isLowPower('Discharging'), true, 'discharging is low power');
44 +eq(P.isLowPower('Pending discharge'), true, 'pending discharge is low power');
45 +eq(P.isLowPower('Charging'), false, 'charging is not');
46 +eq(P.isLowPower('Fully charged'), false, 'full is not');
48 +// --- requiresConfirmation --------------------------------------------------
49 +eq(P.requiresConfirmation('poweroff'), true, 'poweroff confirms');
50 +eq(P.requiresConfirmation('reboot'), true, 'reboot confirms');
51 +eq(P.requiresConfirmation('logout'), true, 'logout confirms');
52 +eq(P.requiresConfirmation('suspend'), false, 'suspend is recoverable, no confirm');
53 +eq(P.requiresConfirmation('lock'), false, 'lock no confirm');
54 +eq(P.requiresConfirmation('monitor-off'), false, 'monitor-off no confirm');
56 +// --- actionPlan: the routing table (the safety-critical part) --------------
57 +deep(P.actionPlan('lock'), { via: 'lock' }, 'lock routes to lockService');
58 +deep(P.actionPlan('monitor-off'), { via: 'niri', args: ['power-off-monitors'] }, 'monitor-off via niri');
59 +deep(P.actionPlan('monitor-on'), { via: 'niri', args: ['power-on-monitors'] }, 'monitor-on via niri');
60 +deep(P.actionPlan('logout'), { via: 'niri', args: ['quit', '--skip-confirmation'] }, 'logout = niri quit, skip its prompt');
61 +deep(P.actionPlan('suspend'), { via: 'exec', argv: ['systemctl', 'suspend'] }, 'suspend = systemctl suspend');
62 +deep(P.actionPlan('reboot'), { via: 'exec', argv: ['systemctl', 'reboot'] }, 'reboot = systemctl reboot');
63 +deep(P.actionPlan('poweroff'), { via: 'exec', argv: ['systemctl', 'poweroff'] }, 'poweroff = systemctl poweroff');
64 +deep(P.actionPlan('bogus'), { via: 'none' }, 'unknown action does nothing');
65 +// argv/args must be discrete tokens, never a single shell string
66 +ok(Array.isArray(P.actionPlan('poweroff').argv) && P.actionPlan('poweroff').argv.length === 2, 'poweroff argv is token array (no shell injection)');
68 +// every advertised session action has a real plan (no silent no-ops)
69 +P.SESSION_ACTIONS.forEach(function (a) {
70 + ok(P.actionPlan(a).via !== 'none', 'session action "' + a + '" has a real route');
71 +});
73 +// --- actionLabel -----------------------------------------------------------
74 +eq(P.actionLabel('monitor-off'), 'mon off', 'monitor-off label');
75 +eq(P.actionLabel('poweroff'), 'power', 'poweroff label');
76 +eq(P.actionLabel('lock'), 'lock', 'passthrough label');
78 +console.log(passed + ' assertions passed');
79 +console.log('power.test.js: ALL PASS');

quickshell/nuguland/shell.qml

Modified
1072 1072 return surfaceManager.openRegisteredPopout("connectivity");
1075 - function powerSetProfile(name: string) : string {
1076 - return power.setProfile(name);
1075 + function powerSelfTest() : string {
1076 + return power.selfTest();
1079 1079 function powerSessionAction(kind: string) : string {