Repository navigation
Description
OS
macOS: 27.2.1 (Build 26B131), Apple Silicon (arm64)
LinearMouse
v0.13.0
Describe the bug
Summary
When at least one Bluetooth/BLE pointer device is active (!targets.isEmpty), GATTBatteryMonitor periodically attaches to every system-connected BLE peripheral exposing the standard GATT Battery Service (0x180F) in order to read Device Information (0x180A) and match it against known input devices.
However, once identity discovery completes and a peripheral does not match any target input device (matchedTarget(...) == nil), GATTBatteryMonitor never calls cancelPeripheralConnection(_:) on that peripheral. As a result, LinearMouse retains an active CoreBluetooth central connection reference in bluetoothd indefinitely, keeping unrelated third-party BLE peripherals connected to macOS even after the application that originally connected to them disconnects or quits.
Symptoms
Suppose a user has LinearMouse running with a Bluetooth mouse paired/active, and uses another macOS application (e.g., a BLE client, sensor app, or development utility) to briefly connect to any non-HID BLE peripheral that exposes Battery Service (0x180F)—such as a BLE sensor, wearable, or development board:
- If the session overlaps
BatteryDeviceMonitor's 60-second refresh timer (BatteryDeviceMonitor.swift:92-95),GATTBatteryMonitor.attachConnectedPeripherals()callscentral.connect(peripheral)on that peripheral. - When the other application disconnects (or exits completely),
bluetoothddoes not tear down the physical BLE ACL link becausecom.lujjjh.LinearMousestill holds an activeCBCentralManagerconnection reference to the peripheral. - Most single-link BLE peripherals stop advertising while connected and accept only one central connection at a time:
- Subsequent BLE scans on macOS can no longer discover the peripheral.
- Other central devices (such as a phone or another host) cannot connect to the peripheral at all.
- The peripheral remains stuck connected to the Mac until Bluetooth is toggled off/on in System Settings, LinearMouse quits, or Bluetooth permission for LinearMouse is revoked.
Root Cause
- Unconditional
connect(_:)during candidate probing (LinearMouse/Device/VendorSpecific/GATTBatteryMonitor.swift:105-118):
attachConnectedPeripherals()retrieves all system-connected peripherals offering0x180F, inserts each intopeers, and callscentral.connect(peripheral)to inspect0x180A(0x2A25Serial Number /0x2A50PnP ID). - Unmatched peers are never retired after discovery completes (
GATTBatteryMonitor.swift:276-304):
Inpublish():While this avoids subscribing tolet identities = peers.values.map(\.identity) let complete = peers.values.allSatisfy { !$0.identityServicesPending && $0.identityReads.isEmpty } let values = peers.values .compactMap { peer -> Value? in peer.targetID = GATTBatteryIdentity.matchedTarget( for: peer.identity, peers: identities, targets: targets, discoveryComplete: complete ) guard let id = peer.targetID else { return nil } // Only subscribe after matching a connected input device.
0x2A19on unmatched devices, whencomplete == trueandpeer.targetID == nil,peerstays inpeerswith itsCBPeripheralconnection open forever—retire(peer.peripheral.identifier, cancel: true)is never called. updateTargets(_:)also skips unmatched peers (GATTBatteryMonitor.swift:56-59):Becausefor (id, peer) in peers where peer.targetID.map({ !validIDs.contains($0) }) == true { retire(id, cancel: true) }
peer.targetIDisnil,peer.targetID.map(...)evaluates tonilrather thantrue, so unmatched peripherals are never retired on subsequent refreshes either—only whenstop()runs.
Suggested Fix
- Cancel the connection as soon as identity discovery completes without a match:
Oncecomplete == true(all pending0x180Aservice/characteristic reads have finished), retire every peer whosematchedTarget(...)isnilwithcancel: true(central.cancelPeripheralConnection(peer.peripheral)), being careful not to trigger re-entrantpublish()churn while iterating. - Avoid re-probing a rejected peripheral every 60 seconds while another app is still using it:
Currently,centralManager(_:didDisconnectPeripheral:error:)(GATTBatteryMonitor.swift:143) unconditionally callsattempted.remove(peripheral.identifier). When LinearMouse cancels its own connection to an unmatched peripheral while another app still holds the link, CoreBluetooth deliversdidDisconnectPeripheralto LinearMouse'sCBCentralManager, whileretrieveConnectedPeripherals(withServices: [0x180F])continues to list that peripheral on the next 60-second tick.- Keep rejected UUIDs (and optionally their
GATTBatteryIdentity) recorded for as long as the UUID continues to appear inretrieveConnectedPeripherals(withServices: [Self.batteryService]), pruning entries fromattempted/rejectedIdentitiesinattachConnectedPeripherals()only once the peripheral is no longer connected to the system (and clearing them instop(), on Bluetooth power-off, or whentargets != self.targets).
- Keep rejected UUIDs (and optionally their
- Preserve
matchedTargetambiguity protection (GATTBatteryState.swift:45-47,GATTBatteryTests.swift:103-115):
IfrejectedIdentities: [UUID: GATTBatteryIdentity]is kept for currently system-connected peripherals whoseCBPeripheralconnection was already canceled, passingArray(peers.values.map(\.identity)) + Array(rejectedIdentities.values)intoGATTBatteryIdentity.matchedTarget(...)preserves the existing ambiguity check (testPnPFallbackRequiresCompletedAndUnambiguousDiscovery) without holding openCBPeripheralconnections to non-target devices.
To reproduce
Environment:
- macOS: 27.2.1 (Build
26B131), Apple Silicon (arm64) - LinearMouse: 0.13.0 (also present on
main) - Relevant setup:
- Bluetooth access granted to LinearMouse (System Settings → Privacy & Security → Bluetooth)
- Menu bar icon / battery monitoring active (
BatteryDeviceMonitor60 s refresh timer running) - At least one Bluetooth / BLE pointer device connected (e.g., Logitech MX Master 3S over BLE, making
GATTBatteryMonitortargetsnon-empty) - An unrelated single-link BLE peripheral exposing standard GATT Battery Service (
0x180F) connected transiently by another macOS app
- Run LinearMouse on macOS with Bluetooth access granted and at least one Bluetooth/BLE mouse active.
- From any BLE utility or script, connect to an unrelated BLE peripheral that exposes Battery Service (
0x180F) and perform service discovery so0x180Fis known tobluetoothd. - Keep the connection open across one tick of
BatteryDeviceMonitor's 60-second timer (up to 60 s), then disconnect from the peripheral and quit the BLE utility. - Check
system_profiler SPBluetoothDataType(or scan for the peripheral from another device).
Expected behavior
Expected: bluetoothd closes the unused BLE link immediately after the application disconnects, and the peripheral resumes advertising.
Actual: The peripheral stays listed under Connected in system_profiler SPBluetoothDataType because com.lujjjh.LinearMouse still holds a CoreBluetooth connection to it.
Anything else?
No response
Activity
Release unmatched BLE battery connections (linearmouse#1535)