Skip to content

fix(ble): end the link when the Mac's Bluetooth powers off or resets - #2787

Open
matthiasthomas wants to merge 2 commits into
ryanbr:mainfrom
matthiasthomas:fix/radio-off-teardown
Open

matthiasthomas wants to merge 2 commits into
ryanbr:mainfrom
matthiasthomas:fix/radio-off-teardown

Conversation

@matthiasthomas

@matthiasthomas matthiasthomas commented Oct 13, 2026 •

Copy link
Copy Markdown

What this PR does

CoreBluetooth delivers no didDisconnectPeripheral when the radio powers off or resets. On a Mac that happens every time it sleeps, and on Bluetooth toggles. Nothing tore the link down, so every per-link flag survived into the next link. On poweredOn the app re-attached to the strap macOS still held, with didBond and connectHandshakeDone still true, so the connect handshake never ran again: no Set Clock, no GET_DATA_RANGE, no SEND_HISTORICAL_DATA, no battery read, no alarm re-arm.

What a user sees after a night with the Mac asleep:

  • Frozen sync: a backfill that was mid-drain stays backfilling with a frozen frontier, so the Devices card reads "Syncing…" indefinitely.
  • Stale battery: the battery is the last reading from before the sleep. Here it read 26% while the strap had been on its charger all night.
  • Live data only: HR and double-tap events still arrive, which makes the link look healthy.

From the strap log, Mac asleep 21:58 → awake 09:18:

[21:58:43] Central state: 4 (5 = poweredOn)
[21:58:43] Bluetooth is off — cannot scan or connect
[09:18:13] Central state: 5 (5 = poweredOn)
[09:18:14] Connected — discovering services
[09:18:15] Bonding: confirmed write GET_BATTERY_LEVEL to 61080002
(no handshake follows — no Set Clock / Get Data Range / Send Historical Data / Set Alarm Time;
 battery table's last row stays at 21:56; the card shows "last frame 11h 30m ago")

Fix: centralManagerDidUpdateState now runs the ordinary didDisconnectPeripheral teardown for .poweredOff and .resetting whenever a link was held. It is marked intentional, so:

poweredOn's connectFromSystem → connectCore clears the flag and connects afresh. This is the Apple twin of Android's onBluetoothRadioOff → teardownAfterGattFailure (#314). The state rule is a pure BLEManager.radioStateEndsLink(_:).

Relation to #2716: #2716 re-proves encryptedBond when didConnect re-enters a link that was already bonded. After this PR the radio-off path no longer re-enters with stale state. #2716 still covers the other trigger it documents: the delayed standing-connect retry firing on a live link. The two are independent and can merge in either order.

Type of change

  • Bug fix
  • New feature
  • Refactor / cleanup
  • Documentation
  • CI / tooling

How it was tested

  • Hardware: WHOOP 4.0, firmware 41.17.6.0, macOS 26.4.1. I ran this build overnight on a Mac that sleeps and wakes. Over that run (23:57 → 09:55):

    Event Count
    Teardown log line ("Bluetooth turned off - ending this link here…") 133
    Disconnected (intentional) 133
    Fresh BONDED (confirmed write acknowledged) on the next poweredOn 133
    BONDED again (the fix(ble): stop a reconnected WHOOP 4.0 reading not fully paired #2716 re-entry path) 0
    auto-reconnect paused 0
    Bond-loop (#617) 0

    Each wake ran the full handshake, for example:

    [00:17:35] Bluetooth turned off - ending this link here (CoreBluetooth reports no disconnect for it); the next connect starts a fresh session
    [00:17:35] Disconnected (intentional)
    [09:31:01] Central state: 5 (5 = poweredOn)
    [09:31:06] BONDED (confirmed write acknowledged) — custom channels should now flow
    [09:31:06] → Set Alarm Time payload=…
    [09:31:07] → Send Historical Data payload=00
    [09:31:07] Backfill: session started — historical offload requested
    

    The battery and the sync resumed after wake.

  • Unit tests: RadioOffTeardownTests pins which states end the link: .poweredOff and .resetting do; .poweredOn, .unauthorized, .unknown and .unsupported don't.

  • Full StrandTests (macOS): 2,297 tests ran on this branch. Two failures are timezone-dependent and unrelated to this change: SkinTempAbsoluteDisplayTests and SleepCarriedStampTests fail in America/New_York and pass with TEST_RUNNER_TZ=UTC.

  • Build and checks: xcodegen generate plus xcodebuild (macOS Strand scheme) builds. Tools/doc_comment_lint.py and Tools/i18n_audit.py --ci upstream/main pass.

  • Not verified locally: the iOS compile, because my Xcode lacks the watchOS platform NOOPiOS embeds. iOS reaches the same centralManagerDidUpdateState path when Bluetooth is toggled. I have only exercised the Mac.

Checklist

  • Swift package tests pass for any package I touched (swift test in Packages/<name>): n/a, no package touched
  • Android unit tests pass if I touched android/: n/a. Android already tears down on radio-off (Fix/297 #314)
  • No new build warnings introduced
  • UI changes use only StrandDesign tokens: n/a, no UI change
  • No hardcoded hex frame bytes; protocol facts live in the schema / decoders
  • Follows the conventions in docs/CONTRIBUTING.md
  • I did not commit generated output (Strand.xcodeproj/) or any secrets/keystores

Related issues

Refs #2716

CoreBluetooth delivers no didDisconnectPeripheral when the radio powers off
or resets, which on a Mac happens on every sleep and on Bluetooth toggles.
Nothing tore the link down, so every per-link flag survived into the next
link. On poweredOn the app re-attached to the strap macOS still held with
didBond and connectHandshakeDone still true, so the connect handshake never
ran again: no Set Clock, no GET_DATA_RANGE, no SEND_HISTORICAL_DATA, no
battery read, no alarm re-arm. A backfill that was mid-drain stayed
backfilling with a frozen frontier, so the UI read "Syncing" indefinitely
and the battery shown was the last reading from before the sleep.

centralManagerDidUpdateState now runs the ordinary didDisconnectPeripheral
teardown for .poweredOff and .resetting when a link was held, marked
intentional so it does not feed the bond-loop / drop detectors and does not
schedule a reconnect into a dead radio. poweredOn's connectFromSystem ->
connectCore clears the flag and connects afresh. This is the Apple twin of
Android's onBluetoothRadioOff -> teardownAfterGattFailure (ryanbr#314).

Refs ryanbr#2716

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ryanbr

ryanbr commented Oct 15, 2026

Copy link
Copy Markdown
Owner

Traced the mechanism end to end and it holds up. Notes below, one of them a real hole.

What checks out

  • CoreBluetooth genuinely delivers no didDisconnectPeripheral for a power-off, so the orphan is real.
  • intentionalDisconnect = true before the handler call is the right placement. It suppresses scheduleReconnect at BLEManager.swift:6384, and it also neutralises the bond-loop branch above it, because shouldStandingConnectWhilePaused takes intentionalDisconnect as an input and returns false on it. So the autoReconnectPausedForBondLoop arm cannot park a connect into a dead radio either.
  • The teardown clears connectHandshakeDone and whoop5SessionStarted, which are exactly the two flags the description blames for the skipped handshake.
  • The Android twin named in the comment is real and the same shape: WhoopConnectionService.kt:277 dispatches to WhoopBleClient.kt:4001, which runs the full teardown and relies on the radio-on path to re-arm. Refs Fix/297 #314.
  • Worth adding for context: this is the last of five central managers to handle a non-poweredOn state. StandardHRSource, OuraLiveSource, FTMSSource and HuamiHRSource already carry a default: arm on their state switch that clears live.connected. The WHOOP manager was the only one doing nothing, and it is also the only one with per-link bond and handshake flags to strand, which is why it needs the fuller teardown rather than a flag clear.
  • The bond re-prove work interacts correctly. The teardown clears didBond but leaves lastBondedPeripheralUUID populated, so the next connect classifies as .firstBond on both families rather than latching a stale encryptedBond. Refs fix(ble): re-prove the WHOOP 5/MG encrypted bond on a re-entered link #2785, fix(ble): ask whether the re-proved bond is this strap's #2786.

The hole

The comment says poweredOn's connectFromSystem then connectCore clears the flag. connectCore does clear it, at :1655. But the poweredOn branch has two exits, at :5845 to :5856: when restoredPeripheral is non-nil it goes to connectRestored, which calls central.connect(p, options: nil) directly and never touches intentionalDisconnect. The only writers in the file are :1114, :1655, :1773 and :1806, so didConnect is not one of them either.

So on an iOS session launched through state restoration, where restoredPeripheral is still set because didConnect at :5966 has not cleared it yet, a Bluetooth toggle leaves intentionalDisconnect == true for the whole of the next link. The next genuine out-of-range drop then takes the "Disconnected (intentional)" branch: no scheduleReconnect, and because timedOut computes to false, the marginal-radio fallback does not arm either. The link stays down until Connect is tapped.

macOS, the stated target, is unaffected: there is no CoreBluetooth state restoration there, so poweredOn always takes the connectFromSystem exit.

One line in connectRestored covers it, which also makes the two system-initiated connect entry points consistent.

Minor

radioStateEndsLink includes .resetting, but the switch in the same guard block has no .resetting case, so a bluetoothd restart tears the link down with no message shown (.poweredOff sets state.lastSyncError). It resolves itself on the next poweredOn, so this is cosmetic.

RadioOffTeardownTests covers the predicate only. Nothing exercises the flag lifecycle, which is where the hole above sits.

…ect too

Review follow-up. poweredOn has two connect exits: connectFromSystem ->
connectCore, which clears intentionalDisconnect, and connectRestored, which
did not. On a state-restored iOS session a radio-off teardown therefore left
the flag set for the whole next link, and the next genuine out-of-range drop
took the "Disconnected (intentional)" branch: no reconnect until Connect was
tapped. macOS has no state restoration and was unaffected.

- connectRestored now clears the flag like connectCore.
- Every writer of the flag goes through BLEManager.LinkIntent (connect,
  restoredConnect, userDisconnect, forget, radioOff), so the lifecycle is one
  table and a future connect entry cannot forget it. LinkIntentTests pins it,
  including the radio-off-then-reconnect sequence through either entry.
- .resetting now logs a line ("Bluetooth is restarting …"), so a bluetoothd
  restart that ends a link says why. No banner: it resolves on the next
  poweredOn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@matthiasthomas

matthiasthomas commented Nov 17, 2026 •

Copy link
Copy Markdown
Author

Thanks for tracing it end to end, and sorry for the slow turnaround. All three points are addressed in 761278c:

The hole. connectRestored now clears intentionalDisconnect, the same as connectCore. That makes the two system-initiated connect entries consistent. To stop a future entry point from drifting the same way, every writer of the flag now goes through one table, BLEManager.LinkIntent:

  • connect and restoredConnect clear it.
  • userDisconnect, forget and radioOff set it.

Flag lifecycle coverage. LinkIntentTests pins the table. It checks that both connect entries clear the flag and that only intended teardowns set it. It also replays your sequence: radio-off teardown, then a reconnect through either entry, and the next drop must not be "intentional".

.resetting. It now logs Bluetooth is restarting — waiting for it to come back, so a bluetoothd restart that ends a link says why in the strap log. I left it without a banner because it resolves itself on the next poweredOn; happy to add one if you'd prefer.

Verification:

  • Full StrandTests: 2,301 tests ran. The only failures are the two timezone tests that fix(dates): show day-keyed dates on their own day in every time zone #2723 fixes.
  • New tests: LinkIntentTests and RadioOffTeardownTests pass with no warnings.
  • Mac behaviour: unchanged by this commit; the flag values at the existing writers are the same. The restore path is iOS-only, and I have no iPhone build here to exercise it on hardware.

jvascopf added a commit to jvascopf/noop that referenced this pull request Nov 21, 2026
… the Mac's Bluetooth powers off or resets

ryanbr#2787

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jvascopf added a commit to jvascopf/noop that referenced this pull request Nov 21, 2026
…p from stalling a sync while the strap is connected

ryanbr#2919

Conflict: both sides were additive; kept ryanbr#2912's battery rated-life init call and
ryanbr#2787's LinkIntent table alongside this PR's App Nap exemption.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants