Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 125 additions & 0 deletions bin/omarchy-bluetooth-agent
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
#!/usr/bin/python3

# omarchy:summary=BlueZ pairing agent that shows passkeys
# omarchy:group=bluetooth
# omarchy:hidden=true

# Python because a BlueZ agent has to hold one D-Bus connection for its whole
# lifetime and answer DisplayPasskey / RequestConfirmation on that connection.
# bt-agent -c NoInputNoOutput auto-accepts Just Works but cannot show a PIN,
# so BLE HID keyboards (HHKB, many others) fail to pair from the panel.

import shutil
import subprocess
import sys

import dbus
import dbus.mainloop.glib
import dbus.service
from gi.repository import GLib

AGENT_PATH = "/org/omarchy/BluetoothAgent"
AGENT_IFACE = "org.bluez.Agent1"
AGENT_MANAGER = "org.bluez.AgentManager1"
DEVICE_IFACE = "org.bluez.Device1"
PROPS_IFACE = "org.freedesktop.DBus.Properties"
BLUEZ = "org.bluez"


def notify(headline, description):
sender = shutil.which("omarchy-notification-send")
if sender:
# Critical toasts never expire in the Omarchy shell and nothing here can
# retract one, so an unanswered passkey would sit on screen forever.
subprocess.Popen(
[sender, "-u", "normal", "-g", "󰂯", headline, description, "-t", "30000"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
start_new_session=True,
)
return
print(f"{headline}: {description}", flush=True)


def device_label(bus, path):
try:
props = dbus.Interface(bus.get_object(BLUEZ, path), PROPS_IFACE)
values = props.GetAll(DEVICE_IFACE)
return str(values.get("Name") or values.get("Alias") or path)
except dbus.exceptions.DBusException:
return path


class Agent(dbus.service.Object):
def __init__(self, bus, path):
self.bus = bus
super().__init__(bus, path)

def _passkey_notice(self, device, passkey):
name = device_label(self.bus, device)
notify(
f"Pair {name}",
f"Type {int(passkey):06d} on the device, then press Enter.",
)

@dbus.service.method(AGENT_IFACE, in_signature="ou", out_signature="")
def RequestConfirmation(self, device, passkey):
self._passkey_notice(device, passkey)

@dbus.service.method(AGENT_IFACE, in_signature="ouq", out_signature="")
def DisplayPasskey(self, device, passkey, entered):
if int(entered) == 0:
self._passkey_notice(device, passkey)

@dbus.service.method(AGENT_IFACE, in_signature="os", out_signature="")
def DisplayPinCode(self, device, pincode):
name = device_label(self.bus, device)
notify(f"Pair {name}", f"Type {pincode} on the device, then press Enter.")

@dbus.service.method(AGENT_IFACE, in_signature="o", out_signature="")
def RequestAuthorization(self, device):
return

@dbus.service.method(AGENT_IFACE, in_signature="os", out_signature="")
def AuthorizeService(self, device, uuid):
return

@dbus.service.method(AGENT_IFACE, in_signature="o", out_signature="s")
def RequestPinCode(self, device):
return "000000"

@dbus.service.method(AGENT_IFACE, in_signature="o", out_signature="u")
def RequestPasskey(self, device):
return dbus.UInt32(0)

@dbus.service.method(AGENT_IFACE, in_signature="", out_signature="")
def Cancel(self):
return

@dbus.service.method(AGENT_IFACE, in_signature="", out_signature="")
def Release(self):
return


def main():
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
Agent(bus, AGENT_PATH)
mgr = dbus.Interface(bus.get_object(BLUEZ, "/org/bluez"), AGENT_MANAGER)
try:
mgr.UnregisterAgent(AGENT_PATH)
except dbus.exceptions.DBusException:
pass
# KeyboardDisplay: host shows the passkey, the peripheral types it.
# Just Works still auto-accepts via RequestAuthorization / AuthorizeService.
mgr.RegisterAgent(AGENT_PATH, "KeyboardDisplay")
mgr.RequestDefaultAgent(AGENT_PATH)
GLib.MainLoop().run()
return 0


if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
sys.exit(0)
10 changes: 7 additions & 3 deletions bin/omarchy-bluetooth-device
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,13 @@ trust_device() {
case "$action" in
pair)
power_on
timeout 20s bluetoothctl pair "$address" >/dev/null 2>&1 || true
trust_device
timeout 20s bluetoothctl connect "$address" >/dev/null 2>&1 || true
# Do not trust a device that never bonded. A failed pair + trust made the
# panel treat the device as known and connect-only, so a BLE keyboard that
# needs a passkey could never be retried.
if timeout 60s bluetoothctl pair "$address" >/dev/null 2>&1; then
trust_device
timeout 20s bluetoothctl connect "$address" >/dev/null 2>&1 || true
fi
;;
connect)
power_on
Expand Down
12 changes: 5 additions & 7 deletions default/systemd/user/bt-agent.service
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
[Unit]
Description=Bluetooth pairing agent (auto-accept)
Documentation=man:bt-agent(1)
Description=Bluetooth pairing agent (shows passkeys, auto-accepts Just Works)
ConditionPathIsDirectory=/sys/class/bluetooth
# bluez must be reachable on the system bus before we can register.
After=dbus.socket
Expand All @@ -11,11 +10,10 @@ Type=simple
# If bluetoothd is unavailable (for example in VMs or machines without a
# usable adapter), skip cleanly instead of entering a restart loop.
ExecCondition=/usr/bin/systemctl is-active --quiet bluetooth.service
# NoInputNoOutput auto-accepts pair requests. Safe because the adapter
# is only `pairable: true` when the user explicitly opens the omarchy
# bluetoothPanel and starts scanning; outside that window bluez refuses
# inbound pair attempts at a lower layer.
ExecStart=/usr/bin/bt-agent -c NoInputNoOutput
# KeyboardDisplay shows the six-digit passkey BLE HID keyboards need.
# Just Works (mice, headphones) still auto-accepts. Pairable remains a
# BlueZ policy; this agent only answers pairing prompts.
ExecStart=/usr/bin/omarchy-bluetooth-agent
Restart=on-failure
RestartSec=2

Expand Down
1 change: 1 addition & 0 deletions install/omarchy-base.packages
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ plocate
plymouth
postgresql-libs
power-profiles-daemon
python-dbus
python-gobject
python-poetry-core
ttfx
Expand Down
17 changes: 17 additions & 0 deletions migrations/1786728635.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
echo "Restart Bluetooth agent so pairing can show a keyboard passkey"

# omarchy-bluetooth-agent talks to BlueZ through python-dbus. The ISO pacstraps
# it from omarchy-base.packages, but an existing install only gets it here.
# Restarting the unit without it would fail on import and loop every two
# seconds, so let a failed install stop this migration and keep it pending.
omarchy-pkg-add python-dbus

# The packaged unit now starts omarchy-bluetooth-agent instead of
# bt-agent -c NoInputNoOutput. Reload so the user manager picks up the
# new ExecStart, then bounce a live agent. Login starts it for everyone else.
systemctl --user daemon-reload >/dev/null 2>&1 || true

if systemctl --user is-enabled --quiet bt-agent.service 2>/dev/null; then
systemctl --user reset-failed bt-agent.service 2>/dev/null || true
systemctl --user restart bt-agent.service || true
fi
8 changes: 8 additions & 0 deletions shell/plugins/panels/bluetooth/Model.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,13 +85,20 @@ function sortedByLabel(devices) {
// var property, and BlueZ churn (discovery timeouts, unpair) can destroy the
// object while a delegate is still incubating, which segfaults quickshell.
// Actions resolve the backend object via Panel.deviceFor().
function isBonded(device) {
return !!(device && (device.paired || device.bonded))
}

function deviceRow(d) {
if (!d) return null
return {
address: d.address || "",
name: d.name || "",
deviceName: d.deviceName || "",
connected: !!d.connected,
paired: !!d.paired,
bonded: !!d.bonded,
trusted: !!d.trusted,
state: d.state !== undefined ? d.state : -1,
batteryAvailable: !!d.batteryAvailable,
battery: d.battery !== undefined ? d.battery : 0,
Expand Down Expand Up @@ -166,6 +173,7 @@ if (typeof module !== "undefined") {
nodeText: nodeText,
bluetoothSinkMatchesDevice: bluetoothSinkMatchesDevice,
sortedByLabel: sortedByLabel,
isBonded: isBonded,
deviceRow: deviceRow,
deviceLists: deviceLists,
cloneMap: cloneMap,
Expand Down
4 changes: 3 additions & 1 deletion shell/plugins/panels/bluetooth/Panel.qml
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,9 @@ Panel {

function connectDevice(device) {
if (!device || device.connected) return
if (device.paired || device.bonded || device.trusted) runDeviceAction(device, "connect", "connecting")
// Trusted-without-a-bond is not paired. Connecting it skips the passkey
// and leaves BLE keyboards stuck; pair again instead.
if (Model.isBonded(device)) runDeviceAction(device, "connect", "connecting")
else runDeviceAction(device, "pair", "connecting")
}

Expand Down
56 changes: 56 additions & 0 deletions test/shell.d/bluetooth-agent-migration-test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#!/bin/bash

set -euo pipefail

source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh"

migration="$ROOT/migrations/1786728635.sh"

test_tmp=$(mktemp -d)
trap 'rm -rf "$test_tmp"' EXIT
mkdir -p "$test_tmp/bin"

cat >"$test_tmp/bin/omarchy-pkg-add" <<'SH'
#!/bin/bash
printf 'pkg-add %s\n' "$*" >>"$CALL_LOG"
exit "${TEST_PKG_ADD_STATUS:-0}"
SH

cat >"$test_tmp/bin/systemctl" <<'SH'
#!/bin/bash
printf 'systemctl %s\n' "$*" >>"$CALL_LOG"
exit 0
SH

chmod +x "$test_tmp/bin"/*

call_log="$test_tmp/calls.log"

run_migration() {
: >"$call_log"
PATH="$test_tmp/bin:$PATH" CALL_LOG="$call_log" "$@" bash -euo pipefail "$migration"
}

# The agent imports python-dbus. The ISO pacstraps it from the base package
# list, but an existing install only receives it from this migration, and a
# restart before the install would loop on ImportError every two seconds.
run_migration env >/dev/null || fail "the agent migration runs cleanly" "$(cat "$call_log")"
grep -qx 'pkg-add python-dbus' "$call_log" ||
fail "the agent migration installs python-dbus" "$(cat "$call_log")"
pass "the agent migration installs python-dbus"

install_line=$(grep -n '^pkg-add python-dbus$' "$call_log" | cut -d: -f1)
restart_line=$(grep -n '^systemctl --user restart bt-agent.service$' "$call_log" | cut -d: -f1)
[[ -n $restart_line ]] || fail "the agent migration restarts an enabled bt-agent" "$(cat "$call_log")"
((install_line < restart_line)) ||
fail "the agent migration installs python-dbus before restarting bt-agent" "$(cat "$call_log")"
pass "the agent migration installs python-dbus before restarting bt-agent"

# A failed install must stop the migration so it stays pending, not restart
# the unit into a crash loop and then mark itself done.
if run_migration env TEST_PKG_ADD_STATUS=1 >/dev/null 2>&1; then
fail "the agent migration fails when python-dbus cannot be installed" "$(cat "$call_log")"
fi
grep -q 'restart bt-agent.service' "$call_log" &&
fail "the agent migration does not restart bt-agent without python-dbus" "$(cat "$call_log")"
pass "the agent migration stays pending when python-dbus cannot be installed"
38 changes: 37 additions & 1 deletion test/shell.d/bluetooth-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ assert(/manageIpc: false/.test(panelSource), 'bluetooth owns its IPC handler so
// Writing adapter.enabled sets BlueZ Powered, which does not survive a reboot.
assert(/function toggleBluetooth\(\)[\s\S]*?execDetached\(\["omarchy-bluetooth-power", adapter\.enabled \? "off" : "on"\]\)/.test(panelSource), 'bluetooth toggles the radio through the rfkill soft block')
assert(!/adapter\.enabled = /.test(panelSource), 'bluetooth never writes the adapter power state directly')
const connectFn = panelSource.match(/function connectDevice\(device\) \{[\s\S]*?\n \}/)
assert(connectFn, 'bluetooth has connectDevice')
assert(/Model\.isBonded\(device\)/.test(connectFn[0]), 'bluetooth connects only after a real bond')
assert(!/device\.trusted/.test(connectFn[0]), 'bluetooth does not treat trusted-only devices as paired')

// Discovery is a BlueZ session that nothing ends at panel close: it persists
// until StopDiscovery or until quickshell's D-Bus connection drops with the
Expand Down Expand Up @@ -55,6 +59,10 @@ assert(bluetooth.isAddressLike('AA:BB:CC:DD:EE:FF'), 'bluetooth detects address-
assertEqual(bluetooth.normalizedAddress('AA:BB_CC-dd-ee-ff'), 'aabbccddeeff', 'bluetooth normalizes BlueZ and PipeWire address formats')
assert(!bluetooth.hasHumanName({ name: 'AA:BB:CC:DD:EE:FF' }), 'bluetooth rejects address-only device labels')
assert(bluetooth.hasHumanName({ deviceName: 'MX Master 3S' }), 'bluetooth accepts human device labels')
assert(bluetooth.isBonded({ paired: true }), 'bluetooth treats paired as bonded')
assert(bluetooth.isBonded({ bonded: true }), 'bluetooth treats bonded as bonded')
assert(!bluetooth.isBonded({ trusted: true }), 'bluetooth does not treat trusted-only as bonded')
assert(!bluetooth.isBonded({}), 'bluetooth does not treat unknown devices as bonded')

const devices = [
{ name: 'Speaker', connected: false, paired: true, address: '2' },
Expand Down Expand Up @@ -94,7 +102,7 @@ assertDeepEqual(arrayLikeLists.discovered.map(bluetooth.deviceLabel), ['Gamepad'

assertDeepEqual(
bluetooth.deviceRow({ name: 'Deadbeef', address: '1', connected: false }),
{ address: '1', name: 'Deadbeef', deviceName: '', connected: false, state: -1, batteryAvailable: false, battery: 0, pairing: false },
{ address: '1', name: 'Deadbeef', deviceName: '', connected: false, paired: false, bonded: false, trusted: false, state: -1, batteryAvailable: false, battery: 0, pairing: false },
'bluetooth projects device rows with primitives only'
)
assertEqual(
Expand Down Expand Up @@ -165,6 +173,7 @@ if [[ $1 == "show" ]]; then
[[ -n ${2:-} && -f "$POWERED_FILE.$2" ]] && state="$POWERED_FILE.$2"
printf '\tPowered: %s\n' "$(cat "$state")"
fi
[[ $1 == "pair" && -n ${PAIR_FAIL:-} ]] && exit 1
exit 0
SH

Expand Down Expand Up @@ -237,6 +246,33 @@ grep -qx "rfkill unblock bluetooth" "$toggle_off_log" ||
fail "bluetooth toggles an unpowered adapter on" "$(cat "$toggle_off_log")"
pass "bluetooth toggles an unpowered adapter on"

# A failed pair must not trust the device. Trust-without-bond is what made
# the panel skip pairing on the next click.
pair_fail_log=$(
echo yes >"$POWERED_FILE"
: >"$device_tmp/log"
PATH="$mock_bin:$ROOT/bin:$PATH" BLUETOOTHCTL_LOG="$device_tmp/log" PAIR_FAIL=1 \
OMARCHY_BLUETOOTH_POWER_WAIT_SECONDS=0 \
"$ROOT/bin/omarchy-bluetooth-device" pair AA:BB:CC:DD:EE:FF ||
fail "pair still exits cleanly when bonding fails"
printf '%s' "$device_tmp/log"
)
grep -qx "pair AA:BB:CC:DD:EE:FF" "$pair_fail_log" ||
fail "bluetooth still attempts to pair" "$(cat "$pair_fail_log")"
pass "bluetooth still attempts to pair"
grep -q "^trust " "$pair_fail_log" &&
fail "bluetooth does not trust a device that failed to pair" "$(cat "$pair_fail_log")"
pass "bluetooth does not trust a device that failed to pair"

pair_ok_log=$(bluetooth_run yes "$ROOT/bin/omarchy-bluetooth-device" pair AA:BB:CC:DD:EE:FF)
grep -qx "pair AA:BB:CC:DD:EE:FF" "$pair_ok_log" ||
fail "bluetooth pairs before it trusts" "$(cat "$pair_ok_log")"
grep -qx "trust AA:BB:CC:DD:EE:FF" "$pair_ok_log" ||
fail "bluetooth trusts after a successful pair" "$(cat "$pair_ok_log")"
grep -qx "connect AA:BB:CC:DD:EE:FF" "$pair_ok_log" ||
fail "bluetooth connects after a successful pair" "$(cat "$pair_ok_log")"
pass "bluetooth trusts and connects only after a successful pair"

# The power-on shortcut is the whole point of skipping the stabilization sleep:
# pair/connect from the panel run against an adapter that is already powered.
bluetooth_device_log() {
Expand Down
8 changes: 8 additions & 0 deletions test/shell.d/systemd-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ pass "bt-agent skips when bluetooth.service is inactive"
grep -Fx 'Restart=on-failure' "$service" >/dev/null
pass "bt-agent still restarts after runtime failures"

grep -Fx 'ExecStart=/usr/bin/omarchy-bluetooth-agent' "$service" >/dev/null ||
fail "bt-agent still launches NoInputNoOutput bt-agent, which cannot show a keyboard passkey"
pass "bt-agent shows pairing passkeys through omarchy-bluetooth-agent"

grep -q 'KeyboardDisplay' "$ROOT/bin/omarchy-bluetooth-agent" ||
fail "pairing agent is not registered as KeyboardDisplay"
pass "pairing agent is registered as KeyboardDisplay"

sleep_service="$ROOT/default/systemd/user/omarchy-sleep-lock.service"
grep -Fx 'ExecStart=/usr/bin/omarchy-system-sleep-monitor' "$sleep_service" >/dev/null
pass "sleep lock service uses the package-backed monitor path"
Expand Down