openrtc 1.0.2

OpenRTC: a Rust-first P2P runtime for device discovery, signaling, and iroh/QUIC networking.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
#![cfg(all(not(target_arch = "wasm32"), feature = "transport-webrtc"))]

use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::sync::{Arc, Once, RwLock as StdRwLock};

use anyhow::{Context, Result};
use bytes::Bytes;
use tokio::sync::{mpsc, oneshot, Mutex, RwLock};
use webrtc::api::setting_engine::SettingEngine;
use webrtc::api::APIBuilder;
use webrtc::data_channel::data_channel_init::RTCDataChannelInit;
use webrtc::data_channel::data_channel_message::DataChannelMessage;
use webrtc::data_channel::RTCDataChannel;
use webrtc::ice::candidate::CandidateType;
use webrtc::ice::mdns::MulticastDnsMode;
use webrtc::ice::network_type::NetworkType;
use webrtc::ice_transport::ice_candidate::RTCIceCandidateInit;
use webrtc::ice_transport::ice_candidate_type::RTCIceCandidateType;
use webrtc::ice_transport::ice_server::RTCIceServer;
use webrtc::peer_connection::configuration::RTCConfiguration;
use webrtc::peer_connection::peer_connection_state::RTCPeerConnectionState;
use webrtc::peer_connection::policy::ice_transport_policy::RTCIceTransportPolicy;
use webrtc::peer_connection::sdp::sdp_type::RTCSdpType;
use webrtc::peer_connection::sdp::session_description::RTCSessionDescription;
use webrtc::peer_connection::RTCPeerConnection;

use super::{NativeWebRTCState, WebRTCSignalMessage};
use crate::heartbeat::codec;
use crate::heartbeat::{HealthTransition, HeartbeatConfig, TransportHeartbeat};

const ICE_DISCONNECT_GRACE_MS: u64 = 12_000;
const WEBRTC_HEARTBEAT_LOG_ENV: &str = "OPENRTC_VERBOSE_WEBRTC_HEARTBEAT";

fn parse_multicast_dns_mode(value: &str) -> Option<MulticastDnsMode> {
    match value.trim().to_ascii_lowercase().as_str() {
        "disabled" | "disable" | "off" | "false" | "0" => Some(MulticastDnsMode::Disabled),
        "query-only" | "query_only" | "queryonly" | "query" => Some(MulticastDnsMode::QueryOnly),
        "query-and-gather" | "query_and_gather" | "queryandgather" | "gather" => {
            Some(MulticastDnsMode::QueryAndGather)
        }
        _ => None,
    }
}

fn configured_multicast_dns_mode(config: &crate::client::WebRTCConfig) -> MulticastDnsMode {
    if config.privacy_mode {
        return MulticastDnsMode::Disabled;
    }

    for key in ["OPENRTC_WEBRTC_MDNS_MODE", "PLUTO_WEBRTC_MDNS_MODE"] {
        if let Ok(value) = std::env::var(key) {
            if let Some(mode) = parse_multicast_dns_mode(&value) {
                return mode;
            }
        }
    }

    #[cfg(target_os = "ios")]
    {
        // webrtc-rs QueryOnly resolves browser `.local` candidates by spawning
        // mDNS query loops. The iOS sandbox commonly rejects those outbound
        // multicast sends, and unresolved queries retry indefinitely inside the
        // dependency. Prefer srflx/relay candidates on iOS; opt into QueryOnly
        // via OPENRTC_WEBRTC_MDNS_MODE=query-only when debugging local LAN ICE.
        MulticastDnsMode::Disabled
    }

    #[cfg(not(target_os = "ios"))]
    {
        if config.lan_mode {
            MulticastDnsMode::QueryAndGather
        } else {
            MulticastDnsMode::QueryOnly
        }
    }
}

fn verbose_webrtc_heartbeat_logs() -> bool {
    std::env::var(WEBRTC_HEARTBEAT_LOG_ENV)
        .map(|value| {
            matches!(
                value.trim().to_ascii_lowercase().as_str(),
                "1" | "true" | "yes" | "on"
            )
        })
        .unwrap_or(false)
}

/// Returns true when this host has at least one routable IPv6 interface
/// address (excluding loopback, unspecified, and link-local fe80::/10).
///
/// Native hosts advertise IPv6 NetworkTypes only when the device actually has
/// IPv6 connectivity. Hosts without routable IPv6 otherwise make webrtc-rs
/// spend time on unusable STUN gathers and candidate churn.
///
/// Result is cached for the process lifetime: interface set rarely flips
/// during a session, and re-probing on every PeerConnection construction
/// is wasted work.
fn host_has_routable_ipv6() -> bool {
    use std::net::IpAddr;
    use std::sync::OnceLock;

    static CACHED: OnceLock<bool> = OnceLock::new();
    *CACHED.get_or_init(|| {
        let interfaces = netdev::get_interfaces();
        interfaces.iter().any(|iface| {
            iface.ipv6.iter().any(|net| {
                let ip = IpAddr::V6(net.addr());
                if ip.is_loopback() || ip.is_unspecified() {
                    return false;
                }
                let segments = match ip {
                    IpAddr::V6(v6) => v6.segments(),
                    _ => return false,
                };
                // Skip fe80::/10 link-local — they cannot reach STUN.
                (segments[0] & 0xffc0) != 0xfe80
            })
        })
    })
}

fn network_types_for_routable_ipv6(has_routable_ipv6: bool) -> Vec<NetworkType> {
    let mut net_types = vec![NetworkType::Udp4, NetworkType::Tcp4];
    if has_routable_ipv6 {
        net_types.push(NetworkType::Udp6);
        net_types.push(NetworkType::Tcp6);
    }
    net_types
}

#[derive(Debug, serde::Deserialize)]
struct SignalSessionDescription {
    #[serde(rename = "type")]
    sdp_type: String,
    sdp: String,
}

pub type NativeWebRTCMessageHandler =
    Arc<dyn Fn(Bytes) -> futures::future::BoxFuture<'static, ()> + Send + Sync>;
pub type NativeWebRTCMessageInterceptor =
    Arc<dyn Fn(Bytes) -> futures::future::BoxFuture<'static, bool> + Send + Sync>;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NativeWebRTCIcePairSummary {
    pub local_candidate_type: CandidateType,
    pub remote_candidate_type: CandidateType,
    pub local_ip: String,
    pub remote_ip: String,
}

fn native_candidate_type(candidate_type: RTCIceCandidateType) -> Option<CandidateType> {
    match candidate_type {
        RTCIceCandidateType::Host => Some(CandidateType::Host),
        RTCIceCandidateType::Srflx => Some(CandidateType::ServerReflexive),
        RTCIceCandidateType::Prflx => Some(CandidateType::PeerReflexive),
        RTCIceCandidateType::Relay => Some(CandidateType::Relay),
        RTCIceCandidateType::Unspecified => None,
    }
}

impl NativeWebRTCIcePairSummary {
    pub fn is_lan_direct_pair(&self) -> bool {
        self.local_candidate_type != CandidateType::Relay
            && self.remote_candidate_type != CandidateType::Relay
            && selected_address_is_local(&self.local_ip)
            && selected_address_is_local(&self.remote_ip)
    }

    pub fn transport_label(&self) -> &'static str {
        if self.is_lan_direct_pair() {
            crate::transport_label::WEBRTC_LAN
        } else if self.local_candidate_type == CandidateType::Relay
            || self.remote_candidate_type == CandidateType::Relay
        {
            crate::transport_label::WEBRTC_TURN
        } else {
            crate::transport_label::WEBRTC
        }
    }
}

fn selected_address_is_local(address: &str) -> bool {
    match address.trim().parse::<IpAddr>() {
        Ok(IpAddr::V4(address)) => {
            address.is_private() || address.is_link_local() || address.is_loopback()
        }
        Ok(IpAddr::V6(address)) => {
            address.is_unique_local() || address.is_unicast_link_local() || address.is_loopback()
        }
        Err(_) => false,
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NativeWebRTCRole {
    Auto,
    Initiator,
    Responder,
}

#[derive(Clone)]
pub struct NativeWebRTCDataChannel {
    #[allow(dead_code)]
    local_node_id: String,
    #[allow(dead_code)]
    remote_node_id: String,
    is_initiator: bool,
    state: Arc<AtomicU8>,
    started: Arc<AtomicBool>,
    peer_connection: Arc<RTCPeerConnection>,
    data_channel: Arc<RwLock<Option<Arc<RTCDataChannel>>>>,
    message_handler: Arc<RwLock<Option<NativeWebRTCMessageHandler>>>,
    message_interceptors: Arc<RwLock<Vec<NativeWebRTCMessageInterceptor>>>,
    pending_messages: Arc<Mutex<Vec<Bytes>>>,
    pending_candidates: Arc<Mutex<Vec<RTCIceCandidateInit>>>,
    signal_sender: super::NativeWebRTCSignalSender,
    negotiation_id: Arc<StdRwLock<String>>,
    /// Heartbeat fields — set by `with_heartbeat()` before `start()`.
    heartbeat_config: Arc<Mutex<Option<HeartbeatConfig>>>,
    heartbeat_health_tx: Arc<Mutex<Option<mpsc::Sender<HealthTransition>>>>,
    heartbeat_transport_name: Arc<Mutex<String>>,
    heartbeat_pong_tx: Arc<Mutex<Option<mpsc::Sender<codec::Pong>>>>,
    heartbeat_ping_tx: Arc<Mutex<Option<mpsc::Sender<codec::Ping>>>>,
    heartbeat_handle: Arc<Mutex<Option<TransportHeartbeat>>>,
    latency_waiters: Arc<Mutex<HashMap<u64, oneshot::Sender<codec::Pong>>>>,
    ice_restart_attempted: Arc<AtomicBool>,
    ice_grace_timer: Arc<Mutex<Option<tokio::task::JoinHandle<()>>>>,
}

impl NativeWebRTCDataChannel {
    pub async fn new(
        local_node_id: &str,
        remote_node_id: &str,
        config: &crate::client::WebRTCConfig,
        signal_sender: super::NativeWebRTCSignalSender,
        negotiation_id: &str,
    ) -> Result<Self> {
        Self::new_with_role(
            local_node_id,
            remote_node_id,
            config,
            signal_sender,
            negotiation_id,
            NativeWebRTCRole::Auto,
        )
        .await
    }

    pub async fn new_with_role(
        local_node_id: &str,
        remote_node_id: &str,
        config: &crate::client::WebRTCConfig,
        signal_sender: super::NativeWebRTCSignalSender,
        negotiation_id: &str,
        role: NativeWebRTCRole,
    ) -> Result<Self> {
        anyhow::ensure!(
            !local_node_id.trim().is_empty(),
            "local_node_id is required"
        );
        anyhow::ensure!(
            !remote_node_id.trim().is_empty(),
            "remote_node_id is required"
        );
        anyhow::ensure!(
            !negotiation_id.trim().is_empty(),
            "negotiation_id is required"
        );
        ensure_rustls_crypto_provider();

        let rtc_config = RTCConfiguration {
            ice_servers: config
                .ice_servers
                .iter()
                .map(|server| RTCIceServer {
                    urls: server.urls.clone(),
                    username: server.username.clone().unwrap_or_default(),
                    credential: server.credential.clone().unwrap_or_default(),
                    ..Default::default()
                })
                .collect(),
            ice_transport_policy: if config.privacy_mode {
                RTCIceTransportPolicy::Relay
            } else {
                RTCIceTransportPolicy::All
            },
            ..Default::default()
        };
        let mut setting_engine = SettingEngine::default();
        setting_engine.set_network_types(network_types_for_routable_ipv6(host_has_routable_ipv6()));

        setting_engine.set_ice_multicast_dns_mode(configured_multicast_dns_mode(config));

        let api = APIBuilder::new()
            .with_setting_engine(setting_engine)
            .build();
        let peer_connection = Arc::new(api.new_peer_connection(rtc_config).await?);
        let is_initiator = match role {
            NativeWebRTCRole::Auto => local_node_id > remote_node_id,
            NativeWebRTCRole::Initiator => true,
            NativeWebRTCRole::Responder => false,
        };

        Ok(Self {
            local_node_id: local_node_id.to_string(),
            remote_node_id: remote_node_id.to_string(),
            is_initiator,
            state: Arc::new(AtomicU8::new(0)),
            started: Arc::new(AtomicBool::new(false)),
            peer_connection,
            data_channel: Arc::new(RwLock::new(None)),
            message_handler: Arc::new(RwLock::new(None)),
            message_interceptors: Arc::new(RwLock::new(Vec::new())),
            pending_messages: Arc::new(Mutex::new(Vec::new())),
            pending_candidates: Arc::new(Mutex::new(Vec::new())),
            signal_sender,
            negotiation_id: Arc::new(StdRwLock::new(negotiation_id.to_string())),
            heartbeat_config: Arc::new(Mutex::new(None)),
            heartbeat_health_tx: Arc::new(Mutex::new(None)),
            heartbeat_transport_name: Arc::new(Mutex::new(String::new())),
            heartbeat_pong_tx: Arc::new(Mutex::new(None)),
            heartbeat_ping_tx: Arc::new(Mutex::new(None)),
            heartbeat_handle: Arc::new(Mutex::new(None)),
            latency_waiters: Arc::new(Mutex::new(HashMap::new())),
            ice_restart_attempted: Arc::new(AtomicBool::new(false)),
            ice_grace_timer: Arc::new(Mutex::new(None)),
        })
    }

    /// Attach heartbeat to this channel. Must be called before `start()`.
    pub async fn with_heartbeat(
        &self,
        transport_name: String,
        config: HeartbeatConfig,
        health_tx: mpsc::Sender<HealthTransition>,
    ) {
        *self.heartbeat_transport_name.lock().await = transport_name;
        *self.heartbeat_config.lock().await = Some(config);
        *self.heartbeat_health_tx.lock().await = Some(health_tx);
    }

    pub fn negotiation_id(&self) -> String {
        self.negotiation_id
            .read()
            .expect("negotiation_id lock poisoned")
            .clone()
    }

    pub fn is_initiator(&self) -> bool {
        self.is_initiator
    }

    async fn dispatch_or_buffer_message(
        handler: &Arc<RwLock<Option<NativeWebRTCMessageHandler>>>,
        interceptors: &Arc<RwLock<Vec<NativeWebRTCMessageInterceptor>>>,
        pending_messages: &Arc<Mutex<Vec<Bytes>>>,
        pong_tx: &Arc<Mutex<Option<mpsc::Sender<codec::Pong>>>>,
        ping_tx: &Arc<Mutex<Option<mpsc::Sender<codec::Ping>>>>,
        latency_waiters: &Arc<Mutex<HashMap<u64, oneshot::Sender<codec::Pong>>>>,
        message: Bytes,
    ) {
        // Intercept heartbeat frames (WebRTC wire format: 0x03=ping, 0x04=pong prefix byte).
        if let Some(&first_byte) = message.first() {
            if first_byte == codec::TYPE_PING {
                let decoded = codec::decode_ping(&message[1..]);
                let guard = ping_tx.lock().await;
                let has_tx = guard.is_some();
                if verbose_webrtc_heartbeat_logs() {
                    println!(
                        "[NativeWebRTC] ping received byte_len={} decoded={} has_ping_tx={}",
                        message.len(),
                        decoded.is_some(),
                        has_tx
                    );
                }
                if let Some(ping) = decoded {
                    if let Some(tx) = guard.as_ref() {
                        let _ = tx.try_send(ping);
                    }
                }
                return;
            }
            if first_byte == codec::TYPE_PONG {
                if let Some(pong) = codec::decode_pong(&message[1..]) {
                    if let Some(waiter) = latency_waiters.lock().await.remove(&pong.seq) {
                        let _ = waiter.send(pong);
                        return;
                    }
                    let guard = pong_tx.lock().await;
                    if let Some(tx) = guard.as_ref() {
                        let _ = tx.try_send(pong);
                    }
                }
                return;
            }
        }

        let interceptor_callbacks = {
            let guard = interceptors.read().await;
            guard.clone()
        };

        for interceptor in interceptor_callbacks {
            if interceptor(message.clone()).await {
                return;
            }
        }

        let callback = {
            let guard = handler.read().await;
            guard.clone()
        };

        if let Some(callback) = callback {
            callback(message).await;
            return;
        }

        let mut pending = pending_messages.lock().await;
        pending.push(message);
    }

    pub fn state(&self) -> NativeWebRTCState {
        match self.state.load(Ordering::SeqCst) {
            1 => NativeWebRTCState::Connecting,
            2 => NativeWebRTCState::Connected,
            3 => NativeWebRTCState::Failed,
            4 => NativeWebRTCState::Closed,
            _ => NativeWebRTCState::Idle,
        }
    }

    #[cfg(test)]
    pub(crate) fn force_state_for_test(&self, state: NativeWebRTCState) {
        let value = match state {
            NativeWebRTCState::Idle => 0,
            NativeWebRTCState::Connecting => 1,
            NativeWebRTCState::Connected => 2,
            NativeWebRTCState::Failed => 3,
            NativeWebRTCState::Closed => 4,
        };
        self.state.store(value, Ordering::SeqCst);
    }

    /// Returns true once this peer has applied a remote SDP (offer or answer).
    /// Used by the upgrade watcher to detect sessions stuck before any signal
    /// arrived — those should abort quickly so the retry loop doesn't wait
    /// the full connect timeout.
    pub async fn has_remote_description(&self) -> bool {
        self.peer_connection.remote_description().await.is_some()
    }

    pub async fn start(&self) -> Result<()> {
        if self.started.swap(true, Ordering::SeqCst) {
            return Ok(());
        }

        self.state.store(1, Ordering::SeqCst);
        println!(
            "[NativeWebRTC] start local_node_id={} remote_node_id={} role={}",
            self.local_node_id,
            self.remote_node_id,
            if self.is_initiator {
                "initiator"
            } else {
                "responder"
            }
        );

        let pc_state = self.state.clone();
        let hb_config = self.heartbeat_config.clone();
        let hb_health_tx = self.heartbeat_health_tx.clone();
        let hb_transport_name = self.heartbeat_transport_name.clone();
        let hb_pong_tx_slot = self.heartbeat_pong_tx.clone();
        let hb_ping_tx_slot = self.heartbeat_ping_tx.clone();
        let hb_handle_slot = self.heartbeat_handle.clone();
        let hb_data_channel = self.data_channel.clone();
        let ice_restart_flag = self.ice_restart_attempted.clone();
        let ice_grace_timer_slot = self.ice_grace_timer.clone();
        let pc_for_restart = self.peer_connection.clone();
        let is_initiator_for_restart = self.is_initiator;
        let signal_sender_for_restart = self.signal_sender.clone();
        let negotiation_id_for_restart = self.negotiation_id.clone();
        self.peer_connection
            .on_peer_connection_state_change(Box::new(
                move |next_state: RTCPeerConnectionState| {
                    let state = pc_state.clone();
                    let config_arc = hb_config.clone();
                    let health_tx_arc = hb_health_tx.clone();
                    let name_arc = hb_transport_name.clone();
                    let pong_tx_slot = hb_pong_tx_slot.clone();
                    let ping_tx_slot = hb_ping_tx_slot.clone();
                    let handle_slot = hb_handle_slot.clone();
                    let dc_slot = hb_data_channel.clone();
                    let restart_flag = ice_restart_flag.clone();
                    let grace_slot = ice_grace_timer_slot.clone();
                    let pc_restart = pc_for_restart.clone();
                    let is_initiator_clone = is_initiator_for_restart;
                    let signal_sender_clone = signal_sender_for_restart.clone();
                    let negotiation_id_clone = negotiation_id_for_restart.clone();
                    Box::pin(async move {
                        println!("[NativeWebRTC] peer_connection_state={:?}", next_state);
                        match next_state {
                            RTCPeerConnectionState::Connected => {
                                state.store(2, Ordering::SeqCst);
                                restart_flag.store(false, Ordering::SeqCst);
                                if let Some(handle) = grace_slot.lock().await.take() {
                                    handle.abort();
                                    println!("[NativeWebRTC] ice-recovered — grace timer cancelled");
                                }
                                // Spawn heartbeat if configured.
                                let config = config_arc.lock().await.clone();
                                let health_tx = health_tx_arc.lock().await.clone();
                                if let (Some(config), Some(health_tx)) = (config, health_tx) {
                                    let transport_name = name_arc.lock().await.clone();
                                    let dc_slot_for_send = dc_slot.clone();
                                    let dc_slot_for_pong = dc_slot.clone();
                                    let send_fn: std::sync::Arc<dyn Fn(Bytes) -> futures::future::BoxFuture<'static, anyhow::Result<()>> + Send + Sync> =
                                        std::sync::Arc::new(move |frame: Bytes| {
                                            let dc2 = dc_slot_for_send.clone();
                                            Box::pin(async move {
                                                if let Some(channel) = dc2.read().await.as_ref() {
                                                    channel.send(&frame).await.map_err(|e| anyhow::anyhow!("{e}"))?;
                                                }
                                                Ok(())
                                            })
                                        });
                                    let (pong_tx, mut pong_rx) = mpsc::channel::<codec::Pong>(32);
                                    let (ping_tx, mut ping_rx) = mpsc::channel::<codec::Ping>(32);
                                    let hb = TransportHeartbeat::spawn(
                                        transport_name,
                                        send_fn,
                                        health_tx,
                                        config,
                                        true, // webrtc_mode: 0x03/0x04 prefix byte
                                    );
                                    // Forward pongs from the intercept channel into the heartbeat task.
                                    let hb_pong = hb.pong_sender();
                                    tokio::spawn(async move {
                                        while let Some(pong) = pong_rx.recv().await {
                                            let _ = hb_pong.try_send(pong);
                                        }
                                    });
                                    // Respond to incoming pings with pong frames.
                                    // Use dc_slot (not a snapshot) so we always see the live channel
                                    // even if the DataChannel opens after RTCPeerConnectionState::Connected.
                                    tokio::spawn(async move {
                                        while let Some(ping) = ping_rx.recv().await {
                                            let recv_ms = codec::now_unix_ms();
                                            let pong_frame = codec::build_webrtc_pong(&ping, recv_ms);
                                            let channel_opt = dc_slot_for_pong.read().await.as_ref().cloned();
                                            match channel_opt {
                                                Some(channel) => {
                                                    match channel.send(&Bytes::from(pong_frame)).await {
                                                        Ok(_) => {
                                                            if verbose_webrtc_heartbeat_logs() {
                                                                println!("[NativeWebRTC] pong sent seq={}", ping.seq);
                                                            }
                                                        }
                                                        Err(e) => println!("[NativeWebRTC] pong send failed seq={} err={}", ping.seq, e),
                                                    }
                                                }
                                                None => {
                                                    println!("[NativeWebRTC] pong send skipped seq={} reason=no-data-channel", ping.seq);
                                                }
                                            }
                                        }
                                    });
                                    *pong_tx_slot.lock().await = Some(pong_tx);
                                    *ping_tx_slot.lock().await = Some(ping_tx);
                                    *handle_slot.lock().await = Some(hb);
                                }
                            }
                            RTCPeerConnectionState::Failed => {
                                state.store(3, Ordering::SeqCst);
                                if let Some(handle) = grace_slot.lock().await.take() {
                                    handle.abort();
                                }
                                stop_heartbeat(&handle_slot, &pong_tx_slot, &ping_tx_slot).await;
                            }
                            RTCPeerConnectionState::Closed => {
                                state.store(4, Ordering::SeqCst);
                                if let Some(handle) = grace_slot.lock().await.take() {
                                    handle.abort();
                                }
                                stop_heartbeat(&handle_slot, &pong_tx_slot, &ping_tx_slot).await;
                            }
                            RTCPeerConnectionState::Disconnected => {
                                // Transient per spec — attempt ICE restart and start a 10s grace
                                // timer. Only transition to Failed if still disconnected.
                                //
                                // But skip restart_ice entirely if the DataChannel has already
                                // signalled Closed (state=4) or Failed (state=3): that means the
                                // remote DTLS/SCTP is gone (e.g. browser refresh) and restarting
                                // ICE on this zombie PC just produces ErrMismatchUsername storms
                                // against the remote's fresh PeerConnection. The post-admission
                                // path will force-replace this session when the remote's token
                                // presentation arrives on the new iroh connection.
                                let prior_state = state.load(Ordering::SeqCst);
                                if prior_state == 3 || prior_state == 4 {
                                    println!(
                                        "[NativeWebRTC] ice-restart skipped: session already terminal state={}",
                                        prior_state
                                    );
                                    return;
                                }
                                let already = restart_flag.swap(true, Ordering::SeqCst);
                                if !already {
                                    println!("[NativeWebRTC] ice-restart-attempted reason=pc-disconnected");
                                    pc_restart.restart_ice().await.ok();
                                    // Only the initiator drives (re)negotiation. Generate a fresh
                                    // offer with iceRestart=true semantics (restart_ice set the
                                    // flag internally) and send it over the signaling path so the
                                    // remote peer can answer with matching credentials and emit new
                                    // candidates. Without this step the remote never sees the new
                                    // offer and the restart stalls with zero candidate pairs.
                                    if is_initiator_clone {
                                        use webrtc::peer_connection::sdp::session_description::RTCSessionDescription;
                                        match pc_restart.create_offer(None).await {
                                            Ok(offer) => {
                                                if let Err(e) = pc_restart
                                                    .set_local_description(offer.clone())
                                                    .await
                                                {
                                                    println!(
                                                        "[NativeWebRTC] ice-restart set_local_description failed err={}",
                                                        e
                                                    );
                                                } else {
                                                    let negotiation_id_value = negotiation_id_clone
                                                        .read()
                                                        .expect("negotiation_id lock poisoned")
                                                        .clone();
                                                    send_sdp_envelope(
                                                        &signal_sender_clone,
                                                        negotiation_id_value.as_str(),
                                                        &offer,
                                                    )
                                                    .await;
                                                    println!(
                                                        "[NativeWebRTC] ice-restart re-offer sent negotiation_id={}",
                                                        negotiation_id_value
                                                    );
                                                }
                                                // Silence unused-import lint when feature selection
                                                // trims the downstream uses of RTCSessionDescription
                                                // outside this block.
                                                let _ = std::marker::PhantomData::<RTCSessionDescription>;
                                            }
                                            Err(e) => {
                                                println!(
                                                    "[NativeWebRTC] ice-restart create_offer failed err={}",
                                                    e
                                                );
                                            }
                                        }
                                    }
                                }
                                let mut guard = grace_slot.lock().await;
                                if guard.is_none() {
                                    let pc_check = pc_restart.clone();
                                    let state_for_timer = state.clone();
                                    let grace_slot_inner = grace_slot.clone();
                                    let handle_slot_timer = handle_slot.clone();
                                    let pong_tx_slot_timer = pong_tx_slot.clone();
                                    let ping_tx_slot_timer = ping_tx_slot.clone();
                                    let handle = tokio::spawn(async move {
                                        tokio::time::sleep(std::time::Duration::from_millis(
                                            ICE_DISCONNECT_GRACE_MS,
                                        ))
                                        .await;
                                        let current = pc_check.connection_state();
                                        if matches!(
                                            current,
                                            RTCPeerConnectionState::Connected
                                        ) {
                                            println!("[NativeWebRTC] ice-grace expired — recovered");
                                        } else {
                                            println!(
                                                "[NativeWebRTC] ice-grace expired — marking failed (pc_state={:?})",
                                                current
                                            );
                                            state_for_timer.store(3, Ordering::SeqCst);
                                            stop_heartbeat(&handle_slot_timer, &pong_tx_slot_timer, &ping_tx_slot_timer).await;
                                            let _ = pc_check.close().await;
                                        }
                                        *grace_slot_inner.lock().await = None;
                                    });
                                    *guard = Some(handle);
                                }
                            }
                            _ => {}
                        }
                    })
                },
            ));

        let dc_slot_incoming = self.data_channel.clone();
        let incoming_open_state = self.state.clone();
        let incoming_close_state = self.state.clone();
        let incoming_error_state = self.state.clone();
        let incoming_message_handler = self.message_handler.clone();
        let incoming_message_interceptors = self.message_interceptors.clone();
        let incoming_pending_messages = self.pending_messages.clone();
        let incoming_pong_tx = self.heartbeat_pong_tx.clone();
        let incoming_ping_tx = self.heartbeat_ping_tx.clone();
        let incoming_latency_waiters = self.latency_waiters.clone();
        self.peer_connection
            .on_data_channel(Box::new(move |channel: Arc<RTCDataChannel>| {
                let slot = dc_slot_incoming.clone();
                let open_state = incoming_open_state.clone();
                let close_state = incoming_close_state.clone();
                let error_state = incoming_error_state.clone();
                let message_handler = incoming_message_handler.clone();
                let message_interceptors = incoming_message_interceptors.clone();
                let pending_messages = incoming_pending_messages.clone();
                let pong_tx = incoming_pong_tx.clone();
                let ping_tx = incoming_ping_tx.clone();
                let latency_waiters = incoming_latency_waiters.clone();
                Box::pin(async move {
                    println!(
                        "[NativeWebRTC] on_data_channel label={} id={:?}",
                        channel.label(),
                        channel.id()
                    );
                    let open_state_inner = open_state.clone();
                    channel.on_open(Box::new(move || {
                        let state = open_state_inner.clone();
                        Box::pin(async move {
                            println!("[NativeWebRTC] incoming datachannel_open state=Connected");
                            state.store(2, Ordering::SeqCst);
                        })
                    }));
                    let close_state_inner = close_state.clone();
                    channel.on_close(Box::new(move || {
                        let state = close_state_inner.clone();
                        Box::pin(async move {
                            state.store(4, Ordering::SeqCst);
                        })
                    }));
                    let error_state_inner = error_state.clone();
                    channel.on_error(Box::new(move |_| {
                        let state = error_state_inner.clone();
                        Box::pin(async move {
                            state.store(3, Ordering::SeqCst);
                        })
                    }));
                    let message_handler_inner = message_handler.clone();
                    let message_interceptors_inner = message_interceptors.clone();
                    let pending_messages_inner = pending_messages.clone();
                    let pong_tx_inner = pong_tx.clone();
                    let ping_tx_inner = ping_tx.clone();
                    let latency_waiters_inner = latency_waiters.clone();
                    channel.on_message(Box::new(move |message: DataChannelMessage| {
                        let handler = message_handler_inner.clone();
                        let interceptors = message_interceptors_inner.clone();
                        let pending_messages = pending_messages_inner.clone();
                        let pong_tx = pong_tx_inner.clone();
                        let ping_tx = ping_tx_inner.clone();
                        let latency_waiters = latency_waiters_inner.clone();
                        Box::pin(async move {
                            Self::dispatch_or_buffer_message(
                                &handler,
                                &interceptors,
                                &pending_messages,
                                &pong_tx,
                                &ping_tx,
                                &latency_waiters,
                                message.data,
                            )
                            .await;
                        })
                    }));
                    let mut guard = slot.write().await;
                    if guard.is_none() {
                        *guard = Some(channel);
                    }
                })
            }));

        let signal_sender = self.signal_sender.clone();
        let negotiation_id = self.negotiation_id.clone();
        self.peer_connection
            .on_ice_candidate(Box::new(move |candidate| {
                let sender = signal_sender.clone();
                let negotiation_id = negotiation_id.clone();
                Box::pin(async move {
                    let Some(candidate) = candidate else {
                        return;
                    };
                    let Ok(candidate_init) = candidate.to_json() else {
                        return;
                    };
                    let negotiation_id_value = negotiation_id
                        .read()
                        .expect("negotiation_id lock poisoned")
                        .clone();
                    let envelope = serde_json::json!({
                        "type": "#pluto-signal",
                        "content": {
                            "transport": "webrtc",
                            "type": "candidate",
                            "negotiationId": negotiation_id_value,
                            "candidate": candidate_init,
                        }
                    });
                    sender(envelope).await;
                })
            }));

        let dc_init = RTCDataChannelInit {
            negotiated: Some(0),
            ..Default::default()
        };
        let data_channel = self
            .peer_connection
            .create_data_channel("pluto-dc", Some(dc_init))
            .await?;

        let open_state = self.state.clone();
        let open_channel = data_channel.clone();
        data_channel.on_open(Box::new(move || {
            let state = open_state.clone();
            let _channel = open_channel.clone();
            Box::pin(async move {
                println!("[NativeWebRTC] datachannel_open state=Connected");
                state.store(2, Ordering::SeqCst);
                // Negotiated dataChannels (id=0) open independently on both sides;
                // no in-band probe is needed. The channel open event is sufficient.
            })
        }));

        let close_state = self.state.clone();
        data_channel.on_close(Box::new(move || {
            let state = close_state.clone();
            Box::pin(async move {
                // DataChannel close is authoritative: it fires when SCTP sees
                // ErrChunk (remote DTLS/SCTP teardown, e.g. browser refresh)
                // or when the remote explicitly closes the channel. Previously
                // we suppressed this while PC was still Connected to avoid
                // false churn from Chrome DTLS extension noise, but that caused
                // the session to linger ~5s until PC finally flipped to
                // Disconnected — long enough for a new iroh connection to
                // arrive and be blocked by the zombie session. Mark Closed
                // immediately so upstream tear-down and replacement can run.
                println!("[NativeWebRTC] datachannel_close state=Closed");
                state.store(4, Ordering::SeqCst);
            })
        }));

        let error_state = self.state.clone();
        let outgoing_pending_messages = self.pending_messages.clone();
        data_channel.on_error(Box::new(move |_| {
            let state = error_state.clone();
            Box::pin(async move {
                println!("[NativeWebRTC] datachannel_error state=Failed");
                state.store(3, Ordering::SeqCst);
            })
        }));

        let outgoing_message_handler = self.message_handler.clone();
        let outgoing_message_interceptors = self.message_interceptors.clone();
        let outgoing_pending_messages_inner = outgoing_pending_messages.clone();
        let outgoing_pong_tx = self.heartbeat_pong_tx.clone();
        let outgoing_ping_tx = self.heartbeat_ping_tx.clone();
        let outgoing_latency_waiters = self.latency_waiters.clone();
        data_channel.on_message(Box::new(move |message: DataChannelMessage| {
            let handler = outgoing_message_handler.clone();
            let interceptors = outgoing_message_interceptors.clone();
            let pending_messages = outgoing_pending_messages_inner.clone();
            let pong_tx = outgoing_pong_tx.clone();
            let ping_tx = outgoing_ping_tx.clone();
            let latency_waiters = outgoing_latency_waiters.clone();
            Box::pin(async move {
                Self::dispatch_or_buffer_message(
                    &handler,
                    &interceptors,
                    &pending_messages,
                    &pong_tx,
                    &ping_tx,
                    &latency_waiters,
                    message.data,
                )
                .await;
            })
        }));

        {
            let mut guard = self.data_channel.write().await;
            *guard = Some(data_channel);
        }

        if self.is_initiator {
            println!(
                "[NativeWebRTC] role=initiator creating initial offer local_node_id={} remote_node_id={}",
                self.local_node_id,
                self.remote_node_id,
            );
            let offer = self.peer_connection.create_offer(None).await?;
            self.peer_connection
                .set_local_description(offer.clone())
                .await?;
            self.send_sdp_signal(&offer).await;
        } else {
            println!(
                "[NativeWebRTC] role=responder awaiting remote offer local_node_id={} remote_node_id={}",
                self.local_node_id,
                self.remote_node_id,
            );
            self.send_renegotiate_signal().await;
        }

        Ok(())
    }

    pub async fn set_message_handler(&self, handler: NativeWebRTCMessageHandler) {
        {
            let mut guard = self.message_handler.write().await;
            *guard = Some(handler.clone());
        }

        let pending = {
            let mut guard = self.pending_messages.lock().await;
            std::mem::take(&mut *guard)
        };

        if !pending.is_empty() {
            println!(
                "[NativeWebRTC] flushing {} buffered datachannel message(s) after handler registration",
                pending.len()
            );
        }

        for message in pending {
            handler(message).await;
        }
    }

    pub async fn add_message_interceptor(&self, interceptor: NativeWebRTCMessageInterceptor) {
        let mut guard = self.message_interceptors.write().await;
        guard.push(interceptor);
    }

    pub async fn handle_signal(&self, signal: WebRTCSignalMessage) -> Result<()> {
        if signal.transport != "webrtc" {
            return Ok(());
        }
        if let Some(signal_negotiation_id) = signal
            .negotiation_id
            .as_deref()
            .map(str::trim)
            .filter(|value| !value.is_empty())
        {
            let active_negotiation_id = self.negotiation_id();
            if signal_negotiation_id != active_negotiation_id {
                // Allow the responder to adopt the remote negotiation id on the
                // first inbound SDP offer. The web initiator generates `conn-...`
                // ids, while native retry loops may have started with a `native-...`
                // id; strict equality here causes permanent "no remote SDP" timeouts.
                //
                // Once we see an SDP offer, bind this session to that id so replies
                // (answer/candidates) use the same negotiation id the initiator expects.
                if !self.is_initiator
                    && signal.signal_type == "sdp"
                    && self.peer_connection.remote_description().await.is_none()
                    && signal.sdp.as_ref().is_some_and(|value| {
                        value
                            .get("type")
                            .and_then(serde_json::Value::as_str)
                            .map(|t| t == "offer")
                            .unwrap_or(false)
                    })
                {
                    if let Ok(mut guard) = self.negotiation_id.write() {
                        *guard = signal_negotiation_id.to_string();
                    }
                } else {
                    println!(
                    "[NativeWebRTC] ignoring stale signal type={} signal_negotiation_id={} active_negotiation_id={}",
                    signal.signal_type,
                    signal_negotiation_id,
                    active_negotiation_id
                );
                    return Ok(());
                }
            }
        }

        if self.state() == NativeWebRTCState::Idle {
            self.state.store(1, Ordering::SeqCst);
        }
        println!(
            "[NativeWebRTC] handle_signal type={} role={} local_node_id={} remote_node_id={}",
            signal.signal_type,
            if self.is_initiator {
                "initiator"
            } else {
                "responder"
            },
            self.local_node_id,
            self.remote_node_id,
        );

        match signal.signal_type.as_str() {
            "sdp" => {
                let sdp_value = signal
                    .sdp
                    .context("missing webrtc sdp payload for signal type=sdp")?;
                let session = parse_session_description(sdp_value)?;
                let remote_sdp_type = session.sdp_type;

                self.peer_connection.set_remote_description(session).await?;
                self.flush_pending_candidates().await?;

                if !self.is_initiator && remote_sdp_type == RTCSdpType::Offer {
                    let answer = self.peer_connection.create_answer(None).await?;
                    self.peer_connection
                        .set_local_description(answer.clone())
                        .await?;
                    self.send_sdp_signal(&answer).await;
                }
            }
            "candidate" => {
                let candidate = signal
                    .candidate
                    .context("missing webrtc candidate payload for signal type=candidate")?;
                let candidate_init = parse_ice_candidate_init(candidate)?;

                if self.peer_connection.remote_description().await.is_some() {
                    self.peer_connection
                        .add_ice_candidate(candidate_init)
                        .await?;
                } else {
                    self.pending_candidates.lock().await.push(candidate_init);
                }
            }
            _ => {}
        }

        Ok(())
    }

    pub async fn send(&self, data: &[u8]) -> Result<()> {
        anyhow::ensure!(
            self.state() == NativeWebRTCState::Connected,
            "native webrtc datachannel not connected"
        );

        let channel = {
            let guard = self.data_channel.read().await;
            guard
                .as_ref()
                .cloned()
                .context("native webrtc datachannel handle is missing")?
        };
        channel.send(&Bytes::copy_from_slice(data)).await?;
        Ok(())
    }

    pub async fn selected_ice_pair_summary(&self) -> Option<NativeWebRTCIcePairSummary> {
        let sctp = self.peer_connection.sctp();
        let dtls = sctp.transport();
        let pair = dtls.ice_transport().get_selected_candidate_pair().await?;
        Some(NativeWebRTCIcePairSummary {
            local_candidate_type: native_candidate_type(pair.local.typ)?,
            remote_candidate_type: native_candidate_type(pair.remote.typ)?,
            local_ip: pair.local.address,
            remote_ip: pair.remote.address,
        })
    }

    pub async fn measure_latency(
        &self,
        timeout: std::time::Duration,
        samples: usize,
    ) -> Result<u64> {
        anyhow::ensure!(
            self.state() == NativeWebRTCState::Connected,
            "native webrtc datachannel not connected"
        );

        let sample_count = samples.clamp(1, 10);
        let mut measured = Vec::with_capacity(sample_count);
        for index in 0..sample_count {
            let seq = next_latency_probe_seq(index);
            let (tx, rx) = oneshot::channel();
            self.latency_waiters.lock().await.insert(seq, tx);

            let started = std::time::Instant::now();
            let frame = codec::build_webrtc_ping(seq, codec::now_unix_ms());
            if let Err(error) = self.send(&frame).await {
                self.latency_waiters.lock().await.remove(&seq);
                return Err(error);
            }

            match tokio::time::timeout(timeout, rx).await {
                Ok(Ok(_pong)) => {
                    measured.push(started.elapsed().as_millis() as u64);
                }
                Ok(Err(_closed)) => {
                    self.latency_waiters.lock().await.remove(&seq);
                    anyhow::bail!("native webrtc latency waiter closed");
                }
                Err(_elapsed) => {
                    self.latency_waiters.lock().await.remove(&seq);
                    anyhow::bail!(
                        "native webrtc latency probe timed out after {}ms",
                        timeout.as_millis()
                    );
                }
            }
        }

        anyhow::ensure!(
            !measured.is_empty(),
            "native webrtc latency probe produced no samples"
        );
        Ok(measured.iter().sum::<u64>() / measured.len() as u64)
    }

    /// Latest passive heartbeat RTT for this data-channel generation.
    pub async fn latency_ms(&self) -> Option<u64> {
        let guard = self.heartbeat_handle.lock().await;
        let heartbeat = guard.as_ref()?;
        heartbeat.latency_ms().await
    }

    pub fn close(&self) {
        self.state.store(4, Ordering::SeqCst);

        let handle_slot = self.heartbeat_handle.clone();
        let pong_tx_slot = self.heartbeat_pong_tx.clone();
        let ping_tx_slot = self.heartbeat_ping_tx.clone();
        let grace_slot = self.ice_grace_timer.clone();
        let data_channel_slot = self.data_channel.clone();
        let message_handler_slot = self.message_handler.clone();
        let pending_messages = self.pending_messages.clone();
        let pending_candidates = self.pending_candidates.clone();
        let latency_waiters = self.latency_waiters.clone();
        let pc = self.peer_connection.clone();
        if let Ok(handle) = tokio::runtime::Handle::try_current() {
            handle.spawn(async move {
                if let Some(timer) = grace_slot.lock().await.take() {
                    timer.abort();
                }
                stop_heartbeat(&handle_slot, &pong_tx_slot, &ping_tx_slot).await;
                *data_channel_slot.write().await = None;
                *message_handler_slot.write().await = None;
                pending_messages.lock().await.clear();
                pending_candidates.lock().await.clear();
                latency_waiters.lock().await.clear();
                let _ = pc.close().await;
            });
        }
    }

    async fn flush_pending_candidates(&self) -> Result<()> {
        if self.peer_connection.remote_description().await.is_none() {
            return Ok(());
        }

        let mut pending = self.pending_candidates.lock().await;
        for candidate in pending.drain(..) {
            self.peer_connection.add_ice_candidate(candidate).await?;
        }
        Ok(())
    }

    async fn send_sdp_signal(&self, description: &RTCSessionDescription) {
        let negotiation_id = self.negotiation_id();
        send_sdp_envelope(&self.signal_sender, &negotiation_id, description).await;
    }

    async fn send_renegotiate_signal(&self) {
        let negotiation_id = self.negotiation_id();
        let envelope = serde_json::json!({
            "type": "#pluto-signal",
            "content": {
                "transport": "webrtc",
                "type": "renegotiate",
                "negotiationId": negotiation_id,
            }
        });
        self.signal_sender.as_ref()(envelope).await;
    }
}

fn next_latency_probe_seq(index: usize) -> u64 {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|value| value.as_nanos() as u64)
        .unwrap_or_default();
    now ^ ((std::process::id() as u64) << 32) ^ index as u64
}

async fn send_sdp_envelope(
    signal_sender: &super::NativeWebRTCSignalSender,
    negotiation_id: &str,
    description: &RTCSessionDescription,
) {
    let envelope = serde_json::json!({
        "type": "#pluto-signal",
        "content": {
            "transport": "webrtc",
            "type": "sdp",
            "negotiationId": negotiation_id,
            "sdp": {
                "type": sdp_type_to_wire(&description.sdp_type),
                "sdp": description.sdp.clone(),
            }
        }
    });
    signal_sender(envelope).await;
}

async fn stop_heartbeat(
    handle_slot: &Arc<Mutex<Option<TransportHeartbeat>>>,
    pong_tx_slot: &Arc<Mutex<Option<mpsc::Sender<codec::Pong>>>>,
    ping_tx_slot: &Arc<Mutex<Option<mpsc::Sender<codec::Ping>>>>,
) {
    if let Some(hb) = handle_slot.lock().await.take() {
        hb.cancel();
    }
    pong_tx_slot.lock().await.take();
    ping_tx_slot.lock().await.take();
}

fn ensure_rustls_crypto_provider() {
    static INIT: Once = Once::new();
    INIT.call_once(|| {
        let _ = rustls::crypto::ring::default_provider().install_default();
    });
}

fn parse_session_description(value: serde_json::Value) -> Result<RTCSessionDescription> {
    let parsed: SignalSessionDescription =
        serde_json::from_value(value).context("invalid webrtc session description payload")?;

    match parsed.sdp_type.as_str() {
        "offer" => RTCSessionDescription::offer(parsed.sdp)
            .context("failed to build webrtc offer from signal"),
        "answer" => RTCSessionDescription::answer(parsed.sdp)
            .context("failed to build webrtc answer from signal"),
        other => anyhow::bail!("unsupported webrtc sdp type from signal: {other}"),
    }
}

fn parse_ice_candidate_init(value: serde_json::Value) -> Result<RTCIceCandidateInit> {
    if let Ok(candidate) = serde_json::from_value::<RTCIceCandidateInit>(value.clone()) {
        return Ok(candidate);
    }

    let normalized = normalize_ice_candidate_payload(value)?;
    serde_json::from_value(normalized).context("invalid webrtc ICE candidate payload")
}

fn normalize_ice_candidate_payload(value: serde_json::Value) -> Result<serde_json::Value> {
    use serde_json::{Map, Value};

    let source = value
        .as_object()
        .context("invalid webrtc ICE candidate payload: expected object")?;

    let nested_candidate = source
        .get("candidate")
        .and_then(|candidate| candidate.as_object());
    let candidate_obj = nested_candidate.unwrap_or(source);

    let mut normalized = Map::new();

    if let Some(candidate) = candidate_obj.get("candidate").cloned() {
        normalized.insert("candidate".to_string(), candidate);
    }

    let sdp_mid = candidate_obj
        .get("sdpMid")
        .cloned()
        .or_else(|| candidate_obj.get("sdp_mid").cloned());
    if let Some(value) = sdp_mid {
        normalized.insert("sdpMid".to_string(), value.clone());
        normalized.insert("sdp_mid".to_string(), value);
    }

    let sdp_mline_index = candidate_obj
        .get("sdpMLineIndex")
        .cloned()
        .or_else(|| candidate_obj.get("sdp_mline_index").cloned());
    if let Some(value) = sdp_mline_index {
        normalized.insert("sdpMLineIndex".to_string(), value.clone());
        normalized.insert("sdp_mline_index".to_string(), value);
    }

    let username_fragment = candidate_obj
        .get("usernameFragment")
        .cloned()
        .or_else(|| candidate_obj.get("username_fragment").cloned());
    if let Some(value) = username_fragment {
        normalized.insert("usernameFragment".to_string(), value.clone());
        normalized.insert("username_fragment".to_string(), value);
    }

    if !normalized.contains_key("candidate") {
        anyhow::bail!("invalid webrtc ICE candidate payload: missing candidate");
    }

    Ok(Value::Object(normalized))
}

fn sdp_type_to_wire(sdp_type: &RTCSdpType) -> &'static str {
    match sdp_type {
        RTCSdpType::Offer => "offer",
        RTCSdpType::Pranswer => "pranswer",
        RTCSdpType::Answer => "answer",
        RTCSdpType::Rollback => "rollback",
        RTCSdpType::Unspecified => "offer",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    use crate::client::WebRTCConfig;
    use tokio::sync::mpsc;

    fn parse_signal_frame(frame: serde_json::Value) -> Option<WebRTCSignalMessage> {
        if frame.get("type").and_then(|value| value.as_str()) != Some("#pluto-signal") {
            return None;
        }
        let content = frame.get("content")?;
        Some(WebRTCSignalMessage {
            transport: content
                .get("transport")
                .and_then(|value| value.as_str())
                .unwrap_or("webrtc")
                .to_string(),
            signal_type: content
                .get("type")
                .and_then(|value| value.as_str())
                .unwrap_or("candidate")
                .to_string(),
            negotiation_id: content
                .get("negotiationId")
                .and_then(|value| value.as_str())
                .map(ToOwned::to_owned),
            sdp: content.get("sdp").cloned(),
            candidate: content.get("candidate").cloned(),
        })
    }

    fn noop_sender() -> super::super::NativeWebRTCSignalSender {
        Arc::new(|_| Box::pin(async move {}))
    }

    #[test]
    fn network_type_selection_only_adds_ipv6_when_routable() {
        assert_eq!(
            network_types_for_routable_ipv6(false),
            vec![NetworkType::Udp4, NetworkType::Tcp4]
        );
        assert_eq!(
            network_types_for_routable_ipv6(true),
            vec![
                NetworkType::Udp4,
                NetworkType::Tcp4,
                NetworkType::Udp6,
                NetworkType::Tcp6,
            ]
        );
    }

    #[test]
    fn parses_multicast_dns_mode_overrides() {
        assert_eq!(
            parse_multicast_dns_mode("disabled"),
            Some(MulticastDnsMode::Disabled)
        );
        assert_eq!(
            parse_multicast_dns_mode("query-only"),
            Some(MulticastDnsMode::QueryOnly)
        );
        assert_eq!(
            parse_multicast_dns_mode("query-and-gather"),
            Some(MulticastDnsMode::QueryAndGather)
        );
        assert_eq!(parse_multicast_dns_mode("surprise"), None);
    }

    #[test]
    fn privacy_mode_disables_multicast_dns() {
        let config = WebRTCConfig {
            ice_servers: vec![],
            privacy_mode: true,
            lan_mode: false,
        };
        assert_eq!(
            configured_multicast_dns_mode(&config),
            MulticastDnsMode::Disabled
        );
    }

    #[test]
    fn transport_label_classifies_selected_ice_pairs_by_route_kind() {
        let pair = |local_candidate_type, remote_candidate_type| NativeWebRTCIcePairSummary {
            local_candidate_type,
            remote_candidate_type,
            local_ip: "192.168.1.10".to_string(),
            remote_ip: "192.168.1.11".to_string(),
        };

        assert_eq!(
            pair(CandidateType::Host, CandidateType::Host).transport_label(),
            crate::transport_label::WEBRTC_LAN
        );
        assert_eq!(
            pair(CandidateType::Relay, CandidateType::Host).transport_label(),
            crate::transport_label::WEBRTC_TURN
        );
        assert_eq!(
            pair(CandidateType::ServerReflexive, CandidateType::PeerReflexive).transport_label(),
            crate::transport_label::WEBRTC_LAN
        );
        assert_eq!(
            pair(CandidateType::PeerReflexive, CandidateType::Host).transport_label(),
            crate::transport_label::WEBRTC_LAN
        );
        let public_pair = NativeWebRTCIcePairSummary {
            local_candidate_type: CandidateType::PeerReflexive,
            remote_candidate_type: CandidateType::ServerReflexive,
            local_ip: "203.0.113.10".to_string(),
            remote_ip: "198.51.100.11".to_string(),
        };
        assert_eq!(
            public_pair.transport_label(),
            crate::transport_label::WEBRTC
        );
        let private_relay_pair = NativeWebRTCIcePairSummary {
            local_candidate_type: CandidateType::Relay,
            remote_candidate_type: CandidateType::Host,
            local_ip: "192.168.1.10".to_string(),
            remote_ip: "192.168.1.11".to_string(),
        };
        assert_eq!(
            private_relay_pair.transport_label(),
            crate::transport_label::WEBRTC_TURN
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn starts_connecting_after_start() {
        let config = WebRTCConfig {
            ice_servers: vec![],
            privacy_mode: false,
            lan_mode: false,
        };
        let ch = NativeWebRTCDataChannel::new(
            "local-b",
            "remote-a",
            &config,
            noop_sender(),
            "negotiation-start",
        )
        .await
        .unwrap();
        ch.start().await.unwrap();
        assert_eq!(ch.state(), NativeWebRTCState::Connecting);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn responder_requests_initiator_offer_on_start() {
        let config = WebRTCConfig {
            ice_servers: vec![],
            privacy_mode: false,
            lan_mode: false,
        };
        let (tx, mut rx) = mpsc::unbounded_channel::<serde_json::Value>();
        let sender: super::super::NativeWebRTCSignalSender = Arc::new(move |signal| {
            let tx = tx.clone();
            Box::pin(async move {
                let _ = tx.send(signal);
            })
        });

        let ch = NativeWebRTCDataChannel::new(
            "node-a",
            "node-z",
            &config,
            sender,
            "negotiation-responder",
        )
        .await
        .unwrap();
        ch.start().await.unwrap();

        let frame = rx
            .recv()
            .await
            .expect("responder should request renegotiate");
        let signal = parse_signal_frame(frame).expect("renegotiate frame should parse");
        assert_eq!(signal.signal_type, "renegotiate");
        assert_eq!(
            signal.negotiation_id.as_deref(),
            Some("negotiation-responder")
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn explicit_responder_role_overrides_node_id_ordering() {
        let config = WebRTCConfig {
            ice_servers: vec![],
            privacy_mode: false,
            lan_mode: false,
        };
        let (tx, mut rx) = mpsc::unbounded_channel::<serde_json::Value>();
        let sender: super::super::NativeWebRTCSignalSender = Arc::new(move |signal| {
            let tx = tx.clone();
            Box::pin(async move {
                let _ = tx.send(signal);
            })
        });

        let ch = NativeWebRTCDataChannel::new_with_role(
            "node-z",
            "node-a",
            &config,
            sender,
            "browser-offer-negotiation",
            NativeWebRTCRole::Responder,
        )
        .await
        .unwrap();
        ch.start().await.unwrap();

        let frame = rx
            .recv()
            .await
            .expect("forced responder should request a browser offer");
        let signal = parse_signal_frame(frame).expect("renegotiate frame should parse");
        assert_eq!(signal.signal_type, "renegotiate");
        assert!(!ch.is_initiator());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn responder_adopts_first_offer_negotiation_id_once() {
        let config = WebRTCConfig {
            ice_servers: vec![],
            privacy_mode: false,
            lan_mode: false,
        };

        let (offer_tx, mut offer_rx) = mpsc::unbounded_channel::<serde_json::Value>();
        let initiator_sender: super::super::NativeWebRTCSignalSender = Arc::new(move |signal| {
            let offer_tx = offer_tx.clone();
            Box::pin(async move {
                let _ = offer_tx.send(signal);
            })
        });

        let initiator = NativeWebRTCDataChannel::new(
            "node-z",
            "node-a",
            &config,
            initiator_sender,
            "offer-negotiation",
        )
        .await
        .unwrap();
        initiator.start().await.unwrap();

        let offer = loop {
            let frame = offer_rx.recv().await.expect("initiator should emit offer");
            let Some(signal) = parse_signal_frame(frame) else {
                continue;
            };
            if signal.signal_type == "sdp" {
                break signal;
            }
        };

        let responder = NativeWebRTCDataChannel::new(
            "node-a",
            "node-z",
            &config,
            noop_sender(),
            "responder-provisional",
        )
        .await
        .unwrap();
        responder.start().await.unwrap();

        responder.handle_signal(offer.clone()).await.unwrap();
        assert_eq!(responder.negotiation_id(), "offer-negotiation");

        let mut stale_offer = offer;
        stale_offer.negotiation_id = Some("stale-offer".to_string());
        responder.handle_signal(stale_offer).await.unwrap();
        assert_eq!(
            responder.negotiation_id(),
            "offer-negotiation",
            "after applying a remote description, later mismatched offers are stale"
        );

        initiator.close();
        responder.close();
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn responder_ignores_stale_candidate_after_adopting_offer_negotiation_id() {
        let config = WebRTCConfig {
            ice_servers: vec![],
            privacy_mode: false,
            lan_mode: false,
        };

        let (offer_tx, mut offer_rx) = mpsc::unbounded_channel::<serde_json::Value>();
        let initiator_sender: super::super::NativeWebRTCSignalSender = Arc::new(move |signal| {
            let offer_tx = offer_tx.clone();
            Box::pin(async move {
                let _ = offer_tx.send(signal);
            })
        });

        let initiator = NativeWebRTCDataChannel::new(
            "node-z",
            "node-a",
            &config,
            initiator_sender,
            "offer-negotiation",
        )
        .await
        .unwrap();
        initiator.start().await.unwrap();

        let offer = loop {
            let frame = offer_rx.recv().await.expect("initiator should emit offer");
            let Some(signal) = parse_signal_frame(frame) else {
                continue;
            };
            if signal.signal_type == "sdp" {
                break signal;
            }
        };

        let responder = NativeWebRTCDataChannel::new(
            "node-a",
            "node-z",
            &config,
            noop_sender(),
            "responder-provisional",
        )
        .await
        .unwrap();
        responder.start().await.unwrap();

        responder.handle_signal(offer).await.unwrap();
        assert_eq!(responder.negotiation_id(), "offer-negotiation");

        responder
            .handle_signal(WebRTCSignalMessage {
                transport: "webrtc".to_string(),
                signal_type: "candidate".to_string(),
                negotiation_id: Some("stale-offer".to_string()),
                sdp: None,
                candidate: Some(serde_json::json!({
                    "candidate": "this malformed candidate must never be parsed",
                })),
            })
            .await
            .expect("stale mismatched candidate should be ignored before parsing");

        assert!(
            responder.pending_candidates.lock().await.is_empty(),
            "stale candidate must not be buffered into the live negotiation"
        );

        initiator.close();
        responder.close();
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn loopback_offer_answer_candidate_reaches_connected() {
        let config = WebRTCConfig {
            ice_servers: vec![],
            privacy_mode: false,
            lan_mode: true,
        };

        let (a_to_b_tx, mut a_to_b_rx) = mpsc::unbounded_channel::<serde_json::Value>();
        let (b_to_a_tx, mut b_to_a_rx) = mpsc::unbounded_channel::<serde_json::Value>();
        let left_candidates = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
        let right_candidates = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));

        let left_candidates_for_sender = left_candidates.clone();
        let sender_a: super::super::NativeWebRTCSignalSender = Arc::new(move |signal| {
            if let Some(candidate) = signal
                .get("content")
                .and_then(|content| content.get("candidate"))
                .and_then(|candidate| candidate.get("candidate"))
                .and_then(|candidate| candidate.as_str())
            {
                left_candidates_for_sender
                    .lock()
                    .expect("left candidates lock")
                    .push(candidate.to_string());
            }
            let tx = a_to_b_tx.clone();
            Box::pin(async move {
                let _ = tx.send(signal);
            })
        });
        let right_candidates_for_sender = right_candidates.clone();
        let sender_b: super::super::NativeWebRTCSignalSender = Arc::new(move |signal| {
            if let Some(candidate) = signal
                .get("content")
                .and_then(|content| content.get("candidate"))
                .and_then(|candidate| candidate.get("candidate"))
                .and_then(|candidate| candidate.as_str())
            {
                right_candidates_for_sender
                    .lock()
                    .expect("right candidates lock")
                    .push(candidate.to_string());
            }
            let tx = b_to_a_tx.clone();
            Box::pin(async move {
                let _ = tx.send(signal);
            })
        });

        let left = Arc::new(
            NativeWebRTCDataChannel::new(
                "node-z",
                "node-a",
                &config,
                sender_a,
                "negotiation-loopback",
            )
            .await
            .unwrap(),
        );
        let right = Arc::new(
            NativeWebRTCDataChannel::new(
                "node-a",
                "node-z",
                &config,
                sender_b,
                "negotiation-loopback",
            )
            .await
            .unwrap(),
        );

        let right_for_relay = right.clone();
        let relay_a_to_b = tokio::spawn(async move {
            while let Some(frame) = a_to_b_rx.recv().await {
                let Some(signal) = parse_signal_frame(frame) else {
                    continue;
                };
                let _ = right_for_relay.handle_signal(signal).await;
            }
        });

        let left_for_relay = left.clone();
        let relay_b_to_a = tokio::spawn(async move {
            while let Some(frame) = b_to_a_rx.recv().await {
                let Some(signal) = parse_signal_frame(frame) else {
                    continue;
                };
                let _ = left_for_relay.handle_signal(signal).await;
            }
        });

        left.start().await.unwrap();
        right.start().await.unwrap();

        tokio::time::timeout(Duration::from_secs(10), async {
            loop {
                if left.state() == NativeWebRTCState::Connected
                    && right.state() == NativeWebRTCState::Connected
                {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(50)).await;
            }
        })
        .await
        .expect("native webrtc loopback should connect");

        left.send(b"hello-from-left").await.unwrap();

        let exchanged_candidates = {
            let mut candidates = left_candidates
                .lock()
                .expect("left candidates lock")
                .clone();
            candidates.extend(
                right_candidates
                    .lock()
                    .expect("right candidates lock")
                    .iter()
                    .cloned(),
            );
            candidates
        };
        assert!(
            !exchanged_candidates.is_empty(),
            "native webrtc LAN test should exchange ICE candidates"
        );
        assert!(
            exchanged_candidates
                .iter()
                .all(|candidate| candidate.contains(" typ host")),
            "native webrtc LAN test should exchange only host candidates: {:?}",
            exchanged_candidates
        );
        assert!(
            exchanged_candidates
                .iter()
                .all(|candidate| !candidate.contains(" typ relay")),
            "native webrtc LAN test should not exchange relay candidates: {:?}",
            exchanged_candidates
        );

        left.close();
        right.close();

        relay_a_to_b.abort();
        relay_b_to_a.abort();
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn ice_restart_state_defaults() {
        // Regression test for F3: new channel starts with ice_restart_attempted=false
        // and no grace timer. These defaults are the preconditions for the
        // Disconnected-grace handler to attempt restart_ice exactly once.
        let config = WebRTCConfig {
            ice_servers: vec![],
            privacy_mode: false,
            lan_mode: false,
        };
        let ch = NativeWebRTCDataChannel::new(
            "local-b",
            "remote-a",
            &config,
            noop_sender(),
            "negotiation-ice-defaults",
        )
        .await
        .unwrap();
        assert!(
            !ch.ice_restart_attempted.load(Ordering::SeqCst),
            "ice_restart_attempted must default false"
        );
        assert!(
            ch.ice_grace_timer.lock().await.is_none(),
            "ice_grace_timer must default None"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn wrong_transport_signal_is_ignored() {
        let config = WebRTCConfig {
            ice_servers: vec![],
            privacy_mode: false,
            lan_mode: false,
        };
        let ch = NativeWebRTCDataChannel::new(
            "local-b",
            "remote-a",
            &config,
            noop_sender(),
            "negotiation-ignore",
        )
        .await
        .unwrap();
        ch.start().await.unwrap();

        ch.handle_signal(WebRTCSignalMessage {
            transport: "moq".to_string(),
            signal_type: "sdp".to_string(),
            negotiation_id: Some("negotiation-ignore".to_string()),
            sdp: Some(serde_json::json!({ "type": "offer", "sdp": "v=0\r\n" })),
            candidate: None,
        })
        .await
        .unwrap();

        assert_eq!(ch.state(), NativeWebRTCState::Connecting);
    }
}