Skip to content

fix(ble): restore audio after Limitless pendant reconnect on iOS - #7725

Merged
kodjima33 merged 1 commit into
BasedHardware:mainfrom
formed2forge:fix/limitless-ble-reconnect
Jun 9, 2026
Merged

kodjima33 merged 1 commit into
BasedHardware:mainfrom
formed2forge:fix/limitless-ble-reconnect

Conversation

@formed2forge

@formed2forge formed2forge commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes a silent-audio bug where the Limitless pendant appeared connected after a BLE drop/reconnect but produced no transcription. Two independent root causes, both in the native BLE reconnect path.

Bug 1 — _activeSubscriptionKeys wiped by iOS double-fire (NativeBleTransport)

iOS CoreBluetooth fires both didDisconnectPeripheral and didFailToConnect for the same drop event (e.g. encryption timeout on retry). Both callbacks invoke _handleConnectionState(false), so it fires twice on the same transport instance.

  • First call: saves {audio_char, battery_char} into _activeSubscriptionKeys, then calls _closeAllStreams() → _streamControllers is now empty.
  • Second call: finds _streamControllers empty → clears _activeSubscriptionKeys and adds {} → subscription set wiped.

Result: _resubscribeAfterReconnect() had no keys to iterate. The battery characteristic (00002a19) re-subscribed anyway because iOS automatically re-enables CCCD for standard bonded characteristics — but the vendor audio characteristic (632de003) did not. isNotifying was never set to true for it.

Fix: guard the update with if (_streamControllers.isNotEmpty) so the second fire is a no-op.

Bug 2 — _rxSubscription left dead after reconnect (LimitlessDeviceConnection)

connect() wired _rxSubscription to the BLE characteristic's StreamController.broadcast(). On disconnect, _closeAllStreams() closes that controller, which automatically cancels all listeners including _rxSubscription. After the native auto-reconnect, _resubscribeAfterReconnect() created a new stream controller — but _rxSubscription still referenced the old closed one. Audio data was emitted into a void; _audioController received nothing.

Fix: listen to transport.connectionStateStream after initial connect and re-attach _rxSubscription (via _attachRxSubscription()) synchronously on every subsequent connected event, then re-send the enable-data-stream command to the pendant.

Secondary effect

By recovering real-time streaming on reconnect rather than accumulating offline recordings, this reduces the offline backlog size that gets synced on the next hard reconnect — which should ease the batch-request pressure that contributes to 429s downstream.

Test plan

  • Walk-away test (clean reconnect): didDisconnect → didConnect → isNotifying=true for 632de003 ✓
  • Edge-of-range test triggering double-fire: didDisconnect → didFailToConnect (Failed to encrypt the connection) → didConnect → isNotifying=true for 632de003 ✓
  • Audio transcription resumes after reconnect in both cases
  • Same walk-away test on Omi/Friend pendant (also uses NativeBleTransport)

Related issues

Closes #7324
Related: #6610, #6721

🤖 Generated with Claude Code

@formed2forge
formed2forge force-pushed the fix/limitless-ble-reconnect branch from 4cb7f3c to b56425d Compare June 9, 2026 17:34
@greptile-apps

greptile-apps Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes two independent root causes of silent audio after a Limitless pendant BLE drop/reconnect on iOS: an iOS CoreBluetooth double-fire that wiped the re-subscription key set, and a stale _rxSubscription that pointed at a closed stream controller after native auto-reconnect.

  • native_ble_transport.dart: Guards _activeSubscriptionKeys update with _streamControllers.isNotEmpty, making the second _handleConnectionState(false) call a no-op so the audio characteristic key survives into _resubscribeAfterReconnect.
  • limitless_connection.dart: Introduces _transportReconnectSubscription that fires on every DeviceTransportState.connected event and calls _attachRxSubscription() to re-wire _rxSubscription to the fresh stream controller, followed by re-sending the enable-data-stream command to the pendant.

Confidence Score: 4/5

The BLE transport and connection logic changes are sound; the only blocker is an accidental personal gitignore pattern that should not be committed to the shared repository.

Both dart-side fixes are logically correct and well-scoped. The _streamControllers.isNotEmpty guard in the transport is a minimal, safe change. The reconnect listener in LimitlessDeviceConnection correctly re-attaches _rxSubscription to the new stream controller before re-sending the enable command. The .gitignore commit includes a personal *_TSELEM* pattern under a 'Personal/local files' comment — this does not belong in a shared repository file and should be removed.

.gitignore — contains a personal glob pattern that should be removed before merging.

Important Files Changed

Filename Overview
.gitignore Adds ONBOARDING.md and a personal glob pattern *_TSELEM* to the project-level .gitignore; the personal pattern should live in the global gitignore instead.
app/lib/services/devices/limitless_connection.dart Adds reconnect listener and _attachRxSubscription helper to re-wire the dead _rxSubscription after native auto-reconnect; the reinitialization helper omits the time-sync step that _initialize performs.
app/lib/services/devices/transports/native_ble_transport.dart Guards _activeSubscriptionKeys update with _streamControllers.isNotEmpty to prevent iOS CoreBluetooth double-fire from wiping the re-subscription set; fix is minimal and correct.

Sequence Diagram

sequenceDiagram
    participant iOS as iOS CoreBluetooth
    participant NBT as NativeBleTransport
    participant LDC as LimitlessDeviceConnection

    Note over iOS,LDC: Normal reconnect (single fire)
    iOS->>NBT: didDisconnectPeripheral
    NBT->>NBT: _handleConnectionState(false) — save keys, closeAllStreams
    iOS->>NBT: didDeviceReady(services)
    NBT->>NBT: _resubscribeAfterReconnect() — recreate SCs, re-subscribe audio char
    NBT->>LDC: connectionStateStream: connected
    LDC->>LDC: _attachRxSubscription() — re-wires _rxSubscription to new SC
    LDC->>NBT: writeCharacteristic(enableDataStream)
    Note over LDC: Audio flows again

    Note over iOS,LDC: Double-fire (encryption timeout)
    iOS->>NBT: didDisconnectPeripheral
    NBT->>NBT: _handleConnectionState(false) — save keys, closeAllStreams
    iOS->>NBT: didFailToConnect
    NBT->>NBT: _handleConnectionState(false) — streamControllers EMPTY, guard skips, keys preserved
    iOS->>NBT: didDeviceReady(services)
    NBT->>NBT: _resubscribeAfterReconnect() — audio char re-subscribed via saved keys
    NBT->>LDC: connectionStateStream: connected
    LDC->>LDC: _attachRxSubscription()
    LDC->>NBT: writeCharacteristic(enableDataStream)
    Note over LDC: Audio flows again
Loading

Reviews (1): Last reviewed commit: "fix(ble): restore audio after Limitless ..." | Re-trigger Greptile

Comment thread .gitignore Resolved
Comment on lines +99 to +107
Future<void> _reinitializeAfterReconnect() async {
try {
final dataStreamCmd = _encodeEnableDataStream();
await transport.writeCharacteristic(limitlessServiceUuid, limitlessTxCharUuid, dataStreamCmd);
DebugLogManager.logInfo('Limitless device re-initialized after reconnect');
} catch (e) {
Logger.debug('Limitless: Re-initialization after reconnect failed: $e');
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 _reinitializeAfterReconnect only sends the enable-data-stream command, but _initialize also sends a time-sync command first. After an auto-reconnect the device's clock is never refreshed, which will cause all audio timestamps to be anchored to the pre-disconnect time. If there are session-boundary markers that rely on accurate timestamps (e.g. did_start_session, did_start_recording) the resulting session data will carry wrong time values.

Suggested change
Future<void> _reinitializeAfterReconnect() async {
try {
final dataStreamCmd = _encodeEnableDataStream();
await transport.writeCharacteristic(limitlessServiceUuid, limitlessTxCharUuid, dataStreamCmd);
DebugLogManager.logInfo('Limitless device re-initialized after reconnect');
} catch (e) {
Logger.debug('Limitless: Re-initialization after reconnect failed: $e');
}
}
Future<void> _reinitializeAfterReconnect() async {
try {
final timeSyncCmd = _encodeSetCurrentTime(DateTime.now().millisecondsSinceEpoch);
await transport.writeCharacteristic(limitlessServiceUuid, limitlessTxCharUuid, timeSyncCmd);
final dataStreamCmd = _encodeEnableDataStream();
await transport.writeCharacteristic(limitlessServiceUuid, limitlessTxCharUuid, dataStreamCmd);
DebugLogManager.logInfo('Limitless device re-initialized after reconnect');
} catch (e) {
Logger.debug('Limitless: Re-initialization after reconnect failed: $e');
}
}

Comment on lines +58 to +60
_transportReconnectSubscription = transport.connectionStateStream
.where((s) => s == DeviceTransportState.connected)
.listen((_) => _handleTransportReconnected());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 The listener callback discards the Future<void> returned by _handleTransportReconnected. Any async exception that escapes after the first await will be silently lost as an unhandled future error. Explicitly marking the discarded future with unawaited (from dart:async) communicates intent and avoids the linter warning.

Suggested change
_transportReconnectSubscription = transport.connectionStateStream
.where((s) => s == DeviceTransportState.connected)
.listen((_) => _handleTransportReconnected());
_transportReconnectSubscription = transport.connectionStateStream
.where((s) => s == DeviceTransportState.connected)
.listen((_) => unawaited(_handleTransportReconnected()));

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Two bugs caused the pendant to appear connected but stay silent after a
native BLE auto-reconnect:

1. NativeBleTransport: iOS fires both didDisconnectPeripheral and
   didFailToConnect for the same drop event (e.g. encryption timeout),
   causing _handleConnectionState(false) to fire twice. The second call
   found _streamControllers already empty and wiped _activeSubscriptionKeys
   to {}, so _resubscribeAfterReconnect had no characteristics to re-subscribe.
   Fixed by guarding the update with if (_streamControllers.isNotEmpty).

2. LimitlessDeviceConnection: _rxSubscription (the Dart listener feeding
   _audioController) was killed when _closeAllStreams() closed its backing
   StreamController. After reconnect, new stream controllers were created
   but no listener was re-attached — audio data was emitted into a void.
   Fixed by adding a _transportReconnectSubscription that fires on every
   transport connected event, re-attaches _rxSubscription via
   _attachRxSubscription(), and sends the enable-data-stream command.

Verified on hardware: didDisconnect + didFailToConnect double-fire followed
by successful reconnect with isNotifying=true for both 632de003 (audio) and
00002a19 (battery).

Closes BasedHardware#7324
Related: BasedHardware#6610, BasedHardware#6721

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@formed2forge
formed2forge force-pushed the fix/limitless-ble-reconnect branch from b56425d to e909f21 Compare June 9, 2026 17:37

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

Mobile/iOS BLE bug fix (restore audio after Limitless pendant reconnect). Approve only per policy — mobile area, Nik reviews merges.

@kodjima33
kodjima33 merged commit 9b2d485 into BasedHardware:main Jun 9, 2026
formed2forge added a commit to formed2forge/omi that referenced this pull request Jun 12, 2026
When the Limitless pendant is recording and the server WebSocket drops
(network gone, BLE stays up), the device stops emitting BLE audio after
its internal timeout.  The app's keep-alive timer reconnects the socket
but never re-sends the enable-data-stream command, so no audio flows to
the new socket.  The UI stays on deviceRecord giving no hint, and the
only recovery is force-closing the app or disconnecting BT.

This is the network-side counterpart of the BT reconnect fix (BasedHardware#7725).
That fix added _handleTransportReconnected() which re-sends the command
after a BLE drop.  We apply the same treatment for network-only drops.

Add onNetworkSocketReconnected() as a no-op virtual hook on DeviceConnection.
LimitlessDeviceConnection overrides it to call _reinitializeAfterReconnect()
(re-sends enable-data-stream, same as the BT path).

In CaptureProvider, _socketReconnectPending is set in onClosed() when
the socket drops during deviceRecord state, and consumed in
_initiateWebsocket() after a successful reconnect — guarded by
recordingState == deviceRecord so it is skipped when the user has paused
(no point waking the device when _bleBytesStream is cancelled).
_cleanupCurrentState() clears the flag on explicit stop so it does not
carry over into the next session.

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
kodjima33 pushed a commit that referenced this pull request Jun 16, 2026
)

* fix(ble): resume Limitless recording after network-only reconnect

When the Limitless pendant is recording and the server WebSocket drops
(network gone, BLE stays up), the device stops emitting BLE audio after
its internal timeout.  The app's keep-alive timer reconnects the socket
but never re-sends the enable-data-stream command, so no audio flows to
the new socket.  The UI stays on deviceRecord giving no hint, and the
only recovery is force-closing the app or disconnecting BT.

This is the network-side counterpart of the BT reconnect fix (#7725).
That fix added _handleTransportReconnected() which re-sends the command
after a BLE drop.  We apply the same treatment for network-only drops.

Add onNetworkSocketReconnected() as a no-op virtual hook on DeviceConnection.
LimitlessDeviceConnection overrides it to call _reinitializeAfterReconnect()
(re-sends enable-data-stream, same as the BT path).

In CaptureProvider, _socketReconnectPending is set in onClosed() when
the socket drops during deviceRecord state, and consumed in
_initiateWebsocket() after a successful reconnect — guarded by
recordingState == deviceRecord so it is skipped when the user has paused
(no point waking the device when _bleBytesStream is cancelled).
_cleanupCurrentState() clears the flag on explicit stop so it does not
carry over into the next session.

Co-authored-by: Claude Sonnet 4.6 <[email protected]>

* style: dart format with Flutter 3.44.2 to match CI

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
@cursor
cursor Bot deleted the fix/limitless-ble-reconnect branch September 2, 2026 02:34
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.

Limitless pendant: connects but won't transcribe anything

2 participants