Skip to content

fix(ios): serialize BLE recovery and reclaim CV1 after DFU - #10573

Closed
axAilotl wants to merge 6 commits into
BasedHardware:mainfrom
axAilotl:codex/ios-ble-dfu-reliability
Closed

axAilotl wants to merge 6 commits into
BasedHardware:mainfrom
axAilotl:codex/ios-ble-dfu-reliability

Conversation

@axAilotl

@axAilotl axAilotl commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • serialize CoreBluetooth GATT work and reject stale completions from previous sessions
  • coalesce notification transitions and route high-rate Omi audio / Limitless flash data through native handlers
  • remove RSSI polling as a keepalive while preserving diagnostics-on-demand
  • make DFU handoff idempotent and reconnect the exact suspended pendant on every terminal path
  • retain the post-DFU reconnect lease across transient nulls and exceptions, retrying with capped backoff until ownership is reclaimed or the device is forgotten
  • treat restored peripherals as reconnect-eligible and reissue the first unexpected-disconnect connection request synchronously

Root cause

The old iOS path could overlap discovery, subscription, writes, and reconnect work. High-rate notifications crossed avoidable Dart/UserDefaults routing, and DFU relinquished BLE ownership without a guaranteed exact-device reclaim.

Three reconnect gaps were present:

  1. a CoreBluetooth-restored peripheral was not eligible for the foreground/powered-on reconnect sweep until a fresh didConnect;
  2. the first unexpected-disconnect retry waited 500 ms on the app queue, which iOS can suspend before the work item runs;
  3. the Dart DFU handoff cleared its only suspended-device lease after a transient forced reconnect returned null or threw, so later terminal callbacks became no-ops.

The reconnect policy registers a system-owned pending connect synchronously after an ordinary unexpected link drop. Actual failed connection attempts still use bounded exponential backoff. The Dart DFU handoff now keeps one coalesced reclaim operation alive with capped backoff until ensureConnection returns ownership; explicitly forgetting the device deliberately abandons the lease.

Physical validation

Validated on an iPhone 12 Pro Max running iOS 26.5 and one CV1:

  • full dual-core CV1 OTA completed from iOS in about 13 seconds; the exact UUID was reclaimed without re-pairing
  • foreground reconnect restored usable audio in about 3 seconds
  • Bluetooth-off audio recovered into contiguous immutable ranges 961737..962057..962058
  • the recovered files contained 1,335 structurally valid Opus frames / 26.70 seconds with no source-sequence gap or overlap
  • pendant storage advanced from 187 KB to 0 B only after the local WAL manifest and files were durable
  • live audio resumed after recovery; markers Jade 572 (background) and Pearl 641 (final candidate) appeared in transcription
  • app reinstall preserved auth and all 731 existing WAL records

iOS 26 hard-toggle boundary

A Settings Bluetooth power toggle is not equivalent to an ordinary RF/link drop. One background cycle reconnected in 2 seconds, but a repeat with Omi already suspended remained disconnected for 34 seconds until Omi was foregrounded. Foregrounding then recovered immediately, drained the durable backlog, and resumed live audio.

Apple documents that iOS 26 restoration after user Bluetooth toggles is conditional and that Settings power toggles may not relaunch an app. This PR therefore improves the app-controlled reconnect paths without claiming that it can override that OS policy. The firmware/app durability boundary preserves the missing interval for later backfill.

Validation

  • flutter test --no-pub test/providers/device_provider_test.dart — 18 passed, including null/throw-then-success, concurrent terminal callback coalescing, capped-backoff continuation, and explicit forget cancellation
  • bash app/ios/test/run_ble_gatt_scheduler_tests.sh — passed
  • make preflight / pre-push manifest — 64 selected checks passed
  • Flutter generated-output hook deliberately skipped with PRE_PUSH_SKIP_FLUTTER_GENERATED=1: the shared Flutter installation reported SDK version 0.0.0-unknown; full Flutter analyzer/tests and platform compiles remain CI-authoritative

Failure-Class: none

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @axAilotl — this is a well-structured reliability pass. The serialized GATT scheduler (session-bound tokens, stale-callback rejection, read-while-notifying admission), notification-state coalescing, native notification routing, and the idempotent DFU connection handoff all address real races in the iOS BLE stack. The test coverage (scheduler/router/project-graph suites + the Dart DFU handoff and device-provider tests) and the new ios-ble-gatt-operation-scheduler manifest check are exactly the kind of guard surface that makes a change like this reviewable. Documenting the physical CV1/iOS 26.5.2 validation in the PR body is appreciated.

A few points worth a human maintainer's eyes before this leaves draft:

  • RSSI keep-alive removal. The old path polled readRSSI() every 3 s unconditionally on deviceReady; the new path only polls while the diagnostics view is streaming. The rationale (controller-owned supervision, not an app keep-alive) is technically sound, but this is a behavior change with device/firmware-specific implications. Worth confirming across the supported pendant variants that no firmware relies on host-side traffic to avoid supervision timeouts, especially in background/restoration.
  • Notification-state mismatch handling. When setNotifyValue returns success but isNotifying doesn't match the requested state (ignoreMismatchedState), the operation is left for the scheduler timeout rather than invalidated. That's defensible, but a maintainer should confirm the 10 s fatal-timeout → disconnect on a benign state mismatch is the desired recovery vs. a softer path.
  • DFU suspend/resume state machine. The _dfuSuspendedDeviceId / _dfuSuspendFuture / _dfuResumeFuture triple in DeviceService correctly captures the device id before disconnect and reclaims the exact device on any terminal outcome. The single-device assumption (throwing StateError if a different device suspends mid-DFU) is fine for current product scope; just flagging it as a seam to revisit if multi-device DFU ever lands.
  • Diff churn in OmiBleManager.swift. A large share of the ~600 net-new lines is 4-space→2-space reformatting alongside the real logic. Not asking for a split — the work is cohesive around one subsystem — but when it leaves draft, a whitespace-ignoring review pass (git diff -w) helps confirm no behavior is hidden in the reflow.

Marking for human maintainer review given the core reliability surfaces (BLE session/reconnect lifecycle, DFU ownership transfer) and the draft state. Not formally approving.

Posted by the Omi PR maintainer monitor (GLM-5.2).


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added needs-maintainer-review Needs a human maintainer to sign off before merge ios ble labels Jul 25, 2026
@axAilotl
axAilotl force-pushed the codex/ios-ble-dfu-reliability branch 3 times, most recently from 8c1321a to fc6d75c Compare July 26, 2026 03:56
Alex Vega added 5 commits July 26, 2026 00:05
Route Omi audio batches and Limitless flash data through native handlers while leaving storage and control notifications on Dart. Add deterministic router coverage and DEBUG-only aggregate BLE throughput diagnostics.

Physical iPhone testing validated sustained backlog drain, Bluetooth off/on recovery, app relaunch recovery, and automatic reconnection after CV1 OTA.

Failure-Class: none
Validate MCUboot images before disconnecting, serialize the updater-to-app handoff, and force-reconnect the exact suspended device after every success, failure, cancellation, or disposal path. Legacy DFU now validates local input before relinquishing BLE ownership.

Validated on an iPhone 13 Pro Max with a full CV1 MCUboot reflash: the app reclaimed the pendant automatically and resumed the exact durable sequence with no re-pair or hot restart.

Failure-Class: none
Treat restored CoreBluetooth peripherals as reconnect-eligible and reissue the first unexpected-disconnect connection request synchronously so iOS can own it before suspending the app. Keep bounded backoff for actual connection failures.

Test: bash app/ios/test/run_ble_gatt_scheduler_tests.sh

Physical-Test: iPhone 12 Pro Max + CV1; foreground recovery resumed Listening and live marker Pearl 641, and a 26.7s offline range drained as contiguous ring WALs before device storage advanced to zero.

Failure-Class: none
@axAilotl
axAilotl force-pushed the codex/ios-ble-dfu-reliability branch from fc6d75c to 3f9dc74 Compare July 26, 2026 04:07
Retry transient post-DFU reconnect failures with capped backoff, coalesce terminal callbacks, and release the lease only after ownership is reclaimed or the device is forgotten.

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

axAilotl commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Build 110 composite physical evidence (2026-08-04)

The session-bound iOS GATT changes in this PR were included in the exact composite dev IPA exercised on a physical iPhone/CV1.

  • Cold app launch + pendant power-cycle recovered automatically.
  • A controlled marker appeared in live preview without tapping Listening.
  • Manual SD backlog drain remained active while a second marker appeared and storage decreased.
  • No freeze/disconnect was observed in the controlled interval.
  • Native verification passed:
    • bash app/ios/test/run_ble_gatt_scheduler_tests.sh
    • bash app/ios/test/run_ble_legacy_audio_ownership_tests.sh
    • ruby app/ios/test/ble_gatt_project_graph_test.rb (6 runs, 52 assertions)

Timing caveat: “+5 s” was marker-end to screenshot, not cold-launch-to-first-text latency, and is not being claimed as a cold-start SLO. The composite integration is preserved on fork branch codex/ios-build110-qualification at 8f0f7e0774; app-side evidence is in #10656 at 90927b4562.

@undivisible undivisible added human Human-authored pull request app flutter flutter work mobile workflow-review Needs maintainer review for workflow, automation, hooks, or CI behavior privacy-review Touches user-data persistence, permissions, or privacy-sensitive surfaces labels Aug 10, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Reviewed the iOS BLE serialization and DFU reconnect rework (glm-5.2 automated review). The design is coherent and well-tested; leaving detailed observations for the maintainer.

Strengths

  • BleGattOperationScheduler is a clean serialization primitive: one operation in flight per peripheral, bound to a connection session via sessionId, with completeExpected/failExpectedAndInvalidate rejecting callbacks from the wrong session/kind/characteristic. The 683-line test file covers serialization, stale-session rejection, timeout (fatal and non-fatal RSSI), and session replacement.
  • BleGattReadAdmission rejecting reads on notifying characteristics correctly addresses the CoreBluetooth ambiguity where didUpdateValueFor cannot distinguish a read response from a notification.
  • BleNotificationRouter routing by fixed service/characteristic UUID identity before consulting UserDefaults-backed capture policy is a meaningful hot-path improvement for high-rate ring-sync traffic.
  • The Dart FirmwareDfuConnectionHandoff idempotency (_finishFuture coalescing) and the DeviceService backoff-with-reclaim loop correctly address the transient null/throw lease-loss bug described in the root cause.
  • Removing RSSI polling as a keepalive while preserving diagnostics-on-demand is the right call given connection supervision is controller-owned.

Observations for maintainer attention

  1. BleReconnectDispatchPolicy, BleReconnectLifecycle, and BleReconnectEligibility are referenced in OmiBleManager.swift but I could not locate their definitions in any committed .swift file in this PR diff. Desktop Swift Build & Tests CI passed, so they likely resolve in-repo — worth confirming they are committed and not an unresolved symbol.

  2. requestPersistentReconnect calls centralManager.connect synchronously inside didDisconnectPeripheral. This is the intended fix (avoiding the 500ms dispatch delay that iOS can suspend), but it means every unexpected disconnect now issues a connect on the main queue before the delegate returns. Worth verifying this does not interact adversely with rapid disconnect/reconnect cycles under RF congestion.

  3. In DeviceService._resumeConnectionAfterDfu, the reconnect loop polls ensureConnection(deviceId, force: true) with backoff [0, 250ms, 1s, 2s, 4s]. After exhausting the list, it continues retrying at 4s indefinitely until _dfuSuspendedDeviceId changes. This is intentional (reclaim until success or forget), but there is no maximum attempt cap — if the device is physically gone, only forgetDevice stops the loop. The test covers explicit-forget cancellation, which is good.

  4. peripheralIsReady(toSendWriteWithoutResponse:) completes the pending write token directly via complete(token:result:). If the scheduler session was invalidated between enqueue and this callback, the activeToken == pending.token guard will fail and the write is silently dropped — correct for a stale session, just flagging it.

Verification status: All CI checks green (Desktop Swift Build & Tests, Dart Analyze & Tests, Desktop Swift Static & Test Contracts, Formatting, Hygiene). Could not build/test locally — the worktree fetch failed (non-fast-forward on the PR head ref). Static review only.

This needs maintainer sign-off on the reconnect policy and notification routing changes before merge.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

Git-on-my-level added a commit that referenced this pull request Aug 14, 2026
…11547)

## 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

- Related: #11307 — iOS background BLE `connection_timeout` leaves live
transcription unavailable
- Relates to #5491 — idle/background battery drain from BLE scan +
keep-alives
- Relates to #6570 — GATT connected but app not consuming audio
- Relates to #6610 (closed) — iOS background BLE reconnect stall;
remaining gap is #11307
- Overlaps draft PR #10573 — serialize iOS BLE recovery / drop RSSI
keepalive (this PR takes the idea plus backoff; not a wholesale merge)

## 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)
@axAilotl

Copy link
Copy Markdown
Contributor Author

Closing this experimental CV1/storage-first branch. The only firmware reliability change being carried forward is #11578; this PR is not part of that release candidate.

@axAilotl axAilotl closed this Aug 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Hey @axAilotl 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app ble flutter flutter work human Human-authored pull request ios mobile needs-maintainer-review Needs a human maintainer to sign off before merge privacy-review Touches user-data persistence, permissions, or privacy-sensitive surfaces 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.

3 participants