Skip to content

fix(app): preserve on-device offline batch across BLE disconnect (#7194) - #11084

Merged
kodjima33 merged 5 commits into
BasedHardware:mainfrom
aryanorastar:fix/7194-offline-batch-continue-device-record
Aug 4, 2026
Merged

kodjima33 merged 5 commits into
BasedHardware:mainfrom
aryanorastar:fix/7194-offline-batch-continue-device-record

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

When a supported wearable is doing its own on-device offline/batch recording and BLE disconnects, the app should not interrupt that path by starting the phone-mic batch fallback.

This PR prevents the phone-mic fallback from triggering when an on-device offline batch recording is already active (fixes #7194).

Implementation

  • app/lib/utils/batch_recording.dart: extended shouldFallbackToPhoneOnDeviceDisconnect with isOnDeviceOfflineBatchActive.
  • app/lib/services/capture/capture_controller.dart: computes isOnDeviceOfflineBatchActive from batchModeEnabled plus the current device/offline session state, and passes it into the predicate.
  • app/test/unit/batch_recording_phone_test.dart: added unit coverage for the new gating.

Tests

  • flutter test test/unit/batch_recording_phone_test.dart

Product invariants affected

none

Failure class (fixes)

Failure-Class: none

@aryanorastar
aryanorastar requested a review from mdmohsin7 as a code owner August 4, 2026 09:20
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

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

2 issues found across 4 files

Confidence score: 3/5

  • In app/lib/providers/device_provider.dart, disconnect cleanup can abort if onRecordingDeviceDisconnected() throws, which risks leaving recording, WAL, and analytics state out of sync after a device drop; catch/log that call locally so the remaining teardown steps still run.
  • In app/lib/services/capture/capture_controller.dart (streamDeviceRecording), reconnect teardown waits on _phoneMicBatchStopCompleter tied to a shared native onStop callback, so another batch-stop path can interfere and stall or mis-sequence reconnect cleanup; isolate completer ownership per stop operation (or scope callbacks) to avoid cross-path coupling.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="app/lib/providers/device_provider.dart">

<violation number="1" location="app/lib/providers/device_provider.dart:491">
P2: Disconnect cleanup can stop mid-flow if `onRecordingDeviceDisconnected()` throws, leaving recording/WAL/analytics state partially updated. Wrapping this awaited call in local error handling preserves the rest of the disconnect path even when capture cleanup fails.</violation>
</file>

<file name="app/lib/services/capture/capture_controller.dart">

<violation number="1" location="app/lib/services/capture/capture_controller.dart:1546">
P2: The reconnect teardown in `streamDeviceRecording` serializes on a `_phoneMicBatchStopCompleter` that is completed by the native batch `onStop` callback, but that same callback is shared by every batch-stop path (the stalled-restart watchdog in `_onBatchStalled` and the manual `stopStreamRecording` phone-batch branch both call `phoneMic.stop()`). Because the completer is a single shared field, one of those unrelated stops can resolve it before the reconnect's own native finalization completes, letting the device stream reopen while the phone batch is still draining or restarting — the very mic-ownership overlap this change is meant to avoid. In the opposite case (no `onStop` fires for the immediate stop, e.g. the batch already natively stopped), the reconnect blocks for the full 5s timeout before the device pipe is resumed, slowing reconnection. Consider tying the completer to the specific stop (e.g. confirm the batch instance/generation being torn down rather than completing on any shared `onStop`), which would make the serialization precise and remove the 5s stall.</violation>
</file>

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

Re-trigger cubic

setIsConnected(false);
updateConnectingStatus(false);

await captureProvider?.onRecordingDeviceDisconnected();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: Disconnect cleanup can stop mid-flow if onRecordingDeviceDisconnected() throws, leaving recording/WAL/analytics state partially updated. Wrapping this awaited call in local error handling preserves the rest of the disconnect path even when capture cleanup fails.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At app/lib/providers/device_provider.dart, line 491:

<comment>Disconnect cleanup can stop mid-flow if `onRecordingDeviceDisconnected()` throws, leaving recording/WAL/analytics state partially updated. Wrapping this awaited call in local error handling preserves the rest of the disconnect path even when capture cleanup fails.</comment>

<file context>
@@ -488,6 +488,7 @@ class DeviceProvider extends ChangeNotifier implements IDeviceServiceSubsciption
     setIsConnected(false);
     updateConnectingStatus(false);
 
+    await captureProvider?.onRecordingDeviceDisconnected();
     captureProvider?.updateRecordingDevice(null);
 
</file context>
Suggested change
await captureProvider?.onRecordingDeviceDisconnected();
try {
await captureProvider?.onRecordingDeviceDisconnected();
} catch (e) {
Logger.debug('onDeviceDisconnected: capture cleanup failed: $e');
}

if (_phoneMicBatchActive) {
_micInterrupted = true;
final completer = Completer<void>();
_phoneMicBatchStopCompleter = completer;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: The reconnect teardown in streamDeviceRecording serializes on a _phoneMicBatchStopCompleter that is completed by the native batch onStop callback, but that same callback is shared by every batch-stop path (the stalled-restart watchdog in _onBatchStalled and the manual stopStreamRecording phone-batch branch both call phoneMic.stop()). Because the completer is a single shared field, one of those unrelated stops can resolve it before the reconnect's own native finalization completes, letting the device stream reopen while the phone batch is still draining or restarting — the very mic-ownership overlap this change is meant to avoid. In the opposite case (no onStop fires for the immediate stop, e.g. the batch already natively stopped), the reconnect blocks for the full 5s timeout before the device pipe is resumed, slowing reconnection. Consider tying the completer to the specific stop (e.g. confirm the batch instance/generation being torn down rather than completing on any shared onStop), which would make the serialization precise and remove the 5s stall.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At app/lib/services/capture/capture_controller.dart, line 1546:

<comment>The reconnect teardown in `streamDeviceRecording` serializes on a `_phoneMicBatchStopCompleter` that is completed by the native batch `onStop` callback, but that same callback is shared by every batch-stop path (the stalled-restart watchdog in `_onBatchStalled` and the manual `stopStreamRecording` phone-batch branch both call `phoneMic.stop()`). Because the completer is a single shared field, one of those unrelated stops can resolve it before the reconnect's own native finalization completes, letting the device stream reopen while the phone batch is still draining or restarting — the very mic-ownership overlap this change is meant to avoid. In the opposite case (no `onStop` fires for the immediate stop, e.g. the batch already natively stopped), the reconnect blocks for the full 5s timeout before the device pipe is resumed, slowing reconnection. Consider tying the completer to the specific stop (e.g. confirm the batch instance/generation being torn down rather than completing on any shared `onStop`), which would make the serialization precise and remove the 5s stall.</comment>

<file context>
@@ -1523,6 +1537,29 @@ class CaptureController extends ChangeNotifier
+    if (_phoneMicBatchActive) {
+      _micInterrupted = true;
+      final completer = Completer<void>();
+      _phoneMicBatchStopCompleter = completer;
+
+      ServiceManager.instance().phoneMic.stop();
</file context>

aryanorastar and others added 2 commits August 4, 2026 15:21
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks for this — the intent (don't let phone-mic fallback clobber an active on-device offline/batch recording on BLE drop) is clear and the pure predicate + isRecordingDuringDeviceDisconnect mapping are nicely unit-tested. A few observations for the maintainer and contributor:

  1. DeviceType.limitless special-case looks over-broad. In onRecordingDeviceDisconnected:

    (_recordingDevice!.type == DeviceType.limitless || _offlineSessionStartSeconds != 0)

    When batchModeEnabled is on and the device is a limitless, the isOnDeviceOfflineBatchActive guard is always true regardless of whether an offline session is actually running. That disables phone fallback for any limitless+batchMode disconnect, even when no on-device offline batch is active. If limitless reliably runs on-device batch whenever batchMode is enabled that may be intentional, but worth confirming the invariant holds — otherwise prefer gating on a real "on-device batch active" signal rather than device type.

  2. Disconnect cleanup ordering (device_provider.dart):

    await captureProvider?.onRecordingDeviceDisconnected();
    captureProvider?.updateRecordingDevice(null);

    If onRecordingDeviceDisconnected() throws, updateRecordingDevice(null) and the subsequent WAL/analytics teardown are skipped, leaving state inconsistent after a device drop. Consider wrapping the awaited call in try/catch so the rest of the disconnect path always runs. (cubic flagged the same; +1.)

  3. Shared _phoneMicBatchStopCompleter. The reconnect teardown in streamDeviceRecording waits on a completer that the shared native onStop callback completes. _onBatchStalled and the manual stopStreamRecording batch branch also call phoneMic.stop(), so any of those stops can resolve the completer before this reconnect's own native finalization drains — the mic-ownership overlap this serialization is meant to prevent. Conversely, if onStop doesn't fire, reconnect blocks the full 5s. Tying the completer to the specific stop (e.g. a generation/token checked inside onStop) would make the serialization precise and remove the stall. (Also raised by cubic; the concurrency concern is real.)

The two failing Desktop Swift checks are unrelated to this Flutter/Dart change (no Swift files touched; the jobs were cancelled/skipped on the Swift-changes path and failed on a separate run).

Net: logic is reasonable and tested at the unit level, but the capture state machine has real concurrency/ordering edges here — marking for 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.

@Git-on-my-level Git-on-my-level added needs-maintainer-review Needs a human maintainer to sign off before merge needs-tests PR introduces logic that should be covered by tests flutter flutter work labels Aug 4, 2026

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

Phone-mic batch fallback fired even while the wearable was doing its own on-device offline batch, interrupting that capture. Predicate now gates on isOnDeviceOfflineBatchActive, with unit coverage. Fixes #7194. 5/5 - merging.

@kodjima33
kodjima33 merged commit 75e4e17 into BasedHardware:main Aug 4, 2026
60 of 63 checks passed
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Aug 4, 2026
After BasedHardware#11084 landed the phone-mic fallback path, close the reconnect race
David flagged: bump an epoch on reconnect/stop, recheck device id after
each fallback await, and only clear recordingDevice when reconnect has
not already replaced it. Catch fallback errors so disconnect cleanup
always continues.

Failure-Class: none
Co-authored-by: Cursor <[email protected]>
mdmohsin7 added a commit that referenced this pull request Aug 5, 2026
#11134)

## Summary

Reverts #11084 (`75e4e1789d`), which added
`CaptureController.onRecordingDeviceDisconnected()` and the
`DeviceProvider` hook that starts a **phone-mic batch recording whenever
the wearable disconnects mid-session**.

## Why

**This behaviour was already reviewed and rejected.** #11066 proposed
the same phone-side fallback and received `CHANGES_REQUESTED` from the
app maintainer:

> The tagged issue actually means recording on the device offline when
not connected to bluetooth. Right now it does record offline but it
breaks sometimes. This PR is not the right fix for this

#11066 was closed, and #11078 was opened specifically so a phone-side
fallback could be scoped on its own merits. **#11078 is still open and
unapproved.**

**The PR description did not match its diff.** #11084 is titled
"preserve on-device offline batch across BLE disconnect" and its body
states it "prevents the phone-mic fallback from triggering". Before
#11084 there was no such fallback to prevent:
`onRecordingDeviceDisconnected` did not exist and nothing called it, and
`_startPhoneMicBatch` was reachable only from user-initiated paths. The
PR introduced the feature together with a guard for it; the
Implementation section listed neither the new method nor the
`device_provider.dart` call site.

**The guard does not cover Omi hardware.** It reads:

```dart
final bool isOnDeviceOfflineBatchActive = SharedPreferencesUtil().batchModeEnabled &&
    _recordingDevice != null &&
    (_recordingDevice!.type == DeviceType.limitless || _offlineSessionStartSeconds != 0);
```

It consults `batchModeEnabled`, but ring-buffer capture is keyed on
firmware (`WalSyncs.isRingBufferFirmware`, 3.0.20+) and is independent
of that pref. With batch mode off, an Omi on 3.0.20+ keeps writing to
its on-device ring while the phone starts its own mic batch — the same
interval is captured twice and syncs as duplicate conversations, plus an
unrequested mic activation and the battery cost.

#11084 did address the technical review notes from #11066
(`deviceRecord` state, awaited stop hand-off,
`deviceSupportsTranscribeLater`). The product objection was not
addressed.

## Scope

Revert only. #11064 and #11085 from the same batch are left in place —
#11064 is a genuine sort fix, and #11085 needs a real fix rather than a
revert (its `filterFullySyncedConversations` never releases a WAL
retired to `WalStatus.outsideRecoveryWindow` by #10995, so those
conversations stay filtered out of the synced list; tracked separately).

#7194 remains open on its actual subject: on-device offline recording
that works but is flaky across disconnects.

## Verification

```
flutter analyze lib/services/capture/capture_controller.dart lib/utils/batch_recording.dart \
  lib/providers/device_provider.dart test/unit/batch_recording_phone_test.dart
  -> 1 info (unnecessary_import at device_provider.dart:4), confirmed pre-existing on main; 0 new

flutter test test/unit/batch_recording_phone_test.dart test/providers/capture_provider_test.dart \
  test/providers/sync_provider_fully_synced_conversations_test.dart \
  test/unit/synced_conversation_pointer_order_test.dart
  -> 89 tests, all passed

grep shouldFallbackToPhoneOnDeviceDisconnect | onRecordingDeviceDisconnected |
     isRecordingDuringDeviceDisconnect | _phoneMicBatchStopCompleter
  -> no matches remain under app/

make preflight -> 11 checks passed
```

Clean revert: no later commit touched `capture_controller.dart`,
`batch_recording.dart`, `device_provider.dart`, or
`batch_recording_phone_test.dart` between #11084 and `84e4c1828b`.

## Product invariants affected

none

## Failure class (fixes)

No `fix:` commits; no declaration required.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/11134?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="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
pull Bot pushed a commit to Mu-L/omi that referenced this pull request Aug 5, 2026
Reverts 75e4e17 (BasedHardware#11084), which added `onRecordingDeviceDisconnected()`
and the `device_provider` hook that starts a phone-mic batch recording
whenever the wearable drops mid-session.

The same behaviour was proposed in BasedHardware#11066 and rejected by the app
maintainer: BasedHardware#7194 asks for on-device offline recording to keep working
across a disconnect, not for the phone to start recording in its place.
BasedHardware#11066 was closed and BasedHardware#11078 was opened to scope a phone-side fallback on
its own merits; BasedHardware#11078 is still open and unapproved.

BasedHardware#11084 landed the feature anyway, described as a guard against it. Its
guard is also wrong for Omi hardware: it consults `batchModeEnabled`, but
ring-buffer capture is keyed on firmware (`isRingBufferFirmware`, 3.0.20+)
and is independent of that pref. With batch mode off, an Omi on 3.0.20+
keeps writing to its ring while the phone starts its own mic batch, so the
same interval is captured twice and syncs as duplicate conversations.

Verification:
  flutter analyze lib/services/capture/capture_controller.dart \
    lib/utils/batch_recording.dart lib/providers/device_provider.dart \
    test/unit/batch_recording_phone_test.dart
    -> 1 pre-existing info (unnecessary_import, already on main), 0 new
  flutter test test/unit/batch_recording_phone_test.dart \
    test/providers/capture_provider_test.dart \
    test/providers/sync_provider_fully_synced_conversations_test.dart \
    test/unit/synced_conversation_pointer_order_test.dart
    -> 89 tests, all passed
  grep for shouldFallbackToPhoneOnDeviceDisconnect / onRecordingDeviceDisconnected
  / isRecordingDuringDeviceDisconnect / _phoneMicBatchStopCompleter -> no matches

Failure-Class: none
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 needs-tests PR introduces logic that should be covered by tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Offline/Bluetooth-disconnected recording is not working.

3 participants