Skip to content

fix(ios): stop background audio keep-alive and back off BLE timeouts - #11547

Merged
Git-on-my-level merged 6 commits into
mainfrom
fix/ios-background-battery-keepalive
Aug 14, 2026
Merged

Git-on-my-level merged 6 commits into
mainfrom
fix/ios-background-battery-keepalive

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Aug 14, 2026 •

Copy link
Copy Markdown
Member

What changed and why

Home was starting flutter_foreground_task from location permission alone, which held AVAudioSession (green mic) all day even when nothing was capturing. Pair that with a 200ms BLE reconnect on every background connection_timeout and a 3s readRSSI "keep-alive". This stops those keep-alives, backs off background BLE timeouts, and holds audio/FGS only while capture actually has frames.

Leave issue 11307 open. Firmware AAD/store-when-unsubscribed is a separate device-side defect and is unchanged here. voip stays in Info.plist (CallKit).

Related issues

Product invariants affected

none

How it was verified

cd app && flutter test test/unit test/providers

1024 tests passed (including capture_keepalive_policy_test, capture_foreground_keepalive_sync_test, ble_reconnect_policy_test, and Bee CCCD silence retry in native_ble_transport_resync_test).

Targeted dart analyze on the policy/transport/controller files: no issues. Worktree analyze_ratchet.sh could not run (missing lib/env/dev_env.g.dart / lib/firebase_options_dev.dart).

Not exercised on a physical iPhone in this PR. On-device evidence for the bug (TestFlight 1.0.543, iPhone 15 Pro Max, Omi CV1 3.0.21): 51% battery / 16h background, backgroundServiceAction=API_START, 19/20 last disconnects connection_timeout in background, green mic held while idle.

Tests

  • app/test/unit/capture_keepalive_policy_test.dart — FGS must not start from location permission; Bee/Fieldy/Plaud audio UUIDs; phone-mic/system-audio hold for the whole session; wearable hold is frame-driven and re-acquires after silence; STT keep-alive requires audio in the last 15s
  • app/test/unit/capture_foreground_keepalive_sync_test.dart — stop during in-flight start still tears down FGS; Bluetooth audio-session deactivate is retried on failure and skipped for phone-mic
  • app/test/unit/ble_reconnect_policy_test.dart — first reconnect is immediate; .inactive counts as background; overdue delayed reconnects fire after a CoreBluetooth wake; background timeout/fail backs off 200ms → 2s → 10s → 30s → 60s; battery persist first / ≥5% / 15 min / cross 20%
  • app/test/unit/native_ble_transport_resync_test.dart — after reconnect, one CCCD resubscribe if no audio in 4s, including Bee audio UUIDs

Failure class (fixes)

Failure-Class: none

Test plan

  • Cold launch with location While Using the App and no capture: no green mic, no "Transcription service is running in the background" notification
  • Start wearable capture: FGS + audio session come up; stop capture: both go away (CallKit call in progress should not deactivate the session)
  • Background BLE timeout storm: reconnects back off (200ms → 2s → 10s → 30s → 60s), not a 200ms loop; foreground reconnect stays immediate
  • Diagnostics RSSI graph still updates only while that screen is open
  • Phone-mic recording still starts/stops FGS; in-app playback after capture still works
  • Android Dart FGS now starts from capture, not Home location permission (native Android FGS unchanged)

Git-on-my-level and others added 2 commits August 14, 2026 00:49
Home was starting flutter_foreground_task from location permission alone, which held AVAudioSession all day. Pair that with 200ms BLE reconnect on every connection_timeout. Related to #11307; firmware AAD/store path is unchanged.

Co-authored-by: Cursor <[email protected]>
The 3s readRSSI timer was a fake BLE keep-alive and a background radio cost. Sample once on GATT ready for disconnect annotation; start the timer only when the diagnostics screen subscribes.

Co-authored-by: Cursor <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

All reported issues were addressed across 12 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread app/lib/utils/audio/foreground.dart Resolved
Comment thread app/ios/Runner/AppDelegate.swift Resolved
Comment thread app/ios/Runner/Ble/OmiBleManager.swift Resolved
Comment thread app/lib/utils/audio/foreground.dart Resolved
Git-on-my-level and others added 4 commits August 14, 2026 02:23
CCCD liveness after reconnect ignored those wearables, and a talk gap
must not flap FGS under phone-mic or system-audio (including Transcribe Later).

Failure-Class: none
Co-authored-by: Cursor <[email protected]>
A stop that arrived while ensureForegroundTask was starting left the
task running. Wearable frames after a >5s silence also never re-acquired FGS.

Failure-Class: none
Co-authored-by: Cursor <[email protected]>
…bserver

Only BLE/wearable capture deactivates AVAudioSession, failed deactivates
are retried, and a retained CXCallObserver is used so a live call is not missed.

Failure-Class: none
Co-authored-by: Cursor <[email protected]>
Lock-screen .inactive was classified as foreground and skipped backoff.
Delayed reconnects now persist a deadline and fire from CoreBluetooth wake paths.

Failure-Class: none
Co-authored-by: Cursor <[email protected]>
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Pushed four follow-up commits addressing cubic's review on HEAD 92b81c2948:

  • e7826c2b92 — Bee/Fieldy/Plaud audio UUIDs for CCCD liveness; phone-mic/system-audio (including Transcribe Later) hold FGS for the whole session
  • 9495f70852 — FGS start/stop is serialized so a stop during in-flight start still tears down; wearable frames re-acquire FGS after a >5s silence; session timestamps are cleared at boundaries
  • b7c55cfcca — deactivateForBluetooth only for wearable capture, retries on failure, retained CXCallObserver
  • d13afee202 — .inactive uses background BLE backoff; overdue delayed reconnects flush from CoreBluetooth wake paths

All 12 inline review comments have replies. cd app && flutter test test/unit test/providers — 1024 passed. Targeted dart analyze on the touched Dart files: no issues.

Still intentionally out of scope: WAL copy throttling, firmware AAD / store-when-unsubscribed, removing voip from Info.plist, waking AAD from the phone, Mind Map / knowledge_graph_unavailable, Unknown journey geocode. #11307 stays open (Related:, not Fixes).

Needs human review from @mdmohsin7.

@Git-on-my-level
Git-on-my-level merged commit b5b77f5 into main Aug 14, 2026
30 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/ios-background-battery-keepalive branch August 14, 2026 06:59
mdmohsin7 added a commit that referenced this pull request Aug 14, 2026
…imeouts" (#11567)

Reverts #11547.

## What changed and why

#11547 was premised on `flutter_foreground_task` holding
`AVAudioSession` on iOS ("green mic all day"). It does not. The plugin's
iOS implementation is a BGTaskScheduler refresh task
(`com.pravera.flutter_foreground_task.refresh`, registered in
`app/ios/Runner/Info.plist`) and contains no `AVAudioSession` reference
of any kind — `grep -rin "avaudio\|audio" ios/Classes` in
`flutter_foreground_task-9.1.0` returns nothing. Background execution on
iOS comes from `UIBackgroundModes` (`audio`, `location`,
`bluetooth-central`) in Info.plist, independent of the plugin. Every
downstream decision in that PR — when to hold, when to release, the 5s
stale-audio window, the startup grace, the liveness timer — was tuned
against a mechanism that does not exist, so the policy cannot be
reviewed on its merits.

Four grounds for reverting rather than patching forward:

1. **The stated cause is contradicted by the platform sources** (above).
~700 of the 1231 added lines are control logic over a no-op on iOS.

2. **It moves against the defect it cites.** #11307 reports background
reconnect gaps from 3.9s to 7,335s and asks for prompt re-establishment
of the BLE audio path. #11547 adds escalating backoff (200ms → 2s → 10s
→ 30s → 60s) and states in its own body that #11307 stays open. The
premise behind the backoff is also a misread: iOS `central.connect` has
no timeout — it parks a pending connect at the chipset level (the
deleted comment said exactly this), so the 200ms was a delay before
parking one, not a poll interval. There was no retry storm to back off
from; the attempt rate is set by how fast CoreBluetooth reports
failures.

3. **It shipped a duplication that already drifted into a live defect.**
`app/lib/services/devices/ble_reconnect_policy.dart` declares itself the
"testable SoT" for logic that only executes in Swift, has zero
production callers, and is kept in sync by comments alone. Inside
#11547's own follow-up commits the halves diverged: the Dart audio-UUID
set gained Bee (`b189a505…`), Fieldy (`82a48422…`) and Plaud
(`00002bb0…`); `OmiBleManager.swift` `audioCharUuids` still lists three.
Since `reconnectAttempt` only resets on those three, Bee/Fieldy/Plaud
devices never clear the counter and pin at the 60s backoff cap. The
whole suite stayed green through that drift, which is the point.
`capture_keepalive_policy.dart` has the same shape at smaller scale:
`shouldStartForegroundTaskFromLocationPermission() => false` has no
production caller and its only test asserts `false` is `false`.

4. **It repurposed a service across a category boundary silently.** The
Android service being started and stopped from BLE audio frames is
`com.pravera.flutter_foreground_task.service.ForegroundService`,
declared `foregroundServiceType="location"` — the 5-minute `Geolocator`
poll feeding `_onReceiveTaskData` in `app/lib/pages/home/page.dart`.
After #11547, background location collection is gated on live capture
with frames flowing. That is a user-visible data-collection change that
appears nowhere in the PR description.

The reported symptom is also still unexplained by the merged change. The
only iOS `setActive(true)` sites are `configureForBluetooth` in
`AppDelegate.swift` (called from `voice_recorder_provider.dart:141`,
with no matching deactivate), phone-mic, CallKit, and Ray-Ban. The new
`deactivateForBluetooth` is wired only to the capture-controller release
path, which the voice recorder never enters — so a session left active
there is as stuck after #11547 as before it.

## What is worth re-landing separately

The incidental cleanups in that PR are real, live in Swift plus one
transport function, and are independently verifiable — they do not need
the Dart policy layer:

- removing the 3s `readRSSI` timer (it read a cached controller value
and never prevented a supervision timeout; the Android keep-alive in
`OmiBleManager.kt` is a different mechanism and is untouched here)
- `everConnected.insert` for state-restored peripherals
- the battery-history write throttle
- the CCCD re-subscribe after 4s of post-reconnect silence in
`native_ble_transport.dart`

Any re-land should include Bee/Fieldy/Plaud in the Swift
`audioCharUuids` set and drop the Dart mirror.

## Product invariants affected

none — no locked invariant path glob in `docs/product/invariants/`
matches the reverted files.

## How it was verified

Source-level verification of the claims above, against the merged tree
at `b5b77f5fa1`:

```
grep -rin "avaudio|audio" ~/.pub-cache/hosted/pub.dev/flutter_foreground_task-9.1.0/ios/Classes   # no matches
grep -n "foregroundServiceType" app/android/app/src/main/AndroidManifest.xml                      # pravera service = "location"
git grep -n "shouldStartForegroundTaskFromLocationPermission" -- app                              # 1 definition, 1 test, 0 callers
git grep -n "ble_reconnect_policy" -- app                                                         # 0 production callers
```

`OmiBleManager.swift` `audioCharUuids` vs `isBleAudioCharacteristicUuid`
in `capture_keepalive_policy.dart`: 3 UUIDs vs 6, confirming the drift
in ground 3.

This is a mechanical `git revert -m 1 b5b77f5`; no commit merged
after #11547 touches `app/`, so it applies without conflict and restores
the exact tree that shipped before it. Not exercised on a physical
device — the revert restores previously shipped behavior rather than
introducing new behavior. CI (`Dart Analyze & Tests`, `Android Compile
Smoke`, `Formatting`) is the gate for the restored state.

## Tests

No new tests. The revert removes the four test files added by #11547
(`ble_reconnect_policy_test.dart`, `capture_keepalive_policy_test.dart`,
`capture_foreground_keepalive_sync_test.dart`,
`native_ble_transport_resync_test.dart`) along with the code they cover.
Two of them asserted pure functions with no production callers; a
regression test for #11307 belongs with a fix that actually addresses
it, which #11547 did not claim to be.

## Failure class (fixes)

Failure-Class: none

## Follow-ups

- #11307 stays open and its cause is still unidentified — the reverted
change never addressed it.
- Stuck mic indicator: the candidate is `configureForBluetooth` with no
matching deactivate in `voice_recorder_provider.dart`, not the
foreground task.
- The 5-minute `Geolocator.getCurrentPosition()` poll restored by this
revert is worth removing on its own merit, as a one-line change with its
own evidence.
Git-on-my-level added a commit that referenced this pull request Aug 14, 2026
Stop the 3s readRSSI keep-alive (poll only while diagnostics is
subscribed), mark CoreBluetooth-restored peripherals as everConnected,
throttle battery-history writes, and retry a silent audio CCCD once
after reconnect. Audio notify UUIDs live next to the constants in
models.dart; no Dart reconnect-policy mirror.

Salvaged from #11547 as called out in #11567.

Failure-Class: none
Co-authored-by: Cursor <[email protected]>
Git-on-my-level added a commit that referenced this pull request Aug 20, 2026
…1576)

* fix(ios): salvage incidental BLE cleanups from reverted keepalive

Stop the 3s readRSSI keep-alive (poll only while diagnostics is
subscribed), mark CoreBluetooth-restored peripherals as everConnected,
throttle battery-history writes, and retry a silent audio CCCD once
after reconnect. Audio notify UUIDs live next to the constants in
models.dart; no Dart reconnect-policy mirror.

Salvaged from #11547 as called out in #11567.

Failure-Class: none
Co-authored-by: Cursor <[email protected]>

* fix: address review — restore battery throttle baseline and cancel liveness timer on disconnect

- Rehydrate lastPersistedBatteryLevel/AtMs from the newest persisted
  history entry so the first battery notification after a process
  restart is throttled against the prior persisted sample.
- Cancel _audioLivenessTimer and reset _audioSilenceResubscribes at the
  top of disconnect(), matching dispose() and _handleConnectionState(false),
  so a stale watch cannot fire into a later connection.

---------

Co-authored-by: Cursor <[email protected]>
Co-authored-by: David Zhang <[email protected]>
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.

1 participant