Repository navigation
Fix keyboard backlight not restoring correctly after lock - #8119
Alkiviadroot wants to merge 5 commits into
Conversation
There was a problem hiding this comment.
Pull request overview
Improves keyboard-backlight restoration across lock and suspend cycles.
Changes:
- Queues overlapping wake requests.
- Tracks hardware-driven keyboard brightness changes.
- Adds static regression assertions.
Tip
If you aren't ready for review, convert to a draft PR.
Click "Convert to draft" or run gh pr ready --undo.
Click "Ready for review" or run gh pr ready to reengage.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
shell/plugins/lock/Service.qml |
Implements queued wake and conditional backlight restoration. |
test/shell.d/lock-keyboard-backlight-restore-test.sh |
Adds structural regression checks. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
A wake request fired while another was already running was silently dropped instead of retried, so the keyboard-restore step it carried could simply vanish. Restore also ran unconditionally on every unlock, which could overwrite a brightness set by a firmware-handled key with a stale value from a much earlier session. Track the keyboard's actual brightness directly via the LED class's brightness_hw_changed notification (poll()-based, zero cost while idle) instead of relying on brightnessctl's own saved state, which is only ever updated by scripts this shell calls and so never learns about a hardware-driven change. Only restore when this lock session actually warrants it: either it blanked the keyboard itself, or a suspend was detected that could have reset it independently. Falls back gracefully on hardware whose driver doesn't support the notification, rather than looping forever trying to open a file that never exists.
brightness_hw_changed only fires for driver-notified hardware changes, not for a normal software write -- like the default keyboard bindings in default/hypr/bindings/media.lua, which call omarchy-brightness-keyboard and write brightness directly. On hardware where the physical key routes through that script rather than being handled entirely in firmware, the poll-tracked baseline never followed it, so restore could hand back a stale value from session startup. Track which restore is actually correct: once runBlank() has run the real off, brightnessctl's own save is trustworthy again -- it captured whatever was current, software- or hardware-driven, at that moment. The poll-tracked value is now only ever a fallback for the one case that still needs it: a suspend detected without the blank timer having gotten a turn, where brightnessctl's saved state was never updated.
Before the first hardware-notified brightness change since boot, the kernel has nothing to report yet and brightness_hw_changed reads raise ENODATA rather than returning content. The uncaught read crashed the watcher immediately on a clean boot, and every restart hit the same error until a notification happened to land during one of the brief windows it was actually running. Swallow only ENODATA, on the priming read and after each wake alike; any other read error still surfaces. The poll registers regardless of whether there was anything to prime, so it still reliably wakes on the first real notification.
74025a2 to
82ba51e
Compare
…estore brightnessctl's -s/-r semantics trust whatever is current right before an off call to be the real value. That assumption breaks on hardware where the EC can dim the keyboard on its own within ~2ms of a lock request -- measured directly, faster than any software off call can run -- so by the time the "real" off runs, it saves the value the EC already zeroed. A genuine suspend can also reset the keyboard through a delayed USB re-enumeration a couple of seconds after resume (kernel log: "xHC error in resume ... Reinit"), with no brightness_hw_changed notification for either case: the watcher process is itself frozen by the suspend when the first happens, and the second isn't a driver-visible LED change at all. Replace both paths with one independently-tracked value. A periodic snapshot while unlocked -- sampling on a schedule that shares no trigger with locking or suspend -- sidesteps the race entirely, since it never depends on catching the exact instant of a hardware change, only on having asked recently enough that the answer is still true. A follow-up reapply a few seconds after a restore wins against the delayed USB-reset case, which has nothing to notify against so it can only be corrected after the fact. Also fix a related detection gap: idleBlankTimer's own suspend check only runs if the Timer gets an uninterrupted turn to fire, but a resume replays a burst of a dozen-plus wake nudges within about three seconds, each re-arming the timer from scratch before its five-second deadline is ever reached -- so onTriggered never ran at all for the rest of that lock session. Checking the same gap on every re-arm, not only on an actual firing, catches it regardless: the first re-arm in that burst still sees the full frozen-duration gap against the arm from before the suspend, even though the Timer object itself never got a turn to react to it. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01TVqsieYd6Lm6UopwE4CFFn
The idle-blank timer's normal branch fires again any time it goes 5s without a wake nudge to re-arm it, with no memory of whether it already blanked and restored once already. Pausing for more than 5s anywhere between the lock screen becoming visible -- whether from a fresh lock or a resume -- and actually typing the password was enough to trigger it again, dimming the keyboard and immediately re-lighting it the moment typing resumed: a real, user-visible flicker, not a bug in the restored value itself. keyboardRestoredOnce tracks whether a restore has actually run this lock session and suppresses that branch once it has. It still has to re-arm the timer when suppressing rather than skip outright: without that, armedAt is left at whatever it was several seconds ago, so the next wake -- whenever that happens to be -- sees a large gap against that stale value and misreads ordinary idle time as another suspend (measured: this exact sequence re-triggered the suspend-detected branch on a plain pause, no suspend involved). Re-arming keeps the elapsed-time math honest for whichever branch runs next, while the keyboard itself is never touched again this session. Also schedule the reapply this fix's sibling commit added independently at actual unlock: the delayed hardware reset it exists to counter has been measured landing a second or so after the unlock transition itself, not only after a resume, with no correlation to whether that particular wake needed to restore anything. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01TVqsieYd6Lm6UopwE4CFFn
|
Reviewed at 99758b9 against The bug is real and common: This pull request works around that inside the lock screen rather than fixing it at the cause. It adds 281 lines to
Other open pull requests fix the cause in Two parts of this pull request would still be worth having on top of that fix, each as its own small pull request:
This is waiting on the maintainer to choose between the competing fixes. |
The keyboard backlight can silently stay off after unlocking, or return to a stale brightness instead of what was actually set. Two independent bugs, both in
shell/plugins/lock/Service.qml.Bug 1: the restore call could be silently dropped
runWake()guardswakeProcesswith a plain running check:A lock session fires
runWake()constantly — password-field keystrokes, mouse movement, failed attempts,finishUnlock()itself. If any of those calls lands while a previous invocation ofwakeProcessis still running, it's just discarded with nothing to retry it. Caught it directly in the wild:The exact call that was supposed to restore the keyboard on unlock vanished. It only "worked" by coincidence when some other in-flight invocation happened to also restore state.
Bug 2: restore ran unconditionally, using the wrong source of truth
Even when the restore call did fire, it ran on every unlock regardless of whether this session ever actually dimmed the keyboard, and it targeted
brightnessctl's own saved-state file — which is only updated by an explicitoffcall. A firmware-handled brightness key (Fn+key on many ThinkPads and others) changes the LED directly in hardware, with no script involved and no saved-state update. Result: locking and unlocking without the idle-blank timer ever firing could silently overwrite a value you'd just set by hand with something from a much earlier, unrelated session.Confirmed this is a real hardware behavior, not a software artifact — a raw suspend/resume via
rtcwake, entirely outside the lock flow, left the value untouched; but the EC visibly zeroes the keyboard LED the instant the lid physically closes, independent of anything Omarchy does, well before this session's own idle-blank timer (5s) would ever fire.The fix
Queue instead of drop.
runWake()now setswakeRerunRequestedwhen a wake is already in flight, andwakeProcess.onExitedreruns once more if that flag is set. Never silently loses a request again.Only restore when warranted. A new
keyboardBlankedflag is set when this session's own blank timer fires, or when the suspend-frozen guard detects a resume (the EC can reset the LED across suspend independent of whether the blank timer ever ran). The wake command only restores the keyboard when this flag is true — otherwise a value untouched by this session is left alone.Track the real value directly, not brightnessctl's saved state. The LED class exposes
brightness_hw_changed, apoll()-able attribute the driver notifies on hardware-driven changes (only on drivers that callled_classdev_notify_brightness_hw_changed()— checked for and skipped gracefully if absent, so this never loops trying to open a file that doesn't exist). A small watcher process blocks onPOLLPRIagainst that file at zero cost while idle, and reports the live value the instant the EC changes it — including a firmware key press with no software path at all. Tracking freezes for a session's entire lock (tied tolocked, not toggled around individual events — an earlier version of this that toggled it manually aroundbeginLock/onExitedreintroduced exactly the corruption it was meant to prevent, since any mid-lock wake nudge would prematurely re-enable it) so nothing during the lock (the blank, a suspend reset, an EC quirk) can corrupt the value before the real unlock uses it.Considered and rejected a polling-timer approach before landing on the
poll()-based watcher: a 1s timer works but is strictly worse on both axes that matter — it costs periodic wakeups even while idle, and it lost the same tight-timing race (Fn+key immediately followed by locking) that the event-driven version wins outright, since the watcher reacts to the kernel notification essentially instantly rather than on the next tick.Verification
Extensive manual testing on a ThinkPad T14 Gen 1 (
tpacpi::kbd_backlight,brightness_hw_changedsupported), across repeated runs of each:poll()-based watchertest/shell: addedtest/shell.d/lock-keyboard-backlight-restore-test.sh(13 assertions covering both fixes). Full suite: all lock/sleep-related tests pass; the only failures in./test/all(4 of 199 files) are pre-existing environment issues unrelated to this change (missingomarchy-pkgscompanion checkout), confirmed identical on a clean, unmodified checkout of the same commit.Update: this held up on the ThinkPad above, then broke on it again
Same laptop, no config changes — the difference was a routine
pacman -Syu(kernel7.1.8 → 7.1.9, Omarchy4.0.0 → 4.0.2,quickshell-gitswapped for the stablequickshell0.3.1 package) and, separately, installing a community plugin that adds its own/usr/lib/systemd/system-sleep/hook. Neither touches this file. What changed is how long and how eventful a real suspend/resume now is on this machine, and the original fix's timing assumptions didn't survive that.Bug 3: the suspend check depends on a Timer that may never get a turn to fire
idleBlankTimer.onTriggered's own frozen-timer check only runs if the Timer actually fires. Measured directly: a resume replays a burst of a dozen-plusrunWake()calls within about three seconds (screen/cursor/output reconnect events), and each one callsarmBlankTimer(), restarting the five-second countdown from scratch. The timer never survives long enough between nudges to reach its own deadline, soonTriggered— and the suspend check inside it — never ran at all for the rest of that lock session.keyboardBlankedstayed false, and the wake command's restore branch never engaged.Fixed by checking the same gap on every re-arm inside
armBlankTimer()itself, not only when the Timer gets an uninterrupted turn to fire. The first re-arm in a post-resume burst still sees the full frozen-duration gap against the arm from before the suspend, even though the Timer object itself never got to react to it on its own.Bug 4:
brightnessctl's-s/-rsave-restore isn't trustworthy on this hardware at allThe previous fix already moved off blind unconditional restore, but its
keyboardOffSavedpath still trusted brightnessctl's own-ssave — "whatever's current right before the off call" — as the correct value once this session's blank had run. Two things break that assumption here:catof the brightness sysfs file, started at the top ofbeginLock(), already read 0 before the process finished spawning). By the time software's own "real" off call runs, it's already saving the value the EC just zeroed.brightness_hw_changedever sees — it isn't a driver-visible LED change, so the watcher has nothing to catch.Fixed by dropping
keyboardOffSavedandbrightnessctl -rentirely.savedKeyboardBrightnessis now the single source of truth, refreshed by a lightweight periodic snapshot while unlocked (kbdBrightnessSnapshotTimer, 5s, onecatof the sysfs file — costs nothing while locked or suspended) rather than reactively at lock time. Sampling on a schedule that shares no trigger with locking or suspend means it never depends on catching the exact instant of a hardware change, only on having asked recently enough that the answer is still true — so neither of the two races above can poison it. A follow-up reapply 3s after a restore (and again 3s after actual unlock, since the same USB reset has also been measured landing there instead) re-asserts the value once more to win against the delayed reset, since there's nothing to detect and preempt it with.Bug 5 (UX): a visible off-then-on flicker once restores actually started working
A side effect of fixing Bug 3: the idle-blank timer's normal branch legitimately fires again any time it goes 5s without a nudge, with no memory of already having restored once. Pausing more than 5s anywhere between the lock screen becoming visible (fresh lock or resume) and actually typing the password re-dimmed the keyboard and immediately re-lit it the moment typing resumed — correct per the original design, but a jarring, user-visible flicker once the underlying restore was reliable enough to notice.
Fixed with
keyboardRestoredOnce: once a restore has run this session, the idle timer's normal branch re-arms itself (keeping the elapsed-time math in Bug 3's fix honest for whatever runs next) but never blanks again until the next full lock.Verification
All of the above found and fixed through direct, repeated manual testing on the same ThinkPad, now on kernel 7.1.9 / quickshell 0.3.1 / Omarchy 4.0.2 with a third-party sleep hook also in the chain:
keyboardRestoredOnceprevents any further dimming.xHC ... Reinitreset lands unpredictably — sometimes before actual unlock, sometimes ~1s after it — and that the reapply scheduled independently at both points (resume-restore and actual unlock) catches it within ~3s either way.brightness_hw_changedstill fires instantly and reliably for genuine hardware key presses — the periodic-snapshot redesign only replaces its role as the sole/primary source, it doesn't make it redundant.test/shell.d/lock-keyboard-backlight-restore-test.shupdated to 22 assertions covering the redesigned tracking, the re-arm-based suspend detection, and the flicker fix; the removedkeyboardOffSavedpath's assertions were removed with it.🤖 Generated with Claude Code
https://claude.ai/code/session_01TVqsieYd6Lm6UopwE4CFFn