Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Keep laptop brightness controls independent and usable (#738)

Deebaee40bff639
diff --git a/.github/workflows/os-input.yml b/.github/workflows/os-input.yml
new file mode 100644
index 000000000..bf7978365
--- /dev/null
+++ b/.github/workflows/os-input.yml
@@ -0,0 +1,54 @@
+name: Harness OS laptop input
+
+on:
+ workflow_dispatch:
+ inputs:
+ image_run_id:
+ description: 'Exact Harness OS image artifact to assess'
+ type: string
+ default: '37222390225'
+ required: true
+ push:
+ branches: ['os-polish/laptop-input']
+ paths: ['os/tests/input_*.py', 'os/root/usr/share/harness-os/labwc*/rc.xml', '.github/workflows/os-input.yml']
+
+permissions:
+ contents: read
+ actions: read
+
+concurrency:
+ group: harness-input-${{ github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ input:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/download-artifact@v6
+ with:
+ name: programmer-os-x86_64
+ path: os/dist
+ run-id: ${{ inputs.image_run_id || '37222390225' }}
+ github-token: ${{ github.token }}
+ - name: Check source and install native VM tools
+ run: |
+ make -C os check
+ go run github.com/rhysd/actionlint/cmd/[email protected] .github/workflows/os-input.yml
+ sudo apt-get update -qq
+ sudo apt-get install -y --no-install-recommends qemu-system-x86 qemu-utils ovmf python3-pil tesseract-ocr
+ sudo chmod a+rw /dev/kvm
+ - name: Check actual media-key input on USB and installed sessions
+ run: python3 os/tests/input_vm.py --iso os/dist/*.iso
+ - name: Retain actual input, module and display evidence
+ if: always()
+ uses: actions/upload-artifact@v6
+ with:
+ name: harness-os-laptop-input
+ path: |
+ os/test-results/input/
+ !os/test-results/input/*.qcow2
+ !os/test-results/input/OVMF_VARS.fd
+ retention-days: 14
+ compression-level: 0
diff --git a/os/DEVELOPMENT.md b/os/DEVELOPMENT.md
index 54dcf0a23..6a666fa13 100644
--- a/os/DEVELOPMENT.md
+++ b/os/DEVELOPMENT.md
@@ -58,6 +58,22 @@ keys, and checks DHCP, DNS, HTTP, reconnection and non-silent audio output. Acce
point tools are installed only inside the disposable guest, never in the ISO.
Physical radio, backlight, speaker and microphone tests remain separate.
+The **Harness OS laptop input** workflow exercises both compositor configurations
+on an exact image: USB installation, then an encrypted installed session. A
+test-only uinput keyboard sends real display/keyboard brightness events. The
+packaged brightnessctl writes a synthetic panel fixture and a real kernel
+`uleds` keyboard light. The latter retains normal device permissions, so the test
+also checks access from the active graphical session. It checks a nonzero display
+floor, small-range panels, independent keyboard illumination, absent displays,
+unrelated LEDs and ordinary typing afterward. No test devices or tools enter the
+image. This establishes input routing and driver-interface behavior, not physical
+panel brightness or Apple firmware support.
+
+Display controls explicitly select the backlight class and keep a minimum value
+of one; keyboard controls select only `*::kbd_backlight` LEDs. These use the
+existing [brightnessctl options](https://github.com/Hummer12007/brightnessctl).
+No extra daemon, package, widget or screen is required.
+
`checks=browser` with an `image_run_id` exercises the installed terminal/browser
session in BIOS/plain and UEFI/encrypted VMs. It records and applies only the
candidate `hn-browser` script and labwc configuration over the checksum-verified
diff --git a/os/root/usr/share/harness-os/guide.md b/os/root/usr/share/harness-os/guide.md
index eb9a296c2..b20f6693c 100644
--- a/os/root/usr/share/harness-os/guide.md
+++ b/os/root/usr/share/harness-os/guide.md
@@ -112,7 +112,9 @@ conversation history. Describe only collaboration controls present in this TUI.
- Super+w opens Wi-Fi. Ethernet connects automatically when available.
- Super+n opens New Harness; Super+t opens a terminal; Super+m connects a computer.
- Super+b switches between Harness and the browser. Super+Enter focuses Harness.
-- Super+l locks the screen. Brightness and volume keys operate supported hardware.
+- Super+l locks the screen. Brightness, keyboard-backlight and volume keys operate
+ supported hardware. Display brightness keys keep a nonzero minimum; keyboard
+ illumination can be turned off independently.
- Super+u starts updates after installation; the Update button is clickable too.
No confirmation or password is needed. Restart only when ready. Updates keep projects and running
work; flashing another USB is not the everyday update workflow.
diff --git a/os/root/usr/share/harness-os/labwc-install/rc.xml b/os/root/usr/share/harness-os/labwc-install/rc.xml
index 6e28ea77c..58e03d74a 100644
--- a/os/root/usr/share/harness-os/labwc-install/rc.xml
+++ b/os/root/usr/share/harness-os/labwc-install/rc.xml
@@ -5,8 +5,10 @@
<desktops><number>1</number><popupTime>0</popupTime></desktops>
<keyboard>
<repeatRate>35</repeatRate><repeatDelay>250</repeatDelay>
- <keybind key="XF86MonBrightnessUp"><action name="Execute" command="brightnessctl set +5%" /></keybind>
- <keybind key="XF86MonBrightnessDown"><action name="Execute" command="brightnessctl set 5%-" /></keybind>
+ <keybind key="XF86MonBrightnessUp"><action name="Execute" command="brightnessctl --class=backlight --min-value=1 set +5%" /></keybind>
+ <keybind key="XF86MonBrightnessDown"><action name="Execute" command="brightnessctl --class=backlight --min-value=1 set 5%-" /></keybind>
+ <keybind key="XF86KbdBrightnessUp"><action name="Execute" command="brightnessctl --class=leds --device='*::kbd_backlight' set +10%" /></keybind>
+ <keybind key="XF86KbdBrightnessDown"><action name="Execute" command="brightnessctl --class=leds --device='*::kbd_backlight' set 10%-" /></keybind>
</keyboard>
<mouse><context name="Root"><mousebind button="Right" action="Press"><action name="None" /></mousebind></context></mouse>
<windowRules><windowRule identifier="hn" serverDecoration="no" /></windowRules>
diff --git a/os/root/usr/share/harness-os/labwc/rc.xml b/os/root/usr/share/harness-os/labwc/rc.xml
index 6b585b01c..905d27484 100644
--- a/os/root/usr/share/harness-os/labwc/rc.xml
+++ b/os/root/usr/share/harness-os/labwc/rc.xml
@@ -41,8 +41,10 @@
<action name="Execute" command="hn os-action connect" />
<action name="ForEach"><query identifier="hn" /><then><action name="Raise" /><action name="Focus" /></then></action>
</keybind>
- <keybind key="XF86MonBrightnessUp"><action name="Execute" command="brightnessctl set +5%" /></keybind>
- <keybind key="XF86MonBrightnessDown"><action name="Execute" command="brightnessctl set 5%-" /></keybind>
+ <keybind key="XF86MonBrightnessUp"><action name="Execute" command="brightnessctl --class=backlight --min-value=1 set +5%" /></keybind>
+ <keybind key="XF86MonBrightnessDown"><action name="Execute" command="brightnessctl --class=backlight --min-value=1 set 5%-" /></keybind>
+ <keybind key="XF86KbdBrightnessUp"><action name="Execute" command="brightnessctl --class=leds --device='*::kbd_backlight' set +10%" /></keybind>
+ <keybind key="XF86KbdBrightnessDown"><action name="Execute" command="brightnessctl --class=leds --device='*::kbd_backlight' set 10%-" /></keybind>
<keybind key="XF86AudioRaiseVolume"><action name="Execute" command="wpctl set-volume @DEFAULT_AUDIO_SINK@ 5%+ -l 1" /></keybind>
<keybind key="XF86AudioLowerVolume"><action name="Execute" command="wpctl set-volume @DEFAULT_AUDIO_SINK@ 5%-" /></keybind>
<keybind key="XF86AudioMute"><action name="Execute" command="wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle" /></keybind>
diff --git a/os/tests/input_guest.py b/os/tests/input_guest.py
new file mode 100644
index 000000000..f1c25e52c
--- /dev/null
+++ b/os/tests/input_guest.py
@@ -0,0 +1,205 @@
+#!/usr/bin/env python3
+"""Test actual media-key dispatch, with a synthetic panel and kernel user LEDs.
+
+Runs only in our disposable VM. The display backlight files are a test fixture;
+keyboard illumination uses Linux uleds and the normal session permissions.
+Neither this program nor the devices enter a shipped image.
+"""
+import argparse
+import fcntl
+import json
+import os
+from pathlib import Path
+import signal
+import struct
+import subprocess
+import time
+
+ROOT = Path('/run/harness-input-test')
+PANEL = ROOT / 'backlight/harness_panel'
+LEDS = Path('/sys/class/leds')
+KEYS = {'down': 224, 'up': 225, 'keyboard-down': 229, 'keyboard-up': 230}
+
+
+def run(*args, check=True):
+ return subprocess.run(args, text=True, capture_output=True, check=check)
+
+
+def read(path):
+ return int(path.read_text().strip())
+
+
+class Input:
+ def __enter__(self):
+ run('modprobe', 'uinput')
+ self.fd = os.open('/dev/uinput', os.O_WRONLY | os.O_NONBLOCK)
+ # Linux uinput ABI: EV_KEY and the ordinary keyboard range make udev
+ # recognize this as a keyboard. Only the requested key is ever emitted.
+ fcntl.ioctl(self.fd, 0x40045564, 1)
+ for code in range(1, 256):
+ fcntl.ioctl(self.fd, 0x40045565, code)
+ device = struct.pack('80sHHHHI', b'Harness disposable input test', 3, 1, 1, 1, 0)
+ os.write(self.fd, device + bytes(4 * 64 * 4))
+ fcntl.ioctl(self.fd, 0x5501)
+ run('udevadm', 'settle', '--timeout=10')
+ time.sleep(1) # libinput hotplug follows udev; effects are checked below.
+ return self
+
+ def press(self, key):
+ for value in [1, 0]:
+ os.write(self.fd, struct.pack('llHHi', 0, 0, 1, KEYS[key], value))
+ os.write(self.fd, struct.pack('llHHi', 0, 0, 0, 0, 0))
+ time.sleep(.06)
+
+ def __exit__(self, *_):
+ fcntl.ioctl(self.fd, 0x5502)
+ os.close(self.fd)
+
+
+class KeyboardLight:
+ name = 'harness-test::kbd_backlight'
+
+ def __enter__(self):
+ run('modprobe', 'uleds')
+ self.fd = os.open('/dev/uleds', os.O_RDWR | os.O_NONBLOCK)
+ os.write(self.fd, struct.pack('64si', self.name.encode(), 100))
+ run('udevadm', 'settle', '--timeout=10')
+ self.path = LEDS / self.name / 'brightness'
+ assert self.path.exists(), 'The kernel did not create the test LED'
+ self.path.write_text('50\n')
+ return self
+
+ def __exit__(self, *_):
+ os.close(self.fd)
+
+
+def panel(maximum=100, current=50):
+ PANEL.mkdir(parents=True, exist_ok=True)
+ (PANEL / 'max_brightness').write_text(str(maximum))
+ (PANEL / 'brightness').write_text(str(current))
+ # Equivalent to a writable device granted by udev; the real LED below tests
+ # logind access separately, without altering its kernel-owned permissions.
+ os.chown(PANEL / 'brightness', 1000, -1)
+
+
+def effect(keys, key, path, expected, events):
+ before = read(path)
+ started = time.monotonic()
+ keys.press(key)
+ while read(path) != expected:
+ assert time.monotonic() - started < 5, (key, str(path), before, read(path), expected)
+ time.sleep(.05)
+ # Keep assertions that already match the initial value from racing a late
+ # compositor command, especially the floor and maximum-bound cases.
+ time.sleep(.15)
+ assert read(path) == expected
+ events.append({'key': key, 'path': str(path), 'before': before,
+ 'after': expected, 'seconds': round(time.monotonic() - started, 3)})
+
+
+def led_values():
+ return {p.parent.name: read(p) for p in LEDS.glob('*/brightness')}
+
+
+def audit_boot():
+ result = {'scope': 'Packaged module availability and generic VM initramfs inventory; not Apple keyboard operation',
+ 'modules': {}, 'initramfs': {}}
+ names = ['hid_apple', 'applespi', 'spi_pxa2xx_platform', 'spi_pxa2xx_pci', 'intel_lpss_pci']
+ for name in names:
+ info = run('modinfo', name, check=False)
+ result['modules'][name] = {'exit_code': info.returncode, 'info': info.stdout, 'error': info.stderr}
+ for path in Path('/boot').glob('initramfs-linux-lts*.img'):
+ listing = run('lsinitcpio', '-l', str(path))
+ result['initramfs'][path.name] = {name: [line for line in listing.stdout.splitlines()
+ if '/' + name.replace('_', '-') + '.ko' in line.replace('_', '-')]
+ for name in names}
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--candidate', type=Path, required=True)
+ parser.add_argument('--config', type=Path, required=True)
+ parser.add_argument('--output', type=Path, required=True)
+ parser.add_argument('--installed', action='store_true')
+ args = parser.parse_args()
+ assert os.geteuid() == 0
+ assert run('lsblk', '-ndo', 'SERIAL', '/dev/vda').stdout.strip() == 'HN_OS_TEST'
+ assert args.config in [Path('/usr/share/harness-os/labwc/rc.xml'),
+ Path('/usr/share/harness-os/labwc-install/rc.xml')]
+ ROOT.mkdir(exist_ok=True)
+ panel()
+ run('mount', '--bind', str(ROOT / 'backlight'), '/sys/class/backlight')
+ result = {'status': 'running', 'baseline': [], 'candidate': [],
+ 'fixture': 'Real compositor/uinput/brightnessctl; synthetic display files, real kernel uleds keyboard light',
+ 'brightnessctl_version': run('brightnessctl', '--version').stdout.strip()}
+ try:
+ with Input() as keys, KeyboardLight() as light:
+ mode = light.path.stat().st_mode & 0o777
+ result['keyboard_light'] = {'path': str(light.path), 'mode': oct(mode),
+ 'uid': light.path.stat().st_uid, 'gid': light.path.stat().st_gid,
+ 'user_groups': run('id', 'me').stdout.strip()}
+ # Retain the broken baseline using the released, unmodified config.
+ panel(current=5)
+ effect(keys, 'down', PANEL / 'brightness', 0, result['baseline'])
+ original_light = read(light.path)
+ keys.press('keyboard-up')
+ time.sleep(.4)
+ assert read(light.path) == original_light, 'Baseline already has a working keyboard-light binding'
+ result['baseline'].append({'missing_keyboard_binding': True})
+
+ args.config.write_bytes(args.candidate.read_bytes())
+ pids = run('pgrep', '-u', '1000', '-x', 'labwc').stdout.split()
+ assert len(pids) == 1, pids
+ os.kill(int(pids[0]), signal.SIGHUP)
+ time.sleep(.4)
+ events = result['candidate']
+ panel(current=50)
+ effect(keys, 'up', PANEL / 'brightness', 55, events)
+ effect(keys, 'down', PANEL / 'brightness', 50, events)
+ panel(current=5)
+ effect(keys, 'down', PANEL / 'brightness', 1, events)
+ effect(keys, 'down', PANEL / 'brightness', 1, events)
+ panel(current=99)
+ effect(keys, 'up', PANEL / 'brightness', 100, events)
+ # Small-range backlights still move by a real step and never hit 0.
+ panel(maximum=15, current=2)
+ effect(keys, 'down', PANEL / 'brightness', 1, events)
+ effect(keys, 'down', PANEL / 'brightness', 1, events)
+ effect(keys, 'up', PANEL / 'brightness', 2, events)
+ panel()
+ unrelated = {k: v for k, v in led_values().items() if k != light.name}
+ effect(keys, 'keyboard-up', light.path, 60, events)
+ effect(keys, 'keyboard-down', light.path, 50, events)
+ light.path.write_text('5\n')
+ effect(keys, 'keyboard-down', light.path, 0, events)
+ effect(keys, 'keyboard-up', light.path, 10, events)
+ light.path.write_text('99\n')
+ effect(keys, 'keyboard-up', light.path, 100, events)
+ assert {k: v for k, v in led_values().items() if k != light.name} == unrelated
+
+ # No display device: display keys must not fall through to any LED.
+ hidden = ROOT / 'hidden-panel'
+ PANEL.rename(hidden)
+ try:
+ before = led_values()
+ keys.press('up')
+ keys.press('down')
+ time.sleep(.5)
+ assert led_values() == before, 'Display keys changed an LED without a panel'
+ events.append({'absent_display_preserves_all_leds': True})
+ finally:
+ hidden.rename(PANEL)
+ if args.installed:
+ result['apple_boot_audit'] = audit_boot()
+ result['status'] = 'passed'
+ except BaseException as error:
+ result.update(status='failed', error=str(error))
+ raise
+ finally:
+ run('umount', '/sys/class/backlight')
+ args.output.write_text(json.dumps(result, indent=2) + '\n')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/tests/input_vm.py b/os/tests/input_vm.py
new file mode 100644
index 000000000..08b7e7d5d
--- /dev/null
+++ b/os/tests/input_vm.py
@@ -0,0 +1,111 @@
+#!/usr/bin/env python3
+"""Native laptop-key acceptance on a verified image, without physical Mac claims."""
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import shlex
+import subprocess
+import time
+from footprint_vm import copy_file
+from session_vm import screen_text
+from vm import VM
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--iso', type=Path, required=True)
+ parser.add_argument('--output', type=Path, default=Path('os/test-results/input'))
+ args = parser.parse_args()
+ assert os.access('/dev/kvm', os.R_OK | os.W_OK), 'Native KVM is required'
+ iso = args.iso.resolve()
+ manifest = json.loads(iso.with_name('manifest.json').read_text())
+ with iso.open('rb') as source:
+ assert hashlib.file_digest(source, 'sha256').hexdigest() == manifest['iso']['sha256']
+ assert iso.stat().st_size == manifest['iso']['bytes']
+ folder = args.output.resolve()
+ folder.mkdir(parents=True, exist_ok=True)
+ root = Path(__file__).resolve().parents[1]
+ vm = VM(folder, iso, 'uefi', 1024, cpu='Nehalem')
+ result = {'status': 'running', 'image_sha256': manifest['iso']['sha256'],
+ 'image_source': manifest['source_commit'], 'candidate_files': {},
+ 'test_source': subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip(),
+ 'started_at_unix': time.time(), 'checks': []}
+ config = {'disk': '/dev/vda', 'expected_serial': 'HN_OS_TEST', 'confirm_erase': '/dev/vda',
+ 'username': 'me', 'hostname': 'harness', 'password': 'test-password-123',
+ 'encrypt': True, 'serial_console': True}
+
+ def exercise(name, installed=False):
+ print('Checking ' + name + ' media keys', flush=True)
+ config_path = '/usr/share/harness-os/' + ('labwc' if installed else 'labwc-install') + '/rc.xml'
+ candidate = root / 'root' / config_path.lstrip('/')
+ result['candidate_files'][config_path] = hashlib.sha256(candidate.read_bytes()).hexdigest()
+ copy_file(vm, candidate.read_bytes(), '/tmp/input-candidate.xml')
+ copy_file(vm, Path(__file__).with_name('input_guest.py').read_bytes(), '/tmp/input-guest.py')
+ command = ('sudo -n ' if installed else '') + 'python3 /tmp/input-guest.py --candidate /tmp/input-candidate.xml --config ' + config_path + ' --output /tmp/input-result.json' + (' --installed' if installed else '')
+ try:
+ output, _ = vm.command(command, timeout=80)
+ (folder / (name + '.log')).write_text(output)
+ finally:
+ output = vm.read_file('/tmp/input-result.json')
+ (folder / (name + '.json')).write_bytes(output)
+ record = json.loads(output)
+ assert record['status'] == 'passed', record
+ result['checks'].append(name + ': actual media keys passed through labwc and packaged brightnessctl; kernel keyboard LED permissions unchanged')
+ vm.screenshot(name)
+
+ try:
+ vm.start(live=True)
+ vm.wait(r'root@[^\r\n]*[#] ')
+ vm.shell_ready = True
+ vm.command('stty -echo')
+ vm.command('timeout 30 sh -c \'until pgrep -u 1000 -x labwc && pgrep -u 1000 -x foot; do sleep .2; done\'')
+ exercise('usb')
+ copy_file(vm, json.dumps(config).encode(), '/tmp/install-config.json')
+ vm.command('nmcli networking off')
+ output, _ = vm.command('harness install --config /tmp/install-config.json --yes-erase-disk', timeout=360)
+ (folder / 'install.log').write_text(output)
+ vm.command('sync')
+ vm.stop()
+ vm.start(live=False)
+ vm.login_installed(config)
+ vm.command('printf %s ' + shlex.quote(config['password'] + '\n') + ' | sudo -S -v')
+ vm.command('/usr/lib/harness-os/wait-runtime')
+ exercise('installed', installed=True)
+ # Media keys must leave ordinary typing directed to the same terminal.
+ vm.command('hn new-window -n keyboard-check ' + shlex.quote(
+ 'echo $$ > /tmp/input-terminal-pid; printf "Type into Harness: "; read -r word; printf %s "$word" > /tmp/input-terminal-word; exec sleep 600'))
+ deadline = time.monotonic() + 20
+ while 'type into harness' not in screen_text(vm, 'terminal-ready'):
+ assert time.monotonic() < deadline
+ time.sleep(.2)
+ vm.type_probe('keyboard-still-works')
+ vm.keys('ret')
+ vm.command('timeout 10 sh -c \'until test "$(cat /tmp/input-terminal-word 2>/dev/null)" = keyboard-still-works; do sleep .1; done\'; kill -0 "$(cat /tmp/input-terminal-pid)"')
+ vm.screenshot('terminal-after-media-keys')
+ result['checks'].append('Installed hn accepts real graphical keyboard input after media controls')
+ result['status'] = 'passed'
+ except BaseException as error:
+ result.update(status='failed', error=str(error))
+ if vm.process and vm.process.poll() is None:
+ try:
+ vm.screenshot('failure')
+ output, _ = vm.command('cat /home/me/.local/state/harness-os/display.log; '
+ 'sudo -n journalctl -b --no-pager -n 200; ls -l /sys/class/leds/*/brightness; '
+ 'cat /tmp/input-result.json', check=False, timeout=20)
+ (folder / 'diagnostics.log').write_text(output)
+ except Exception:
+ pass
+ raise
+ finally:
+ result['finished_at_unix'] = time.time()
+ (folder / 'receipt.json').write_text(json.dumps(result, indent=2) + '\n')
+ vm.stop()
+ vm.log.close()
+ vm.stderr.close()
+ vm.control.cleanup()
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/tools/run-vm.py b/os/tools/run-vm.py
index 9126f074d..af631e035 100644
--- a/os/tools/run-vm.py
+++ b/os/tools/run-vm.py
@@ -157,7 +157,7 @@ def main(argv=None):
print(f'Virtual disk: {disk} ({info["virtual-size"] / 1024 ** 3:g} GiB capacity; grows only as used)', flush=True)
print(f'Guest: {args.memory} MiB RAM, 2 CPUs, {accel}; control: {control}', flush=True)
if not args.installed:
- print('Press Enter on the Harness welcome screen to install (choose /dev/vda), or T to try it.', flush=True)
+ print('The USB opens the installer. Install to the virtual disk (/dev/vda).', flush=True)
reboot = ['python3', 'os/tools/run-vm.py', '--installed', '--directory', str(folder),
'--firmware', args.firmware, '--memory', str(args.memory)]
for flag, value in [('--vnc-port', args.vnc_port), ('--ssh-port', args.ssh_port), ('--remote-host', args.remote_host)]: