From f16277eb3e4a424951107930eac59be5c7fceb20 Mon Sep 17 00:00:00 2001 From: Hiroshi Horie <548776+hiroshihorie@users.noreply.github.com> Date: Fri, 18 Sep 2026 23:31:38 +0800 Subject: [PATCH 1/6] fix: keep the pre-connect audio buffer through a region failover on connect When the first connect attempt fails, the engine reports a disconnect before Room.connect retries another region. The Room handled that disconnect like any other and reset the pre-connect audio buffer, so the retry connected without a recording buffer and the join response found nothing to publish. The participant ended up in the room with no microphone until they toggled it, even though they had joined unmuted. Track whether Room.connect is running and leave the buffer alone when the disconnect belongs to a connect attempt. A connect that fails for good still ends with the caller's own cleanup, and a disconnect outside of a connect attempt still resets the buffer. Tests: a failover where the first socket connect fails and the validate call answers 403 now keeps the buffer recording, and a server initiated leave still resets it. Adds small test hooks for the region provider, the buffer's recording state, the HTTP client and a fail-once websocket mock. --- lib/src/core/room.dart | 26 ++++- .../preconnect/pre_connect_audio_buffer.dart | 10 ++ lib/src/support/http_client.dart | 9 +- test/core/preconnect_failover_test.dart | 100 ++++++++++++++++++ test/mock/websocket_mock.dart | 8 ++ 5 files changed, 149 insertions(+), 4 deletions(-) create mode 100644 test/core/preconnect_failover_test.dart diff --git a/lib/src/core/room.dart b/lib/src/core/room.dart index 7f5c592f6..d6077211a 100644 --- a/lib/src/core/room.dart +++ b/lib/src/core/room.dart @@ -133,6 +133,19 @@ class Room extends DisposableChangeNotifier with EventsEmittable { late EventsListener _signalListener; RegionUrlProvider? _regionUrlProvider; + + /// True while [connect] is running. A failed attempt tears the engine down + /// and reports a disconnect before [connect] retries another region, and + /// that cleanup must not throw away state the retry still needs. + bool _connectInProgress = false; + + /// Lets tests install a provider with known regions, so a failover can be + /// exercised without reaching a real LiveKit Cloud endpoint. + @visibleForTesting + set regionUrlProviderForTesting(RegionUrlProvider? provider) { + _regionUrlProvider = provider; + } + String? _regionUrl; // Agents @@ -368,6 +381,7 @@ class Room extends DisposableChangeNotifier with EventsEmittable { await NativeAudioManagement.start(); var didConnect = false; + _connectInProgress = true; try { await engine.connect( _regionUrl ?? url, @@ -407,6 +421,7 @@ class Room extends DisposableChangeNotifier with EventsEmittable { rethrow; } } finally { + _connectInProgress = false; if (!didConnect) { await NativeAudioManagement.stop(); } @@ -676,7 +691,10 @@ class Room extends DisposableChangeNotifier with EventsEmittable { // pending one when it starts. if ((!engine.fullReconnectOnNext && !engine.isFullReconnectInProgress) || event.reason == DisconnectReason.clientInitiated) { - await _cleanUp(disposeLocalParticipant: false); + // A failed first attempt lands here before connect() retries another + // region. The pre-connect audio buffer has to survive that, or the + // retry connects without ever publishing the microphone. + await _cleanUp(disposeLocalParticipant: false, preservePreConnectAudio: _connectInProgress); events.emit(RoomDisconnectedEvent(reason: event.reason)); notifyListeners(); } @@ -1133,7 +1151,7 @@ class Room extends DisposableChangeNotifier with EventsEmittable { extension RoomPrivateMethods on Room { // resets internal state to a re-usable state - Future _cleanUp({bool disposeLocalParticipant = true}) async { + Future _cleanUp({bool disposeLocalParticipant = true, bool preservePreConnectAudio = false}) async { logger.fine('[${objectId}] cleanUp()'); // Fail any open data streams so their handlers return rather than awaiting a reader that will @@ -1161,7 +1179,9 @@ extension RoomPrivateMethods on Room { _activeSpeakers.clear(); - await preConnectAudioBuffer.reset(); + if (!preservePreConnectAudio) { + await preConnectAudioBuffer.reset(); + } // clean up engine await engine.cleanUp(); diff --git a/lib/src/preconnect/pre_connect_audio_buffer.dart b/lib/src/preconnect/pre_connect_audio_buffer.dart index b2994b170..e513074e2 100644 --- a/lib/src/preconnect/pre_connect_audio_buffer.dart +++ b/lib/src/preconnect/pre_connect_audio_buffer.dart @@ -14,6 +14,8 @@ import 'dart:async'; +import 'package:meta/meta.dart'; + import 'package:uuid/uuid.dart'; import '../audio/audio_frame_capture.dart'; @@ -108,6 +110,14 @@ class PreConnectAudioBuffer { /// Requires microphone permission. On iOS/macOS it is requested here while /// the app is in the foreground. Throws a [TrackCreateException] when it is /// denied or cannot be requested (app not in the foreground). + /// Puts the buffer into its recording state without touching the + /// microphone, so tests can check what the Room does with a live buffer + /// where no audio device exists. + @visibleForTesting + void markRecordingForTesting() { + _isRecording = true; + } + Future startRecording({ Duration timeout = const Duration(seconds: 20), }) async { diff --git a/lib/src/support/http_client.dart b/lib/src/support/http_client.dart index 22f5c1a22..8518b36d3 100644 --- a/lib/src/support/http_client.dart +++ b/lib/src/support/http_client.dart @@ -13,11 +13,18 @@ // limitations under the License. import 'package:http/http.dart' as http; +import 'package:meta/meta.dart'; import '../options.dart'; import 'http_client/io.dart' if (dart.library.js_interop) 'http_client/web.dart' as impl; -http.Client createSdkHttpClient(NetworkOptions networkOptions) => impl.createSdkHttpClient(networkOptions); +/// Replaces the HTTP client the SDK builds, so tests can answer the requests +/// the SDK makes on its own, such as the validate call after a failed connect. +@visibleForTesting +http.Client Function(NetworkOptions networkOptions)? sdkHttpClientFactoryForTesting; + +http.Client createSdkHttpClient(NetworkOptions networkOptions) => + sdkHttpClientFactoryForTesting?.call(networkOptions) ?? impl.createSdkHttpClient(networkOptions); Future sdkHttpGet( Uri uri, { diff --git a/test/core/preconnect_failover_test.dart b/test/core/preconnect_failover_test.dart new file mode 100644 index 000000000..b9461997c --- /dev/null +++ b/test/core/preconnect_failover_test.dart @@ -0,0 +1,100 @@ +// Copyright 2026 LiveKit, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +@Timeout(Duration(seconds: 10)) +library; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:livekit_client/livekit_client.dart'; +import 'package:livekit_client/src/proto/livekit_models.pb.dart' as lk_models; +import 'package:livekit_client/src/proto/livekit_rtc.pb.dart' as lk_rtc; +import 'package:livekit_client/src/support/http_client.dart'; +import 'package:livekit_client/src/support/region_url_provider.dart'; +import 'package:livekit_client/src/support/websocket.dart'; + +import '../mock/e2e_container.dart'; + +const cloudUri = 'wss://test.livekit.cloud'; +const token = 'token'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late E2EContainer container; + + setUp(() { + container = E2EContainer(); + // After a failed socket connect the SDK validates the token over HTTP. A + // 403 there is how LiveKit Cloud signals that the project is not served + // from that region, and it is the case that fails over to another region. + sdkHttpClientFactoryForTesting = (_) => + MockClient((request) async => http.Response('project not allowed in this region.', 403)); + }); + + tearDown(() async { + sdkHttpClientFactoryForTesting = null; + await container.dispose(); + }); + + test('pre-connect audio buffer survives a region failover on the first attempt', () async { + final room = container.room; + + // Known regions, so a failed first attempt retries another region instead + // of failing the connect. + room.regionUrlProviderForTesting = RegionUrlProvider(url: cloudUri, token: token) + ..setServerReportedRegions( + lk_rtc.RegionSettings() + ..regions.add( + lk_rtc.RegionInfo() + ..region = 'other' + ..url = 'wss://other.livekit.cloud', + ), + ); + room.preConnectAudioBuffer.markRecordingForTesting(); + + // The first socket connect fails, the retry gets through. + container.wsConnector.connectError = WebSocketException('first region down'); + container.wsConnector.connectErrorOnce = true; + final connecting = room.connect(cloudUri, token); + await container.answerJoin(); + await connecting; + + expect(room.connectionState, ConnectionState.connected); + expect(container.wsConnector.uri.toString(), startsWith('wss://other.livekit.cloud')); + // The buffered microphone track is published from the join response, so + // the cleanup that runs for the failed attempt must leave the buffer alone. + expect(room.preConnectAudioBuffer.isRecording, isTrue); + }); + + test('pre-connect audio buffer is still reset when the connection drops', () async { + final room = container.room; + await container.connectRoom(); + room.preConnectAudioBuffer.markRecordingForTesting(); + + // The server asks the participant to leave, outside of any connect attempt. + container.wsConnector.onData( + lk_rtc.SignalResponse( + leave: lk_rtc.LeaveRequest( + action: lk_rtc.LeaveRequest_Action.DISCONNECT, + reason: lk_models.DisconnectReason.ROOM_DELETED, + ), + ).writeToBuffer(), + ); + await Future.delayed(const Duration(milliseconds: 200)); + + expect(room.preConnectAudioBuffer.isRecording, isFalse); + }); +} diff --git a/test/mock/websocket_mock.dart b/test/mock/websocket_mock.dart index 83365d5f6..20b918f65 100644 --- a/test/mock/websocket_mock.dart +++ b/test/mock/websocket_mock.dart @@ -31,6 +31,11 @@ class MockWebSocketConnector { NetworkOptions? networkOptions; Object? connectError; + /// When true, [connectError] is thrown once and then cleared, so the next + /// connect succeeds. Models a first attempt that fails and a retry that gets + /// through. + bool connectErrorOnce = false; + /// Every message the SDK sent over any socket this connector opened. final List> sentData = []; @@ -52,6 +57,9 @@ class MockWebSocketConnector { final error = connectError; if (error != null) { + if (connectErrorOnce) { + connectError = null; + } throw error; } From eeca29bb6190f41c53a8f623073d6ced0665fda8 Mon Sep 17 00:00:00 2001 From: Hiroshi Horie <548776+hiroshihorie@users.noreply.github.com> Date: Sat, 19 Sep 2026 00:47:34 +0800 Subject: [PATCH 2/6] style: sort imports --- lib/src/preconnect/pre_connect_audio_buffer.dart | 1 - test/core/preconnect_failover_test.dart | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/src/preconnect/pre_connect_audio_buffer.dart b/lib/src/preconnect/pre_connect_audio_buffer.dart index e513074e2..172da562c 100644 --- a/lib/src/preconnect/pre_connect_audio_buffer.dart +++ b/lib/src/preconnect/pre_connect_audio_buffer.dart @@ -15,7 +15,6 @@ import 'dart:async'; import 'package:meta/meta.dart'; - import 'package:uuid/uuid.dart'; import '../audio/audio_frame_capture.dart'; diff --git a/test/core/preconnect_failover_test.dart b/test/core/preconnect_failover_test.dart index b9461997c..3756df2e8 100644 --- a/test/core/preconnect_failover_test.dart +++ b/test/core/preconnect_failover_test.dart @@ -18,13 +18,13 @@ library; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; + import 'package:livekit_client/livekit_client.dart'; import 'package:livekit_client/src/proto/livekit_models.pb.dart' as lk_models; import 'package:livekit_client/src/proto/livekit_rtc.pb.dart' as lk_rtc; import 'package:livekit_client/src/support/http_client.dart'; import 'package:livekit_client/src/support/region_url_provider.dart'; import 'package:livekit_client/src/support/websocket.dart'; - import '../mock/e2e_container.dart'; const cloudUri = 'wss://test.livekit.cloud'; From ee3fbc86532b67228e5022326219e1c28e0c8373 Mon Sep 17 00:00:00 2001 From: Hiroshi Horie <548776+hiroshihorie@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:51:44 +0800 Subject: [PATCH 3/6] Add changeset for the pre-connect failover fix Co-Authored-By: Claude Opus 5.5 --- .changes/preconnect-audio-survives-failover | 1 + 1 file changed, 1 insertion(+) create mode 100644 .changes/preconnect-audio-survives-failover diff --git a/.changes/preconnect-audio-survives-failover b/.changes/preconnect-audio-survives-failover new file mode 100644 index 000000000..6583392a4 --- /dev/null +++ b/.changes/preconnect-audio-survives-failover @@ -0,0 +1 @@ +patch type="fixed" "Keep the pre-connect audio buffer recording through a region failover on connect, so the microphone is still published when the first attempt is rejected (for example by a region-pinned LiveKit Cloud project)" From e399ee3560cddba7168207b5a654e013faf6d4de Mon Sep 17 00:00:00 2001 From: Hiroshi Horie <548776+hiroshihorie@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:45:19 +0800 Subject: [PATCH 4/6] docs: keep startRecording's doc comment on startRecording markRecordingForTesting had been inserted between startRecording and its doc comment, so the test helper inherited the documentation and startRecording lost it. Move the helper above the comment. Co-Authored-By: Claude Fable 5.2 --- lib/src/preconnect/pre_connect_audio_buffer.dart | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/lib/src/preconnect/pre_connect_audio_buffer.dart b/lib/src/preconnect/pre_connect_audio_buffer.dart index 172da562c..41130a37f 100644 --- a/lib/src/preconnect/pre_connect_audio_buffer.dart +++ b/lib/src/preconnect/pre_connect_audio_buffer.dart @@ -98,6 +98,14 @@ class PreConnectAudioBuffer { /// future completes with an error. Future get agentReadyFuture => _agentReadyManager.future; + /// Puts the buffer into its recording state without touching the + /// microphone, so tests can check what the Room does with a live buffer + /// where no audio device exists. + @visibleForTesting + void markRecordingForTesting() { + _isRecording = true; + } + /// Starts capturing audio into an in-memory buffer. /// /// [timeout] controls how long to wait for an agent to become active. When the @@ -109,14 +117,6 @@ class PreConnectAudioBuffer { /// Requires microphone permission. On iOS/macOS it is requested here while /// the app is in the foreground. Throws a [TrackCreateException] when it is /// denied or cannot be requested (app not in the foreground). - /// Puts the buffer into its recording state without touching the - /// microphone, so tests can check what the Room does with a live buffer - /// where no audio device exists. - @visibleForTesting - void markRecordingForTesting() { - _isRecording = true; - } - Future startRecording({ Duration timeout = const Duration(seconds: 20), }) async { From f9c394be92299114f227ff43e3f65924606d0fb6 Mon Sep 17 00:00:00 2001 From: Hiroshi Horie <548776+hiroshihorie@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:01:38 +0800 Subject: [PATCH 5/6] fix: reset the pre-connect buffer when a connect is cancelled or its failover gives up Keeping the buffer for every disconnect during connect() also kept it in two cases where nothing should be published: - disconnect() called while the connect is in flight. The buffer stayed recording, and the microphone was published if that connect completed. A client initiated disconnect now resets the buffer as before. - a failed attempt that is eligible for failover but ends with no retry that connects (no region left, the region fetch fails, or the retry fails too). connect() now resets the buffer itself before it throws. Tests cover each way connect() can end: failover on a 403 from validate, failover on a rejected socket, failure with no failover, no region left, a failed retry, disconnect() during connect, and a server initiated leave. Co-Authored-By: Claude Fable 5.2 --- lib/src/core/room.dart | 17 +++- test/core/preconnect_failover_test.dart | 114 +++++++++++++++++++++--- test/mock/websocket_mock.dart | 6 ++ 3 files changed, 121 insertions(+), 16 deletions(-) diff --git a/lib/src/core/room.dart b/lib/src/core/room.dart index d6077211a..9482c885d 100644 --- a/lib/src/core/room.dart +++ b/lib/src/core/room.dart @@ -381,6 +381,10 @@ class Room extends DisposableChangeNotifier with EventsEmittable { await NativeAudioManagement.start(); var didConnect = false; + // Set once a failed attempt is handed to the failover path. Its cleanup + // leaves the pre-connect audio buffer alone, so when no retry succeeds the + // buffer has to be reset here instead. + var failoverStarted = false; _connectInProgress = true; try { await engine.connect( @@ -395,6 +399,7 @@ class Room extends DisposableChangeNotifier with EventsEmittable { } catch (e) { logger.warning('could not connect to $url $e'); if (_regionUrlProvider != null && canFailOverToAnotherRegion(e)) { + failoverStarted = true; String? nextUrl; try { nextUrl = await _regionUrlProvider!.getNextBestRegionUrl(); @@ -423,6 +428,9 @@ class Room extends DisposableChangeNotifier with EventsEmittable { } finally { _connectInProgress = false; if (!didConnect) { + if (failoverStarted) { + await preConnectAudioBuffer.reset(); + } await NativeAudioManagement.stop(); } } @@ -693,8 +701,13 @@ class Room extends DisposableChangeNotifier with EventsEmittable { event.reason == DisconnectReason.clientInitiated) { // A failed first attempt lands here before connect() retries another // region. The pre-connect audio buffer has to survive that, or the - // retry connects without ever publishing the microphone. - await _cleanUp(disposeLocalParticipant: false, preservePreConnectAudio: _connectInProgress); + // retry connects without ever publishing the microphone. A disconnect + // the app asked for is not a retry: it resets the buffer as always, so + // nothing is published if that connect still completes. + await _cleanUp( + disposeLocalParticipant: false, + preservePreConnectAudio: _connectInProgress && event.reason != DisconnectReason.clientInitiated, + ); events.emit(RoomDisconnectedEvent(reason: event.reason)); notifyListeners(); } diff --git a/test/core/preconnect_failover_test.dart b/test/core/preconnect_failover_test.dart index 3756df2e8..d7c322169 100644 --- a/test/core/preconnect_failover_test.dart +++ b/test/core/preconnect_failover_test.dart @@ -15,6 +15,8 @@ @Timeout(Duration(seconds: 10)) library; +import 'dart:async'; + import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; @@ -30,18 +32,36 @@ import '../mock/e2e_container.dart'; const cloudUri = 'wss://test.livekit.cloud'; const token = 'token'; +/// A provider that already knows its regions, so a failover never has to +/// fetch them. With no [regions] there is nowhere left to fail over to. +RegionUrlProvider providerWith(List regions) => + RegionUrlProvider(url: cloudUri, token: token)..setServerReportedRegions( + lk_rtc.RegionSettings() + ..regions.addAll([ + for (final region in regions) + lk_rtc.RegionInfo() + ..region = region + ..url = 'wss://$region.livekit.cloud', + ]), + ); + void main() { TestWidgetsFlutterBinding.ensureInitialized(); late E2EContainer container; + // What the validate request answers after a failed socket connect. A 403 is + // one of the answers that makes connect() fail over to another region. + late int validateStatus; + setUp(() { container = E2EContainer(); - // After a failed socket connect the SDK validates the token over HTTP. A - // 403 there is how LiveKit Cloud signals that the project is not served - // from that region, and it is the case that fails over to another region. - sdkHttpClientFactoryForTesting = (_) => - MockClient((request) async => http.Response('project not allowed in this region.', 403)); + validateStatus = 403; + sdkHttpClientFactoryForTesting = (_) => MockClient( + (request) async => validateStatus == 200 + ? http.Response('success', 200) + : http.Response('project not allowed in this region.', validateStatus), + ); }); tearDown(() async { @@ -54,15 +74,7 @@ void main() { // Known regions, so a failed first attempt retries another region instead // of failing the connect. - room.regionUrlProviderForTesting = RegionUrlProvider(url: cloudUri, token: token) - ..setServerReportedRegions( - lk_rtc.RegionSettings() - ..regions.add( - lk_rtc.RegionInfo() - ..region = 'other' - ..url = 'wss://other.livekit.cloud', - ), - ); + room.regionUrlProviderForTesting = providerWith(['other']); room.preConnectAudioBuffer.markRecordingForTesting(); // The first socket connect fails, the retry gets through. @@ -79,6 +91,80 @@ void main() { expect(room.preConnectAudioBuffer.isRecording, isTrue); }); + test('pre-connect audio buffer survives a failover when only the socket is rejected', () async { + final room = container.room; + room.regionUrlProviderForTesting = providerWith(['other']); + room.preConnectAudioBuffer.markRecordingForTesting(); + + // The socket is refused while the validate request succeeds, so connect() + // fails over on the socket error itself. + validateStatus = 200; + container.wsConnector.connectError = WebSocketException('rejected'); + container.wsConnector.connectErrorOnce = true; + final connecting = room.connect(cloudUri, token); + await container.answerJoin(); + await connecting; + + expect(room.connectionState, ConnectionState.connected); + expect(container.wsConnector.uri.toString(), startsWith('wss://other.livekit.cloud')); + expect(room.preConnectAudioBuffer.isRecording, isTrue); + }); + + test('pre-connect audio buffer is reset when connect fails with no failover', () async { + final room = container.room; + room.preConnectAudioBuffer.markRecordingForTesting(); + + // Not a LiveKit Cloud url, so there is no other region to try. + validateStatus = 401; + container.wsConnector.connectError = WebSocketException('down'); + await expectLater(room.connect('wss://self.hosted.example', token), throwsA(isA())); + await Future.delayed(const Duration(milliseconds: 200)); + + expect(room.preConnectAudioBuffer.isRecording, isFalse); + }); + + test('pre-connect audio buffer is reset when the failover has no region left', () async { + final room = container.room; + room.regionUrlProviderForTesting = providerWith([]); + room.preConnectAudioBuffer.markRecordingForTesting(); + + container.wsConnector.connectError = WebSocketException('down'); + await expectLater(room.connect(cloudUri, token), throwsA(isA())); + await Future.delayed(const Duration(milliseconds: 200)); + + expect(room.preConnectAudioBuffer.isRecording, isFalse); + }); + + test('pre-connect audio buffer is reset when the failover attempt fails too', () async { + final room = container.room; + room.regionUrlProviderForTesting = providerWith(['other']); + room.preConnectAudioBuffer.markRecordingForTesting(); + + container.wsConnector.connectError = WebSocketException('down'); + await expectLater(room.connect(cloudUri, token), throwsA(isA())); + await Future.delayed(const Duration(milliseconds: 200)); + + expect(room.preConnectAudioBuffer.isRecording, isFalse); + }); + + test('pre-connect audio buffer is reset when disconnect() is called during connect', () async { + final room = container.room; + room.preConnectAudioBuffer.markRecordingForTesting(); + + // The socket handshake is still in flight when the app gives up. A buffer + // left recording here would publish the microphone if that connect went + // on to complete. + final handshake = Completer(); + container.wsConnector.connectGate = handshake.future; + unawaited(room.connect(cloudUri, token).then((_) {}, onError: (_) {})); + await Future.delayed(const Duration(milliseconds: 10)); + unawaited(room.disconnect().then((_) {}, onError: (_) {})); + await Future.delayed(const Duration(milliseconds: 200)); + + expect(room.preConnectAudioBuffer.isRecording, isFalse); + handshake.complete(); + }); + test('pre-connect audio buffer is still reset when the connection drops', () async { final room = container.room; await container.connectRoom(); diff --git a/test/mock/websocket_mock.dart b/test/mock/websocket_mock.dart index 20b918f65..33fbadbf9 100644 --- a/test/mock/websocket_mock.dart +++ b/test/mock/websocket_mock.dart @@ -36,6 +36,10 @@ class MockWebSocketConnector { /// through. bool connectErrorOnce = false; + /// When set, a connect waits for it before it answers. Models a socket + /// handshake that is still in flight. + Future? connectGate; + /// Every message the SDK sent over any socket this connector opened. final List> sentData = []; @@ -55,6 +59,8 @@ class MockWebSocketConnector { this.headers = headers; this.networkOptions = networkOptions; + await connectGate; + final error = connectError; if (error != null) { if (connectErrorOnce) { From ec7b96dceee55052014f16e38e7abc6c2bf5da1d Mon Sep 17 00:00:00 2001 From: Hiroshi Horie <548776+hiroshihorie@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:20:26 +0800 Subject: [PATCH 6/6] fix: stop the pre-connect recorder with the error when a failover gives up The previous commit reset the buffer when a failover ended without a connection. A plain reset does not stop the native recorder, and it ran before withPreConnectAudio could stop the buffer with the error, so that stop found nothing to do and the microphone kept recording. connect() now stops the buffer with the error itself in that case, the way withPreConnectAudio ends a failed operation, and then resets it. The tests check that agentReadyFuture completes with the connect error, which only the error-aware stop does. Co-Authored-By: Claude Fable 5.2 --- lib/src/core/room.dart | 52 +++++++++++++------------ test/core/preconnect_failover_test.dart | 8 +++- 2 files changed, 33 insertions(+), 27 deletions(-) diff --git a/lib/src/core/room.dart b/lib/src/core/room.dart index 9482c885d..5731309e1 100644 --- a/lib/src/core/room.dart +++ b/lib/src/core/room.dart @@ -381,10 +381,6 @@ class Room extends DisposableChangeNotifier with EventsEmittable { await NativeAudioManagement.start(); var didConnect = false; - // Set once a failed attempt is handed to the failover path. Its cleanup - // leaves the pre-connect audio buffer alone, so when no retry succeeds the - // buffer has to be reset here instead. - var failoverStarted = false; _connectInProgress = true; try { await engine.connect( @@ -399,27 +395,36 @@ class Room extends DisposableChangeNotifier with EventsEmittable { } catch (e) { logger.warning('could not connect to $url $e'); if (_regionUrlProvider != null && canFailOverToAnotherRegion(e)) { - failoverStarted = true; - String? nextUrl; try { - nextUrl = await _regionUrlProvider!.getNextBestRegionUrl(); - } catch (error) { - if (error is ConnectException && (error.statusCode == 401)) { + String? nextUrl; + try { + nextUrl = await _regionUrlProvider!.getNextBestRegionUrl(); + } catch (error) { + if (error is ConnectException && (error.statusCode == 401)) { + rethrow; + } + } + if (nextUrl != null) { + logger.fine('Initial connection failed with ConnectionError: $e. Retrying with another region: ${nextUrl}'); + await engine.connect( + nextUrl, + token, + connectOptions: connectOptions, + roomOptions: effectiveRoomOptions, + fastConnectOptions: fastConnectOptions, + regionUrlProvider: _regionUrlProvider, + ); + didConnect = true; + } else { rethrow; } - } - if (nextUrl != null) { - logger.fine('Initial connection failed with ConnectionError: $e. Retrying with another region: ${nextUrl}'); - await engine.connect( - nextUrl, - token, - connectOptions: connectOptions, - roomOptions: effectiveRoomOptions, - fastConnectOptions: fastConnectOptions, - regionUrlProvider: _regionUrlProvider, - ); - didConnect = true; - } else { + } catch (error) { + // The cleanup for the failed attempt left the pre-connect audio + // buffer recording for a retry, and no retry connected. Stop it + // with the error, the way withPreConnectAudio ends a failed + // operation, so the native recorder is stopped as well. + await preConnectAudioBuffer.stopRecording(withError: error); + await preConnectAudioBuffer.reset(); rethrow; } } else { @@ -428,9 +433,6 @@ class Room extends DisposableChangeNotifier with EventsEmittable { } finally { _connectInProgress = false; if (!didConnect) { - if (failoverStarted) { - await preConnectAudioBuffer.reset(); - } await NativeAudioManagement.stop(); } } diff --git a/test/core/preconnect_failover_test.dart b/test/core/preconnect_failover_test.dart index d7c322169..3a469311f 100644 --- a/test/core/preconnect_failover_test.dart +++ b/test/core/preconnect_failover_test.dart @@ -127,10 +127,13 @@ void main() { final room = container.room; room.regionUrlProviderForTesting = providerWith([]); room.preConnectAudioBuffer.markRecordingForTesting(); + // Stopped with the connect error, which is what also stops the native + // recorder, rather than with a plain reset. + final agentReady = expectLater(room.preConnectAudioBuffer.agentReadyFuture, throwsA(isA())); container.wsConnector.connectError = WebSocketException('down'); await expectLater(room.connect(cloudUri, token), throwsA(isA())); - await Future.delayed(const Duration(milliseconds: 200)); + await agentReady; expect(room.preConnectAudioBuffer.isRecording, isFalse); }); @@ -139,10 +142,11 @@ void main() { final room = container.room; room.regionUrlProviderForTesting = providerWith(['other']); room.preConnectAudioBuffer.markRecordingForTesting(); + final agentReady = expectLater(room.preConnectAudioBuffer.agentReadyFuture, throwsA(isA())); container.wsConnector.connectError = WebSocketException('down'); await expectLater(room.connect(cloudUri, token), throwsA(isA())); - await Future.delayed(const Duration(milliseconds: 200)); + await agentReady; expect(room.preConnectAudioBuffer.isRecording, isFalse); });