Linux + iPhone Continuity / iMessage / SMS
fix: le connect loop
Zack Barteld03a0b08eab8
diff --git a/docs/BLUETOOTH.md b/docs/BLUETOOTH.mdindex 0512318..37c4d00 100644--- a/docs/BLUETOOTH.md+++ b/docs/BLUETOOTH.md@@ -121,7 +121,8 @@ checks the daemon does not make.| MAP reports `busy`, or the transport says `Connection refused (111)` | Another computer holds the iPhone's single MAP session | Stop the other client || Pairing fails with `br-connection-key-missing` | A stale bond on one side, or the adapter is not `Pairable` | Delete the computer's entry on the phone (Forget This Device) and `tether --bt-unpair <addr>` locally, then pair again || The phone shows two entries for this computer | A failed pairing left both a Classic and an LE record | Delete both on the phone before retrying |-| LE never connects and the log repeats `org.bluez.Error.InProgress` | BlueZ is holding a connect operation that never completed | The daemon now drops the LE bearer itself and redials, which clears it without a restart. If it persists, `sudo systemctl restart bluetooth`. With `tether-btclass@hci0` enabled the class survives the restart |+| LE never connects and the log repeats `org.bluez.Error.InProgress` | BlueZ is holding an auto-connect registration that never completed | `sudo systemctl restart bluetooth` -- nothing short of that clears it, see 2026-08-19 below. With `tether-btclass@hci0` enabled the class survives the restart |+| The status says "Nothing is listening for the iPhone's LE link" | BlueZ refused to register for the phone's LE connection, so nothing is waiting for it | `sudo systemctl restart bluetooth`. This is different from waiting on the phone, which the status says instead when a registration is open || Notifications stopped and never came back, while messages and contacts kept working | Fixed. The bearer supervisor used to stop retrying LE after six attempts, and only a Classic drop or a daemon restart re-armed it | Nothing. LE is now retried indefinitely at the five-minute ceiling, and the ANCS solicitation is kept on air whenever LE is down || `tether --bt-status` reports `Bond: BR/EDR only` | The bond was made without cross-transport key derivation, so it has no LE half and can never carry ANCS | Forget this computer on the iPhone and pair again. Check `secure-connections` in the same output first: re-pairing cannot help while it is off || Everything connects but `ancs_ready` stays false | Compatibility mode, or iOS has not authorized notification content yet | Check `Mode:` in `tether --bt-status`. In full mode the daemon retries, the first request returns `NotPermitted` until the prompt on the phone is approved |@@ -355,12 +356,27 @@ down. Trusting it alone reported "notifications are unavailable" over a sessionthat was delivering them, and kept the supervisor dialling a link that wasalready open.-The ANCS characteristics in the object tree are the better signal, and are what-Tether now reads (`Device::le_link_up()`). GATT exists only over LE, and BlueZ-withdraws those objects when the link drops -- confirmed on this hardware, where-an LE-down device shows only `avrcp` and `sep1-6` under its path and no-`service*` objects at all. Anything that tears the bearer down now refuses to do-so while that tree is present.+**Corrected later the same day.** The first version of this entry concluded that+the presence of the ANCS characteristics in the object tree was the better+signal, on the evidence that an LE-down device showed only `avrcp` and `sep1-6`+under its path. That evidence was from a boot in which no LE session had yet been+established. BlueZ caches a bonded device's attributes (`main.conf` `[GATT]+Cache`, default `always`), so once a session has existed the `service*` objects+persist across a disconnect, and reading their presence as a live link reported+LE up on a dead one -- which stopped the bearer supervisor dialling it at all.++Neither obvious property can be trusted alone:++| Signal | Fails when |+|---|---|+| `Bearer.LE1.Connected` | reads false on a live link the phone opened inbound |+| ANCS characteristics present | survive the disconnect, because BlueZ caches them |++`Notifying` on the Notification Source characteristic is the one that holds. A+notify session needs a live ATT link to exist, so it cannot outlive the link the+way a cached attribute does, and it was true throughout the working session+above. That is what `Device::le_link_up()` reads, and what anything tearing the+bearer down refuses to act against.### 2026-08-19 - The solicitation advert was a one-shot@@ -382,6 +398,122 @@ Measured on the machine above, which had been in the broken state all day: thedaemon brought LE up 12 seconds after starting, with no manual step, and reported`Notification mirroring is active`.+### 2026-08-19 - A subscription latch reported the phone's permission as missing++Same hardware, with all three iPhone toggles granted and verified.++`ancs_ready` stayed false with the reason "Waiting for notification access to be+allowed on the iPhone", which sends the user to settings that are already+correct. `Notifying` on both notify characteristics read false at the time.++`AncsClientState::subscribed` recorded that `StartNotify` had once succeeded, and+nothing re-read it. BlueZ clears `Notifying` when the LE link goes and restores+the characteristics without it, so the flag outlived what it described. The only+thing that used to clear it was `set_device()` seeing the device path change,+which the ANCS grace window and the cached GATT tree together prevented.++`tick()` now re-reads `Notifying` from BlueZ once per retry interval while+`ready` is false, and rebuilds the subscription -- or the whole discovery, when+the characteristics are gone -- rather than trusting the flag. The status text is+reached only with the subscription verified live, so it now names the toggle+(`Share System Notifications`) and means it.++### 2026-08-19 - A hung LE dial poisons the path until bluetoothd restarts++Same hardware, immediately after the above. Every `Bearer.LE1.Connect` was+*accepted* -- `ConnectResult::Requested`, no error -- and no link ever appeared,+while `StartNotify` on the same device answered `org.bluez.Error.InProgress`+indefinitely. `Bearer.LE1.Disconnect` succeeded and changed nothing.++This is worse than the `InProgress` case recorded on 2026-07-16. Three ways out+were tried against it directly, with the daemon stopped so nothing raced them:++| Attempt | Result |+|---|---|+| `Bearer.LE1.Disconnect` | `Not Connected`. Does not cancel a pending connect |+| `Device1.Disconnect` | Succeeds, BR/EDR returns within seconds, LE still `In Progress` |+| Waiting | `In Progress` indefinitely |++**`sudo systemctl restart bluetooth` is the only thing that clears it**, and a+bearer-level recovery built on `Bearer.LE1.Disconnect` was removed again after+this measurement rather than shipped as a remedy that does not remedy anything.++The consequence for the retry policy is the important part. A hung dial is not+free: it poisons `Bearer.LE1.Connect` for that device for the rest of+bluetoothd's life. Six dials after a clean restart were enough to do it. So the+cap on outbound LE attempts is deliberate and stays, and the link is expected to+come from the phone answering the solicitation advert instead -- which is why+that advert now stays on air the whole time LE is down. `reset()` re-arms the+attempts when the device or the Classic link returns, which includes every+bluetoothd restart, so a machine that recovers gets fresh dials without ever+accumulating them.++### 2026-08-19 - What an LE "connect" actually is, captured++`btmon` over a full session, including a clean re-pair. Two findings that change+how the LE half should be driven.++**`Bearer.LE1.Connect` does not dial.** Six Connect calls produced six+`Add Device` with `Action: Auto-connect remote device (0x02)`, one+`LE Add Device To Accept List`, one `LE Add Device To Resolving List`, eighteen+`LE Set Extended Scan Enable` -- and **zero** `LE Create Connection`. BlueZ+registers the phone for background auto-connect and waits for it to advertise.+An iPhone that is already BR/EDR-connected does not advertise, so the request+simply expires.++So the supervisor now holds exactly one registration open for as long as LE is+down (`BearerOps::le_connect_outstanding()`) instead of repeating a dial.+Repeating was what wedged BlueZ: the request runs for `LE_CONNECT_TIMEOUT_MS`+(45s) while the backoff re-fired after five, so registrations overlapped and+every later one answered `InProgress`. `Requested` and `Busy` are both the+healthy state now -- BlueZ is listening -- and only a refusal counts or backs off.++**The advertisement is correct**, which rules out a long-standing suspicion. It+goes out as `Use legacy advertising PDUs: ADV_IND`, connectable and scannable,+public address, 31 bytes exactly:++```+11 15 <ANCS UUID, little-endian> solicitation, AD type 0x15+04 ff ff ff 00 manufacturer data, company 0xffff+04 16 99 99 00 service data, 16-bit UUID 0x9999+02 01 06 flags: LE General Discoverable, BR/EDR Not Supported+```++with `Tether` in an 8-byte scan response. The 16-bit form of the service data is+what keeps it inside the legacy 31-byte limit. Nothing here needs trimming.++### 2026-08-19 - Cross-transport key derivation, captured++The re-pair produced a dual bond, and the capture shows exactly how. Immediately+after the BR/EDR link key lands, SMP runs **over the BR/EDR channel**:++```+HCI Event: Link Key Notification+BR/EDR SMP: Pairing Request Authentication requirement: ... CT2 (0x20)+ Responder key distribution: EncKey IdKey Sign+BR/EDR SMP: Pairing Response Responder key distribution: EncKey IdKey+BR/EDR SMP: Identity Information (the phone's IRK)+BR/EDR SMP: Identity Address Information+MGMT Event: New Identity Resolving Key+MGMT Event: New Long Term Key Key type: Authenticated key from P-256 (0x03)+```++`Authenticated key from P-256` is the point: the LE LTK is derived from the+BR/EDR Secure Connections link key, which is why Secure Connections is a hard+precondition and why `--bt-status` reports it. The `CT2` bit in the+authentication requirements is what asks for the derivation.++**This is the check for a bond that has no LE half.** Capture a pairing with+`sudo btmon -w /tmp/pair.btsnoop` and look for `BR/EDR SMP: Pairing Request`+followed by `New Long Term Key`. If the SMP exchange never happens, or the key+type is not a P-256 one, the bond is BR/EDR-only and no amount of re-soliciting+or restarting will give it ANCS -- it has to be re-made, and Secure Connections+has to be on first.++The `Role Change ... Role: Peripheral` right before the exchange is also worth+noting: the iPhone takes the central role on the ACL, which is what connect-first+pairing exists to allow.+### PBAP`Select("int", "pb")` followed by `PullAll` with `Format: vcard30` and `MaxCount` returned 456 contacts on the first attempt.diff --git a/src/core/include/tether/bluetooth/bearer_supervisor.hpp b/src/core/include/tether/bluetooth/bearer_supervisor.hppindex 3d2372e..1769714 100644--- a/src/core/include/tether/bluetooth/bearer_supervisor.hpp+++ b/src/core/include/tether/bluetooth/bearer_supervisor.hpp@@ -43,8 +43,8 @@ namespace tether::bluetooth {// Must not block: BlueZ keeps working on a connect after a synchronous// call gives up, and every later attempt then collides with it.virtual ConnectResult connect_le(std::string& err) = 0;- // Drops the LE transport alone- virtual ConnectResult disconnect_le(std::string& err) = 0;+ // Whether a connect request is still outstanding+ virtual bool le_connect_outstanding() const = 0;};struct BearerStatus {@@ -84,9 +84,8 @@ namespace tether::bluetooth {BearerStatus status_;int classic_failures_ = 0;- int le_attempts_ = 0;- // Whether LE attempts keep colliding with a connect BlueZ never- // finished, rather than the phone declining. Needs opposite advice.+ int le_failures_ = 0;+ bool le_listening_ = false;bool le_stuck_locally_ = false;int64_t classic_connected_since_ = -1;int64_t next_classic_attempt_ = 0;diff --git a/src/core/include/tether/bluetooth/objects.hpp b/src/core/include/tether/bluetooth/objects.hppindex f723453..3e4f982 100644--- a/src/core/include/tether/bluetooth/objects.hpp+++ b/src/core/include/tether/bluetooth/objects.hpp@@ -48,7 +48,7 @@ namespace tether::bluetooth {bool connected = false;std::vector<std::string> uuids;- bool has_ancs_gatt = false;+ bool ancs_notifying = false;bool has_le_bearer = false;bool le_paired = false;@@ -62,7 +62,7 @@ namespace tether::bluetooth {bool classic_state_known = false;bool classic_link_up() const { return classic_state_known ? classic_connected : connected; }- bool le_link_up() const { return le_connected || has_ancs_gatt; }+ bool le_link_up() const { return le_connected || ancs_notifying; }bool has_uuid(const std::string& uuid) const;bool supports_map() const { return has_uuid(UUID_MAP_MAS); }diff --git a/src/core/src/bluetooth/ancs/client.cpp b/src/core/src/bluetooth/ancs/client.cppindex 090afb2..415c415 100644--- a/src/core/src/bluetooth/ancs/client.cpp+++ b/src/core/src/bluetooth/ancs/client.cpp@@ -44,6 +44,7 @@ namespace tether::bluetooth::ancs {int64_t next_discover = 0;int64_t next_subscribe = 0;int64_t next_probe = 0;+ int64_t next_verify = 0;// Guards everything that crosses a thread boundary: the two GATT buffers// filled on the GLib thread, the characteristic paths that thread compares@@ -77,6 +78,7 @@ namespace tether::bluetooth::ancs {bool discover();bool subscribe();void unsubscribe();+ void verify_subscription();void handle_source_event(const SourceEvent& event, int64_t now);void handle_response(const Request& request, const Response& response, int64_t now);std::string app_display_name(const std::string& app_id);@@ -314,6 +316,62 @@ namespace tether::bluetooth::ancs {}}+ // `subscribed` records that StartNotify once succeeded, which is not the same as a subscription that is still live.+ void AncsClientState::verify_subscription() {+ if (!monitor || !monitor->connection())+ return;+ GDBusConnection* conn = monitor->connection();++ bool object_gone = false;+ bool notifying = true;+ for (const std::string& path : {notification_source_path, data_source_path}) {+ if (path.empty())+ continue;+ GError* error = nullptr;+ GVariant* reply = g_dbus_connection_call_sync(conn,+ BLUEZ_NAME,+ path.c_str(),+ IFACE_PROPS,+ "Get",+ g_variant_new("(ss)", IFACE_CHARACTERISTIC, "Notifying"),+ G_VARIANT_TYPE("(v)"),+ G_DBUS_CALL_FLAGS_NONE,+ CALL_TIMEOUT_MS,+ nullptr,+ &error);+ if (!reply) {+ object_gone = true;+ g_clear_error(&error);+ continue;+ }+ GVariant* boxed = nullptr;+ g_variant_get(reply, "(v)", &boxed);+ if (!boxed || !g_variant_is_of_type(boxed, G_VARIANT_TYPE_BOOLEAN) || !g_variant_get_boolean(boxed))+ notifying = false;+ if (boxed)+ g_variant_unref(boxed);+ g_variant_unref(reply);+ }++ if (!object_gone && notifying)+ return;++ debug::log(INFO,+ "ancs: the notification subscription is no longer live ({}), rebuilding it",+ object_gone ? "characteristics gone" : "BlueZ cleared Notifying");+ unsubscribe();+ subscribed = false;+ next_subscribe = 0;+ if (object_gone) {+ notification_source_path.clear();+ control_point_path.clear();+ data_source_path.clear();+ next_discover = 0;+ }+ sequencer->reset();+ in_progress.clear();+ }+void AncsClientState::handle_source_event(const SourceEvent& event, int64_t now) {(void)now;Decision decision;@@ -457,6 +515,7 @@ namespace tether::bluetooth::ancs {state_->next_discover = 0;state_->next_subscribe = 0;state_->next_probe = 0;+ state_->next_verify = 0;state_->sequencer->reset();state_->in_progress.clear();// A new LE session replays the phone's backlog, so the next batch of@@ -511,6 +570,11 @@ namespace tether::bluetooth::ancs {if (s->device_path.empty())return;+ if (s->subscribed && !s->ready && now >= s->next_verify) {+ s->next_verify = now + ANCS_RETRY_SECONDS;+ s->verify_subscription();+ }+if (s->notification_source_path.empty()) {if (now < s->next_discover)return;@@ -568,7 +632,9 @@ namespace tether::bluetooth::ancs {// that iOS authorized notification access.if (!s->ready && now >= s->next_probe) {s->next_probe = now + ANCS_RETRY_SECONDS;- s->set_status(false, "Waiting for notification access to be allowed on the iPhone.");+ s->set_status(false,+ "Waiting for the iPhone to allow notification access. Settings > Bluetooth > (i) > "+ "Share System Notifications.");s->sequencer->submit(build_app_request(APP_ID_MESSAGES));}}diff --git a/src/core/src/bluetooth/bearer_supervisor.cpp b/src/core/src/bluetooth/bearer_supervisor.cppindex 3cb0e32..8611f8b 100644--- a/src/core/src/bluetooth/bearer_supervisor.cpp+++ b/src/core/src/bluetooth/bearer_supervisor.cpp@@ -64,7 +64,8 @@ namespace tether::bluetooth {void BearerSupervisor::reset() {classic_failures_ = 0;- le_attempts_ = 0;+ le_failures_ = 0;+ le_listening_ = false;le_stuck_locally_ = false;classic_connected_since_ = -1;next_classic_attempt_ = 0;@@ -91,7 +92,7 @@ namespace tether::bluetooth {status_.le_available = ops_.le_bearer_available();status_.le_connected = status_.le_available && ops_.le_connected();if (status_.le_connected) {- le_attempts_ = 0;+ le_failures_ = 0;le_stuck_locally_ = false;status_.le_backoff = 0;next_le_attempt_ = 0;@@ -161,16 +162,8 @@ namespace tether::bluetooth {const bool settled =classic_connected_since_ >= 0 && now - classic_connected_since_ >= BEARER_SETTLE_SECONDS;- if (settled && now >= next_le_attempt_) {- // connect that keeps colliding is bluez still holding one that never finished- if (le_stuck_locally_ && le_attempts_ >= LE_ATTEMPTS_BEFORE_ADVICE) {- std::string drop_err;- if (ops_.disconnect_le(drop_err) == ConnectResult::Failed)- debug::log(WARN, "bluetooth: LE bearer disconnect failed ({})", drop_err);- else- debug::log(INFO, "bluetooth: dropped a stuck LE bearer before retrying");- }-+ if (settled && !ops_.le_connect_outstanding() && le_failures_ < LE_ATTEMPTS_BEFORE_ADVICE &&+ now >= next_le_attempt_) {// Select LE only for this attempt, then hand the preference back// so LE is never left preferred while idle.ops_.set_preferred_bearer("le");@@ -180,25 +173,15 @@ namespace tether::bluetooth {switch (result) {case ConnectResult::Requested:- // BlueZ accepting the request is not a link. Believe only an- // observed Connected, and widen the window each time so the- // next attempt cannot race a connect still running inside it.- ++le_attempts_;- le_stuck_locally_ = false;- status_.le_backoff = grow_backoff(status_.le_backoff);- next_le_attempt_ = now + status_.le_backoff;- break;case ConnectResult::Busy:- // A collision says nothing about the phone, so it selects- // different advice -- but it still counts, or a permanently- // wedged BlueZ would never reach any advice at all.- ++le_attempts_;- le_stuck_locally_ = true;- status_.le_backoff = grow_backoff(status_.le_backoff);- next_le_attempt_ = now + status_.le_backoff;+ le_listening_ = true;+ le_stuck_locally_ = false;+ status_.le_backoff = 0;+ next_le_attempt_ = now + BEARER_POLL_SECONDS;break;case ConnectResult::Failed:- ++le_attempts_;+ ++le_failures_;+ le_listening_ = false;le_stuck_locally_ = false;status_.le_backoff = next_backoff(status_.le_backoff, err);next_le_attempt_ = now + status_.le_backoff;@@ -207,21 +190,14 @@ namespace tether::bluetooth {}}if (!status_.le_connected) {- if (le_attempts_ < LE_ATTEMPTS_BEFORE_ADVICE)- status_.reason = "Connected. Bringing up the LE link for notifications...";- else if (le_stuck_locally_)- // Indistinguishable from a phone that declines, so name the- // local remedy first and the phone second rather than- // sending the user to settings that may be fine already.- status_.reason = "Nothing is bringing up the LE link that carries notifications. BlueZ is "- "holding a connect that never completed; Tether keeps dropping and "- "redialling the LE bearer. If it still will not come up, run \"sudo "- "systemctl restart bluetooth\" -- disconnecting the iPhone does not clear "- "it. Messages and contacts are unaffected.";+ if (ops_.le_connect_outstanding() || le_listening_)+ status_.reason = "Connected. Waiting for the iPhone to open the LE link that carries "+ "notifications. If it does not, open Settings > Bluetooth > (i) on the "+ "iPhone and check Share System Notifications.";else- status_.reason = "The iPhone is not opening the LE link that carries notifications. Tether "- "keeps asking; open Settings > Bluetooth > (i) on the iPhone and turn on "- "Share System Notifications. Messages and contacts are unaffected.";+ status_.reason = "Nothing is listening for the iPhone's LE link. BlueZ refused to register "+ "for it, which only \"sudo systemctl restart bluetooth\" clears. Messages "+ "and contacts are unaffected.";return !(status_ == previous);}}diff --git a/src/core/src/bluetooth/connection.cpp b/src/core/src/bluetooth/connection.cppindex 50be0b0..311389f 100644--- a/src/core/src/bluetooth/connection.cpp+++ b/src/core/src/bluetooth/connection.cpp@@ -221,7 +221,6 @@ namespace tether::bluetooth {// asynchronously and left to run to completion rather than abandoned, so// this is generous on purpose.constexpr int LE_CONNECT_TIMEOUT_MS = 45000;- constexpr int DISCONNECT_TIMEOUT_MS = 10000;constexpr int MESSAGE_POLL_SECONDS = 15;// obexd can drop a MAP session while the Classic link stays up, and the@@ -315,6 +314,11 @@ namespace tether::bluetooth {: ConnectResult::Failed;}+ bool le_connect_outstanding() const override {+ std::lock_guard<std::mutex> lock(le_->mutex);+ return le_->pending;+ }+// Issued asynchronously and never abandoned: a synchronous call that// times out leaves BlueZ still connecting, and the next attempt then// collides with it forever.@@ -364,41 +368,11 @@ namespace tether::bluetooth {return ConnectResult::Requested;}- // Drops the LE transport so a wedged connect can be retried.- ConnectResult disconnect_le(std::string& err) override {- auto device = lookup();- if (!device) {- err = "device not present";- return ConnectResult::Failed;- }- if (!device->has_le_bearer) {- err = "no LE bearer";- return ConnectResult::Failed;- }- // bluez can report the bearer disconnected while gatt is live and ancs is delivering over it.- if (device->has_ancs_gatt) {- err = "ANCS is live on this link";- return ConnectResult::Failed;- }- if (!call(device->path, IFACE_BEARER_LE, "Disconnect", err, DISCONNECT_TIMEOUT_MS)) {- if (err.find("NotConnected") == std::string::npos)- return ConnectResult::Failed;- err.clear();- }-- // A dropped bearer cannot still be the subject of our own outstanding connect- {- std::lock_guard<std::mutex> lock(le_->mutex);- le_->pending = false;- }- return ConnectResult::Requested;- }-private:// Outlives the ops object: a reply can land after the supervised// device is torn down and replaced.struct LeConnect {- std::mutex mutex;+ mutable std::mutex mutex;bool pending = false;std::string error;bool bearer_connect_missing = false;diff --git a/src/core/src/bluetooth/objects.cpp b/src/core/src/bluetooth/objects.cppindex 805429b..603cab4 100644--- a/src/core/src/bluetooth/objects.cpp+++ b/src/core/src/bluetooth/objects.cpp@@ -246,7 +246,7 @@ namespace tether::bluetooth {GVariant* chr = g_variant_lookup_value(ifaces, IFACE_CHARACTERISTIC, G_VARIANT_TYPE("a{sv}"));if (!chr)continue;- if (iequals(get_string(chr, "UUID"), UUID_ANCS_NOTIFICATION_SOURCE))+ if (iequals(get_string(chr, "UUID"), UUID_ANCS_NOTIFICATION_SOURCE) && get_bool(chr, "Notifying"))ancs_char_paths.emplace_back(path);g_variant_unref(chr);}@@ -257,7 +257,7 @@ namespace tether::bluetooth {for (const auto& char_path : ancs_char_paths) {for (auto& device : out.devices) {if (char_path.rfind(device.path + "/", 0) == 0)- device.has_ancs_gatt = true;+ device.ancs_notifying = true;}}@@ -460,7 +460,7 @@ namespace tether::bluetooth {{"map", d.supports_map()},{"pbap", d.supports_pbap()},{"ancs", d.supports_ancs()},- {"ancs_gatt", d.has_ancs_gatt},+ {"ancs_notifying", d.ancs_notifying},{"iphone", d.looks_like_iphone()},};}diff --git a/test/test_bluetooth_objects.cpp b/test/test_bluetooth_objects.cppindex 57730db..2b98d07 100644--- a/test/test_bluetooth_objects.cpp+++ b/test/test_bluetooth_objects.cpp@@ -307,14 +307,14 @@ TEST(Capability, ClassicOnlyBondOnANonPhoneIsNotReported) {// opened the link inbound in answer to the solicitation advert. GATT exists only// over LE and BlueZ withdraws these objects when the link drops, so their// presence is the more trustworthy signal of the two.-TEST(DeviceParsing, AncsCharacteristicsProveTheLeLinkIsUp) {+TEST(DeviceParsing, AnAncsNotifySessionProvesTheLeLinkIsUp) {Payload p(join(ADAPTER_FULL, R"({'/org/bluez/hci0/dev_60_57_C8_30_6A_F7': {'org.bluez.Device1': { 'Paired': <true>, 'Bonded': <true>, 'Connected': <true> },'org.bluez.Bearer.LE1': { 'Paired': <true>, 'Bonded': <true>, 'Connected': <false> }},'/org/bluez/hci0/dev_60_57_C8_30_6A_F7/service004f/char0050': {- 'org.bluez.GattCharacteristic1': { 'UUID': <'9FBF120D-6301-42D9-8C58-25E699A21DBD'> }+ 'org.bluez.GattCharacteristic1': { 'UUID': <'9FBF120D-6301-42D9-8C58-25E699A21DBD'>, 'Notifying': <true> }}})").c_str());@@ -322,13 +322,13 @@ TEST(DeviceParsing, AncsCharacteristicsProveTheLeLinkIsUp) {ASSERT_EQ(objects.devices.size(), 1u);EXPECT_FALSE(objects.devices[0].le_connected) << "the fixture is not reproducing the disagreement";- EXPECT_TRUE(objects.devices[0].has_ancs_gatt);+ EXPECT_TRUE(objects.devices[0].ancs_notifying);EXPECT_TRUE(objects.devices[0].le_link_up()) << "a live ANCS session was reported as no LE link";}// The characteristic has to belong to this device. A sibling device's GATT tree// saying nothing about ours is the whole reason the paths are matched.-TEST(DeviceParsing, AncsCharacteristicsBelongToOneDeviceOnly) {+TEST(DeviceParsing, AnAncsNotifySessionBelongsToOneDeviceOnly) {Payload p(join(ADAPTER_FULL, R"({'/org/bluez/hci0/dev_60_57_C8_30_6A_F7': {'org.bluez.Device1': { 'Paired': <true>, 'Bonded': <true> }@@ -337,20 +337,42 @@ TEST(DeviceParsing, AncsCharacteristicsBelongToOneDeviceOnly) {'org.bluez.Device1': { 'Paired': <true>, 'Bonded': <true> }},'/org/bluez/hci0/dev_F8_D3_F0_3C_84_4A/service004f/char0050': {- 'org.bluez.GattCharacteristic1': { 'UUID': <'9fbf120d-6301-42d9-8c58-25e699a21dbd'> }+ 'org.bluez.GattCharacteristic1': { 'UUID': <'9fbf120d-6301-42d9-8c58-25e699a21dbd'>, 'Notifying': <true> }}})").c_str());auto objects = parse_managed_objects(p.v);ASSERT_EQ(objects.devices.size(), 2u);- EXPECT_FALSE(objects.devices[0].has_ancs_gatt) << "borrowed a sibling device's GATT tree";- EXPECT_TRUE(objects.devices[1].has_ancs_gatt);+ EXPECT_FALSE(objects.devices[0].ancs_notifying) << "borrowed a sibling device's notify session";+ EXPECT_TRUE(objects.devices[1].ancs_notifying);}// An LE link that is down has no GATT tree, which is what makes its presence// mean anything.-TEST(DeviceParsing, NoGattTreeMeansNoLeLink) {+// BlueZ caches a bonded device's attributes (main.conf [GATT] Cache, default+// always), so the ANCS characteristics stay in the object tree long after the LE+// link is gone. Reading their presence as a live link reported LE up on a dead+// one, which stopped the bearer supervisor dialling it at all.+TEST(DeviceParsing, CachedCharacteristicsWithoutNotifyAreNotALink) {+ Payload p(join(ADAPTER_FULL, R"({+ '/org/bluez/hci0/dev_60_57_C8_30_6A_F7': {+ 'org.bluez.Device1': { 'Paired': <true>, 'Bonded': <true>, 'Connected': <true>, 'ServicesResolved': <true> },+ 'org.bluez.Bearer.LE1': { 'Paired': <true>, 'Bonded': <true>, 'Connected': <false> }+ },+ '/org/bluez/hci0/dev_60_57_C8_30_6A_F7/service006f/char0073': {+ 'org.bluez.GattCharacteristic1': { 'UUID': <'9fbf120d-6301-42d9-8c58-25e699a21dbd'>, 'Notifying': <false> }+ }+ })")+ .c_str());+ auto objects = parse_managed_objects(p.v);++ ASSERT_EQ(objects.devices.size(), 1u);+ EXPECT_FALSE(objects.devices[0].ancs_notifying);+ EXPECT_FALSE(objects.devices[0].le_link_up()) << "a cached GATT tree was read as a live LE link";+}++TEST(DeviceParsing, NoGattTreeAtAllMeansNoLeLink) {Payload p(join(ADAPTER_FULL, R"({'/org/bluez/hci0/dev_60_57_C8_30_6A_F7': {'org.bluez.Device1': { 'Paired': <true>, 'Bonded': <true>, 'Connected': <true> },@@ -361,7 +383,7 @@ TEST(DeviceParsing, NoGattTreeMeansNoLeLink) {auto objects = parse_managed_objects(p.v);ASSERT_EQ(objects.devices.size(), 1u);- EXPECT_FALSE(objects.devices[0].has_ancs_gatt);+ EXPECT_FALSE(objects.devices[0].ancs_notifying);EXPECT_FALSE(objects.devices[0].le_link_up());}diff --git a/test/test_bluetooth_supervisor.cpp b/test/test_bluetooth_supervisor.cppindex 3bc2e18..14bea53 100644--- a/test/test_bluetooth_supervisor.cpp+++ b/test/test_bluetooth_supervisor.cpp@@ -54,18 +54,11 @@ namespace {return ConnectResult::Requested;}- int le_disconnects = 0;- bool disconnect_le_succeeds = true;-- ConnectResult disconnect_le(std::string& err) override {- ++le_disconnects;- if (!disconnect_le_succeeds) {- err = "no LE bearer";- return ConnectResult::Failed;- }- le = false;- return ConnectResult::Requested;- }+ // Models BlueZ holding the accept-list registration open. Tests that+ // care set this; the default of "nothing outstanding" keeps the older+ // cases reading as they did.+ bool outstanding = false;+ bool le_connect_outstanding() const override { return outstanding; }};class FakeProfiles : public ProfileOps {@@ -190,27 +183,6 @@ TEST(BearerSupervisor, InProgressWidensTheClassicWindow) {EXPECT_EQ(ops.classic_attempts, 5);}-TEST(BearerSupervisor, InProgressWidensTheLeWindow) {- FakeBearer ops;- ops.le_succeeds = false;- ops.le_error = "GDBus.Error:org.bluez.Error.InProgress: In Progress";- BearerSupervisor sup(ops, true);-- // Classic is observed connected on the tick after it is dialed, and the- // settle window runs from there.- sup.tick(0);- sup.tick(1);- int64_t now = 1 + BEARER_SETTLE_SECONDS;- int previous = 0;- for (int i = 0; i < LE_ATTEMPTS_BEFORE_ADVICE; ++i) {- sup.tick(now);- EXPECT_GT(sup.status().le_backoff, previous) << "collided again at the same cadence";- previous = sup.status().le_backoff;- now += previous;- }- EXPECT_EQ(ops.le_attempts, LE_ATTEMPTS_BEFORE_ADVICE);-}-// A refusal is different: the phone said no, and hammering it was observed to// hold the bond in a half-connected flapping state.TEST(BearerSupervisor, RefusalStillGrowsTheLeBackoff) {@@ -531,6 +503,90 @@ TEST(BearerSupervisor, TransientFailuresDoNotEscalateTheBackoff) {}}+// BlueZ implements an LE connect as an accept-list registration plus a+// background scan -- it waits for the phone to advertise rather than dialling+// it. Captured 2026-08-19: six Connect calls produced six "Add Device, action+// auto-connect" and not one LE Create Connection. So exactly one registration+// should be held open while LE is down, and repeating it is not progress.+TEST(BearerSupervisor, HoldsOneLeRegistrationRatherThanRepeatingIt) {+ class ListeningBearer : public FakeBearer {+ public:+ ConnectResult connect_le(std::string&) override {+ ++le_attempts;+ outstanding = true; // BlueZ now holds it until the request completes+ return ConnectResult::Requested;+ }+ } listening;++ BearerSupervisor sup(listening, true);+ int64_t now = 0;+ sup.tick(now);+ sup.tick(++now);+ now += BEARER_SETTLE_SECONDS;+ sup.tick(now);+ EXPECT_EQ(listening.le_attempts, 1);++ // Hours of ticks while BlueZ is listening must not add a second one.+ for (int i = 0; i < 500; ++i)+ sup.tick(++now);+ EXPECT_EQ(listening.le_attempts, 1) << "re-registered on top of a live registration";+ EXPECT_NE(sup.status().reason.find("Waiting for the iPhone to open the LE link"), std::string::npos);++ // When the request finally completes without a link, one fresh registration+ // replaces it -- still only ever one at a time.+ listening.outstanding = false;+ sup.tick(++now);+ EXPECT_EQ(listening.le_attempts, 2);+}++// InProgress means BlueZ already holds a registration. That is the state worth+// being in, so it must not be counted as a failure or earn a backoff -- treating+// it as one is what turned a healthy wait into an escalating retry.+TEST(BearerSupervisor, InProgressIsListeningNotFailing) {+ class InProgressBearer : public FakeBearer {+ public:+ ConnectResult connect_le(std::string& err) override {+ ++le_attempts;+ err = "GDBus.Error:org.bluez.Error.InProgress: In Progress";+ return ConnectResult::Failed;+ }+ } busy;++ BearerSupervisor sup(busy, true);+ int64_t now = 0;+ sup.tick(now);+ sup.tick(++now);+ now += BEARER_SETTLE_SECONDS;+ sup.tick(now);++ EXPECT_EQ(sup.status().le_backoff, 0) << "an outstanding registration was treated as a refusal";+ EXPECT_NE(sup.status().reason.find("Waiting for the iPhone"), std::string::npos);+}++// A registration BlueZ refuses outright is different: nothing is listening, and+// the status has to say so rather than implying the phone is being waited on.+TEST(BearerSupervisor, ARefusedRegistrationSaysNothingIsListening) {+ FakeBearer ops;+ ops.le_succeeds = false;+ ops.le_error = "org.bluez.Error.AuthenticationFailed";+ BearerSupervisor sup(ops, true);++ int64_t now = 0;+ sup.tick(now);+ sup.tick(++now);+ now += BEARER_SETTLE_SECONDS;+ while (ops.le_attempts < LE_ATTEMPTS_BEFORE_ADVICE) {+ sup.tick(now);+ now += BEARER_BACKOFF_MAX_SECONDS;+ }+ sup.tick(now);++ EXPECT_NE(sup.status().reason.find("Nothing is listening"), std::string::npos);+ EXPECT_NE(sup.status().reason.find("systemctl restart bluetooth"), std::string::npos);+ EXPECT_NE(sup.status().reason.find("Messages and contacts are unaffected"), std::string::npos);+ EXPECT_GT(sup.status().le_backoff, BEARER_BACKOFF_MIN_SECONDS) << "a refusal must still back off";+}+// A refusal from the phone is a real answer, and repeating it every five seconds// helps nobody.TEST(BearerSupervisor, PersistentFailuresStillEscalate) {@@ -671,48 +727,6 @@ TEST(BearerSupervisor, RepeatedRefusalNamesTheRemedy) {EXPECT_TRUE(sup.status().classic_connected);}-// BR/EDR can stay up for days, so the LE half is the only one that ever needs-// re-dialling, and nothing else in the daemon dials it. Standing down for good-// after a run of failures left notification mirroring dead until a restart even-// though the phone had long since become willing. The backoff ceiling, not a-// attempt cap, is what keeps this from being a storm.-TEST(BearerSupervisor, KeepsDiallingLeAtTheCappedCadence) {- // A phone that will not accept an inbound LE connect: BlueZ keeps working- // after our call gives up, so the next attempts collide with it.- class RefusingBearer : public FakeBearer {- public:- ConnectResult connect_le(std::string& err) override {- ++le_attempts;- err = (le_attempts % 2) ? "Timeout was reached" : "GDBus.Error:org.bluez.Error.InProgress: In Progress";- return ConnectResult::Failed;- }- } refusing;-- BearerSupervisor sup(refusing, true);- int64_t now = 0;- sup.tick(now);- now += BEARER_SETTLE_SECONDS + 1;-- for (int i = 0; i < 200; ++i) {- now += BEARER_BACKOFF_MAX_SECONDS;- sup.tick(now);- }-- EXPECT_GT(refusing.le_attempts, LE_ATTEMPTS_BEFORE_ADVICE) << "LE was abandoned for the daemon's whole lifetime";- EXPECT_NE(sup.status().reason.find("LE link that carries notifications"), std::string::npos);-- // ...but no faster than the ceiling. Every tick above is a full backoff- // window apart, so one attempt per window is the most that may happen.- EXPECT_LE(refusing.le_attempts, 202) << "the backoff ceiling is not pacing the retries";-- // And it recovers the moment the phone becomes willing, with no reset() and- // no restart.- refusing.le = true;- now += BEARER_BACKOFF_MAX_SECONDS;- sup.tick(now);- EXPECT_TRUE(sup.status().le_connected);-}-// An LE link that needed a few tries, then held, must not resume at the backoff// those tries grew to. Inheriting it means the first drop after a healthy day// costs five minutes of dead notification mirroring.@@ -748,158 +762,3 @@ TEST(BearerSupervisor, ASuccessfulLeLinkClearsTheBackoffItGrew) {EXPECT_EQ(ops.le_attempts, attempts + 1) << "sat out a backoff inherited from a previous outage";EXPECT_EQ(sup.status().le_backoff, BEARER_BACKOFF_MIN_SECONDS);}--// A connect that keeps colliding is BlueZ holding one that never finished.-// Waiting does not clear it; dropping the bearer does. Without this the only-// documented remedy was restarting bluetoothd.-TEST(BearerSupervisor, DropsAStuckLeBearerBeforeRedialling) {- class StuckBearer : public FakeBearer {- public:- ConnectResult connect_le(std::string& err) override {- ++le_attempts;- err = "GDBus.Error:org.bluez.Error.InProgress: In Progress";- return ConnectResult::Busy;- }- } stuck;-- BearerSupervisor sup(stuck, true);- int64_t now = 0;- sup.tick(now);- now += BEARER_SETTLE_SECONDS + 1;-- // Nothing is dropped while the run is still short enough to be ordinary.- while (stuck.le_attempts < LE_ATTEMPTS_BEFORE_ADVICE) {- sup.tick(now);- now += BEARER_BACKOFF_MAX_SECONDS;- }- EXPECT_EQ(stuck.le_disconnects, 0) << "dropped the bearer before the collisions meant anything";-- sup.tick(now);- EXPECT_EQ(stuck.le_disconnects, 1) << "a wedged bearer was never dropped";-- // One per backoff window at most, not one per tick.- sup.tick(now + 1);- EXPECT_EQ(stuck.le_disconnects, 1) << "dropped the bearer again inside its own backoff";-}--// A refusal from the phone is not a collision, and tearing the transport down-// over one would interrupt a link that is merely unwelcome, not stuck.-TEST(BearerSupervisor, DoesNotDropTheBearerOverAPlainRefusal) {- FakeBearer ops;- ops.le_succeeds = false;- ops.le_error = "org.bluez.Error.Failed: le-connection-abort-by-local";- BearerSupervisor sup(ops, true);-- int64_t now = 0;- sup.tick(now);- now += BEARER_SETTLE_SECONDS + 1;- for (int i = 0; i < LE_ATTEMPTS_BEFORE_ADVICE * 3; ++i) {- sup.tick(now);- now += BEARER_BACKOFF_MAX_SECONDS;- }-- EXPECT_GT(ops.le_attempts, LE_ATTEMPTS_BEFORE_ADVICE);- EXPECT_EQ(ops.le_disconnects, 0) << "a refusal is the phone's answer, not a wedged bearer";-}--// A link that is up must never be torn down by the recovery path.-TEST(BearerSupervisor, NeverDropsAConnectedLeBearer) {- FakeBearer ops;- BearerSupervisor sup(ops, true);-- sup.tick(0);- sup.tick(1);- sup.tick(1 + BEARER_SETTLE_SECONDS);- sup.tick(2 + BEARER_SETTLE_SECONDS);- ASSERT_TRUE(sup.status().le_connected);-- for (int i = 0; i < 50; ++i)- sup.tick(10 + BEARER_BACKOFF_MAX_SECONDS * i);- EXPECT_EQ(ops.le_disconnects, 0);-}--// A wedged bluetoothd and a phone that declines both end in a dead LE link, but-// only one of them is fixed on the phone. Sending the user to iOS settings for a-// stuck local connect is the wrong errand.-TEST(BearerSupervisor, StuckBluezAdviceNamesTheDaemonRestart) {- class StuckBearer : public FakeBearer {- public:- ConnectResult connect_le(std::string& err) override {- ++le_attempts;- err = "GDBus.Error:org.bluez.Error.InProgress: In Progress";- return ConnectResult::Failed;- }- } stuck;-- BearerSupervisor sup(stuck, true);- int64_t now = 0;- sup.tick(now);- now += BEARER_SETTLE_SECONDS + 1;- while (stuck.le_attempts < LE_ATTEMPTS_BEFORE_ADVICE) {- now += BEARER_BACKOFF_MAX_SECONDS;- sup.tick(now);- }-- EXPECT_NE(sup.status().reason.find("systemctl restart bluetooth"), std::string::npos)- << "the one thing that clears a stuck connect is never named";- EXPECT_NE(sup.status().reason.find("Messages and contacts are unaffected"), std::string::npos);-- // A refusal that never collides is the phone's to fix, and must not send the- // user restarting daemons.- FakeBearer refusing;- refusing.le_succeeds = false;- refusing.le_error = "org.bluez.Error.Failed: le-connection-abort-by-local";- BearerSupervisor other(refusing, true);- now = 0;- other.tick(now);- now += BEARER_SETTLE_SECONDS + 1;- while (refusing.le_attempts < LE_ATTEMPTS_BEFORE_ADVICE) {- now += BEARER_BACKOFF_MAX_SECONDS;- other.tick(now);- }-- EXPECT_NE(other.status().reason.find("not opening the LE link"), std::string::npos);- EXPECT_EQ(other.status().reason.find("systemctl"), std::string::npos) << "nothing here says BlueZ is wedged";-}--TEST(BearerSupervisor, UndiallableLeStopsClaimingItIsComingUp) {- // The connect reports success but the link never appears, which is exactly- // what a Device1.Connect fallback does on an already-connected device.- class OptimisticBearer : public FakeBearer {- public:- ConnectResult connect_le(std::string&) override {- ++le_attempts;- return ConnectResult::Requested;- }- } optimistic;-- BearerSupervisor sup(optimistic, true);- int64_t now = 0;- sup.tick(now);- sup.tick(++now);- now += BEARER_SETTLE_SECONDS;- sup.tick(now);- // The attempt reports success, so this tick believes it. The next one reads- // the real state back and finds nothing there.- sup.tick(++now);- ASSERT_FALSE(sup.status().le_connected) << "the fake never actually brings LE up";- EXPECT_NE(sup.status().reason.find("Bringing up the LE link"), std::string::npos);-- while (optimistic.le_attempts < LE_ATTEMPTS_BEFORE_ADVICE) {- now += BEARER_BACKOFF_MIN_SECONDS;- sup.tick(now);- }- // The tick that made the last attempt believed it worked; the one after reads- // the truth back, and that is where the status has to change.- sup.tick(++now);-- EXPECT_NE(sup.status().reason.find("not opening the LE link"), std::string::npos)- << "the status never admits the link is not coming from this end";- EXPECT_NE(sup.status().reason.find("Messages and contacts are unaffected"), std::string::npos)- << "a user reading this needs to know messages still work";-- // An optimistic success must not turn into a connect attempt every tick.- const int attempts = optimistic.le_attempts;- sup.tick(++now);- EXPECT_EQ(optimistic.le_attempts, attempts) << "LE was re-dialled inside its own backoff";-}