Skip to content

fix(app): reconnect onboarding's socket and complete it despite a failed speech-profile upload - #11704

Merged
kodjima33 merged 2 commits into
BasedHardware:mainfrom
formed2forge:fix/onboarding-socket-reconnect
Aug 17, 2026
Merged

kodjima33 merged 2 commits into
BasedHardware:mainfrom
formed2forge:fix/onboarding-socket-reconnect

Conversation

@formed2forge

@formed2forge formed2forge commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Two independent bugs were trapping users on the last onboarding question, verified live against the local dev harness (Omi CV1 + Limitless Pendant + phone mic):

  1. The onboarding websocket had no reconnect. /v4/listen sessions in onboarding=enabled mode drop periodically (confirmed independent of any connected pendant). Once dropped, SpeechProfileProvider.skipCurrentQuestion() and outgoing mic audio are both gated on _socket?.state == connected and silently became permanent no-ops — matching the reported symptom exactly: spoke an answer, saw the transcription, screen never advanced, and "Skip this question" did nothing. pure_socket.dart / transcription_service.dart had zero reconnect logic for this socket, unlike CaptureProvider._startKeepAliveServices, which already has this pattern for the main recording socket.

  2. finalize()'s upload-failure branch never completed onboarding. The comment said "Upload failed - notify user but still process conversation", and conversation processing did proceed — but profileCompleted was never set. The "All Done" continue button in both speech_profile_widget.dart and speech_profile/page.dart is gated on exactly that field. Since the speech-profile upload fails on every local-harness run (BUCKET_SPEECH_PROFILES unconfigured there — filed separately as a harness gap, not part of this fix), every onboarding run that reached the last question was silently trapped, independent of bug 1.

Fixes

  • SpeechProfileProvider now retries the onboarding socket on a 5s interval after a drop, guarded against overlapping in-flight attempts (same class of race as iOS transcription reconnect timer can start overlapping WebSocket attempts #11305). Because OnboardingHandler (backend) keeps no state across connections, a successful reconnect resets the local question index to match the server restarting from the top.
  • Extracted the upload-failure handling into completeAfterUploadFailure(), which now sets profileCompleted = true on both the TOO_SHORT and generic UPLOAD_FAILED paths (matching the success path, minus hasSpeakerProfile = true since no profile was actually saved).
  • Small adjacent cleanup: dropped a stray late on two nullable callback fields (_finalizedCallback, _processConversationCallback) that don't need it (already null-checked everywhere they're read) — it was blocking the provider from being constructed in a test without the full initialise() flow.

Test plan

  • flutter test test/providers/speech_profile_provider_test.dart — 4 new tests: reconnect-after-drop, no-reconnect-once-completed, complete-on-upload-failure, complete-on-too-short-audio. All pass.
  • flutter analyze clean on both changed files.
  • Verified live on device against the local dev harness: fresh onboarding run through all 6 questions, reached the app's own Profile settings screen. Confirmed via backend.log correlated to the exact run: a single onboarding websocket session start-to-finish, /v3/upload-audio still 500s (expected — harness gap, unrelated to this fix), but process_conversation completed / POST /v1/conversations 200 OK followed by normal app traffic, proving the app moved past onboarding despite the upload failure.
  • Reconnect path exercised live in an earlier run (socket dropped and successfully recovered mid-onboarding, confirmed via a fresh /v4/listen connection in backend.log immediately after a reason=disconnect).

Product invariants

None — no locked invariant path globs touched (scripts/pr-preflight --suggest confirms).

Failure class

Failure-Class: none

Both are first-observed, independent instance fixes in this subsystem — no existing failure-class in .github/failure-classes/ matches either shape, and neither has a second prior occurrence in this codebase to warrant registering a new one now.

Review in cubic

Onboarding's /v4/listen websocket had no reconnect logic at all: once it
dropped mid-flow (observed live against the local dev harness, reproduced
twice), both live mic audio and skipCurrentQuestion() are gated on
`_socket?.state == connected` (transcription_service.dart) and silently
became permanent no-ops, requiring a full app relaunch to unstick onboarding.

Mirrors CaptureProvider's existing keep-alive pattern: retry on a 5s interval
until reconnected, guarded against overlapping in-flight attempts (the same
class of bug as BasedHardware#11305). The backend's OnboardingHandler keeps no state
across connections, so a successful reconnect resets the local question
index to match the server restarting from the top rather than showing a
stale question.

Failure-Class: none
finalize()'s upload-failure branch commented "still process conversation"
but never set profileCompleted, so the "All Done" continue button (gated on
provider.profileCompleted in both speech_profile_widget.dart and
speech_profile/page.dart) never appeared. Any user hitting a speech-profile
upload failure on the last onboarding question was trapped there permanently
with no way forward — reproduced live against the local dev harness, whose
BUCKET_SPEECH_PROFILES is unconfigured so every upload 500s.

Extracted the upload-failure handling into completeAfterUploadFailure() so
it's directly testable without a real (opus-decoder-backed) WavBytesUtil.
Also drops a stray `late` on two nullable callback fields that are already
null-checked everywhere they're read — unrelated to production behavior,
but it was blocking the provider from being constructed in a test without
going through the full initialise() flow first.

Failure-Class: none

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

3 issues found across 2 files

Confidence score: 2/5

  • In app/lib/providers/speech_profile_provider.dart, close()/dispose() can still allow an in-flight reconnect Future to continue and reattach a socket after teardown, which risks resurrecting subscriptions and leaking resources in a disposed provider — add a post-await disposal/closed guard (or cancellation token) before installing/subscribing the socket.
  • In app/test/providers/speech_profile_provider_test.dart, the reconnect test uses a synchronously completing fake connect(), so it never exercises the _reconnecting overlap path the fix depends on; this leaves the main race condition vulnerable to regression — make connect() asynchronous and assert overlapping reconnect attempts are ignored.
  • In app/test/providers/speech_profile_provider_test.dart, the “profile already completed” test sets profileCompleted before onClosed, so it doesn’t validate the intended timing-sensitive behavior and can give false confidence about reconnect suppression — restructure the setup to match the real sequence and verify no reconnect is scheduled from onClosed.

You’re at about 90% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].

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/speech_profile_provider.dart">

<violation number="1" location="app/lib/providers/speech_profile_provider.dart:569">
P1: When `close()` or `dispose()` runs while a reconnect attempt is awaiting connection, cancelling `_reconnectTimer` does not cancel the in-flight future. The continuation can install and subscribe a new socket after teardown, then call `notifyListeners()` on a disposed provider; add a session-generation or closed guard after the await and stop any late-created socket.</violation>
</file>

<file name="app/test/providers/speech_profile_provider_test.dart">

<violation number="1" location="app/test/providers/speech_profile_provider_test.dart:153">
P3: Test 1 exercises reconnect success but never the `_reconnecting` in-flight overlap guard, which the PR cites as the main fix (mirroring #11305). `_FakeConnectedSocket` completes `connect()` synchronously, so `_initiateWebsocket` resolves within the same timer tick and `_reconnecting` is never true when the next 5s tick fires — the guard's branch is dead in this test. Add a slow fake whose `openSpeechProfileSocket` returns a delayed/suspended socket and elapse two 5s ticks to assert only one socket is opened while the first attempt is still in flight.</violation>

<violation number="2" location="app/test/providers/speech_profile_provider_test.dart:165">
P3: Test 2 ("does not schedule a reconnect once the profile is already completed") does not exercise the behavior its name and the PR describe. It sets `provider.profileCompleted = true` before calling `onClosed`, so `onClosed`'s guard (`startedRecording && !profileCompleted && !uploadingProfile`) short-circuits and `_scheduleReconnect()` is never invoked. The dangerous scenario — a 5s reconnect timer already scheduled from a mid-onboarding drop, then the profile completing — is left untested, so neither the timer's `if (profileCompleted || ...) timer.cancel()` guard nor the `_reconnectTimer?.cancel()` in the completion paths is verified. To cover the intended regression, schedule the reconnect first (e.g. `onClosed` while incomplete) and only then set `profileCompleted` (or drive `finalize`), then elapse past a reconnect tick and assert `openCalls == 0`.</violation>
</file>

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

Re-trigger cubic

Logger.debug('Speech profile socket reconnect attempt');
try {
if (usePhoneMic) {
await _initiateWebsocket(codec: BleAudioCodec.pcm16, sampleRate: 16000, force: true);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: When close() or dispose() runs while a reconnect attempt is awaiting connection, cancelling _reconnectTimer does not cancel the in-flight future. The continuation can install and subscribe a new socket after teardown, then call notifyListeners() on a disposed provider; add a session-generation or closed guard after the await and stop any late-created socket.

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

<comment>When `close()` or `dispose()` runs while a reconnect attempt is awaiting connection, cancelling `_reconnectTimer` does not cancel the in-flight future. The continuation can install and subscribe a new socket after teardown, then call `notifyListeners()` on a disposed provider; add a session-generation or closed guard after the await and stop any late-created socket.</comment>

<file context>
@@ -481,9 +531,60 @@ class SpeechProfileProvider extends ChangeNotifier
+      Logger.debug('Speech profile socket reconnect attempt');
+      try {
+        if (usePhoneMic) {
+          await _initiateWebsocket(codec: BleAudioCodec.pcm16, sampleRate: 16000, force: true);
+        } else if (device != null) {
+          final codec = await _getAudioCodec(device!.id);
</file context>

// The fake socket reports connected immediately, so the periodic
// timer must stop rather than opening a second socket on the next
// tick.
async.elapse(const Duration(seconds: 15));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: Test 1 exercises reconnect success but never the _reconnecting in-flight overlap guard, which the PR cites as the main fix (mirroring #11305). _FakeConnectedSocket completes connect() synchronously, so _initiateWebsocket resolves within the same timer tick and _reconnecting is never true when the next 5s tick fires — the guard's branch is dead in this test. Add a slow fake whose openSpeechProfileSocket returns a delayed/suspended socket and elapse two 5s ticks to assert only one socket is opened while the first attempt is still in flight.

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

<comment>Test 1 exercises reconnect success but never the `_reconnecting` in-flight overlap guard, which the PR cites as the main fix (mirroring #11305). `_FakeConnectedSocket` completes `connect()` synchronously, so `_initiateWebsocket` resolves within the same timer tick and `_reconnecting` is never true when the next 5s tick fires — the guard's branch is dead in this test. Add a slow fake whose `openSpeechProfileSocket` returns a delayed/suspended socket and elapse two 5s ticks to assert only one socket is opened while the first attempt is still in flight.</comment>

<file context>
@@ -0,0 +1,207 @@
+        // The fake socket reports connected immediately, so the periodic
+        // timer must stop rather than opening a second socket on the next
+        // tick.
+        async.elapse(const Duration(seconds: 15));
+        expect(provider.openCalls, 1, reason: 'timer must stop once reconnected, not keep firing');
+
</file context>

final provider = _CountingSpeechProfileProvider();
provider.usePhoneMic = true;
provider.updateStartedRecording(true);
provider.profileCompleted = true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: Test 2 ("does not schedule a reconnect once the profile is already completed") does not exercise the behavior its name and the PR describe. It sets provider.profileCompleted = true before calling onClosed, so onClosed's guard (startedRecording && !profileCompleted && !uploadingProfile) short-circuits and _scheduleReconnect() is never invoked. The dangerous scenario — a 5s reconnect timer already scheduled from a mid-onboarding drop, then the profile completing — is left untested, so neither the timer's if (profileCompleted || ...) timer.cancel() guard nor the _reconnectTimer?.cancel() in the completion paths is verified. To cover the intended regression, schedule the reconnect first (e.g. onClosed while incomplete) and only then set profileCompleted (or drive finalize), then elapse past a reconnect tick and assert openCalls == 0.

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

<comment>Test 2 ("does not schedule a reconnect once the profile is already completed") does not exercise the behavior its name and the PR describe. It sets `provider.profileCompleted = true` before calling `onClosed`, so `onClosed`'s guard (`startedRecording && !profileCompleted && !uploadingProfile`) short-circuits and `_scheduleReconnect()` is never invoked. The dangerous scenario — a 5s reconnect timer already scheduled from a mid-onboarding drop, then the profile completing — is left untested, so neither the timer's `if (profileCompleted || ...) timer.cancel()` guard nor the `_reconnectTimer?.cancel()` in the completion paths is verified. To cover the intended regression, schedule the reconnect first (e.g. `onClosed` while incomplete) and only then set `profileCompleted` (or drive `finalize`), then elapse past a reconnect tick and assert `openCalls == 0`.</comment>

<file context>
@@ -0,0 +1,207 @@
+        final provider = _CountingSpeechProfileProvider();
+        provider.usePhoneMic = true;
+        provider.updateStartedRecording(true);
+        provider.profileCompleted = true;
+
+        provider.onClosed(1000);
</file context>

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified both diagnoses against the code at this head — they hold up, and the fixes match existing patterns in the codebase. Nice investigation, especially correlating the harness backend.log to prove the flow completed.

What I checked:

  • Reconnect gap is real: skipCurrentQuestion() and both mic-audio forwarding sites in speech_profile_provider.dart are gated on _socket?.state == SocketServiceState.connected, and this socket had no reconnect path at all — so a dropped /v4/listen onboarding session dead-ended the flow until app relaunch, exactly as described.
  • _scheduleReconnect() mirrors CaptureProvider._startKeepAliveServices (capture_controller.dart), including the in-flight guard against overlapping attempts. Cancelling the timer from onConnected(), both completion paths, close(), and dispose() covers the lifecycle.
  • The question-index reset on reconnect is correct for the backend: OnboardingHandler is constructed fresh per websocket (backend/routers/listen/runtime.py), so the server restarts the sequence from the top — resetting locally avoids showing a stale question.
  • Upload-failure trap is real: the old branch never set profileCompleted, and the All Done continue button is gated on exactly that field in both onboarding/speech_profile_widget.dart and speech_profile/page.dart. completeAfterUploadFailure() now mirrors the success path (minus hasSpeakerProfile = true, which is right since nothing was saved).
  • Dropping late from _finalizedCallback/_processConversationCallback is safe — both are assigned in initialise() and null-checked at every read.
  • The @visibleForTesting seams (openSpeechProfileSocket, uploadSpeechProfile) route production through the same service calls as before, so they're test-only hooks with no behavior change — same pattern the capture-provider tests already use.

Two non-blocking polish notes for a follow-up (the first echoes what cubic found):

  1. Teardown race: if close()/dispose() runs while a reconnect attempt is mid-await, cancelling _reconnectTimer doesn't cancel the in-flight future — the continuation can still install/subscribe a socket and notifyListeners() on a torn-down provider. A generation counter or disposed check after the await would close it. Worth noting the existing capture keep-alive has the same shape, so this is parity, not a regression.
  2. Test hardening: the reconnect test's fake socket connects synchronously, so the _reconnecting overlap guard is never actually exercised; and the already-completed test sets profileCompleted before onClosed(), so it validates the entry guard rather than the timer's own cancel path. A slow-connecting fake and a schedule-then-complete sequence would pin down both.

Neither blocks this. Thanks for the clear commit messages and the live harness verification — left for routine maintainer sign-off 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 flutter flutter work positive-signal Automation verified a genuine fix/quality contribution labels Aug 16, 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.

onboarding /v4/listen socket now reconnects (mirroring CaptureProvider's keep-alive) and a failed voice-print upload completes onboarding instead of trapping the user on the last question; both covered by new provider tests

@kodjima33
kodjima33 merged commit 97fac1e into BasedHardware:main Aug 17, 2026
37 of 38 checks passed
igor-popov-dev added a commit to igor-popov-dev/omi that referenced this pull request Aug 22, 2026
closeCode 1011 with no captured speech means the STT backend is down,
not a transient socket hiccup. The onboarding reconnect loop (added in
BasedHardware#11704) kept retrying it every 5s forever, repeatedly popping the
"Connection Lost" dialog with no way out besides force-quitting, even
though "Skip for now" sits right next to it in the same flow.
After 3 consecutive 1011 closes with zero user segments, give up
reconnecting and surface a distinct STT_UNAVAILABLE error so the
onboarding widget can route to the existing skip path instead.

Failure-Class: none
igor-popov-dev added a commit to igor-popov-dev/omi that referenced this pull request Aug 22, 2026
closeCode 1011 with no captured speech means the STT backend is down,
not a transient socket hiccup. The onboarding reconnect loop (added in
BasedHardware#11704) kept retrying it every 5s forever, repeatedly popping the
"Connection Lost" dialog with no way out besides force-quitting, even
though "Skip for now" sits right next to it in the same flow.
After 3 consecutive 1011 closes with zero user segments, give up
reconnecting and surface a distinct STT_UNAVAILABLE error so the
onboarding widget can route to the existing skip path instead.

Failure-Class: none
kodjima33 pushed a commit that referenced this pull request Aug 23, 2026
…ead (#12070)

closeCode 1011 with no captured speech means the STT backend is down,
not a transient socket hiccup. The onboarding reconnect loop (added in
#11704) kept retrying it every 5s forever, repeatedly popping the
"Connection Lost" dialog with no way out besides force-quitting, even
though "Skip for now" sits right next to it in the same flow.
After 3 consecutive 1011 closes with zero user segments, give up
reconnecting and surface a distinct STT_UNAVAILABLE error so the
onboarding widget can route to the existing skip path instead.

Failure-Class: none
formed2forge pushed a commit to formed2forge/omi that referenced this pull request Aug 24, 2026
…ead (BasedHardware#12070)

closeCode 1011 with no captured speech means the STT backend is down,
not a transient socket hiccup. The onboarding reconnect loop (added in
BasedHardware#11704) kept retrying it every 5s forever, repeatedly popping the
"Connection Lost" dialog with no way out besides force-quitting, even
though "Skip for now" sits right next to it in the same flow.
After 3 consecutive 1011 closes with zero user segments, give up
reconnecting and surface a distinct STT_UNAVAILABLE error so the
onboarding widget can route to the existing skip path instead.

Failure-Class: none
@cursor
cursor Bot deleted the fix/onboarding-socket-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

flutter flutter work positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants