Skip to content

Fix keyboard backlight not restoring correctly after lock - #8119

Open
Alkiviadroot wants to merge 5 commits into
omacom:quattrofrom
Alkiviadroot:fix-keyboard-backlight-lock-restore
Open

Alkiviadroot wants to merge 5 commits into
omacom:quattrofrom
Alkiviadroot:fix-keyboard-backlight-lock-restore

Conversation

@Alkiviadroot

@Alkiviadroot Alkiviadroot commented Aug 24, 2026 •

Copy link
Copy Markdown

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() guards wakeProcess with a plain running check:

function runWake() {
  if (!wakeProcess.running) wakeProcess.running = true
  if (lockRequested) armBlankTimer()
}

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 of wakeProcess is still running, it's just discarded with nothing to retry it. Caught it directly in the wild:

23:36:10.101Z unlocked
[DEBUG] finishUnlock -> calling runWake at 1787603770101
[DEBUG] runWake called at 1787603770101 wakeProcess.running=true
[DEBUG] runWake DROPPED (wakeProcess already running)

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 explicit off call. 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 sets wakeRerunRequested when a wake is already in flight, and wakeProcess.onExited reruns once more if that flag is set. Never silently loses a request again.

Only restore when warranted. A new keyboardBlanked flag 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, a poll()-able attribute the driver notifies on hardware-driven changes (only on drivers that call led_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 on POLLPRI against 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 to locked, not toggled around individual events — an earlier version of this that toggled it manually around beginLock/onExited reintroduced 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_changed supported), across repeated runs of each:

  • Manual lock (no suspend), natural 5s idle-blank → restores correctly
  • Lid-close-into-suspend → restores correctly, including the case where the EC's own dim happens with zero involvement from this session's blank logic
  • Brightness set via the firmware key immediately followed by locking (tight-timing race) → correctly captured and restored; this specifically failed under a 1s-polling version of the same fix and succeeds under the poll()-based watcher
  • All three brightness levels (off/1/2), both via software and the physical key
  • Idle behavior: watcher process confirmed via journal logging to fully stop polling during a real idle window (compositor idle-notify, not a timer) and resume instantly on activity
  • Control test: 15s window with the watcher active and nothing touched — zero spurious events

test/shell: added test/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 (missing omarchy-pkgs companion 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 (kernel 7.1.8 → 7.1.9, Omarchy 4.0.0 → 4.0.2, quickshell-git swapped for the stable quickshell 0.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-plus runWake() calls within about three seconds (screen/cursor/output reconnect events), and each one calls armBlankTimer(), restarting the five-second countdown from scratch. The timer never survives long enough between nudges to reach its own deadline, so onTriggered — and the suspend check inside it — never ran at all for the rest of that lock session. keyboardBlanked stayed 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/-r save-restore isn't trustworthy on this hardware at all

The previous fix already moved off blind unconditional restore, but its keyboardOffSaved path still trusted brightnessctl's own -s save — "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:

  • The EC can dim the keyboard on its own within ~2ms of a lock request (measured directly: a cat of the brightness sysfs file, started at the top of beginLock(), 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.
  • A genuine suspend can trigger a USB host-controller resume error a couple of seconds after wake:
    ACPI: PM: Waking up from system sleep state S3
    xhci_hcd 0000:2b:00.0: xHC error in resume, USBSTS 0x401, Reinit
    
    That forces a full USB re-enumeration, which resets the keyboard controller to a hardware default independent of anything either brightnessctl or brightness_hw_changed ever sees — it isn't a driver-visible LED change, so the watcher has nothing to catch.

Fixed by dropping keyboardOffSaved and brightnessctl -r entirely. savedKeyboardBrightness is now the single source of truth, refreshed by a lightweight periodic snapshot while unlocked (kbdBrightnessSnapshotTimer, 5s, one cat of 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:

  • Real lid-close-into-suspend, immediate unlock: restores correctly, keyboardRestoredOnce prevents any further dimming.
  • Real suspend with a long pause on the lock screen before typing the password (the exact case that used to false-positive as "another suspend" once Bug 3's fix was in without also fixing the re-arm staleness it introduced): no spurious re-blank, correct final value.
  • Repeated cycles confirming the xHC ... Reinit reset 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.
  • Confirmed via a standalone DPMS on/off cycle (no suspend, no lock) that display modesetting alone does not trigger the keyboard reset, isolating the cause to the suspend/resume path specifically.
  • Confirmed via direct Fn-key testing (12 rapid presses) that brightness_hw_changed still 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.sh updated to 22 assertions covering the redesigned tracking, the re-arm-based suspend detection, and the flicker fix; the removed keyboardOffSaved path's assertions were removed with it.


🤖 Generated with Claude Code

https://claude.ai/code/session_01TVqsieYd6Lm6UopwE4CFFn

Copilot AI balanced review requested due to automatic review settings August 24, 2026 23:25

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread shell/plugins/lock/Service.qml Resolved
Comment thread shell/plugins/lock/Service.qml Resolved
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.
@Alkiviadroot
Alkiviadroot force-pushed the fix-keyboard-backlight-lock-restore branch from 74025a2 to 82ba51e Compare September 13, 2026 07:47
Alkiviadroot and others added 2 commits September 13, 2026 12:44
…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
@omarchybot omarchybot added the bug Something isn't working label Sep 27, 2026
@omarchybot

Copy link
Copy Markdown
Collaborator

Reviewed at 99758b9 against quattro, by reading the diff, the lock and idle services, omarchy-brightness-keyboard and omarchy-system-wake, and the other open pull requests fixing the same symptom. Nothing was run: this pull request competes with smaller fixes for the same bug, so it was not taken to a worker. Reviewed by Claude Opus 5.5 alone; the second opinion (Codex) did not run, because omabot's review budget for the day was spent, so no second model has checked this.

The bug is real and common: omarchy-brightness-keyboard off saves with brightnessctl -s every time it runs (bin/omarchy-brightness-keyboard:29), so an off that lands while the keyboard is already dark (a repeated blank, or firmware that dimmed it first) saves 0 over the real level, and the next restore brings back 0.

This pull request works around that inside the lock screen rather than fixing it at the cause. It adds 281 lines to shell/plugins/lock/Service.qml: a Python brightness_hw_changed watcher, a cat of sysfs every 5 seconds for as long as the session is unlocked, two reapply timers, and a copy of omarchy-system-wake inlined into the QML. What that costs:

  • The idle service still wakes through omarchy-system-wake (shell/plugins/services/idle/Service.qml:108), which still restores from brightnessctl -r, so the saved-state problem this pull request describes stays in place on that path.
  • On the many laptops whose LED driver has no brightness_hw_changed, the value restored is the last 5-second snapshot. If you change the keyboard brightness and lock within 5 seconds, unlocking brings back the old level. On quattro the value is captured when the blank runs, so this is a regression.
  • The xHCI re-enumeration and EC timing that the reapply timers work around were measured on one ThinkPad T14 Gen 1. That is a hardware compatibility question, and it lands as code every machine runs.

Other open pull requests fix the cause in bin/omarchy-brightness-keyboard itself, which puts the fix on both the lock and idle paths: #10364 (save once per blank cycle, and drop the save when you change brightness by hand), #12960 (save only when the level is above 0), and #12502. Of these, #10364 looks like the most complete proportionate fix. Only one of them should land.

Two parts of this pull request would still be worth having on top of that fix, each as its own small pull request:

  • The queued rerun in runWake(), so a wake that arrives while one is running is not dropped.
  • The ThinkPad-specific handling, if the maintainer wants to carry it.

This is waiting on the maintainer to choose between the competing fixes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants