Repository navigation
fix(devices): preserve connection and transport on launch timeout for native reconnect (#20777) - #21302
Conversation
|
Thanks for this well-scoped fix and the excellent write-up — the diagnosis of why the app stayed permanently disconnected after a launch timeout (transport disposed → File-by-file:
Two non-blocking notes for a follow-up:
One validation gap: the checks on this PR only ran a static reviewer; the Flutter test suite hasn't been executed on this head. Please make sure the two tests pass locally ( Good first contribution — leaving a positive signal; human maintainer review needed for the on-device reconnect behavior before this merges. by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
… typed timeout check (BasedHardware#20777)
|
@Git-on-my-level Thank you for the detailed review and verifying both the automatic recovery and manual Addressed both follow-up notes in commit
Ready for merge whenever convenient! |
|
Thanks @Dragonire9 — well-scoped fix for #20777, and the diagnosis matches the code. What I verified against the head:
Two notes for maintainer sign-off:
Both are judgment items rather than defects — leaving this for human maintainer review before merge. by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
|
Thanks for reviewing and merging! 🙏 Bounty Payout Details: |
…21343 follow-ups) (#21425) * fix(app): restore green Flutter tests on main (#21302 #21340 #21341 #21343 follow-ups) Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(app): measure category card text heights Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
A launch connect that times out before the pendant arrives used to dispose its transport, which unregistered the peripheral from BleBridge while native kept connecting. The late device-ready then reached nobody and the app showed Disconnected over a live link until it was killed. BasedHardware#21302 keeps the transport on timeout; this closes the footguns that made the path possible and still leave siblings open: - BleBridge.registerPeripheral returns an owner-scoped disposer, so a retired transport cannot unregister its replacement. - NativeBleTransport.disconnect releases native based on its own intent, not the mirrored state, and ignores a ready in flight after release. - DeviceService.disconnectDevice disposes the transport it drops. - NativeLinkReconciler re-adopts a link native already holds when the app resumes; native replays device-ready without touching the radio. - Transports ignore state updates after dispose. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A launch connect that times out before the pendant arrives used to dispose its transport, which unregistered the peripheral from BleBridge while native kept connecting. The late device-ready then reached nobody and the app showed Disconnected over a live link until it was killed. BasedHardware#21302 keeps the transport on timeout; this closes the footguns that made the path possible and still leave siblings open: - BleBridge.registerPeripheral returns an owner-scoped disposer, so a retired transport cannot unregister its replacement. - NativeBleTransport.disconnect releases native based on its own intent, not the mirrored state, and ignores a ready in flight after release. - DeviceService.disconnectDevice disposes the transport it drops. - NativeLinkReconciler re-adopts a link native already holds when the app resumes; native replays device-ready without touching the radio. - Transports ignore state updates after dispose. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A launch connect that times out before the pendant arrives used to dispose its transport, which unregistered the peripheral from BleBridge while native kept connecting. The late device-ready then reached nobody and the app showed Disconnected over a live link until it was killed. BasedHardware#21302 keeps the transport on timeout; this closes the footguns that made the path possible and still leave siblings open: - BleBridge.registerPeripheral returns an owner-scoped disposer, so a retired transport cannot unregister its replacement. - NativeBleTransport.disconnect releases native based on its own intent, not the mirrored state, and ignores a ready in flight after release. - DeviceService.disconnectDevice disposes the transport it drops. - NativeLinkReconciler re-adopts a link native already holds when the app resumes; native replays device-ready without touching the radio. - Transports ignore state updates after dispose. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…21430) ## Summary Closes the ways the app can show a pendant as Disconnected while native BLE holds a live, ready link. In that state, a pendant that is visibly connected in iOS Settings (blue light) never streams audio until the app is killed. **Root cause (observed on a real iPhone, prod 1.0.563+1377).** The app opened at 22:42:30 and sent one `connect` request at 22:42:34. Dart's launch connect gave up at its 60s deadline. The pendant arrived at 22:43:54, 80s after the request, and native finished service discovery at 22:43:56. After that the app process sent zero GATT reads, writes, or notify subscriptions until it was restarted. The only traffic was the native 10s RSSI poll, which runs only while `peripheral.state == .connected`. This is the pre-#21302 path: the timeout tore the connection down and disposed its transport. That dispose unregistered the peripheral from `BleBridge`, but `NativeBleTransport.disconnect()` returned early because Dart's mirror already said disconnected, so it never sent `unmanageDevice`. Native kept connecting and delivered device-ready to nobody. #21302 (merged 2026-10-13 14:45 UTC) keeps the transport on timeout. A new provider-level test reproduces the report: it fails on `ce3826d2fd^` and passes on main. This PR removes the footguns that made that path possible and still leave sibling paths open on main: 1. **Owned bridge registration.** `BleBridge.registerPeripheral` now returns a disposer that unregisters only while the caller still owns the peripheral. Before, unregistration was by id alone, so a retired transport disposed after its replacement registered would silence the replacement's device-ready. 2. **Disconnect releases native based on intent, not the mirror.** `NativeBleTransport.disconnect()` now calls `unmanageDevice` unless this transport already released native. Before, it skipped the call whenever Dart's mirrored state said disconnected, even though native keeps connecting after a Dart-side timeout. A device-ready already in flight after release is ignored, so it cannot re-adopt the link behind an explicit disconnect. 3. **`DeviceService.disconnectDevice` disposes the transport it drops**, matching `_teardownConnection`. Before, the dropped transport stayed registered and could swallow the next device-ready: tap Disconnect while native is reconnecting, native reconnects, and the ready lands on an orphan whose connection no longer listens. 4. **Foreground reconcile.** A new `NativeLinkReconciler`, bound in `main.dart`, runs on app resume. If the provider shows the paired device disconnected but native reports its peripheral connected, it re-checks that the same id is still paired and still disconnected after the async probe. It then calls `DeviceService.ensureConnection(id, force: true)` for exactly that id and publishes the result through `DeviceProvider.onDeviceConnectionStateChanged`, the entry point native events use. That covers both a missing transport and a `DeviceService` connection the provider never heard about. Native answers `manageDevice` for a connected peripheral by replaying device-ready (iOS `replayReady` / `hydrateReady`, Android `adoptConnectedDevice`), so this does not touch the radio and never starts a physical connect. It covers any future lost-ready path, not one cause. Also: - If `unmanageDevice` fails, the transport stays unreleased, so the release can be retried and native readies are still adopted. - Every transport's `_updateState` ignores events after `dispose()` instead of throwing on a closed controller. - `DeviceProvider._handleDeviceConnected` admits each physical connect once, keyed on `(connection, connectionEpoch)` and cleared whenever the mirror disconnects. Overlapping connected events (a native connect still initializing plus a resume reconcile) no longer run capture start, battery listeners or WAL attach twice. Line-Count-Exception: app/lib/providers/device_provider.dart | 1488 -> 1576 | the per-connect admission guard and the readoption pairing constraint (armed admission, gated persists and setup continuation) live in the provider's own connect entry point; the reconcile logic itself is split into native_link_reconciler.dart UI-Evidence: none -- no visible UI change; main.dart only binds the device provider app-lifecycle listener ## Verification - `flutter test test/providers/device_provider_late_ready_test.dart`: 14 tests. Each invariant was mutation-checked: reverting any one of the ten fixes (owner-scoped bridge release, intent-based disconnect, the ready guard after release, dispose in `disconnectDevice`, the reconcile native probe, the held-link republish, the reconcile id re-check, retryable failed release, the per-connect admission guard, and the admission reset on any mirror disconnect) fails exactly its test. The late-ready provider test also fails on `ce3826d2fd^`. - Independent review: codex `gpt-6.1-sol` via agentctl (read-only brief). Five rounds via `agentctl continue` on one session, each re-reviewing the delta. Rounds 1–4 found eight P2 defects in earlier revisions, all fixed and pinned by tests above: the reconcile didn't republish a link `DeviceService` already held; the probed id could differ from the connected id; a failed release was recorded as released; synthetic publishes across awaits (double admission, overriding a real disconnect, publishing a re-paired device); overlapping admissions for one physical connect; and an admission latch surviving provider-only disconnects. Round 5: "Nothing blocks merge in this delta." - `bash app/test.sh` (full hermetic suite + spine) with Flutter 3.44.5 on macOS: spine 138/138; suite 5,500 passed, 21 skipped, 4 failed. The four failures (`apps_category_section_large_text_test` ×2, `ai_app_generator_large_text_test`, `settings_search_header_stability_test`) fail identically on unmodified `origin/main` and are fixed by the open #21425. That PR also fixes `device_service_connection_failure_test`, which this PR leaves alone to avoid a conflict. - Changed-file `flutter analyze`: no new issues (two pre-existing infos). Not verified on device: the resume reconcile has not been exercised on a physical phone. The incident evidence (bluetoothd/runningboard logs) comes from the reporting iPhone. ## Product invariants affected - INV-DATA-1 — production data-plane routing is unchanged; only the device provider's construction in `main.dart` changes. ## Failure class Failure-Class: FC-superseded-connection-mutates-live-session 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/21430?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
Summary
Resolves #20777.
Problem
At app launch,
DeviceService.ensureConnectionmakes an initial connection attempt to the saved pendant. If the pendant is out of range or powered off for 60 seconds:NativeBleTransport.connect()times out and rethrowsTimeoutException.DeviceConnection.connect()wraps this inDeviceConnectionException.DeviceService._connectToDevice, the catch block was tearing down the connection unconditionally (disconnect(),transport.dispose(), and removing from_connections).BleBridge.instance.unregisterPeripheral(), which removes_deviceReadyCallbacks.onDeviceReady, but finds no Dart callback. The app stays permanently disconnected and never captures audio until manual user reconnection or relaunch.Solution
DeviceConnectionException(device_connection.dart):DeviceConnectionTimeoutExceptionandisTimeoutproperty to distinguish timeout errors from failed device-specific initialization.TimeoutExceptioninDeviceConnectionTimeoutExceptionduringDeviceConnection.connect().DeviceService._connectToDevice(devices.dart):disconnect(),transport.dispose(), and cache removal) whenisTimeoutis true.NativeBleTransportso native background auto-reconnection persists and routes late readiness events back into Dart.app/test/services/device_service_connection_failure_test.dartto verify that launch timeouts preserve the connection and transport, while initialization errors still tear down.app/test/services/devices/saved_pendant_launch_timeout_reconnect_test.dartdriving realDeviceService,FriendPendantDeviceConnection,NativeBleTransport, andBleBridgewithfake_asyncadvancing the 60s timeout, proving the transport stays registered and reconnects intoDeviceConnectionState.connectedon subsequentonDeviceReady.