Repository navigation
feat: Offline (batch) capture mode — store BLE audio locally, transcribe on demand - #7981
Conversation
Appends incoming BLE audio frames to length-prefixed .bin files in the app documents directory (the format the offline sync pipeline accepts) instead of streaming to the transcription socket. Includes size/duration rotation, gap-based finalize, periodic fsync, a journal so partially written files are never ingested, and a free-space guard.
… batch mode Dispatches each audio packet to the batch writer alongside the background streamer (the two self-gate via prefs), subscribes to the audio characteristic when the engine is gone, finalizes the file on destroy, and keeps the foreground service sticky whenever batch mode is on.
…cordings In batch mode the transcription websocket is never opened and the Dart WAL writer stays off (native owns writing). Finalized .bin files are registered into the existing WAL upload/reconcile pipeline via addExternalWal.
ClawSweeper local pilot reviewRecommendation: keep open, but not merge-ready. What it found:
Suggested next step: add real-device proof, translate the new l10n keys, update the audio/transcription pipeline docs, and document recovery behavior for interrupted journaled recordings. Posted from a local report-only ClawSweeper pilot by request; no labels, closes, repairs, or merges were performed. |
Pure, testable parser for batch recording filenames (codec, frame size, timestamp) mirroring how the offline-sync backend interprets the name.
Active files are now *.bin.part (excluded by the .bin scan), so the journal-based skip is no longer needed.
…ch writer Write to .bin.part and rename to .bin only when sealed (rotation/gap/stop) so a half-written file is never ingested; promote stale .bin.part from a crashed process on next start. Replaces the journal.
Mirrors the Android writer: length-prefixed .bin files, size/duration rotation, silence-gap finalize, periodic fsync, atomic .bin.part rename, stale-part recovery, and a free-space guard.
In didUpdateValueFor, hand audio packets to BatchAudioWriter when batch mode is on and skip forwarding to Dart so the Flutter engine stays idle.
A conversations-list row for a local batch recording: time + duration, sync status, swipe-to-delete, and an inline play/pause button that decodes and plays the local audio on device. Tapping opens the WAL detail page.
ConversationsGroupWidget now merges conversations and unsynced recordings into one time-sorted list under each date header.
Group pendingWals by date, union with conversation dates, and render them in the same list (default view only); empty-state guards account for recordings.
Filter pendingWals to the batch marker so device SD-card/flash sync WALs and realtime offline buffers no longer appear here (also avoids their duplicate-id collisions).
… captured-so-far timer
…ract Native batch writer notifies Dart when a recording file finalizes (rotation/gap/stop) so the recordings list rescans without waiting for a BLE disconnect.
Exposes a batchRecordingFinalizedCallback that the recordings provider registers to rescan on file finalize.
After the .part->.bin rename succeeds, invoke BleFlutterApi.onBatchRecordingFinalized on main so a rotated file surfaces in the recordings list without a BLE disconnect.
After the .bin.part->.bin rename succeeds, post BleFlutterApi.onBatchRecordingFinalized on the BLE manager's main handler (gated on isFlutterAlive) so a rotated file surfaces without a BLE disconnect.
Register the batch-finalize callback to refresh on rotation/gap/stop, and return LocalUploadOutcome from upload() so the UI can distinguish a fair-use (429) block from success/failure.
Sync Now no longer pops the page unconditionally: on a fair-use (429) block it shows the daily-limit message and stays put; on failure it shows an error; only a started upload navigates back.
There was a problem hiding this comment.
40 issues found across 77 files
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/ios/Runner/OmiBleManager.swift">
<violation number="1" location="app/ios/Runner/OmiBleManager.swift:765">
P2: Hot-path notifications now call BatchAudioWriter even when offline mode is disabled. This adds unnecessary per-packet config checks and async dispatches during normal realtime streaming.</violation>
</file>
Tip: instead of fixing issues one by one fix them all with cubic
Partial review: This PR has more than 50 files, so cubic reviewed the highest-priority files first. During the trial, paid plans get a higher file limit.
You can try an ultrareview to bypass the file limit, comment @cubic-dev-ai ultrareview. Learn more.
Re-trigger cubic
Adds offlineModeTitle/Description/Note/StorageFull to every non-English ARB (previously falling back to English in the generated localizations, flagged by review). Each locale translated then verified for genuine target-language copy; regenerated with flutter gen-l10n (zero untranslated warnings).
There was a problem hiding this comment.
No issues found across 125 files
Partial review: This PR has more than 50 files, so cubic reviewed the highest-priority files first. During the trial, paid plans get a higher file limit.
You can try an ultrareview to bypass the file limit, comment @cubic-dev-ai ultrareview. Learn more.
Re-trigger cubic
|
@cubic-dev-ai ultrareview |
@mdmohsin7 Starting ultrareview. I'll post findings when complete. |
There was a problem hiding this comment.
Ultrareview completed in 5m 4s
2 issues found across 125 files
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/ios/Runner/OmiBleManager.swift">
<violation number="1" location="app/ios/Runner/OmiBleManager.swift:646">
P2: Batch recording is stopped on every BLE disconnect, even when the disconnected peripheral is not the active batch-capture device.</violation>
<violation number="2" location="app/ios/Runner/OmiBleManager.swift:765">
P2: The new unconditional batch-handler call adds per-packet async queue work even when offline mode is disabled, increasing BLE hot-path overhead.</violation>
</file>
Note: This PR contains a large number of files. cubic only reviews up to 50 files per PR in ultrareview mode, so some files may not have been reviewed. cubic prioritizes the most important files to review.
Fix all with cubic | Re-trigger cubic
| if BatchAudioWriter.shared.handle( | ||
| peripheralUuid: uuid, | ||
| serviceUuid: serviceUuid, | ||
| characteristicUuid: charUuid, | ||
| value: data | ||
| ) { | ||
| return | ||
| } |
There was a problem hiding this comment.
P2: The new unconditional batch-handler call adds per-packet async queue work even when offline mode is disabled, increasing BLE hot-path overhead.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At app/ios/Runner/OmiBleManager.swift, line 765:
<comment>The new unconditional batch-handler call adds per-packet async queue work even when offline mode is disabled, increasing BLE hot-path overhead.</comment>
<file context>
@@ -755,6 +759,18 @@ extension OmiBleManager: CBPeripheralDelegate {
+ // Batch (offline) mode: store audio natively and skip the Dart forward so the
+ // Flutter engine stays idle. Returns true only for the configured audio
+ // characteristic while batch mode is on; everything else falls through.
+ if BatchAudioWriter.shared.handle(
+ peripheralUuid: uuid,
+ serviceUuid: serviceUuid,
</file context>
| if BatchAudioWriter.shared.handle( | |
| peripheralUuid: uuid, | |
| serviceUuid: serviceUuid, | |
| characteristicUuid: charUuid, | |
| value: data | |
| ) { | |
| return | |
| } | |
| if UserDefaults.standard.bool(forKey: "flutter.batchModeEnabled"), | |
| BatchAudioWriter.shared.handle( | |
| peripheralUuid: uuid, | |
| serviceUuid: serviceUuid, | |
| characteristicUuid: charUuid, | |
| value: data | |
| ) { | |
| return | |
| } |
|
|
||
| // Finalize the in-progress batch recording so it's saved + ingestable right away | ||
| // (a plain BLE disconnect never delivers another packet to trigger the gap finalize). | ||
| BatchAudioWriter.shared.stop("disconnected") |
There was a problem hiding this comment.
P2: Batch recording is stopped on every BLE disconnect, even when the disconnected peripheral is not the active batch-capture device.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At app/ios/Runner/OmiBleManager.swift, line 646:
<comment>Batch recording is stopped on every BLE disconnect, even when the disconnected peripheral is not the active batch-capture device.</comment>
<file context>
@@ -641,6 +641,10 @@ extension OmiBleManager: CBCentralManagerDelegate {
+ // Finalize the in-progress batch recording so it's saved + ingestable right away
+ // (a plain BLE disconnect never delivers another packet to trigger the gap finalize).
+ BatchAudioWriter.shared.stop("disconnected")
+
if !isManual {
</file context>
handle() ran a queue.async close dispatch on every BLE audio packet even with batch mode disabled (the common case). Gate it on an enabled->disabled edge flag so the hot path does no per-packet work, while still finalizing an in-progress file the moment offline mode is turned off. Drops the leftover no-config diagnostic probe.
… off
handleCharacteristic() took the writer lock via closeCurrent("disabled")
on every BLE audio packet even with batch mode disabled. Gate it on an
enabled->disabled edge flag so the hot path does no per-packet work,
while still finalizing an in-progress file when offline mode is turned off.
… guard (#21517) ## What changed and why The mobile app stutters intermittently: scrolling, page transitions and taps lag, mostly while recordings sync, during long recordings, and after reopening the app. An audit found that work which grows with the user's history ran on the UI isolate, and that root proxy-provider hooks re-notified on every upstream change. This PR fixes the largest causes. It also adds a guard (INV-PERF-1) and regression tests so the same shapes fail CI instead of coming back. **Performance fixes (`app/lib`)** - **WAL index save** (`utils/wal_file_manager.dart`): - Before, every save read and `jsonDecode`d the whole old index just to validate it, then re-encoded the whole new index on the UI isolate. - Saves queued back-to-back now collapse into the newest snapshot. The final file is identical, because each caller passes a full snapshot and the last write wins either way. - When saves collapse, the newest replaced snapshot is written as the backup, which is what serial writes left. Otherwise the backup copy skips re-decoding when the file still matches what this process wrote (length + mtime), and validates as before. - Indexes of 200+ entries encode on a background isolate. - **Notify cascades:** - `CaptureController.updateExternalActions` no longer notifies when the adapter wraps the same four providers (`ProviderCaptureExternalActions ==`). - `DeviceProvider.setProviders` no longer notifies when its references are unchanged. - Previously, every chat token or conversation refresh re-notified Capture and then Device, and every transcript segment re-notified Device. - **Live transcript mirror:** - `CaptureProvider._persistLiveSegments` ran on every capture notify and built a string from the whole transcript each time. It now checks a cheap key first: list identity, length, `segmentsPhotosVersion` and owner token. - `LocalSegmentStore` hashes and encodes sessions of 150+ segments on a background isolate. The digest is unchanged, and a test pins that. - **Resume path:** - Conversation list bodies of 64 KB or more are parsed on a background isolate (`parseConversationListBody`). - The offline conversation cache is encoded in the background (`SharedPreferencesUtil.cacheConversations`), behind a generation guard. That guard is also bumped by `clear()`, so an in-flight write cannot restore a signed-out account's cache. - `LocalRecordingsProvider.refresh` lists the documents directory asynchronously instead of with `listSync`. When scans overlap, only the newest one rewrites the owners file (rechecked right before the rename) or publishes its results. - **Lists and visuals:** - The memories list filters once per build instead of once per row. - Voice dictation's 60 Hz tick drives a dedicated `waveformTick` instead of notifying the provider, so the whole chat composer no longer rebuilds 60 times a second. - **New shared helper:** `utils/off_ui_isolate.dart`. Work runs inline below a size threshold and in `Isolate.run` above it. Tests assert there is no silent fallback to the UI isolate (`offUiIsolateFallbacks == 0`). **Regression infrastructure** - `.github/scripts/check_mobile_ui_isolate.py`, wired in `checks-manifest.yaml` as `mobile-ui-isolate` plus `-tests`. It has two parts: - A per-file no-increase ratchet (the INV-UI-3 shape) on: sync `dart:io`, JSON in providers, timers faster than 100 ms, blur, network images without a decode size, and `shrinkWrap: true` lists. - A `history-json-on-ui` rule: JSON in the WAL index, live transcript, conversation list and preferences modules must sit inside `offUiIsolate`, so removing the wrapper fails CI. - An absolute check that every proxy update hook named in `app/lib/main.dart` returns early on an `identical`/`==` test before `notifyListeners()`. A hook whose declaration the check cannot read also fails. `ConversationDetailProvider.setProviders` is allowed with a reason: the open detail page derives its conversation from upstream state. - `product/invariants/mobile-ui-isolate.md` (INV-PERF-1, proposed per PRODUCT.md's seven-day rule; the guard runs in CI regardless) and `app/docs/performance.md`. The doc covers the causes, the rules, the guards, and how to measure. It also lists the known remaining candidates: the chat sheet's persistent full-screen blur (a UX-contract D1 decision), SD-card sync refreshing the WAL list per chunk, and the batch buffer's once-per-second fsync. ## Product invariants affected - INV-CAP-1: touches `services/capture/capture_controller.dart` (notify guard only) and `local_segment_store.dart` (where the hash/encode runs). Neither changes when the phone consumes pendant audio. The WAL index changes keep last-write-wins and the validated backup, so no WAL entry can be dropped from the index. Covered by the existing torn-write and recovery tests and the new save tests. - INV-MEM-1: `capture_provider.dart` matched by path. No memory tier behaviour changes. - INV-PERF-1: new invariant, introduced here as proposed. ## How it was verified All on macOS (Apple Silicon), Flutter 3.44.5 (the CI version), with hermetic inputs as in CI. - `bash test.sh` (full app suite, at the final commit): 5680 passed, 21 skipped, 0 failed - `bash scripts/analyze_ratchet.sh`: passed. - `python3 .github/scripts/test_check_mobile_ui_isolate.py`: 39 tests OK. - `check_mobile_ui_isolate.py --changed-files … --base <merge-base>`: OK, and `--graph`: OK. - `check_mobile_ux_contract.py`: OK. - Red proofs (new tests run against the unfixed code): - Repeated proxy updates notified 50 of 50 times (now 0). - 200 transcript-neutral capture notifies did 80,000 segment reads on a 400-segment transcript (now 0). - Back-to-back WAL saves did not coalesce. - A sign-out during a background cache write restored the old cache. - Host interaction harness (`tool/perf_harness.sh`, one run each on the same machine, so indicative only): | Scenario | p90 frame time, ms | jank frames | |---|---|---| | home | 30.4 → 25.6 | 47 → 26 | | detail | 49.5 → 30.0 | 64 → 33 | | memories | 15.6 → 8.7 | 9 → 6 | | chat | 53.9 → 33.9 | 7 → 4 | Host timings are machine-dependent, and two of the harness's own budgets already fail on unmodified `main` on this machine. Rebuild counts vary a few percent between runs. That is why the harness is documented as a measurement tool and not wired as a CI gate. - **Not verified:** on-device frame timing (profile build plus DevTools during a real sync). The raster-bound chat blur was not changed. ## Review follow-ups - **Codex** (3 comments, all fixed): - Collapsed saves now keep the superseded snapshot as the backup. - Braced `if (…) { return; }` guards are accepted. - Hooks without a readable declaration fail. - **Cursor Grok** (read-only review via agentctl, all fixed): - Closed the remaining recordings-scan race. - The guard now catches removed `offUiIsolate` wrappers and null-only guards. - Removed the `ResizeImage` false positive. - Strengthened the replaced-caller save test. - **Codex rounds 2–3** (all fixed): - A guard must be the `return`'s own `identical`/`==` condition on the injected values. - Comments that mention `offUiIsolate(` no longer exempt JSON calls. - A failing superseded-snapshot backup can't block the index write. - The transcript key is dropped when no capture session is active. - INV-PERF-1 is now proposed. ## Tests - `app/test/perf/notify_amplification_test.dart`: proxy hooks don't re-notify, and capture notifies don't walk the transcript. - `app/test/perf/conversation_list_off_ui_test.dart`: off-isolate parse/encode parity, stale writes, and sign-out. - `app/test/unit/wal_file_manager_save_cost_test.dart`: coalescing, off-isolate encode, backup re-validation. - `app/test/unit/voice_recorder_mic_contention_test.dart`: the waveform ticks without provider notifies. - `app/test/unit/local_segment_store_test.dart`: off-isolate digest parity. ## Line-count exceptions Line-Count-Exception: app/lib/backend/preferences.dart | 1514 -> 1538 | background conversation cache write with its generation guard (sign-out safety) Line-Count-Exception: app/lib/pages/conversation_detail/conversation_detail_provider.dart | 1514 -> 1518 | documented INV-PERF-1 allow on the one proxy hook that must notify Line-Count-Exception: app/lib/providers/conversation_provider.dart | 2119 -> 2121 | log failures of the now-async cache write Line-Count-Exception: app/lib/providers/device_provider.dart | 1594 -> 1598 | early return in the proxy update hook Line-Count-Exception: app/lib/services/capture/capture_controller.dart | 4437 -> 4443 | early return in the proxy update hook ## UI evidence UI-Evidence: none -- no visual change; the memories list and voice waveform render the same, only their rebuild scope changed Failure-Class: none ## New guards (only when adding a check or ratchet) The ratchet would have flagged the defects fixed here when they landed: - `listSync` over the WAL directory in #7981 (`sync-file-io`). - The 60 Hz provider notify in the voice recorder, `1588ac7225` from #7009 (`fast-periodic-timer`). The provider-graph check catches the unconditional `notifyListeners()` in `updateExternalActions` / `setProviders`. It is a check, not a shared primitive, because the cost lives in how ordinary provider and file code is written. The primitive part (`offUiIsolate`) is what the check points people to. 🤖 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/21517?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
Adds an Offline (batch) capture mode — the opposite of realtime transcription. When enabled, the app keeps receiving BLE audio from the device but does not open the transcription websocket. Instead the native layer (Android + iOS) stores the audio to local
.binfiles with timestamps; the recordings appear inline in the conversations list, and the user transcribes any one on demand — the existing/v2/sync-local-filesbackend turns it into a conversation. Synced conversations also persist their audio 1:1 with realtime, so they're playable in-app exactly like live ones.Doing the storage natively means the Flutter engine does no per-packet work while the app is minimized/closed — lower battery/CPU/network when idle.
Architecture — recordings are their own subsystem (not WALs)
Local recordings are deliberately decoupled from the offline-sync WAL stack. The recordings directory is the queue and the
.binfiles are the single source of truth:LocalRecording(model) +LocalRecordingsProvider(lib/providers/local_recordings_provider.dart) scan the recordings dir → list; nothing is stored in the WAL_walslist.uploadLocalFilesV2(the/v2/sync-local-filescall),fetchSyncJobStatus(reconcile), andAudioPlayerUtils/WaveformUtilsfor on-device opus playback (fed a throwawayWal, never stored).job_ids persist in a small sidecar (a SharedPreferences map), reconciled by a lightweight 15s poll; the local file is deleted only when the job reportscompleted, and a completed job's conversation is inserted viaConversationProvider.upsertConversation. App-kill mid-processing recovers on next launch.This keeps the Sync page (device SD/flash offline-sync) completely untouched —
sync_provider.dart/local_wal_sync.dartare unchanged. Recordings and device-sync files no longer leak into each other's screens.What it does (app)
Native writers (Android
OmiBatchAudioWriter.kt, iOSBatchAudioWriter.swift)[4-byte LE length][frame]intoaudio_omibatch_{codec}_{sr}_{ch}_fs{frameSize}_{startSec}.bin(the exact format/v2/sync-local-filesdecodes). Theomibatchdevice-segment marker distinguishes batch recordings from offline-sync WAL files that share the same directory + naming (the backend treats that segment as a free-form label)..bin.partfile and atomically rename to.binonly once sealed; recover a stale.bin.partleft by a crashed process on next start; periodicfsync; a free-space guard that pauses + flags rather than crashing.Native → Dart finalize notification (Pigeon)
BleFlutterApi.onBatchRecordingFinalizedover the existing BLE Pigeon contract (iOS on main; Android via the BLE manager's main handler, gated onisFlutterAlive).LocalRecordingsProviderrescans on that signal, so a rotated recording surfaces in the list immediately — no longer only after a BLE disconnect. Disconnect / app-resume / page-load refreshes remain as backstops for the backgrounded case.Wiring
OmiBleManager.didUpdateValueForhands audio to the writer in batch mode and skips the Dart forward; background capture rides the existingbluetooth-centralmode + state restoration.batchAudioDir, etc.) for the writer. No WAL ingestion.Home-page capture UI
Recordings in the conversations list
Backend — conversation audio, 1:1 with realtime (
backend/routers/sync.py)Synced conversations now persist their audio exactly like the realtime/private-cloud-sync path, so they play through the existing conversation audio player with zero client changes:
private_cloud_sync_enabled(+data_protection_level), fetched once per job — same as realtime.process_segment, each segment's decoded audio (16 kHz mono PCM16) is written via the sameupload_audio_chunkthe realtime path uses → encrypted opus chunks atchunks/{uid}/{conversation_id}/{ts}.opus[.enc], keyed by absolute timestamp.create_audio_files_from_chunks+update_conversation('audio_files')+precache_conversation_audioper conversation — identical to the realtime flush.audio_files); never wipes existingaudio_files; best-effort (audio storage never fails transcription).Verification
flutter analyzeclean on changed Dart; filename-parser unit tests pass; iOSBatchAudioWriter.swifttypechecks; Pigeon bindings regenerated for all three platforms.blackclean; no new async-blocker flags; adversarial review (8/8 realtime-parity checks pass, one merge-ordering window fixed); sync unit tests show no regression vs the HEAD baseline.Remaining (follow-ups)
offlineMode*settings strings to non-English locales (the recordings UI reuses existing localized strings — no new keys).🤖 Generated with Claude Code