From db5e6908b9f5807859ab15c9ecb2cccfd7ae4f8e Mon Sep 17 00:00:00 2001 From: itxkarthik Date: Thu, 26 Nov 2026 19:03:04 +0530 Subject: [PATCH 01/19] Warn about a low battery at 20% as well as 10% A pack whose gauge reads high, such as an uncalibrated replacement, can cut out above 10%, so the only warning never came. The shell now warns once at 20%, UPower's own PercentageLow, and once more at 10%. Each level is latched through AC flaps as before, and climbing back above one re-arms it. Fixes #20084 --- .../plugins/services/battery/BatteryModel.js | 24 +++++--- shell/plugins/services/battery/Service.qml | 9 +-- test/shell.d/battery-test.sh | 56 +++++++++++++------ 3 files changed, 60 insertions(+), 29 deletions(-) diff --git a/shell/plugins/services/battery/BatteryModel.js b/shell/plugins/services/battery/BatteryModel.js index b326be129a07..c219b692bb31 100644 --- a/shell/plugins/services/battery/BatteryModel.js +++ b/shell/plugins/services/battery/BatteryModel.js @@ -9,16 +9,24 @@ function isDischarging(device, dischargingState) { return !!(device && device.isPresent && device.state === dischargingState) } -function shouldWarnLowBattery(device, dischargingState, threshold, alreadyNotified) { +// Warn once at each threshold the battery falls to while discharging. warnedAt is the lowest +// threshold already warned at (0 for none). Charging does not re-arm it, so an AC flap at a +// threshold warns once; climbing back above a threshold re-arms that one and those below it. +function shouldWarnLowBattery(device, dischargingState, thresholds, warnedAt) { + var warned = Number(warnedAt) || 0 var level = batteryPercentage(device) - if (level < 0) return { level: level, notify: false, notifiedLowBattery: !!alreadyNotified } + if (level < 0) return { level: level, notify: false, warnedAt: warned } - var low = isDischarging(device, dischargingState) && level <= threshold - return { - level: level, - notify: low && !alreadyNotified, - notifiedLowBattery: level <= threshold && !!(alreadyNotified || low) - } + // The lowest threshold the level is at or under, or 0 when above them all. + var reached = 0 + for (var i = 0; i < thresholds.length; i++) + if (level <= thresholds[i] && (!reached || thresholds[i] < reached)) reached = thresholds[i] + + if (warned && level > warned) warned = reached + + var notify = isDischarging(device, dischargingState) && reached > 0 && (!warned || reached < warned) + if (notify) warned = reached + return { level: level, notify: notify, warnedAt: warned } } function parseActiveProfile(text) { diff --git a/shell/plugins/services/battery/Service.qml b/shell/plugins/services/battery/Service.qml index 0e37fe646d3c..2c1b717c0fae 100644 --- a/shell/plugins/services/battery/Service.qml +++ b/shell/plugins/services/battery/Service.qml @@ -11,7 +11,8 @@ Item { property var shell: null property string omarchyPath: Quickshell.env("OMARCHY_PATH") - readonly property int batteryThreshold: 10 + // 20 is UPower's own PercentageLow, so a pack that cuts out above 10% still gets a warning. + readonly property var batteryThresholds: [20, 10] property string pendingPowerSource: "" // Follows power-profiles-daemon's change signals, so nothing polls it. // Quickshell never attaches that listener if the daemon failed when the @@ -36,7 +37,7 @@ Item { PersistentProperties { id: persisted reloadableId: "omarchy-battery" - property bool notifiedLowBattery: false + property int lowBatteryWarnedAt: 0 } WatchedFile { @@ -88,8 +89,8 @@ Item { } function checkBattery() { - var state = BatteryModel.shouldWarnLowBattery(UPower.displayDevice, UPowerDeviceState.Discharging, batteryThreshold, persisted.notifiedLowBattery) - persisted.notifiedLowBattery = state.notifiedLowBattery + var state = BatteryModel.shouldWarnLowBattery(UPower.displayDevice, UPowerDeviceState.Discharging, batteryThresholds, persisted.lowBatteryWarnedAt) + persisted.lowBatteryWarnedAt = state.warnedAt if (state.notify) sendLowBatteryWarning(state.level) } diff --git a/test/shell.d/battery-test.sh b/test/shell.d/battery-test.sh index 5f573a49aa19..f5b1e049d116 100644 --- a/test/shell.d/battery-test.sh +++ b/test/shell.d/battery-test.sh @@ -15,47 +15,69 @@ assert(battery.isDischarging({ isPresent: true, state: discharging }, dischargin assert(!battery.isDischarging({ isPresent: true, state: charging }, discharging), 'battery ignores non-discharging state') assert(!battery.isDischarging({ isPresent: false, state: discharging }, discharging), 'battery requires a present battery') +const thresholds = [20, 10] +const at = (percentage, state) => ({ isPresent: true, percentage, state }) + assertDeepEqual( - battery.shouldWarnLowBattery({ isPresent: true, percentage: 0.08, state: discharging }, discharging, 10, false), - { level: 8, notify: true, notifiedLowBattery: true }, + battery.shouldWarnLowBattery(at(0.08, discharging), discharging, thresholds, 0), + { level: 8, notify: true, warnedAt: 10 }, 'battery warns once under threshold, plugged in or not' ) assertDeepEqual( - battery.shouldWarnLowBattery({ isPresent: true, percentage: 0.08, state: charging }, discharging, 10, false), - { level: 8, notify: false, notifiedLowBattery: false }, + battery.shouldWarnLowBattery(at(0.08, charging), discharging, thresholds, 0), + { level: 8, notify: false, warnedAt: 0 }, 'battery does not warn while charging' ) assertDeepEqual( - battery.shouldWarnLowBattery({ isPresent: true, percentage: 0.08, state: discharging }, discharging, 10, true), - { level: 8, notify: false, notifiedLowBattery: true }, + battery.shouldWarnLowBattery(at(0.08, discharging), discharging, thresholds, 10), + { level: 8, notify: false, warnedAt: 10 }, 'battery keeps low-battery notified state' ) assertDeepEqual( - battery.shouldWarnLowBattery({ isPresent: true, percentage: 0.4, state: discharging }, discharging, 10, true), - { level: 40, notify: false, notifiedLowBattery: false }, + battery.shouldWarnLowBattery(at(0.4, discharging), discharging, thresholds, 10), + { level: 40, notify: false, warnedAt: 0 }, 'battery clears notified state after recovery' ) +assertDeepEqual( + battery.shouldWarnLowBattery(at(0.12, discharging), discharging, thresholds, 0), + { level: 12, notify: true, warnedAt: 20 }, + 'battery warns at 20% for a pack that cuts out above 10%' +) -let warned = false +let warnedAt = 0 +let levels = [] +for (let percent = 30; percent >= 2; percent--) { + const result = battery.shouldWarnLowBattery(at(percent / 100, discharging), discharging, thresholds, warnedAt) + warnedAt = result.warnedAt + if (result.notify) levels.push(result.level) +} +assertDeepEqual(levels, [20, 10], 'battery warns once at each threshold through one discharge') + +let warned = 0 let warnings = 0 for (const state of [discharging, charging, discharging, charging, discharging]) { - const result = battery.shouldWarnLowBattery({ isPresent: true, percentage: 0.08, state }, discharging, 10, warned) - warned = result.notifiedLowBattery + const result = battery.shouldWarnLowBattery(at(0.08, state), discharging, thresholds, warned) + warned = result.warnedAt warnings += Number(result.notify) } assertEqual(warnings, 1, 'battery warns only once across AC flaps while low') assertEqual( - battery.shouldWarnLowBattery({ isPresent: true, percentage: 0.1, state: charging }, discharging, 10, true).notifiedLowBattery, - true, + battery.shouldWarnLowBattery(at(0.1, charging), discharging, thresholds, 10).warnedAt, + 10, 'charging at the warning threshold does not re-arm the latch' ) assertEqual( - battery.shouldWarnLowBattery(null, discharging, 10, true).notifiedLowBattery, - true, + battery.shouldWarnLowBattery(null, discharging, thresholds, 10).warnedAt, + 10, 'a missing reading does not re-arm the low-battery warning' ) -const recovered = battery.shouldWarnLowBattery({ isPresent: true, percentage: 0.11, state: charging }, discharging, 10, true) -assertEqual(recovered.notifiedLowBattery, false, 'battery re-arms after recovering above the threshold') +const recovered = battery.shouldWarnLowBattery(at(0.11, charging), discharging, thresholds, 10) +assertEqual(recovered.warnedAt, 20, 'battery re-arms the 10% warning after recovering above it') +assertDeepEqual( + battery.shouldWarnLowBattery(at(0.1, discharging), discharging, thresholds, recovered.warnedAt), + { level: 10, notify: true, warnedAt: 10 }, + 'battery warns at 10% again after recovering above it, without repeating 20%' +) const reply = profile => JSON.stringify({ type: 's', data: profile }) assertEqual(battery.parseActiveProfile(reply('power-saver')), 'power-saver', 'battery parses the busctl profile reply') From ba0a904183c679a280ca2b2c6ccb7c23f27f86d3 Mon Sep 17 00:00:00 2001 From: itxkarthik Date: Thu, 26 Nov 2026 19:06:30 +0530 Subject: [PATCH 02/19] Send the 10% warning after the 20% one's hooks finish A battery-low hook still running from the 20% warning made the 10% one return early, and its level was already latched, so it was lost for the rest of the discharge. Hold it and send it when the running warning exits. --- shell/plugins/services/battery/Service.qml | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/shell/plugins/services/battery/Service.qml b/shell/plugins/services/battery/Service.qml index 2c1b717c0fae..750ee1256c2c 100644 --- a/shell/plugins/services/battery/Service.qml +++ b/shell/plugins/services/battery/Service.qml @@ -14,6 +14,8 @@ Item { // 20 is UPower's own PercentageLow, so a pack that cuts out above 10% still gets a warning. readonly property var batteryThresholds: [20, 10] property string pendingPowerSource: "" + // A warning that came due while the last one's hooks were still running. + property int pendingWarningLevel: -1 // Follows power-profiles-daemon's change signals, so nothing polls it. // Quickshell never attaches that listener if the daemon failed when the // shell started, so a one-off read on startup, on a power source change and @@ -95,7 +97,10 @@ Item { } function sendLowBatteryWarning(level) { - if (warningProcess.running) return + if (warningProcess.running) { + pendingWarningLevel = level + return + } warningProcess.command = [ "omarchy-battery-low", String(level) @@ -152,7 +157,15 @@ Item { } } - Process { id: warningProcess } + Process { + id: warningProcess + onExited: { + if (root.pendingWarningLevel < 0) return + var level = root.pendingWarningLevel + root.pendingWarningLevel = -1 + root.sendLowBatteryWarning(level) + } + } Process { id: chargeLimitProcess From a814b4bef315f146e73505ff9cb42f91ea92eb1f Mon Sep 17 00:00:00 2001 From: Alessio Attilio Date: Thu, 26 Nov 2026 15:54:07 +0100 Subject: [PATCH 03/19] Make low-battery warnings persistent and audible --- bin/omarchy-battery-low | 2 +- ...arning-sound.sample => play-warning-sound} | 0 test/shell.d/battery-test.sh | 31 +++++++++++++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) rename config/omarchy/hooks/battery-low.d/{play-warning-sound.sample => play-warning-sound} (100%) diff --git a/bin/omarchy-battery-low b/bin/omarchy-battery-low index 33c642f88410..071cb2d6b05e 100755 --- a/bin/omarchy-battery-low +++ b/bin/omarchy-battery-low @@ -13,5 +13,5 @@ fi level=$1 -omarchy-notification-send -g 󱐋 -u normal "$(omarchy-i18n battery.lowTitle)" "$(omarchy-i18n battery.lowBody "$level")" -i battery-caution -t 30000 +omarchy-notification-send -g 󱐋 -u critical "$(omarchy-i18n battery.lowTitle)" "$(omarchy-i18n battery.lowBody "$level")" -i battery-caution omarchy-hook battery-low "$level" diff --git a/config/omarchy/hooks/battery-low.d/play-warning-sound.sample b/config/omarchy/hooks/battery-low.d/play-warning-sound similarity index 100% rename from config/omarchy/hooks/battery-low.d/play-warning-sound.sample rename to config/omarchy/hooks/battery-low.d/play-warning-sound diff --git a/test/shell.d/battery-test.sh b/test/shell.d/battery-test.sh index f5b1e049d116..c7528b444077 100644 --- a/test/shell.d/battery-test.sh +++ b/test/shell.d/battery-test.sh @@ -143,3 +143,34 @@ assertEqual(battery.recordUsage(usage, { at: at(1, 30), plugged: false, screenOn assertDeepEqual(battery.parseUsage('not json'), {}, 'usage reads a broken file as empty') JS + +# The low-battery command must insist until noticed and still pass the level to hooks. +tmpdir=$(mktemp -d) +trap 'rm -rf "$tmpdir"' EXIT +mkdir -p "$tmpdir/bin" +cat >"$tmpdir/bin/omarchy-notification-send" <<'SH' +#!/bin/bash +printf '%s\0' "$@" >"$OMARCHY_TEST_NOTIFICATION_ARGS" +SH +cat >"$tmpdir/bin/omarchy-hook" <<'SH' +#!/bin/bash +printf '%s\0' "$@" >"$OMARCHY_TEST_HOOK_ARGS" +SH +chmod +x "$tmpdir/bin/omarchy-notification-send" "$tmpdir/bin/omarchy-hook" +OMARCHY_TEST_NOTIFICATION_ARGS="$tmpdir/notification-args" \ +OMARCHY_TEST_HOOK_ARGS="$tmpdir/hook-args" \ +PATH="$tmpdir/bin:$ROOT/bin:$PATH" \ + "$ROOT/bin/omarchy-battery-low" 7 + +declare -a notification_args hook_args +mapfile -d '' -t notification_args <"$tmpdir/notification-args" +mapfile -d '' -t hook_args <"$tmpdir/hook-args" +urgency_index=-1 +for ((i = 0; i < ${#notification_args[@]}; i++)); do + if [[ ${notification_args[i]} == "-u" ]]; then urgency_index=$((i + 1)); break; fi +done +(( urgency_index >= 0 )) || fail "low-battery warning sets an urgency" +[[ ${notification_args[urgency_index]} == "critical" ]] || fail "low-battery warning persists until noticed" "${notification_args[*]}" +[[ ${notification_args[*]} != *"-t 30000"* ]] || fail "low-battery warning does not set a misleading transient timeout" +[[ ${hook_args[*]} == "battery-low 7" ]] || fail "low-battery warning still calls hooks with the percentage" "${hook_args[*]}" +pass "low-battery command sends a persistent warning and runs its hook" From f858ffc645b724d57259c12571cd6d08de8d27aa Mon Sep 17 00:00:00 2001 From: Alessio Attilio Date: Thu, 26 Nov 2026 16:07:50 +0100 Subject: [PATCH 04/19] Dismiss low-battery warning after recovery --- bin/omarchy-battery-low-dismiss | 8 ++++ .../hooks/battery-low.d/play-warning-sound | 2 +- migrations/1795704847.sh | 16 ++++++++ .../plugins/services/battery/BatteryModel.js | 6 +++ shell/plugins/services/battery/Service.qml | 14 +++++++ test/shell.d/battery-test.sh | 37 +++++++++++++++++++ 6 files changed, 82 insertions(+), 1 deletion(-) create mode 100755 bin/omarchy-battery-low-dismiss create mode 100644 migrations/1795704847.sh diff --git a/bin/omarchy-battery-low-dismiss b/bin/omarchy-battery-low-dismiss new file mode 100755 index 000000000000..0f440f17e2d8 --- /dev/null +++ b/bin/omarchy-battery-low-dismiss @@ -0,0 +1,8 @@ +#!/bin/bash + +# omarchy:summary=Dismiss the resolved low-battery warning +# omarchy:hidden=true + +set -euo pipefail + +omarchy-notification-dismiss "$(omarchy-i18n battery.lowTitle)" diff --git a/config/omarchy/hooks/battery-low.d/play-warning-sound b/config/omarchy/hooks/battery-low.d/play-warning-sound index 661c9fc5a2fa..0ba333d1d3d2 100644 --- a/config/omarchy/hooks/battery-low.d/play-warning-sound +++ b/config/omarchy/hooks/battery-low.d/play-warning-sound @@ -1,7 +1,7 @@ #!/bin/bash # This hook is called with the current battery percentage when the low battery -# notification is sent. To put it into use, remove .sample from this file name. +# notification is sent. SOUND_FILE="/usr/share/sounds/freedesktop/stereo/dialog-warning.oga" diff --git a/migrations/1795704847.sh b/migrations/1795704847.sh new file mode 100644 index 000000000000..ae3bfb45e4f1 --- /dev/null +++ b/migrations/1795704847.sh @@ -0,0 +1,16 @@ +echo "Enable the default sound for low-battery warnings" + +default_hook="$OMARCHY_PATH/config/omarchy/hooks/battery-low.d/play-warning-sound" +user_hook="$HOME/.config/omarchy/hooks/battery-low.d/play-warning-sound" + +if [[ -e $user_hook || -L $user_hook ]]; then + exit 0 +fi + +[[ -f $default_hook ]] || { + echo "Missing default low-battery sound hook: $default_hook" >&2 + exit 1 +} + +mkdir -p "$(dirname "$user_hook")" +cp -- "$default_hook" "$user_hook" diff --git a/shell/plugins/services/battery/BatteryModel.js b/shell/plugins/services/battery/BatteryModel.js index c219b692bb31..8bfb6571440d 100644 --- a/shell/plugins/services/battery/BatteryModel.js +++ b/shell/plugins/services/battery/BatteryModel.js @@ -29,6 +29,11 @@ function shouldWarnLowBattery(device, dischargingState, thresholds, warnedAt) { return { level: level, notify: notify, warnedAt: warned } } +function shouldDismissLowBatteryWarning(device, dischargingState, warningVisible, recoveryThreshold) { + if (!warningVisible || !device || !device.isPresent) return false + return !isDischarging(device, dischargingState) || batteryPercentage(device) > recoveryThreshold +} + function parseActiveProfile(text) { // busctl --json=short prints {"type":"s","data":"balanced"}; an empty or // malformed reply (daemon not running) reads as no active profile. @@ -112,6 +117,7 @@ if (typeof module !== "undefined") { batteryPercentage: batteryPercentage, isDischarging: isDischarging, shouldWarnLowBattery: shouldWarnLowBattery, + shouldDismissLowBatteryWarning: shouldDismissLowBatteryWarning, parseActiveProfile: parseActiveProfile, profileAfterRead: profileAfterRead, shouldRearmChargeLimit: shouldRearmChargeLimit, diff --git a/shell/plugins/services/battery/Service.qml b/shell/plugins/services/battery/Service.qml index 750ee1256c2c..4082094a2a2b 100644 --- a/shell/plugins/services/battery/Service.qml +++ b/shell/plugins/services/battery/Service.qml @@ -13,6 +13,7 @@ Item { // 20 is UPower's own PercentageLow, so a pack that cuts out above 10% still gets a warning. readonly property var batteryThresholds: [20, 10] + readonly property int lowBatteryWarningRecoveryThreshold: 20 property string pendingPowerSource: "" // A warning that came due while the last one's hooks were still running. property int pendingWarningLevel: -1 @@ -40,6 +41,7 @@ Item { id: persisted reloadableId: "omarchy-battery" property int lowBatteryWarnedAt: 0 + property bool lowBatteryWarningVisible: false } WatchedFile { @@ -94,6 +96,9 @@ Item { var state = BatteryModel.shouldWarnLowBattery(UPower.displayDevice, UPowerDeviceState.Discharging, batteryThresholds, persisted.lowBatteryWarnedAt) persisted.lowBatteryWarnedAt = state.warnedAt if (state.notify) sendLowBatteryWarning(state.level) + if (BatteryModel.shouldDismissLowBatteryWarning(UPower.displayDevice, UPowerDeviceState.Discharging, persisted.lowBatteryWarningVisible, lowBatteryWarningRecoveryThreshold) && !warningDismissProcess.running) { + warningDismissProcess.running = true + } } function sendLowBatteryWarning(level) { @@ -105,6 +110,7 @@ Item { "omarchy-battery-low", String(level) ] + persisted.lowBatteryWarningVisible = true warningProcess.running = true } @@ -182,6 +188,14 @@ Item { } } + Process { + id: warningDismissProcess + command: ["omarchy-battery-low-dismiss"] + onExited: function(exitCode, exitStatus) { + if (exitCode === 0) persisted.lowBatteryWarningVisible = false + } + } + Process { id: powerProfileProcess onExited: { diff --git a/test/shell.d/battery-test.sh b/test/shell.d/battery-test.sh index c7528b444077..5dd0f66aafd9 100644 --- a/test/shell.d/battery-test.sh +++ b/test/shell.d/battery-test.sh @@ -78,6 +78,26 @@ assertDeepEqual( { level: 10, notify: true, warnedAt: 10 }, 'battery warns at 10% again after recovering above it, without repeating 20%' ) +assertEqual( + battery.shouldDismissLowBatteryWarning({ isPresent: true, percentage: 0.08, state: charging }, discharging, true, 20), + true, + 'battery dismisses its visible warning after charging starts' +) +assertEqual( + battery.shouldDismissLowBatteryWarning({ isPresent: true, percentage: 0.21, state: discharging }, discharging, true, 20), + true, + 'battery dismisses its visible warning after recovering above the threshold' +) +assertEqual( + battery.shouldDismissLowBatteryWarning({ isPresent: true, percentage: 0.08, state: discharging }, discharging, true, 20), + false, + 'battery keeps its warning while it is still low and discharging' +) +assertEqual( + battery.shouldDismissLowBatteryWarning(null, discharging, true, false), + false, + 'a missing battery reading does not dismiss the warning' +) const reply = profile => JSON.stringify({ type: 's', data: profile }) assertEqual(battery.parseActiveProfile(reply('power-saver')), 'power-saver', 'battery parses the busctl profile reply') @@ -174,3 +194,20 @@ done [[ ${notification_args[*]} != *"-t 30000"* ]] || fail "low-battery warning does not set a misleading transient timeout" [[ ${hook_args[*]} == "battery-low 7" ]] || fail "low-battery warning still calls hooks with the percentage" "${hook_args[*]}" pass "low-battery command sends a persistent warning and runs its hook" + +cat >"$tmpdir/bin/omarchy-notification-dismiss" <<'SH' +#!/bin/bash +printf '%s\0' "$@" >"$OMARCHY_TEST_DISMISS_ARGS" +SH +cat >"$tmpdir/bin/omarchy-i18n" <<'SH' +#!/bin/bash +printf '%s\n' 'Localized low battery' +SH +chmod +x "$tmpdir/bin/omarchy-notification-dismiss" "$tmpdir/bin/omarchy-i18n" +OMARCHY_TEST_DISMISS_ARGS="$tmpdir/dismiss-args" \ +PATH="$tmpdir/bin:$ROOT/bin:$PATH" \ + "$ROOT/bin/omarchy-battery-low-dismiss" +declare -a dismiss_args +mapfile -d '' -t dismiss_args <"$tmpdir/dismiss-args" +[[ ${dismiss_args[*]} == "Localized low battery" ]] || fail "battery dismissal uses the localized notification summary" "${dismiss_args[*]}" +pass "low-battery dismissal uses the localized notification summary" From 49ea3896fd732be6ac08141294d38169fb485938 Mon Sep 17 00:00:00 2001 From: Alessio Attilio Date: Thu, 26 Nov 2026 16:13:31 +0100 Subject: [PATCH 05/19] Handle low-battery dismissal edge cases --- migrations/1795704847.sh | 4 ++-- shell/plugins/services/battery/BatteryModel.js | 5 +++++ shell/plugins/services/battery/Service.qml | 14 ++++++++++++-- test/shell.d/battery-test.sh | 15 +++++++++++++++ 4 files changed, 34 insertions(+), 4 deletions(-) diff --git a/migrations/1795704847.sh b/migrations/1795704847.sh index ae3bfb45e4f1..dc3c69a79d03 100644 --- a/migrations/1795704847.sh +++ b/migrations/1795704847.sh @@ -8,8 +8,8 @@ if [[ -e $user_hook || -L $user_hook ]]; then fi [[ -f $default_hook ]] || { - echo "Missing default low-battery sound hook: $default_hook" >&2 - exit 1 + echo "Waiting for omarchy-settings to provide: $default_hook" >&2 + exit 75 } mkdir -p "$(dirname "$user_hook")" diff --git a/shell/plugins/services/battery/BatteryModel.js b/shell/plugins/services/battery/BatteryModel.js index 8bfb6571440d..158fa61f1e69 100644 --- a/shell/plugins/services/battery/BatteryModel.js +++ b/shell/plugins/services/battery/BatteryModel.js @@ -34,6 +34,10 @@ function shouldDismissLowBatteryWarning(device, dischargingState, warningVisible return !isDischarging(device, dischargingState) || batteryPercentage(device) > recoveryThreshold } +function shouldRearmLowBatteryWarning(device, dischargingState) { + return !!(device && device.isPresent && !isDischarging(device, dischargingState)) +} + function parseActiveProfile(text) { // busctl --json=short prints {"type":"s","data":"balanced"}; an empty or // malformed reply (daemon not running) reads as no active profile. @@ -118,6 +122,7 @@ if (typeof module !== "undefined") { isDischarging: isDischarging, shouldWarnLowBattery: shouldWarnLowBattery, shouldDismissLowBatteryWarning: shouldDismissLowBatteryWarning, + shouldRearmLowBatteryWarning: shouldRearmLowBatteryWarning, parseActiveProfile: parseActiveProfile, profileAfterRead: profileAfterRead, shouldRearmChargeLimit: shouldRearmChargeLimit, diff --git a/shell/plugins/services/battery/Service.qml b/shell/plugins/services/battery/Service.qml index 4082094a2a2b..686aed07b27f 100644 --- a/shell/plugins/services/battery/Service.qml +++ b/shell/plugins/services/battery/Service.qml @@ -17,6 +17,7 @@ Item { property string pendingPowerSource: "" // A warning that came due while the last one's hooks were still running. property int pendingWarningLevel: -1 + property bool warningDismissRearmRequested: false // Follows power-profiles-daemon's change signals, so nothing polls it. // Quickshell never attaches that listener if the daemon failed when the // shell started, so a one-off read on startup, on a power source change and @@ -96,7 +97,9 @@ Item { var state = BatteryModel.shouldWarnLowBattery(UPower.displayDevice, UPowerDeviceState.Discharging, batteryThresholds, persisted.lowBatteryWarnedAt) persisted.lowBatteryWarnedAt = state.warnedAt if (state.notify) sendLowBatteryWarning(state.level) - if (BatteryModel.shouldDismissLowBatteryWarning(UPower.displayDevice, UPowerDeviceState.Discharging, persisted.lowBatteryWarningVisible, lowBatteryWarningRecoveryThreshold) && !warningDismissProcess.running) { + var shouldDismissWarning = BatteryModel.shouldDismissLowBatteryWarning(UPower.displayDevice, UPowerDeviceState.Discharging, persisted.lowBatteryWarningVisible, lowBatteryWarningRecoveryThreshold) + if (shouldDismissWarning && !warningDismissProcess.running) { + warningDismissRearmRequested = warningDismissRearmRequested || BatteryModel.shouldRearmLowBatteryWarning(UPower.displayDevice, UPowerDeviceState.Discharging) warningDismissProcess.running = true } } @@ -192,7 +195,14 @@ Item { id: warningDismissProcess command: ["omarchy-battery-low-dismiss"] onExited: function(exitCode, exitStatus) { - if (exitCode === 0) persisted.lowBatteryWarningVisible = false + if (exitCode === 0) { + persisted.lowBatteryWarningVisible = false + if (root.warningDismissRearmRequested) { + persisted.notifiedLowBattery = false + root.warningDismissRearmRequested = false + Qt.callLater(root.checkBattery) + } + } } } diff --git a/test/shell.d/battery-test.sh b/test/shell.d/battery-test.sh index 5dd0f66aafd9..c4e4fa567f21 100644 --- a/test/shell.d/battery-test.sh +++ b/test/shell.d/battery-test.sh @@ -98,6 +98,21 @@ assertEqual( false, 'a missing battery reading does not dismiss the warning' ) +assertEqual( + battery.shouldRearmLowBatteryWarning({ isPresent: true, state: charging }, discharging), + true, + 'charging after automatic dismissal re-arms the low-battery warning' +) +assertEqual( + battery.shouldRearmLowBatteryWarning({ isPresent: true, state: discharging }, discharging), + false, + 'continued discharging does not re-arm a dismissed warning' +) +assertEqual( + battery.shouldRearmLowBatteryWarning(null, discharging), + false, + 'a missing battery reading does not re-arm the warning' +) const reply = profile => JSON.stringify({ type: 's', data: profile }) assertEqual(battery.parseActiveProfile(reply('power-saver')), 'power-saver', 'battery parses the busctl profile reply') From 25ed413e1043c7851b2b5931c219d31a50c46286 Mon Sep 17 00:00:00 2001 From: Alessio Attilio Date: Thu, 26 Nov 2026 16:48:00 +0100 Subject: [PATCH 06/19] Keep battery alerts transient across shell restarts --- bin/omarchy-battery-low | 2 +- shell/plugins/services/battery/Service.qml | 10 ++++++---- test/shell.d/battery-test.sh | 8 +++++--- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/bin/omarchy-battery-low b/bin/omarchy-battery-low index 071cb2d6b05e..beec9fc1a5c0 100755 --- a/bin/omarchy-battery-low +++ b/bin/omarchy-battery-low @@ -13,5 +13,5 @@ fi level=$1 -omarchy-notification-send -g 󱐋 -u critical "$(omarchy-i18n battery.lowTitle)" "$(omarchy-i18n battery.lowBody "$level")" -i battery-caution +omarchy-notification-send --transient -g 󱐋 -u critical "$(omarchy-i18n battery.lowTitle)" "$(omarchy-i18n battery.lowBody "$level")" -i battery-caution omarchy-hook battery-low "$level" diff --git a/shell/plugins/services/battery/Service.qml b/shell/plugins/services/battery/Service.qml index 686aed07b27f..92792813f100 100644 --- a/shell/plugins/services/battery/Service.qml +++ b/shell/plugins/services/battery/Service.qml @@ -14,10 +14,13 @@ Item { // 20 is UPower's own PercentageLow, so a pack that cuts out above 10% still gets a warning. readonly property var batteryThresholds: [20, 10] readonly property int lowBatteryWarningRecoveryThreshold: 20 + property bool notifiedLowBattery: false property string pendingPowerSource: "" // A warning that came due while the last one's hooks were still running. property int pendingWarningLevel: -1 property bool warningDismissRearmRequested: false + // Not persisted: a shell restart while the battery is still low warns again. + property int lowBatteryWarnedAt: 0 // Follows power-profiles-daemon's change signals, so nothing polls it. // Quickshell never attaches that listener if the daemon failed when the // shell started, so a one-off read on startup, on a power source change and @@ -41,7 +44,6 @@ Item { PersistentProperties { id: persisted reloadableId: "omarchy-battery" - property int lowBatteryWarnedAt: 0 property bool lowBatteryWarningVisible: false } @@ -94,8 +96,8 @@ Item { } function checkBattery() { - var state = BatteryModel.shouldWarnLowBattery(UPower.displayDevice, UPowerDeviceState.Discharging, batteryThresholds, persisted.lowBatteryWarnedAt) - persisted.lowBatteryWarnedAt = state.warnedAt + var state = BatteryModel.shouldWarnLowBattery(UPower.displayDevice, UPowerDeviceState.Discharging, batteryThresholds, lowBatteryWarnedAt) + lowBatteryWarnedAt = state.warnedAt if (state.notify) sendLowBatteryWarning(state.level) var shouldDismissWarning = BatteryModel.shouldDismissLowBatteryWarning(UPower.displayDevice, UPowerDeviceState.Discharging, persisted.lowBatteryWarningVisible, lowBatteryWarningRecoveryThreshold) if (shouldDismissWarning && !warningDismissProcess.running) { @@ -198,7 +200,7 @@ Item { if (exitCode === 0) { persisted.lowBatteryWarningVisible = false if (root.warningDismissRearmRequested) { - persisted.notifiedLowBattery = false + root.lowBatteryWarnedAt = 0 root.warningDismissRearmRequested = false Qt.callLater(root.checkBattery) } diff --git a/test/shell.d/battery-test.sh b/test/shell.d/battery-test.sh index c4e4fa567f21..0dee66af3048 100644 --- a/test/shell.d/battery-test.sh +++ b/test/shell.d/battery-test.sh @@ -179,7 +179,8 @@ assertDeepEqual(battery.parseUsage('not json'), {}, 'usage reads a broken file a JS -# The low-battery command must insist until noticed and still pass the level to hooks. +# The low-battery command must stay critical in-session, avoid restoring stale +# warnings after shell restarts and still pass the level to hooks. tmpdir=$(mktemp -d) trap 'rm -rf "$tmpdir"' EXIT mkdir -p "$tmpdir/bin" @@ -205,10 +206,11 @@ for ((i = 0; i < ${#notification_args[@]}; i++)); do if [[ ${notification_args[i]} == "-u" ]]; then urgency_index=$((i + 1)); break; fi done (( urgency_index >= 0 )) || fail "low-battery warning sets an urgency" -[[ ${notification_args[urgency_index]} == "critical" ]] || fail "low-battery warning persists until noticed" "${notification_args[*]}" +[[ ${notification_args[urgency_index]} == "critical" ]] || fail "low-battery warning is critical" "${notification_args[*]}" +[[ ${notification_args[*]} == *"--transient"* ]] || fail "low-battery warning is not restored after a shell restart" "${notification_args[*]}" [[ ${notification_args[*]} != *"-t 30000"* ]] || fail "low-battery warning does not set a misleading transient timeout" [[ ${hook_args[*]} == "battery-low 7" ]] || fail "low-battery warning still calls hooks with the percentage" "${hook_args[*]}" -pass "low-battery command sends a persistent warning and runs its hook" +pass "low-battery command sends a critical transient warning and runs its hook" cat >"$tmpdir/bin/omarchy-notification-dismiss" <<'SH' #!/bin/bash From caaa2bbb243d2aae2befbaca01dbe0d5f6aa8896 Mon Sep 17 00:00:00 2001 From: Alessio Attilio Date: Mon, 30 Nov 2026 19:35:18 +0100 Subject: [PATCH 07/19] Retry battery warning after an active send --- shell/plugins/services/battery/Service.qml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/shell/plugins/services/battery/Service.qml b/shell/plugins/services/battery/Service.qml index 92792813f100..4a4976af505b 100644 --- a/shell/plugins/services/battery/Service.qml +++ b/shell/plugins/services/battery/Service.qml @@ -109,7 +109,7 @@ Item { function sendLowBatteryWarning(level) { if (warningProcess.running) { pendingWarningLevel = level - return + return true } warningProcess.command = [ "omarchy-battery-low", @@ -117,6 +117,7 @@ Item { ] persisted.lowBatteryWarningVisible = true warningProcess.running = true + return true } function applyPowerProfile() { From 5267c4fb3ec13059b0681b9262cb4cd4e46cc06b Mon Sep 17 00:00:00 2001 From: Shan Rizvi Date: Sat, 28 Nov 2026 18:10:23 -0500 Subject: [PATCH 08/19] Pin upower locale and parse all time units in omarchy-battery-status --- bin/omarchy-battery-status | 12 +++- test/shell.d/battery-status-test.sh | 90 +++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 3 deletions(-) diff --git a/bin/omarchy-battery-status b/bin/omarchy-battery-status index 320a08fbd8e2..1c05ebc8bed3 100755 --- a/bin/omarchy-battery-status +++ b/bin/omarchy-battery-status @@ -45,13 +45,13 @@ battery="" battery_info="" while read -r candidate; do [[ -n $candidate ]] || continue - candidate_info=$(upower -i "$candidate" 2>/dev/null) || continue + candidate_info=$(LC_ALL=C upower -i "$candidate" 2>/dev/null) || continue if grep -qE '^\s*power supply:\s+yes' <<<"$candidate_info"; then battery=$candidate battery_info=$candidate_info break fi -done < <(upower -e 2>/dev/null | grep '/battery_') +done < <(LC_ALL=C upower -e 2>/dev/null | grep '/battery_') [[ -z $battery ]] && exit 0 percentage=$(awk '/percentage/ { print int($2); exit }' <<<"$battery_info") @@ -60,7 +60,13 @@ energy=$(awk '/^ *energy:/ { print $2; exit }' <<<"$battery_info") energy_full=$(awk '/energy-full:/ { print $2; exit }' <<<"$battery_info") energy_full_design=$(awk '/energy-full-design:/ { print $2; exit }' <<<"$battery_info") upower_capacity=$(awk '/^ *capacity:/ { gsub(/%/, "", $2); print $2; exit }' <<<"$battery_info") -upower_hours=$(awk '/time to (empty|full)/ { print ($5 ~ /^minute/ ? $4 / 60 : $4); exit }' <<<"$battery_info") +upower_hours=$(awk '/time to (empty|full)/ { + if ($5 ~ /^second/) printf "%.17g", $4 / 3600 + else if ($5 ~ /^minute/) printf "%.17g", $4 / 60 + else if ($5 ~ /^day/) printf "%.17g", $4 * 24 + else print $4 + exit +}' <<<"$battery_info") power_rate_raw=$(awk '/energy-rate/ { print $2; exit }' <<<"$battery_info") native_path=$(awk '/native-path/ { print $2; exit }' <<<"$battery_info") battery_path="$power_supply_path/$native_path" diff --git a/test/shell.d/battery-status-test.sh b/test/shell.d/battery-status-test.sh index a409fdcbff37..2f97bb501956 100644 --- a/test/shell.d/battery-status-test.sh +++ b/test/shell.d/battery-status-test.sh @@ -366,3 +366,93 @@ env "${limit_env[@]}" "$ROOT/bin/omarchy-battery-limit" toggle env "${limit_env[@]}" "$ROOT/bin/omarchy-battery-limit" off [[ $(env "${limit_env[@]}" "$ROOT/bin/omarchy-battery-limit" status) == "off" ]] || fail "battery-limit disables charge limit" pass "omarchy-battery-limit handles status, on, off, once, and toggle" + +# Comma-decimal locales (de_DE, fr_FR, etc.) make upower print commas unless +# invoked under LC_ALL=C; awk must still receive dot-decimal numbers. +locale_dir="$tmp_dir/locale" +mkdir -p "$locale_dir/bin" "$locale_dir/power/BAT0" +cat >"$locale_dir/bin/upower" <<'STUB' +#!/bin/bash + +if [[ $1 == "-e" ]]; then + echo "/org/freedesktop/UPower/devices/battery_BAT0" + exit 0 +fi + +if [[ $1 == "-i" ]]; then + locale=${LC_ALL:-${LC_NUMERIC:-}} + if [[ $locale == "C" || $locale == C.* || $locale == "POSIX" ]]; then + sep="." + else + sep="," + fi + cat </dev/null || fail "comma-decimal locale does not truncate power rate" "$locale_out" +grep -Fx $'health\t100%' <<<"$locale_out" >/dev/null || fail "comma-decimal locale does not truncate battery health" "$locale_out" +grep -Fx $'time\t2h' <<<"$locale_out" >/dev/null || fail "comma-decimal locale does not skew time remaining" "$locale_out" + +subwatt_out=$(env -u LC_ALL -u LC_NUMERIC OMARCHY_TEST_RATE_INT=0 OMARCHY_POWER_SUPPLY_PATH="$locale_dir/power" PATH="$locale_dir/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell) +grep -Fx $'rate\t0.9W' <<<"$subwatt_out" >/dev/null || fail "comma-decimal locale does not truncate sub-1W rate to 0W" "$subwatt_out" +subwatt_line=$(env -u LC_ALL -u LC_NUMERIC OMARCHY_TEST_RATE_INT=0 OMARCHY_POWER_SUPPLY_PATH="$locale_dir/power" PATH="$locale_dir/bin:$PATH" "$ROOT/bin/omarchy-battery-status") +[[ $subwatt_line == *$' '"0.9W"* ]] || fail "sub-1W rate is not treated as charge_idle under comma-decimal locale" "$subwatt_line" +pass "battery status pins UPower locale so comma-decimal readings are not truncated" + +# UPower emits seconds, minutes, hours, or days for time-to-full/empty; +# sub-minute durations must not be interpreted as hours. +units_dir="$tmp_dir/units" +mkdir -p "$units_dir/bin" "$units_dir/power/BAT0" +cat >"$units_dir/bin/upower" <<'STUB' +#!/bin/bash + +if [[ $1 == "-e" ]]; then + echo "/org/freedesktop/UPower/devices/battery_BAT0" + exit 0 +fi + +if [[ $1 == "-i" ]]; then + cat </dev/null || fail "UPower seconds duration converts to minutes instead of hours" "$seconds_out" + +minutes_out=$(OMARCHY_TEST_TIME="15.5 minutes" OMARCHY_POWER_SUPPLY_PATH="$units_dir/power" PATH="$units_dir/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell) +grep -Fx $'time\t16m' <<<"$minutes_out" >/dev/null || fail "UPower minutes duration converts accurately" "$minutes_out" + +hours_out=$(OMARCHY_TEST_TIME="2.5 hours" OMARCHY_POWER_SUPPLY_PATH="$units_dir/power" PATH="$units_dir/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell) +grep -Fx $'time\t2h 30m' <<<"$hours_out" >/dev/null || fail "UPower hours duration converts accurately" "$hours_out" + +days_out=$(OMARCHY_TEST_TIME="1.5 days" OMARCHY_POWER_SUPPLY_PATH="$units_dir/power" PATH="$units_dir/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell) +grep -Fx $'time\t36h' <<<"$days_out" >/dev/null || fail "UPower days duration converts to hours" "$days_out" +pass "battery status parses UPower seconds, minutes, hours, and days" From 287ad921e8e0440370b4e53db128216ef2de4dd6 Mon Sep 17 00:00:00 2001 From: Brandon Williams Date: Fri, 27 Nov 2026 15:39:21 -0500 Subject: [PATCH 09/19] Show the Surface Pro 11's battery cycle count from the Surface EC The Surface Pro 11's battery manager reports cycle_count 0: its ADSP firmware keeps no count. The Surface EC does, and microsoft-surface-pro-11-support writes it to /run/surface-pro-11-battery/cycle-count. omarchy-battery-status takes that file when the battery's own count is 0 or missing; a real count still wins and a file that isn't a number is ignored. Co-Authored-By: Claude Opus 5.5 --- bin/omarchy-battery-status | 7 +++++++ test/shell.d/battery-status-test.sh | 22 ++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/bin/omarchy-battery-status b/bin/omarchy-battery-status index 1c05ebc8bed3..0c30a561b4d8 100755 --- a/bin/omarchy-battery-status +++ b/bin/omarchy-battery-status @@ -7,6 +7,7 @@ shell_output=false power_supply_path="${OMARCHY_POWER_SUPPLY_PATH:-/sys/class/power_supply}" sleep_run_dir="${OMARCHY_SLEEP_RUN_DIR:-/run/omarchy}" battery_state_dir="${OMARCHY_BATTERY_STATE_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/battery}" +surface_battery_dir="${OMARCHY_SURFACE_BATTERY_DIR:-/run/surface-pro-11-battery}" case "${1:-}" in "") @@ -224,6 +225,12 @@ if [[ $shell_output == "true" ]]; then cycles="" [[ ! -r $battery_path/cycle_count ]] || cycles=$(<"$battery_path/cycle_count") [[ -n $cycles ]] || cycles=$(cat "$power_supply_path"/BAT*/cycle_count 2>/dev/null | head -1) + # The Surface Pro 11's battery manager firmware keeps no count and reads 0; + # the Surface EC has it, and microsoft-surface-pro-11-support writes it here. + if [[ -z $cycles || $cycles == "0" ]]; then + surface_cycles=$(read_sysfs_number "$surface_battery_dir/cycle-count" || true) + [[ -z $surface_cycles ]] || cycles=$surface_cycles + fi [[ -n $cycles ]] && printf 'cycles\t%s\n' "$cycles" diff --git a/test/shell.d/battery-status-test.sh b/test/shell.d/battery-status-test.sh index 2f97bb501956..781ec579b7e0 100644 --- a/test/shell.d/battery-status-test.sh +++ b/test/shell.d/battery-status-test.sh @@ -86,6 +86,28 @@ unknown_rate_output=$(OMARCHY_TEST_NATIVE_PATH=CMB0 OMARCHY_POWER_SUPPLY_PATH="$ grep -Fx $'rate\t7.3W' <<<"$unknown_rate_output" >/dev/null || fail "an unreadable current_now leaves UPower's rate in place" "$unknown_rate_output" pass "battery status keeps UPower's rate when the battery has no live reading" +# The Surface Pro 11's battery reads 0 cycles; its support package writes the +# Surface EC's count to a file, which stands in for a 0 but never a real count. +surface_dir="$tmp_dir/surface-pro-11-battery" +mkdir -p "$surface_dir" +cycles_output() { + OMARCHY_SURFACE_BATTERY_DIR="$surface_dir" OMARCHY_TEST_NATIVE_PATH=CMB0 OMARCHY_POWER_SUPPLY_PATH="$tmp_dir/power" \ + PATH="$tmp_dir/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell +} +printf '0\n' >"$tmp_dir/power/CMB0/cycle_count" +grep -Fx $'cycles\t0' <<<"$(cycles_output)" >/dev/null || fail "a battery's 0 cycles stand without the Surface EC's count" +printf '148\n' >"$surface_dir/cycle-count" +grep -Fx $'cycles\t148' <<<"$(cycles_output)" >/dev/null || fail "the Surface EC's cycle count replaces the battery's 0" +rm "$tmp_dir/power/CMB0/cycle_count" +grep -Fx $'cycles\t148' <<<"$(cycles_output)" >/dev/null || fail "the Surface EC's cycle count stands in for a missing one" +printf '212\n' >"$tmp_dir/power/CMB0/cycle_count" +grep -Fx $'cycles\t212' <<<"$(cycles_output)" >/dev/null || fail "a battery's own cycle count wins over the Surface EC's" +printf '0\n' >"$tmp_dir/power/CMB0/cycle_count" +printf 'unknown\n' >"$surface_dir/cycle-count" +grep -Fx $'cycles\t0' <<<"$(cycles_output)" >/dev/null || fail "an unreadable Surface EC count is ignored" +rm -r "$surface_dir" "$tmp_dir/power/CMB0/cycle_count" +pass "battery status takes the Surface EC's cycle count when the battery reports none" + # An 80% hold threshold doesn't trip while the battery is still below it. hold_dir=$(mktemp -d) trap 'rm -rf "$tmp_dir" "$hold_dir"' EXIT From cdb1c989ac196e40f8d1676049cc46de9cfeaa5d Mon Sep 17 00:00:00 2001 From: emrgim <275777976+emrgim@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:56:34 +0400 Subject: [PATCH 10/19] Announce when the charger is connected Send a transient toast when line power arrives after the machine has been on battery. A flip shorter than two seconds is ignored, so a USB-C renegotiation or a UPower reading that settles at startup does not announce a charger that was not just plugged in. --- bin/omarchy-battery-plugged | 16 ++++++++ default/i18n/en/cli.json | 2 + docs/notifications.md | 1 + .../plugins/services/battery/BatteryModel.js | 15 ++++++- shell/plugins/services/battery/Service.qml | 39 +++++++++++++++++++ test/shell.d/battery-test.sh | 24 ++++++++++++ 6 files changed, 96 insertions(+), 1 deletion(-) create mode 100755 bin/omarchy-battery-plugged diff --git a/bin/omarchy-battery-plugged b/bin/omarchy-battery-plugged new file mode 100755 index 000000000000..d040c7bb5ffa --- /dev/null +++ b/bin/omarchy-battery-plugged @@ -0,0 +1,16 @@ +#!/bin/bash + +# omarchy:summary=Announce that the charger was just connected. +# omarchy:hidden=true + +set -euo pipefail + +# Nerd Font power plug. The icon theme is tried first; this is the fallback. +glyph=$'\U000f06a5' +status=$(omarchy-battery-status || true) + +if [[ -n $status ]]; then + omarchy-notification-send -g "$glyph" -u normal "$(omarchy-i18n battery.chargerConnectedTitle)" "$status" -i ac-adapter --transient +else + omarchy-notification-send -g "$glyph" -u normal "$(omarchy-i18n battery.chargerConnectedTitle)" "$(omarchy-i18n battery.chargerConnectedBody)" -i ac-adapter --transient +fi diff --git a/default/i18n/en/cli.json b/default/i18n/en/cli.json index 867f0dabcfbe..17211458d3e8 100644 --- a/default/i18n/en/cli.json +++ b/default/i18n/en/cli.json @@ -63,6 +63,8 @@ "audio.micOn": "Microphone on", "audio.noDevices": "No audio devices found", "audio.noMicrophone": "No microphone found", + "battery.chargerConnectedBody": "Now charging", + "battery.chargerConnectedTitle": "Charger connected", "battery.durationHours": "%1h", "battery.durationHoursMinutes": "%1h %2m", "battery.durationMinutes": "%1m", diff --git a/docs/notifications.md b/docs/notifications.md index 054af508c6f1..9ee0270f6a56 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -207,6 +207,7 @@ The `notifications` IPC target also answers `ping` (used by `omarchy-notificatio Everything goes through the same sender contract, so the pieces are small: - **Low battery** — `omarchy-battery-low` sends a normal toast that expires after 30 seconds (paused, like any card, while the deck is open) and runs the `battery-low` hook. Not critical: a critical toast never expires and comes back on every shell start, so the warning would outlive the charger going in. As an `omarchy-action` toast it still gets through Do Not Disturb. +- **Charger connected** — when line power arrives after the machine has been on battery, `omarchy-battery-plugged` sends a normal transient toast. A flip shorter than two seconds is ignored, so a USB-C renegotiation or a UPower reading that settles at startup does not announce a charger that was not just plugged in. - **Crash capture** — `omarchy-crash-watch` follows the systemd-coredump journal stream and announces each crashed program (deduped per minute) as a critical toast whose click runs `omarchy-agent-crash` (via `--exec`, so a diff --git a/shell/plugins/services/battery/BatteryModel.js b/shell/plugins/services/battery/BatteryModel.js index 158fa61f1e69..31232b1fce69 100644 --- a/shell/plugins/services/battery/BatteryModel.js +++ b/shell/plugins/services/battery/BatteryModel.js @@ -116,6 +116,17 @@ function recordUsage(hours, held, now, maxGap) { return next } +// Line power just arrived. Ignore a flap shorter than this: USB-C PD +// renegotiation and the first UPower reading at startup both look like a +// plug-in if the machine was only "on battery" for a moment. +var chargerAnnounceMinMs = 2000 + +function shouldAnnounceChargerConnected(wasOnBattery, onBattery, batteryPresent, onBatteryForMs) { + if (!batteryPresent) return false + if (wasOnBattery !== true || onBattery !== false) return false + return onBatteryForMs >= chargerAnnounceMinMs +} + if (typeof module !== "undefined") { module.exports = { batteryPercentage: batteryPercentage, @@ -127,6 +138,8 @@ if (typeof module !== "undefined") { profileAfterRead: profileAfterRead, shouldRearmChargeLimit: shouldRearmChargeLimit, parseUsage: parseUsage, - recordUsage: recordUsage + recordUsage: recordUsage, + chargerAnnounceMinMs: chargerAnnounceMinMs, + shouldAnnounceChargerConnected: shouldAnnounceChargerConnected } } diff --git a/shell/plugins/services/battery/Service.qml b/shell/plugins/services/battery/Service.qml index 4a4976af505b..8d4ea85da682 100644 --- a/shell/plugins/services/battery/Service.qml +++ b/shell/plugins/services/battery/Service.qml @@ -31,6 +31,8 @@ Item { property int powerProfileReadSignals: 0 property int chargeLimitSignals: 0 property bool lastOnBattery: UPower.onBattery + // When line power last dropped. -1 while on AC, or before the first on-battery reading. + property double onBatterySinceMs: -1 readonly property string stateDir: { var stateHome = Quickshell.env("XDG_STATE_HOME") @@ -169,6 +171,28 @@ Item { } } + function noteOnBatteryClock() { + if (UPower.onBattery && root.onBatterySinceMs < 0) + root.onBatterySinceMs = Date.now() + } + + function considerChargerConnected(wasOnBattery) { + var elapsed = root.onBatterySinceMs < 0 ? -1 : Date.now() - root.onBatterySinceMs + var present = !!(UPower.displayDevice && UPower.displayDevice.isPresent) + if (BatteryModel.shouldAnnounceChargerConnected(wasOnBattery, UPower.onBattery, present, elapsed)) + chargerAnnounceDebounce.restart() + else if (UPower.onBattery) + chargerAnnounceDebounce.stop() + if (UPower.onBattery) root.noteOnBatteryClock() + else root.onBatterySinceMs = -1 + } + + function sendChargerConnected() { + if (chargerAnnounceProcess.running) return + chargerAnnounceProcess.command = ["omarchy-battery-plugged"] + chargerAnnounceProcess.running = true + } + Process { id: warningProcess onExited: { @@ -179,6 +203,19 @@ Item { } } + Process { id: chargerAnnounceProcess } + + // Confirm the plug survived a moment, so a double signal does not toast twice. + Timer { + id: chargerAnnounceDebounce + interval: 500 + onTriggered: { + if (UPower.onBattery) return + if (!UPower.displayDevice || !UPower.displayDevice.isPresent) return + root.sendChargerConnected() + } + } + Process { id: chargeLimitProcess onExited: root.refreshChargeLimit() @@ -278,6 +315,7 @@ Item { root.checkTopUpOnceRearm() } } + root.considerChargerConnected(wasOnBattery) } } @@ -291,6 +329,7 @@ Item { } Component.onCompleted: { + root.noteOnBatteryClock() root.refreshPowerProfile() root.checkTopUpOnceRearm() } diff --git a/test/shell.d/battery-test.sh b/test/shell.d/battery-test.sh index 0dee66af3048..f8c4edbb7427 100644 --- a/test/shell.d/battery-test.sh +++ b/test/shell.d/battery-test.sh @@ -177,6 +177,30 @@ assertDeepEqual(Object.keys(aged), [String(at(30, 0))], 'usage drops hours older assertEqual(battery.recordUsage(usage, { at: at(1, 30), plugged: false, screenOn: false, level: 79 }, { at: at(60, 0), plugged: false, screenOn: false, level: 20 }, 90)[at(60, 0)].used, 0, 'usage leaves out a drop that spans more than the day it keeps') assertDeepEqual(battery.parseUsage('not json'), {}, 'usage reads a broken file as empty') +assert( + battery.shouldAnnounceChargerConnected(true, false, true, battery.chargerAnnounceMinMs), + 'battery announces a charger connected after time on battery' +) +assert( + !battery.shouldAnnounceChargerConnected(true, false, true, battery.chargerAnnounceMinMs - 1), + 'battery ignores a power-source flap shorter than the announce window' +) +assert( + !battery.shouldAnnounceChargerConnected(true, false, false, 5000), + 'battery does not announce a charger when no battery is present' +) +assert( + !battery.shouldAnnounceChargerConnected(false, false, true, 5000), + 'battery does not announce when already on external power' +) +assert( + !battery.shouldAnnounceChargerConnected(true, true, true, 5000), + 'battery does not announce while still on battery' +) +assert( + !battery.shouldAnnounceChargerConnected(false, true, true, 5000), + 'battery does not announce when the charger is removed' +) JS # The low-battery command must stay critical in-session, avoid restoring stale From 36550608463c3fc72afe08b45f863d814c3a4a83 Mon Sep 17 00:00:00 2001 From: emrgim <275777976+emrgim@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:11:22 +0400 Subject: [PATCH 11/19] Keep the charger toast across a short reconnect A USB-C blip during the confirm wait was clearing the on-battery clock, so plugging back in within two seconds never qualified. A confirmation already earned stays pending across that blip and is dropped only if the machine stays on battery through the window. --- docs/notifications.md | 2 +- .../plugins/services/battery/BatteryModel.js | 34 ++++++++++++- shell/plugins/services/battery/Service.qml | 48 ++++++++++++------- test/shell.d/battery-test.sh | 13 +++++ 4 files changed, 78 insertions(+), 19 deletions(-) diff --git a/docs/notifications.md b/docs/notifications.md index 9ee0270f6a56..12215f8e6124 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -207,7 +207,7 @@ The `notifications` IPC target also answers `ping` (used by `omarchy-notificatio Everything goes through the same sender contract, so the pieces are small: - **Low battery** — `omarchy-battery-low` sends a normal toast that expires after 30 seconds (paused, like any card, while the deck is open) and runs the `battery-low` hook. Not critical: a critical toast never expires and comes back on every shell start, so the warning would outlive the charger going in. As an `omarchy-action` toast it still gets through Do Not Disturb. -- **Charger connected** — when line power arrives after the machine has been on battery, `omarchy-battery-plugged` sends a normal transient toast. A flip shorter than two seconds is ignored, so a USB-C renegotiation or a UPower reading that settles at startup does not announce a charger that was not just plugged in. +- **Charger connected** — when line power arrives after the machine has been on battery, `omarchy-battery-plugged` sends a normal transient toast. A flip shorter than two seconds is ignored, so a USB-C renegotiation or a UPower reading that settles at startup does not announce a charger that was not just plugged in. A confirmation already earned survives a reconnect inside that window, and is dropped only if the machine stays on battery through it. - **Crash capture** — `omarchy-crash-watch` follows the systemd-coredump journal stream and announces each crashed program (deduped per minute) as a critical toast whose click runs `omarchy-agent-crash` (via `--exec`, so a diff --git a/shell/plugins/services/battery/BatteryModel.js b/shell/plugins/services/battery/BatteryModel.js index 31232b1fce69..dce5f9e35305 100644 --- a/shell/plugins/services/battery/BatteryModel.js +++ b/shell/plugins/services/battery/BatteryModel.js @@ -127,6 +127,37 @@ function shouldAnnounceChargerConnected(wasOnBattery, onBattery, batteryPresent, return onBatteryForMs >= chargerAnnounceMinMs } +// A qualified plug stays pending across a power blip shorter than +// chargerAnnounceMinMs. Returning to AC while it is still pending announces +// again. Staying on battery through that window drops it: the charger is out. +function stepChargerAnnounce(state, onBattery, batteryPresent, nowMs) { + var sinceMs = state && state.sinceMs != null ? state.sinceMs : -1 + var pending = !!(state && state.pending) + var wasOnBattery = !!(state && state.onBattery) + var announce = false + + if (!batteryPresent) { + return { onBattery: !!onBattery, sinceMs: -1, pending: false, announce: false } + } + + if (wasOnBattery && !onBattery) { + var elapsed = sinceMs < 0 ? -1 : nowMs - sinceMs + if (pending || elapsed >= chargerAnnounceMinMs) { + pending = true + announce = true + } + sinceMs = -1 + } else if (!wasOnBattery && onBattery) { + if (sinceMs < 0) sinceMs = nowMs + } else if (onBattery && pending && sinceMs >= 0 && nowMs - sinceMs >= chargerAnnounceMinMs) { + pending = false + } else if (onBattery && sinceMs < 0) { + sinceMs = nowMs + } + + return { onBattery: !!onBattery, sinceMs: sinceMs, pending: pending, announce: announce } +} + if (typeof module !== "undefined") { module.exports = { batteryPercentage: batteryPercentage, @@ -140,6 +171,7 @@ if (typeof module !== "undefined") { parseUsage: parseUsage, recordUsage: recordUsage, chargerAnnounceMinMs: chargerAnnounceMinMs, - shouldAnnounceChargerConnected: shouldAnnounceChargerConnected + shouldAnnounceChargerConnected: shouldAnnounceChargerConnected, + stepChargerAnnounce: stepChargerAnnounce } } diff --git a/shell/plugins/services/battery/Service.qml b/shell/plugins/services/battery/Service.qml index 8d4ea85da682..e4f4217ea092 100644 --- a/shell/plugins/services/battery/Service.qml +++ b/shell/plugins/services/battery/Service.qml @@ -31,8 +31,9 @@ Item { property int powerProfileReadSignals: 0 property int chargeLimitSignals: 0 property bool lastOnBattery: UPower.onBattery - // When line power last dropped. -1 while on AC, or before the first on-battery reading. - property double onBatterySinceMs: -1 + property bool chargerAnnounceOnBattery: UPower.onBattery + property double chargerOnBatterySinceMs: -1 + property bool chargerAnnouncePending: false readonly property string stateDir: { var stateHome = Quickshell.env("XDG_STATE_HOME") @@ -171,23 +172,24 @@ Item { } } - function noteOnBatteryClock() { - if (UPower.onBattery && root.onBatterySinceMs < 0) - root.onBatterySinceMs = Date.now() - } - - function considerChargerConnected(wasOnBattery) { - var elapsed = root.onBatterySinceMs < 0 ? -1 : Date.now() - root.onBatterySinceMs + function applyChargerAnnounce(nowMs) { var present = !!(UPower.displayDevice && UPower.displayDevice.isPresent) - if (BatteryModel.shouldAnnounceChargerConnected(wasOnBattery, UPower.onBattery, present, elapsed)) - chargerAnnounceDebounce.restart() - else if (UPower.onBattery) - chargerAnnounceDebounce.stop() - if (UPower.onBattery) root.noteOnBatteryClock() - else root.onBatterySinceMs = -1 + var next = BatteryModel.stepChargerAnnounce({ + onBattery: root.chargerAnnounceOnBattery, + sinceMs: root.chargerOnBatterySinceMs, + pending: root.chargerAnnouncePending + }, UPower.onBattery, present, nowMs) + root.chargerAnnounceOnBattery = next.onBattery + root.chargerOnBatterySinceMs = next.sinceMs + root.chargerAnnouncePending = next.pending + if (next.announce) chargerAnnounceDebounce.restart() + else if (UPower.onBattery) chargerAnnounceDebounce.stop() + if (next.pending && UPower.onBattery) chargerAnnounceExpire.restart() + else chargerAnnounceExpire.stop() } function sendChargerConnected() { + root.chargerAnnouncePending = false if (chargerAnnounceProcess.running) return chargerAnnounceProcess.command = ["omarchy-battery-plugged"] chargerAnnounceProcess.running = true @@ -206,6 +208,8 @@ Item { Process { id: chargerAnnounceProcess } // Confirm the plug survived a moment, so a double signal does not toast twice. + // A blip back to battery during this wait must not drop the confirmation: + // applyChargerAnnounce keeps it pending and restarts this timer if AC returns. Timer { id: chargerAnnounceDebounce interval: 500 @@ -216,6 +220,16 @@ Item { } } + // A pending confirmation dies only if the machine stays on battery this long. + Timer { + id: chargerAnnounceExpire + interval: BatteryModel.chargerAnnounceMinMs + onTriggered: { + if (!UPower.onBattery) return + root.applyChargerAnnounce(Date.now()) + } + } + Process { id: chargeLimitProcess onExited: root.refreshChargeLimit() @@ -315,7 +329,7 @@ Item { root.checkTopUpOnceRearm() } } - root.considerChargerConnected(wasOnBattery) + root.applyChargerAnnounce(Date.now()) } } @@ -329,7 +343,7 @@ Item { } Component.onCompleted: { - root.noteOnBatteryClock() + if (UPower.onBattery) root.chargerOnBatterySinceMs = Date.now() root.refreshPowerProfile() root.checkTopUpOnceRearm() } diff --git a/test/shell.d/battery-test.sh b/test/shell.d/battery-test.sh index f8c4edbb7427..abae7f60779f 100644 --- a/test/shell.d/battery-test.sh +++ b/test/shell.d/battery-test.sh @@ -201,6 +201,19 @@ assert( !battery.shouldAnnounceChargerConnected(false, true, true, 5000), 'battery does not announce when the charger is removed' ) + +const minMs = battery.chargerAnnounceMinMs +let plugged = battery.stepChargerAnnounce({ onBattery: true, sinceMs: 0, pending: false }, false, true, minMs) +assert(plugged.announce && plugged.pending, 'a long battery stretch qualifies the charger toast') +let blip = battery.stepChargerAnnounce(plugged, true, true, minMs + 200) +assert(!blip.announce && blip.pending, 'a power blip keeps the charger confirmation pending') +let back = battery.stepChargerAnnounce(blip, false, true, minMs + 400) +assert(back.announce, 'reconnecting inside the window still announces the charger') +let stayed = battery.stepChargerAnnounce(blip, true, true, minMs + 200 + minMs) +assert(!stayed.pending && !stayed.announce, 'staying on battery through the window drops the confirmation') +let flap = battery.stepChargerAnnounce({ onBattery: false, sinceMs: -1, pending: false }, true, true, 0) +flap = battery.stepChargerAnnounce(flap, false, true, minMs - 1) +assert(!flap.announce, 'a flap that never qualified does not announce a charger') JS # The low-battery command must stay critical in-session, avoid restoring stale From 417cccd38744ee7066119558146af4060e2842fb Mon Sep 17 00:00:00 2001 From: Cynnamoroll Date: Mon, 30 Nov 2026 07:38:36 +0000 Subject: [PATCH 12/19] Wait for a battery event after a failed charge-limit write A rejected hardware write leaves the one-time top-up marker in place. Refresh the state when the process exits without rechecking the same charge reading. A new battery event can still restore the limit. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- shell/plugins/services/battery/Service.qml | 10 +- test/shell.d/battery-test.sh | 10 ++ test/shell.d/fixtures/battery-charge-limit.py | 120 ++++++++++++++++++ 3 files changed, 138 insertions(+), 2 deletions(-) create mode 100644 test/shell.d/fixtures/battery-charge-limit.py diff --git a/shell/plugins/services/battery/Service.qml b/shell/plugins/services/battery/Service.qml index e4f4217ea092..09911bf00676 100644 --- a/shell/plugins/services/battery/Service.qml +++ b/shell/plugins/services/battery/Service.qml @@ -146,9 +146,13 @@ Item { powerProfileReadProcess.running = true } - function refreshChargeLimit() { + function refreshChargeLimitState() { topUpOnceFile.reread() chargeLimitSignals++ + } + + function refreshChargeLimit() { + refreshChargeLimitState() checkTopUpOnceRearm() } @@ -232,7 +236,9 @@ Item { Process { id: chargeLimitProcess - onExited: root.refreshChargeLimit() + // A failed write leaves the marker in place. Refresh the readout, but + // wait for another battery event or explicit refresh before trying again. + onExited: root.refreshChargeLimitState() } // Wait briefly on unplug before re-arming a one-time top-up so USB-C PD diff --git a/test/shell.d/battery-test.sh b/test/shell.d/battery-test.sh index abae7f60779f..91230368d729 100644 --- a/test/shell.d/battery-test.sh +++ b/test/shell.d/battery-test.sh @@ -265,3 +265,13 @@ declare -a dismiss_args mapfile -d '' -t dismiss_args <"$tmpdir/dismiss-args" [[ ${dismiss_args[*]} == "Localized low battery" ]] || fail "battery dismissal uses the localized notification summary" "${dismiss_args[*]}" pass "low-battery dismissal uses the localized notification summary" + +if command -v quickshell >/dev/null && command -v dbus-run-session >/dev/null; then + if ! output=$(timeout 15 dbus-run-session -- /usr/bin/python3 \ + "$SHELL_TEST_DIR/fixtures/battery-charge-limit.py" "$ROOT" 2>&1); then + fail "charge-limit failure waits for a new battery event before retrying" "$output" + fi + pass "charge-limit failure waits for a new battery event before retrying" +else + skip "Quickshell and dbus-run-session are needed for the charge-limit retry fixture" +fi diff --git a/test/shell.d/fixtures/battery-charge-limit.py b/test/shell.d/fixtures/battery-charge-limit.py new file mode 100644 index 000000000000..368439adae2e --- /dev/null +++ b/test/shell.d/fixtures/battery-charge-limit.py @@ -0,0 +1,120 @@ +import os +from pathlib import Path +import subprocess +import sys +from tempfile import TemporaryDirectory + +from gi.repository import Gio, GLib + +UPOWER = "org.freedesktop.UPower" +DEVICE = UPOWER + ".Device" +ROOT = "/org/freedesktop/UPower" +BATTERY = ROOT + "/devices/battery_BAT0" +bus = Gio.bus_get_sync(Gio.BusType.SESSION) +loop = GLib.MainLoop() +props = { + "IsPresent": GLib.Variant("b", True), + "PowerSupply": GLib.Variant("b", True), + "ChargeThresholdSupported": GLib.Variant("b", True), + "ChargeThresholdEnabled": GLib.Variant("b", False), + "Percentage": GLib.Variant("d", 100.0), + "State": GLib.Variant("u", 1), # Charging; 100% also finishes a top-up. +} +attempts = 0 +accept_threshold = False + + +def method_call(connection, sender, path, interface, method, params, invocation): + global attempts + if method == "EnumerateDevices": + invocation.return_value(GLib.Variant("(ao)", ([BATTERY],))) + elif method == "GetDisplayDevice": + invocation.return_value(GLib.Variant("(o)", (BATTERY,))) + elif method == "EnableChargeThreshold": + attempts += 1 + assert params.unpack() == (True,) + if accept_threshold: + props["ChargeThresholdEnabled"] = GLib.Variant("b", True) + invocation.return_value(None) + else: + invocation.return_dbus_error("org.freedesktop.UPower.GeneralError", "test threshold write rejected") + + +def get_property(connection, sender, path, interface, name): + return GLib.Variant("b", False) if name == "OnBattery" else props[name] + + +def register(path, interface, methods, properties): + xml = f'{methods}' + "".join( + f'' + for name, value in properties.items() + ) + "" + bus.register_object(path, Gio.DBusNodeInfo.new_for_xml(xml).interfaces[0], method_call, get_property) + + +register(ROOT, UPOWER, """ + + +""", {"OnBattery": GLib.Variant("b", False)}) +register(BATTERY, DEVICE, """ + +""", props) +bus.call_sync("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", + "RequestName", GLib.Variant("(su)", (UPOWER, 0)), None, 0, 5000, None) + + +def update_percentage(percentage): + changed = {"Percentage": GLib.Variant("d", percentage)} + props.update(changed) + bus.emit_signal(None, BATTERY, "org.freedesktop.DBus.Properties", "PropertiesChanged", + GLib.Variant("(sa{sv}as)", (DEVICE, changed, []))) + + +with TemporaryDirectory() as tmp: + home = Path(tmp) + state = home / "state" + marker = state / "omarchy" / "battery" / "top-up-once" + marker.parent.mkdir(parents=True) + marker.write_text("1\n") + repo = Path(sys.argv[1]) + config = home / "config" + config.mkdir() + (config / "battery").symlink_to(repo / "shell/plugins/services/battery", target_is_directory=True) + (config / "Commons").symlink_to(repo / "shell/Commons", target_is_directory=True) + (config / "shell.qml").write_text('import Quickshell\nimport "battery" as Battery\nShellRoot { Battery.Service {} }\n') + (home / "run").mkdir(mode=0o700) + env = {**os.environ, "DBUS_SYSTEM_BUS_ADDRESS": os.environ["DBUS_SESSION_BUS_ADDRESS"], + "HOME": tmp, "XDG_RUNTIME_DIR": str(home / "run"), "XDG_CONFIG_HOME": str(home / ".config"), + "XDG_CACHE_HOME": str(home / ".cache"), "XDG_STATE_HOME": str(state), + "OMARCHY_BATTERY_STATE_DIR": str(marker.parent), "OMARCHY_POWER_SUPPLY_PATH": str(home / "sys"), + "QT_QPA_PLATFORM": "offscreen", "QML_IMPORT_PATH": str(repo / "shell"), + "QS_DISABLE_CRASH_HANDLER": "1", "PATH": f"{repo}/bin:{os.environ['PATH']}"} + with (home / "quickshell.log").open("w+") as log: + shell = subprocess.Popen(["quickshell", "-p", str(config), "--no-color"], stdout=log, stderr=log, env=env) + try: + # Dispatch the real Quickshell battery service and its real CLI on a + # private bus. The fixture only supplies the battery and write outcome. + GLib.timeout_add(1200, loop.quit) + loop.run() + assert shell.poll() is None, "Quickshell exited before settling" + assert attempts == 1, f"expected one failed charge-limit write, saw {attempts}" + assert marker.exists(), "a failed write must keep the request pending" + + update_percentage(95.0) + GLib.timeout_add(200, loop.quit) + loop.run() + assert attempts == 1, "charging below the limit must not retry" + + accept_threshold = True + update_percentage(100.0) + GLib.timeout_add(1000, loop.quit) + loop.run() + assert attempts == 2, f"a new full-charge event must retry exactly once, saw {attempts}" + assert not marker.exists(), "a successful retry must clear the pending request" + except Exception: + log.seek(0) + print(log.read()[-5000:], file=sys.stderr) + raise + finally: + shell.terminate() + shell.wait(timeout=5) From 7730413c1696064515c1bb16f0a383048fba7bd3 Mon Sep 17 00:00:00 2001 From: Cynnamoroll Date: Mon, 30 Nov 2026 07:48:51 +0000 Subject: [PATCH 13/19] Wait for charge-limit events in the regression test Wait for Quickshell to handle the failed write before watching for a retry, and wait for the successful write to clear the marker. Bound both waits so slow startup or D-Bus calls do not fail a working implementation. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- test/shell.d/fixtures/battery-charge-limit.py | 55 ++++++++++++++----- 1 file changed, 41 insertions(+), 14 deletions(-) diff --git a/test/shell.d/fixtures/battery-charge-limit.py b/test/shell.d/fixtures/battery-charge-limit.py index 368439adae2e..33da54d68226 100644 --- a/test/shell.d/fixtures/battery-charge-limit.py +++ b/test/shell.d/fixtures/battery-charge-limit.py @@ -70,6 +70,20 @@ def update_percentage(percentage): GLib.Variant("(sa{sv}as)", (DEVICE, changed, []))) +def wait_until(predicate, timeout_ms=4000): + deadline = GLib.get_monotonic_time() + timeout_ms * 1000 + + def check(): + if predicate() or GLib.get_monotonic_time() >= deadline: + loop.quit() + return GLib.SOURCE_REMOVE + return GLib.SOURCE_CONTINUE + + GLib.timeout_add(10, check) + loop.run() + return predicate() + + with TemporaryDirectory() as tmp: home = Path(tmp) state = home / "state" @@ -81,7 +95,20 @@ def update_percentage(percentage): config.mkdir() (config / "battery").symlink_to(repo / "shell/plugins/services/battery", target_is_directory=True) (config / "Commons").symlink_to(repo / "shell/Commons", target_is_directory=True) - (config / "shell.qml").write_text('import Quickshell\nimport "battery" as Battery\nShellRoot { Battery.Service {} }\n') + (config / "shell.qml").write_text(""" +import Quickshell +import "battery" as Battery + +ShellRoot { + Battery.Service { + readonly property int observedPercentage: batteryPercentage() + onObservedPercentageChanged: console.info("fixture percentage " + observedPercentage) + // A rejected CLI write cannot send a refresh over IPC. The service only + // emits this signal for that attempt once it has handled the child's exit. + onChargeLimitSignalsChanged: console.info("fixture charge limit refreshed") + } +} +""") (home / "run").mkdir(mode=0o700) env = {**os.environ, "DBUS_SYSTEM_BUS_ADDRESS": os.environ["DBUS_SESSION_BUS_ADDRESS"], "HOME": tmp, "XDG_RUNTIME_DIR": str(home / "run"), "XDG_CONFIG_HOME": str(home / ".config"), @@ -89,31 +116,31 @@ def update_percentage(percentage): "OMARCHY_BATTERY_STATE_DIR": str(marker.parent), "OMARCHY_POWER_SUPPLY_PATH": str(home / "sys"), "QT_QPA_PLATFORM": "offscreen", "QML_IMPORT_PATH": str(repo / "shell"), "QS_DISABLE_CRASH_HANDLER": "1", "PATH": f"{repo}/bin:{os.environ['PATH']}"} - with (home / "quickshell.log").open("w+") as log: + log_path = home / "quickshell.log" + + def logged(message): + return message.encode() in log_path.read_bytes() + + with log_path.open("w") as log: shell = subprocess.Popen(["quickshell", "-p", str(config), "--no-color"], stdout=log, stderr=log, env=env) try: # Dispatch the real Quickshell battery service and its real CLI on a # private bus. The fixture only supplies the battery and write outcome. - GLib.timeout_add(1200, loop.quit) - loop.run() - assert shell.poll() is None, "Quickshell exited before settling" - assert attempts == 1, f"expected one failed charge-limit write, saw {attempts}" + assert wait_until(lambda: attempts > 0 and logged("fixture charge limit refreshed")), \ + "the first charge-limit failure did not complete" assert marker.exists(), "a failed write must keep the request pending" + assert not wait_until(lambda: attempts > 1, 300), "the failed charge-limit write retried without a new battery event" update_percentage(95.0) - GLib.timeout_add(200, loop.quit) - loop.run() - assert attempts == 1, "charging below the limit must not retry" + assert wait_until(lambda: logged("fixture percentage 95")), "Quickshell did not see the below-full reading" + assert not wait_until(lambda: attempts > 1, 200), "charging below the limit must not retry" accept_threshold = True update_percentage(100.0) - GLib.timeout_add(1000, loop.quit) - loop.run() + assert wait_until(lambda: attempts >= 2 and not marker.exists()), "the successful retry did not clear the request" assert attempts == 2, f"a new full-charge event must retry exactly once, saw {attempts}" - assert not marker.exists(), "a successful retry must clear the pending request" except Exception: - log.seek(0) - print(log.read()[-5000:], file=sys.stderr) + print(log_path.read_text(errors="replace")[-5000:], file=sys.stderr) raise finally: shell.terminate() From 51da86d16d1a8cb5a3816872d0f46a5f5afb3ddf Mon Sep 17 00:00:00 2001 From: jvdp11 Date: Mon, 30 Nov 2026 10:05:12 +0100 Subject: [PATCH 14/19] Report the charger's rating and the power drawn from it in battery status --- bin/omarchy-battery-status | 36 +++++++++++++++++++++++++++++ test/shell.d/battery-status-test.sh | 30 ++++++++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/bin/omarchy-battery-status b/bin/omarchy-battery-status index 0c30a561b4d8..fdbab4ef7224 100755 --- a/bin/omarchy-battery-status +++ b/bin/omarchy-battery-status @@ -5,6 +5,7 @@ shell_output=false power_supply_path="${OMARCHY_POWER_SUPPLY_PATH:-/sys/class/power_supply}" +hwmon_path="${OMARCHY_HWMON_PATH:-/sys/class/hwmon}" sleep_run_dir="${OMARCHY_SLEEP_RUN_DIR:-/run/omarchy}" battery_state_dir="${OMARCHY_BATTERY_STATE_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/battery}" surface_battery_dir="${OMARCHY_SURFACE_BATTERY_DIR:-/run/surface-pro-11-battery}" @@ -242,6 +243,41 @@ if [[ $shell_output == "true" ]]; then fi fi + # The connected charger: what it can give, and what is drawn from it now. A + # small charger under load leaves little for the battery, and the panel shows + # that split instead of a charge rate that looks like a fault. Apple Silicon + # reports the rating as input_power_limit on its Mains supply; USB-PD supplies + # elsewhere (UCSI) report the negotiated voltage_max and current_max. Below + # 5W is a plain USB port, not a charger rating. + charger_uw=0 + for supply in "$power_supply_path"/*; do + [[ -r $supply/type && $(<"$supply/type") =~ ^(Mains|USB) ]] || continue + [[ $(read_sysfs_number "$supply/online" || true) == "1" ]] || continue + if supply_uw=$(read_sysfs_number "$supply/input_power_limit"); then + : + elif microvolts=$(read_sysfs_number "$supply/voltage_max") && microamps=$(read_sysfs_number "$supply/current_max"); then + supply_uw=$(( microvolts * microamps / 1000000 )) + else + continue + fi + if (( supply_uw > charger_uw )); then + charger_uw=$supply_uw + fi + done + + if (( charger_uw >= 5000000 )); then + printf 'charger\t%sW\n' "$(( (charger_uw + 500000) / 1000000 ))" + + # Only a sensor gives the draw itself (the Apple SMC's "AC Input Power"); + # without one the panel shows the rating alone. + for label in "$hwmon_path"/*/power*_label; do + [[ -r $label && $(<"$label") == "AC Input Power" ]] || continue + microwatts=$(read_sysfs_number "${label%_label}_input") || continue + printf 'charger_draw\t%sW\n' "$(awk -v microwatts="$microwatts" 'BEGIN { rounded = sprintf("%.1f", microwatts / 1000000); sub(/\.0$/, "", rounded); print rounded }')" + break + done + fi + # Charge limit control metadata for the power panel. limit_supported=0 if [[ $upower_threshold_supported == "yes" || -r $battery_path/charge_control_end_threshold ]]; then diff --git a/test/shell.d/battery-status-test.sh b/test/shell.d/battery-status-test.sh index 781ec579b7e0..49968f012a7b 100644 --- a/test/shell.d/battery-status-test.sh +++ b/test/shell.d/battery-status-test.sh @@ -161,6 +161,36 @@ charging_output=$(OMARCHY_POWER_SUPPLY_PATH="$hold_dir/power" PATH="$hold_dir/bi grep -Fx $'time\t1h' <<<"$charging_output" >/dev/null || fail "time to full counts up to the charge limit" "$charging_output" pass "battery status times charging to the charge limit" +# The charger: a Mains supply without a rating shows none, Apple Silicon's +# input_power_limit and SMC sensor give the rating and the draw, a USB-PD +# supply gives its negotiated rating, and a plain USB port is no charger. +mkdir -p "$hold_dir/hwmon/hwmon0" +charger_output=$(OMARCHY_POWER_SUPPLY_PATH="$hold_dir/power" OMARCHY_HWMON_PATH="$hold_dir/hwmon" PATH="$hold_dir/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell) +! grep -q '^charger' <<<"$charger_output" || fail "a charger without a rating reports none" "$charger_output" + +printf '65200000\n' >"$hold_dir/power/ac/input_power_limit" +printf 'AC Input Power\n' >"$hold_dir/hwmon/hwmon0/power1_label" +printf '64120000\n' >"$hold_dir/hwmon/hwmon0/power1_input" +charger_output=$(OMARCHY_POWER_SUPPLY_PATH="$hold_dir/power" OMARCHY_HWMON_PATH="$hold_dir/hwmon" PATH="$hold_dir/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell) +grep -Fx $'charger\t65W' <<<"$charger_output" >/dev/null || fail "battery status reports the charger's input power limit" "$charger_output" +grep -Fx $'charger_draw\t64.1W' <<<"$charger_output" >/dev/null || fail "battery status reports the power drawn from the charger" "$charger_output" + +rm "$hold_dir/power/ac/input_power_limit" "$hold_dir/hwmon/hwmon0/power1_label" +mkdir -p "$hold_dir/power/ucsi-source-psy-USBC000:001" +printf 'USB\n' >"$hold_dir/power/ucsi-source-psy-USBC000:001/type" +printf '1\n' >"$hold_dir/power/ucsi-source-psy-USBC000:001/online" +printf '20000000\n' >"$hold_dir/power/ucsi-source-psy-USBC000:001/voltage_max" +printf '5000000\n' >"$hold_dir/power/ucsi-source-psy-USBC000:001/current_max" +charger_output=$(OMARCHY_POWER_SUPPLY_PATH="$hold_dir/power" OMARCHY_HWMON_PATH="$hold_dir/hwmon" PATH="$hold_dir/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell) +grep -Fx $'charger\t100W' <<<"$charger_output" >/dev/null || fail "battery status reports a USB-PD charger's negotiated rating" "$charger_output" +! grep -q '^charger_draw' <<<"$charger_output" || fail "battery status reports no draw without a sensor" "$charger_output" + +printf '5000000\n' >"$hold_dir/power/ucsi-source-psy-USBC000:001/voltage_max" +printf '500000\n' >"$hold_dir/power/ucsi-source-psy-USBC000:001/current_max" +charger_output=$(OMARCHY_POWER_SUPPLY_PATH="$hold_dir/power" OMARCHY_HWMON_PATH="$hold_dir/hwmon" PATH="$hold_dir/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell) +! grep -q '^charger' <<<"$charger_output" || fail "a plain USB port is no charger" "$charger_output" +pass "battery status reports the charger's rating and draw where the hardware gives them" + # UPower's own estimate stands in when the draw is too small to divide by... printf '100000\n' >"$hold_dir/power/BAT0/power_now" idle_output=$(OMARCHY_POWER_SUPPLY_PATH="$hold_dir/power" PATH="$hold_dir/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell) From aeae6ca53ebb40f730d85fef736210b7fde9c246 Mon Sep 17 00:00:00 2001 From: jvdp11 Date: Mon, 30 Nov 2026 10:09:39 +0100 Subject: [PATCH 15/19] Show the charger and how its power is shared in the power panel --- default/i18n/en/shell.json | 5 + shell/plugins/panels/power/Model.js | 43 ++++++++- shell/plugins/panels/power/Panel.qml | 136 +++++++++++++++++++++++++++ test/shell.d/power-test.sh | 11 +++ 4 files changed, 194 insertions(+), 1 deletion(-) diff --git a/default/i18n/en/shell.json b/default/i18n/en/shell.json index 97d934f51e97..1d6b8200a360 100644 --- a/default/i18n/en/shell.json +++ b/default/i18n/en/shell.json @@ -597,6 +597,11 @@ "power.chargeLimit": "Charge limit", "power.chargeLimitFailed": "Could not update charge limit", "power.chargeLimitTo": "Charge to only %1", + "power.charger": "CHARGER", + "power.chargerMaxed": "The charger is at its limit: a stronger one would charge faster", + "power.chargerToBattery": "To battery", + "power.chargerToSystem": "To system", + "power.chargerUse": "%1 of %2", "power.charging": "Charging", "power.chargingPhrase1": "Pumping power", "power.chargingPhrase2": "Injecting electrons", diff --git a/shell/plugins/panels/power/Model.js b/shell/plugins/panels/power/Model.js index 2a621f28006d..d3d5aa11cc12 100644 --- a/shell/plugins/panels/power/Model.js +++ b/shell/plugins/panels/power/Model.js @@ -222,6 +222,45 @@ function usageChart(hours, nowSeconds) { return { columns: columns, screen: screen, used: used } } +// How the charger's power is shared out. Battery status reports the charger's +// rating ("140W") and, where a sensor gives it, the power drawn from it now +// ("136.9W"); what flows into the battery is the charge rate, and the rest of +// the draw is what the system takes. Fractions are of the rating. maxed: the +// charger gives all it has while the battery gets a small share of it, so a +// stronger charger would charge faster. Null without a charger rating. +function chargerFlow(batteryInfo, charging) { + var info = batteryInfo || {} + var limit = parseFloat(info.charger) + if (!(limit > 0)) return null + + var draw = parseFloat(info.charger_draw) + var hasDraw = draw >= 0 + var battery = charging ? Math.max(0, parseFloat(info.rate) || 0) : 0 + if (hasDraw) battery = Math.min(battery, draw) + var system = hasDraw ? Math.max(0, draw - battery) : -1 + + function fraction(watts) { return Math.max(0, Math.min(1, watts / limit)) } + + return { + limit: limit, + draw: hasDraw ? draw : -1, + battery: battery, + system: system, + batteryFraction: fraction(battery), + systemFraction: hasDraw ? fraction(system) : 0, + maxed: hasDraw && charging && draw >= limit * 0.93 && battery < limit * 0.3 + } +} + +// A wattage in the shape battery status writes one, for localizeReading: +// whole watts from 10W up, one decimal below that. +function wattsReading(watts) { + var value = Math.max(0, Number(watts) || 0) + if (value >= 10) return Math.round(value) + "W" + var rounded = String(Math.round(value * 10) / 10) + return rounded + "W" +} + if (typeof module !== "undefined") { module.exports = { clampIndex: clampIndex, @@ -241,6 +280,8 @@ if (typeof module !== "undefined") { formatSleepTooltip: formatSleepTooltip, isLowS0ix: isLowS0ix, moveFocus: moveFocus, - usageChart: usageChart + usageChart: usageChart, + chargerFlow: chargerFlow, + wattsReading: wattsReading } } diff --git a/shell/plugins/panels/power/Panel.qml b/shell/plugins/panels/power/Panel.qml index 3d1c07fddf02..1822bd8b6df6 100644 --- a/shell/plugins/panels/power/Panel.qml +++ b/shell/plugins/panels/power/Panel.qml @@ -119,6 +119,9 @@ Panel { return Model.chargeThresholdActive(device, root.discharging, upowerStates(), root.chargeRateFresh, root.activeChargeLimit) } readonly property bool batteryFull: fullyCharged || (!root.discharging && batteryFraction >= 1) + // The charger's rating and how its power is shared between battery and system. + readonly property var chargerFlow: root.discharging ? null + : Model.chargerFlow(root.batteryInfo, root.charging && !root.batteryFull && !root.chargeThresholdActive) readonly property bool batteryFlowIdle: batteryFull || chargeThresholdActive // 0..1 charge level, used by the visual progress bar. @@ -708,6 +711,139 @@ Panel { } } + // ---------- Charger: its rating, and how its power is shared ---------- + // One bar is the charger's whole rating: the solid part flows into the + // battery, the softer part is what the system takes, the track is what + // is left. Without a sensor for the draw only the battery's part shows. + PanelSeparator { + visible: chargerSection.visible + foreground: root.bar.foreground + } + + Column { + id: chargerSection + readonly property var flow: root.chargerFlow + readonly property bool maxed: flow !== null && flow.maxed + visible: flow !== null + width: parent.width + spacing: Style.space(10) + + Item { + width: parent.width + implicitHeight: Math.max(chargerHeader.implicitHeight, chargerRating.implicitHeight) + + PanelSectionHeader { + id: chargerHeader + text: Commons.I18n.t("power.charger") + foreground: root.bar.foreground + fontFamily: root.bar.fontFamily + anchors.left: parent.left + anchors.verticalCenter: parent.verticalCenter + } + + InfoValue { + id: chargerRating + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + color: chargerSection.maxed ? Commons.Color.warning : root.bar.foreground + text: { + var flow = chargerSection.flow + if (!flow) return "" + if (flow.draw < 0) return root.reading(root.batteryInfo.charger) + return Commons.I18n.t("power.chargerUse").arg(root.reading(Model.wattsReading(flow.draw))).arg(root.reading(root.batteryInfo.charger)) + } + + Behavior on color { ColorAnimation { duration: Style.duration(220) } } + } + } + + Item { + width: parent.width + implicitHeight: Style.space(6) + + Rectangle { + id: chargerTrack + anchors.fill: parent + radius: height / 2 + color: Qt.rgba(root.bar.foreground.r, root.bar.foreground.g, root.bar.foreground.b, 0.12) + } + + // The system's part spans both shares and the battery's covers its + // start, so the two meet without a seam. + Rectangle { + readonly property real fraction: chargerSection.flow ? Math.min(1, chargerSection.flow.batteryFraction + chargerSection.flow.systemFraction) : 0 + visible: chargerSection.flow !== null && chargerSection.flow.systemFraction > 0 + anchors.left: chargerTrack.left + anchors.verticalCenter: chargerTrack.verticalCenter + height: chargerTrack.height + radius: chargerTrack.radius + width: Math.max(chargerTrack.height, chargerTrack.width * fraction) + color: chargerSection.maxed + ? Qt.rgba(Commons.Color.warning.r, Commons.Color.warning.g, Commons.Color.warning.b, 0.75) + : Qt.rgba(root.bar.foreground.r, root.bar.foreground.g, root.bar.foreground.b, 0.38) + + Behavior on width { NumberAnimation { duration: Style.duration(320); easing.type: Easing.OutCubic } } + Behavior on color { ColorAnimation { duration: Style.duration(220) } } + } + + Rectangle { + visible: chargerSection.flow !== null && chargerSection.flow.batteryFraction > 0 + anchors.left: chargerTrack.left + anchors.verticalCenter: chargerTrack.verticalCenter + height: chargerTrack.height + radius: chargerTrack.radius + width: chargerSection.flow ? Math.max(chargerTrack.height, chargerTrack.width * chargerSection.flow.batteryFraction) : 0 + color: root.batteryFillColor + + Behavior on width { NumberAnimation { duration: Style.duration(320); easing.type: Easing.OutCubic } } + } + } + + Row { + width: parent.width + spacing: Style.space(20) + + InfoPair { + width: (parent.width - parent.spacing) / 2 + label: Commons.I18n.t("power.chargerToBattery") + value: chargerSection.flow && chargerSection.flow.battery > 0 ? root.reading(Model.wattsReading(chargerSection.flow.battery)) : "-" + } + + InfoPair { + width: (parent.width - parent.spacing) / 2 + label: Commons.I18n.t("power.chargerToSystem") + value: chargerSection.flow && chargerSection.flow.system >= 0 ? root.reading(Model.wattsReading(chargerSection.flow.system)) : "—" + } + } + + Row { + visible: chargerSection.maxed + width: parent.width + spacing: Style.space(6) + + Text { + id: chargerWarnIcon + text: "󰀦" + textFormat: Text.PlainText + color: Commons.Color.warning + font.family: root.bar.fontFamily + font.pixelSize: Style.font.caption + anchors.verticalCenter: parent.verticalCenter + } + + Text { + text: Commons.I18n.t("power.chargerMaxed") + textFormat: Text.PlainText + color: Commons.Color.warning + font.family: root.bar.fontFamily + font.pixelSize: Style.font.caption + wrapMode: Text.WordWrap + width: parent.width - chargerWarnIcon.implicitWidth - parent.spacing + anchors.verticalCenter: parent.verticalCenter + } + } + } + // ---------- Last 24 hours: level, external power, screen-on time ---------- PanelSeparator { foreground: root.bar.foreground diff --git a/test/shell.d/power-test.sh b/test/shell.d/power-test.sh index 96aafb4acc13..1904e035a138 100644 --- a/test/shell.d/power-test.sh +++ b/test/shell.d/power-test.sh @@ -137,4 +137,15 @@ assertEqual(chart.screen, 1920, 'power totals screen-on time within the window') assertEqual(chart.columns[23].change, 10, 'power reports the change against the hour before') assertEqual(power.usageChart({ [499 * hour]: { level: 60, used: 5 }, [500 * hour]: { level: 60, used: 15 }, [470 * hour]: { used: 9 } }, now).used, 20, 'power totals the battery used within the window') +// A small charger under load: most of it goes to the system, so it reads as maxed. +const small = power.chargerFlow({ charger: '65W', charger_draw: '64.1W', rate: '10.7W' }, true) +assertEqual(small.system, 64.1 - 10.7, 'power takes the battery\'s share out of the charger draw') +assert(small.maxed, 'power flags a charger that is maxed while the battery gets little of it') +assert(!power.chargerFlow({ charger: '140W', charger_draw: '136.9W', rate: '67.1W' }, true).maxed, 'power does not flag a charger that is maxed by fast charging') +assertEqual(power.chargerFlow({ charger: '140W', charger_draw: '40W', rate: '0W' }, false).batteryFraction, 0, 'power gives a battery that is not charging no share') +const unsensed = power.chargerFlow({ charger: '65W', rate: '30W' }, true) +assert(unsensed.system < 0 && !unsensed.maxed, 'power leaves the system share unknown without a draw sensor') +assertEqual(power.chargerFlow({ rate: '12W' }, false), null, 'power shows no charger without a rating') +assertEqual(power.wattsReading(7.25) + ' ' + power.wattsReading(136.9), '7.3W 137W', 'power rounds wattages like battery status') + JS From 713b17ad788146020b9a83d2a89dba6c56aebee6 Mon Sep 17 00:00:00 2001 From: jvdp11 Date: Mon, 30 Nov 2026 10:36:20 +0100 Subject: [PATCH 16/19] Take the charger split's direction from the battery state, and keep the bars' motion within the motion rules --- default/i18n/en/shell.json | 2 ++ shell/plugins/panels/power/Model.js | 21 ++++++++++++++------- shell/plugins/panels/power/Panel.qml | 15 ++++++++------- test/shell.d/power-test.sh | 13 ++++++++----- 4 files changed, 32 insertions(+), 19 deletions(-) diff --git a/default/i18n/en/shell.json b/default/i18n/en/shell.json index 1d6b8200a360..d94e7d1ff70d 100644 --- a/default/i18n/en/shell.json +++ b/default/i18n/en/shell.json @@ -598,7 +598,9 @@ "power.chargeLimitFailed": "Could not update charge limit", "power.chargeLimitTo": "Charge to only %1", "power.charger": "CHARGER", + "power.chargerFromBattery": "From battery", "power.chargerMaxed": "The charger is at its limit: a stronger one would charge faster", + "power.chargerShort": "The charger can't keep up: the battery covers the rest", "power.chargerToBattery": "To battery", "power.chargerToSystem": "To system", "power.chargerUse": "%1 of %2", diff --git a/shell/plugins/panels/power/Model.js b/shell/plugins/panels/power/Model.js index d3d5aa11cc12..0a75838f9a64 100644 --- a/shell/plugins/panels/power/Model.js +++ b/shell/plugins/panels/power/Model.js @@ -224,18 +224,24 @@ function usageChart(hours, nowSeconds) { // How the charger's power is shared out. Battery status reports the charger's // rating ("140W") and, where a sensor gives it, the power drawn from it now -// ("136.9W"); what flows into the battery is the charge rate, and the rest of -// the draw is what the system takes. Fractions are of the rating. maxed: the -// charger gives all it has while the battery gets a small share of it, so a -// stronger charger would charge faster. Null without a charger rating. -function chargerFlow(batteryInfo, charging) { +// ("136.9W"), with the battery's state and rate. The battery's state, not the +// plug, gives the direction: a charger too weak for the load leaves the battery +// draining while plugged in. Charging, the rate flows into the battery and the +// rest of the draw is what the system takes; draining, the whole draw goes to +// the system and the battery covers the rest (drain). Fractions are of the +// rating. maxed: the charger gives all it has while the battery gets a small +// share of it or none. Null without a charger rating. +function chargerFlow(batteryInfo) { var info = batteryInfo || {} var limit = parseFloat(info.charger) if (!(limit > 0)) return null + var rate = Math.max(0, parseFloat(info.rate) || 0) + var charging = info.state === "charging" + var draining = info.state === "discharging" var draw = parseFloat(info.charger_draw) var hasDraw = draw >= 0 - var battery = charging ? Math.max(0, parseFloat(info.rate) || 0) : 0 + var battery = charging ? rate : 0 if (hasDraw) battery = Math.min(battery, draw) var system = hasDraw ? Math.max(0, draw - battery) : -1 @@ -245,10 +251,11 @@ function chargerFlow(batteryInfo, charging) { limit: limit, draw: hasDraw ? draw : -1, battery: battery, + drain: draining ? rate : 0, system: system, batteryFraction: fraction(battery), systemFraction: hasDraw ? fraction(system) : 0, - maxed: hasDraw && charging && draw >= limit * 0.93 && battery < limit * 0.3 + maxed: hasDraw && (charging || draining) && draw >= limit * 0.93 && battery < limit * 0.3 } } diff --git a/shell/plugins/panels/power/Panel.qml b/shell/plugins/panels/power/Panel.qml index 1822bd8b6df6..770ea2d51112 100644 --- a/shell/plugins/panels/power/Panel.qml +++ b/shell/plugins/panels/power/Panel.qml @@ -120,8 +120,7 @@ Panel { } readonly property bool batteryFull: fullyCharged || (!root.discharging && batteryFraction >= 1) // The charger's rating and how its power is shared between battery and system. - readonly property var chargerFlow: root.discharging ? null - : Model.chargerFlow(root.batteryInfo, root.charging && !root.batteryFull && !root.chargeThresholdActive) + readonly property var chargerFlow: root.discharging ? null : Model.chargerFlow(root.batteryInfo) readonly property bool batteryFlowIdle: batteryFull || chargeThresholdActive // 0..1 charge level, used by the visual progress bar. @@ -782,7 +781,7 @@ Panel { ? Qt.rgba(Commons.Color.warning.r, Commons.Color.warning.g, Commons.Color.warning.b, 0.75) : Qt.rgba(root.bar.foreground.r, root.bar.foreground.g, root.bar.foreground.b, 0.38) - Behavior on width { NumberAnimation { duration: Style.duration(320); easing.type: Easing.OutCubic } } + Behavior on width { NumberAnimation { duration: Style.duration(250); easing.type: Easing.Bezier; easing.bezierCurve: Style.easeOut } } Behavior on color { ColorAnimation { duration: Style.duration(220) } } } @@ -795,7 +794,7 @@ Panel { width: chargerSection.flow ? Math.max(chargerTrack.height, chargerTrack.width * chargerSection.flow.batteryFraction) : 0 color: root.batteryFillColor - Behavior on width { NumberAnimation { duration: Style.duration(320); easing.type: Easing.OutCubic } } + Behavior on width { NumberAnimation { duration: Style.duration(250); easing.type: Easing.Bezier; easing.bezierCurve: Style.easeOut } } } } @@ -805,8 +804,10 @@ Panel { InfoPair { width: (parent.width - parent.spacing) / 2 - label: Commons.I18n.t("power.chargerToBattery") - value: chargerSection.flow && chargerSection.flow.battery > 0 ? root.reading(Model.wattsReading(chargerSection.flow.battery)) : "-" + readonly property bool draining: chargerSection.flow !== null && chargerSection.flow.drain > 0 + label: draining ? Commons.I18n.t("power.chargerFromBattery") : Commons.I18n.t("power.chargerToBattery") + value: draining ? root.reading(Model.wattsReading(chargerSection.flow.drain)) + : chargerSection.flow && chargerSection.flow.battery > 0 ? root.reading(Model.wattsReading(chargerSection.flow.battery)) : "-" } InfoPair { @@ -832,7 +833,7 @@ Panel { } Text { - text: Commons.I18n.t("power.chargerMaxed") + text: chargerSection.flow && chargerSection.flow.drain > 0 ? Commons.I18n.t("power.chargerShort") : Commons.I18n.t("power.chargerMaxed") textFormat: Text.PlainText color: Commons.Color.warning font.family: root.bar.fontFamily diff --git a/test/shell.d/power-test.sh b/test/shell.d/power-test.sh index 1904e035a138..5635dad6accf 100644 --- a/test/shell.d/power-test.sh +++ b/test/shell.d/power-test.sh @@ -138,14 +138,17 @@ assertEqual(chart.columns[23].change, 10, 'power reports the change against the assertEqual(power.usageChart({ [499 * hour]: { level: 60, used: 5 }, [500 * hour]: { level: 60, used: 15 }, [470 * hour]: { used: 9 } }, now).used, 20, 'power totals the battery used within the window') // A small charger under load: most of it goes to the system, so it reads as maxed. -const small = power.chargerFlow({ charger: '65W', charger_draw: '64.1W', rate: '10.7W' }, true) +const small = power.chargerFlow({ charger: '65W', charger_draw: '64.1W', rate: '10.7W', state: 'charging' }) assertEqual(small.system, 64.1 - 10.7, 'power takes the battery\'s share out of the charger draw') assert(small.maxed, 'power flags a charger that is maxed while the battery gets little of it') -assert(!power.chargerFlow({ charger: '140W', charger_draw: '136.9W', rate: '67.1W' }, true).maxed, 'power does not flag a charger that is maxed by fast charging') -assertEqual(power.chargerFlow({ charger: '140W', charger_draw: '40W', rate: '0W' }, false).batteryFraction, 0, 'power gives a battery that is not charging no share') -const unsensed = power.chargerFlow({ charger: '65W', rate: '30W' }, true) +assert(!power.chargerFlow({ charger: '140W', charger_draw: '136.9W', rate: '67.1W', state: 'charging' }).maxed, 'power does not flag a charger that is maxed by fast charging') +// A charger too weak for the load: plugged in, yet the battery drains. +const short = power.chargerFlow({ charger: '65W', charger_draw: '64.1W', rate: '10W', state: 'discharging' }) +assert(short.battery === 0 && short.drain === 10 && short.system === 64.1 && short.maxed, 'power counts a battery draining on a weak charger as covering the system, not as charging') +assertEqual(power.chargerFlow({ charger: '140W', charger_draw: '40W', rate: '0W', state: 'fully-charged' }).batteryFraction, 0, 'power gives a full battery no share') +const unsensed = power.chargerFlow({ charger: '65W', rate: '30W', state: 'charging' }) assert(unsensed.system < 0 && !unsensed.maxed, 'power leaves the system share unknown without a draw sensor') -assertEqual(power.chargerFlow({ rate: '12W' }, false), null, 'power shows no charger without a rating') +assertEqual(power.chargerFlow({ rate: '12W' }), null, 'power shows no charger without a rating') assertEqual(power.wattsReading(7.25) + ' ' + power.wattsReading(136.9), '7.3W 137W', 'power rounds wattages like battery status') JS From 44691f9ab74a24ac845be801ccfefb06e03ffe39 Mon Sep 17 00:00:00 2001 From: Cynnamoroll Date: Tue, 1 Dec 2026 01:10:46 +0000 Subject: [PATCH 17/19] Refresh power-panel battery telemetry less often Keep immediate reads for panel opens, power source changes and charge-limit updates. Poll the remaining battery telemetry every 30 seconds while the panel is open. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- shell/plugins/panels/power/Panel.qml | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/shell/plugins/panels/power/Panel.qml b/shell/plugins/panels/power/Panel.qml index 770ea2d51112..156c718543e6 100644 --- a/shell/plugins/panels/power/Panel.qml +++ b/shell/plugins/panels/power/Panel.qml @@ -108,6 +108,7 @@ Panel { chargeRateFresh = discharging if (discharging) chargeRateSettle.stop() else chargeRateSettle.restart() + if (opened) refreshBatteryInfo() } Timer { id: chargeRateSettle @@ -240,9 +241,12 @@ Panel { } function refresh() { - if (!batteryPresent) return - refreshBatteryInfo() + refreshPanelData() + } + + function refreshPanelData() { + if (!batteryPresent) return usage = Model.usageChart(batteryService ? batteryService.usage : null, Math.floor(Date.now() / 1000)) if (profiles.length === 0 && !profilesProc.running) profilesProc.running = true } @@ -409,7 +413,10 @@ Panel { } } - Timer { interval: 5000; running: root.opened; repeat: true; onTriggered: root.refresh() } + Timer { interval: 5000; running: root.opened; repeat: true; onTriggered: root.refreshPanelData() } + // The helper also reads values without change signals, such as sleep drain. + // Read those periodically only while open; power and charge-limit events refresh immediately. + Timer { interval: 30000; running: root.opened; repeat: true; onTriggered: root.refreshBatteryInfo() } // Rotate the status phrase while the panel is open and we're in a // rotating state (charging or on battery). The text swap is wrapped in a From 9ac8c7fa67ef18c0b22642f2f880bb4a62b52a10 Mon Sep 17 00:00:00 2001 From: Taksh Date: Tue, 1 Dec 2026 07:33:24 +0530 Subject: [PATCH 18/19] Keep one low-battery latch and let the usage tests compile beside it. The 20% and 10% warnings and the charger announcement were joined into one battery model. The old boolean latch was unused, and the usage checks reused the device helper's name. --- shell/plugins/services/battery/Service.qml | 1 - test/shell.d/battery-test.sh | 34 +++++++++++----------- 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/shell/plugins/services/battery/Service.qml b/shell/plugins/services/battery/Service.qml index 09911bf00676..aa80abf74df2 100644 --- a/shell/plugins/services/battery/Service.qml +++ b/shell/plugins/services/battery/Service.qml @@ -14,7 +14,6 @@ Item { // 20 is UPower's own PercentageLow, so a pack that cuts out above 10% still gets a warning. readonly property var batteryThresholds: [20, 10] readonly property int lowBatteryWarningRecoveryThreshold: 20 - property bool notifiedLowBattery: false property string pendingPowerSource: "" // A warning that came due while the last one's hooks were still running. property int pendingWarningLevel: -1 diff --git a/test/shell.d/battery-test.sh b/test/shell.d/battery-test.sh index 91230368d729..150485365a28 100644 --- a/test/shell.d/battery-test.sh +++ b/test/shell.d/battery-test.sh @@ -156,25 +156,25 @@ assert( ) // Usage history: hourly tallies of screen-on and plugged-in seconds. const H = 3600 -const at = (hour, seconds) => 1000 * H + hour * H + seconds -let usage = battery.recordUsage({}, null, { at: at(0, 3000), plugged: false, screenOn: true, level: 80 }, 90) -assertDeepEqual(usage, { [at(0, 0)]: { screen: 0, plugged: 0, used: 0, level: 80 } }, 'usage starts with the level and no time') -usage = battery.recordUsage(usage, { at: at(0, 3570), plugged: false, screenOn: true, level: 80 }, { at: at(1, 30), plugged: false, screenOn: true, level: 79 }, 90) -assertEqual(usage[at(0, 0)].screen, 30, 'usage credits screen time up to the hour boundary') -assertDeepEqual(usage[at(1, 0)], { screen: 30, plugged: 0, used: 1, level: 79 }, 'usage credits the rest to the new hour') -const dipped = battery.recordUsage(usage, { at: at(1, 30), plugged: true, screenOn: true, level: 60 }, { at: at(1, 60), plugged: true, screenOn: true, level: 79 }, 90) -assertEqual(dipped[at(1, 0)].used, 1, 'usage keeps a drop that was charged back within the hour') +const hourAt = (hour, seconds) => 1000 * H + hour * H + seconds +let usage = battery.recordUsage({}, null, { at: hourAt(0, 3000), plugged: false, screenOn: true, level: 80 }, 90) +assertDeepEqual(usage, { [hourAt(0, 0)]: { screen: 0, plugged: 0, used: 0, level: 80 } }, 'usage starts with the level and no time') +usage = battery.recordUsage(usage, { at: hourAt(0, 3570), plugged: false, screenOn: true, level: 80 }, { at: hourAt(1, 30), plugged: false, screenOn: true, level: 79 }, 90) +assertEqual(usage[hourAt(0, 0)].screen, 30, 'usage credits screen time up to the hour boundary') +assertDeepEqual(usage[hourAt(1, 0)], { screen: 30, plugged: 0, used: 1, level: 79 }, 'usage credits the rest to the new hour') +const dipped = battery.recordUsage(usage, { at: hourAt(1, 30), plugged: true, screenOn: true, level: 60 }, { at: hourAt(1, 60), plugged: true, screenOn: true, level: 79 }, 90) +assertEqual(dipped[hourAt(1, 0)].used, 1, 'usage keeps a drop that was charged back within the hour') -const slept = battery.recordUsage(usage, { at: at(1, 30), plugged: true, screenOn: true }, { at: at(4, 0), plugged: true, screenOn: true, level: 100 }, 90) -assertEqual(slept[at(2, 0)].screen, 0, 'usage counts no screen time across a suspend') -assertEqual(slept[at(2, 0)].plugged, H, 'usage counts a suspend plugged in at both ends as on power') -assertEqual(slept[at(2, 0)].level, undefined, 'usage has no level for an hour spent asleep') -const unplugged = battery.recordUsage(usage, { at: at(1, 30), plugged: true, screenOn: true }, { at: at(4, 0), plugged: false, screenOn: true, level: 70 }, 90) -assertEqual(unplugged[at(2, 0)], undefined, 'usage does not count a suspend that ended unplugged as on power') +const slept = battery.recordUsage(usage, { at: hourAt(1, 30), plugged: true, screenOn: true }, { at: hourAt(4, 0), plugged: true, screenOn: true, level: 100 }, 90) +assertEqual(slept[hourAt(2, 0)].screen, 0, 'usage counts no screen time across a suspend') +assertEqual(slept[hourAt(2, 0)].plugged, H, 'usage counts a suspend plugged in at both ends as on power') +assertEqual(slept[hourAt(2, 0)].level, undefined, 'usage has no level for an hour spent asleep') +const unplugged = battery.recordUsage(usage, { at: hourAt(1, 30), plugged: true, screenOn: true }, { at: hourAt(4, 0), plugged: false, screenOn: true, level: 70 }, 90) +assertEqual(unplugged[hourAt(2, 0)], undefined, 'usage does not count a suspend that ended unplugged as on power') -const aged = battery.recordUsage(usage, { at: at(30, 0), plugged: false, screenOn: false }, { at: at(30, 30), plugged: false, screenOn: false, level: 50 }, 90) -assertDeepEqual(Object.keys(aged), [String(at(30, 0))], 'usage drops hours older than a day') -assertEqual(battery.recordUsage(usage, { at: at(1, 30), plugged: false, screenOn: false, level: 79 }, { at: at(60, 0), plugged: false, screenOn: false, level: 20 }, 90)[at(60, 0)].used, 0, 'usage leaves out a drop that spans more than the day it keeps') +const aged = battery.recordUsage(usage, { at: hourAt(30, 0), plugged: false, screenOn: false }, { at: hourAt(30, 30), plugged: false, screenOn: false, level: 50 }, 90) +assertDeepEqual(Object.keys(aged), [String(hourAt(30, 0))], 'usage drops hours older than a day') +assertEqual(battery.recordUsage(usage, { at: hourAt(1, 30), plugged: false, screenOn: false, level: 79 }, { at: hourAt(60, 0), plugged: false, screenOn: false, level: 20 }, 90)[hourAt(60, 0)].used, 0, 'usage leaves out a drop that spans more than the day it keeps') assertDeepEqual(battery.parseUsage('not json'), {}, 'usage reads a broken file as empty') assert( From 55451e71b4516dca44391aaf016c7ccbb2038407 Mon Sep 17 00:00:00 2001 From: Taksh Date: Wed, 2 Dec 2026 08:56:59 +0530 Subject: [PATCH 19/19] Serialize low battery warnings and recovery dismissal --- docs/notifications.md | 2 +- shell/plugins/services/battery/Service.qml | 17 ++++++++++------- test/shell.d/battery-test.sh | 22 ++++++++++++++++++++++ 3 files changed, 33 insertions(+), 8 deletions(-) diff --git a/docs/notifications.md b/docs/notifications.md index 12215f8e6124..45c7f26eb49e 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -206,7 +206,7 @@ The `notifications` IPC target also answers `ping` (used by `omarchy-notificatio Everything goes through the same sender contract, so the pieces are small: -- **Low battery** — `omarchy-battery-low` sends a normal toast that expires after 30 seconds (paused, like any card, while the deck is open) and runs the `battery-low` hook. Not critical: a critical toast never expires and comes back on every shell start, so the warning would outlive the charger going in. As an `omarchy-action` toast it still gets through Do Not Disturb. +- **Low battery** — `omarchy-battery-low` sends a critical, transient warning at 20% and again at 10%, and runs the `battery-low` hook. Each warning remains until dismissed or until charging starts or the battery recovers above 20%; recovery waits for any active sender to finish before dismissing its card. Transient warnings are not restored from notification history after a shell restart; the battery service rechecks the current reading and warns again if needed. The warning gets through Do Not Disturb. - **Charger connected** — when line power arrives after the machine has been on battery, `omarchy-battery-plugged` sends a normal transient toast. A flip shorter than two seconds is ignored, so a USB-C renegotiation or a UPower reading that settles at startup does not announce a charger that was not just plugged in. A confirmation already earned survives a reconnect inside that window, and is dropped only if the machine stays on battery through it. - **Crash capture** — `omarchy-crash-watch` follows the systemd-coredump journal stream and announces each crashed program (deduped per minute) as a diff --git a/shell/plugins/services/battery/Service.qml b/shell/plugins/services/battery/Service.qml index aa80abf74df2..b950bd82c0fc 100644 --- a/shell/plugins/services/battery/Service.qml +++ b/shell/plugins/services/battery/Service.qml @@ -102,7 +102,7 @@ Item { lowBatteryWarnedAt = state.warnedAt if (state.notify) sendLowBatteryWarning(state.level) var shouldDismissWarning = BatteryModel.shouldDismissLowBatteryWarning(UPower.displayDevice, UPowerDeviceState.Discharging, persisted.lowBatteryWarningVisible, lowBatteryWarningRecoveryThreshold) - if (shouldDismissWarning && !warningDismissProcess.running) { + if (shouldDismissWarning && !warningProcess.running && !warningDismissProcess.running) { warningDismissRearmRequested = warningDismissRearmRequested || BatteryModel.shouldRearmLowBatteryWarning(UPower.displayDevice, UPowerDeviceState.Discharging) warningDismissProcess.running = true } @@ -122,6 +122,14 @@ Item { return true } + function finishLowBatteryWarning() { + var recovered = BatteryModel.shouldDismissLowBatteryWarning(UPower.displayDevice, UPowerDeviceState.Discharging, true, lowBatteryWarningRecoveryThreshold) + var level = pendingWarningLevel + pendingWarningLevel = -1 + if (!recovered && level >= 0) sendLowBatteryWarning(level) + checkBattery() + } + function applyPowerProfile() { pendingPowerSource = UPower.onBattery ? "battery" : "ac" if (!powerProfileProcess.running) runPendingPowerProfile() @@ -200,12 +208,7 @@ Item { Process { id: warningProcess - onExited: { - if (root.pendingWarningLevel < 0) return - var level = root.pendingWarningLevel - root.pendingWarningLevel = -1 - root.sendLowBatteryWarning(level) - } + onExited: Qt.callLater(root.finishLowBatteryWarning) } Process { id: chargerAnnounceProcess } diff --git a/test/shell.d/battery-test.sh b/test/shell.d/battery-test.sh index 150485365a28..4ac36aa8ab46 100644 --- a/test/shell.d/battery-test.sh +++ b/test/shell.d/battery-test.sh @@ -275,3 +275,25 @@ if command -v quickshell >/dev/null && command -v dbus-run-session >/dev/null; t else skip "Quickshell and dbus-run-session are needed for the charge-limit retry fixture" fi + +run_node_test <<'JS' +const fs = require('fs') +const source = fs.readFileSync(root + '/shell/plugins/services/battery/Service.qml', 'utf8') +const names = ['checkBattery', 'sendLowBatteryWarning', 'finishLowBatteryWarning'] +const functions = names.map(name => source.match(new RegExp('function ' + name + '\\([^]*?\\n \\}'))[0]).join('\n') +const device = { isPresent: true, state: 1, percentage: 0.09 } +const warningProcess = { running: true } +const warningDismissProcess = { running: false } +const persisted = { lowBatteryWarningVisible: true } +const state = { lowBatteryWarnedAt: 10, batteryThresholds: [20, 10], lowBatteryWarningRecoveryThreshold: 20, pendingWarningLevel: 9, warningDismissRearmRequested: false } +const api = new Function('state', 'warningProcess', 'warningDismissProcess', 'persisted', 'UPower', 'UPowerDeviceState', 'BatteryModel', 'with(state) { ' + functions + '; return {checkBattery, finishLowBatteryWarning} }')(state, warningProcess, warningDismissProcess, persisted, {displayDevice: device}, {Discharging: 1}, requireFromRoot('shell/plugins/services/battery/BatteryModel.js')) +warningProcess.running = false +api.finishLowBatteryWarning() +assertEqual(warningProcess.running, true, 'a queued threshold starts after the previous sender stops') +device.state = 2 +api.checkBattery() +assertEqual(warningDismissProcess.running, false, 'charging waits for the active warning sender before dismissing') +warningProcess.running = false +api.finishLowBatteryWarning() +assertEqual(warningDismissProcess.running, true, 'sender completion rechecks charging and dismisses the posted warning') +JS