Skip to content

refactor(app): extract WAL logic from CaptureProvider, unify AudioSource abstraction - #6058

Merged
beastoin merged 142 commits into
fix/phone-mic-wal-offline-5913from
refactor/wal-audio-source-6056
Mar 26, 2026
Merged

beastoin merged 142 commits into
fix/phone-mic-wal-offline-5913from
refactor/wal-audio-source-6056

Conversation

@beastoin

@beastoin beastoin commented Mar 26, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #6056

Extract AudioSource abstraction from CaptureProvider so WAL is source-agnostic and CaptureProvider doesn't hold WAL-specific logic (header stripping, frame buffering, byte routing).

Changes

New files:

  • audio_source.dart — abstract AudioSource, WalFrame, FrameSyncKey with content-based equality
  • ble_device_source.dart — strips 3-byte firmware header, produces BLE sync key
  • phone_mic_source.dart — buffers variable chunks into fixed 320-byte PCM frames with monotonic index key

Modified files:

  • wal_interfaces.dart — replaced onByteStream/onBytesSync with onFrameCaptured(WalFrame)/markFrameSynced(FrameSyncKey)
  • local_wal_sync.dart — frames list uses WalFrame, _chunk extracts .payload, _flush writes directly (no sublist(3)), added @VisibleForTesting getters
  • capture_provider.dart — delegates to _activeSource for header stripping, frame production, socket payload
  • audio_player_utils.dart — removed double sublist(3) on now-headerless payloads (reviewer-caught bug)

Review cycle fixes

  1. High: Fixed double sublist(3) in audio_player_utils._createTempFileFromMemoryData — payloads are now headerless, so writing directly
  2. Medium: Fixed cleanup ordering race — close BLE stream before nulling _activeSource
  3. Medium (accepted): Phone mic 1-byte sync key wrapping is safe — _chunk drains every ~75s, well within 256-frame window

Testing

  • 36 unit tests pass (20 audio_source + 16 local_wal_sync)
  • audio_source_test.dart: FrameSyncKey equality/factories, BleDeviceSource header stripping/short packets/WAL compat, PhoneMicSource buffering/wrapping/flush
  • local_wal_sync_test.dart: onFrameCaptured ordering, markFrameSynced duplicate keys/no-match/BLE/phone-mic keys, WAL binary serialization format, double-strip regression, chunk payload extraction
  • 1 pre-existing env_test failure on main (unrelated)

by AI for @beastoin

mdmohsin7 and others added 30 commits March 23, 2026 00:15
When the user disconnects from Device Info page, set _manualDisconnect
flag so onDeviceDisconnected skips periodicConnect and cancels the
reconnection timer.
The "2-8 lines" default in response_style was cutting off mid-answer
on detailed questions, requiring users to say "continue" repeatedly.

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

process_segment() had no error handling — Deepgram failures caused silent
returns or thread crashes, and the endpoint always returned HTTP 200. This
caused the app to mark WALs as synced and delete audio permanently.

Fix: wrap process_segment() in try/except, collect errors via thread-safe
lock, return HTTP 207 for partial failures and 500 when all segments fail.
Old clients (checking only for 200) safely treat 207 as failure and retry.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
21 tests covering: structural verification of error handling, thread-safe
error collection, status code logic (200/207/500), Deepgram retry behavior,
app-side sync marking documentation, and data loss prevention flow.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
When app retries a batch after 207, already-processed segments are
deduplicated by (timestamp, end) pair before merging into existing
conversations. Uses rounding to avoid float precision issues.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
5 new tests: dedup structural verification, dedup correctness with sample
data, all-duplicates skip, and behavioral thread simulation with mixed
success/failure/exception scenarios.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
process_segment spawns a background thread with time.sleep(480) for
file cleanup. Without patching, tests hang waiting for that sleep.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Silent/no-speech segments legitimately return empty transcripts from
Deepgram. Treating this as an error would cause permanent 207 retry
loops for old clients that only accept HTTP 200.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Move sys.modules stubs into setup_class/teardown_class to prevent
  contamination of other test files in the same pytest process
- Update empty transcript test to verify it's a warning skip, not error
- Change mixed thread test to use exception (not empty result) as failure

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Icons added to all top-level and nested groups:
- Get Started: rocket
- Core Development: code
  - Backend: server
  - Firmware: microchip
  - SDK: cube
  - Audio & Testing: headphones
- Developer API: square-terminal
- MCP Integration: plug
- Build Apps: grid-2
  - Examples: flask
- Hardware: circuit-board
  - Open Source Hardware: screwdriver-wrench
- OmiGlass: glasses
- DIY Guide: hammer
- Info: circle-info
Adds icons to all sidebar navigation groups in the Mintlify docs,
similar to the Supermemory docs style.

**Icons added:**
| Group | Icon |
|-------|------|
| Get Started | 🚀 `rocket` |
| Core Development | `code` |
| Backend | `server` |
| Firmware | `microchip` |
| SDK | `cube` |
| Audio & Testing | `headphones` |
| Developer API | `square-terminal` |
| MCP Integration | `plug` |
| Build Apps | `grid-2` |
| Examples | `flask` |
| Hardware | `circuit-board` |
| Open Source Hardware | `screwdriver-wrench` |
| OmiGlass | `glasses` |
| DIY Guide | `hammer` |
| Info | `circle-info` |

Uses Mintlify's built-in Font Awesome icon support via the `icon`
property on navigation groups.
Added icon frontmatter to all 61 doc pages for per-page sidebar icons:
- Get Started: book-open, play, message-dots
- Backend: server, magnifying-glass, comments, database, microphone, tower-broadcast
- SDK: cube, snake, react, swift
- Developer API: square-terminal, brain, list-check, message, key
- Apps: grid-2, terminal, link, wrench, github, slack, graduation-cap, etc.
- Hardware: circle-dot, screwdriver-wrench, bolt, gears, glasses, circuit-board
- DIY: book, cart-shopping, screwdriver
- Info: life-ring, scale-balanced, triangle-exclamation, lock
Adds icons to each individual page in the docs sidebar (not group
headings). Each MDX file gets an `icon` frontmatter property.

**61 pages updated** with contextual icons — similar to the Supermemory
docs style where every line item has its own icon.

Examples:
- 🧠 Memories → `brain`
- 🔑 API Keys → `key`
- 📡 Transcription → `microphone`
- 🔌 MCP → `plug`
- 🛒 Buying Guide → `cart-shopping`
- 🔒 Privacy → `lock`
- Restructure docs.json to use Mintlify tabs: Documentation, API Reference, Build Apps, Hardware, MCP
- Add icons to all tabs and groups
- Create OpenAPI 3.1.0 spec for the Omi Developer API (replaces plant store placeholder)
- Add 19 interactive API endpoint pages using Mintlify OpenAPI integration
- Cover all endpoints: Memories, Conversations, Action Items, API Keys
- Include proper schemas, examples, auth config, and error responses
- Keep existing hand-written API guide pages alongside interactive playground pages
Top-level headings (Get Started, Core Development, etc.) no longer have icons.
Nested sub-groups (Backend, Firmware, SDK, Audio & Testing) keep their icons.
Individual page icons remain via frontmatter.
…5998)

## What

Restructure the Omi docs to use **Mintlify tabs** for top-level
navigation and add a professional **OpenAPI-powered API Reference** with
interactive playground.

## Changes

### Navigation Tabs
- Reorganized `docs.json` from flat groups into 5 tabs:
**Documentation**, **API Reference**, **Build Apps**, **Hardware**,
**MCP**
- Added icons to all tabs and sidebar groups
- All existing pages preserved — just reorganized into a cleaner
hierarchy

### API Reference (OpenAPI)
- Created a proper **OpenAPI 3.1.0 spec** (`api-reference/openapi.json`)
covering all Developer API endpoints
  - Replaces the placeholder plant store spec
- Accurate schemas, parameters, request/response examples based on the
actual backend routers
  - Bearer auth configuration for the API playground
- Added **19 interactive endpoint pages** using Mintlify OpenAPI
integration:
  - Memories: list, create, create-batch, update, delete
- Conversations: list, create, create-from-segments, get, update, delete
  - Action Items: list, create, create-batch, update, delete
  - API Keys: list, create, revoke
- Existing hand-written API guide pages (with code examples, use cases)
kept alongside the interactive playground pages

### Before / After
- **Before**: Single flat sidebar with all groups visible. API reference
was just hand-written guides. OpenAPI spec was a placeholder plant
store.
- **After**: Clean tabbed navigation. API Reference tab has both guides
AND interactive OpenAPI playground. Users can try endpoints directly
from the docs.

## Testing
- All existing page paths preserved (no broken links)
- OpenAPI spec validates against 3.1.0
- Follows Mintlify docs.json tabs format
- Support → help.omi.me
- Buy Now → omi.me cart
- Enable llms.txt for AI discoverability
- Support link → help.omi.me
- Buy Now button → omi.me cart
- Enable auto-generated llms.txt for AI tool discoverability
Codemagic dropped v0.11.167-168 builds. This commit triggers a new
tag+build so the DMG fix gets tested in CI.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Codemagic dropped v0.11.167-168 builds. Triggering a new build to test
the DMG fix.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Triggers Codemagic build to test dmgbuild DMG fix (v0.11.167-168 were
dropped).
Auto-generated: consolidates unreleased entries into v0.11.169 and
clears the unreleased array.
dmgbuild change may have broken Codemagic trigger — reverting to the
exact create-dmg config that was building successfully (v0.11.161-166).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Reverting dmgbuild change — Codemagic stopped building after the switch.
Restoring exact config from v0.11.166 (last successful build).
kodjima33 and others added 13 commits March 26, 2026 02:03
## Summary
- disable macOS relaunch-on-login while onboarding is incomplete
- terminate the app when the last onboarding window closes instead of
leaving a menu bar process running
- re-enable relaunch-on-login once onboarding completes

## Verification
- built and launched the patched dev app with `./run.sh --yolo`
- relaunched the app into incomplete onboarding and confirmed onboarding
UI appeared
- sent `Cmd-W` to the onboarding window and confirmed the dev app
process exited and stayed down
- relaunched into onboarding again, quit the app explicitly, and
confirmed the dev app process exited and stayed down

## Notes
- macOS restart behavior is inferred from
`NSApp.disableRelaunchOnLogin()` / `enableRelaunchOnLogin()`; I did not
reboot or log out the machine to test that path directly.
Auto-generated: consolidates unreleased entries into v0.11.183 and
clears the unreleased array.
## Summary

Fix broken "Notion CRM Example" link in the Integrations documentation
page.

## Background

The link at `docs/doc/developer/apps/Integrations.mdx` points to
`plugins/example/main.py`, which no longer exists.

Commit fff6516 ("Move plugins from plugins/example/ to plugins/")
flattened the plugin directory, moving all files from `plugins/example/`
up one level. The documentation link was not updated in that change,
resulting in a 404.

The previous target (`plugins/example/main.py`, now `plugins/main.py`)
was only a FastAPI router aggregation file — it never contained Notion
CRM logic itself. The actual Notion CRM implementation lives in
`plugins/oauth/conversation_created.py`, which handles the `/notion-crm`
webhook endpoint, OAuth setup, and Notion row creation. This is the file
the documentation intended to reference as a "complete implementation"
example.

## Changes

- **`docs/doc/developer/apps/Integrations.mdx`**: Updated the "Notion
CRM Example" link from `plugins/example/main.py` (404) to
`plugins/oauth/conversation_created.py` (the actual implementation)

## References

- fff6516 - Move plugins from plugins/example/ to plugins/
- 53e3f12 - docs: revamp Omi apps introduction and prompt-based apps
documentation (introduced the current broken link)
- https://docs.omi.me/doc/developer/apps/Integrations#how-it-works
## Summary

When a Deepgram WebSocket connection dies, we now capture and log
**why** — not just that it died. This enables operators to distinguish
DG server closures, network drops, idle timeouts, and billing limits
from Cloud Logging.

### Problem

SafeDeepgramSocket (PR #5944) detects dead connections but swallows the
close reason. The `except Exception` blocks log generic "connection
dead" without the exception type or message. Current prod error rate
(~60/hr at peak) cannot be triaged because all disconnects look the
same.

### Changes

| File | Change |
|------|--------|
| `utils/stt/safe_socket.py` | `death_reason` property +
`set_close_reason()` method. First-reason-wins latch on ALL write paths
(send, keepalive, external close). |
| `utils/stt/streaming.py` | Register `on_close` / `on_error` handlers
on DG connection that feed into `safe_conn.set_close_reason()` |
| `utils/stt/vad_gate.py` | `GatedDeepgramSocket.death_reason` delegates
to SafeDeepgramSocket |
| `routers/transcribe.py` | "DG connection died mid-session" log now
includes `reason=` field |
| `tests/unit/test_streaming_deepgram_backoff.py` | 14 new tests (37
total) for death_reason, set_close_reason, callback wiring, delegation |

### How it works

1. **SafeDeepgramSocket** captures exception details when `send()` or
`keep_alive()` fails:
   - `send ConnectionResetError: Connection reset by peer`
   - `keep_alive TimeoutError: timed out`
   - `send returned False`

2. **DG SDK callbacks** feed close events into SafeDeepgramSocket via
`set_close_reason()`:
   - `DG close event: CloseResponse(type='Close')`
   - `DG error event: ErrorResponse(...)`

3. **First reason wins** — ALL write paths guard with `if
self._death_reason is None`. The first close event is the root cause;
subsequent failures are no-ops.

4. **transcribe.py** includes the reason in the operator-facing log:
   ```
DG connection died mid-session uid=abc session=xyz reason=send
ConnectionResetError: Connection reset by peer
   ```

### Example Cloud Logging queries after deploy

```
# See all disconnect reasons
"DG connection died mid-session" "reason="

# Network issues (code 1006 = abnormal)
"reason=" "ConnectionResetError"

# DG server errors
"reason=" "DG error event"

# Keepalive failures specifically
"reason=" "keep_alive"
```

### Review cycle

- **CODEx review (R1)**: Found first-reason-wins bug —
`send()`/`_send_keepalive_locked()` unconditionally overwrote
`_death_reason`. Fixed with `if None` guard on all write paths.
- **CODEx review (R2)**: Approved (`PR_APPROVED_LGTM`). Thread safety
confirmed, PII risk low.
- **Tester (T1)**: Found 3 coverage gaps: (1) DG callback wiring
untested, (2) gated delegation untested, (3) exception permutations
incomplete.
- **Tester (T2)**: Approved (`TESTS_APPROVED`). All 3 gaps closed with 5
new tests.

### Testing

- 37 tests passing (23 existing + 14 new)
- Coverage: death_reason lifecycle, exception capture, first-reason-wins
matrix (all orderings), DG callback wiring, gated delegation, non-safe
socket fallback

## Deployment

**Services affected**: `backend-listen`
**No env vars needed**
**Risk**: Low — logging-only change, no behavior change

Relates to #5870

_by AI for @beastoin_
## Summary
- **Fixes** #4867, #4669 (umbrella #5733 S1) — Backend sync fails
silently, causing permanent audio loss
- **Backend**: `process_segment()` wrapped in try/except with
thread-safe error collection via `threading.Lock`
- **Backend**: Endpoint returns HTTP 207 (partial failure) or 500 (all
failed) instead of always 200
- **Backend**: Empty Deepgram words treated as error (triggers retry);
empty postprocessed segments treated as warning (skip)
- **Backend**: Segment deduplication (timestamp-based) prevents
duplicate transcripts on retry
- **App**: HTTP 207 parsed alongside 200 — partial failure info logged
for debugging
- **App**: `SyncLocalFilesResponse` extended with `failedSegments`,
`totalSegments`, `errors` fields
- **App**: WALs kept retryable on partial failure (207) instead of
marking synced — failed segments get another chance
- **Backward compatible**: Old clients treat 207 as failure → WALs stay
in miss state → retryable

## Changes

### Backend (`routers/sync.py`)
- `process_segment()`: try/except wrapping entire body, `with lock:`
protecting shared state mutations
- Empty words from Deepgram → error collected (may be Deepgram failure,
not just silence)
- Empty postprocessed segments (words present but no segments) →
warning, not error
- Exceptions caught → error message with context appended to shared
errors list
- Endpoint: creates `segment_lock` + `segment_errors`, passes to all
threads
- Response includes `failed_segments`, `total_segments`, `errors` for
debugging
- HTTP 200 (all succeed), 207 (partial), 500 (all fail)
- Segment dedup via `(round(timestamp, 2), round(end, 2))` set
comparison

### App (`conversations.dart`, `conversation.dart`,
`local_wal_sync.dart`)
- `SyncLocalFilesResponse`: new `failedSegments`, `totalSegments`,
`errors` fields with `hasPartialFailure` getter
- `syncLocalFiles()`: accepts both 200 and 207 status codes, logs
partial failure details
- `syncAll()` + `syncWal()`: on partial failure, keep WALs retryable
(reset sync state) instead of marking synced
- Backend dedup prevents duplicate transcripts when WALs are retried

### Tests (`test_sync_silent_failure.py`)
- 32 tests: structural verification, threading behavior, dedup logic,
behavioral tests with mocked deps
- Test isolation via `setup_class`/`teardown_class` to prevent
sys.modules contamination
- Verifies empty words → error, empty postprocessed → warning, app 207
handling, WAL retry behavior

## Backward Compatibility Matrix

| Client | Server | Behavior |
|--------|--------|----------|
| Old app | New server | 207 treated as failure → WALs retried → safe |
| New app | Old server | Never gets 207 → always 200 path → no change |
| New app | New server | 207 parsed, WALs kept retryable → optimal |

## Test Evidence
```
63 passed, 3 warnings in 0.86s
```
All 32 sync silent failure tests + 31 fair use gate tests pass together
(no isolation issues).

## Risks / Edge Cases
- Silent segments (no speech) now trigger retry via empty-words error
path — dedup prevents duplicates
- `postprocess_words` returning empty with valid words is a legitimate
edge case (all words filtered) — not an error
- Thread count unchanged (one per segment) — lock contention minimal for
typical 1-5 segments

Closes #4867, Closes #4669

## Live Test Evidence

### Backend (curl + local server)
All 3 status codes verified with real opus audio files uploaded to
`/v1/sync-local-files`:
- **200 OK**: Both segments processed by Deepgram, conversation created
- **207 Multi-Status**: 1/2 segments failed (simulated), partial failure
details in response
- **500 Internal Server Error**: All segments failed (simulated), error
details in response

### App (VPS emulator + local backend)
Real opus WALs injected into app, synced via Offline Sync page:

| Case | HTTP | App Behavior | WAL State |
|------|------|-------------|-----------|
| 500 all fail | Server error caught, logged | Pending 2 (retryable) |
| 207 partial | "1 conversations created", partial failure logged |
Pending 2 (retryable) |
| 200 retry | Full success | Synced 11, "All caught up" |

Full screenshots and logs in [PR
comment](#5994 (comment)).

### Flutter Unit Tests
17 tests covering response parsing, HTTP status handling, WAL retry
behavior, and backward compatibility.
```
flutter test test/unit/sync_response_handling_test.dart
00:08 +17: All tests passed!
```
…cKey

Introduces the core types for the WAL audio source architecture:
- AudioSource: abstract class for processing raw audio bytes into WAL-ready frames
- WalFrame: carries headerless audio payload + source-specific sync key
- FrameSyncKey: value type with content-based equality for sync matching

Part of #6056.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
BleDeviceSource implements AudioSource for BLE devices that prepend a
3-byte firmware header [packet_id_low, packet_id_high, packet_index].
Strips header to produce headerless WAL payloads and uses header bytes
as sync key.

Part of #6056.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
PhoneMicSource implements AudioSource for phone mic PCM16 recording.
Buffers variable-sized mic chunks into fixed 320-byte frames (10ms at
16kHz 16-bit mono) with monotonic frame index as sync key.

Part of #6056.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
LocalWalSync now accepts WalFrame via onFrameCaptured() and matches
synced frames via markFrameSynced(FrameSyncKey), replacing the old
onByteStream/onBytesSync raw byte methods. WAL no longer needs to
know about source-specific header formats.

Part of #6056.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
LocalWalSyncImpl now stores WalFrame objects in _frames and extracts
payloads when chunking into Wal. Flush writes payload bytes directly
instead of hardcoding sublist(3) for BLE header stripping. Sync
matching uses FrameSyncKey equality instead of hardcoded 3-byte
comparison.

Part of #6056.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…vider

CaptureProvider now creates BleDeviceSource for Omi/OpenGlass devices
and delegates byte processing, header stripping, and socket payload
extraction to the source. WAL frame capture and sync marking use the
new frame-based API. Inline header knowledge removed from provider.

Fixes #6056.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Tests cover: FrameSyncKey equality, BLE header stripping, BLE sync key
generation, PhoneMicSource frame buffering, frame index wrapping,
flush behavior, socket payload extraction, and codec/device info.

Part of #6056.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@greptile-apps

greptile-apps Bot commented Mar 26, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR refactors audio byte handling by introducing an AudioSource abstraction that encapsulates source-specific concerns (BLE header stripping, phone mic frame buffering) and propagates WalFrame objects with typed FrameSyncKeys into LocalWalSync, replacing the previous raw-byte API (onByteStream/onBytesSync). The BLE path is cleanly wired up; LocalWalSync no longer hard-codes the 3-byte header offset; and 19 new unit tests cover the new classes thoroughly.\n\nKey findings:\n- PhoneMicSource is fully implemented and tested but never instantiated in production code — CaptureProvider.streamRecording() (the phone mic path) still sends raw bytes straight to the WebSocket with no AudioSource involvement and no WAL integration. The stated goal of making phone mic a "first-class audio capturing device" is incomplete.\n- AudioSource.flush() — documented as "called when recording stops to capture remaining partial data" — is never invoked anywhere in CaptureProvider. _cleanupCurrentState() simply nulls _activeSource without flushing. For BleDeviceSource this is harmless today, but the contract violation means buffered tail bytes would be silently lost if PhoneMicSource is wired up.\n- Minor: FrameSyncKey's primary constructor does not enforce list immutability, unlike both factory constructors.

Confidence Score: 3/5

Safe to merge for BLE-only users today, but two logic gaps (missing flush() call and unwired PhoneMicSource) should be resolved before the phone mic path is extended.

The BLE path is correctly refactored, existing tests pass, and WAL behaviour is functionally equivalent. However, PhoneMicSource is dead code and flush() is never called — both are gaps in the stated goal of the PR that would cause silent data loss if the phone mic path is extended without addressing them.

app/lib/providers/capture_provider.dart — missing flush() call in _cleanupCurrentState and missing PhoneMicSource instantiation in streamRecording()

Important Files Changed

Filename Overview
app/lib/providers/capture_provider.dart Wires BleDeviceSource into the BLE audio path correctly, but never calls flush() before teardown and never instantiates PhoneMicSource for the phone-mic path.
app/lib/services/audio_sources/audio_source.dart Clean abstraction; minor inconsistency in FrameSyncKey where primary constructor allows a mutable backing list unlike the factory constructors.
app/lib/services/audio_sources/ble_device_source.dart Correct header-stripping and sync-key extraction; flush() is a no-op as expected for a non-buffering source.
app/lib/services/audio_sources/phone_mic_source.dart Implementation is correct but dead code — never imported or used in production; flush() logic would lose buffered bytes because the call site in CaptureProvider is missing.
app/lib/services/wals/local_wal_sync.dart Cleanly migrated to WalFrame/FrameSyncKey; flush no longer strips 3-byte header (correctly removed), sync matching simplified via equality operator.
app/lib/services/wals/wal_interfaces.dart Interface cleanly updated; onByteStream/onBytesSync replaced with well-documented onFrameCaptured/markFrameSynced.
app/test/unit/audio_source_test.dart 19 new unit tests providing good coverage of FrameSyncKey equality, BLE header stripping, phone mic frame buffering, sync key wrapping, flush padding, and codec/device info.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    BLE["BLE Audio Bytes\n(onAudioBytesReceived)"] --> SA["_activeSource\n(BleDeviceSource)"]
    SA --> PP["processBytes(snapshot)\n→ List&lt;WalFrame&gt;"]
    SA --> SP["getSocketPayload(snapshot)\n→ headerless bytes"]
    PP --> WAL{"_isWalSupported?"}
    WAL -- yes --> WC["onFrameCaptured(frame)"]
    WAL -- no --> DISC1["frames discarded"]
    SP --> WS["WebSocket.send()"]
    WS --> MS{"_isWalSupported?"}
    MS -- yes --> MF["markFrameSynced(frame.syncKey)"]
    MS -- no --> DISC2["no-op"]

    MIC["Phone Mic Bytes\n(streamRecording)"] --> DIRECT["_socket?.send(bytes)\n(NO AudioSource)"]
    DIRECT --> WS2["WebSocket.send()"]

    FLUSH["_cleanupCurrentState()"] --> NULL["_activeSource = null\n⚠️ flush() NOT called"]

    style MIC fill:#ffe0b2
    style DIRECT fill:#ffe0b2
    style NULL fill:#ffcccc
    style FLUSH fill:#ffcccc
Loading

Reviews (1): Last reviewed commit: "test(app): add 19 tests for AudioSource,..." | Re-trigger Greptile

Comment thread app/lib/providers/capture_provider.dart Outdated
Comment on lines 717 to 720
_activeSource = null;
await _closeBleStream();
notifyListeners();
}

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.

P1 AudioSource.flush() never called before teardown

_cleanupCurrentState() nulls out _activeSource without calling flush() first. The AudioSource interface explicitly documents flush() as "Called when recording stops to capture remaining partial data."

For BleDeviceSource this is harmless today (flush() returns []). But PhoneMicSource.flush() pads and emits whatever bytes remain in _buffer — if PhoneMicSource is ever wired up, silently discarding those buffered bytes would cause audio loss at the end of every recording session. The calling contract should be honoured now while it is easy to do:

Suggested change
_activeSource = null;
await _closeBleStream();
notifyListeners();
}
Future _cleanupCurrentState() async {
// Flush any remaining buffered bytes before tearing down the source
if (_activeSource != null && _isWalSupported) {
for (final frame in _activeSource!.flush()) {
_wal.getSyncs().phone.onFrameCaptured(frame);
}
}
_activeSource = null;
await _closeBleStream();
notifyListeners();
}

Comment on lines +1 to +15
import 'package:omi/backend/schema/bt_device/bt_device.dart';
import 'package:omi/services/audio_sources/audio_source.dart';

/// Audio source for the phone's built-in microphone.
///
/// Phone mic records PCM16 audio at 16kHz mono. Raw bytes arrive in
/// variable-sized chunks from the platform microphone API. This source
/// buffers incoming bytes and splits them into fixed 320-byte frames
/// (10ms at 16kHz, 16-bit mono = 160 samples x 2 bytes).
///
/// Each frame gets a monotonic index (0-255 wrapping) as its sync key.
class PhoneMicSource implements AudioSource {
/// Fixed frame size: 10ms at 16kHz, 16-bit mono = 320 bytes.
static const int frameSize = 320;

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.

P1 PhoneMicSource is dead code — never instantiated in production

PhoneMicSource is fully implemented and tested, but it is imported nowhere in app/lib/ outside its own file. The streamRecording() path in CaptureProvider (line 984-1011) still sends bytes directly to the WebSocket without creating an AudioSource:

// capture_provider.dart – streamRecording() – unchanged by this PR
await ServiceManager.instance().mic.start(
  onByteReceived: (bytes) {
    if (_socket?.state == SocketServiceState.connected) {
      _socket?.send(bytes);          // ← no _activeSource, no WAL
    }
  },
  ...
);

_activeSource is only ever assigned a BleDeviceSource (line 796) — never a PhoneMicSource. The PR description states phone mic should be "a first-class audio capturing device with shared WAL integration," but that integration was not wired up. Either the phone mic path needs to be updated to create a PhoneMicSource and route bytes through it, or the class should be clearly marked as a future placeholder.

Comment on lines +16 to +18
class FrameSyncKey {
final List<int> bytes;

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 FrameSyncKey primary constructor does not enforce immutability

The two factory constructors both wrap their lists with List<int>.unmodifiable(...), but the primary constructor stores the caller's list as-is. A caller who mutates the backing list after construction silently changes the key's identity, which would break equality and hash-map lookups.

Suggested change
class FrameSyncKey {
final List<int> bytes;
FrameSyncKey(List<int> bytes) : bytes = List<int>.unmodifiable(bytes);

beastoin and others added 7 commits March 26, 2026 08:24
…ayload

Packets with only header bytes (<=3) should produce empty payload, not
forward header bytes as audio data. Matches prior behavior where
sublist(3) on a 3-byte packet returned empty.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Short BLE packets now correctly expect empty payload. Added WAL
compatibility test proving processBytes payload matches old sublist(3)
behavior for identical on-disk format.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
… serialization

Cover tester-identified gaps: markFrameSynced with duplicate keys and
no-match, onFrameCaptured ordering, WAL binary format with headerless
payloads, and chunk payload extraction from WalFrame.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Expose testFrames, testFrameSynced, and testWals for unit test access
to internal frame state.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…eation

WAL payloads are now headerless after AudioSource refactor, so
_createTempFileFromMemoryData must write wal.data[i] directly instead
of stripping another 3 bytes.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Prevents race where in-flight BLE packets bypass AudioSource and send
raw firmware header bytes to the socket.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
1-byte index wraps safely because _chunk drains frames every ~75s,
well within the 256-frame window at 100 fps.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@beastoin

Copy link
Copy Markdown
Collaborator Author

Review fixes applied:

  • High fix: Removed double sublist(3) in audio_player_utils.dart — WAL payloads are now headerless, so temp file creation writes them directly without stripping additional bytes.
  • Medium fix: Reordered _cleanupCurrentState() to close BLE stream before nulling _activeSource, preventing race where in-flight packets bypass AudioSource.
  • Medium (accepted risk): Phone mic 1-byte sync key wrapping is safe — _chunk drains every ~75s, well within the 256-frame window at 100fps. Added documenting comment.

All 287 tests pass (1 pre-existing env_test failure on main).


by AI for @beastoin

Verify that headerless payloads are serialized correctly and that the
old buggy sublist(3) would have corrupted them.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@beastoin

Copy link
Copy Markdown
Collaborator Author

All checkpoints passed — PR is ready for merge.

  • CP7: Reviewer approved (2 rounds — fixed double sublist(3) bug and cleanup race)
  • CP8: Tester approved (36 unit tests covering all changed paths)
  • CP9A: Dev APK built and launched on emulator — no crashes
  • CP9B: App running with API connection — no runtime errors in logcat

by AI for @beastoin

@beastoin
beastoin changed the base branch from main to fix/phone-mic-wal-offline-5913 March 26, 2026 09:04
@beastoin
beastoin merged commit 3dd6df8 into fix/phone-mic-wal-offline-5913 Mar 26, 2026
2 checks passed
@beastoin
beastoin deleted the refactor/wal-audio-source-6056 branch March 26, 2026 09:08
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.

refactor(app): extract WAL logic from CaptureProvider, unify audio source abstraction

7 participants