Repository navigation
fix(ble): force reconnect on CDM appear (android) + kick stuck .connecting on foreground (ios) - #6987
Conversation
When a retry is sitting on autoConnect=true passive scan and the device can't be found (e.g. congested RF at events), the stuck GATT has currentGattHash set. If CompanionDeviceManager then fires EVENT_BLE_APPEARED — which means the OS scan *did* find the device — our previous code called manageDevice, which saw the non-null hash and returned without doing anything. The CDM signal was silently dropped. Fix: when startService is called with a CompanionSvc caller and the service is already running, route to a new forceReconnect() method that cancels pending retries, closes the stuck GATT, and starts a fresh connect. Mirrors Fieldy's approach of treating CDM presence events as the most reliable "device is here" indicator and always acting on them. Rate limiting (15s) remains so rapid CDM events don't spam connectGatt.
…n foreground reconnectStalePeripherals skipped both .connected and .connecting states. A peripheral with a long-pending connect() in congested RF would be silently ignored on foreground — nothing nudged CoreBluetooth to retry. Match Fieldy's approach: on foreground, re-issue connect() for any non-.connected peripheral. connect() is idempotent, so this is safe for .connecting peripherals and kicks truly-stuck ones.
Greptile SummaryThis PR fixes stuck BLE reconnections in congested RF environments: on Android, a new
Confidence Score: 4/5Safe to merge after the The iOS fix is clean and correct. The Android app/android/app/src/main/kotlin/com/friend/ios/OmiBleForegroundService.kt — specifically the Important Files Changed
Flowchart%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[startService called] --> B{Rate-limit check\nCompanionSvc only}
B -->|Rate-limited| Z[Return / skip]
B -->|Pass| C{Service instance\nalready running?}
C -->|No| D[Start foreground service\nonStartCommand → manageDevice]
C -->|Yes — NEW behavior| E[forceReconnect\naddr, requiresBond, caller]
C -->|Yes — OLD behavior| F[manageDevice\naddr, requiresBond]
E --> G{isPeripheralConnected?}
G -->|Yes| Z
G -->|No| H[synchronized: cancel pending retry\nclose stuck GATT\nreset retryCount]
H --> I[connectToDevice addr, source\nautoConnect = source != manageDevice]
F --> J{currentGattHash != null\nor pendingReconnect?}
J -->|Yes| Z
J -->|No| K[triggerReconnection / connectToDevice]
F --> L[Persist to SharedPreferences]
style E fill:#f9a,stroke:#c00
style F fill:#adf,stroke:#06c
style L fill:#adf,stroke:#06c
Reviews (2): Last reviewed commit: "refactor(android/ble): always force reco..." | Re-trigger Greptile |
| managed.currentGattHash = null | ||
| } | ||
| } | ||
| connectToDevice(addr, source) |
There was a problem hiding this comment.
autoConnect=true defeats the "device is definitely here" intent
connectToDevice derives autoConnect as source != "manageDevice". Since forceReconnect passes the raw CDM caller string (e.g. "CompanionSvc.deviceAppeared"), the new GATT is opened with autoConnect=true — the same passive background-scan mode that was already stuck. CDM EVENT_BLE_APPEARED is exactly the "device is confirmed nearby right now" signal; this code path should request a fast, active connect (autoConnect=false) just like the original manageDevice call does.
Suggested fix — use a dedicated source name that maps to autoConnect=false:
// in connectToDevice:
val autoConnect = source != "manageDevice" && source != "forceReconnect"
// in forceReconnect, replace:
connectToDevice(addr, source)
// with:
connectToDevice(addr, "forceReconnect")… running The single-owner refactor eliminated the Dart-side races that the caller check was guarding against. BT toggle now goes through triggerReconnection directly (bypasses manageDevice), MainActivity only fires on fresh pair, and Dart's manageDevice is called once per connect lifecycle. Simplify startService to match Fieldy: any call that lands while the service is running is a "please (re)connect" signal — route all callers through forceReconnect so a stuck autoConnect=true retry doesn't silently swallow the request.
|
@greptile-apps re-review |
| if (inst != null) { | ||
| Log.d(TAG, "startService($caller): service already running, managing $deviceAddress directly") | ||
| inst.manageDevice(deviceAddress, requiresBond) | ||
| // Service already running — any startService call is effectively a | ||
| // "please (re)connect this device" signal. Always force a fresh attempt | ||
| // so a stuck autoConnect=true passive scan doesn't silently swallow it. | ||
| Log.d(TAG, "startService($caller): service running, forcing reconnect for $deviceAddress") | ||
| inst.forceReconnect(deviceAddress, requiresBond, caller) | ||
| return | ||
| } |
There was a problem hiding this comment.
All callers bypass
manageDevice guards and SharedPreferences persistence
The change routes every startService call (not just CompanionSvc) through forceReconnect when the service is already running. manageDevice does two things this path now skips:
- Persistence — lines 254–257 write
addr|requiresBondto SharedPreferences so the service can recover the managed device after a restart.forceReconnectnever touches SharedPreferences, so if Dart callsstartServiceto updaterequiresBondwhile the service is running, the new value is applied in-memory only and lost on service restart. - In-progress guard —
manageDevicereturns early whenexisting.currentGattHash != null || existing.pendingReconnect != null(line 271), intentionally not interrupting an active connection attempt.forceReconnectalways cancels the pending retry and closes the GATT, even for harmless app-foregrounding or BT-toggle calls from Dart.
The PR description explicitly states "Non-CompanionSvc callers (Dart manageDevice, BT toggle handler) still go through manageDevice as before," but the implementation contradicts this. A minimal fix would be to route only CompanionSvc callers through forceReconnect:
if (caller.startsWith("CompanionSvc")) {
inst.forceReconnect(deviceAddress, requiresBond, caller)
} else {
inst.manageDevice(deviceAddress, requiresBond)
}
kodjima33
left a comment
There was a problem hiding this comment.
mobile BLE — approve only
…engine Background Mode keeps OmiBleForegroundService and the GATT link alive after the Flutter engine dies. On the next app start Dart calls manageDevice to re-establish its side, but startService routed that to forceReconnect, which returned silently when the peripheral was already connected (#6987). onDeviceReady is Dart's only "connected" signal, so connect() waited out its 60s timeout and settled on disconnected while the link was up: blue LED, "Connected to Omi" in the service notification, no transcription, recoverable only by a manual disconnect. Route already-running connect requests through onConnectRequest, which adopts the live link and re-emits ready when the peripheral is connected and otherwise forces a fresh attempt as before. manageDevice shares the same adopt helper. Also stop gating the native audio subscription on isFlutterAlive, and clear isFlutterAlive/nativeBleForegroundReady on every activity destroy rather than only a finishing one. A system-initiated destroy left both stale, so native deferred the audio characteristic to an engine that no longer existed and nobody subscribed it. Verification: cd app/android && ./gradlew :app:testDevDebugUnitTest # 15 tests, 0 failures cd app && flutter build apk --flavor dev --debug # built Fixes #10847 Failure-Class: new
… outlives the Flutter engine (#10908) Fixes #10847. ## Symptom On Android with Background Mode on, the app shows the device as disconnected while the LED is blue, the foreground-service notification says "Connected to Omi", and the diagnostics page still counts connection uptime. Transcription stops silently. The only recovery is a manual disconnect + reconnect. ## Root cause Background Mode's whole point is that `OmiBleForegroundService` — and the GATT link it owns — outlive the Flutter engine. When the user reopens the app, a fresh engine and a fresh Dart isolate start at `isConnected = false` and call `manageDevice` to re-establish their side of a link that is already up. `startService()` routes that call to `forceReconnect()` when the service instance already exists, and `forceReconnect()` returned immediately if the peripheral was connected. The "already connected → re-emit ready" resync (`notifyReadyForConnectedGatt`) lives only in `manageDevice()`, which that branch bypasses. `onDeviceReady` is the only signal Dart has for "connected", so `NativeBleTransport.connect()` waited out its 60s timeout and settled on `disconnected` — permanently, since nothing reconciles Dart state against native. This is a regression from #6987, which replaced `inst.manageDevice(...)` with `inst.forceReconnect(...)` to break stuck `autoConnect` passive scans. The already-connected case was never the stuck case, and it lost its resync in the swap. Two adjacent defects turn "wrong badge" into "silent loss of transcription": - `ensureBackgroundAudioSubscription()` returned early whenever `isFlutterAlive` was true, deferring the audio CCCD subscribe to Dart. With Dart stuck disconnected, any subsequent BLE drop/reconnect left the audio characteristic subscribed by nobody — link up, zero packets. - `isFlutterAlive` was cleared only when the activity was *finishing*. A system-initiated destroy (memory pressure while the foreground service pins the process) left it `true` pointing at a dead binary messenger, alongside a stale `nativeBleForegroundReady` that makes `OmiBackgroundAudioStreamer` bail with `foreground_ready`. ## Change - `startService` → `onConnectRequest`, which adopts the live link and re-emits ready when the peripheral is connected, and otherwise forces a fresh attempt exactly as before. `manageDevice` shares the same `adoptConnectedDevice` helper. The decision is a pure policy function (`BleConnectRouter.kt`) so the contract is testable off-device. - `adoptConnectedDevice` deliberately does not touch the managed-device or user-disconnected prefs, so a CompanionDeviceManager appear event can never resurrect a device the user explicitly disconnected. - Native always ensures the audio subscription; enabling notifications is idempotent. - `MainActivity.onDestroy` clears `isFlutterAlive` and `nativeBleForegroundReady` whether or not the activity is finishing. `configureFlutterEngine` re-arms both on attach. - Dart: a guard test pinning that a device-ready never replaces stream controllers that still have subscribers. The native resync makes a repeated `onDeviceReady` routinely reachable, and replacing live controllers orphans every subscriber — the same silent audio stop in a new shape. `main` landed the controller-preservation branch itself while this PR was open (b0e2b2b, d5b35a4), so this commit is now the test plus a `hostApi` seam that lets the transport be driven without a platform channel. ## Verification ``` cd app/android && ./gradlew :app:testDevDebugUnitTest # 15 tests, 0 failures (3 new) cd app && flutter test test/unit/native_ble_transport_resync_test.dart # 2 passed cd app && flutter analyze <changed dart files> # No issues found cd app && flutter build apk --flavor dev --debug # built cd app && ./test.sh # 956 passed, 1 failed ``` The new Dart test is a real guard: removing the controller-preservation branch makes it fail with `Expected: [[1, 2, 3]] Actual: []`. The single `./test.sh` failure is `conversation_detail_provider_selection_test.dart: conversation getter resolves when startedAt and createdAt fall on different days`, a date-boundary test unrelated to this change. Confirmed pre-existing: it fails identically on `origin/main` with these commits stashed. Not verified by me: the on-device repro (Background Mode on, close the app, reopen, confirm the app adopts the live link and resumes transcription) needs the pendant. `BleConnectRouterTest` is a contract test on new code rather than a regression test, and Android unit tests are not currently run by any CI workflow — a pre-existing gap, worth wiring into `mobile-app-checks.yml` in its own change. Failure-Class: new --- Rebased on `main`, and re-verified there: `./gradlew :app:testDevDebugUnitTest`, `flutter test test/unit/native_ble_transport_resync_test.dart`, `flutter analyze`, and `flutter build apk --flavor dev --debug` all pass on the rebased branch. The branch originally carried a fourth commit fixing `${resolved,,}` (a bash 4+ expansion) in `scripts/dev-harness/_resolve_python.sh`, which crashed `pre-push-singleflight` on macOS bash 3.2. `main` fixed the same defect in 5c8f8f6 / cd997c0, so that commit is dropped. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Problem
In congested RF environments (events, venues with heavy BLE/WiFi traffic), when the device disconnects and the app retries, the pending reconnection attempt can sit indefinitely waiting for advertising packets. Users had to bring the phone within 1-2 inches of the device for it to finally reconnect.
Happens on both Android and iOS — different underlying mechanisms but same user experience.
Android root cause
The most reliable "device is here" signal the OS gives us was being silently dropped.
Android fix
Mirror Fieldy's pattern: when CDM triggers `startService`, bypass `manageDevice`'s guards and route to a new `forceReconnect` method that cancels the pending retry, closes the stuck GATT, and starts a fresh `connectToDevice`. Non-CompanionSvc callers (Dart `manageDevice`, BT toggle handler) still go through `manageDevice` as before. Rate limiting (15s) preserved.
iOS root cause
`OmiBleManager.reconnectStalePeripherals()` is called on `applicationWillEnterForeground` and re-issues `centralManager.connect(peripheral, options: nil)` on previously-connected peripherals that aren't currently connected. But it skipped peripherals in `.connecting` state:
```swift
switch peripheral.state {
case .connected, .connecting:
continue // <-- skip both
```
A peripheral stuck in `.connecting` (iOS equivalent of Android's stuck `autoConnect=true`) got no kick on foreground.
iOS fix
Match Fieldy's `handleWillEnterForeground`: re-issue `connect()` for any non-`.connected` peripheral. iOS's `connect()` is idempotent — safe for already-connecting peripherals, and it nudges CoreBluetooth to retry for truly stuck ones.
Files
Test plan