Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .changes/room-restart-ice
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
minor type="added" "`Room.restartIce()` resumes the session on purpose to restart ICE on both peer connections, so media stuck on a TURN relay over TCP/TLS can move back to UDP"
11 changes: 11 additions & 0 deletions lib/src/core/room.dart
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import '../track/local/video.dart';
import '../track/track.dart';
import '../track/web/_audio_api.dart' if (dart.library.js_interop) '../track/web/_audio_html.dart' as audio;
import '../types/data_stream.dart';
import '../types/internal.dart';
import '../types/other.dart';
import '../types/rpc.dart';
import '../types/transcription_segment.dart';
Expand Down Expand Up @@ -823,6 +824,16 @@ class Room extends DisposableChangeNotifier with EventsEmittable<RoomEvent> {
}
});

/// Resumes the session on purpose, restarting ICE on both peer connections.
///
/// Once UDP is blocked, media falls back to a TURN relay over TCP/TLS and
/// stays there after UDP comes back. An app that sees from the stats that a
/// better path is available again can call this to let ICE find it.
Future<void> restartIce() => engine.handleReconnect(
ClientDisconnectReason.reconnect,
reconnectReason: lk_models.ReconnectReason.RR_SWITCH_CANDIDATE,
);
Comment on lines +832 to +835

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 ICE restart future completes too early

When a connected app awaits restartIce(), it completes before ICE restarts. handleReconnect only schedules a timer, so later failures never reach the caller.

Learn more

The public method returns the future from handleReconnect, which completes after scheduling a retry timer. The timer later invokes attemptReconnect; that method catches reconnect failures and starts further retries without completing the original future. A caller cannot await ICE restart completion or distinguish success from eventual disconnect.

Example: An app calls await room.restartIce() and immediately reads the candidate pair. The await completes before the zero-delay timer even opens a new signaling socket, so the old TCP pair is still selected.

Recommended fix: Give the requested reconnect a completion future tied to the final successful resume or failure, and return that future from Room.restartIce(). Preserve the engine's retry behavior and settle the future on disconnect or disposal.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved

/// Disconnects from the room, notifying server of disconnection.
Future<void> disconnect() async {
final bool isPendingReconnect = engine.isPendingReconnect;
Expand Down
74 changes: 74 additions & 0 deletions test/core/restart_ice_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// 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:flutter_webrtc/flutter_webrtc.dart' as rtc;

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 '../mock/e2e_container.dart';
import '../mock/peerconnection_mock.dart';
import '../mock/websocket_mock.dart';

void main() {
TestWidgetsFlutterBinding.ensureInitialized();

late E2EContainer container;
late MockWebSocketConnector ws;

setUp(() async {
resetMockDataChannels();
container = E2EContainer();
ws = container.wsConnector;
await container.connectRoom();
});

tearDown(() async {
await container.dispose();
});

Future<void> until(bool Function() condition) async {
for (var i = 0; i < 200 && !condition(); i++) {
await Future<void>.delayed(const Duration(milliseconds: 10));
}
expect(condition(), isTrue);
}

test('restartIce() resumes to switch candidates, restarting publisher ICE', () async {
final publisher = container.engine.publisher!;
await container.engine.negotiate();
await until(() => publisher.pc.signalingState == rtc.RTCSignalingState.RTCSignalingStateHaveLocalOffer);
ws.onData(
lk_rtc.SignalResponse(
answer: lk_rtc.SessionDescription(type: 'answer', sdp: 'remote_answer'),
).writeToBuffer(),
);
await until(() => publisher.pc.connectionState == rtc.RTCPeerConnectionState.RTCPeerConnectionStateConnected);

final previousHandlers = ws.handlers;
await container.room.restartIce();
await until(() => !identical(ws.handlers, previousHandlers));

expect(ws.uri!.queryParameters['reconnect'], '1');
expect(ws.uri!.queryParameters['reconnect_reason'], '${lk_models.ReconnectReason.RR_SWITCH_CANDIDATE.value}');

ws.onData(lk_rtc.SignalResponse(reconnect: lk_rtc.ReconnectResponse()).writeToBuffer());
await container.room.events.waitFor<RoomReconnectedEvent>(duration: const Duration(seconds: 5));
expect(publisher.restartingIce, isTrue);
});
}
3 changes: 1 addition & 2 deletions test/mock/peerconnection_mock.dart
Original file line number Diff line number Diff line change
Expand Up @@ -303,8 +303,7 @@ a=rtpmap:32 MPV/90000
]) async => MockPeerConnection();

@override
// TODO: implement restartIce
Future<void> restartIce() => throw UnimplementedError();
Future<void> restartIce() async {}
}

class MockRtpSender implements RTCRtpSender {
Expand Down
Loading