Skip to content
Open
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
47 changes: 47 additions & 0 deletions bin/omarchy-bluetooth-device
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,56 @@ trust_device() {
bluetoothctl trust "$address" >/dev/null 2>&1 || true
}

# The shell keeps the adapter pairable only while the Bluetooth panel is open,
# since the pairing agent auto-accepts. A pairing this command starts needs it
# on as well, or a Low Energy device pairs without bonding and is forgotten at
# disconnect. The shell owns the property, so it is asked to hold pairing for
# the length of this command. Without a shell to ask, commands share the
# property through a lock: each holds it shared while pairing, the first one
# to find it off leaves a marker, and the last one out (the only one able to
# take it exclusively) turns it back off.
pairing_lock_dir="${XDG_RUNTIME_DIR:-/tmp}"
pairing_lock="$pairing_lock_dir/omarchy-bluetooth-pairable.lock"
pairing_restore_marker="$pairing_lock_dir/omarchy-bluetooth-pairable.restore"
pairing_token=""
holding_lock=0

hold_pairing() {
# The shell answers a hold with a token for that hold alone, so the release
# below cannot take another pairing's hold away. A request that got no
# answer leaves nothing to release; the shell expires such a hold itself.
if pairing_token=$(omarchy-shell omarchy.bluetooth holdPairing 2>/dev/null) &&
[[ $pairing_token =~ ^[0-9a-f]{32}$ ]]; then
return
Comment on lines +50 to +52

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.

P1 Restart interrupts pairing

After receiving a token, hold_pairing returns without keeping a hold outside the shell. If the shell restarts during pairing, the new BluetoothPairing starts with no tokens. With the panels closed, its gates turn pairing off even though the detached pairing command is still running. A Low Energy device can then fail to bond and be forgotten after disconnecting.

Keep command holds somewhere the replacement shell can read, or have the command renew its hold after a restart.

Knowledge Base Used: CLI command platform

fi
pairing_token=""
exec 8>>"$pairing_lock" || return 0
flock -s 8 || return 0
holding_lock=1
if [[ $(timeout 2s bluetoothctl show 2>/dev/null) != *"Pairable: yes"* ]]; then
: >"$pairing_restore_marker"
timeout 5s bluetoothctl pairable on >/dev/null 2>&1 || true
fi
}

release_pairing() {
if [[ -n $pairing_token ]]; then
omarchy-shell -q omarchy.bluetooth releasePairing "$pairing_token" >/dev/null 2>&1 || true
fi
(( holding_lock )) || return 0
flock -u 8 || true
if flock -x -n 8 && [[ -e $pairing_restore_marker ]]; then
rm -f "$pairing_restore_marker"
timeout 5s bluetoothctl pairable off >/dev/null 2>&1 || true
fi
exec 8>&-
}

case "$action" in
pair)
power_on
trap release_pairing EXIT
hold_pairing
timeout 20s bluetoothctl pair "$address" >/dev/null 2>&1 || true
trust_device
timeout 20s bluetoothctl connect "$address" >/dev/null 2>&1 || true
Expand Down
15 changes: 11 additions & 4 deletions default/systemd/user/bt-agent.service
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,17 @@ 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.
# NoInputNoOutput auto-accepts pair requests, so the window in which one can
# arrive is what keeps this safe. BlueZ brings every controller up pairable
# with no timeout; the Omarchy Bluetooth bar widget turns the Pairable
# property of each one on only while its panel is open or
# omarchy-bluetooth-device holds it for a pairing it runs, and the kernel
# refuses bonding while it is off. A controller is also not connectable or
# discoverable unless something makes it so, which turns unknown devices away
# before pairing starts. The gate lives in the widget: with it removed from
# the bar, or the shell not running, BlueZ's default stands. Pair from the
# panel or omarchy-bluetooth-device; a `bluetoothctl pairable on` is undone by
# the shell.
ExecStart=/usr/bin/bt-agent -c NoInputNoOutput
Restart=on-failure
RestartSec=2
Expand Down
43 changes: 43 additions & 0 deletions shell/Commons/BluetoothPairing.qml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
pragma Singleton
import QtQuick
import Quickshell

// Holds that omarchy-bluetooth-device takes over IPC for the pairings it runs.
// The Bluetooth bar widget turns the adapters' Pairable property on while a
// hold is live, so a Low Energy device bonds even with every panel closed.
// Kept here rather than on a widget instance: the instance that answered the
// IPC call can go away with its monitor before the pairing finishes, and the
// widgets left on screen must still see the hold.
Singleton {
id: root

// One token per hold, so a command releases only the hold it took and two
// pairings at once cannot release each other. A command whose hold request
// got no answer has no token and leaves its hold to the expiry below.
property var tokens: []
readonly property int holds: tokens.length

function hold() {
var token = ""
for (var i = 0; i < 4; i++) token += Math.floor(Math.random() * 0x100000000).toString(16).padStart(8, "0")
tokens = tokens.concat([token])
expiry.restart()
return token
}

function release(token) {
var index = tokens.indexOf(String(token || ""))
if (index === -1) return "unknown"
tokens = tokens.slice(0, index).concat(tokens.slice(index + 1))
if (tokens.length === 0) expiry.stop()
return "ok"
}

// A pairing that dies without releasing its hold must not leave pairing on.
Timer {
id: expiry
interval: 90000
repeat: false
onTriggered: root.tokens = []
}
}
1 change: 1 addition & 0 deletions shell/Commons/qmldir
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
module qs.Commons
singleton AudioNodes 1.0 AudioNodes.qml
singleton BluetoothPairing 1.0 BluetoothPairing.qml
singleton Border 1.0 Border.qml
singleton Color 1.0 Color.qml
singleton IpcRegistry 1.0 IpcRegistry.qml
Expand Down
61 changes: 61 additions & 0 deletions shell/plugins/panels/bluetooth/PairableGate.qml
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import QtQuick

// The pairing agent in default/systemd/user/bt-agent.service answers every
// incoming pairing request without asking, so a nearby device must only be
// able to bond while someone is at the Bluetooth panel, or a pairing started
// from this machine is under way. BlueZ brings adapters up pairable with no
// timeout and nothing else in Omarchy touches the property, so this owns it:
// on while held, off the rest of the time, including right after login and
// when the adapter appears later.
//
// quickshell applies a pairable write to adapter.pairable at once and sends
// the D-Bus Set behind it, so the property reads as the requested state, a
// write never needs a retry, and a change BlueZ reports (a late adapter, or a
// `bluetoothctl pairable on` behind the shell's back) arrives as a change to
// react to. A Set that BlueZ refuses is only logged by quickshell and leaves
// the property reading the requested value, so that case is not recovered.
Item {
id: gate

visible: false

// Bluetooth.defaultAdapter, or a stand-in with a writable pairable property.
property var adapter: null
// True while this instance needs pairing possible.
property bool open: false
// One widget instance exists per monitor and they share the default adapter,
// so a closing instance leaves pairing on for another instance that holds it.
property var siblingOpen: function() { return false }

// Every instance must compute the same answer, or two of them write each
// other's value back forever; the panel's heldSibling reads one shared list
// for that. The guard keeps a write's own change notification from
// re-entering here, so even a disagreement cannot recurse.
property bool applying: false

function apply() {
if (adapter === null || applying) return
applying = true
var wanted = open || siblingOpen()
if (adapter.pairable !== wanted) adapter.pairable = wanted
applying = false
}

onOpenChanged: apply()
onAdapterChanged: apply()
Component.onCompleted: apply()

Connections {
target: gate.adapter
ignoreUnknownSignals: true
function onPairableChanged() { gate.apply() }
}

// A destroyed instance is no longer counted among the siblings, so it turns
// pairing off itself when it was the last one holding it. One replaced while
// its panel still holds (a controller appeared, and the gates were rebuilt)
// leaves that to its successor.
Component.onDestruction: {
if (adapter !== null && adapter.pairable === true && !open && !siblingOpen()) adapter.pairable = false
}
}
42 changes: 42 additions & 0 deletions shell/plugins/panels/bluetooth/Panel.qml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ Panel {
// permits — needed for the toggleBluetooth method below.
manageIpc: false

// An instance being torn down (its monitor went away) drops its hold first,
// so the siblings that outlive it, and its own gate, settle without it: a
// parent's destruction runs before its children's. The IPC holds live in
// Commons.BluetoothPairing, shared by every instance, so a pairing survives
// the instance that took its hold.
property bool destroying: false
readonly property bool pairingHeld: !destroying && (opened || Commons.BluetoothPairing.holds > 0)

// Address -> "connecting" | "disconnecting" | "forgetting".
// The actual Bluetooth sequencing lives in bin/omarchy-bluetooth-device;
// this map only keeps the panel responsive while BlueZ catches up.
Expand Down Expand Up @@ -434,6 +442,18 @@ Panel {
return null
}

// Like openSibling, for the pairable gate: it reads the same pairingHeld the
// gates use, so every instance computes one answer.
function heldSibling() {
if (!bar || typeof bar.moduleWidgets !== "function") return null
var items = bar.moduleWidgets(moduleName)
for (var i = 0; i < items.length; i++) {
if (items[i] && items[i] !== root && items[i].pairingHeld === true) return items[i]
}
return null
}


function updateFocusedAddress() {
var d = deviceAt(focusSection, selectedIndex)
focusedDeviceAddress = d ? (d.address || "") : ""
Expand Down Expand Up @@ -570,6 +590,7 @@ Panel {
// confirmed after this object is gone — and only writes the stop directly
// when it is the last one standing.
Component.onDestruction: {
destroying = true
if (!owesDiscoveryStop) return
var items = bar && typeof bar.moduleWidgets === "function" ? bar.moduleWidgets(moduleName) : []
for (var i = 0; i < items.length; i++) {
Expand All @@ -578,6 +599,25 @@ Panel {
if (adapter !== null && adapter.discovering) adapter.discovering = false
}

// Pairing is only possible while this panel is on screen or a pairing this
// machine started is under way: the pairing agent auto-accepts, and BlueZ
// leaves adapters pairable by default. omarchy-bluetooth-device holds it
// over IPC for the pairings it runs, from the panel or the command line, so
// closing the panel mid-pair cannot stop a Low Energy device from bonding;
// Commons.BluetoothPairing keeps those holds across widget instances.
// Every controller gets a gate, not just the default one the panel shows:
// the agent answers for a USB dongle too. The adapter is handed over only
// once the bar has injected itself, since heldSibling reads the bar's
// widget list and a first apply before that would not see a holder.
Instantiator {
model: Bluetooth.adapters ? Bluetooth.adapters.values : []
delegate: PairableGate {
adapter: root.bar ? modelData : null
open: root.pairingHeld
siblingOpen: function() { return root.heldSibling() !== null }
}
}

Timer {
id: pendingTimeout
interval: 20000
Expand Down Expand Up @@ -647,6 +687,8 @@ Panel {
function hide() { root.close() }
function toggle() { root.toggle() }
function toggleBluetooth() { root.toggleBluetooth() }
function holdPairing(): string { return Commons.BluetoothPairing.hold() }
function releasePairing(token: string): string { return Commons.BluetoothPairing.release(token) }
}

BarIconButton {
Expand Down
23 changes: 23 additions & 0 deletions test/shell.d/bluetooth-pairable-gate-test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#!/bin/bash

set -euo pipefail

source "$(dirname "$0")/base-test.sh"
require_compositor "the Bluetooth pairable gate"
require_command quickshell

stage=$(mktemp -d)
trap 'rm -rf "$stage"' EXIT
# The directory import scans Panel.qml too, whose own imports resolve here.
for component in Commons Ui; do
ln -s "$ROOT/shell/$component" "$stage/$component"
done
ln -s "$ROOT/shell/plugins/panels/bluetooth" "$stage/bluetooth"
cp "$SHELL_TEST_DIR/fixtures/bluetooth-pairable-gate/shell.qml" "$stage/shell.qml"

output=$(timeout 25 quickshell -p "$stage" --no-color 2>&1) || fail "the pairable gate fixture exits cleanly" "$output"
[[ $output == *"RESULT pass"* ]] || fail "the adapter is pairable only while a Bluetooth panel is open" "$output"
if rg -q 'RESULT fail|ReferenceError|TypeError|Unable to assign|Binding loop' <<<"$output"; then
fail "the pairable gate has no QML errors" "$output"
fi
pass "the adapter is pairable only while a Bluetooth panel is open"
Loading