whatsapp-rust 0.7.0

Rust client for WhatsApp Web
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
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
//! Call-control accessor. Reject/terminate are always available since their stanza builders live in
//! core; the high-level call/accept flows, including their signaling, need the `voip` feature.

#[cfg(feature = "voip-runtime")]
use std::mem::size_of;
#[cfg(feature = "voip-runtime")]
use std::sync::Arc;
#[cfg(feature = "voip-runtime")]
use std::time::Duration;

#[cfg(feature = "voip-runtime")]
use log::warn;
use wacore::stanza::call::{TerminateParams, build_reject, build_terminate};
#[cfg(feature = "voip-runtime")]
use wacore::stanza::group_call::{
    build_active_group_accept, build_active_group_preaccept, build_call_link_create,
    build_call_link_join_with_capability, build_call_link_query, build_raise_hand,
    build_screen_share, build_waiting_room_admit, build_waiting_room_deny,
    build_waiting_room_heartbeat, build_waiting_room_toggle, parse_call_link_create_ack,
    parse_call_link_join_ack, parse_call_link_join_call_id, parse_call_link_query_ack,
    parse_waiting_room_admit_ack, parse_waiting_room_deny_ack, parse_waiting_room_toggle_ack,
};
use wacore::types::call::IncomingCall;
#[cfg(feature = "voip-runtime")]
use wacore::types::call::{CallAction, VideoState};
#[cfg(feature = "voip-runtime")]
use wacore::types::group_call::{
    CallLink, CallLinkJoin, CallLinkMedia, CallLinkPreview, GroupCallUpdate, ScreenShare,
    ScreenShareState, WaitingRoom,
};
#[cfg(feature = "voip-runtime")]
use wacore::voip::{AudioFormat, CallEvent, CallPhase, CallSession, VideoControl};
use wacore_binary::Jid;
#[cfg(feature = "voip-runtime")]
use wacore_binary::Node;
#[cfg(feature = "voip-runtime")]
use wacore_binary::Server;
#[cfg(feature = "voip-runtime")]
use zeroize::Zeroizing;

#[cfg(feature = "voip-runtime")]
use super::ResponseWaiter;
use super::{Client, ClientError};

#[cfg(feature = "voip-runtime")]
const CALL_SERVICE_REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
#[cfg(feature = "voip-runtime")]
const WAITING_ROOM_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(10);
#[cfg(feature = "voip-runtime")]
const WAITING_ROOM_HEARTBEAT_MAX_CONSECUTIVE_FAILURES: u8 = 3;
#[cfg(feature = "voip-runtime")]
const MAX_PENDING_CALL_LINK_TRANSITIONS: usize = 32;
#[cfg(feature = "voip-runtime")]
const MAX_PENDING_CALL_LINK_TRANSITION_BYTES: usize = 1024 * 1024;
#[cfg(feature = "voip-runtime")]
const MAX_PENDING_CALL_LINK_SATURATION_FINGERPRINTS: usize = 32;

/// Opaque call-control handle obtained via [`Client::voip`]. Borrows the client;
/// kept as a newtype so the surface can grow without breaking callers.
pub struct Voip<'a> {
    client: &'a Client,
}

#[cfg(feature = "voip-runtime")]
struct CallLinkRegistrationGuard {
    client: std::sync::Weak<Client>,
    registry: Arc<wacore::voip::CallRegistry>,
    call_id: String,
    call_creator: Jid,
    generation: u64,
    armed: bool,
}

#[cfg(feature = "voip-runtime")]
pub(crate) struct CallLinkJoinRegistration {
    pub(crate) join: CallLinkJoin,
    pub(crate) generation: u64,
}

#[cfg(feature = "voip-runtime")]
#[derive(Clone, Copy)]
enum WaitingRoomUserAction {
    Admit,
    Deny,
}

#[cfg(feature = "voip-runtime")]
enum PendingCallLinkTransition {
    Group(Box<GroupCallUpdate>),
    WaitingRoom(WaitingRoom),
    RawEpoch {
        call_creator: Jid,
        sender: Jid,
        transaction_id: u32,
        raw_epoch: Zeroizing<Vec<u8>>,
    },
    Terminated {
        call_creator: Jid,
        sender: Jid,
    },
    Saturated,
}

#[cfg(feature = "voip-runtime")]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PendingCallLinkBuffer {
    NotPending,
    Buffered,
    Saturated,
}

#[cfg(feature = "voip-runtime")]
impl PendingCallLinkBuffer {
    pub(crate) fn suppresses_dispatch(self) -> bool {
        self != Self::NotPending
    }
}

#[cfg(feature = "voip-runtime")]
impl PendingCallLinkTransition {
    fn group_heap_bytes(update: &GroupCallUpdate) -> usize {
        use wacore::stats::HeapSize;

        size_of::<GroupCallUpdate>() + update.heap_bytes()
    }

    fn waiting_room_heap_bytes(room: &WaitingRoom) -> usize {
        use wacore::stats::HeapSize;

        room.heap_bytes()
    }

    fn heap_bytes(&self) -> usize {
        use wacore::stats::HeapSize;

        match self {
            Self::Group(update) => Self::group_heap_bytes(update),
            Self::WaitingRoom(room) => Self::waiting_room_heap_bytes(room),
            Self::RawEpoch {
                call_creator,
                sender,
                raw_epoch,
                ..
            } => call_creator
                .heap_bytes()
                .saturating_add(sender.heap_bytes())
                .saturating_add(raw_epoch.capacity()),
            Self::Terminated {
                call_creator,
                sender,
            } => call_creator
                .heap_bytes()
                .saturating_add(sender.heap_bytes()),
            Self::Saturated => 0,
        }
    }
}

#[cfg(feature = "voip-runtime")]
#[derive(Default)]
pub(super) struct PendingCallLinkJoins {
    active: usize,
    bound_call_id: Option<String>,
    transitions: std::collections::HashMap<String, Vec<PendingCallLinkTransition>>,
    saturation_fingerprints: Vec<u64>,
    saturation_hash_builder: std::collections::hash_map::RandomState,
    untracked_saturation: bool,
}

#[cfg(feature = "voip-runtime")]
impl PendingCallLinkJoins {
    fn accepts(&self, call_id: &str) -> bool {
        self.bound_call_id
            .as_deref()
            .is_none_or(|bound| bound == call_id)
    }

    fn can_buffer_transition(&self, call_id: &str, payload_bytes: usize) -> bool {
        use wacore::stats::HeapSize;

        let entries = self.transitions.values().map(Vec::len).sum::<usize>();
        if entries >= MAX_PENDING_CALL_LINK_TRANSITIONS {
            return false;
        }
        let new_key_bytes = if self.transitions.contains_key(call_id) {
            0
        } else {
            size_of::<String>() + call_id.heap_bytes()
        };
        let structural_reserve = MAX_PENDING_CALL_LINK_TRANSITIONS
            .saturating_mul(size_of::<PendingCallLinkTransition>());
        self.memory_stats()
            .bytes
            .saturating_add(payload_bytes.try_into().unwrap_or(u64::MAX))
            .saturating_add(new_key_bytes.try_into().unwrap_or(u64::MAX))
            .saturating_add(structural_reserve.try_into().unwrap_or(u64::MAX))
            <= MAX_PENDING_CALL_LINK_TRANSITION_BYTES as u64
    }

    fn bind_call_id(&mut self, call_id: &str) {
        let fingerprint = self.call_id_fingerprint(call_id);
        self.bound_call_id = Some(call_id.to_string());
        self.transitions.retain(|retained, _| retained == call_id);
        self.saturation_fingerprints
            .retain(|retained| *retained == fingerprint);
    }

    fn prepare_bound_retry(&mut self, call_id: &str) -> bool {
        if !self.untracked_saturation || self.bound_call_id.as_deref() != Some(call_id) {
            return false;
        }
        // The first ACK gives the provisional buffer an exact identity. When unrelated traffic
        // exhausted even the overflow fingerprints, retry the join from that bound state instead
        // of either failing the valid call or silently ignoring a possibly dropped transition.
        // The refreshed ACK is the new authoritative floor; controls racing the retry are retained
        // only for this call id and replayed after it.
        self.transitions.clear();
        self.saturation_fingerprints.clear();
        self.untracked_saturation = false;
        true
    }

    fn is_saturated(&self, call_id: &str) -> bool {
        self.untracked_saturation
            || self
                .saturation_fingerprints
                .contains(&self.call_id_fingerprint(call_id))
            || self.transitions.get(call_id).is_some_and(|transitions| {
                transitions
                    .iter()
                    .any(|transition| matches!(transition, PendingCallLinkTransition::Saturated))
            })
    }

    fn call_id_fingerprint(&self, call_id: &str) -> u64 {
        use std::hash::BuildHasher;

        self.saturation_hash_builder.hash_one(call_id)
    }

    fn mark_saturated(&mut self, call_id: &str) {
        // Saturation belongs to the call whose transition could not be retained. An unrelated
        // creator-authenticated control must not poison the one unknown call-link join that owns
        // this bounded buffer.
        self.transitions.remove(call_id);
        if self.can_buffer_transition(call_id, 0) {
            self.transitions.insert(
                call_id.to_string(),
                vec![PendingCallLinkTransition::Saturated],
            );
            return;
        }
        let fingerprint = self.call_id_fingerprint(call_id);
        if self.saturation_fingerprints.contains(&fingerprint) {
            return;
        }
        if self.saturation_fingerprints.len() < MAX_PENDING_CALL_LINK_SATURATION_FINGERPRINTS {
            // Keep the failure identity in fixed-size metadata even when unrelated payloads have
            // consumed every transition slot. Binding the ACK can then fail exactly the join whose
            // admission state was dropped without letting unrelated saturation poison it.
            self.saturation_fingerprints.push(fingerprint);
        } else {
            // If even the bounded fingerprint reserve is exhausted, remember that exact
            // membership is ambiguous. Once the ACK binds a call id, the join path refreshes its
            // authoritative state before registration instead of guessing or failing another id.
            self.untracked_saturation = true;
        }
    }

    pub(super) fn memory_stats(&self) -> wacore::stats::CollectionStats {
        use wacore::stats::HeapSize;

        let transition_bytes = self
            .transitions
            .iter()
            .map(|(call_id, transitions)| {
                size_of::<String>()
                    + call_id.heap_bytes()
                    + transitions.capacity() * size_of::<PendingCallLinkTransition>()
                    + transitions
                        .iter()
                        .map(PendingCallLinkTransition::heap_bytes)
                        .sum::<usize>()
            })
            .sum::<usize>();
        let bytes = transition_bytes
            .saturating_add(self.saturation_fingerprints.capacity() * size_of::<u64>());
        wacore::stats::CollectionStats::new(
            self.transitions
                .values()
                .map(Vec::len)
                .sum::<usize>()
                .saturating_add(self.saturation_fingerprints.len())
                .saturating_add(usize::from(self.untracked_saturation))
                .try_into()
                .unwrap_or(u64::MAX),
            bytes.try_into().unwrap_or(u64::MAX),
        )
    }
}

#[cfg(feature = "voip-runtime")]
struct PendingCallLinkJoinGuard {
    state: Arc<std::sync::Mutex<PendingCallLinkJoins>>,
}

#[cfg(feature = "voip-runtime")]
impl Drop for PendingCallLinkJoinGuard {
    fn drop(&mut self) {
        let mut state = self
            .state
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        state.active = state.active.saturating_sub(1);
        if state.active == 0 {
            state.bound_call_id = None;
            state.transitions.clear();
            state.saturation_fingerprints.clear();
            state.untracked_saturation = false;
        }
    }
}

#[cfg(feature = "voip-runtime")]
impl CallLinkRegistrationGuard {
    fn new(
        client: &Client,
        registry: Arc<wacore::voip::CallRegistry>,
        call_id: &str,
        call_creator: Jid,
        generation: u64,
    ) -> Self {
        Self {
            client: client.self_weak.get().cloned().unwrap_or_default(),
            registry,
            call_id: call_id.to_string(),
            call_creator,
            generation,
            armed: true,
        }
    }

    fn disarm(&mut self) {
        self.armed = false;
    }
}

#[cfg(feature = "voip-runtime")]
impl Drop for CallLinkRegistrationGuard {
    fn drop(&mut self) {
        if !self.armed {
            return;
        }
        let Some(client) = self.client.upgrade() else {
            self.registry
                .remove_if_current(&self.call_id, self.generation);
            return;
        };
        let registry = self.registry.clone();
        let call_id = self.call_id.clone();
        let call_creator = self.call_creator.clone();
        let generation = self.generation;
        let runtime = client.runtime.clone();
        runtime
            .spawn(Box::pin(async move {
                // A cancelled admitted join is still live on the call service. Claim this exact
                // generation under the replacement lane before deciding whether a wire terminate
                // is required; waiting-room cancellation remains local-only.
                let _transition = client.lock_answer_transition(&call_id).await;
                let Some(phase) = registry.remove_if_current_with_phase(&call_id, generation)
                else {
                    return;
                };
                if phase == CallPhase::WaitingRoom {
                    return;
                }
                let target = Jid::new(&call_id, Server::Call);
                crate::voip::facade::send_answer_terminate(
                    &client,
                    &call_id,
                    &target,
                    &call_creator,
                )
                .await;
            }))
            .detach();
    }
}

impl Client {
    /// Call control: reject/terminate are always available; media (call/accept)
    /// needs the `voip` feature.
    pub fn voip(&self) -> Voip<'_> {
        Voip { client: self }
    }

    /// The per-call media registry the `voip` facade registers active calls in. `pub(crate)` so the
    /// facade and the connection-cleanup teardown share one instance.
    #[cfg(feature = "voip-runtime")]
    pub(crate) fn call_registry(&self) -> Arc<wacore::voip::CallRegistry> {
        self.call_registry.clone()
    }

    #[cfg(feature = "voip-runtime")]
    fn begin_call_link_join(&self) -> PendingCallLinkJoinGuard {
        let mut state = self
            .pending_call_link_joins
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if state.active == 0 {
            state.bound_call_id = None;
            state.transitions.clear();
            state.saturation_fingerprints.clear();
            state.untracked_saturation = false;
        }
        state.active = state.active.saturating_add(1);
        drop(state);
        PendingCallLinkJoinGuard {
            state: self.pending_call_link_joins.clone(),
        }
    }

    #[cfg(feature = "voip-runtime")]
    pub(crate) fn pending_call_link_control_candidate(
        &self,
        call_id: &str,
        call_creator: &Jid,
        sender: &Jid,
    ) -> bool {
        let state = self
            .pending_call_link_joins
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        state.active != 0
            && !call_id.is_empty()
            && state.accepts(call_id)
            && sender.to_non_ad() == call_creator.to_non_ad()
            && self.call_registry.generation_of(call_id).is_none()
    }

    /// Bind the one serialized pending link join to the ACK's exact call id before the read loop
    /// wakes the request task. Controls for unrelated unknown calls can no longer consume its
    /// retained-entry or byte budget during the ACK/registration race.
    #[cfg(feature = "voip-runtime")]
    pub(crate) fn bind_pending_call_link_join_ack(&self, response: &wacore_binary::NodeRef<'_>) {
        let Ok(call_id) = parse_call_link_join_call_id(response) else {
            return;
        };
        let mut state = self
            .pending_call_link_joins
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if state.active != 0 {
            state.bind_call_id(&call_id);
        }
    }

    #[cfg(feature = "voip-runtime")]
    fn prepare_pending_call_link_join_retry(&self, call_id: &str) -> bool {
        let mut state = self
            .pending_call_link_joins
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        state.prepare_bound_retry(call_id)
    }

    /// Buffer a creator-authenticated admission snapshot while its link-join ACK is being
    /// registered. The pending-state lock is shared with registration, closing both orderings of
    /// the ACK/update race without accepting arbitrary unknown calls.
    #[cfg(feature = "voip-runtime")]
    pub(crate) fn buffer_pending_call_link_update(
        &self,
        update: &GroupCallUpdate,
        sender: &Jid,
    ) -> PendingCallLinkBuffer {
        let mut state = self
            .pending_call_link_joins
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if state.active == 0
            || update.call_id.is_empty()
            || !state.accepts(&update.call_id)
            || sender.to_non_ad() != update.call_creator.to_non_ad()
            || self.call_registry.generation_of(&update.call_id).is_some()
        {
            return PendingCallLinkBuffer::NotPending;
        }
        if state.is_saturated(&update.call_id) {
            return PendingCallLinkBuffer::Saturated;
        }
        if state
            .transitions
            .get(&update.call_id)
            .into_iter()
            .flatten()
            .rev()
            .find_map(|transition| match transition {
                PendingCallLinkTransition::Group(update) => Some(update.transaction_id),
                PendingCallLinkTransition::WaitingRoom(_)
                | PendingCallLinkTransition::RawEpoch { .. }
                | PendingCallLinkTransition::Terminated { .. }
                | PendingCallLinkTransition::Saturated => None,
            })
            .is_some_and(|transaction_id| transaction_id >= update.transaction_id)
        {
            return PendingCallLinkBuffer::Buffered;
        }
        if !state.can_buffer_transition(
            &update.call_id,
            PendingCallLinkTransition::group_heap_bytes(update),
        ) {
            state.mark_saturated(&update.call_id);
            return PendingCallLinkBuffer::Saturated;
        }
        state
            .transitions
            .entry(update.call_id.clone())
            .or_default()
            .push(PendingCallLinkTransition::Group(Box::new(update.clone())));
        PendingCallLinkBuffer::Buffered
    }

    /// Retain a creator-authenticated epoch that overtook publication of the call-link generation.
    #[cfg(feature = "voip-runtime")]
    pub(crate) fn buffer_pending_call_link_epoch(
        &self,
        call_id: &str,
        call_creator: &Jid,
        sender: &Jid,
        transaction_id: u32,
        raw_epoch: &[u8],
    ) -> PendingCallLinkBuffer {
        let mut state = self
            .pending_call_link_joins
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if state.active == 0
            || call_id.is_empty()
            || !state.accepts(call_id)
            || sender.to_non_ad() != call_creator.to_non_ad()
            || self.call_registry.generation_of(call_id).is_some()
        {
            return PendingCallLinkBuffer::NotPending;
        }
        if state.is_saturated(call_id) {
            return PendingCallLinkBuffer::Saturated;
        }
        if state
            .transitions
            .get(call_id)
            .into_iter()
            .flatten()
            .rev()
            .find_map(|transition| match transition {
                PendingCallLinkTransition::RawEpoch {
                    call_creator: retained_creator,
                    sender: retained_sender,
                    transaction_id,
                    ..
                } if retained_creator == call_creator && retained_sender == sender => {
                    Some(*transaction_id)
                }
                _ => None,
            })
            .is_some_and(|retained| retained >= transaction_id)
        {
            return PendingCallLinkBuffer::Buffered;
        }
        if !state.can_buffer_transition(call_id, raw_epoch.len()) {
            state.mark_saturated(call_id);
            return PendingCallLinkBuffer::Saturated;
        }
        state
            .transitions
            .entry(call_id.to_string())
            .or_default()
            .push(PendingCallLinkTransition::RawEpoch {
                call_creator: call_creator.clone(),
                sender: sender.clone(),
                transaction_id,
                raw_epoch: Zeroizing::new(raw_epoch.to_vec()),
            });
        PendingCallLinkBuffer::Buffered
    }

    /// Mark a creator-authenticated call-link generation as ended before its ACK is registered.
    #[cfg(feature = "voip-runtime")]
    pub(crate) fn buffer_pending_call_link_terminate(
        &self,
        call_id: &str,
        call_creator: &Jid,
        sender: &Jid,
    ) -> PendingCallLinkBuffer {
        let mut state = self
            .pending_call_link_joins
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if state.active == 0
            || call_id.is_empty()
            || !state.accepts(call_id)
            || sender.to_non_ad() != call_creator.to_non_ad()
            || self.call_registry.generation_of(call_id).is_some()
        {
            return PendingCallLinkBuffer::NotPending;
        }
        if state.is_saturated(call_id) {
            return PendingCallLinkBuffer::Saturated;
        }
        if state
            .transitions
            .get(call_id)
            .into_iter()
            .flatten()
            .any(|transition| {
                matches!(
                    transition,
                    PendingCallLinkTransition::Terminated {
                        call_creator: retained_creator,
                        sender: retained_sender,
                    } if retained_creator == call_creator && retained_sender == sender
                )
            })
        {
            return PendingCallLinkBuffer::Buffered;
        }
        if !state.can_buffer_transition(call_id, 0) {
            state.mark_saturated(call_id);
            return PendingCallLinkBuffer::Saturated;
        }
        state
            .transitions
            .entry(call_id.to_string())
            .or_default()
            .push(PendingCallLinkTransition::Terminated {
                call_creator: call_creator.clone(),
                sender: sender.clone(),
            });
        PendingCallLinkBuffer::Buffered
    }

    /// Serialize a terminal control with publication of the call-link generation it targets.
    #[cfg(feature = "voip-runtime")]
    pub(crate) async fn retain_or_apply_pending_call_link_terminate(
        &self,
        call_id: &str,
        call_creator: &Jid,
        sender: &Jid,
    ) -> bool {
        let _answer_transition = self.lock_answer_transition(call_id).await;
        let buffered = self.buffer_pending_call_link_terminate(call_id, call_creator, sender);
        if buffered.suppresses_dispatch() {
            return true;
        }
        let Some(generation) = self.call_registry.generation_of(call_id) else {
            return false;
        };
        if !self.call_registry.group_creator_authorized_if_current(
            call_id,
            generation,
            call_creator,
            sender,
        ) {
            return false;
        }
        self.call_registry.remove_if_current(call_id, generation)
    }

    /// Buffer a creator-authenticated waiting-room snapshot in the same ordered call-link
    /// transition stream as admission rosters.
    #[cfg(feature = "voip-runtime")]
    pub(crate) fn buffer_pending_call_link_waiting_room(
        &self,
        room: &WaitingRoom,
        sender: &Jid,
    ) -> PendingCallLinkBuffer {
        let mut state = self
            .pending_call_link_joins
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if self.call_registry.generation_of(&room.call_id).is_some()
            || state.active == 0
            || room.call_id.is_empty()
            || !state.accepts(&room.call_id)
            || room.link_token.is_empty()
            || sender.to_non_ad() != room.call_creator.to_non_ad()
        {
            return PendingCallLinkBuffer::NotPending;
        }
        if state.is_saturated(&room.call_id) {
            return PendingCallLinkBuffer::Saturated;
        }
        if !state.can_buffer_transition(
            &room.call_id,
            PendingCallLinkTransition::waiting_room_heap_bytes(room),
        ) {
            state.mark_saturated(&room.call_id);
            return PendingCallLinkBuffer::Saturated;
        }
        state
            .transitions
            .entry(room.call_id.clone())
            .or_default()
            .push(PendingCallLinkTransition::WaitingRoom(room.clone()));
        PendingCallLinkBuffer::Buffered
    }

    #[cfg(feature = "voip-runtime")]
    async fn register_call_link_session(
        &self,
        session: CallSession,
        waiting_room: Option<WaitingRoom>,
        expected_media: CallLinkMedia,
        expected_token: &str,
    ) -> Result<u64, wacore::voip::GroupStateApply> {
        let call_id = session.call_id.clone();
        let call_creator = session.call_creator.clone();
        let mut rekey_pending = session
            .group
            .as_ref()
            .is_some_and(|update| update.rekey_requested);
        // Share the stable call-id lane with every competing call registration. Once this join
        // inserts its generation, no re-offer can replace it until all staged admission state has
        // either committed to that generation or caused registration to fail.
        let _answer_transition = self.lock_answer_transition(&call_id).await;
        let mut state = self
            .pending_call_link_joins
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        state.bind_call_id(&call_id);
        let saturated = state.is_saturated(&call_id);
        let staged = state.transitions.remove(&call_id).unwrap_or_default();
        if saturated {
            return Err(wacore::voip::GroupStateApply::InvalidSnapshot);
        }
        let generation = self.call_registry.insert_call_link_checked(session)?;
        if let Some(room) = waiting_room {
            let applied = self
                .call_registry
                .apply_waiting_room_if_current(room, generation);
            if applied != wacore::voip::GroupStateApply::Applied {
                self.call_registry.remove_if_current(&call_id, generation);
                return Err(applied);
            }
        }
        for transition in staged {
            match transition {
                PendingCallLinkTransition::Group(update)
                    if update.call_creator == call_creator
                        && update.media == expected_media.as_str() =>
                {
                    let mut update = *update;
                    update.rekey_requested |= rekey_pending;
                    let staged_rekey = update.rekey_requested;
                    match self.apply_pending_call_link_update(update, generation) {
                        wacore::voip::GroupStateApply::Applied => {
                            rekey_pending = staged_rekey;
                        }
                        wacore::voip::GroupStateApply::Stale => {}
                        rejected => {
                            self.call_registry.remove_if_current(&call_id, generation);
                            return Err(rejected);
                        }
                    }
                }
                PendingCallLinkTransition::WaitingRoom(room)
                    if room.call_creator == call_creator
                        && room.media == expected_media
                        && room.link_token == expected_token =>
                {
                    let applied = self
                        .call_registry
                        .apply_waiting_room_if_current(room, generation);
                    if !matches!(
                        applied,
                        wacore::voip::GroupStateApply::Applied
                            | wacore::voip::GroupStateApply::Stale
                    ) {
                        self.call_registry.remove_if_current(&call_id, generation);
                        return Err(applied);
                    }
                }
                PendingCallLinkTransition::RawEpoch {
                    call_creator: staged_creator,
                    sender,
                    transaction_id,
                    raw_epoch,
                } => {
                    if !self.call_registry.group_sender_authorized_if_current(
                        &call_id,
                        generation,
                        &staged_creator,
                        &sender,
                    ) {
                        continue;
                    }
                    if !self.call_registry.send_group_epoch_if_current(
                        &call_id,
                        generation,
                        transaction_id,
                        raw_epoch.to_vec(),
                    ) {
                        self.call_registry.remove_if_current(&call_id, generation);
                        return Err(wacore::voip::GroupStateApply::UnknownCall);
                    }
                }
                PendingCallLinkTransition::Terminated {
                    call_creator: staged_creator,
                    sender,
                } => {
                    if !self.call_registry.group_creator_authorized_if_current(
                        &call_id,
                        generation,
                        &staged_creator,
                        &sender,
                    ) {
                        continue;
                    }
                    self.call_registry.remove_if_current(&call_id, generation);
                    return Err(wacore::voip::GroupStateApply::InvalidSnapshot);
                }
                PendingCallLinkTransition::Saturated => {
                    self.call_registry.remove_if_current(&call_id, generation);
                    return Err(wacore::voip::GroupStateApply::InvalidSnapshot);
                }
                _ => {}
            }
        }
        Ok(generation)
    }

    #[cfg(feature = "voip-runtime")]
    fn apply_pending_call_link_update(
        &self,
        update: GroupCallUpdate,
        generation: u64,
    ) -> wacore::voip::GroupStateApply {
        self.call_registry
            .apply_group_update_if_current(update, generation)
    }

    /// Lock the striped answer-transition lane for `call_id`. Incoming answer registration and
    /// answer teardown both use this, preventing a replacement generation from being installed
    /// after the old one is claimed but before its terminal stanza reaches the wire.
    #[cfg(feature = "voip-runtime")]
    pub(crate) fn answer_transition_lock(&self, call_id: &str) -> Arc<async_lock::Mutex<()>> {
        use std::hash::{Hash, Hasher};

        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        call_id.hash(&mut hasher);
        let lane = hasher.finish() as usize % self.answer_transition_locks.len();
        self.answer_transition_locks[lane].clone()
    }

    #[cfg(feature = "voip-runtime")]
    pub(crate) async fn lock_answer_transition(
        &self,
        call_id: &str,
    ) -> async_lock::MutexGuardArc<()> {
        self.answer_transition_lock(call_id).lock_arc().await
    }
}

/// Errors from call-control operations. `#[non_exhaustive]` so new variants stay
/// non-breaking after 1.0.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum CallError {
    #[error("{0}")]
    Send(#[from] ClientError),
    #[error("call_id cannot be empty")]
    EmptyCallId,
    /// `accept` was called with an `IncomingCall` that is not an `<offer>` (nothing to answer).
    #[cfg(feature = "voip-runtime")]
    #[error("not an incoming call offer")]
    NotAnOffer,
    /// `accept().start()` was called without PCM or encoded audio endpoints.
    #[cfg(feature = "voip-runtime")]
    #[error("accept() requires audio(...) or encoded_audio(...) before start()")]
    MissingAudio,
    /// The selected media profile was not present in the incoming offer.
    #[cfg(feature = "voip-runtime")]
    #[error("incoming offer does not advertise the selected audio rate {0}")]
    AudioFormatNotOffered(u32),
    /// Video endpoints were supplied for an offer that only advertised audio.
    #[cfg(feature = "voip-runtime")]
    #[error("incoming offer did not advertise video; use start_video() after answering")]
    VideoNotOffered,
    /// The peer ended or superseded the call while the answer was being prepared.
    #[cfg(feature = "voip-runtime")]
    #[error("call ended during answer setup")]
    CallEndedDuringSetup,
    /// Decrypting the offer's encrypted callKey failed.
    #[cfg(feature = "voip-runtime")]
    #[error("callKey decrypt failed: {0}")]
    Decrypt(String),
    /// Assembling the call config from the offer's relay block failed.
    #[cfg(feature = "voip-runtime")]
    #[error("call setup failed: {0}")]
    Setup(String),
    /// Connecting the relay media transport (UDP/DTLS/SCTP) failed.
    #[cfg(feature = "voip-runtime")]
    #[error("relay connect failed: {0}")]
    Connect(String),
    /// The offer was missing media material (no `<enc>`/`<relay>`, no callKey, no own LID, etc.).
    #[cfg(feature = "voip-runtime")]
    #[error("media offer error: {0}")]
    Media(&'static str),
    /// The peer cancelled or replaced the upgrade before its video source became ready.
    #[cfg(feature = "voip-runtime")]
    #[error("video upgrade request is no longer current")]
    VideoUpgradeExpired,
    /// `call(peer)` resolved zero devices for the peer (nothing to address an offer to).
    #[cfg(feature = "voip-runtime")]
    #[error("peer has no resolvable devices")]
    NoDevices,
    /// An outgoing offer would emit a pkmsg `<enc>` but we hold no ADV account, so the peer could
    /// not validate the pre-key message. Refused before send to avoid advancing the sender chain
    /// (mirrors the peer-send path's `<device-identity>` requirement).
    #[cfg(feature = "voip-runtime")]
    #[error("offer pkmsg requires <device-identity> (account is None)")]
    MissingDeviceIdentity,
    /// A call-service response was malformed or rejected.
    #[cfg(feature = "voip-runtime")]
    #[error("call service response failed: {0}")]
    Response(String),
    /// The call service did not answer within its bounded request window.
    #[cfg(feature = "voip-runtime")]
    #[error("call service request timed out")]
    ResponseTimeout,
}

impl Voip<'_> {
    /// Reject an incoming call. Fire-and-forget — no server response is expected.
    pub async fn reject(&self, incoming: &IncomingCall) -> Result<(), CallError> {
        self.reject_call_inner(
            incoming.action.call_id(),
            &incoming.from,
            incoming.action.call_creator(),
            incoming.ringing_generation(),
        )
        .await
    }

    /// Reject a call when its signaling identifiers are already available.
    /// `peer` is the outer `<call to>` target, while `call_creator` is the
    /// action's `call-creator` attribute; preserve them separately because
    /// they may differ for companion-device signaling.
    /// Fire-and-forget — no server response is expected.
    pub async fn reject_call(
        &self,
        call_id: &str,
        peer: &Jid,
        call_creator: &Jid,
    ) -> Result<(), CallError> {
        self.reject_call_inner(call_id, peer, call_creator, None)
            .await
    }

    async fn reject_call_inner(
        &self,
        call_id: &str,
        peer: &Jid,
        call_creator: &Jid,
        _ringing_generation: Option<u64>,
    ) -> Result<(), CallError> {
        if call_id.is_empty() {
            return Err(CallError::EmptyCallId);
        }
        let id = self.client.generate_request_id();
        let stanza = build_reject(call_id, peer, call_creator, &id);
        // Consume the ringing flag BEFORE the async send: a caller <terminate> processed while we await
        // the send would otherwise hit take_ringing first and surface a phantom missed call for a call
        // we already declined (WA Web deletes it from _ringingCalls on reject). No-op if never ringing.
        #[cfg(feature = "voip-runtime")]
        {
            let registry = self.client.call_registry();
            if let Some(generation) = _ringing_generation {
                if !registry.reject_ringing_if_current(call_id, generation) {
                    return Err(CallError::CallEndedDuringSetup);
                }
            } else {
                let generation = registry.ringing_group_generation(call_id, call_creator);
                registry.take_ringing(call_id);
                if let Some(generation) = generation {
                    registry.remove_if_current(call_id, generation);
                }
            }
        }
        self.client.send_node(stanza).await?;
        Ok(())
    }

    /// Begin answering an incoming call: returns a builder; call `.audio(source, sink)` then
    /// `.start().await` to send `<preaccept>`, decrypt the callKey, send `<accept>`, connect the relay,
    /// and drive the call, yielding a [`CallHandle`](crate::voip::CallHandle). Requires
    /// `voip-runtime` or a profile that enables it: `voip`, `voip-encoded`, `voip-mlow`, or
    /// `voip-libopus`.
    #[cfg(feature = "voip-runtime")]
    pub fn accept<'b>(&'b self, incoming: &'b IncomingCall) -> crate::voip::AcceptCall<'b> {
        crate::voip::facade::AcceptCall::new(self.client, incoming)
    }

    /// Begin placing an outgoing 1:1 call to `peer`: returns a builder; call `.audio(source, sink)`
    /// then `.start().await` to generate the callKey, encrypt it per peer device, send the `<offer>`,
    /// and register the call, yielding a [`CallHandle`](crate::voip::CallHandle). The media engine
    /// only attaches once the server hands back the relay for our call-id (live), so the returned
    /// handle is dormant until then. Requires `voip-runtime` or a profile that enables it: `voip`,
    /// `voip-encoded`, `voip-mlow`, or `voip-libopus`.
    #[cfg(feature = "voip-runtime")]
    pub fn call<'b>(&'b self, peer: &'b Jid) -> crate::voip::OutgoingCall<'b> {
        crate::voip::facade::OutgoingCall::new(self.client, peer)
    }

    /// Begin a native group call to two or more selected users.
    #[cfg(feature = "voip-runtime")]
    pub fn group_call<'b>(&'b self, targets: &'b [Jid]) -> crate::voip::OutgoingGroupCall<'b> {
        crate::voip::facade::OutgoingGroupCall::new(self.client, targets)
    }

    /// Begin a native call bound to an existing group. The current roster is resolved at
    /// [`start`](crate::voip::GroupBoundCall::start), with this account excluded automatically.
    #[cfg(feature = "voip-runtime")]
    pub fn group_call_by_id<'b>(&'b self, group_jid: &'b Jid) -> crate::voip::GroupBoundCall<'b> {
        crate::voip::facade::GroupBoundCall::new(self.client, group_jid)
    }

    /// Join a reusable call link and attach group media after admission.
    #[cfg(feature = "voip-runtime")]
    pub fn call_link<'b>(
        &'b self,
        token_or_url: &'b str,
        media: CallLinkMedia,
    ) -> crate::voip::CallLinkCall<'b> {
        crate::voip::facade::CallLinkCall::new(self.client, token_or_url, media)
    }

    /// Send the eager preparation response for an active group-call invitation.
    #[cfg(feature = "voip-runtime")]
    pub async fn preaccept_group_invite(&self, incoming: &IncomingCall) -> Result<(), CallError> {
        let CallAction::Offer {
            call_id,
            call_creator,
            is_video,
            ..
        } = &incoming.action
        else {
            return Err(CallError::NotAnOffer);
        };
        if incoming.group.is_none() {
            return Err(CallError::Media("offer is not an active group invitation"));
        }
        let registry = self.client.call_registry();
        let Some(retained_generation) = incoming.ringing_generation() else {
            return Err(CallError::CallEndedDuringSetup);
        };
        let generation = registry
            .ringing_group_generation(call_id, call_creator)
            .ok_or(CallError::CallEndedDuringSetup)?;
        if generation != retained_generation {
            return Err(CallError::CallEndedDuringSetup);
        }
        let node = build_active_group_preaccept(
            call_id,
            call_creator,
            &self.client.generate_request_id(),
            *is_video,
        )
        .map_err(|error| CallError::Response(error.to_string()))?;
        self.client.send_node(node).await?;
        if registry.ringing_group_generation(call_id, call_creator) != Some(generation) {
            return Err(CallError::CallEndedDuringSetup);
        }
        Ok(())
    }

    /// Send an early call-scoped accept for an active group invitation.
    ///
    /// The retained offer remains ringing so [`accept`](Self::accept) can subsequently attach the
    /// application's media endpoints to the exact same generation.
    #[cfg(feature = "voip-runtime")]
    pub async fn accept_group_invite(&self, incoming: &IncomingCall) -> Result<(), CallError> {
        let CallAction::Offer {
            call_id,
            call_creator,
            is_video,
            ..
        } = &incoming.action
        else {
            return Err(CallError::NotAnOffer);
        };
        if incoming.group.is_none() {
            return Err(CallError::Media("offer is not an active group invitation"));
        }
        let registry = self.client.call_registry();
        let Some(retained_generation) = incoming.ringing_generation() else {
            return Err(CallError::CallEndedDuringSetup);
        };
        let generation = registry
            .ringing_group_generation(call_id, call_creator)
            .ok_or(CallError::CallEndedDuringSetup)?;
        if generation != retained_generation {
            return Err(CallError::CallEndedDuringSetup);
        }
        let node = build_active_group_accept(
            call_id,
            call_creator,
            &self.client.generate_request_id(),
            *is_video,
        )
        .map_err(|error| CallError::Response(error.to_string()))?;
        self.client.send_node(node).await?;
        if registry.ringing_group_generation(call_id, call_creator) != Some(generation) {
            return Err(CallError::CallEndedDuringSetup);
        }
        Ok(())
    }

    /// Create a reusable audio or video call link.
    #[cfg(feature = "voip-runtime")]
    pub async fn create_call_link(&self, media: CallLinkMedia) -> Result<CallLink, CallError> {
        let request_id = self.client.generate_request_id();
        let request = build_call_link_create(media, &request_id)
            .map_err(|error| CallError::Response(error.to_string()))?;
        let link = execute_call_service_request(
            self.client,
            &request_id,
            request,
            parse_call_link_create_ack,
        )
        .await?;
        if link.media != media {
            return Err(CallError::Response(
                "call-link creation changed the requested media mode".to_string(),
            ));
        }
        Ok(link)
    }

    /// Inspect a call link without joining it.
    #[cfg(feature = "voip-runtime")]
    pub async fn preview_call_link(
        &self,
        token_or_url: &str,
        media: CallLinkMedia,
    ) -> Result<CallLinkPreview, CallError> {
        let token = normalize_call_link_token(token_or_url, media)?;
        let request_id = self.client.generate_request_id();
        let request = build_call_link_query(&token, media, &request_id)
            .map_err(|error| CallError::Response(error.to_string()))?;
        let preview = execute_call_service_request(
            self.client,
            &request_id,
            request,
            parse_call_link_query_ack,
        )
        .await?;
        if preview.token != token || preview.media != media {
            return Err(CallError::Response(
                "call-link preview changed the requested link identity".to_string(),
            ));
        }
        Ok(preview)
    }

    /// Join a call link. The result explicitly reports whether this endpoint was admitted or placed
    /// in the waiting room; media starts only after an admitted authoritative group snapshot.
    #[cfg(feature = "voip-runtime")]
    pub async fn join_call_link(
        &self,
        token_or_url: &str,
        media: CallLinkMedia,
    ) -> Result<CallLinkJoin, CallError> {
        self.join_call_link_with_audio(token_or_url, media, AudioFormat::MLOW_16KHZ_60MS)
            .await
    }

    #[cfg(feature = "voip-runtime")]
    pub(crate) async fn join_call_link_with_audio(
        &self,
        token_or_url: &str,
        media: CallLinkMedia,
        audio_format: AudioFormat,
    ) -> Result<CallLinkJoin, CallError> {
        Ok(self
            .join_call_link_registration_with_audio(token_or_url, media, audio_format)
            .await?
            .join)
    }

    #[cfg(feature = "voip-runtime")]
    pub(crate) async fn join_call_link_registration_with_audio(
        &self,
        token_or_url: &str,
        media: CallLinkMedia,
        audio_format: AudioFormat,
    ) -> Result<CallLinkJoinRegistration, CallError> {
        // Before the ACK arrives, creator-authenticated admission traffic has no trusted call id
        // to associate with this request. Keep one such request active at a time so bounded-buffer
        // saturation can fail only its owning join; other joins wait here and start with clean
        // staging state.
        let pending_join_lane = self.client.pending_call_link_join_lane.lock().await;
        let own_lid = self.client.lid().ok_or(CallError::Media("no own LID"))?;
        let token = normalize_call_link_token(token_or_url, media)?;
        let capability =
            crate::voip::facade::offer_capability(media == CallLinkMedia::Video, audio_format);
        let pending_join = self.client.begin_call_link_join();
        let mut join =
            execute_call_link_join_request(self.client, &token, media, capability).await?;
        if join.media != media {
            return Err(CallError::Response(
                "call-link response changed the requested media mode".to_string(),
            ));
        }
        if join.call_id.is_empty() {
            return Err(CallError::EmptyCallId);
        }
        if self
            .client
            .prepare_pending_call_link_join_retry(&join.call_id)
        {
            let first_call_id = join.call_id.clone();
            let first_call_creator = join.call_creator.clone();
            let refreshed =
                execute_call_link_join_request(self.client, &token, media, capability).await?;
            if refreshed.media != media
                || refreshed.call_id != first_call_id
                || refreshed.call_creator != first_call_creator
            {
                return Err(CallError::Response(
                    "call-link identity changed while refreshing admission state".to_string(),
                ));
            }
            join = refreshed;
        }

        let mut session = CallSession::new_outgoing(
            &join.call_id,
            Jid::new(&join.call_id, Server::Call),
            join.call_creator.clone(),
        );
        session.audio_format = Some(audio_format);
        session.is_video = media == CallLinkMedia::Video;
        session.group = join.group.clone();
        let _ = session.transition_to(CallPhase::Calling);
        let _ = session.transition_to(if join.in_waiting_room {
            CallPhase::WaitingRoom
        } else {
            CallPhase::Connecting
        });
        let registry = self.client.call_registry();
        let generation = self
            .client
            .register_call_link_session(session, join.waiting_room.clone(), media, &token)
            .await
            .map_err(|_| {
                CallError::Response("call-link admission snapshot was rejected".to_string())
            })?;
        // Publication transfers admission controls to the generation-scoped registry. Clear the
        // provisional binding before another serialized unknown-id join starts with a clean buffer.
        drop(pending_join);
        drop(pending_join_lane);
        let mut registration = CallLinkRegistrationGuard::new(
            self.client,
            registry.clone(),
            &join.call_id,
            join.call_creator.clone(),
            generation,
        );

        if join.in_waiting_room && join.waiting_room.is_none() {
            return Err(CallError::Response(
                "call-link join omitted its waiting-room state".to_string(),
            ));
        }

        registry.set_group_invite_self_device(
            &join.call_id,
            generation,
            wacore::types::group_call::GroupCallDevice::new(own_lid).with_capability(1, capability),
        );
        let rekey_required = join
            .group
            .as_ref()
            .is_some_and(|update| update.rekey_requested);
        let mut still_waiting = self
            .synchronize_call_link_admission(&mut join, generation, rekey_required)
            .await?;
        if still_waiting {
            let heartbeat = self
                .waiting_room_heartbeat(&join.call_id, &join.call_creator)
                .await;
            // The heartbeat crosses an unbounded transport await. Admission may have committed
            // while it was in flight, so re-read the generation before publishing the result or
            // starting a task that now belongs to an admitted call.
            still_waiting = self
                .synchronize_call_link_admission(&mut join, generation, rekey_required)
                .await?;
            if still_waiting {
                heartbeat?;
            }
        }
        if still_waiting {
            self.start_waiting_room_heartbeat(
                join.call_id.clone(),
                join.call_creator.clone(),
                generation,
            );
        }

        registration.disarm();
        Ok(CallLinkJoinRegistration { join, generation })
    }

    #[cfg(feature = "voip-runtime")]
    async fn synchronize_call_link_admission(
        &self,
        join: &mut CallLinkJoin,
        generation: u64,
        rekey_required: bool,
    ) -> Result<bool, CallError> {
        let registry = self.client.call_registry();
        let transition_lock = registry
            .group_transition_lock(&join.call_id, generation)
            .ok_or(CallError::CallEndedDuringSetup)?;
        let _transition_guard = transition_lock.lock().await;
        let state = registry
            .group_state_if_current(&join.call_id, generation)
            .ok_or(CallError::CallEndedDuringSetup)?;
        if let Some(room) = state.waiting_room().cloned() {
            join.waiting_room_enabled = room.enabled;
            join.is_admin = room.is_admin;
            join.waiting_room = Some(room);
        }
        let phase = registry
            .phase_if_current(&join.call_id, generation)
            .ok_or(CallError::CallEndedDuringSetup)?;
        if phase == CallPhase::WaitingRoom {
            join.in_waiting_room = true;
            return Ok(true);
        }

        let update = state.snapshot().cloned().ok_or(CallError::Media(
            "admitted call link has no authoritative group snapshot",
        ))?;
        join.in_waiting_room = false;
        join.group = Some(update.clone());
        let retained_epoch =
            registry.pending_group_epoch_transaction_if_current(&join.call_id, generation);
        if (rekey_required || update.rekey_requested)
            && retained_epoch.is_none_or(|transaction| transaction < update.transaction_id)
        {
            // The shared transition lane keeps roster selection, fan-out, and publication on the
            // same transaction even if a post-registration update tries to overtake the ACK.
            crate::voip::facade::fanout_group_epoch(self.client, &update)
                .await?
                .commit(|epoch| {
                    registry
                        .send_group_epoch_if_current(
                            &join.call_id,
                            generation,
                            update.transaction_id,
                            epoch.to_vec(),
                        )
                        .then_some(())
                        .ok_or(CallError::Media(
                            "call-link group epoch could not be retained",
                        ))
                })?;
        }
        Ok(false)
    }

    /// Enable or disable approval for a live call-link waiting room.
    #[cfg(feature = "voip-runtime")]
    pub async fn set_approval_required(
        &self,
        call_id: &str,
        call_creator: &Jid,
        enabled: bool,
    ) -> Result<(), CallError> {
        let generation = self
            .client
            .call_registry()
            .generation_of(call_id)
            .ok_or(CallError::Media("call is no longer active"))?;
        self.set_approval_required_for_generation(call_id, call_creator, generation, enabled)
            .await
    }

    #[cfg(feature = "voip-runtime")]
    pub(crate) async fn set_approval_required_for_generation(
        &self,
        call_id: &str,
        call_creator: &Jid,
        generation: u64,
        enabled: bool,
    ) -> Result<(), CallError> {
        let registry = self.client.call_registry();
        let transition_lock = registry
            .group_transition_lock(call_id, generation)
            .ok_or(CallError::Media("call is no longer active"))?;
        let _transition_guard = transition_lock.lock().await;
        self.ensure_waiting_room_admin_if_current(call_id, generation)?;
        let request_id = self.client.generate_request_id();
        execute_call_service_request(
            self.client,
            &request_id,
            build_waiting_room_toggle(call_id, call_creator, enabled, &request_id)
                .map_err(|error| CallError::Response(error.to_string()))?,
            parse_waiting_room_toggle_ack,
        )
        .await?;
        if registry.set_waiting_room_enabled_if_current(call_id, generation, enabled) {
            Ok(())
        } else {
            Err(CallError::Media(
                "call was replaced while applying group control",
            ))
        }
    }

    /// Keep a pending call-link admission alive.
    #[cfg(feature = "voip-runtime")]
    pub async fn waiting_room_heartbeat(
        &self,
        call_id: &str,
        call_creator: &Jid,
    ) -> Result<(), CallError> {
        self.send_group_control(
            call_id,
            build_waiting_room_heartbeat(call_id, call_creator, &self.client.generate_request_id())
                .map_err(|error| CallError::Response(error.to_string()))?,
        )
        .await
    }

    /// Admit one user from a call-link waiting room.
    #[cfg(feature = "voip-runtime")]
    pub async fn admit_waiting_user(
        &self,
        call_id: &str,
        call_creator: &Jid,
        user: &Jid,
    ) -> Result<(), CallError> {
        let generation = self
            .client
            .call_registry()
            .generation_of(call_id)
            .ok_or(CallError::Media("call is no longer active"))?;
        self.admit_waiting_user_for_generation(call_id, call_creator, generation, user)
            .await
    }

    #[cfg(feature = "voip-runtime")]
    pub(crate) async fn admit_waiting_user_for_generation(
        &self,
        call_id: &str,
        call_creator: &Jid,
        generation: u64,
        user: &Jid,
    ) -> Result<(), CallError> {
        self.waiting_room_user_action_for_generation(
            call_id,
            call_creator,
            generation,
            user,
            WaitingRoomUserAction::Admit,
        )
        .await
    }

    /// Deny one user from a call-link waiting room.
    #[cfg(feature = "voip-runtime")]
    pub async fn deny_waiting_user(
        &self,
        call_id: &str,
        call_creator: &Jid,
        user: &Jid,
    ) -> Result<(), CallError> {
        let generation = self
            .client
            .call_registry()
            .generation_of(call_id)
            .ok_or(CallError::Media("call is no longer active"))?;
        self.deny_waiting_user_for_generation(call_id, call_creator, generation, user)
            .await
    }

    #[cfg(feature = "voip-runtime")]
    pub(crate) async fn deny_waiting_user_for_generation(
        &self,
        call_id: &str,
        call_creator: &Jid,
        generation: u64,
        user: &Jid,
    ) -> Result<(), CallError> {
        self.waiting_room_user_action_for_generation(
            call_id,
            call_creator,
            generation,
            user,
            WaitingRoomUserAction::Deny,
        )
        .await
    }

    #[cfg(feature = "voip-runtime")]
    async fn waiting_room_user_action_for_generation(
        &self,
        call_id: &str,
        call_creator: &Jid,
        generation: u64,
        user: &Jid,
        action: WaitingRoomUserAction,
    ) -> Result<(), CallError> {
        self.ensure_waiting_room_admin_if_current(call_id, generation)?;
        let request_id = self.client.generate_request_id();
        let (request, parse) = match action {
            WaitingRoomUserAction::Admit => (
                build_waiting_room_admit(call_id, call_creator, user, &request_id),
                parse_waiting_room_admit_ack
                    as fn(&wacore_binary::NodeRef<'_>) -> anyhow::Result<()>,
            ),
            WaitingRoomUserAction::Deny => (
                build_waiting_room_deny(call_id, call_creator, user, &request_id),
                parse_waiting_room_deny_ack
                    as fn(&wacore_binary::NodeRef<'_>) -> anyhow::Result<()>,
            ),
        };
        execute_call_service_request(
            self.client,
            &request_id,
            request.map_err(|error| CallError::Response(error.to_string()))?,
            parse,
        )
        .await?;
        if self.client.call_registry().is_current(call_id, generation) {
            Ok(())
        } else {
            Err(CallError::Media(
                "call was replaced while applying group control",
            ))
        }
    }

    /// Publish the local persistent raise/lower-hand state.
    #[cfg(feature = "voip-runtime")]
    pub async fn set_hand_raised(
        &self,
        call_id: &str,
        call_creator: &Jid,
        raised: bool,
    ) -> Result<(), CallError> {
        let generation = self
            .client
            .call_registry()
            .generation_of(call_id)
            .ok_or(CallError::Media("call is no longer active"))?;
        self.set_hand_raised_for_generation(call_id, call_creator, generation, raised)
            .await
    }

    #[cfg(feature = "voip-runtime")]
    pub(crate) async fn set_hand_raised_for_generation(
        &self,
        call_id: &str,
        call_creator: &Jid,
        generation: u64,
        raised: bool,
    ) -> Result<(), CallError> {
        let registry = self.client.call_registry();
        let transition_lock = registry
            .group_transition_lock(call_id, generation)
            .ok_or(CallError::Media("call is no longer active"))?;
        let _transition_guard = transition_lock.lock().await;
        if !registry.group_creator_matches_if_current(call_id, generation, call_creator) {
            return Err(CallError::Media(
                "call creator does not match the active group call",
            ));
        }
        let participant = self
            .client
            .lid()
            .ok_or(CallError::Media("no own LID"))?
            .to_non_ad();
        let target = Jid::new(call_id, Server::Call);
        self.send_group_control(
            call_id,
            build_raise_hand(
                call_id,
                &target,
                call_creator,
                &self.client.generate_request_id(),
                raised,
            )
            .map_err(|error| CallError::Response(error.to_string()))?,
        )
        .await?;
        if registry.set_raised_hand_if_current(call_id, generation, &participant, raised) {
            registry.send_call_event_if_current(
                call_id,
                generation,
                CallEvent::HandRaised {
                    participant,
                    raised,
                },
            );
            Ok(())
        } else {
            Err(CallError::Media(
                "call was replaced while applying group control",
            ))
        }
    }

    /// Publish a screen-share start/stop transition.
    #[cfg(feature = "voip-runtime")]
    pub async fn set_screen_share(
        &self,
        call_id: &str,
        call_creator: &Jid,
        state: ScreenShareState,
        screen_share_id: Option<u32>,
    ) -> Result<(), CallError> {
        let generation = self
            .client
            .call_registry()
            .generation_of(call_id)
            .ok_or(CallError::Media("call is no longer active"))?;
        self.set_screen_share_for_generation(
            call_id,
            call_creator,
            generation,
            state,
            screen_share_id,
        )
        .await
    }

    #[cfg(feature = "voip-runtime")]
    pub(crate) async fn set_screen_share_for_generation(
        &self,
        call_id: &str,
        call_creator: &Jid,
        generation: u64,
        state: ScreenShareState,
        screen_share_id: Option<u32>,
    ) -> Result<(), CallError> {
        let registry = self.client.call_registry();
        let transition_lock = registry
            .group_transition_lock(call_id, generation)
            .ok_or(CallError::Media("call is no longer active"))?;
        let _transition_guard = transition_lock.lock().await;
        if !registry.group_creator_matches_if_current(call_id, generation, call_creator) {
            return Err(CallError::Media(
                "call creator does not match the active group call",
            ));
        }
        let group = registry
            .group_state_if_current(call_id, generation)
            .ok_or(CallError::Media("call is not an active group call"))?;
        if state == ScreenShareState::Started
            && (group
                .snapshot()
                .is_none_or(|snapshot| snapshot.media != "video")
                || !matches!(
                    registry.video_states(call_id, generation),
                    Some((VideoState::Enabled, _))
                ))
        {
            return Err(CallError::Media(
                "screen sharing requires an active local video plane",
            ));
        }
        let participant = self
            .client
            .lid()
            .ok_or(CallError::Media("no own LID"))?
            .to_non_ad();
        let target = Jid::new(call_id, Server::Call);
        self.send_group_control(
            call_id,
            build_screen_share(
                call_id,
                &target,
                call_creator,
                &self.client.generate_request_id(),
                state,
                screen_share_id,
            )
            .map_err(|error| CallError::Response(error.to_string()))?,
        )
        .await?;
        let screen_share = ScreenShare::new(state, screen_share_id);
        if registry.set_screen_share_if_current(
            call_id,
            generation,
            &participant,
            screen_share.clone(),
        ) {
            registry.send_call_event_if_current(
                call_id,
                generation,
                CallEvent::ScreenShareChanged {
                    participant,
                    screen_share,
                },
            );
        } else {
            return Err(CallError::Media(
                "call was replaced while applying group control",
            ));
        }
        // Both directions swap the encoder source, so the peer needs an IDR before either stream
        // can safely resume.
        registry.send_video_ctl(call_id, generation, VideoControl::RequireKeyframe);
        Ok(())
    }

    #[cfg(feature = "voip-runtime")]
    async fn send_group_control(&self, call_id: &str, node: Node) -> Result<(), CallError> {
        if call_id.is_empty() {
            return Err(CallError::EmptyCallId);
        }
        self.client.send_node(node).await?;
        Ok(())
    }

    #[cfg(feature = "voip-runtime")]
    fn ensure_waiting_room_admin_if_current(
        &self,
        call_id: &str,
        generation: u64,
    ) -> Result<(), CallError> {
        let room = self
            .client
            .call_registry()
            .group_state_if_current(call_id, generation)
            .and_then(|state| state.waiting_room().cloned())
            .ok_or(CallError::Media("call has no waiting-room state"))?;
        if !room.is_admin {
            return Err(CallError::Media(
                "waiting-room control requires an administrator",
            ));
        }
        Ok(())
    }

    #[cfg(feature = "voip-runtime")]
    fn start_waiting_room_heartbeat(&self, call_id: String, call_creator: Jid, generation: u64) {
        let weak_client = self.client.self_weak.get().cloned().unwrap_or_default();
        let runtime = self.client.runtime.clone();
        let sleeper = runtime.clone();
        let heartbeat_call_id = call_id.clone();
        let task = runtime.spawn(Box::pin(async move {
            let mut consecutive_failures = 0;
            loop {
                sleeper.sleep(WAITING_ROOM_HEARTBEAT_INTERVAL).await;
                let Some(client) = weak_client.upgrade() else {
                    break;
                };
                if client
                    .call_registry()
                    .phase_if_current(&heartbeat_call_id, generation)
                    != Some(CallPhase::WaitingRoom)
                {
                    break;
                }
                let request_id = client.generate_request_id();
                let heartbeat = match build_waiting_room_heartbeat(
                    &heartbeat_call_id,
                    &call_creator,
                    &request_id,
                ) {
                    Ok(heartbeat) => heartbeat,
                    Err(error) => {
                        warn!(
                            "voip: invalid waiting-room heartbeat for call {}: {error}",
                            heartbeat_call_id
                        );
                        break;
                    }
                };
                if let Err(error) = client
                    .send_node(heartbeat)
                    .await
                {
                    consecutive_failures += 1;
                    warn!(
                        "voip: waiting-room heartbeat failed for call {} ({consecutive_failures}/{WAITING_ROOM_HEARTBEAT_MAX_CONSECUTIVE_FAILURES}): {error}",
                        heartbeat_call_id,
                    );
                    if consecutive_failures >= WAITING_ROOM_HEARTBEAT_MAX_CONSECUTIVE_FAILURES {
                        client.call_registry().send_call_event_if_current(
                            &heartbeat_call_id,
                            generation,
                            CallEvent::WaitingRoomHeartbeatFailed,
                        );
                        client
                            .call_registry()
                            .remove_if_current(&heartbeat_call_id, generation);
                        break;
                    }
                    continue;
                }
                consecutive_failures = 0;
            }
        }));
        self.client
            .call_registry()
            .set_waiting_room_task(&call_id, generation, task);
    }

    /// Terminate an active call.
    pub async fn terminate(
        &self,
        call_id: &str,
        peer: &Jid,
        call_creator: &Jid,
    ) -> Result<(), CallError> {
        if call_id.is_empty() {
            return Err(CallError::EmptyCallId);
        }
        let id = self.client.generate_request_id();
        let stanza = build_terminate(&TerminateParams {
            call_id,
            to: peer,
            id: Some(&id),
            call_creator,
            reason: None,
        });
        let sent = self.client.send_node(stanza).await;
        // Tear the local call down regardless of whether the stanza reached the peer: the app asked to
        // hang up, and a failed signaling send must not leave the media task capturing/sending (or a
        // dormant outgoing call free to attach on a late relay ack). Reuse the same teardown the peer's
        // `<terminate>` triggers so the public hangup actually ends our side too.
        #[cfg(feature = "voip-runtime")]
        crate::voip::facade::terminate_call(self.client, call_id);
        sent?;
        Ok(())
    }
}

#[cfg(feature = "voip-runtime")]
fn normalize_call_link_token(
    token_or_url: &str,
    expected_media: CallLinkMedia,
) -> Result<String, CallError> {
    let value = token_or_url.trim();
    if value.is_empty() {
        return Err(CallError::Response(
            "call-link token is required".to_string(),
        ));
    }
    const PREFIX: &str = "https://call.whatsapp.com/";
    if let Some(path) = value.strip_prefix(PREFIX) {
        let path = path.split_once(['?', '#']).map_or(path, |(path, _)| path);
        let mut parts = path.split('/');
        let media = parts.next();
        let Some(token) = parts.next().filter(|token| !token.is_empty()) else {
            return Err(CallError::Response(
                "invalid call-link URL or media mode".to_string(),
            ));
        };
        if parts.next().is_some() || media != Some(expected_media.as_str()) {
            return Err(CallError::Response(
                "invalid call-link URL or media mode".to_string(),
            ));
        }
        return Ok(token.to_string());
    }
    if value.contains("://") || value.contains('/') {
        return Err(CallError::Response("invalid call-link token".to_string()));
    }
    Ok(value.to_string())
}

#[cfg(feature = "voip-runtime")]
#[inline(never)]
async fn execute_call_link_join_request(
    client: &Client,
    token: &str,
    media: CallLinkMedia,
    capability: &[u8],
) -> Result<CallLinkJoin, CallError> {
    let request_id = client.generate_request_id();
    let request = build_call_link_join_with_capability(token, media, &request_id, capability)
        .map_err(|error| CallError::Response(error.to_string()))?;
    execute_call_service_request(client, &request_id, request, |response| {
        parse_call_link_join_ack(response, token)
    })
    .await
}

#[cfg(feature = "voip-runtime")]
async fn execute_call_service_request<T>(
    client: &Client,
    request_id: &str,
    request: Node,
    parse: impl FnOnce(&wacore_binary::NodeRef<'_>) -> anyhow::Result<T>,
) -> Result<T, CallError> {
    let (tx, response) = futures::channel::oneshot::channel();
    let cleanup_generation = client
        .response_waiters_guard()
        .try_insert_guarded(request_id.to_string(), ResponseWaiter::Iq(tx))
        .ok_or_else(|| CallError::Response("duplicate call-service request id".to_string()))?;
    let _waiter_guard = crate::request::ResponseWaiterGuard::new(
        client.response_waiters.clone(),
        request_id.to_string(),
        cleanup_generation,
    );
    client.send_node(request).await?;
    let response =
        match wacore::runtime::timeout(&*client.runtime, CALL_SERVICE_REQUEST_TIMEOUT, response)
            .await
        {
            Ok(Ok(response)) => response,
            Ok(Err(_)) => return Err(CallError::Response("response channel closed".to_string())),
            Err(_) => return Err(CallError::ResponseTimeout),
        };
    parse(response.get()).map_err(|error| CallError::Response(error.to_string()))
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "voip-runtime")]
    use super::PendingCallLinkBuffer;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};
    #[cfg(feature = "voip-runtime")]
    use std::time::Duration;

    use async_trait::async_trait;
    use bytes::Bytes;
    use wacore::handshake::NoiseCipher;
    use wacore::types::call::{CallAction, IncomingCall};
    #[cfg(feature = "voip-runtime")]
    use wacore::types::group_call::{
        CallLinkMedia, GroupCallDevice, GroupCallParticipant, GroupCallRelay,
        GroupCallRelayEndpoint, GroupCallUpdate, ScreenShareState, WaitingRoom,
    };
    #[cfg(feature = "voip-runtime")]
    use wacore::voip::{
        AudioFormat, CallEvent, CallPhase, CallSession, VideoControl, video_control_channel,
    };
    #[cfg(feature = "voip-runtime")]
    use wacore_binary::builder::NodeBuilder;
    use wacore_binary::{Jid, Server};

    #[cfg(feature = "voip-runtime")]
    use super::{
        MAX_PENDING_CALL_LINK_SATURATION_FINGERPRINTS, MAX_PENDING_CALL_LINK_TRANSITION_BYTES,
        MAX_PENDING_CALL_LINK_TRANSITIONS, WaitingRoomUserAction,
    };
    use crate::client::Client;
    #[cfg(feature = "voip-runtime")]
    use crate::client::{CallError, ResponseWaiter};

    #[cfg(feature = "voip-runtime")]
    #[test]
    fn call_link_urls_strip_query_and_fragment_without_relaxing_validation() {
        assert_eq!(
            super::normalize_call_link_token(
                "https://call.whatsapp.com/video/TEST-TOKEN?utm_source=test#join",
                CallLinkMedia::Video,
            )
            .unwrap(),
            "TEST-TOKEN"
        );
        assert!(
            super::normalize_call_link_token(
                "https://call.whatsapp.com/audio/TEST-TOKEN?x=1",
                CallLinkMedia::Video,
            )
            .is_err()
        );
        assert!(
            super::normalize_call_link_token(
                "https://call.whatsapp.com/video/?x=1",
                CallLinkMedia::Video,
            )
            .is_err()
        );
    }

    struct CountingTransport {
        count: Arc<AtomicUsize>,
    }

    #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
    #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
    impl crate::transport::Transport for CountingTransport {
        async fn send(&self, _data: Bytes) -> Result<(), anyhow::Error> {
            self.count.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
        async fn disconnect(&self) {}
    }

    async fn make_client_with_count() -> (Arc<Client>, Arc<AtomicUsize>) {
        let client = crate::test_utils::create_test_client().await;

        let count = Arc::new(AtomicUsize::new(0));
        let socket_transport: Arc<dyn crate::transport::Transport> = Arc::new(CountingTransport {
            count: count.clone(),
        });
        let key = [0u8; 32];
        let noise_socket = crate::socket::NoiseSocket::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            socket_transport,
            NoiseCipher::new(&key).expect("valid key"),
            NoiseCipher::new(&key).expect("valid key"),
        );
        *client.noise_socket.lock().await = Some(Arc::new(noise_socket));
        (client, count)
    }

    #[cfg(feature = "voip-runtime")]
    struct FailingTransport;

    #[cfg(feature = "voip-runtime")]
    #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
    #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
    impl crate::transport::Transport for FailingTransport {
        async fn send(&self, _data: Bytes) -> Result<(), anyhow::Error> {
            Err(anyhow::anyhow!("transport down"))
        }
        async fn disconnect(&self) {}
    }

    #[cfg(feature = "voip-runtime")]
    async fn make_client_failing() -> Arc<Client> {
        let client = crate::test_utils::create_test_client().await;
        let socket_transport: Arc<dyn crate::transport::Transport> = Arc::new(FailingTransport);
        let key = [0u8; 32];
        let noise_socket = crate::socket::NoiseSocket::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            socket_transport,
            NoiseCipher::new(&key).expect("valid key"),
            NoiseCipher::new(&key).expect("valid key"),
        );
        *client.noise_socket.lock().await = Some(Arc::new(noise_socket));
        client
    }

    fn caller() -> Jid {
        Jid::new("111111111111111", Server::Lid)
    }

    fn call_creator() -> Jid {
        Jid::new("222222222222222", Server::Lid)
    }

    fn incoming_reject() -> IncomingCall {
        IncomingCall::new_for_test(
            caller(),
            "STANZA-ID-0001".into(),
            wacore::time::from_secs(1_766_847_151_i64).expect("valid ts"),
            CallAction::Offer {
                call_id: "CALL-ID-0001".into(),
                call_creator: caller(),
                caller_pn: None,
                caller_country_code: None,
                device_class: None,
                joinable: false,
                is_video: false,
                audio: Vec::new(),
                group_jid: None,
            },
        )
    }

    #[tokio::test]
    async fn reject_sends_stanza() {
        let (client, count) = make_client_with_count().await;
        client
            .voip()
            .reject(&incoming_reject())
            .await
            .expect("reject should send");
        assert_eq!(count.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn reject_call_sends_stanza_without_event_context() {
        let (client, count) = make_client_with_count().await;
        let waiter = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
        let peer = caller();
        let creator = call_creator();
        client
            .voip()
            .reject_call("CALL-ID-0001", &peer, &creator)
            .await
            .expect("reject should send");
        assert_eq!(count.load(Ordering::SeqCst), 1);

        let sent = waiter.await.expect("reject stanza should be observable");
        let call = sent.as_node_ref();
        assert_eq!(
            call.attrs().optional_string("to").as_deref(),
            Some(peer.to_string().as_str())
        );
        let reject = &call.children().expect("call action")[0];
        assert_eq!(reject.tag, "reject");
        assert_eq!(
            reject.attrs().optional_string("call-id").as_deref(),
            Some("CALL-ID-0001")
        );
        assert_eq!(
            reject.attrs().optional_string("call-creator").as_deref(),
            Some(creator.to_string().as_str())
        );
        assert_eq!(
            reject.attrs().optional_string("count").as_deref(),
            Some("0")
        );
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn rejecting_an_incoming_group_offer_removes_its_ringing_generation() {
        let (client, _count) = make_client_with_count().await;
        let creator = caller();
        let call_id = "INCOMING-GROUP-CALL";
        let mut session = CallSession::new_incoming(call_id, creator.clone(), creator.clone());
        session.group = Some(
            GroupCallUpdate::builder()
                .call_id(call_id.to_string())
                .call_creator(creator.clone())
                .transaction_id(1)
                .media("audio".to_string())
                .connected_limit(32)
                .joinable(true)
                .av_upgradable(true)
                .rekey_requested(false)
                .participants(Vec::new())
                .build(),
        );
        let generation = client
            .call_registry()
            .insert_ringing_group_if_inactive(session)
            .expect("valid group snapshot")
            .expect("ringing generation");

        client
            .voip()
            .reject_call(call_id, &creator, &creator)
            .await
            .expect("reject");

        assert_ne!(
            client.call_registry().generation_of(call_id),
            Some(generation),
            "reject must reap the exact eagerly registered group offer"
        );
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn rejecting_a_stale_group_offer_event_preserves_the_replacement_generation() {
        let (client, count) = make_client_with_count().await;
        let creator = caller();
        let call_id = "REPLACED-INCOMING-GROUP-CALL";
        let update = GroupCallUpdate::builder()
            .call_id(call_id.to_string())
            .call_creator(creator.clone())
            .transaction_id(1)
            .media("audio".to_string())
            .connected_limit(32)
            .joinable(true)
            .av_upgradable(true)
            .rekey_requested(false)
            .participants(Vec::new())
            .build();
        let mut session = CallSession::new_incoming(call_id, creator.clone(), creator.clone());
        session.group = Some(update.clone());
        let stale = client
            .call_registry()
            .insert_ringing_group_if_inactive(session)
            .expect("valid group snapshot")
            .expect("ringing generation");
        let mut incoming = IncomingCall::new_for_test(
            creator.clone(),
            "STALE-GROUP-OFFER".to_string(),
            wacore::time::from_secs(1_766_847_151_i64).expect("valid ts"),
            CallAction::Offer {
                call_id: call_id.to_string(),
                call_creator: creator.clone(),
                caller_pn: None,
                caller_country_code: None,
                device_class: None,
                joinable: true,
                is_video: false,
                audio: Vec::new(),
                group_jid: None,
            },
        );
        incoming.group = Some(Box::new(update.clone()));
        incoming.set_ringing_generation(stale);

        let mut replacement = CallSession::new_incoming(call_id, creator.clone(), creator.clone());
        replacement.group = Some(update);
        let replacement = client.call_registry().insert_ringing_group(replacement);

        assert!(matches!(
            client.voip().reject(&incoming).await,
            Err(CallError::CallEndedDuringSetup)
        ));
        assert_eq!(
            count.load(Ordering::SeqCst),
            0,
            "a stale application event must not reject the replacement on the wire"
        );

        assert_eq!(
            client.call_registry().generation_of(call_id),
            Some(replacement),
            "a retained application event must not reap a newer same-id generation"
        );
        assert_eq!(
            client
                .call_registry()
                .ringing_group_generation(call_id, &creator),
            Some(replacement),
            "the newer offer must remain available for the application to answer or reject"
        );
        client
            .call_registry()
            .remove_if_current(call_id, replacement);
        client.call_registry().take_ringing(call_id);
    }

    #[tokio::test]
    async fn terminate_sends_stanza() {
        let (client, count) = make_client_with_count().await;
        client
            .voip()
            .terminate("CALL-ID-0001", &caller(), &caller())
            .await
            .expect("terminate should send");
        assert_eq!(count.load(Ordering::SeqCst), 1);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn terminate_aborts_the_local_call() {
        use wacore::voip::CallSession;
        let (client, _count) = make_client_with_count().await;
        let reg = client.call_registry();
        reg.insert(CallSession::new_outgoing(
            "CALL-ID-0001",
            caller(),
            caller(),
        ));
        assert_eq!(reg.active_count(), 1);
        client
            .voip()
            .terminate("CALL-ID-0001", &caller(), &caller())
            .await
            .expect("terminate should send");
        assert_eq!(
            reg.active_count(),
            0,
            "terminate must tear the local call down, not just signal the peer"
        );
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn terminate_tears_down_local_even_when_send_fails() {
        use wacore::voip::CallSession;
        let client = make_client_failing().await;
        let reg = client.call_registry();
        reg.insert(CallSession::new_outgoing(
            "CALL-ID-0001",
            caller(),
            caller(),
        ));
        assert_eq!(reg.active_count(), 1);
        let res = client
            .voip()
            .terminate("CALL-ID-0001", &caller(), &caller())
            .await;
        assert!(
            res.is_err(),
            "a failed signaling send must surface the error"
        );
        assert_eq!(
            reg.active_count(),
            0,
            "a failed signaling send must still tear the local media task down"
        );
    }

    #[tokio::test]
    async fn reject_empty_call_id_errors() {
        let (client, _count) = make_client_with_count().await;
        let mut call = incoming_reject();
        call.action = CallAction::Reject {
            call_id: String::new(),
            call_creator: caller(),
            reason: None,
        };
        assert!(client.voip().reject(&call).await.is_err());
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn local_group_controls_commit_state_events_and_screen_keyframe_gate() {
        let (client, transport) = crate::test_utils::create_iq_test_client().await;
        let own_device = Jid::new("111111111111111", Server::Lid).with_device(1);
        client
            .persistence_manager()
            .process_command(crate::store::commands::DeviceCommand::SetLid(Some(
                own_device,
            )))
            .await;
        let participant = Jid::new("111111111111111", Server::Lid);
        let creator = participant.clone();
        let call_id = "TEST-GROUP-CONTROLS";
        let registry = client.call_registry();
        let mut session =
            CallSession::new_outgoing(call_id, Jid::new(call_id, Server::Call), creator.clone());
        session.group = Some(
            GroupCallUpdate::builder()
                .call_id(call_id.to_string())
                .call_creator(creator.clone())
                .transaction_id(1)
                .media("video".to_string())
                .connected_limit(32)
                .joinable(true)
                .av_upgradable(true)
                .rekey_requested(false)
                .participants(vec![GroupCallParticipant::new(
                    participant.clone(),
                    vec![GroupCallDevice::new(participant.clone().with_device(1))],
                )])
                .build(),
        );
        let generation = registry.insert(session);
        let (event_tx, event_rx) = async_channel::bounded(4);
        let (video_tx, video_rx) = video_control_channel();
        registry.set_video_channels(call_id, generation, event_tx, video_tx, Box::new(|| {}));

        client
            .voip()
            .set_hand_raised(call_id, &creator, true)
            .await
            .expect("raise hand");
        assert!(
            registry
                .group_state(call_id)
                .expect("group state")
                .raised_hands()
                .contains(&participant)
        );
        assert!(matches!(
            event_rx.try_recv(),
            Ok(CallEvent::HandRaised {
                participant: event_participant,
                raised: true,
            }) if event_participant == participant
        ));

        assert!(
            client
                .voip()
                .set_screen_share(call_id, &creator, ScreenShareState::Started, Some(7))
                .await
                .is_err(),
            "a call without a local video plane must not advertise an unsendable screen share"
        );
        assert_eq!(
            transport.sent_count(),
            1,
            "the rejected screen-share transition must stay off the wire"
        );
        assert!(registry.set_is_video(call_id, generation, true));

        client
            .voip()
            .set_screen_share(call_id, &creator, ScreenShareState::Started, Some(7))
            .await
            .expect("start screen share");
        let share = registry
            .group_state(call_id)
            .expect("group state")
            .screen_shares()
            .get(&participant)
            .cloned()
            .expect("local screen share");
        assert_eq!(share.state, ScreenShareState::Started);
        assert_eq!(share.version, 2);
        assert_eq!(share.screen_share_id, Some(7));
        assert!(matches!(
            event_rx.try_recv(),
            Ok(CallEvent::ScreenShareChanged {
                participant: event_participant,
                screen_share,
            }) if event_participant == participant && screen_share == share
        ));
        assert_eq!(
            video_rx.try_recv(),
            Ok(VideoControl::RequireKeyframe),
            "starting a replacement screen source must re-arm the H.264 recovery gate"
        );

        client
            .voip()
            .set_screen_share(call_id, &creator, ScreenShareState::Stopped, None)
            .await
            .expect("stop screen share");
        assert!(
            registry
                .group_state(call_id)
                .expect("group state")
                .screen_shares()
                .is_empty()
        );
        assert!(matches!(
            event_rx.try_recv(),
            Ok(CallEvent::ScreenShareChanged {
                participant: event_participant,
                screen_share,
            }) if event_participant == participant
                && screen_share.state == ScreenShareState::Stopped
        ));
        assert_eq!(
            video_rx.try_recv(),
            Ok(VideoControl::RequireKeyframe),
            "returning to the camera must re-arm the H.264 recovery gate"
        );
        assert_eq!(transport.sent_count(), 3);

        let mut audio_only = registry
            .group_state_if_current(call_id, generation)
            .and_then(|state| state.snapshot().cloned())
            .expect("authoritative roster");
        audio_only.transaction_id = 2;
        audio_only.media = "audio".to_string();
        assert_eq!(
            registry.apply_group_update_if_current(audio_only, generation),
            wacore::voip::GroupStateApply::Applied
        );
        assert!(
            client
                .voip()
                .set_screen_share(call_id, &creator, ScreenShareState::Started, Some(8))
                .await
                .is_err(),
            "an authoritative audio downgrade must disable screen sharing even if local video was negotiated"
        );
        assert_eq!(
            transport.sent_count(),
            3,
            "the rejected post-downgrade transition must stay off the wire"
        );

        let replacement_creator = Jid::new("222222222222222", Server::Lid);
        let mut replacement = CallSession::new_outgoing(
            call_id,
            Jid::new(call_id, Server::Call),
            replacement_creator.clone(),
        );
        replacement.group = Some(
            GroupCallUpdate::builder()
                .call_id(call_id.to_string())
                .call_creator(replacement_creator)
                .transaction_id(1)
                .media("video".to_string())
                .connected_limit(32)
                .joinable(true)
                .av_upgradable(true)
                .rekey_requested(false)
                .participants(vec![GroupCallParticipant::new(
                    participant,
                    vec![GroupCallDevice::new(
                        Jid::new("111111111111111", Server::Lid).with_device(1),
                    )],
                )])
                .build(),
        );
        let replacement_generation = registry.insert(replacement);
        assert!(
            client
                .voip()
                .set_hand_raised(call_id, &creator, true)
                .await
                .is_err(),
            "stale creator metadata cannot mutate a replacement generation"
        );
        assert_eq!(
            transport.sent_count(),
            3,
            "a stale group identity must be rejected before signaling"
        );
        registry.remove_if_current(call_id, replacement_generation);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn local_group_controls_wait_for_the_authoritative_transition_lane() {
        let (client, transport) = crate::test_utils::create_iq_test_client().await;
        let own_device = Jid::new("111111111111111", Server::Lid).with_device(1);
        client
            .persistence_manager()
            .process_command(crate::store::commands::DeviceCommand::SetLid(Some(
                own_device,
            )))
            .await;
        let participant = Jid::new("111111111111111", Server::Lid);
        let creator = participant.clone();
        let call_id = "TEST-GROUP-CONTROL-SERIALIZATION";
        let registry = client.call_registry();
        let mut session =
            CallSession::new_outgoing(call_id, Jid::new(call_id, Server::Call), creator.clone());
        session.group = Some(
            GroupCallUpdate::builder()
                .call_id(call_id.to_string())
                .call_creator(creator.clone())
                .transaction_id(1)
                .media("video".to_string())
                .connected_limit(32)
                .joinable(true)
                .av_upgradable(true)
                .rekey_requested(false)
                .participants(vec![GroupCallParticipant::new(
                    participant,
                    vec![GroupCallDevice::new(
                        Jid::new("111111111111111", Server::Lid).with_device(1),
                    )],
                )])
                .build(),
        );
        let generation = registry.insert(session);
        assert!(registry.set_is_video(call_id, generation, true));
        let transition_lock = registry
            .group_transition_lock(call_id, generation)
            .expect("group transition lane");

        let guard = transition_lock.lock().await;
        let hand_client = client.clone();
        let hand_creator = creator.clone();
        let hand = tokio::spawn(async move {
            hand_client
                .voip()
                .set_hand_raised_for_generation(call_id, &hand_creator, generation, true)
                .await
        });
        tokio::task::yield_now().await;
        assert_eq!(
            transport.sent_count(),
            0,
            "raise-hand signaling must wait for an authoritative transition"
        );
        drop(guard);
        hand.await
            .expect("raise-hand task")
            .expect("raise-hand transition");

        let guard = transition_lock.lock().await;
        let screen_client = client.clone();
        let screen = tokio::spawn(async move {
            screen_client
                .voip()
                .set_screen_share_for_generation(
                    call_id,
                    &creator,
                    generation,
                    ScreenShareState::Started,
                    Some(7),
                )
                .await
        });
        tokio::task::yield_now().await;
        assert_eq!(
            transport.sent_count(),
            1,
            "screen-share signaling must wait for an authoritative transition"
        );
        drop(guard);
        screen
            .await
            .expect("screen-share task")
            .expect("screen-share transition");
        assert_eq!(transport.sent_count(), 2);
        registry.remove_if_current(call_id, generation);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn direct_calls_reject_group_controls_before_sending() {
        let (client, transport) = crate::test_utils::create_iq_test_client().await;
        let own_device = Jid::new("111111111111111", Server::Lid).with_device(1);
        client
            .persistence_manager()
            .process_command(crate::store::commands::DeviceCommand::SetLid(Some(
                own_device,
            )))
            .await;
        let call_id = "TEST-DIRECT-CONTROLS";
        let creator = Jid::new("111111111111111", Server::Lid);
        let generation = client.call_registry().insert(CallSession::new_outgoing(
            call_id,
            Jid::new("222222222222222", Server::Lid),
            creator.clone(),
        ));

        assert!(
            client
                .voip()
                .set_hand_raised(call_id, &creator, true)
                .await
                .is_err()
        );
        assert!(
            client
                .voip()
                .set_screen_share(call_id, &creator, ScreenShareState::Started, Some(7))
                .await
                .is_err()
        );
        assert_eq!(
            transport.sent_count(),
            0,
            "group-only controls must not be emitted for a direct call"
        );
        assert!(client.call_registry().group_state(call_id).is_none());
        client
            .call_registry()
            .remove_if_current(call_id, generation);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test(start_paused = true)]
    async fn call_link_requests_round_trip_through_bounded_response_waiters() {
        async fn wait_for_frames(
            transport: &crate::transport::mock::CapturingMockTransport,
            expected: usize,
        ) {
            for _ in 0..10_000 {
                if transport.sent_count() >= expected {
                    return;
                }
                tokio::task::yield_now().await;
            }
            panic!("timed out waiting for {expected} captured call frames");
        }

        let (client, transport) = crate::test_utils::create_iq_test_client().await;
        let own_lid = Jid::new("111111111111111", Server::Lid).with_device(1);
        client
            .persistence_manager()
            .process_command(crate::store::commands::DeviceCommand::SetLid(Some(
                own_lid.clone(),
            )))
            .await;
        let creator = Jid::new("333333333333333", Server::Lid);

        let sent = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
        let create_client = client.clone();
        let create = tokio::spawn(async move {
            create_client
                .voip()
                .create_call_link(CallLinkMedia::Video)
                .await
        });
        let request = sent.await.expect("link_create request");
        let request_id = request
            .as_node_ref()
            .attrs()
            .optional_string("id")
            .expect("request id")
            .into_owned();
        crate::test_utils::answer_iq(
            &client,
            &request_id,
            &NodeBuilder::new("ack")
                .attr("class", "call")
                .attr("type", "link_create")
                .attr("id", request_id.as_str())
                .children([NodeBuilder::new("link_create")
                    .attr("token", "TEST-CALL-LINK")
                    .attr("media", "video")
                    .build()])
                .build(),
        )
        .await;
        let link = create.await.expect("create task").expect("create response");
        assert_eq!(link.token, "TEST-CALL-LINK");
        assert_eq!(link.media, CallLinkMedia::Video);

        let sent = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
        let preview_client = client.clone();
        let preview = tokio::spawn(async move {
            preview_client
                .voip()
                .preview_call_link("TEST-CALL-LINK", CallLinkMedia::Video)
                .await
        });
        let request = sent.await.expect("link_query request");
        let request_id = request
            .as_node_ref()
            .attrs()
            .optional_string("id")
            .expect("request id")
            .into_owned();
        crate::test_utils::answer_iq(
            &client,
            &request_id,
            &NodeBuilder::new("ack")
                .attr("class", "call")
                .attr("type", "link_query")
                .attr("id", request_id.as_str())
                .children([NodeBuilder::new("link_query")
                    .attr("token", "TEST-CALL-LINK")
                    .attr("media", "video")
                    .attr("link_creator", creator.clone())
                    .children([NodeBuilder::new("waiting_room")
                        .attr("enabled", "1")
                        .attr("is_admin", "0")
                        .build()])
                    .build()])
                .build(),
        )
        .await;
        let preview = preview
            .await
            .expect("preview task")
            .expect("preview response");
        assert_eq!(preview.creator, creator);
        assert!(preview.waiting_room_enabled);
        assert!(!preview.is_admin);

        let sent = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
        let join_client = client.clone();
        let join = tokio::spawn(async move {
            join_client
                .voip()
                .join_call_link_with_audio(
                    "TEST-CALL-LINK",
                    CallLinkMedia::Video,
                    AudioFormat::OPUS_16KHZ_60MS,
                )
                .await
        });
        let request = sent.await.expect("link_join request");
        let request_ref = request.as_node_ref();
        let action = &request_ref.children().expect("join action children")[0];
        assert_eq!(
            action
                .get_optional_child("capability")
                .expect("join capability")
                .content_bytes(),
            Some(wacore::stanza::call::CAPABILITY_STANDARD_OPUS_VIDEO_OFFER.as_slice())
        );
        let request_id = request
            .as_node_ref()
            .attrs()
            .optional_string("id")
            .expect("request id")
            .into_owned();
        crate::test_utils::answer_iq(
            &client,
            &request_id,
            &NodeBuilder::new("ack")
                .attr("class", "call")
                .attr("type", "link_join")
                .attr("id", request_id.as_str())
                .children([NodeBuilder::new("waiting_room")
                    .attr("call-id", "TEST-CALL-ID")
                    .attr("call-creator", creator.clone())
                    .attr("link-token", "TEST-CALL-LINK")
                    .attr("media", "video")
                    .attr("enabled", "1")
                    .attr("is_admin", "0")
                    .attr("transaction-id", "7")
                    .children([NodeBuilder::new("user")
                        .attr("jid", Jid::new("444444444444444", Server::Lid))
                        .attr("state", "pending")
                        .build()])
                    .build()])
                .build(),
        )
        .await;
        let join = join.await.expect("join task").expect("join response");
        assert!(join.in_waiting_room);
        assert!(join.waiting_room_enabled);
        assert_eq!(join.call_id, "TEST-CALL-ID");
        assert!(join.group.is_none());
        assert_eq!(
            client.call_registry().phase("TEST-CALL-ID"),
            Some(CallPhase::WaitingRoom)
        );
        let room = client
            .call_registry()
            .group_state("TEST-CALL-ID")
            .and_then(|state| state.waiting_room().cloned())
            .expect("waiting-room state retained");
        assert_eq!(room.transaction_id, Some(7));
        assert_eq!(room.users.len(), 1);

        wait_for_frames(&transport, 4).await;
        let immediate = crate::test_utils::decode_sent_iq(&transport, 3).await;
        let heartbeat = &immediate.get().children().expect("heartbeat action")[0];
        assert_eq!(heartbeat.tag, "heartbeat");
        assert_eq!(
            heartbeat.attrs().optional_string("type").as_deref(),
            Some("waiting_room")
        );

        tokio::time::advance(Duration::from_secs(10)).await;
        wait_for_frames(&transport, 5).await;
        let scheduled = crate::test_utils::decode_sent_iq(&transport, 4).await;
        assert_eq!(
            scheduled.get().children().expect("heartbeat action")[0].tag,
            "heartbeat"
        );

        let admitted = NodeBuilder::new("group_update")
            .attr("call-id", "TEST-CALL-ID")
            .attr("call-creator", creator)
            .children([NodeBuilder::new("group_info")
                .attr("transaction-id", "8")
                .attr("connected-limit", "32")
                .attr("media", "video")
                .children([NodeBuilder::new("user")
                    .attr("jid", own_lid.to_non_ad())
                    .attr("state", "connected")
                    .children([NodeBuilder::new("device").attr("jid", own_lid).build()])
                    .build()])
                .build()])
            .build();
        let update = wacore::stanza::group_call::parse_group_update(&admitted.as_node_ref())
            .expect("admitted group snapshot");
        assert_eq!(
            client.call_registry().apply_group_update(update),
            wacore::voip::GroupStateApply::Applied
        );
        assert_eq!(
            client.call_registry().phase("TEST-CALL-ID"),
            Some(CallPhase::Connecting)
        );
        let heartbeat_count = transport.sent_count();
        tokio::time::advance(Duration::from_secs(20)).await;
        tokio::task::yield_now().await;
        assert_eq!(
            transport.sent_count(),
            heartbeat_count,
            "admission must cancel the repeating heartbeat"
        );
        let generation = client
            .call_registry()
            .generation_of("TEST-CALL-ID")
            .expect("registered call-link generation");
        client
            .call_registry()
            .remove_if_current("TEST-CALL-ID", generation);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn call_link_preview_rejects_a_changed_token_or_media() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let creator = Jid::new("333333333333333", Server::Lid);
        for (response_token, response_media) in
            [("OTHER-CALL-LINK", "video"), ("TEST-CALL-LINK", "audio")]
        {
            let sent = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
            let preview_client = client.clone();
            let preview = tokio::spawn(async move {
                preview_client
                    .voip()
                    .preview_call_link("TEST-CALL-LINK", CallLinkMedia::Video)
                    .await
            });
            let request = sent.await.expect("link_query request");
            let request_id = request
                .as_node_ref()
                .attrs()
                .optional_string("id")
                .expect("request id")
                .into_owned();
            crate::test_utils::answer_iq(
                &client,
                &request_id,
                &NodeBuilder::new("ack")
                    .attr("class", "call")
                    .attr("type", "link_query")
                    .attr("id", request_id.as_str())
                    .children([NodeBuilder::new("link_query")
                        .attr("token", response_token)
                        .attr("media", response_media)
                        .attr("link_creator", creator.clone())
                        .build()])
                    .build(),
            )
            .await;
            assert!(matches!(
                preview.await.expect("preview task"),
                Err(CallError::Response(message))
                    if message == "call-link preview changed the requested link identity"
            ));
        }
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn call_link_creation_rejects_a_changed_media_mode() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let sent = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
        let create_client = client.clone();
        let create = tokio::spawn(async move {
            create_client
                .voip()
                .create_call_link(CallLinkMedia::Video)
                .await
        });
        let request = sent.await.expect("link_create request");
        let request_id = request
            .as_node_ref()
            .attrs()
            .optional_string("id")
            .expect("request id")
            .into_owned();
        crate::test_utils::answer_iq(
            &client,
            &request_id,
            &NodeBuilder::new("ack")
                .attr("class", "call")
                .attr("type", "link_create")
                .attr("id", request_id.as_str())
                .children([NodeBuilder::new("link_create")
                    .attr("token", "TEST-CALL-LINK")
                    .attr("media", "audio")
                    .build()])
                .build(),
        )
        .await;
        assert!(matches!(
            create.await.expect("create task"),
            Err(CallError::Response(message))
                if message == "call-link creation changed the requested media mode"
        ));
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn approval_ack_cannot_commit_to_a_replacement_generation() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let call_id = "TEST-APPROVAL-GENERATION";
        let creator = Jid::new("333333333333333", Server::Lid);
        let registry = client.call_registry();
        let first = registry
            .insert_call_link_checked(CallSession::new_outgoing(
                call_id,
                Jid::new(call_id, Server::Call),
                creator.clone(),
            ))
            .expect("valid call-link session");
        assert_eq!(
            registry.apply_waiting_room(
                WaitingRoom::builder()
                    .call_id(call_id.to_string())
                    .call_creator(creator.clone())
                    .link_token("TEST-CALL-LINK".to_string())
                    .media(CallLinkMedia::Audio)
                    .enabled(false)
                    .is_admin(true)
                    .transaction_id(1)
                    .users(Vec::new())
                    .build(),
            ),
            wacore::voip::GroupStateApply::Applied
        );

        let sent = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
        let request_client = client.clone();
        let request_creator = creator.clone();
        let toggle = tokio::spawn(async move {
            request_client
                .voip()
                .set_approval_required(call_id, &request_creator, true)
                .await
        });
        let request = sent.await.expect("waiting-room toggle request");
        let request_id = request
            .as_node_ref()
            .attrs()
            .optional_string("id")
            .expect("request id")
            .into_owned();

        let replacement = registry.insert(CallSession::new_outgoing(
            call_id,
            Jid::new(call_id, Server::Call),
            creator,
        ));
        assert_ne!(replacement, first);
        crate::test_utils::answer_iq(
            &client,
            &request_id,
            &NodeBuilder::new("ack")
                .attr("class", "call")
                .attr("type", "waiting_room_toggle")
                .attr("id", request_id.as_str())
                .build(),
        )
        .await;

        assert!(matches!(
            toggle.await.expect("toggle task"),
            Err(CallError::Media(
                "call was replaced while applying group control"
            ))
        ));
        assert!(
            registry.group_state(call_id).is_none(),
            "the stale ACK must not synthesize waiting-room state on the replacement"
        );
        registry.remove_if_current(call_id, replacement);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn approval_toggle_serializes_with_authoritative_waiting_room_updates() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let call_id = "TEST-APPROVAL-SERIALIZATION";
        let creator = Jid::new("333333333333333", Server::Lid);
        let registry = client.call_registry();
        let generation = registry
            .insert_call_link_checked(CallSession::new_outgoing(
                call_id,
                Jid::new(call_id, Server::Call),
                creator.clone(),
            ))
            .expect("valid call-link session");
        let room = |transaction_id, enabled| {
            WaitingRoom::builder()
                .call_id(call_id.to_string())
                .call_creator(creator.clone())
                .link_token("TEST-CALL-LINK".to_string())
                .media(CallLinkMedia::Audio)
                .enabled(enabled)
                .is_admin(true)
                .transaction_id(transaction_id)
                .users(Vec::new())
                .build()
        };
        assert_eq!(
            registry.apply_waiting_room(room(1, false)),
            wacore::voip::GroupStateApply::Applied
        );
        let transition_lock = registry
            .group_transition_lock(call_id, generation)
            .expect("active group transition");

        let sent = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
        let request_client = client.clone();
        let request_creator = creator.clone();
        let toggle = tokio::spawn(async move {
            request_client
                .voip()
                .set_approval_required_for_generation(call_id, &request_creator, generation, true)
                .await
        });
        let request = sent.await.expect("waiting-room toggle request");
        let request_id = request
            .as_node_ref()
            .attrs()
            .optional_string("id")
            .expect("request id")
            .into_owned();

        let update_registry = registry.clone();
        let update = room(2, false);
        let authoritative = tokio::spawn(async move {
            let _guard = transition_lock.lock().await;
            update_registry.apply_waiting_room_if_current(update, generation)
        });
        tokio::task::yield_now().await;
        assert!(
            !authoritative.is_finished(),
            "the authoritative snapshot must wait for the toggle ACK and local commit"
        );

        crate::test_utils::answer_iq(
            &client,
            &request_id,
            &NodeBuilder::new("ack")
                .attr("class", "call")
                .attr("type", "waiting_room_toggle")
                .attr("id", request_id.as_str())
                .build(),
        )
        .await;
        toggle.await.expect("toggle task").expect("toggle response");
        assert_eq!(
            authoritative.await.expect("authoritative update task"),
            wacore::voip::GroupStateApply::Applied
        );
        assert!(
            registry
                .group_state_if_current(call_id, generation)
                .and_then(|state| state.waiting_room().cloned())
                .is_some_and(|room| room.transaction_id == Some(2) && !room.enabled),
            "the newer authoritative snapshot must win after the serialized local toggle"
        );
        registry.remove_if_current(call_id, generation);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn waiting_room_user_acks_are_bound_to_the_originating_generation() {
        let user = Jid::new("444444444444444", Server::Lid);
        for (index, action) in [WaitingRoomUserAction::Admit, WaitingRoomUserAction::Deny]
            .into_iter()
            .enumerate()
        {
            let (client, _transport) = crate::test_utils::create_iq_test_client().await;
            let call_id = format!("TEST-WAITING-ACTION-{index}");
            let creator = Jid::new("333333333333333", Server::Lid);
            let registry = client.call_registry();
            let first = registry
                .insert_call_link_checked(CallSession::new_outgoing(
                    &call_id,
                    Jid::new(&call_id, Server::Call),
                    creator.clone(),
                ))
                .expect("valid call-link session");
            assert_eq!(
                registry.apply_waiting_room(
                    WaitingRoom::builder()
                        .call_id(call_id.clone())
                        .call_creator(creator.clone())
                        .link_token("TEST-CALL-LINK".to_string())
                        .media(CallLinkMedia::Audio)
                        .enabled(true)
                        .is_admin(true)
                        .transaction_id(1)
                        .users(Vec::new())
                        .build(),
                ),
                wacore::voip::GroupStateApply::Applied
            );

            let sent = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
            let request_client = client.clone();
            let request_call_id = call_id.clone();
            let request_creator = creator.clone();
            let request_user = user.clone();
            let control = tokio::spawn(async move {
                match action {
                    WaitingRoomUserAction::Admit => {
                        request_client
                            .voip()
                            .admit_waiting_user_for_generation(
                                &request_call_id,
                                &request_creator,
                                first,
                                &request_user,
                            )
                            .await
                    }
                    WaitingRoomUserAction::Deny => {
                        request_client
                            .voip()
                            .deny_waiting_user_for_generation(
                                &request_call_id,
                                &request_creator,
                                first,
                                &request_user,
                            )
                            .await
                    }
                }
            });
            let request = sent.await.expect("waiting-room user request");
            let request_id = request
                .as_node_ref()
                .attrs()
                .optional_string("id")
                .expect("request id")
                .into_owned();

            let replacement = registry.insert(CallSession::new_outgoing(
                &call_id,
                Jid::new(&call_id, Server::Call),
                creator,
            ));
            assert_ne!(replacement, first);
            let action_type = match action {
                WaitingRoomUserAction::Admit => "waiting_room_admit",
                WaitingRoomUserAction::Deny => "waiting_room_deny",
            };
            crate::test_utils::answer_iq(
                &client,
                &request_id,
                &NodeBuilder::new("ack")
                    .attr("class", "call")
                    .attr("type", action_type)
                    .attr("id", request_id.as_str())
                    .build(),
            )
            .await;

            assert!(matches!(
                control.await.expect("waiting-room control task"),
                Err(CallError::Media(
                    "call was replaced while applying group control"
                ))
            ));
            registry.remove_if_current(&call_id, replacement);
        }
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn call_link_admission_is_buffered_until_ack_registration() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let creator = Jid::new("333333333333333", Server::Lid);
        let call_id = "BUFFERED-ADMISSION";
        let local_device = Jid::new("111111111111111", Server::Lid).with_device(1);
        let mut participant = GroupCallParticipant::new(
            local_device.to_non_ad(),
            vec![GroupCallDevice::new(local_device.clone())],
        );
        participant.state = Some("connected".to_string());
        let update = GroupCallUpdate::builder()
            .call_id(call_id.to_string())
            .call_creator(creator.clone())
            .transaction_id(8)
            .media("audio".to_string())
            .connected_limit(32)
            .joinable(true)
            .av_upgradable(true)
            .rekey_requested(false)
            .participants(vec![participant])
            .build();
        let creator_sender = creator.clone().with_device(1);

        let pending = client.begin_call_link_join();
        assert_eq!(
            client.buffer_pending_call_link_update(&update, &creator_sender),
            PendingCallLinkBuffer::Buffered,
            "the creator's admission update must survive until the ACK registers its call id"
        );
        assert_eq!(
            client.buffer_pending_call_link_update(
                &update,
                &Jid::new("999999999999999", Server::Lid)
            ),
            PendingCallLinkBuffer::NotPending,
            "an unrelated sender cannot populate the pre-registration buffer"
        );
        let pending_memory = client.memory_report().await.pending_call_link_updates;
        assert_eq!(pending_memory.entries, 1);
        assert!(pending_memory.bytes > 0);

        let mut session =
            CallSession::new_outgoing(call_id, Jid::new(call_id, Server::Call), creator);
        let _ = session.transition_to(CallPhase::Calling);
        let _ = session.transition_to(CallPhase::WaitingRoom);
        let generation = client
            .register_call_link_session(session, None, CallLinkMedia::Audio, "TEST-CALL-LINK")
            .await
            .expect("valid buffered admission");
        assert!(client.call_registry().set_group_invite_self_device(
            call_id,
            generation,
            GroupCallDevice::new(local_device).with_capability(1, [1]),
        ));
        assert_eq!(
            client.call_registry().phase_if_current(call_id, generation),
            Some(CallPhase::Connecting),
            "consuming the buffered admission must perform the waiting-room transition"
        );
        assert_eq!(
            client
                .call_registry()
                .group_state_if_current(call_id, generation)
                .and_then(|state| { state.snapshot().map(|snapshot| snapshot.transaction_id) }),
            Some(8)
        );
        assert_eq!(
            client
                .memory_report()
                .await
                .pending_call_link_updates
                .entries,
            0
        );
        let mut later = update;
        later.transaction_id = 9;
        assert_eq!(
            client.buffer_pending_call_link_update(&later, &creator_sender),
            PendingCallLinkBuffer::NotPending,
            "an already registered generation must dispatch instead of entering an orphan buffer"
        );

        drop(pending);
        client
            .call_registry()
            .remove_if_current(call_id, generation);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn call_link_termination_before_registration_rejects_the_join() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let creator = Jid::new("333333333333333", Server::Lid);
        let call_id = "TERMINATED-CALL-LINK";
        let _pending = client.begin_call_link_join();
        assert!(
            client
                .retain_or_apply_pending_call_link_terminate(
                    call_id,
                    &creator,
                    &creator.clone().with_device(1),
                )
                .await
        );

        let mut session =
            CallSession::new_outgoing(call_id, Jid::new(call_id, Server::Call), creator);
        let _ = session.transition_to(CallPhase::Calling);
        let _ = session.transition_to(CallPhase::WaitingRoom);
        assert_eq!(
            client
                .register_call_link_session(session, None, CallLinkMedia::Audio, "TEST-CALL-LINK")
                .await,
            Err(wacore::voip::GroupStateApply::InvalidSnapshot)
        );
        assert_eq!(
            client.call_registry().generation_of(call_id),
            None,
            "a terminal control that overtakes registration must prevent publication"
        );
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn call_link_termination_removes_a_generation_that_won_registration() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let creator = Jid::new("333333333333333", Server::Lid);
        let call_id = "REGISTERED-THEN-TERMINATED-CALL-LINK";
        let _pending = client.begin_call_link_join();
        let mut session =
            CallSession::new_outgoing(call_id, Jid::new(call_id, Server::Call), creator.clone());
        let _ = session.transition_to(CallPhase::Calling);
        let _ = session.transition_to(CallPhase::WaitingRoom);
        let generation = client
            .register_call_link_session(session, None, CallLinkMedia::Audio, "TEST-CALL-LINK")
            .await
            .expect("registration wins the answer-transition lane");

        assert!(
            client
                .retain_or_apply_pending_call_link_terminate(
                    call_id,
                    &creator,
                    &creator.with_device(1),
                )
                .await
        );
        assert_eq!(
            client.call_registry().generation_of(call_id),
            None,
            "the terminal control must remove the just-published generation"
        );
        assert!(
            !client.call_registry().is_current(call_id, generation),
            "the removed generation cannot remain active"
        );
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn call_link_epoch_before_registration_is_replayed_to_the_generation() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let creator = Jid::new("333333333333333", Server::Lid);
        let call_id = "EPOCH-CALL-LINK";
        let _pending = client.begin_call_link_join();
        assert_eq!(
            client.buffer_pending_call_link_epoch(
                call_id,
                &creator,
                &creator.clone().with_device(1),
                7,
                &[7; 32],
            ),
            PendingCallLinkBuffer::Buffered
        );

        let mut session =
            CallSession::new_outgoing(call_id, Jid::new(call_id, Server::Call), creator);
        let _ = session.transition_to(CallPhase::Calling);
        let _ = session.transition_to(CallPhase::Connecting);
        let generation = client
            .register_call_link_session(session, None, CallLinkMedia::Audio, "TEST-CALL-LINK")
            .await
            .expect("valid call-link generation");
        assert_eq!(
            client
                .call_registry()
                .pending_group_epoch_transaction_if_current(call_id, generation),
            Some(7),
            "the decrypted epoch must survive until the media driver attaches"
        );
        client
            .call_registry()
            .remove_if_current(call_id, generation);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn staged_call_link_epoch_and_termination_revalidate_provenance() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let call_id = "PROVENANCE-CALL-LINK";
        let creator = Jid::new("333333333333333", Server::Lid);
        let asserted_creator = Jid::new("999999999999999", Server::Lid);
        let asserted_sender = asserted_creator.clone().with_device(7);
        let _pending = client.begin_call_link_join();

        assert_eq!(
            client.buffer_pending_call_link_epoch(
                call_id,
                &asserted_creator,
                &asserted_sender,
                7,
                &[7; 32],
            ),
            PendingCallLinkBuffer::Buffered
        );
        assert_eq!(
            client
                .buffer_pending_call_link_terminate(call_id, &asserted_creator, &asserted_sender,),
            PendingCallLinkBuffer::Buffered
        );

        let mut session =
            CallSession::new_outgoing(call_id, Jid::new(call_id, Server::Call), creator);
        let _ = session.transition_to(CallPhase::Calling);
        let _ = session.transition_to(CallPhase::Connecting);
        let generation = client
            .register_call_link_session(session, None, CallLinkMedia::Audio, "TEST-CALL-LINK")
            .await
            .expect("unauthorized staged controls must not abort the legitimate join");
        assert!(
            client.call_registry().is_current(call_id, generation),
            "the unauthorized terminal marker must be ignored after registration"
        );
        assert_eq!(
            client
                .call_registry()
                .pending_group_epoch_transaction_if_current(call_id, generation),
            None,
            "the unauthorized epoch must not enter the registered generation"
        );
        client
            .call_registry()
            .remove_if_current(call_id, generation);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn concurrent_call_link_join_waits_for_the_unknown_call_id_lane() {
        use std::time::Duration;

        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        client
            .persistence_manager()
            .process_command(crate::store::commands::DeviceCommand::SetLid(Some(
                Jid::new("111111111111111", Server::Lid).with_device(1),
            )))
            .await;

        let first_request = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
        let first_client = client.clone();
        let first = tokio::spawn(async move {
            first_client
                .voip()
                .join_call_link_registration_with_audio(
                    "FIRST-CALL-LINK",
                    CallLinkMedia::Audio,
                    AudioFormat::OPUS_16KHZ_60MS,
                )
                .await
        });
        first_request.await.expect("first link_join request");

        let second_request = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
        let second_client = client.clone();
        let second = tokio::spawn(async move {
            second_client
                .voip()
                .join_call_link_registration_with_audio(
                    "SECOND-CALL-LINK",
                    CallLinkMedia::Audio,
                    AudioFormat::OPUS_16KHZ_60MS,
                )
                .await
        });
        assert!(
            tokio::time::timeout(Duration::from_millis(25), second_request)
                .await
                .is_err(),
            "a second unknown-call-id join must wait instead of sharing the first join's buffer"
        );

        let released_request = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
        first.abort();
        let _ = first.await;
        tokio::time::timeout(Duration::from_secs(1), released_request)
            .await
            .expect("the second join lane should be released")
            .expect("second link_join request");
        second.abort();
        let _ = second.await;
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn registered_call_link_releases_the_unknown_id_lane_before_heartbeat() {
        use std::time::Duration;
        use wacore::handshake::NoiseCipher;

        struct GatedTransport {
            started: async_channel::Sender<()>,
            release: async_channel::Receiver<()>,
            gate_next_send: std::sync::atomic::AtomicBool,
        }

        #[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
        #[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
        impl crate::transport::Transport for GatedTransport {
            async fn send(&self, _data: Bytes) -> Result<(), anyhow::Error> {
                if self.gate_next_send.swap(false, Ordering::AcqRel) {
                    self.started
                        .send(())
                        .await
                        .map_err(|_| anyhow::anyhow!("heartbeat observer closed"))?;
                    self.release
                        .recv()
                        .await
                        .map_err(|_| anyhow::anyhow!("heartbeat gate closed"))?;
                }
                Ok(())
            }

            async fn disconnect(&self) {}
        }

        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        client
            .persistence_manager()
            .process_command(crate::store::commands::DeviceCommand::SetLid(Some(
                Jid::new("111111111111111", Server::Lid).with_device(1),
            )))
            .await;
        let creator = Jid::new("333333333333333", Server::Lid);
        let first_request = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
        let first_client = client.clone();
        let first = tokio::spawn(async move {
            first_client
                .voip()
                .join_call_link_registration_with_audio(
                    "FIRST-CALL-LINK",
                    CallLinkMedia::Audio,
                    AudioFormat::OPUS_16KHZ_60MS,
                )
                .await
        });
        let request = first_request.await.expect("first link_join request");
        let request_id = request
            .as_node_ref()
            .attrs()
            .optional_string("id")
            .expect("request id")
            .into_owned();
        let (started_tx, started_rx) = async_channel::bounded(1);
        let (release_tx, release_rx) = async_channel::bounded(1);
        let gated_socket = crate::socket::NoiseSocket::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            Arc::new(GatedTransport {
                started: started_tx,
                release: release_rx,
                gate_next_send: std::sync::atomic::AtomicBool::new(true),
            }),
            NoiseCipher::new(&[0u8; 32]).expect("valid key"),
            NoiseCipher::new(&[0u8; 32]).expect("valid key"),
        );
        *client.noise_socket.lock().await = Some(Arc::new(gated_socket));
        crate::test_utils::answer_iq(
            &client,
            &request_id,
            &NodeBuilder::new("ack")
                .attr("class", "call")
                .attr("type", "link_join")
                .attr("id", request_id.as_str())
                .children([NodeBuilder::new("waiting_room")
                    .attr("call-id", "FIRST-CALL-ID")
                    .attr("call-creator", creator.clone())
                    .attr("link-token", "FIRST-CALL-LINK")
                    .attr("media", "audio")
                    .attr("enabled", "1")
                    .attr("is_admin", "0")
                    .attr("transaction-id", "1")
                    .build()])
                .build(),
        )
        .await;
        started_rx
            .recv()
            .await
            .expect("first waiting-room heartbeat entered the gated transport");

        let second_request = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
        let second_client = client.clone();
        let second = tokio::spawn(async move {
            second_client
                .voip()
                .join_call_link_registration_with_audio(
                    "SECOND-CALL-LINK",
                    CallLinkMedia::Audio,
                    AudioFormat::OPUS_16KHZ_60MS,
                )
                .await
        });
        let request = tokio::time::timeout(Duration::from_secs(1), second_request)
            .await
            .expect("registration must release the lane while the heartbeat remains gated")
            .expect("second link_join request");
        assert_eq!(
            request
                .as_node_ref()
                .children()
                .expect("second request action")[0]
                .tag,
            "link_join"
        );
        let second_sender = creator.clone().with_device(1);
        let second_update = GroupCallUpdate::builder()
            .call_id("SECOND-CALL-ID".to_string())
            .call_creator(creator)
            .transaction_id(1)
            .media("audio".to_string())
            .connected_limit(32)
            .joinable(true)
            .av_upgradable(true)
            .rekey_requested(false)
            .participants(Vec::new())
            .build();
        assert_eq!(
            client.buffer_pending_call_link_update(&second_update, &second_sender),
            PendingCallLinkBuffer::Buffered,
            "the second join must not inherit the first call id's provisional binding"
        );

        release_tx.send(()).await.expect("release heartbeat send");
        second.abort();
        let _ = second.await;
        let registration = first
            .await
            .expect("first join task")
            .expect("first waiting-room registration");
        drop(registration);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn pending_call_link_transitions_are_bounded_by_retained_bytes() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let creator = Jid::new("333333333333333", Server::Lid);
        let sender = creator.clone().with_device(1);
        let _pending = client.begin_call_link_join();
        let chunk = MAX_PENDING_CALL_LINK_TRANSITION_BYTES / 3;
        let mut accepted = 0;
        for index in 0..4 {
            let participant = GroupCallParticipant::new(
                creator.clone(),
                vec![GroupCallDevice::new(sender.clone()).with_capability(1, vec![7; chunk])],
            );
            let update = GroupCallUpdate::builder()
                .call_id(format!("BUFFERED-BYTES-{index}"))
                .call_creator(creator.clone())
                .transaction_id(1)
                .media("audio".to_string())
                .connected_limit(32)
                .joinable(true)
                .av_upgradable(true)
                .rekey_requested(false)
                .participants(vec![participant])
                .build();
            accepted += usize::from(
                client.buffer_pending_call_link_update(&update, &sender)
                    == PendingCallLinkBuffer::Buffered,
            );
        }
        let stats = client.memory_report().await.pending_call_link_updates;
        assert!(
            accepted < 4,
            "the aggregate byte budget must reject excess staged snapshots"
        );
        assert!(
            stats.bytes <= MAX_PENDING_CALL_LINK_TRANSITION_BYTES as u64,
            "retained staged snapshots must stay within the aggregate byte budget"
        );

        let oversized = GroupCallUpdate::builder()
            .call_id("BUFFERED-OVERSIZED".to_string())
            .call_creator(creator.clone())
            .transaction_id(1)
            .media("audio".to_string())
            .connected_limit(32)
            .joinable(true)
            .av_upgradable(true)
            .rekey_requested(false)
            .participants(vec![GroupCallParticipant::new(
                creator,
                vec![
                    GroupCallDevice::new(sender.clone())
                        .with_capability(1, vec![7; MAX_PENDING_CALL_LINK_TRANSITION_BYTES]),
                ],
            )])
            .build();
        assert_eq!(
            client.buffer_pending_call_link_update(&oversized, &sender),
            PendingCallLinkBuffer::Saturated,
            "one staged snapshot cannot consume the entire retained-byte budget"
        );
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn saturated_call_link_admission_fails_instead_of_falling_back() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let creator = Jid::new("333333333333333", Server::Lid);
        let sender = creator.clone().with_device(1);
        let call_id = "SATURATED-ADMISSION";
        let _pending = client.begin_call_link_join();
        let update = GroupCallUpdate::builder()
            .call_id(call_id.to_string())
            .call_creator(creator.clone())
            .transaction_id(1)
            .media("audio".to_string())
            .connected_limit(32)
            .joinable(true)
            .av_upgradable(true)
            .rekey_requested(false)
            .participants(vec![GroupCallParticipant::new(
                creator.clone(),
                vec![
                    GroupCallDevice::new(sender.clone())
                        .with_capability(1, vec![7; MAX_PENDING_CALL_LINK_TRANSITION_BYTES]),
                ],
            )])
            .build();
        assert_eq!(
            client.buffer_pending_call_link_update(&update, &sender),
            PendingCallLinkBuffer::Saturated,
            "the admission is handled locally even when it exceeds the staging budget"
        );

        let mut session =
            CallSession::new_outgoing(call_id, Jid::new(call_id, Server::Call), creator);
        let _ = session.transition_to(CallPhase::Calling);
        let _ = session.transition_to(CallPhase::WaitingRoom);
        assert_eq!(
            client
                .register_call_link_session(session, None, CallLinkMedia::Audio, "TEST-CALL-LINK",)
                .await,
            Err(wacore::voip::GroupStateApply::InvalidSnapshot),
            "a saturated join must fail rather than wait forever for a discarded admission"
        );
        assert_eq!(client.call_registry().generation_of(call_id), None);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn saturated_admission_is_retained_when_unrelated_call_ids_fill_the_payload_budget() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let creator = Jid::new("333333333333333", Server::Lid);
        let sender = creator.clone().with_device(1);
        let _pending = client.begin_call_link_join();
        for index in 0..MAX_PENDING_CALL_LINK_TRANSITIONS {
            let unrelated_creator = Jid::new(format!("55555555555{index:04}"), Server::Lid);
            let unrelated_sender = unrelated_creator.clone().with_device(1);
            assert_eq!(
                client.buffer_pending_call_link_terminate(
                    &format!("UNRELATED-{index}"),
                    &unrelated_creator,
                    &unrelated_sender,
                ),
                PendingCallLinkBuffer::Buffered
            );
        }

        let call_id = "SATURATED-AFTER-UNRELATED";
        let oversized = GroupCallUpdate::builder()
            .call_id(call_id.to_string())
            .call_creator(creator.clone())
            .transaction_id(1)
            .media("audio".to_string())
            .connected_limit(32)
            .joinable(true)
            .av_upgradable(true)
            .rekey_requested(false)
            .participants(vec![GroupCallParticipant::new(
                creator.clone(),
                vec![
                    GroupCallDevice::new(sender.clone())
                        .with_capability(1, vec![7; MAX_PENDING_CALL_LINK_TRANSITION_BYTES]),
                ],
            )])
            .build();
        assert_eq!(
            client.buffer_pending_call_link_update(&oversized, &sender),
            PendingCallLinkBuffer::Saturated
        );

        let mut session =
            CallSession::new_outgoing(call_id, Jid::new(call_id, Server::Call), creator);
        let _ = session.transition_to(CallPhase::Calling);
        let _ = session.transition_to(CallPhase::WaitingRoom);
        assert_eq!(
            client
                .register_call_link_session(session, None, CallLinkMedia::Audio, "TEST-CALL-LINK",)
                .await,
            Err(wacore::voip::GroupStateApply::InvalidSnapshot),
            "binding the ACK must retain the exact overflow identity outside the full payload map"
        );
        assert_eq!(client.call_registry().generation_of(call_id), None);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn unrelated_saturation_does_not_reject_the_valid_call_link_join() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let unrelated_creator = Jid::new("333333333333333", Server::Lid);
        let unrelated_sender = unrelated_creator.clone().with_device(1);
        let _pending = client.begin_call_link_join();
        for index in 0..MAX_PENDING_CALL_LINK_TRANSITIONS {
            assert!(
                client
                    .buffer_pending_call_link_terminate(
                        &format!("UNRELATED-{index}"),
                        &unrelated_creator,
                        &unrelated_sender,
                    )
                    .suppresses_dispatch()
            );
        }
        let mut oversized = GroupCallUpdate::builder()
            .call_id("UNRELATED-SATURATED-CALL-0".to_string())
            .call_creator(unrelated_creator.clone())
            .transaction_id(1)
            .media("audio".to_string())
            .connected_limit(32)
            .joinable(true)
            .av_upgradable(true)
            .rekey_requested(false)
            .participants(vec![GroupCallParticipant::new(
                unrelated_creator,
                vec![
                    GroupCallDevice::new(unrelated_sender.clone())
                        .with_capability(1, vec![7; MAX_PENDING_CALL_LINK_TRANSITION_BYTES]),
                ],
            )])
            .build();
        for index in 0..=MAX_PENDING_CALL_LINK_SATURATION_FINGERPRINTS {
            oversized.call_id = format!("UNRELATED-SATURATED-CALL-{index}");
            assert_eq!(
                client.buffer_pending_call_link_update(&oversized, &unrelated_sender),
                PendingCallLinkBuffer::Saturated,
                "every oversized unrelated identity must remain handled locally"
            );
        }

        let call_id = "VALID-CALL-LINK";
        let call_creator = Jid::new("444444444444444", Server::Lid);
        let ack = NodeBuilder::new("ack")
            .attr("class", "call")
            .attr("type", "link_join")
            .children([NodeBuilder::new("waiting_room")
                .attr("call-id", call_id)
                .build()])
            .build();
        client.bind_pending_call_link_join_ack(&ack.as_node_ref());
        assert!(
            client.prepare_pending_call_link_join_retry(call_id),
            "exhausted pre-ACK identity metadata requires one exact-call refresh"
        );
        assert_eq!(
            client
                .memory_report()
                .await
                .pending_call_link_updates
                .entries,
            0,
            "binding the ACK must discard every unrelated candidate bucket"
        );
        assert_eq!(
            client.buffer_pending_call_link_terminate(
                "LATE-UNRELATED",
                &unrelated_sender.to_non_ad(),
                &unrelated_sender,
            ),
            PendingCallLinkBuffer::NotPending,
            "later unrelated controls cannot consume the bound join's budget"
        );
        let mut participant = GroupCallParticipant::new(
            call_creator.clone(),
            vec![GroupCallDevice::new(call_creator.clone().with_device(1))],
        );
        participant.state = Some("connected".to_string());
        let admitted = GroupCallUpdate::builder()
            .call_id(call_id.to_string())
            .call_creator(call_creator.clone())
            .transaction_id(1)
            .media("audio".to_string())
            .connected_limit(32)
            .joinable(true)
            .av_upgradable(true)
            .rekey_requested(false)
            .participants(vec![participant])
            .build();
        assert_eq!(
            client
                .buffer_pending_call_link_update(&admitted, &call_creator.clone().with_device(1),),
            PendingCallLinkBuffer::Buffered
        );
        let mut session =
            CallSession::new_outgoing(call_id, Jid::new(call_id, Server::Call), call_creator);
        let _ = session.transition_to(CallPhase::Calling);
        let _ = session.transition_to(CallPhase::WaitingRoom);
        let generation = client
            .register_call_link_session(session, None, CallLinkMedia::Audio, "VALID-CALL-LINK")
            .await
            .expect("an unrelated saturated control cannot abort the ACK's actual call id");
        assert!(
            client.call_registry().is_current(call_id, generation),
            "the legitimate call-link generation must remain registered"
        );
        assert_eq!(
            client
                .call_registry()
                .group_state_if_current(call_id, generation)
                .and_then(|state| state.snapshot().map(|snapshot| snapshot.transaction_id)),
            Some(1)
        );
        client
            .call_registry()
            .remove_if_current(call_id, generation);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn ambiguous_pre_ack_saturation_retries_after_binding_the_exact_call_id() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        client
            .persistence_manager()
            .process_command(crate::store::commands::DeviceCommand::SetLid(Some(
                Jid::new("111111111111111", Server::Lid).with_device(1),
            )))
            .await;
        let creator = Jid::new("333333333333333", Server::Lid);
        let sender = creator.clone().with_device(1);
        let sent = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
        let join_client = client.clone();
        let join = tokio::spawn(async move {
            join_client
                .voip()
                .join_call_link_registration_with_audio(
                    "RETRIED-CALL-LINK",
                    CallLinkMedia::Audio,
                    AudioFormat::OPUS_16KHZ_60MS,
                )
                .await
        });
        let first_request = sent.await.expect("initial link_join request");

        for index in 0..MAX_PENDING_CALL_LINK_TRANSITIONS {
            assert_eq!(
                client.buffer_pending_call_link_terminate(
                    &format!("UNRELATED-FILLED-{index}"),
                    &creator,
                    &sender,
                ),
                PendingCallLinkBuffer::Buffered
            );
        }
        let mut oversized = GroupCallUpdate::builder()
            .call_id("UNRELATED-OVERFLOW-0".to_string())
            .call_creator(creator.clone())
            .transaction_id(1)
            .media("audio".to_string())
            .connected_limit(32)
            .joinable(true)
            .av_upgradable(true)
            .rekey_requested(false)
            .participants(vec![GroupCallParticipant::new(
                creator.clone(),
                vec![
                    GroupCallDevice::new(sender.clone())
                        .with_capability(1, vec![7; MAX_PENDING_CALL_LINK_TRANSITION_BYTES]),
                ],
            )])
            .build();
        for index in 0..=MAX_PENDING_CALL_LINK_SATURATION_FINGERPRINTS {
            oversized.call_id = format!("UNRELATED-OVERFLOW-{index}");
            assert_eq!(
                client.buffer_pending_call_link_update(&oversized, &sender),
                PendingCallLinkBuffer::Saturated
            );
        }

        let first_request_id = first_request
            .as_node_ref()
            .attrs()
            .optional_string("id")
            .expect("initial request id")
            .into_owned();
        let refreshed_sent = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
        crate::test_utils::answer_iq(
            &client,
            &first_request_id,
            &NodeBuilder::new("ack")
                .attr("class", "call")
                .attr("type", "link_join")
                .attr("id", first_request_id.as_str())
                .children([NodeBuilder::new("waiting_room")
                    .attr("call-id", "RETRIED-CALL-ID")
                    .attr("call-creator", creator.clone())
                    .attr("link-token", "RETRIED-CALL-LINK")
                    .attr("media", "audio")
                    .attr("enabled", "1")
                    .attr("is_admin", "0")
                    .attr("transaction-id", "1")
                    .build()])
                .build(),
        )
        .await;
        let refreshed_request = refreshed_sent.await.expect("refreshed link_join request");
        assert_eq!(
            refreshed_request
                .as_node_ref()
                .children()
                .expect("refreshed request action")[0]
                .tag,
            "link_join"
        );
        let refreshed_request_id = refreshed_request
            .as_node_ref()
            .attrs()
            .optional_string("id")
            .expect("refreshed request id")
            .into_owned();
        crate::test_utils::answer_iq(
            &client,
            &refreshed_request_id,
            &NodeBuilder::new("ack")
                .attr("class", "call")
                .attr("type", "link_join")
                .attr("id", refreshed_request_id.as_str())
                .children([NodeBuilder::new("waiting_room")
                    .attr("call-id", "RETRIED-CALL-ID")
                    .attr("call-creator", creator)
                    .attr("link-token", "RETRIED-CALL-LINK")
                    .attr("media", "audio")
                    .attr("enabled", "1")
                    .attr("is_admin", "0")
                    .attr("transaction-id", "2")
                    .build()])
                .build(),
        )
        .await;
        let registration = join
            .await
            .expect("join task")
            .expect("an unrelated overflow must recover through the bound retry");
        assert_eq!(registration.join.call_id, "RETRIED-CALL-ID");
        assert!(
            client
                .call_registry()
                .is_current("RETRIED-CALL-ID", registration.generation)
        );
        client
            .call_registry()
            .remove_if_current("RETRIED-CALL-ID", registration.generation);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn call_link_ack_paths_bind_before_waking_the_waiter() {
        for owned_fast_path in [false, true] {
            let (client, _transport) = crate::test_utils::create_iq_test_client().await;
            let unrelated_creator = Jid::new("333333333333333", Server::Lid);
            let unrelated_sender = unrelated_creator.clone().with_device(1);
            let _pending = client.begin_call_link_join();
            assert_eq!(
                client.buffer_pending_call_link_terminate(
                    "UNRELATED-CALL-LINK",
                    &unrelated_creator,
                    &unrelated_sender,
                ),
                PendingCallLinkBuffer::Buffered
            );

            let request_id = if owned_fast_path {
                "OWNED-LINK-JOIN-ACK"
            } else {
                "SHARED-LINK-JOIN-ACK"
            };
            let (sender, receiver) = futures::channel::oneshot::channel();
            client
                .response_waiters_guard()
                .insert(request_id.to_string(), ResponseWaiter::Iq(sender));
            let ack = NodeBuilder::new("ack")
                .attr("id", request_id)
                .attr("class", "call")
                .attr("type", "link_join")
                .children([NodeBuilder::new("waiting_room")
                    .attr("call-id", "ACTUAL-CALL-LINK")
                    .build()])
                .build();
            let node = crate::test_utils::node_to_owned_ref(&ack);
            let handled = if owned_fast_path {
                let node = Arc::try_unwrap(node)
                    .unwrap_or_else(|_| panic!("the test owns the ACK allocation"));
                client.handle_ack_response_owned(node)
            } else {
                client.handle_ack_response_arc(&node)
            };
            assert!(handled, "the ACK must resolve its registered waiter");
            assert_eq!(
                client
                    .memory_report()
                    .await
                    .pending_call_link_updates
                    .entries,
                0,
                "the ACK call id must be bound before the waiter can observe the response"
            );
            assert_eq!(
                client.buffer_pending_call_link_terminate(
                    "LATE-UNRELATED-CALL",
                    &unrelated_creator,
                    &unrelated_sender,
                ),
                PendingCallLinkBuffer::NotPending,
                "later unrelated controls cannot consume the bound join's budget"
            );
            let response = receiver.await.expect("the ACK waiter should be woken");
            assert!(
                response
                    .get()
                    .get_attr("id")
                    .is_some_and(|value| value.as_str() == request_id)
            );
        }
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn call_link_registration_replays_staged_transitions_in_order() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let creator = Jid::new("333333333333333", Server::Lid);
        let call_id = "ORDERED-CALL-LINK";
        let local_device = Jid::new("111111111111111", Server::Lid).with_device(1);
        let mut participant = GroupCallParticipant::new(
            local_device.to_non_ad(),
            vec![GroupCallDevice::new(local_device.clone())],
        );
        participant.state = Some("connected".to_string());
        let relay = GroupCallRelay::builder()
            .transaction_id(8)
            .self_pid(1)
            .uuid("TEST-RELAY".to_string())
            .participant_uuid("TEST-PARTICIPANT".to_string())
            .attribute_padding(false)
            .warp_mi_tag_len(4)
            .key(vec![7; 32])
            .tokens(vec![vec![9; 16]])
            .endpoints(vec![
                GroupCallRelayEndpoint::builder()
                    .relay_id(1)
                    .token_id(0)
                    .auth_token_id(0)
                    .relay_name("test-relay".to_string())
                    .is_fna(false)
                    .ipv4("203.0.113.7".to_string())
                    .port(3478)
                    .build(),
            ])
            .build();
        let first = GroupCallUpdate::builder()
            .call_id(call_id.to_string())
            .call_creator(creator.clone())
            .transaction_id(8)
            .media("audio".to_string())
            .connected_limit(32)
            .joinable(true)
            .av_upgradable(true)
            .rekey_requested(true)
            .participants(vec![participant.clone()])
            .relay(relay)
            .build();
        let second = GroupCallUpdate::builder()
            .call_id(call_id.to_string())
            .call_creator(creator.clone())
            .transaction_id(9)
            .media("audio".to_string())
            .connected_limit(32)
            .joinable(true)
            .av_upgradable(true)
            .rekey_requested(false)
            .participants(vec![participant])
            .build();
        let initial_room = WaitingRoom::builder()
            .call_id(call_id.to_string())
            .call_creator(creator.clone())
            .link_token("TEST-CALL-LINK".to_string())
            .media(CallLinkMedia::Audio)
            .enabled(true)
            .is_admin(false)
            .transaction_id(1)
            .users(Vec::new())
            .build();
        let newer_room = WaitingRoom::builder()
            .call_id(call_id.to_string())
            .call_creator(creator.clone())
            .link_token("TEST-CALL-LINK".to_string())
            .media(CallLinkMedia::Audio)
            .enabled(true)
            .is_admin(true)
            .transaction_id(2)
            .users(Vec::new())
            .build();

        let pending = client.begin_call_link_join();
        let sender = creator.clone().with_device(1);
        assert_eq!(
            client.buffer_pending_call_link_update(&first, &sender),
            PendingCallLinkBuffer::Buffered
        );
        assert_eq!(
            client.buffer_pending_call_link_waiting_room(&newer_room, &sender),
            PendingCallLinkBuffer::Buffered
        );
        assert_eq!(
            client.buffer_pending_call_link_update(&second, &sender),
            PendingCallLinkBuffer::Buffered
        );
        assert_eq!(
            client
                .memory_report()
                .await
                .pending_call_link_updates
                .entries,
            3
        );

        let mut session =
            CallSession::new_outgoing(call_id, Jid::new(call_id, Server::Call), creator);
        let _ = session.transition_to(CallPhase::Calling);
        let _ = session.transition_to(CallPhase::WaitingRoom);
        let registration_lane = client.lock_answer_transition(call_id).await;
        let register_client = client.clone();
        let registration = tokio::spawn(async move {
            register_client
                .register_call_link_session(
                    session,
                    Some(initial_room),
                    CallLinkMedia::Audio,
                    "TEST-CALL-LINK",
                )
                .await
        });
        tokio::task::yield_now().await;
        assert_eq!(
            client.call_registry().generation_of(call_id),
            None,
            "call-link insertion must share the call-id registration lane"
        );
        drop(registration_lane);
        let generation = registration
            .await
            .expect("registration task")
            .expect("valid staged transitions");
        assert!(client.call_registry().set_group_invite_self_device(
            call_id,
            generation,
            GroupCallDevice::new(local_device).with_capability(1, [1]),
        ));
        let state = client
            .call_registry()
            .group_state_if_current(call_id, generation)
            .expect("registered group state");
        let snapshot = state.snapshot().expect("latest admission roster");
        assert_eq!(snapshot.transaction_id, 9);
        assert!(snapshot.relay.is_some(), "roster-only update retains relay");
        assert!(
            snapshot.rekey_requested,
            "the earlier unfulfilled rekey obligation survives the roster-only update"
        );
        assert!(
            state
                .waiting_room()
                .is_some_and(|room| room.transaction_id == Some(2) && room.is_admin)
        );
        assert_eq!(
            client.call_registry().phase_if_current(call_id, generation),
            Some(CallPhase::Connecting)
        );
        assert_eq!(
            client
                .memory_report()
                .await
                .pending_call_link_updates
                .entries,
            0
        );

        drop(pending);
        client
            .call_registry()
            .remove_if_current(call_id, generation);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn call_link_rekey_targets_the_latest_post_registration_roster() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let own_lid = Jid::new("111111111111111", Server::Lid).with_device(1);
        client
            .persistence_manager()
            .process_command(crate::store::commands::DeviceCommand::SetLid(Some(
                own_lid.clone(),
            )))
            .await;
        let creator = Jid::new("333333333333333", Server::Lid);
        let call_id = "POST-REGISTRATION-REKEY";
        let mut participant =
            GroupCallParticipant::new(own_lid.to_non_ad(), vec![GroupCallDevice::new(own_lid)]);
        participant.state = Some("connected".to_string());
        let initial = GroupCallUpdate::builder()
            .call_id(call_id.to_string())
            .call_creator(creator.clone())
            .transaction_id(1)
            .media("audio".to_string())
            .connected_limit(32)
            .joinable(true)
            .av_upgradable(true)
            .rekey_requested(true)
            .participants(vec![participant.clone()])
            .build();
        let mut session =
            CallSession::new_outgoing(call_id, Jid::new(call_id, Server::Call), creator.clone());
        session.group = Some(initial.clone());
        let _ = session.transition_to(CallPhase::Calling);
        let _ = session.transition_to(CallPhase::Connecting);
        let generation = client
            .register_call_link_session(session, None, CallLinkMedia::Audio, "TEST-CALL-LINK")
            .await
            .expect("registered admitted call link");

        let mut current = initial.clone();
        current.transaction_id = 2;
        current.rekey_requested = false;
        assert_eq!(
            client
                .call_registry()
                .apply_group_update_if_current(current, generation),
            wacore::voip::GroupStateApply::Applied
        );
        let mut join = wacore::types::group_call::CallLinkJoin::builder()
            .token("TEST-CALL-LINK".to_string())
            .media(CallLinkMedia::Audio)
            .call_id(call_id.to_string())
            .call_creator(creator)
            .waiting_room_enabled(false)
            .in_waiting_room(false)
            .is_admin(false)
            .group(initial)
            .build();

        assert!(
            !client
                .voip()
                .synchronize_call_link_admission(&mut join, generation, true)
                .await
                .expect("latest admission state")
        );
        assert_eq!(
            join.group.as_ref().map(|update| update.transaction_id),
            Some(2)
        );
        assert_eq!(
            client
                .call_registry()
                .pending_group_epoch_transaction_if_current(call_id, generation),
            Some(2),
            "the ACK rekey obligation must publish against the latest serialized roster"
        );
        client
            .call_registry()
            .remove_if_current(call_id, generation);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn invalid_admitted_call_link_snapshot_is_not_registered() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let creator = Jid::new("333333333333333", Server::Lid);
        let call_id = "INVALID-CALL-LINK";
        let mut invalid = GroupCallUpdate::builder()
            .call_id(call_id.to_string())
            .call_creator(creator.clone())
            .transaction_id(1)
            .media("audio".to_string())
            .connected_limit(32)
            .joinable(true)
            .av_upgradable(true)
            .rekey_requested(false)
            .participants(Vec::new())
            .build();
        invalid.connected_limit = 0;
        let mut session =
            CallSession::new_outgoing(call_id, Jid::new(call_id, Server::Call), creator);
        session.group = Some(invalid);

        assert_eq!(
            client
                .register_call_link_session(session, None, CallLinkMedia::Audio, "TEST-CALL-LINK",)
                .await,
            Err(wacore::voip::GroupStateApply::InvalidSnapshot)
        );
        assert_eq!(client.call_registry().generation_of(call_id), None);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn buffered_call_link_admission_cannot_cross_generations() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let creator = Jid::new("333333333333333", Server::Lid);
        let call_id = "BUFFERED-ADMISSION-GENERATION";
        let mut participant = GroupCallParticipant::new(
            creator.clone(),
            vec![GroupCallDevice::new(creator.clone().with_device(1))],
        );
        participant.state = Some("connected".to_string());
        let update = GroupCallUpdate::builder()
            .call_id(call_id.to_string())
            .call_creator(creator.clone())
            .transaction_id(8)
            .media("audio".to_string())
            .connected_limit(32)
            .joinable(true)
            .av_upgradable(true)
            .rekey_requested(false)
            .participants(vec![participant])
            .build();

        let registry = client.call_registry();
        let stale = registry.insert(CallSession::new_outgoing(
            call_id,
            Jid::new(call_id, Server::Call),
            creator.clone(),
        ));
        let replacement = registry.insert(CallSession::new_outgoing(
            call_id,
            Jid::new(call_id, Server::Call),
            creator,
        ));
        assert_ne!(stale, replacement);
        assert_eq!(
            client.apply_pending_call_link_update(update, stale),
            wacore::voip::GroupStateApply::UnknownCall
        );
        assert!(
            registry
                .group_state_if_current(call_id, replacement)
                .is_none(),
            "a buffered snapshot from the joining generation must not mutate its replacement"
        );
        registry.remove_if_current(call_id, replacement);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn call_link_waiting_room_cannot_cross_generations() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let creator = Jid::new("333333333333333", Server::Lid);
        let call_id = "WAITING-ROOM-GENERATION";
        let registry = client.call_registry();
        let stale = registry.insert(CallSession::new_outgoing(
            call_id,
            Jid::new(call_id, Server::Call),
            creator.clone(),
        ));
        let replacement = registry.insert(CallSession::new_outgoing(
            call_id,
            Jid::new(call_id, Server::Call),
            creator.clone(),
        ));
        let room = WaitingRoom::builder()
            .call_id(call_id.to_string())
            .call_creator(creator)
            .link_token("TEST-CALL-LINK".to_string())
            .media(CallLinkMedia::Audio)
            .enabled(true)
            .is_admin(true)
            .transaction_id(1)
            .users(Vec::new())
            .build();

        assert_eq!(
            registry.apply_waiting_room_if_current(room, stale),
            wacore::voip::GroupStateApply::UnknownCall
        );
        assert!(
            registry
                .group_state_if_current(call_id, replacement)
                .and_then(|state| state.waiting_room().cloned())
                .is_none(),
            "a stale join cannot grant waiting-room admin state to its replacement"
        );
        registry.remove_if_current(call_id, replacement);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn early_group_invite_accept_preserves_media_attachment_generation() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let creator = call_creator();
        let call_id = "ATTACHABLE-GROUP-INVITE";
        let update = GroupCallUpdate::builder()
            .call_id(call_id.to_string())
            .call_creator(creator.clone())
            .transaction_id(1)
            .media("audio".to_string())
            .connected_limit(32)
            .joinable(true)
            .av_upgradable(true)
            .rekey_requested(false)
            .participants(Vec::new())
            .build();
        let mut incoming = IncomingCall::new_for_test(
            creator.clone(),
            "ATTACHABLE-GROUP-INVITE-STANZA".to_string(),
            wacore::time::from_secs(1_766_847_151_i64).expect("valid ts"),
            CallAction::Offer {
                call_id: call_id.to_string(),
                call_creator: creator.clone(),
                caller_pn: None,
                caller_country_code: None,
                device_class: None,
                joinable: true,
                is_video: false,
                audio: Vec::new(),
                group_jid: None,
            },
        );
        incoming.group = Some(Box::new(update.clone()));
        let mut ringing = CallSession::new_incoming(call_id, creator.clone(), creator.clone());
        ringing.group = Some(update);
        let generation = client
            .call_registry()
            .insert_ringing_group_if_inactive(ringing)
            .expect("valid group snapshot")
            .expect("ringing invitation");
        incoming.set_ringing_generation(generation);

        client
            .voip()
            .accept_group_invite(&incoming)
            .await
            .expect("early group invitation accept");

        assert_eq!(
            client
                .call_registry()
                .ringing_group_generation(call_id, &creator),
            Some(generation),
            "the media accept builder must still be able to claim the exact ringing generation"
        );
        assert_eq!(
            client.call_registry().phase_if_current(call_id, generation),
            Some(CallPhase::Ringing)
        );
        assert!(client.call_registry().take_ringing(call_id));
        client
            .call_registry()
            .remove_if_current(call_id, generation);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn group_invite_preaccept_and_accept_are_bound_to_the_retained_offer_generation() {
        let client = crate::test_utils::create_test_client().await;
        let retained_creator = call_creator();
        let replacement_creator = retained_creator.clone();
        let call_id = "REPLACED-GROUP-INVITE";
        let group_update = |creator: &Jid| {
            GroupCallUpdate::builder()
                .call_id(call_id.to_string())
                .call_creator(creator.clone())
                .transaction_id(1)
                .media("audio".to_string())
                .connected_limit(32)
                .joinable(true)
                .av_upgradable(true)
                .rekey_requested(false)
                .participants(Vec::new())
                .build()
        };
        let retained_update = group_update(&retained_creator);
        let mut incoming = IncomingCall::new_for_test(
            retained_creator.clone(),
            "RETAINED-GROUP-INVITE".to_string(),
            wacore::time::from_secs(1_766_847_151_i64).expect("valid ts"),
            CallAction::Offer {
                call_id: call_id.to_string(),
                call_creator: retained_creator.clone(),
                caller_pn: None,
                caller_country_code: None,
                device_class: None,
                joinable: true,
                is_video: false,
                audio: Vec::new(),
                group_jid: None,
            },
        );
        incoming.group = Some(Box::new(retained_update.clone()));
        let mut retained =
            CallSession::new_incoming(call_id, retained_creator.clone(), retained_creator);
        retained.group = Some(retained_update);
        let stale = client.call_registry().insert_ringing_group(retained);
        incoming.set_ringing_generation(stale);

        let replacement_update = group_update(&replacement_creator);
        let mut replacement =
            CallSession::new_incoming(call_id, replacement_creator.clone(), replacement_creator);
        replacement.group = Some(replacement_update);
        let current = client.call_registry().insert_ringing_group(replacement);

        assert!(matches!(
            client.voip().preaccept_group_invite(&incoming).await,
            Err(CallError::CallEndedDuringSetup)
        ));
        assert!(matches!(
            client.voip().accept_group_invite(&incoming).await,
            Err(CallError::CallEndedDuringSetup)
        ));
        assert_eq!(client.call_registry().generation_of(call_id), Some(current));
        assert_eq!(
            client.call_registry().phase_if_current(call_id, current),
            Some(CallPhase::Ringing)
        );
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn group_invite_accept_does_not_consume_a_replacement_generation() {
        struct GatedTransport {
            started: async_channel::Sender<()>,
            release: async_channel::Receiver<()>,
        }

        #[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
        #[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
        impl crate::transport::Transport for GatedTransport {
            async fn send(&self, _data: Bytes) -> Result<(), anyhow::Error> {
                let _ = self.started.try_send(());
                self.release.recv().await?;
                Ok(())
            }

            async fn disconnect(&self) {}
        }

        let client = crate::test_utils::create_test_client().await;
        let creator = call_creator();
        let call_id = "ACTIVE-GROUP-INVITE";
        let update = GroupCallUpdate::builder()
            .call_id(call_id.to_string())
            .call_creator(creator.clone())
            .transaction_id(1)
            .media("audio".to_string())
            .connected_limit(32)
            .joinable(true)
            .av_upgradable(true)
            .rekey_requested(false)
            .participants(Vec::new())
            .build();
        let mut incoming = IncomingCall::new_for_test(
            creator.clone(),
            "GROUP-INVITE-STANZA".to_string(),
            wacore::time::from_secs(1_766_847_151_i64).expect("valid ts"),
            CallAction::Offer {
                call_id: call_id.to_string(),
                call_creator: creator.clone(),
                caller_pn: None,
                caller_country_code: None,
                device_class: None,
                joinable: true,
                is_video: false,
                audio: Vec::new(),
                group_jid: None,
            },
        );
        incoming.group = Some(Box::new(update.clone()));
        let mut ringing = CallSession::new_incoming(call_id, creator.clone(), creator.clone());
        ringing.group = Some(update.clone());
        let stale = client
            .call_registry()
            .insert_ringing_group_if_inactive(ringing)
            .expect("valid group snapshot")
            .expect("ringing invitation");
        incoming.set_ringing_generation(stale);

        let (started_tx, started_rx) = async_channel::bounded(1);
        let (release_tx, release_rx) = async_channel::bounded(1);
        let noise_socket = crate::socket::NoiseSocket::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            Arc::new(GatedTransport {
                started: started_tx,
                release: release_rx,
            }),
            NoiseCipher::new(&[0u8; 32]).expect("valid key"),
            NoiseCipher::new(&[0u8; 32]).expect("valid key"),
        );
        *client.noise_socket.lock().await = Some(Arc::new(noise_socket));

        let accept = tokio::spawn({
            let client = client.clone();
            let incoming = incoming.clone();
            async move { client.voip().accept_group_invite(&incoming).await }
        });
        started_rx.recv().await.expect("accept send entered");
        let mut replacement = CallSession::new_incoming(call_id, creator.clone(), creator);
        replacement.group = Some(update);
        let current = client.call_registry().insert_ringing_group(replacement);
        assert_ne!(current, stale);
        release_tx.send(()).await.expect("release accept send");

        assert!(matches!(
            accept.await.expect("accept task"),
            Err(CallError::CallEndedDuringSetup)
        ));
        assert_eq!(client.call_registry().generation_of(call_id), Some(current));
        assert_eq!(
            client.call_registry().phase_if_current(call_id, current),
            Some(CallPhase::Ringing)
        );
        assert!(
            client.call_registry().take_ringing(call_id),
            "the stale accept must leave the replacement ringing"
        );
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn cancelling_call_link_request_removes_response_waiter() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let sent = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
        let request_client = client.clone();
        let request = tokio::spawn(async move {
            request_client
                .voip()
                .create_call_link(CallLinkMedia::Audio)
                .await
        });
        let node = sent.await.expect("link_create request");
        let request_id = node
            .as_node_ref()
            .attrs()
            .optional_string("id")
            .expect("request id")
            .into_owned();
        assert!(
            client.response_waiters_guard().contains_key(&request_id),
            "the request must register its ACK waiter before sending"
        );

        request.abort();
        assert!(
            request
                .await
                .expect_err("request should be cancelled")
                .is_cancelled()
        );
        tokio::task::yield_now().await;
        assert!(
            !client.response_waiters_guard().contains_key(&request_id),
            "cancelling a call-service request must not leak its waiter"
        );
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn cancelling_registered_call_link_join_removes_its_generation() {
        use wacore::handshake::NoiseCipher;

        struct BlockingTransport {
            started: async_channel::Sender<()>,
        }

        #[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
        #[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
        impl crate::transport::Transport for BlockingTransport {
            async fn send(&self, _data: Bytes) -> Result<(), anyhow::Error> {
                let _ = self.started.try_send(());
                futures::future::pending().await
            }

            async fn disconnect(&self) {}
        }

        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        client
            .persistence_manager()
            .process_command(crate::store::commands::DeviceCommand::SetLid(Some(
                Jid::new("111111111111111", Server::Lid).with_device(1),
            )))
            .await;
        let creator = Jid::new("333333333333333", Server::Lid);
        let join_sent = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
        let join_client = client.clone();
        let join = tokio::spawn(async move {
            join_client
                .voip()
                .join_call_link_with_audio(
                    "CANCELLED-CALL-LINK",
                    CallLinkMedia::Audio,
                    AudioFormat::OPUS_16KHZ_60MS,
                )
                .await
        });
        let request = join_sent.await.expect("link_join request");
        let request_id = request
            .as_node_ref()
            .attrs()
            .optional_string("id")
            .expect("request id")
            .into_owned();
        let (started_tx, started_rx) = async_channel::bounded(1);
        let blocking_socket = crate::socket::NoiseSocket::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            Arc::new(BlockingTransport {
                started: started_tx,
            }),
            NoiseCipher::new(&[0u8; 32]).expect("valid key"),
            NoiseCipher::new(&[0u8; 32]).expect("valid key"),
        );
        *client.noise_socket.lock().await = Some(Arc::new(blocking_socket));
        crate::test_utils::answer_iq(
            &client,
            &request_id,
            &NodeBuilder::new("ack")
                .attr("class", "call")
                .attr("type", "link_join")
                .attr("id", request_id.as_str())
                .children([NodeBuilder::new("waiting_room")
                    .attr("call-id", "CANCELLED-CALL-ID")
                    .attr("call-creator", creator)
                    .attr("link-token", "CANCELLED-CALL-LINK")
                    .attr("media", "audio")
                    .attr("enabled", "1")
                    .attr("is_admin", "0")
                    .attr("transaction-id", "1")
                    .build()])
                .build(),
        )
        .await;
        started_rx.recv().await.expect("heartbeat send must start");
        assert!(
            client
                .call_registry()
                .generation_of("CANCELLED-CALL-ID")
                .is_some(),
            "the join must register before its heartbeat completes"
        );

        join.abort();
        assert!(
            join.await
                .expect_err("join should be cancelled")
                .is_cancelled()
        );
        tokio::task::yield_now().await;
        assert_eq!(
            client.call_registry().generation_of("CANCELLED-CALL-ID"),
            None,
            "cancelling after registration must reap only that generation"
        );
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn cancelling_an_admitted_call_link_registration_sends_terminate() {
        let (client, sends) = make_client_with_count().await;
        let call_id = "CANCELLED-ADMITTED-CALL";
        let creator = Jid::new("333333333333333", Server::Lid);
        let mut session =
            CallSession::new_outgoing(call_id, Jid::new(call_id, Server::Call), creator.clone());
        let _ = session.transition_to(CallPhase::Calling);
        let _ = session.transition_to(CallPhase::Connecting);
        let registry = client.call_registry();
        let generation = registry.insert(session);
        let registration = super::CallLinkRegistrationGuard::new(
            &client,
            registry.clone(),
            call_id,
            creator,
            generation,
        );

        drop(registration);

        tokio::time::timeout(Duration::from_secs(2), async {
            while sends.load(Ordering::SeqCst) == 0 {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("admitted cancellation must send a call-scoped terminate");
        assert_eq!(sends.load(Ordering::SeqCst), 1);
        assert_eq!(registry.generation_of(call_id), None);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn call_link_join_reports_admission_committed_during_heartbeat() {
        use wacore::handshake::NoiseCipher;

        struct GatedTransport {
            started: async_channel::Sender<()>,
            release: async_channel::Receiver<()>,
        }

        #[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
        #[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
        impl crate::transport::Transport for GatedTransport {
            async fn send(&self, _data: Bytes) -> Result<(), anyhow::Error> {
                self.started
                    .send(())
                    .await
                    .map_err(|_| anyhow::anyhow!("heartbeat observer closed"))?;
                self.release
                    .recv()
                    .await
                    .map_err(|_| anyhow::anyhow!("heartbeat gate closed"))?;
                Ok(())
            }

            async fn disconnect(&self) {}
        }

        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        let own_lid = Jid::new("111111111111111", Server::Lid).with_device(1);
        client
            .persistence_manager()
            .process_command(crate::store::commands::DeviceCommand::SetLid(Some(
                own_lid.clone(),
            )))
            .await;
        let creator = Jid::new("333333333333333", Server::Lid);
        let sent = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
        let join_client = client.clone();
        let join = tokio::spawn(async move {
            join_client
                .voip()
                .join_call_link_registration_with_audio(
                    "ADMISSION-RACE-LINK",
                    CallLinkMedia::Audio,
                    AudioFormat::OPUS_16KHZ_60MS,
                )
                .await
        });
        let request = sent.await.expect("link_join request");
        let request_id = request
            .as_node_ref()
            .attrs()
            .optional_string("id")
            .expect("request id")
            .into_owned();
        let (started_tx, started_rx) = async_channel::bounded(1);
        let (release_tx, release_rx) = async_channel::bounded(1);
        let gated_socket = crate::socket::NoiseSocket::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            Arc::new(GatedTransport {
                started: started_tx,
                release: release_rx,
            }),
            NoiseCipher::new(&[0u8; 32]).expect("valid key"),
            NoiseCipher::new(&[0u8; 32]).expect("valid key"),
        );
        *client.noise_socket.lock().await = Some(Arc::new(gated_socket));
        crate::test_utils::answer_iq(
            &client,
            &request_id,
            &NodeBuilder::new("ack")
                .attr("class", "call")
                .attr("type", "link_join")
                .attr("id", request_id.as_str())
                .children([NodeBuilder::new("waiting_room")
                    .attr("call-id", "ADMISSION-RACE-CALL")
                    .attr("call-creator", creator.clone())
                    .attr("link-token", "ADMISSION-RACE-LINK")
                    .attr("media", "audio")
                    .attr("enabled", "1")
                    .attr("is_admin", "0")
                    .attr("transaction-id", "1")
                    .build()])
                .build(),
        )
        .await;
        started_rx.recv().await.expect("heartbeat send started");

        let registry = client.call_registry();
        let generation = registry
            .generation_of("ADMISSION-RACE-CALL")
            .expect("registered waiting-room generation");
        let mut participant =
            GroupCallParticipant::new(own_lid.to_non_ad(), vec![GroupCallDevice::new(own_lid)]);
        participant.state = Some("connected".to_string());
        let admitted = GroupCallUpdate::builder()
            .call_id("ADMISSION-RACE-CALL".to_string())
            .call_creator(creator)
            .transaction_id(2)
            .media("audio".to_string())
            .connected_limit(32)
            .joinable(true)
            .av_upgradable(true)
            .rekey_requested(false)
            .participants(vec![participant])
            .build();
        let transition_lock = registry
            .group_transition_lock("ADMISSION-RACE-CALL", generation)
            .expect("group transition lane");
        let transition_guard = transition_lock.lock().await;
        assert_eq!(
            registry.apply_group_update_if_current(admitted, generation),
            wacore::voip::GroupStateApply::Applied
        );
        assert_eq!(
            registry.phase_if_current("ADMISSION-RACE-CALL", generation),
            Some(CallPhase::Connecting)
        );
        drop(transition_guard);
        release_tx.send(()).await.expect("release heartbeat send");

        let registration = join.await.expect("join task").expect("join response");
        assert_eq!(registration.generation, generation);
        assert!(!registration.join.in_waiting_room);
        assert_eq!(
            registration
                .join
                .group
                .as_ref()
                .map(|update| update.transaction_id),
            Some(2),
            "the public result must report admission committed during the heartbeat"
        );
        registry.remove_if_current("ADMISSION-RACE-CALL", generation);
    }

    #[cfg(feature = "voip-runtime")]
    #[tokio::test]
    async fn immediately_admitted_call_link_preserves_token_and_origin_generation() {
        let (client, _transport) = crate::test_utils::create_iq_test_client().await;
        client
            .persistence_manager()
            .process_command(crate::store::commands::DeviceCommand::SetLid(Some(
                Jid::new("111111111111111", Server::Lid).with_device(1),
            )))
            .await;
        let creator = Jid::new("333333333333333", Server::Lid);
        let sent = client.wait_for_sent_node(crate::client::NodeFilter::tag("call"));
        let join_client = client.clone();
        let join = tokio::spawn(async move {
            join_client
                .voip()
                .join_call_link_registration_with_audio(
                    "REQUESTED-CALL-LINK",
                    CallLinkMedia::Video,
                    AudioFormat::OPUS_16KHZ_60MS,
                )
                .await
        });
        let request = sent.await.expect("link_join request");
        let request_id = request
            .as_node_ref()
            .attrs()
            .optional_string("id")
            .expect("request id")
            .into_owned();
        crate::test_utils::answer_iq(
            &client,
            &request_id,
            &NodeBuilder::new("ack")
                .attr("class", "call")
                .attr("type", "link_join")
                .attr("id", request_id.as_str())
                .children([
                    NodeBuilder::new("waiting_room")
                        .attr("call-id", "ADMITTED-CALL-ID")
                        .attr("call-creator", creator.clone())
                        .attr("link-token", "REQUESTED-CALL-LINK")
                        .attr("media", "video")
                        .attr("enabled", "1")
                        .attr("is_admin", "1")
                        .attr("transaction-id", "1")
                        .build(),
                    NodeBuilder::new("group_info")
                        .attr("call-id", "ADMITTED-CALL-ID")
                        .attr("call-creator", creator)
                        .attr("transaction-id", "1")
                        .attr("connected-limit", "32")
                        .attr("media", "video")
                        .build(),
                ])
                .build(),
        )
        .await;

        let admitted_registration = join.await.expect("join task").expect("join response");
        let admitted = admitted_registration.join;
        assert_eq!(admitted.token, "REQUESTED-CALL-LINK");
        assert!(!admitted.in_waiting_room);
        let generation = client
            .call_registry()
            .generation_of("ADMITTED-CALL-ID")
            .expect("registered admitted call");
        assert_eq!(
            admitted_registration.generation, generation,
            "the join result must retain the generation it created"
        );
        assert!(
            client
                .call_registry()
                .group_state("ADMITTED-CALL-ID")
                .and_then(|state| state.waiting_room().cloned())
                .is_some_and(|room| room.is_admin && room.enabled),
            "admitted joins must retain waiting-room admin state from the ACK"
        );
        let replacement = client.call_registry().insert(CallSession::new_outgoing(
            "ADMITTED-CALL-ID",
            Jid::new("ADMITTED-CALL-ID", Server::Call),
            Jid::new("333333333333333", Server::Lid),
        ));
        assert_ne!(replacement, admitted_registration.generation);
        assert!(
            client
                .call_registry()
                .snapshot_if_current("ADMITTED-CALL-ID", admitted_registration.generation)
                .is_none(),
            "a stale starter must not attach through a replacement generation"
        );
        client
            .call_registry()
            .remove_if_current("ADMITTED-CALL-ID", replacement);
    }
}