Skip to content

fix(android): re-emit device-ready when Background Mode's BLE service outlives the Flutter engine - #10908

Merged
mdmohsin7 merged 3 commits into
mainfrom
fix/android-bg-mode-ble-resync
Aug 11, 2026
Merged

mdmohsin7 merged 3 commits into
mainfrom
fix/android-bg-mode-ble-resync

Conversation

@mdmohsin7

@mdmohsin7 mdmohsin7 commented Jul 30, 2026 •

Copy link
Copy Markdown
Member

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

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Android bug fix (5/5): re-emits device-ready when Background Mode's BLE service outlives the Flutter engine (#10847); clear root cause + unit tests. Not merged — branch has conflicts with main.

…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
…lers

A device-ready for a link that is already up must not swap out stream controllers
that still have subscribers: the capture provider's audio subscription would be
orphaned and BLE packets would land where nobody listens — the same silent audio
stop as the native defect, in a new shape. main already preserves open controllers;
this pins that behaviour, which the native resync in the previous commit makes
routinely reachable.

Adds a hostApi seam to NativeBleTransport so the transport can be driven in a test
without a platform channel.

Verification:
  cd app && flutter test test/unit/native_ble_transport_resync_test.dart
    # 2 passed; the first fails (Expected: [[1, 2, 3]] Actual: []) when the
    # controller-preservation branch is removed
The class this PR's fix instantiates: an establish request whose target is already
in the desired state must still emit the observation its client depends on. Its
guard surface is the BleConnectRouter policy plus the contract test that pins the
already-connected branch to a ready re-emit.
@mdmohsin7
mdmohsin7 force-pushed the fix/android-bg-mode-ble-resync branch from 099d13e to 42f2797 Compare August 11, 2026 11:51
@mdmohsin7
mdmohsin7 merged commit 53999d8 into main Aug 11, 2026
31 checks passed
@mdmohsin7
mdmohsin7 deleted the fix/android-bg-mode-ble-resync branch August 11, 2026 12:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app flutter flutter work human Human-authored pull request mobile workflow-review Needs maintainer review for workflow, automation, hooks, or CI behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Android background mode shows device as disconnected even though status says connected, and transcription stops until manual reconnect

3 participants