Skip to content

fix(devices): preserve connection and transport on launch timeout for native reconnect (#20777) - #21302

Merged
kodjima33 merged 5 commits into
BasedHardware:mainfrom
Dragonire9:fix/ble-launch-timeout-reconnect
Oct 13, 2026
Merged

kodjima33 merged 5 commits into
BasedHardware:mainfrom
Dragonire9:fix/ble-launch-timeout-reconnect

Conversation

@Dragonire9

@Dragonire9 Dragonire9 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Resolves #20777.

Problem

At app launch, DeviceService.ensureConnection makes an initial connection attempt to the saved pendant. If the pendant is out of range or powered off for 60 seconds:

  1. NativeBleTransport.connect() times out and rethrows TimeoutException.
  2. DeviceConnection.connect() wraps this in DeviceConnectionException.
  3. In DeviceService._connectToDevice, the catch block was tearing down the connection unconditionally (disconnect(), transport.dispose(), and removing from _connections).
  4. Disposing the transport calls BleBridge.instance.unregisterPeripheral(), which removes _deviceReadyCallbacks.
  5. When the user later brings the pendant in range or powers it on, native BLE reconnects and emits onDeviceReady, but finds no Dart callback. The app stays permanently disconnected and never captures audio until manual user reconnection or relaunch.

Solution

  1. DeviceConnectionException (device_connection.dart):
    • Added DeviceConnectionTimeoutException and isTimeout property to distinguish timeout errors from failed device-specific initialization.
    • Wrapped TimeoutException in DeviceConnectionTimeoutException during DeviceConnection.connect().
  2. DeviceService._connectToDevice (devices.dart):
    • Guarded the teardown path (disconnect(), transport.dispose(), and cache removal) when isTimeout is true.
    • Preserves the cached connection and registered NativeBleTransport so native background auto-reconnection persists and routes late readiness events back into Dart.
    • Non-timeout failures (such as a broken GATT link or failed device initialization) continue to tear down partial links as before.
  3. Tests:
    • Extended app/test/services/device_service_connection_failure_test.dart to verify that launch timeouts preserve the connection and transport, while initialization errors still tear down.
    • Added hermetic regression test app/test/services/devices/saved_pendant_launch_timeout_reconnect_test.dart driving real DeviceService, FriendPendantDeviceConnection, NativeBleTransport, and BleBridge with fake_async advancing the 60s timeout, proving the transport stays registered and reconnects into DeviceConnectionState.connected on subsequent onDeviceReady.

View guided diff

@Git-on-my-level

Copy link
Copy Markdown
Member

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 → BleBridge.unregisterPeripheral → late onDeviceReady finds no Dart callback) matches the code exactly, and the fix preserves the existing native auto-reconnect design rather than fighting it.

File-by-file:

  • app/lib/services/devices/connectors/device_connection.dart — DeviceConnectionTimeoutException plus the typed wrap in connect() is the right shape: timeouts from the transport are now distinguishable from failed device initialization, and the original error is retained on .error. ensureConnection's existing on DeviceConnectionException catch still swallows this cleanly, so no raw exception escapes to the WAL/capture callers.
  • app/lib/services/devices.dart — the isTimeout guard before teardown keeps the cached connection and transport registration alive while non-timeout partial-GATT failures still disconnect/dispose/remove as before. I also verified the user-initiated path: force=true on a preserved (non-recovery) connection routes through _connectToDevice → _teardownConnection, so manual reconnect still starts clean — no stale-transport deadlock.
  • app/test/services/device_service_connection_failure_test.dart — good complement to the existing teardown test: asserting disconnectCalls/disposeCalls stay 0 and that a late transport-state event restores connected covers the regression directly.
  • app/test/services/devices/saved_pendant_launch_timeout_reconnect_test.dart — nice hermetic end-to-end test; mocking the pigeon BleHostApi channels and driving BleBridge.onDeviceReady exercises the real NativeBleTransport → FriendPendantDeviceConnection path, and the tearDown cleanup of mock handlers and bridge registration is careful.

Two non-blocking notes for a follow-up:

  1. DeviceConnectionException.isTimeout falls back to cause.toLowerCase().contains('timeout'). That string match could occasionally classify a non-timeout failure (whose message happens to contain "timeout") as a timeout and keep a partial link alive. The typed DeviceConnectionTimeoutException / error is TimeoutException checks already cover the real scenarios — consider dropping the string heuristic or tightening it.
  2. cause is still a mutable field while the new error is final; making cause final would be a trivial tidy-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 (flutter test test/services/device_service_connection_failure_test.dart test/services/devices/saved_pendant_launch_timeout_reconnect_test.dart), and since this changes on-device BLE lifecycle behavior, a maintainer should confirm the out-of-range-at-launch → bring-pendant-back scenario on real hardware before merge.

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 need human response.

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution needs-maintainer-review Needs a human maintainer to sign off before merge flutter flutter work labels Oct 12, 2026
@Dragonire9

Copy link
Copy Markdown
Contributor Author

@Git-on-my-level Thank you for the detailed review and verifying both the automatic recovery and manual force=true reconnect paths!

Addressed both follow-up notes in commit 01c4b4e:

  1. Removed the loose cause.toLowerCase().contains('timeout') string heuristic from DeviceConnectionException.isTimeout so it strictly checks this is DeviceConnectionTimeoutException || error is TimeoutException.
  2. Made final String cause; immutable on DeviceConnectionException.

Ready for merge whenever convenient!

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @Dragonire9 — well-scoped fix for #20777, and the diagnosis matches the code.

What I verified against the head:

  • app/lib/services/devices/connectors/device_connection.dart — cause becoming final plus the new optional error field is safe repo-wide: the only other construction site (rayban_meta_connection.dart:112) is a positional constructor call, and devices.dart only reads e.cause. The new DeviceConnectionTimeoutException subclass and isTimeout getter cleanly classify the 60s device-ready timeout thrown by NativeBleTransport.connect() (native_ble_transport.dart:108-111) without changing behavior for other failures.
  • app/lib/services/devices.dart — the rethrow-before-teardown guard preserves the cached connection and registered transport on timeout only. That is consistent with the service's existing stance for mid-session disconnects ("native handles reconnection… don't dispose and recreate the transport"). The recovery path holds: after a timeout the transport stays registered with BleBridge, so a late native onDeviceReady flows through _handleDeviceReady → _resubscribeAfterReconnect → connected, and the retained state-changed callback still reaches subscribers. Non-timeout failures (ghost GATT link, failed init) still tear down as before, and a user-initiated force retry after a timeout still rebuilds cleanly.
  • app/test/services/device_service_connection_failure_test.dart — good pairing: the new test asserts disconnectCalls == 0 / disposeCalls == 0 / cached-connection identity and late reconnect, while the pre-existing init-failure test still pins the teardown path.
  • app/test/services/devices/saved_pendant_launch_timeout_reconnect_test.dart — hermetic end-to-end regression through the real NativeBleTransport/BleBridge with Pigeon channel mocks and fake_async (already a dev dependency); asserts unmanagedCalls == 0 after the 60s elapse and reconnection via onDeviceReady. Nice.

Two notes for maintainer sign-off:

  1. No checks have reported on this head yet, so the new tests haven't run in CI — worth confirming the mobile test suite result before merge.
  2. This is a real semantics change on the launch path, worth a conscious nod: a launch timeout now leaves a disconnected-but-registered connection cached (native keeps auto-reconnect alive in the background) until a force reconnect, forget, or service stop tears it down.

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 need human response.

@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.

Confirmed not yet fixed on main (devices.dart has no isTimeout guard). Root cause stated step-by-step, linked real bug #20777, scoped diff (205 lines), two regression tests added, no CI failures. Merging.

@kodjima33
kodjima33 merged commit ce3826d into BasedHardware:main Oct 13, 2026
@Dragonire9

Copy link
Copy Markdown
Contributor Author

Thanks for reviewing and merging! 🙏

Bounty Payout Details:

Git-on-my-level added a commit that referenced this pull request Oct 13, 2026
…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]>
Git-on-my-level added a commit to Git-on-my-level/omi that referenced this pull request Oct 13, 2026
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]>
Git-on-my-level added a commit to Git-on-my-level/omi that referenced this pull request Oct 13, 2026
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]>
Git-on-my-level added a commit to Git-on-my-level/omi that referenced this pull request Oct 14, 2026
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]>
Git-on-my-level added a commit that referenced this pull request Oct 14, 2026
…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. -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

flutter flutter work needs-maintainer-review Needs a human maintainer to sign off before merge positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A saved pendant that is out of range at launch never reconnects capture after the 60 s attempt times out

3 participants