Repository navigation
fix(app): reconnect onboarding's socket and complete it despite a failed speech-profile upload - #11704
Conversation
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
There was a problem hiding this comment.
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 reconnectFutureto 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 fakeconnect(), so it never exercises the_reconnectingoverlap path the fix depends on; this leaves the main race condition vulnerable to regression — makeconnect()asynchronous and assert overlapping reconnect attempts are ignored. - In
app/test/providers/speech_profile_provider_test.dart, the “profile already completed” test setsprofileCompletedbeforeonClosed, 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 fromonClosed.
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); |
There was a problem hiding this comment.
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)); |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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>
|
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:
Two non-blocking polish notes for a follow-up (the first echoes what cubic found):
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 |
kodjima33
left a comment
There was a problem hiding this comment.
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
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
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
…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
…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
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):
The onboarding websocket had no reconnect.
/v4/listensessions inonboarding=enabledmode drop periodically (confirmed independent of any connected pendant). Once dropped,SpeechProfileProvider.skipCurrentQuestion()and outgoing mic audio are both gated on_socket?.state == connectedand 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.darthad zero reconnect logic for this socket, unlikeCaptureProvider._startKeepAliveServices, which already has this pattern for the main recording socket.finalize()'s upload-failure branch never completed onboarding. The comment said "Upload failed - notify user but still process conversation", and conversation processing did proceed — butprofileCompletedwas never set. The "All Done" continue button in bothspeech_profile_widget.dartandspeech_profile/page.dartis gated on exactly that field. Since the speech-profile upload fails on every local-harness run (BUCKET_SPEECH_PROFILESunconfigured 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
SpeechProfileProvidernow 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). BecauseOnboardingHandler(backend) keeps no state across connections, a successful reconnect resets the local question index to match the server restarting from the top.completeAfterUploadFailure(), which now setsprofileCompleted = trueon both theTOO_SHORTand genericUPLOAD_FAILEDpaths (matching the success path, minushasSpeakerProfile = truesince no profile was actually saved).lateon 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 fullinitialise()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 analyzeclean on both changed files.backend.logcorrelated to the exact run: a single onboarding websocket session start-to-finish,/v3/upload-audiostill 500s (expected — harness gap, unrelated to this fix), butprocess_conversation completed/POST /v1/conversations 200 OKfollowed by normal app traffic, proving the app moved past onboarding despite the upload failure./v4/listenconnection inbackend.logimmediately after areason=disconnect).Product invariants
None — no locked invariant path globs touched (
scripts/pr-preflight --suggestconfirms).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.