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
use crate::client::Client;
use crate::types::events::{Event, Receipt};
use crate::types::message::MessageInfo;
use crate::types::presence::ReceiptType;
use log::debug;
use std::sync::Arc;
use wacore::protocol::nack::NackReason;
use wacore::types::message::MessageCategory;
use wacore_binary::builder::NodeBuilder;
use wacore_binary::{Jid, JidExt as _, NodeRef, NodeValue};

use wacore_binary::OwnedNodeRef;

/// Max message ids per read/played `<receipt>` stanza. WA Web's
/// `sendAggregateReceipts` splices ids into chunks of 256 and emits one receipt
/// per chunk, so a large catch-up doesn't produce one oversized stanza.
const MAX_RECEIPT_IDS_PER_STANZA: usize = 256;

/// Pure builder for the delivery `<receipt>` node. Extracted so unit tests
/// can assert wire shape without spinning a transport. Mirrors WA Web's
/// `Send/DeliveryReceiptJob.js` — the participant gate there is
/// `(t.isGroup() || t.isBroadcast()) && r ? DEVICE_JID(r) : DROP_ATTR`, so
/// status broadcasts (isBroadcast = true) also carry the original poster's
/// JID. Without it the server can't map the ack back to the status owner.
/// `active=false` sends `type="inactive"` (not rendered as ticks), matching
/// whatsmeow's background companion. Peer/status keep their own type/context.
///
/// Self-fanout (`is_from_me` + a `recipient`) gets `type="sender"` + the
/// `recipient`, matching WA Web (`isMeAccount` author => SENDER) and whatsmeow.
/// The server's offline queue only drops a self-fanout on this sender receipt;
/// a bare transport `<ack>` is ignored and the stanza is replayed until a
/// ~50min GC closes the stream.
/// Builds a `<receipt type="played"|"played-self">` for voice/video notes,
/// mirroring WA Web `WAWebSendPlayedReceiptJob`: newsletters use `played-self`,
/// everything else `played`. The `participant` attr is set only for
/// group/broadcast chats; in DMs WA Web drops it (`r.isUser() ? null : author`).
/// `read_receipts_disabled` is the `readreceipts==none` privacy gate: only a DM
/// (not group, status, or broadcast list) then uses `played-self` (does not
/// notify the sender), matching WA Web `PlayedReceiptJob.js`.
fn build_played_receipt_node(
    chat: &Jid,
    sender: Option<&Jid>,
    message_ids: &[&str],
    timestamp: &str,
    read_receipts_disabled: bool,
) -> wacore_binary::Node {
    let is_private_dm =
        !chat.is_group() && !chat.is_status_broadcast() && !chat.is_broadcast_list();
    let receipt_type = if chat.is_newsletter() || (read_receipts_disabled && is_private_dm) {
        ReceiptType::PlayedSelf
    } else {
        ReceiptType::Played
    };

    let mut builder = NodeBuilder::new("receipt")
        .attr("to", chat)
        .attr("type", receipt_type.as_wire_str())
        .attr("id", message_ids[0])
        .attr("t", timestamp);

    if (chat.is_group() || chat.is_status_broadcast() || chat.is_broadcast_list())
        && let Some(sender) = sender
    {
        builder = builder.attr("participant", sender);
    }

    if message_ids.len() > 1 {
        let items: Vec<wacore_binary::Node> = message_ids[1..]
            .iter()
            .map(|id| NodeBuilder::new("item").attr("id", *id).build())
            .collect();
        builder = builder.children(vec![NodeBuilder::new("list").children(items).build()]);
    }

    builder.build()
}

/// Pure builder for the read `<receipt>` node. Mirrors WA Web
/// `WAWebSendReadReceiptJob` + `sendAggregateReceipts`: newsletters use
/// `read-self`, everything else `read`; status reads carry `context="status"`
/// and, for a LID author, `peer_participant_pn` (the resolved LID->PN).
/// `read_receipts_disabled` is the `readreceipts==none` privacy gate: only a DM
/// (not group, status, or broadcast list) then uses `read-self` (does not notify
/// the sender), matching WA Web `ReadReceiptJob.js`.
fn build_read_receipt_node(
    chat: &Jid,
    sender: Option<&Jid>,
    message_ids: &[&str],
    timestamp: &str,
    peer_participant_pn: Option<&Jid>,
    read_receipts_disabled: bool,
) -> wacore_binary::Node {
    let is_private_dm =
        !chat.is_group() && !chat.is_status_broadcast() && !chat.is_broadcast_list();
    let receipt_type = if chat.is_newsletter() || (read_receipts_disabled && is_private_dm) {
        ReceiptType::ReadSelf
    } else {
        ReceiptType::Read
    };

    let mut builder = NodeBuilder::new("receipt")
        .attr("to", chat)
        .attr("type", receipt_type.as_wire_str())
        .attr("id", message_ids[0])
        .attr("t", timestamp);

    if let Some(sender) = sender {
        builder = builder.attr("participant", sender);
    }

    if chat.is_status_broadcast() {
        builder = builder.attr("context", "status");
        if let Some(pn) = peer_participant_pn {
            builder = builder.attr("peer_participant_pn", pn);
        }
    }

    if message_ids.len() > 1 {
        let items: Vec<wacore_binary::Node> = message_ids[1..]
            .iter()
            .map(|id| NodeBuilder::new("item").attr("id", *id).build())
            .collect();
        builder = builder.children(vec![NodeBuilder::new("list").children(items).build()]);
    }

    builder.build()
}

/// The `type` attr a delivery receipt carries for `info`, as a static wire
/// string (`None` = plain delivered, which omits the attr). Single source of
/// truth for both the receipt builder and the aggregation grouping key, so the
/// two can't drift apart.
fn delivery_receipt_type(info: &MessageInfo, active: bool) -> Option<&'static str> {
    let is_status = info.source.chat.is_status_broadcast();
    if info.category == MessageCategory::Peer {
        Some("peer_msg")
    } else if info.source.is_self_fanout() {
        Some("sender")
    } else if !active && !is_status {
        Some("inactive")
    } else {
        None
    }
}

/// Receipt-level attrs shared by the single and aggregate delivery builders
/// (everything except `id`/`t`/the `<list>` child).
fn delivery_receipt_builder(info: &MessageInfo, active: bool) -> NodeBuilder {
    let is_status = info.source.chat.is_status_broadcast();
    // A peer-synced message takes `type="peer_msg"` and carries NO recipient
    // (WA Web `!l` guard), so the sender-receipt shape applies only off the
    // peer path.
    let sender_receipt = info.source.is_self_fanout() && info.category != MessageCategory::Peer;
    // Mirror whatsmeow `buildBaseReceipt` / WA Web `JID(extractJidFromJidWithType)`:
    // echo `from` verbatim so the device survives. `chat` strips it via to_non_ad,
    // which the LID server rejects for multi-device DMs.
    let to = if info.source.is_group || is_status {
        &info.source.chat
    } else {
        &info.source.sender
    };
    let mut builder = NodeBuilder::new("receipt").attr("to", to);

    if let Some(receipt_type) = delivery_receipt_type(info, active) {
        builder = builder.attr("type", receipt_type);
    }

    // Device-stripped recipient (WA Web `USER_JID`) so the server can route it.
    if sender_receipt && let Some(recipient) = &info.source.recipient {
        builder = builder.attr("recipient", recipient.to_non_ad());
    }

    if info.source.is_group || is_status {
        builder = builder.attr("participant", &info.source.sender);
    }

    if is_status {
        builder = builder.attr("context", "status");
    }

    builder
}

fn build_delivery_receipt_node(info: &MessageInfo, active: bool) -> wacore_binary::Node {
    delivery_receipt_builder(info, active)
        .attr("id", &info.id)
        .build()
}

/// One buffered-offline delivery group: every entry shares identical
/// receipt-level attrs, derived from the representative `rep`.
struct DeliveryReceiptGroup<'a> {
    rep: &'a MessageInfo,
    ids: Vec<&'a str>,
}

/// Group buffered offline messages so each group maps to ONE aggregate
/// `<receipt>` (WA Web `sendAggregateOfflineReceipts` groups by chat and
/// author). The key covers every input that varies the receipt-level attrs
/// for a fixed `active`: the `to` JID, the participant (group/status author),
/// the type attr, and the self-fanout recipient. Splitting more finely than
/// WA Web (e.g. on recipient device) is always wire-safe; merging across any
/// of these would corrupt the receipt. Keys are borrowed, no per-entry
/// allocation beyond the ids vec.
fn group_delivery_receipts<'a>(
    infos: &'a [Arc<MessageInfo>],
    active: bool,
) -> Vec<DeliveryReceiptGroup<'a>> {
    #[derive(PartialEq, Eq, Hash)]
    struct Key<'a> {
        to: &'a Jid,
        participant: Option<&'a Jid>,
        receipt_type: Option<&'static str>,
        recipient: Option<&'a Jid>,
    }

    let mut index: std::collections::HashMap<Key, usize> = std::collections::HashMap::new();
    let mut groups: Vec<DeliveryReceiptGroup> = Vec::new();
    for info in infos {
        let is_status = info.source.chat.is_status_broadcast();
        let is_group_like = info.source.is_group || is_status;
        let sender_receipt = info.source.is_self_fanout() && info.category != MessageCategory::Peer;
        let key = Key {
            to: if is_group_like {
                &info.source.chat
            } else {
                &info.source.sender
            },
            participant: is_group_like.then_some(&info.source.sender),
            receipt_type: delivery_receipt_type(info, active),
            recipient: if sender_receipt {
                info.source.recipient.as_ref()
            } else {
                None
            },
        };
        match index.entry(key) {
            std::collections::hash_map::Entry::Occupied(e) => {
                groups[*e.get()].ids.push(&info.id);
            }
            std::collections::hash_map::Entry::Vacant(e) => {
                e.insert(groups.len());
                groups.push(DeliveryReceiptGroup {
                    rep: info,
                    ids: vec![&info.id],
                });
            }
        }
    }
    groups
}

/// Aggregate delivery `<receipt>` nodes for one group, chunked at
/// [`MAX_RECEIPT_IDS_PER_STANZA`]: per chunk the first id is the `id` attr and
/// the rest become `<list><item id=.../></list>`, the same shape WA Web's
/// `sendAggregateReceipts` emits and `collect_simple_message_ids` parses on
/// ingest. `t` mirrors the offline aggregate path passing `unixTime()`.
fn build_aggregate_delivery_receipt_nodes(
    rep: &MessageInfo,
    ids: &[&str],
    active: bool,
    timestamp: &str,
) -> Vec<wacore_binary::Node> {
    ids.chunks(MAX_RECEIPT_IDS_PER_STANZA)
        .map(|chunk| {
            let mut builder = delivery_receipt_builder(rep, active)
                .attr("id", chunk[0])
                .attr("t", timestamp);
            if chunk.len() > 1 {
                let items: Vec<wacore_binary::Node> = chunk[1..]
                    .iter()
                    .map(|id| NodeBuilder::new("item").attr("id", *id).build())
                    .collect();
                builder = builder.children(vec![NodeBuilder::new("list").children(items).build()]);
            }
            builder.build()
        })
        .collect()
}

trait NackSource {
    fn class(&self, reason: NackReason) -> Result<&str, crate::features::StanzaResponseError>;
    fn id(&self) -> Result<NodeValue, crate::features::StanzaResponseError>;
    fn to(&self) -> Result<NodeValue, crate::features::StanzaResponseError>;
    fn participant(&self) -> Option<NodeValue>;
    fn stanza_type(&self) -> Option<NodeValue>;
}

impl NackSource for NodeRef<'_> {
    fn class(&self, reason: NackReason) -> Result<&str, crate::features::StanzaResponseError> {
        if reason == NackReason::UnrecognizedStanza
            || matches!(self.tag.as_ref(), "message" | "notification" | "receipt")
        {
            Ok(self.tag.as_ref())
        } else {
            Err(crate::features::StanzaResponseError::UnsupportedStanzaClass)
        }
    }

    fn id(&self) -> Result<NodeValue, crate::features::StanzaResponseError> {
        crate::features::required_stanza_attr(self, "id").map(|value| value.to_node_value())
    }

    fn to(&self) -> Result<NodeValue, crate::features::StanzaResponseError> {
        crate::features::required_stanza_attr(self, "from").map(|value| value.to_node_value())
    }

    fn participant(&self) -> Option<NodeValue> {
        self.get_attr("participant")
            .map(|value| value.to_node_value())
    }

    fn stanza_type(&self) -> Option<NodeValue> {
        self.get_attr("type").map(|value| value.to_node_value())
    }
}

impl NackSource for MessageInfo {
    fn class(&self, _reason: NackReason) -> Result<&str, crate::features::StanzaResponseError> {
        Ok("message")
    }

    fn id(&self) -> Result<NodeValue, crate::features::StanzaResponseError> {
        if self.id.is_empty() {
            Err(crate::features::StanzaResponseError::MissingAttribute("id"))
        } else {
            Ok(NodeValue::from(&self.id))
        }
    }

    fn to(&self) -> Result<NodeValue, crate::features::StanzaResponseError> {
        Ok(NodeValue::from(&self.source.chat))
    }

    fn participant(&self) -> Option<NodeValue> {
        (self.source.is_group || self.source.chat.is_status_broadcast())
            .then(|| NodeValue::from(&self.source.sender))
    }

    fn stanza_type(&self) -> Option<NodeValue> {
        (!self.r#type.is_empty()).then(|| NodeValue::from(&self.r#type))
    }
}

/// Build the canonical rejection for either an original stanza or parsed
/// message metadata. `failure_reason` is valid only for `InvalidProtobuf`.
fn build_nack_node<S: NackSource + ?Sized>(
    source: &S,
    own_pn: &Jid,
    reason: NackReason,
    failure_reason: Option<i32>,
) -> Result<wacore_binary::Node, crate::features::StanzaResponseError> {
    let mut builder = NodeBuilder::new("ack")
        .attr("class", source.class(reason)?)
        .attr("id", source.id()?)
        .attr("from", own_pn)
        .attr("to", source.to()?)
        .attr("error", reason.code());

    if let Some(participant) = source.participant() {
        builder = builder.attr("participant", participant);
    }

    if let Some(stanza_type) = source.stanza_type() {
        builder = builder.attr("type", stanza_type);
    }

    if reason == NackReason::InvalidProtobuf
        && let Some(code) = failure_reason
    {
        let meta = NodeBuilder::new("meta")
            .attr("failure_reason", code)
            .build();
        builder = builder.children(vec![meta]);
    }

    Ok(builder.build())
}

impl Client {
    pub(crate) fn should_send_delivery_receipt(info: &MessageInfo) -> bool {
        if info.id.is_empty() || info.source.chat.is_newsletter() {
            return false;
        }

        // WA Web sends type="peer_msg" delivery receipts for self-synced
        // messages (category="peer").  These tell the primary phone that
        // this companion device received the message.
        // For all other messages, skip receipts for our own messages.
        //
        // status@broadcast: WA Web sends `<receipt context="status">`
        // (`Send/DeliveryReceiptJob.js` + `Handle/MsgSendReceipt.js` —
        // `C = y && isStatusStanzaReceiveEnabled() ? "status" : void 0`).
        // The context attribute is added in send_delivery_receipt below.
        //
        // Self-fanout (own message echoed back, carrying a `recipient`) needs a
        // sender receipt to drain the offline queue; without it the server
        // replays it until a ~50min GC closes the stream. A recipient-less own
        // message (self-note) stays skipped. See `build_delivery_receipt_node`.
        info.category == MessageCategory::Peer
            || !info.source.is_from_me
            || info.source.is_self_fanout()
    }

    pub(crate) async fn handle_receipt(self: &Arc<Self>, node: Arc<OwnedNodeRef>) {
        self.handle_receipt_inline(node);
    }

    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(name = "wa.receipt.handle", level = "debug", skip_all)
    )]
    pub(crate) fn handle_receipt_inline(self: &Arc<Self>, node: Arc<OwnedNodeRef>) {
        let nr = node.get();
        let mut attrs = nr.attrs();
        let from = attrs.jid("from");
        let stanza_id = match attrs.optional_string("id") {
            Some(id) => id.to_string(),
            None => {
                log::warn!("Receipt stanza missing required 'id' attribute");
                return;
            }
        };
        let receipt_type_cow = attrs.optional_string("type");
        let receipt_type_str = receipt_type_cow.as_deref().unwrap_or("delivery");
        let participant = attrs.optional_jid("participant");
        // participant_pn -> sender_alt so the LID-PN cache warms from receipts too.
        let participant_pn = attrs.optional_jid("participant_pn");
        // Present when this receipt was drained from the offline queue on reconnect.
        let offline = attrs.optional_string("offline").is_some();
        let stanza_ts = attrs
            .optional_u64("t")
            .and_then(|t| i64::try_from(t).ok())
            .and_then(wacore::time::from_secs)
            .unwrap_or_else(wacore::time::now_utc);

        let receipt_type = ReceiptType::parse(receipt_type_str);
        // WA Web downgrades a delivery ack to "sent" (not delivered) when the receipt carries
        // <error reason="lid" type="feature-incapable"> (the LID peer can't receive it).
        let receipt_type =
            wacore::stanza::receipt::downgrade_for_feature_incapable(nr, receipt_type);
        let is_view = receipt_type_str == "view";
        let is_group = from.is_group();
        let default_sender = if is_group {
            participant.unwrap_or_else(|| from.clone())
        } else {
            from.clone()
        };

        // Aggregated shape (`<participants>` child): WAWebHandleMsgReceiptParser
        // produces one entry per `<user>`. Fan out into one Receipt event per
        // user so per-user type/timestamp/sender are not lost. Retries and
        // enc_rekey_retry never use the aggregated shape, so this short-circuits
        // before the retry pipeline below.
        if let Some(part_node) = nr.get_optional_child("participants") {
            let (agg_msg_id, agg_key, users) =
                wacore::stanza::receipt::parse_participants(part_node);
            let fan_out_id = agg_msg_id
                .clone()
                .or_else(|| agg_key.clone())
                .unwrap_or_else(|| stanza_id.clone());
            debug!(
                "Aggregated receipt from {}: stanza={stanza_id} \
                 message_id={agg_msg_id:?} key={agg_key:?} users={}",
                from.observe(),
                users.len()
            );
            for user in users {
                // Missing `<user t>` means the server didn't disambiguate the
                // per-user time; fall back to the stanza-level `t`.
                let user_ts = user
                    .timestamp
                    .and_then(|t| i64::try_from(t).ok())
                    .and_then(wacore::time::from_secs)
                    .unwrap_or(stanza_ts);
                // aggregated_by_message: each <user> carries its own type;
                // aggregated_by_type: all users share the receipt-level type.
                let effective_type = match user.r#type.as_deref() {
                    // Apply the receipt-level feature-incapable downgrade to the per-user type
                    // too, so an aggregated delivery receipt with a feature-incapable LID
                    // participant doesn't re-emit a delivered tick for it.
                    Some(t) => wacore::stanza::receipt::downgrade_for_feature_incapable(
                        nr,
                        ReceiptType::parse(t),
                    ),
                    None => receipt_type.clone(),
                };
                let r = Receipt::builder()
                    .message_ids(vec![fan_out_id.clone()])
                    .source(crate::types::message::MessageSource {
                        chat: from.clone(),
                        sender: user.jid,
                        sender_alt: user.participant_pn,
                        ..Default::default()
                    })
                    .timestamp(user_ts)
                    .r#type(effective_type)
                    .offline(offline)
                    .build();
                self.core.event_bus.dispatch(Event::Receipt(r));
            }
            return;
        }

        // Simple receipt: collect `<list><item id=.../>` items plus the stanza
        // id (for non-view receipts), matching the JS p() branch.
        let message_ids =
            wacore::stanza::receipt::collect_simple_message_ids(nr, &stanza_id, is_view);

        debug!(
            "Received receipt type '{receipt_type:?}' for {} message(s) from {}",
            message_ids.len(),
            from.observe()
        );

        let receipt = Receipt::builder()
            .message_ids(message_ids)
            .source(crate::types::message::MessageSource {
                chat: from,
                sender: default_sender,
                sender_alt: participant_pn,
                ..Default::default()
            })
            .timestamp(stanza_ts)
            .r#type(receipt_type)
            .offline(offline)
            .build();

        if receipt.r#type == ReceiptType::Retry {
            let client_clone = Arc::clone(self);
            let node_clone = Arc::clone(&node);
            self.runtime
                .spawn(Box::pin(async move {
                    if let Err(e) = client_clone
                        .handle_retry_receipt(&receipt, &node_clone)
                        .await
                    {
                        log::warn!(
                            "Failed to handle retry receipt for {}: {:?}",
                            receipt.message_ids[0],
                            e
                        );
                    }
                }))
                .detach();
        } else if receipt.r#type == ReceiptType::EncRekeyRetry {
            // WA Web: both "retry" and "enc_rekey_retry" route through
            // handleMessageRetryRequest, but enc_rekey_retry branches to the
            // VoIP stack's resendEncRekeyRetry(peerJid, retryCount).
            // Since we don't have a VoIP stack yet, log and dispatch as a
            // Receipt event so consumers can observe it. When VoIP is
            // implemented (#345), this will route to the VoIP re-key handler.
            if let Some(child) = nr.get_optional_child("enc_rekey") {
                let mut child_attrs = child.attrs();
                log::debug!(
                    "Received enc_rekey_retry receipt for call-id={} from {} \
                     (call-creator={}, count={}). VoIP not implemented, forwarding as event.",
                    child_attrs
                        .optional_string("call-id")
                        .as_deref()
                        .unwrap_or_default(),
                    receipt.source.chat.observe(),
                    child_attrs
                        .optional_string("call-creator")
                        .as_deref()
                        .unwrap_or_default(),
                    child_attrs
                        .optional_string("count")
                        .and_then(|s| s.parse::<u8>().ok())
                        .unwrap_or(1),
                );
            }
            self.core.event_bus.dispatch(Event::Receipt(receipt));
        } else {
            self.core.event_bus.dispatch(Event::Receipt(receipt));
        }
    }

    /// Sends a delivery receipt to the sender of a message.
    ///
    /// Eligibility lives in [`Self::should_send_delivery_receipt`]; the wire
    /// shape is assembled by [`build_delivery_receipt_node`]. Coverage:
    ///
    /// - Direct messages (DMs) — `<receipt>` to the sender's JID.
    /// - Group messages — `<receipt participant=...>` to the group JID.
    /// - Peer device messages (`category="peer"`) — `<receipt type="peer_msg">`
    ///   to acknowledge self-synced messages from the primary phone.
    /// - Status broadcasts — `<receipt context="status">` (WA Web's
    ///   `Send/DeliveryReceiptJob.js`); these are NOT skipped anymore.
    /// - Newsletters and messages without an ID are skipped (newsletters are
    ///   handled by the ack gate, not here).
    #[cfg_attr(feature = "tracing", tracing::instrument(name = "wa.receipt.send_delivery", level = "debug", skip_all, fields(chat = %info.source.chat.observe(), sender = %info.source.sender.observe(), msg_id = %info.id)))]
    pub(crate) async fn send_delivery_receipt(&self, info: &MessageInfo) {
        let Some(frame) = self.prepare_delivery_receipt(info) else {
            return;
        };
        if let Err(e) = self.send_raw_bytes(frame).await
            && !matches!(e, crate::client::ClientError::NotConnected)
        {
            log::warn!(target: "Client/Receipt", "Failed to send delivery receipt for message {}: {:?}", info.id, e);
        }
    }

    /// Everything [`Self::send_delivery_receipt`] does short of the send: the
    /// eligibility gate, node construction, logging and marshalling. Returns
    /// `None` when no receipt is owed. Split out so the receipt worker can
    /// prepare a whole burst before touching the socket.
    pub(crate) fn prepare_delivery_receipt(&self, info: &MessageInfo) -> Option<Vec<u8>> {
        if !Self::should_send_delivery_receipt(info) {
            return None;
        }

        let receipt_node = build_delivery_receipt_node(info, self.receipts_are_active());

        // Mirror build_delivery_receipt_node's type selection so the log is
        // accurate (a passive companion emits `inactive`, not `delivery`).
        let receipt_kind = if info.category == MessageCategory::Peer {
            ReceiptType::PeerMsg
        } else if info.source.is_self_fanout() {
            ReceiptType::Sender
        } else if !self.receipts_are_active() && !info.source.chat.is_status_broadcast() {
            ReceiptType::Inactive
        } else {
            ReceiptType::Delivered
        };
        debug!(target: "Client/Receipt", "Sending {} receipt for message {} to {}",
            receipt_kind.as_wire_str(), info.id, info.source.sender.observe());

        self.marshal_node_for_send(receipt_node)
            .inspect_err(|e| {
                log::warn!(target: "Client/Receipt", "Failed to marshal delivery receipt for message {}: {:?}", info.id, e);
            })
            .ok()
    }

    /// Buffer an offline-drained message's delivery receipt for the aggregate
    /// flush at offline-sync completion (WA Web `sendAggregateOfflineReceipts`).
    /// Returns `false` when the sync already completed, so the caller falls
    /// back to the live 1:1 receipt. The completed flag is re-checked under
    /// the buffer lock: the drain finisher (`finish_offline_sync`) flips the
    /// flag before draining, so a push that wins the lock either lands before
    /// the drain (and is included) or observes the flag and goes 1:1 — a
    /// receipt can never strand in the buffer.
    pub(crate) fn try_buffer_offline_receipt(&self, info: &Arc<MessageInfo>) -> bool {
        let mut buffer = self
            .offline_receipt_buffer
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        // Batcher still active covers the deferred drain→live window: the
        // completion flag is already set there, but SKDM-only stanzas keep
        // mutating cache-only sender-key state, and a 1:1 receipt for one of
        // them before the deferred retry flushes would trade a redeliverable
        // failure for a crash-permanent one. Completion of the deferred
        // transition flushes this buffer (after its durable flush).
        if self
            .offline_sync_completed
            .load(std::sync::atomic::Ordering::Acquire)
            && !self.inbound_commit_batch.is_active()
        {
            return false;
        }
        buffer.push(Arc::clone(info));
        true
    }

    /// Drain the offline receipt buffer and send one aggregate `<receipt>`
    /// per (chat, author, type, recipient) group, chunked at 256 ids. The
    /// drain `mem::take`s the buffer so no capacity is retained between
    /// offline windows, and the send runs as an `outbound_flush` task so
    /// `disconnect()` flushes it like any other receipt (issue #571).
    pub(crate) fn flush_offline_receipts(&self) {
        let infos = std::mem::take(
            &mut *self
                .offline_receipt_buffer
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner()),
        );
        if infos.is_empty() {
            return;
        }
        let Some(client) = self.self_weak.get().and_then(std::sync::Weak::upgrade) else {
            // Shutdown teardown: receipts stay unsent and the server
            // redelivers the messages on the next connect, same as a failed
            // send today.
            return;
        };
        self.outbound_flush.spawn(&*self.runtime, async move {
            let active = client.receipts_are_active();
            let timestamp = wacore::time::now_utc().timestamp().to_string();
            let groups = group_delivery_receipts(&infos, active);
            debug!(
                target: "Client/Receipt",
                "Flushing {} offline delivery receipts as {} aggregate stanza group(s)",
                infos.len(),
                groups.len()
            );
            for group in &groups {
                for node in build_aggregate_delivery_receipt_nodes(
                    group.rep, &group.ids, active, &timestamp,
                ) {
                    if let Err(e) = client.send_node(node).await
                        && !matches!(e, crate::client::ClientError::NotConnected)
                    {
                        log::warn!(
                            target: "Client/Receipt",
                            "Failed to send aggregate delivery receipt for chat {}: {:?}",
                            group.rep.source.chat.observe(),
                            e
                        );
                    }
                }
            }
        });
    }

    /// Drop receipts a teardown drain missed. Called from the connection-state
    /// resets: a receipt buffered after `disconnect()`'s drain belongs to a
    /// message that was never acked, so the server redelivers it on the next
    /// connect and it gets re-acked fresh there. Carrying the stale entry over
    /// would mix a dead connection's receipts into the next connection's
    /// aggregate flush.
    pub(crate) fn clear_offline_receipt_buffer(&self) {
        *self
            .offline_receipt_buffer
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()) = Vec::new();
    }

    /// Spawn an async nack so the caller doesn't await network I/O while
    /// holding a session lock. Mirrors `spawn_retry_receipt`.
    pub(crate) fn spawn_nack(
        self: &Arc<Self>,
        info: &Arc<MessageInfo>,
        reason: NackReason,
        failure_reason: Option<i32>,
    ) {
        let client = Arc::clone(self);
        let info = Arc::clone(info);
        self.runtime
            .spawn(Box::pin(async move {
                client.send_nack(&info, reason, failure_reason).await;
            }))
            .detach();
    }

    fn build_nack_from_snapshot<S: NackSource + ?Sized>(
        &self,
        source: &S,
        reason: NackReason,
        failure_reason: Option<i32>,
    ) -> Result<wacore_binary::Node, crate::features::StanzaResponseError> {
        let device = self.persistence_manager.get_device_snapshot();
        let own_pn = device
            .pn
            .as_ref()
            .ok_or(crate::features::StanzaResponseError::MissingLocalIdentity)?;
        let nack = build_nack_node(source, own_pn, reason, failure_reason);
        drop(device);
        nack
    }

    /// Reject a malformed stanza without retaining or cloning its decoded tree.
    pub(crate) fn spawn_stanza_nack(
        self: &Arc<Self>,
        stanza: &NodeRef<'_>,
        reason: NackReason,
        failure_reason: Option<i32>,
    ) {
        let nack = match self.build_nack_from_snapshot(stanza, reason, failure_reason) {
            Ok(nack) => nack,
            Err(error) => {
                log::warn!(target: "Client/Receipt", "Failed to build stanza nack: {error}");
                return;
            }
        };
        let client = Arc::clone(self);
        self.runtime
            .spawn(Box::pin(async move {
                if let Err(error) = client.send_node(nack).await
                    && !matches!(error, crate::client::ClientError::NotConnected)
                {
                    log::warn!(target: "Client/Receipt", "Failed to send stanza nack: {error:?}");
                }
            }))
            .detach();
    }

    /// Emits a nack so the server stops retransmitting an unrecoverable
    /// failure. Prefer [`Client::send_retry_receipt`] for recoverable
    /// errors (BadMac, NoSession, etc).
    #[cfg_attr(feature = "tracing", tracing::instrument(name = "wa.receipt.send_nack", level = "debug", skip_all, fields(chat = %info.source.chat.observe(), sender = %info.source.sender.observe(), msg_id = %info.id, reason = ?reason)))]
    pub(crate) async fn send_nack(
        &self,
        info: &MessageInfo,
        reason: NackReason,
        failure_reason: Option<i32>,
    ) {
        if info.id.is_empty() {
            return;
        }
        let nack = match self.build_nack_from_snapshot(info, reason, failure_reason) {
            Ok(nack) => nack,
            Err(crate::features::StanzaResponseError::MissingLocalIdentity) => {
                log::debug!(
                    "[msg:{}] Skipping nack ({:?}): own PN not yet set",
                    info.id,
                    reason
                );
                return;
            }
            Err(error) => {
                log::warn!(target: "Client/Receipt",
                    "Failed to build nack for message {}: {error}", info.id);
                return;
            }
        };
        debug!(target: "Client/Receipt",
            "Sending nack (reason={:?}, code={}) for message {} from {}",
            reason, reason.code(), info.id, info.source.sender.observe());

        if let Err(e) = self.send_node(nack).await
            && !matches!(e, crate::client::ClientError::NotConnected)
        {
            log::warn!(target: "Client/Receipt",
                "Failed to send nack for message {}: {:?}", info.id, e);
        }
    }

    /// Reject a received stanza using its original borrowed representation.
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(
            name = "wa.receipt.reject_stanza",
            level = "debug",
            skip_all,
            err(Debug)
        )
    )]
    pub async fn reject_stanza(
        &self,
        stanza: &NodeRef<'_>,
        rejection: crate::features::StanzaRejection,
    ) -> Result<(), crate::features::StanzaResponseError> {
        let nack =
            self.build_nack_from_snapshot(stanza, rejection.reason(), rejection.failure_reason())?;
        self.send_node(nack).await?;
        Ok(())
    }

    /// Sends read receipts for one or more messages.
    ///
    /// For group messages, pass the message sender as `sender`.
    #[cfg_attr(feature = "tracing", tracing::instrument(name = "wa.receipt.mark_as_read", level = "debug", skip_all, fields(chat = %chat.observe()), err(Debug)))]
    pub async fn mark_as_read(
        &self,
        chat: &Jid,
        sender: Option<&Jid>,
        message_ids: &[&str],
    ) -> Result<(), anyhow::Error> {
        if message_ids.is_empty() {
            return Ok(());
        }

        let timestamp = wacore::time::now_secs_u64().to_string();

        // Status reads from a LID author carry peer_participant_pn (the resolved
        // LID->PN), matching WA Web's LidMigrationUtils.toPn.
        let peer_participant_pn = if chat.is_status_broadcast()
            && let Some(sender) = sender
            && sender.is_lid()
        {
            self.get_lid_pn_entry(sender)
                .await
                .ok()
                .flatten()
                .map(|e| Jid::new(&*e.phone_number, wacore_binary::Server::Pn))
        } else {
            None
        };

        debug!(target: "Client/Receipt", "Sending read receipt for {} message(s) to {}", message_ids.len(), chat.observe());

        let read_receipts_disabled = self
            .persistence_manager
            .get_device_snapshot()
            .read_receipts_disabled;

        // WA Web's sendAggregateReceipts caps each <receipt> at 256 ids (one <list>
        // per chunk), so a large catch-up read (post-reconnect / history scroll)
        // doesn't emit one oversized stanza the server may reject.
        for chunk in message_ids.chunks(MAX_RECEIPT_IDS_PER_STANZA) {
            let node = build_read_receipt_node(
                chat,
                sender,
                chunk,
                &timestamp,
                peer_participant_pn.as_ref(),
                read_receipts_disabled,
            );
            self.send_node(node)
                .await
                .map_err(|e| anyhow::anyhow!("Failed to send read receipt: {}", e))?;
        }
        Ok(())
    }

    /// Marks one or more voice/video notes as played (`<receipt type="played">`).
    ///
    /// Mirrors WA Web `WAWebSendPlayedReceiptJob`. For group/broadcast chats pass
    /// the message sender as `sender` so the receipt carries `participant`; in DMs
    /// pass `None`. Newsletters emit `played-self`. When `readreceipts` privacy is
    /// `none`, a DM emits `played-self` too (the sender is not notified), matching
    /// [`mark_as_read`](Self::mark_as_read).
    #[cfg_attr(feature = "tracing", tracing::instrument(name = "wa.receipt.mark_as_played", level = "debug", skip_all, fields(chat = %chat.observe()), err(Debug)))]
    pub async fn mark_as_played(
        &self,
        chat: &Jid,
        sender: Option<&Jid>,
        message_ids: &[&str],
    ) -> Result<(), anyhow::Error> {
        if message_ids.is_empty() {
            return Ok(());
        }

        let timestamp = wacore::time::now_secs_u64().to_string();

        debug!(target: "Client/Receipt", "Sending played receipt for {} message(s) to {}", message_ids.len(), chat.observe());

        let read_receipts_disabled = self
            .persistence_manager
            .get_device_snapshot()
            .read_receipts_disabled;

        // Same 256-id cap per stanza as read receipts (WA Web sendAggregateReceipts).
        for chunk in message_ids.chunks(MAX_RECEIPT_IDS_PER_STANZA) {
            let node =
                build_played_receipt_node(chat, sender, chunk, &timestamp, read_receipts_disabled);
            self.send_node(node)
                .await
                .map_err(|e| anyhow::anyhow!("Failed to send played receipt: {}", e))?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::persistence_manager::PersistenceManager;
    use crate::test_utils::{MockHttpClient, TestEventCollector};
    use crate::types::message::{MessageInfo, MessageSource};

    fn node_to_arc(node: wacore_binary::Node) -> Arc<OwnedNodeRef> {
        crate::test_utils::node_to_owned_ref(&node)
    }

    fn info_with(chat: &str, sender: &str, is_group: bool) -> MessageInfo {
        MessageInfo {
            id: "MID".to_string(),
            source: MessageSource {
                chat: chat.parse().expect("test chat JID"),
                sender: sender.parse().expect("test sender JID"),
                is_from_me: false,
                is_group,
                ..Default::default()
            },
            ..Default::default()
        }
    }

    #[test]
    fn delivery_receipt_for_status_broadcast_carries_context_status_and_participant() {
        // WA Web's gate is `(isGroup || isBroadcast) && participant` for the
        // participant attr, and `isStatus && gating` for context — see
        // `Send/DeliveryReceiptJob.js`. Status broadcasts must carry BOTH so
        // the server can map the ack back to the status owner.
        let info = info_with("status@broadcast", "12345@s.whatsapp.net", false);
        let node = build_delivery_receipt_node(&info, true);
        assert_eq!(node.tag, "receipt");
        assert_eq!(
            node.attrs.get("context").map(|v| v.as_str()).as_deref(),
            Some("status")
        );
        assert_eq!(
            node.attrs.get("participant").map(|v| v.as_str()).as_deref(),
            Some("12345@s.whatsapp.net")
        );
    }

    #[test]
    fn delivery_receipt_for_dm_has_no_context_no_participant() {
        let info = info_with("12345@s.whatsapp.net", "12345@s.whatsapp.net", false);
        let node = build_delivery_receipt_node(&info, true);
        assert!(node.attrs.get("context").is_none());
        assert!(node.attrs.get("participant").is_none());
        assert!(node.attrs.get("type").is_none());
    }

    #[test]
    fn delivery_receipt_for_self_fanout_to_bot_is_sender_with_recipient() {
        // Own prompt to a @bot, echoed back: <receipt type="sender" to=ourLID
        // recipient=@bot>, `to` preserving the sender's device. Mirrors WA Web
        // DeliveryReceiptJob (SENDER + USER_JID(recipient)) and whatsmeow.
        let info = MessageInfo {
            id: "FANOUT_BOT".to_string(),
            source: MessageSource {
                sender: "100000000000001:11@lid".parse().expect("sender"),
                chat: "200000000000002@bot".parse().expect("chat"),
                recipient: Some("200000000000002@bot".parse().expect("recipient")),
                is_from_me: true,
                is_group: false,
                ..Default::default()
            },
            ..Default::default()
        };
        let node = build_delivery_receipt_node(&info, true);
        assert_eq!(node.tag, "receipt");
        assert_eq!(
            node.attrs.get("type").map(|v| v.as_str()).as_deref(),
            Some("sender")
        );
        assert_eq!(
            node.attrs.get("to").map(|v| v.as_str()).as_deref(),
            Some("100000000000001:11@lid"),
            "`to` must preserve the own device or the LID server rejects it"
        );
        assert_eq!(
            node.attrs.get("recipient").map(|v| v.as_str()).as_deref(),
            Some("200000000000002@bot")
        );
        assert!(node.attrs.get("participant").is_none());
        assert!(node.attrs.get("context").is_none());
    }

    #[test]
    fn delivery_receipt_for_self_fanout_strips_recipient_device() {
        // WA Web's `USER_JID` strips the device from `recipient`; a fanout to a
        // multi-device user echoes the non-AD recipient.
        let info = MessageInfo {
            id: "FANOUT_DEV".to_string(),
            source: MessageSource {
                sender: "100000000000001:5@lid".parse().expect("sender"),
                chat: "300000000000003@lid".parse().expect("chat"),
                recipient: Some("300000000000003:7@lid".parse().expect("recipient")),
                is_from_me: true,
                is_group: false,
                ..Default::default()
            },
            ..Default::default()
        };
        let node = build_delivery_receipt_node(&info, true);
        assert_eq!(
            node.attrs.get("recipient").map(|v| v.as_str()).as_deref(),
            Some("300000000000003@lid"),
            "recipient device must be stripped (USER_JID semantics)"
        );
    }

    #[test]
    fn peer_self_fanout_is_peer_msg_without_recipient() {
        // A peer-synced message that also looks like a self-fanout (is_from_me +
        // recipient) must keep `type="peer_msg"` and carry NO recipient (WA Web
        // `!l` guard), never `type="sender"`.
        let info = MessageInfo {
            id: "PEER_FANOUT".to_string(),
            source: MessageSource {
                sender: "100000000000001@lid".parse().expect("sender"),
                chat: "300000000000003@lid".parse().expect("chat"),
                recipient: Some("300000000000003@lid".parse().expect("recipient")),
                is_from_me: true,
                is_group: false,
                ..Default::default()
            },
            category: MessageCategory::Peer,
            ..Default::default()
        };
        let node = build_delivery_receipt_node(&info, true);
        assert_eq!(
            node.attrs.get("type").map(|v| v.as_str()).as_deref(),
            Some("peer_msg")
        );
        assert!(
            node.attrs.get("recipient").is_none(),
            "a peer_msg receipt must not carry a recipient"
        );
    }

    #[test]
    fn self_fanout_is_sender_even_when_inactive() {
        // type=sender takes precedence over the inactive (passive companion)
        // branch: a self-fanout is always acknowledged as sender.
        let info = MessageInfo {
            id: "FANOUT_INACTIVE".to_string(),
            source: MessageSource {
                sender: "100000000000001@lid".parse().expect("sender"),
                chat: "200000000000002@bot".parse().expect("chat"),
                recipient: Some("200000000000002@bot".parse().expect("recipient")),
                is_from_me: true,
                is_group: false,
                ..Default::default()
            },
            ..Default::default()
        };
        let node = build_delivery_receipt_node(&info, false);
        assert_eq!(
            node.attrs.get("type").map(|v| v.as_str()).as_deref(),
            Some("sender"),
            "self-fanout must stay type=sender, not become inactive"
        );
        assert_eq!(
            node.attrs.get("recipient").map(|v| v.as_str()).as_deref(),
            Some("200000000000002@bot")
        );
    }

    #[test]
    fn delivery_receipt_is_inactive_when_not_active() {
        let info = info_with("12345@s.whatsapp.net", "12345@s.whatsapp.net", false);
        let inactive = build_delivery_receipt_node(&info, false);
        assert_eq!(
            inactive.attrs.get("type").map(|v| v.as_str()).as_deref(),
            Some("inactive"),
            "a passive companion sends inactive delivery receipts"
        );
        let active = build_delivery_receipt_node(&info, true);
        assert!(active.attrs.get("type").is_none());
    }

    #[test]
    fn status_and_peer_receipts_ignore_inactive() {
        let status = info_with("status@broadcast", "12345@s.whatsapp.net", false);
        let node = build_delivery_receipt_node(&status, false);
        // status keeps context, never type=inactive
        assert!(node.attrs.get("type").is_none());
        assert_eq!(
            node.attrs.get("context").map(|v| v.as_str()).as_deref(),
            Some("status")
        );

        let mut peer = info_with("12345@s.whatsapp.net", "12345@s.whatsapp.net", false);
        peer.category = MessageCategory::Peer;
        let node = build_delivery_receipt_node(&peer, false);
        assert_eq!(
            node.attrs.get("type").map(|v| v.as_str()).as_deref(),
            Some("peer_msg")
        );
    }

    #[test]
    fn delivery_receipt_for_group_carries_participant() {
        let info = info_with(
            "120363021033254949@g.us",
            "15551234567@s.whatsapp.net",
            true,
        );
        let node = build_delivery_receipt_node(&info, true);
        assert_eq!(
            node.attrs.get("participant").map(|v| v.as_str()).as_deref(),
            Some("15551234567@s.whatsapp.net")
        );
        assert!(node.attrs.get("context").is_none());
    }

    #[test]
    fn should_send_delivery_receipt_allows_status_broadcast() {
        let info = info_with("status@broadcast", "12345@s.whatsapp.net", false);
        assert!(Client::should_send_delivery_receipt(&info));
    }

    /// Regression: LID DM with explicit device must echo the device in `to`
    /// (matches whatsmeow buildBaseReceipt + WA Web JID encoding). Stripping
    /// the device caused <stream:error><ack/> for multi-device LID senders.
    #[test]
    fn delivery_receipt_for_lid_dm_preserves_device_in_to() {
        let info = MessageInfo {
            id: "LID_DEV_RECEIPT".to_string(),
            source: MessageSource {
                // chat is the non-AD form (matches parse_message_info's
                // chat = from.to_non_ad()).
                chat: "156535032389744@lid".parse().expect("chat"),
                // sender preserves device (matches parse_message_info's
                // sender = from.clone()).
                sender: "156535032389744:7@lid".parse().expect("sender"),
                is_from_me: false,
                is_group: false,
                ..Default::default()
            },
            ..Default::default()
        };
        let node = build_delivery_receipt_node(&info, true);
        assert_eq!(
            node.attrs.get("to").map(|v| v.as_str()).as_deref(),
            Some("156535032389744:7@lid"),
            "LID DM receipt must preserve the device or the server rejects the ack"
        );
        assert!(node.attrs.get("participant").is_none());
    }

    /// LID DM without device stays as-is (no-op for the common case).
    #[test]
    fn delivery_receipt_for_lid_dm_no_device_unchanged() {
        let info = MessageInfo {
            id: "LID_NO_DEV".to_string(),
            source: MessageSource {
                chat: "185323896221943@lid".parse().expect("chat"),
                sender: "185323896221943@lid".parse().expect("sender"),
                is_from_me: false,
                is_group: false,
                ..Default::default()
            },
            ..Default::default()
        };
        let node = build_delivery_receipt_node(&info, true);
        assert_eq!(
            node.attrs.get("to").map(|v| v.as_str()).as_deref(),
            Some("185323896221943@lid")
        );
    }

    /// Group: `to` must remain the group JID, participant carries the device.
    #[test]
    fn delivery_receipt_for_group_to_is_group_not_sender() {
        let info = MessageInfo {
            id: "GRP_RECEIPT".to_string(),
            source: MessageSource {
                chat: "120363021033254949@g.us".parse().expect("group"),
                sender: "156535032389744:7@lid".parse().expect("sender"),
                is_from_me: false,
                is_group: true,
                ..Default::default()
            },
            ..Default::default()
        };
        let node = build_delivery_receipt_node(&info, true);
        assert_eq!(
            node.attrs.get("to").map(|v| v.as_str()).as_deref(),
            Some("120363021033254949@g.us")
        );
        assert_eq!(
            node.attrs.get("participant").map(|v| v.as_str()).as_deref(),
            Some("156535032389744:7@lid")
        );
    }

    /// peer_msg: `to` echoes from (us with device), no participant.
    #[test]
    fn delivery_receipt_for_peer_dm_to_preserves_device() {
        let mut info = MessageInfo {
            id: "PEER_DEV".to_string(),
            source: MessageSource {
                chat: "9999999999@lid".parse().expect("chat"),
                sender: "9999999999:3@lid".parse().expect("sender"),
                is_from_me: true,
                is_group: false,
                ..Default::default()
            },
            ..Default::default()
        };
        info.category = MessageCategory::Peer;
        let node = build_delivery_receipt_node(&info, true);
        assert_eq!(
            node.attrs.get("to").map(|v| v.as_str()).as_deref(),
            Some("9999999999:3@lid")
        );
        assert_eq!(
            node.attrs.get("type").map(|v| v.as_str()).as_deref(),
            Some("peer_msg")
        );
        assert!(node.attrs.get("participant").is_none());
    }

    /// status@broadcast: `to` must stay status@broadcast (chat), participant
    /// carries the original sender device.
    #[test]
    fn delivery_receipt_for_status_to_is_status_not_sender() {
        let info = MessageInfo {
            id: "STATUS_RECEIPT".to_string(),
            source: MessageSource {
                chat: "status@broadcast".parse().expect("status"),
                sender: "156535032389744:7@lid".parse().expect("sender"),
                is_from_me: false,
                is_group: false,
                ..Default::default()
            },
            ..Default::default()
        };
        let node = build_delivery_receipt_node(&info, true);
        assert_eq!(
            node.attrs.get("to").map(|v| v.as_str()).as_deref(),
            Some("status@broadcast")
        );
        assert_eq!(
            node.attrs.get("participant").map(|v| v.as_str()).as_deref(),
            Some("156535032389744:7@lid")
        );
        assert_eq!(
            node.attrs.get("context").map(|v| v.as_str()).as_deref(),
            Some("status")
        );
    }

    #[test]
    fn delivery_receipt_for_peer_dm_carries_type_peer_msg() {
        // category=Peer + DM (self device sync) → type="peer_msg", no
        // participant, no context. Matches WA Web's DROP_ATTR gating.
        let mut info = info_with("12345@s.whatsapp.net", "12345@s.whatsapp.net", false);
        info.category = MessageCategory::Peer;
        let node = build_delivery_receipt_node(&info, true);
        assert_eq!(
            node.attrs.get("type").map(|v| v.as_str()).as_deref(),
            Some("peer_msg")
        );
        assert!(node.attrs.get("participant").is_none());
        assert!(node.attrs.get("context").is_none());
    }

    #[test]
    fn delivery_receipt_for_status_broadcast_keeps_participant_even_with_peer_type() {
        // Defensive: if a status broadcast ever surfaces with category=Peer,
        // the participant attr must still be there — server identifies the
        // status owner from it regardless of the peer_msg type.
        let mut info = info_with("status@broadcast", "12345@s.whatsapp.net", false);
        info.category = MessageCategory::Peer;
        let node = build_delivery_receipt_node(&info, true);
        assert_eq!(
            node.attrs.get("participant").map(|v| v.as_str()).as_deref(),
            Some("12345@s.whatsapp.net")
        );
        assert_eq!(
            node.attrs.get("context").map(|v| v.as_str()).as_deref(),
            Some("status")
        );
    }

    // --- read/played receipt privacy gating (readreceipts==none) ---

    fn type_of(node: &wacore_binary::Node) -> Option<String> {
        node.attrs.get("type").map(|v| v.as_str().to_string())
    }

    #[test]
    fn dm_read_receipt_gates_to_read_self_when_disabled() {
        let chat: Jid = "12025550143@s.whatsapp.net".parse().expect("dm jid");
        let read = build_read_receipt_node(&chat, None, &["MID"], "1", None, true);
        assert_eq!(type_of(&read).as_deref(), Some("read-self"));
        let played = build_played_receipt_node(&chat, None, &["MID"], "1", true);
        assert_eq!(type_of(&played).as_deref(), Some("played-self"));
    }

    #[test]
    fn dm_receipts_stay_plain_when_privacy_enabled() {
        let chat: Jid = "12025550143@s.whatsapp.net".parse().expect("dm jid");
        let read = build_read_receipt_node(&chat, None, &["MID"], "1", None, false);
        assert_eq!(type_of(&read).as_deref(), Some("read"));
        let played = build_played_receipt_node(&chat, None, &["MID"], "1", false);
        assert_eq!(type_of(&played).as_deref(), Some("played"));
    }

    #[test]
    fn group_receipts_ignore_privacy_gate() {
        // Privacy does not apply to groups: still `read`/`played` even when disabled.
        let chat: Jid = "120363021033254949@g.us".parse().expect("group jid");
        let sender: Jid = "12025550143@s.whatsapp.net".parse().expect("sender jid");
        let read = build_read_receipt_node(&chat, Some(&sender), &["MID"], "1", None, true);
        assert_eq!(type_of(&read).as_deref(), Some("read"));
        let played = build_played_receipt_node(&chat, Some(&sender), &["MID"], "1", true);
        assert_eq!(type_of(&played).as_deref(), Some("played"));
    }

    #[test]
    fn broadcast_list_receipts_ignore_privacy_gate() {
        // Broadcast lists are group-adjacent (they carry `participant`), so the
        // privacy gate must not downgrade them to `*-self` — matching WA Web.
        let chat: Jid = "120363000000000001@broadcast"
            .parse()
            .expect("broadcast list jid");
        let sender: Jid = "12025550143@s.whatsapp.net".parse().expect("sender jid");
        let read = build_read_receipt_node(&chat, Some(&sender), &["MID"], "1", None, true);
        assert_eq!(type_of(&read).as_deref(), Some("read"));
        let played = build_played_receipt_node(&chat, Some(&sender), &["MID"], "1", true);
        assert_eq!(type_of(&played).as_deref(), Some("played"));
    }

    #[test]
    fn newsletter_receipts_are_self_regardless_of_flag() {
        let chat: Jid = "120363298765432100@newsletter"
            .parse()
            .expect("newsletter jid");
        for disabled in [false, true] {
            let read = build_read_receipt_node(&chat, None, &["MID"], "1", None, disabled);
            assert_eq!(type_of(&read).as_deref(), Some("read-self"));
            let played = build_played_receipt_node(&chat, None, &["MID"], "1", disabled);
            assert_eq!(type_of(&played).as_deref(), Some("played-self"));
        }
    }

    fn own_pn() -> Jid {
        "5511000000001:0@s.whatsapp.net"
            .parse()
            .expect("own PN should parse")
    }

    #[test]
    fn nack_from_original_stanza_preserves_each_supported_class() {
        for tag in ["message", "receipt", "notification"] {
            let stanza = NodeBuilder::new(tag)
                .attr("id", "STANZA-ID")
                .attr("from", "120363021033254949@g.us")
                .attr("participant", "12025550111:4@s.whatsapp.net")
                .attr("type", "test-type")
                .build();
            let nack = build_nack_node(
                &stanza.as_node_ref(),
                &own_pn(),
                NackReason::ParsingError,
                None,
            )
            .expect("supported stanza should produce a nack");

            assert_eq!(
                nack.attrs
                    .get("class")
                    .map(|value| value.as_str())
                    .as_deref(),
                Some(tag)
            );
            assert_eq!(
                nack.attrs.get("id").map(|value| value.as_str()).as_deref(),
                Some("STANZA-ID")
            );
            assert_eq!(
                nack.attrs.get("to").map(|value| value.as_str()).as_deref(),
                Some("120363021033254949@g.us")
            );
            assert_eq!(
                nack.attrs
                    .get("participant")
                    .map(|value| value.as_str())
                    .as_deref(),
                Some("12025550111:4@s.whatsapp.net")
            );
            assert_eq!(
                nack.attrs
                    .get("type")
                    .map(|value| value.as_str())
                    .as_deref(),
                Some("test-type")
            );
            assert_eq!(
                nack.attrs
                    .get("from")
                    .map(|value| value.as_str())
                    .as_deref(),
                Some("5511000000001@s.whatsapp.net")
            );
        }
    }

    #[test]
    fn unrecognized_stanza_rejection_preserves_custom_class() {
        let stanza = NodeBuilder::new("future-stanza")
            .attr("id", "FUTURE-ID")
            .attr("from", "12025550111@s.whatsapp.net")
            .build();
        let nack = build_nack_node(
            &stanza.as_node_ref(),
            &own_pn(),
            NackReason::UnrecognizedStanza,
            None,
        )
        .expect("unrecognized stanza reason supports arbitrary classes");

        assert_eq!(
            nack.attrs
                .get("class")
                .map(|value| value.as_str())
                .as_deref(),
            Some("future-stanza")
        );
        assert!(matches!(
            build_nack_node(
                &stanza.as_node_ref(),
                &own_pn(),
                NackReason::ParsingError,
                None
            ),
            Err(crate::features::StanzaResponseError::UnsupportedStanzaClass)
        ));
    }

    #[test]
    fn nack_does_not_apply_the_receipt_ack_participant_rule() {
        let stanza = NodeBuilder::new("receipt")
            .attr("id", "NACK-DUPLICATE-PARTICIPANT")
            .attr("from", "12025550111@s.whatsapp.net")
            .attr("participant", "12025550111@s.whatsapp.net")
            .build();
        let nack = build_nack_node(
            &stanza.as_node_ref(),
            &own_pn(),
            NackReason::ParsingError,
            None,
        )
        .expect("supported stanza should produce a nack");

        assert!(
            nack.attrs
                .get("participant")
                .is_some_and(|value| value == "12025550111@s.whatsapp.net"),
            "nack must preserve participant even when a receipt ack would omit it"
        );
    }

    #[test]
    fn nack_from_original_stanza_requires_id_and_from() {
        let without_id = NodeBuilder::new("message")
            .attr("from", "12025550111@s.whatsapp.net")
            .build();
        assert!(matches!(
            build_nack_node(
                &without_id.as_node_ref(),
                &own_pn(),
                NackReason::ParsingError,
                None
            ),
            Err(crate::features::StanzaResponseError::MissingAttribute("id"))
        ));

        let without_from = NodeBuilder::new("message")
            .attr("id", "MISSING-FROM")
            .build();
        assert!(matches!(
            build_nack_node(
                &without_from.as_node_ref(),
                &own_pn(),
                NackReason::ParsingError,
                None
            ),
            Err(crate::features::StanzaResponseError::MissingAttribute(
                "from"
            ))
        ));
    }

    #[test]
    fn nack_preserves_unknown_numeric_reason() {
        let stanza = NodeBuilder::new("message")
            .attr("id", "UNKNOWN-REASON")
            .attr("from", "12025550111@s.whatsapp.net")
            .build();
        let nack = build_nack_node(
            &stanza.as_node_ref(),
            &own_pn(),
            NackReason::Unknown(599),
            None,
        )
        .expect("known stanza supports unknown future error codes");

        assert_eq!(
            nack.attrs
                .get("error")
                .map(|value| value.as_str())
                .as_deref(),
            Some("599")
        );
    }

    #[test]
    fn nack_for_dm_carries_class_message_and_error_code() {
        let info = info_with("12345@s.whatsapp.net", "12345@s.whatsapp.net", false);
        let node = build_nack_node(&info, &own_pn(), NackReason::ParsingError, None)
            .expect("valid DM should produce a nack");

        assert_eq!(node.tag, "ack");
        assert_eq!(
            node.attrs.get("class").map(|v| v.as_str()).as_deref(),
            Some("message")
        );
        assert_eq!(
            node.attrs.get("error").map(|v| v.as_str()).as_deref(),
            Some("487")
        );
        assert_eq!(
            node.attrs.get("id").map(|v| v.as_str()).as_deref(),
            Some("MID")
        );
        assert!(node.attrs.get("from").is_some());
        assert!(node.attrs.get("to").is_some());
        assert!(node.attrs.get("participant").is_none());
    }

    #[test]
    fn nack_for_group_carries_participant() {
        let info = info_with(
            "120363021033254949@g.us",
            "15551234567@s.whatsapp.net",
            true,
        );
        let node = build_nack_node(&info, &own_pn(), NackReason::UnhandledError, None)
            .expect("valid group message should produce a nack");

        assert_eq!(
            node.attrs.get("participant").map(|v| v.as_str()).as_deref(),
            Some("15551234567@s.whatsapp.net")
        );
        assert_eq!(
            node.attrs.get("error").map(|v| v.as_str()).as_deref(),
            Some("500")
        );
    }

    #[test]
    fn nack_for_status_broadcast_carries_participant() {
        let info = info_with("status@broadcast", "12345@s.whatsapp.net", false);
        let node = build_nack_node(&info, &own_pn(), NackReason::ParsingError, None)
            .expect("valid status message should produce a nack");

        assert_eq!(
            node.attrs.get("participant").map(|v| v.as_str()).as_deref(),
            Some("12345@s.whatsapp.net")
        );
    }

    #[test]
    fn nack_invalid_protobuf_includes_meta_failure_reason() {
        let info = info_with("12345@s.whatsapp.net", "12345@s.whatsapp.net", false);
        let node = build_nack_node(&info, &own_pn(), NackReason::InvalidProtobuf, Some(42))
            .expect("valid message should produce a nack");

        assert_eq!(
            node.attrs.get("error").map(|v| v.as_str()).as_deref(),
            Some("491")
        );
        let meta = node
            .get_optional_child("meta")
            .expect("InvalidProtobuf nack must have <meta> child");
        assert_eq!(
            meta.attrs
                .get("failure_reason")
                .map(|v| v.as_str())
                .as_deref(),
            Some("42")
        );
    }

    #[test]
    fn nack_invalid_protobuf_without_failure_reason_omits_meta() {
        let info = info_with("12345@s.whatsapp.net", "12345@s.whatsapp.net", false);
        let node = build_nack_node(&info, &own_pn(), NackReason::InvalidProtobuf, None)
            .expect("valid message should produce a nack");
        assert!(node.get_optional_child("meta").is_none());
    }

    /// failure_reason only applies to InvalidProtobuf.
    #[test]
    fn nack_omits_meta_for_non_invalid_protobuf_even_with_failure_reason() {
        let info = info_with("12345@s.whatsapp.net", "12345@s.whatsapp.net", false);
        let node = build_nack_node(&info, &own_pn(), NackReason::ParsingError, Some(99))
            .expect("valid message should produce a nack");
        assert!(node.get_optional_child("meta").is_none());
    }

    #[test]
    fn nack_includes_type_when_present() {
        let mut info = info_with("12345@s.whatsapp.net", "12345@s.whatsapp.net", false);
        info.r#type = "text".to_string();
        let node = build_nack_node(&info, &own_pn(), NackReason::ParsingError, None)
            .expect("valid message should produce a nack");
        assert_eq!(
            node.attrs.get("type").map(|v| v.as_str()).as_deref(),
            Some("text")
        );
    }

    #[test]
    fn nack_omits_type_when_empty() {
        let mut info = info_with("12345@s.whatsapp.net", "12345@s.whatsapp.net", false);
        info.r#type = String::new();
        let node = build_nack_node(&info, &own_pn(), NackReason::ParsingError, None)
            .expect("valid message should produce a nack");
        assert!(node.attrs.get("type").is_none());
    }

    #[test]
    fn should_send_delivery_receipt_skips_newsletter() {
        let info = info_with(
            "120363298765432100@newsletter",
            "120363298765432100@newsletter",
            false,
        );
        assert!(!Client::should_send_delivery_receipt(&info));
    }

    #[test]
    fn should_send_delivery_receipt_skips_empty_id() {
        let mut info = info_with("12345@s.whatsapp.net", "12345@s.whatsapp.net", false);
        info.id = String::new();
        assert!(!Client::should_send_delivery_receipt(&info));
    }

    #[test]
    fn should_send_delivery_receipt_skips_own_dm() {
        // Self-sent message with NO `recipient` (a self-note where from==to):
        // not a fanout, so no receipt. Peer-category self-sync and self-fanouts
        // (which carry a `recipient`) are handled by the cases below.
        let mut info = info_with("12345@s.whatsapp.net", "12345@s.whatsapp.net", false);
        info.source.is_from_me = true;
        assert!(info.source.recipient.is_none());
        assert!(!Client::should_send_delivery_receipt(&info));
    }

    #[test]
    fn should_send_delivery_receipt_allows_self_fanout_to_user() {
        // Own outgoing DM to another user, echoed back to this device
        // (is_from_me + recipient). WA Web emits a `<receipt type="sender">`.
        let mut info = info_with("300000000000003@lid", "100000000000001@lid", false);
        info.source.is_from_me = true;
        info.source.recipient = Some("300000000000003@lid".parse().expect("recipient"));
        assert!(Client::should_send_delivery_receipt(&info));
    }

    #[test]
    fn should_send_delivery_receipt_allows_self_fanout_to_bot() {
        // The reported disconnect-loop case: our own prompt to a @bot, echoed
        // back. Must get a sender receipt or the server replays it forever.
        let mut info = info_with("200000000000002@bot", "100000000000001@lid", false);
        info.source.is_from_me = true;
        info.source.recipient = Some("200000000000002@bot".parse().expect("recipient"));
        assert!(Client::should_send_delivery_receipt(&info));
    }

    #[test]
    fn should_send_delivery_receipt_skips_own_status_and_group_fanout() {
        // Regression guard: the self-fanout allowance must NOT leak into our own
        // status broadcasts or group messages (WA Web does not send a DM-style
        // sender receipt there).
        let mut own_status = info_with("status@broadcast", "100000000000001@lid", false);
        own_status.source.is_from_me = true;
        own_status.source.recipient = Some("100000000000001@lid".parse().expect("recipient"));
        assert!(!Client::should_send_delivery_receipt(&own_status));

        let mut own_group = info_with("120363021033254949@g.us", "100000000000001@lid", true);
        own_group.source.is_from_me = true;
        own_group.source.recipient = Some("100000000000001@lid".parse().expect("recipient"));
        assert!(!Client::should_send_delivery_receipt(&own_group));
    }

    #[test]
    fn should_send_delivery_receipt_allows_own_peer_msg() {
        // Self-synced messages from the primary phone (category=Peer) DO need
        // a receipt with type="peer_msg", per the WA Web `OUR_OWN_DEVICE` ack.
        let mut info = info_with("12345@s.whatsapp.net", "12345@s.whatsapp.net", false);
        info.source.is_from_me = true;
        info.category = MessageCategory::Peer;
        assert!(Client::should_send_delivery_receipt(&info));
    }

    #[tokio::test]
    async fn test_send_delivery_receipt_dm() {
        let backend = crate::test_utils::create_test_backend().await;
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("persistence manager should initialize"),
        );
        let (client, _rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            Arc::new(crate::transport::mock::MockTransportFactory::new()),
            Arc::new(MockHttpClient),
            None,
        )
        .await;

        let info = MessageInfo {
            id: "TEST-ID-123".to_string(),
            source: MessageSource {
                chat: "12345@s.whatsapp.net"
                    .parse()
                    .expect("test JID should be valid"),
                sender: "12345@s.whatsapp.net"
                    .parse()
                    .expect("test JID should be valid"),
                is_from_me: false,
                is_group: false,
                ..Default::default()
            },
            ..Default::default()
        };

        // This should complete without panicking. The actual node sending
        // would fail since we're not connected, but the function should
        // handle that gracefully and log a warning.
        client.send_delivery_receipt(&info).await;

        // If we got here, the function executed successfully.
        // In a real scenario, we'd need to mock the transport to verify
        // the exact node sent, but basic functionality testing confirms
        // the method doesn't panic and logs appropriately.
    }

    #[tokio::test]
    async fn test_send_delivery_receipt_group() {
        let backend = crate::test_utils::create_test_backend().await;
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("persistence manager should initialize"),
        );
        let (client, _rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            Arc::new(crate::transport::mock::MockTransportFactory::new()),
            Arc::new(MockHttpClient),
            None,
        )
        .await;

        let info = MessageInfo {
            id: "GROUP-MSG-ID".to_string(),
            source: MessageSource {
                chat: "120363021033254949@g.us"
                    .parse()
                    .expect("test JID should be valid"),
                sender: "15551234567@s.whatsapp.net"
                    .parse()
                    .expect("test JID should be valid"),
                is_from_me: false,
                is_group: true,
                ..Default::default()
            },
            ..Default::default()
        };

        // Should complete without panicking for group messages too.
        client.send_delivery_receipt(&info).await;
    }

    #[tokio::test]
    async fn test_skip_delivery_receipt_for_own_messages() {
        let backend = crate::test_utils::create_test_backend().await;
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("persistence manager should initialize"),
        );
        let (client, _rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            Arc::new(crate::transport::mock::MockTransportFactory::new()),
            Arc::new(MockHttpClient),
            None,
        )
        .await;

        let info = MessageInfo {
            id: "OWN-MSG-ID".to_string(),
            source: MessageSource {
                chat: "12345@s.whatsapp.net"
                    .parse()
                    .expect("test JID should be valid"),
                sender: "12345@s.whatsapp.net"
                    .parse()
                    .expect("test JID should be valid"),
                is_from_me: true, // Own message
                is_group: false,
                ..Default::default()
            },
            ..Default::default()
        };

        // Should return early without attempting to send.
        // We can't easily assert that send_node was not called without
        // refactoring, but at least verify the function completes.
        client.send_delivery_receipt(&info).await;
    }

    #[tokio::test]
    async fn test_skip_delivery_receipt_for_empty_id() {
        let backend = crate::test_utils::create_test_backend().await;
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("persistence manager should initialize"),
        );
        let (client, _rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            Arc::new(crate::transport::mock::MockTransportFactory::new()),
            Arc::new(MockHttpClient),
            None,
        )
        .await;

        let info = MessageInfo {
            id: "".to_string(), // Empty ID
            source: MessageSource {
                chat: "12345@s.whatsapp.net"
                    .parse()
                    .expect("test JID should be valid"),
                sender: "12345@s.whatsapp.net"
                    .parse()
                    .expect("test JID should be valid"),
                is_from_me: false,
                is_group: false,
                ..Default::default()
            },
            ..Default::default()
        };

        // Should return early without attempting to send.
        client.send_delivery_receipt(&info).await;
    }

    #[tokio::test]
    async fn test_skip_delivery_receipt_for_status_broadcast() {
        let backend = crate::test_utils::create_test_backend().await;
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("persistence manager should initialize"),
        );
        let (client, _rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            Arc::new(crate::transport::mock::MockTransportFactory::new()),
            Arc::new(MockHttpClient),
            None,
        )
        .await;

        let info = MessageInfo {
            id: "STATUS-MSG-ID".to_string(),
            source: MessageSource {
                chat: "status@broadcast"
                    .parse()
                    .expect("test JID should be valid"), // Status broadcast
                sender: "12345@s.whatsapp.net"
                    .parse()
                    .expect("test JID should be valid"),
                is_from_me: false,
                is_group: true,
                ..Default::default()
            },
            ..Default::default()
        };

        // Should return early without attempting to send for status broadcasts.
        client.send_delivery_receipt(&info).await;
    }

    #[test]
    fn test_should_skip_delivery_receipt_for_newsletter() {
        let info = MessageInfo {
            id: "NEWSLETTER-MSG-ID".to_string(),
            source: MessageSource {
                chat: "120363173003902460@newsletter"
                    .parse()
                    .expect("newsletter JID should be valid"),
                sender: "120363173003902460@newsletter"
                    .parse()
                    .expect("newsletter JID should be valid"),
                is_from_me: false,
                is_group: false,
                ..Default::default()
            },
            ..Default::default()
        };

        assert!(
            !Client::should_send_delivery_receipt(&info),
            "generic delivery receipts must be skipped for newsletters"
        );
    }

    #[test]
    fn test_should_send_peer_msg_receipt_for_self_synced_messages() {
        // Self-synced messages (category="peer") should get delivery receipts
        // even though is_from_me is true.  WA Web sends type="peer_msg" for these.
        let info = MessageInfo {
            id: "PEER-MSG-ID".to_string(),
            source: MessageSource {
                chat: "155500012345@s.whatsapp.net"
                    .parse()
                    .expect("own PN JID should be valid"),
                sender: "155500012345@s.whatsapp.net"
                    .parse()
                    .expect("own PN JID should be valid"),
                is_from_me: true,
                is_group: false,
                ..Default::default()
            },
            category: MessageCategory::Peer,
            ..Default::default()
        };

        assert!(
            Client::should_send_delivery_receipt(&info),
            "peer device messages must get delivery receipts even when is_from_me"
        );
    }

    /// Create a test client with an event collector registered.
    async fn setup_client_with_collector() -> (Arc<Client>, Arc<TestEventCollector>) {
        let backend = crate::test_utils::create_test_backend().await;
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("persistence manager should initialize"),
        );
        let (client, _rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            Arc::new(crate::transport::mock::MockTransportFactory::new()),
            Arc::new(MockHttpClient),
            None,
        )
        .await;

        let collector = Arc::new(TestEventCollector::default());
        client.subscribe_handler(collector.clone()).detach();
        (client, collector)
    }

    /// Verify that enc_rekey_retry receipt is dispatched as a Receipt event
    /// with EncRekeyRetry type so consumers can observe it.
    #[tokio::test]
    async fn test_enc_rekey_retry_receipt_dispatches_event() {
        let (client, collector) = setup_client_with_collector().await;

        // Build an enc_rekey_retry receipt node matching WA Web structure
        let node = node_to_arc(
            NodeBuilder::new("receipt")
                .attr("from", "5511999999999@s.whatsapp.net")
                .attr("id", "3EB0AABBCCDD")
                .attr("type", "enc_rekey_retry")
                .children([
                    NodeBuilder::new("enc_rekey")
                        .attr("call-creator", "5511888888888@s.whatsapp.net")
                        .attr("call-id", "CALL-123")
                        .attr("count", "1")
                        .build(),
                    NodeBuilder::new("registration")
                        .bytes(12345u32.to_be_bytes().to_vec())
                        .build(),
                ])
                .build(),
        );

        client.handle_receipt(node).await;

        // Must dispatch exactly one Receipt event with EncRekeyRetry type
        let events = collector.events();
        let receipt_events: Vec<_> = events
            .iter()
            .filter_map(|e| match &**e {
                Event::Receipt(r) => Some(r),
                _ => None,
            })
            .collect();
        assert_eq!(
            receipt_events.len(),
            1,
            "enc_rekey_retry must dispatch exactly one Receipt event"
        );
        assert_eq!(
            receipt_events[0].r#type,
            ReceiptType::EncRekeyRetry,
            "dispatched receipt must have EncRekeyRetry type"
        );
        assert_eq!(receipt_events[0].message_ids, vec!["3EB0AABBCCDD"]);
    }

    /// Verify that enc_rekey_retry without <enc_rekey> child still dispatches
    /// the Receipt event (graceful degradation, no crash).
    #[tokio::test]
    async fn test_enc_rekey_retry_receipt_without_child_still_dispatches() {
        let (client, collector) = setup_client_with_collector().await;

        // Malformed: no <enc_rekey> child
        let node = node_to_arc(
            NodeBuilder::new("receipt")
                .attr("from", "5511999999999@s.whatsapp.net")
                .attr("id", "3EB0AABBCCDD")
                .attr("type", "enc_rekey_retry")
                .build(),
        );

        client.handle_receipt(node).await;

        // Should still dispatch the Receipt event even without <enc_rekey> child
        let events = collector.events();
        let receipt_events: Vec<_> = events
            .iter()
            .filter_map(|e| match &**e {
                Event::Receipt(r) => Some(r),
                _ => None,
            })
            .collect();
        assert_eq!(
            receipt_events.len(),
            1,
            "malformed enc_rekey_retry must still dispatch Receipt event"
        );
        assert_eq!(receipt_events[0].r#type, ReceiptType::EncRekeyRetry);
    }

    #[test]
    fn test_should_skip_non_peer_self_messages() {
        // Normal self messages (no category) should still be skipped.
        let info = MessageInfo {
            id: "SELF-MSG-ID".to_string(),
            source: MessageSource {
                chat: "155500012345@s.whatsapp.net"
                    .parse()
                    .expect("own PN JID should be valid"),
                sender: "155500012345@s.whatsapp.net"
                    .parse()
                    .expect("own PN JID should be valid"),
                is_from_me: true,
                is_group: false,
                ..Default::default()
            },
            ..Default::default()
        };

        assert!(
            !Client::should_send_delivery_receipt(&info),
            "non-peer self messages must not get delivery receipts"
        );
    }

    /// Aggregated-by-message receipt: fan out one Receipt event per `<user>`
    /// with that user's type, and use the `message_id` attr (not the stanza
    /// id) as the message id. Matches `WAWebHandleMsgReceiptParser` m() branch.
    #[tokio::test]
    async fn test_aggregated_by_message_receipt_fans_out_per_user() {
        let (client, collector) = setup_client_with_collector().await;

        let node = node_to_arc(
            NodeBuilder::new("receipt")
                .attr("from", "120363000000000001@g.us")
                .attr("id", "STANZA-AGG-XYZ")
                .attr("t", "1700000000")
                .children([NodeBuilder::new("participants")
                    .attr("message_id", "REAL-MSG-ID")
                    .children([
                        NodeBuilder::new("user")
                            .attr("jid", "99000000000001@lid")
                            .attr("t", "1700000001")
                            .attr("type", "delivery")
                            .build(),
                        NodeBuilder::new("user")
                            .attr("jid", "99000000000002@lid")
                            .attr("t", "1700000002")
                            .attr("type", "read")
                            .build(),
                        NodeBuilder::new("user")
                            .attr("jid", "99000000000003@lid")
                            .attr("t", "1700000003")
                            .attr("type", "inactive")
                            .build(),
                    ])
                    .build()])
                .build(),
        );
        client.handle_receipt(node).await;

        let events = collector.events();
        let receipts: Vec<_> = events
            .iter()
            .filter_map(|e| match &**e {
                Event::Receipt(r) => Some(r),
                _ => None,
            })
            .collect();
        assert_eq!(receipts.len(), 3, "must dispatch one event per <user>");
        for r in &receipts {
            assert_eq!(
                r.message_ids,
                vec!["REAL-MSG-ID"],
                "fan-out events must use participants.message_id, not stanza id"
            );
            assert_eq!(r.source.chat.user, "120363000000000001");
        }
        assert_eq!(receipts[0].r#type, ReceiptType::Delivered);
        assert_eq!(receipts[0].source.sender.user, "99000000000001");
        assert_eq!(receipts[1].r#type, ReceiptType::Read);
        assert_eq!(receipts[2].r#type, ReceiptType::Inactive);
    }

    /// participant_pn must land in the Receipt event's sender_alt on both shapes.
    #[tokio::test]
    async fn test_receipt_threads_participant_pn_into_sender_alt() {
        let (client, collector) = setup_client_with_collector().await;

        // Aggregated shape: per-user participant_pn.
        client
            .handle_receipt(node_to_arc(
                NodeBuilder::new("receipt")
                    .attr("from", "120363000000000001@g.us")
                    .attr("id", "STANZA-PPN")
                    .attr("t", "1700000000")
                    .children([NodeBuilder::new("participants")
                        .attr("message_id", "MSG-PPN")
                        .children([NodeBuilder::new("user")
                            .attr("jid", "99000000000001@lid")
                            .attr("participant_pn", "15551234567@s.whatsapp.net")
                            .attr("type", "read")
                            .build()])
                        .build()])
                    .build(),
            ))
            .await;

        // Simple shape: receipt-level participant_pn.
        client
            .handle_receipt(node_to_arc(
                NodeBuilder::new("receipt")
                    .attr("from", "99000000000002@lid")
                    .attr("id", "STANZA-PPN-SIMPLE")
                    .attr("participant_pn", "15557654321@s.whatsapp.net")
                    .attr("t", "1700000000")
                    .build(),
            ))
            .await;

        let events = collector.events();
        let receipts: Vec<_> = events
            .iter()
            .filter_map(|e| match &**e {
                Event::Receipt(r) => Some(r),
                _ => None,
            })
            .collect();

        let agg = receipts
            .iter()
            .find(|r| r.message_ids.iter().any(|id| id == "MSG-PPN"))
            .expect("aggregated receipt dispatched");
        assert_eq!(
            agg.source.sender_alt.as_ref().expect("sender_alt set").user,
            "15551234567",
            "aggregated receipt must thread per-user participant_pn into sender_alt"
        );

        let simple = receipts
            .iter()
            .find(|r| r.message_ids.iter().any(|id| id == "STANZA-PPN-SIMPLE"))
            .expect("simple receipt dispatched");
        assert_eq!(
            simple
                .source
                .sender_alt
                .as_ref()
                .expect("sender_alt set")
                .user,
            "15557654321",
            "simple receipt must thread receipt-level participant_pn into sender_alt"
        );
    }

    #[tokio::test]
    async fn test_receipt_offline_attr_propagated() {
        let (client, collector) = setup_client_with_collector().await;

        // Drained from the offline queue: carries the `offline` attr.
        client
            .handle_receipt(node_to_arc(
                NodeBuilder::new("receipt")
                    .attr("from", "15551234567@s.whatsapp.net")
                    .attr("id", "OFFLINE-RCPT")
                    .attr("offline", "1")
                    .attr("t", "1700000000")
                    .build(),
            ))
            .await;

        // Live delivery: no `offline` attr.
        client
            .handle_receipt(node_to_arc(
                NodeBuilder::new("receipt")
                    .attr("from", "15551234567@s.whatsapp.net")
                    .attr("id", "LIVE-RCPT")
                    .attr("t", "1700000000")
                    .build(),
            ))
            .await;

        let events = collector.events();
        let receipts: Vec<_> = events
            .iter()
            .filter_map(|e| match &**e {
                Event::Receipt(r) => Some(r),
                _ => None,
            })
            .collect();

        let offline = receipts
            .iter()
            .find(|r| r.message_ids.iter().any(|id| id == "OFFLINE-RCPT"))
            .expect("offline receipt dispatched");
        assert!(
            offline.offline,
            "receipt with the offline attr sets offline=true"
        );

        let live = receipts
            .iter()
            .find(|r| r.message_ids.iter().any(|id| id == "LIVE-RCPT"))
            .expect("live receipt dispatched");
        assert!(
            !live.offline,
            "receipt without the offline attr sets offline=false"
        );
    }

    /// Missing per-user `t`: the fan-out event's timestamp falls back to
    /// the stanza-level `t` rather than collapsing to epoch zero (which
    /// was the previous behavior).
    #[tokio::test]
    async fn test_aggregated_user_missing_t_uses_stanza_timestamp() {
        let (client, collector) = setup_client_with_collector().await;

        let node = node_to_arc(
            NodeBuilder::new("receipt")
                .attr("from", "120363000000000001@g.us")
                .attr("id", "STANZA-AGG-NOT")
                .attr("t", "1700000000")
                .children([NodeBuilder::new("participants")
                    .attr("message_id", "REAL-MSG-NOT")
                    .children([NodeBuilder::new("user")
                        .attr("jid", "99000000000001@lid")
                        .attr("type", "delivery")
                        .build()])
                    .build()])
                .build(),
        );
        client.handle_receipt(node).await;

        let events = collector.events();
        let r = events
            .iter()
            .find_map(|e| match &**e {
                Event::Receipt(r) => Some(r),
                _ => None,
            })
            .expect("expected Receipt");
        let expected = wacore::time::from_secs(1700000000).expect("valid ts");
        assert_eq!(r.timestamp, expected);
    }

    /// Aggregated-by-type receipt: `<participants key="...">` without
    /// `message_id`. All users inherit the receipt-level type. Mirrors d() branch.
    #[tokio::test]
    async fn test_aggregated_by_type_receipt_uses_receipt_level_type() {
        let (client, collector) = setup_client_with_collector().await;

        let node = node_to_arc(
            NodeBuilder::new("receipt")
                .attr("from", "120363000000000001@g.us")
                .attr("id", "STANZA-KEY")
                .attr("type", "read")
                .attr("t", "1700000000")
                .children([NodeBuilder::new("participants")
                    .attr("key", "AGG-KEY")
                    .children([NodeBuilder::new("user")
                        .attr("jid", "99000000000001@lid")
                        .attr("t", "1700000001")
                        .build()])
                    .build()])
                .build(),
        );
        client.handle_receipt(node).await;

        let events = collector.events();
        let receipts: Vec<_> = events
            .iter()
            .filter_map(|e| match &**e {
                Event::Receipt(r) => Some(r),
                _ => None,
            })
            .collect();
        assert_eq!(receipts.len(), 1);
        assert_eq!(receipts[0].r#type, ReceiptType::Read);
        assert_eq!(receipts[0].message_ids, vec!["AGG-KEY"]);
    }

    /// `<list><item id=.../>` batched read receipt: all items plus the stanza
    /// id (appended last) must end up in `message_ids`. Pre-fix only the
    /// stanza id was kept.
    #[tokio::test]
    async fn test_simple_receipt_with_list_collects_all_ids() {
        let (client, collector) = setup_client_with_collector().await;

        let node = node_to_arc(
            NodeBuilder::new("receipt")
                .attr("from", "99000000000001@s.whatsapp.net")
                .attr("id", "MSG-A")
                .attr("type", "read")
                .attr("t", "1700000000")
                .children([NodeBuilder::new("list")
                    .children([
                        NodeBuilder::new("item").attr("id", "MSG-B").build(),
                        NodeBuilder::new("item").attr("id", "MSG-C").build(),
                    ])
                    .build()])
                .build(),
        );
        client.handle_receipt(node).await;

        let events = collector.events();
        let r = events
            .iter()
            .find_map(|e| match &**e {
                Event::Receipt(r) => Some(r),
                _ => None,
            })
            .expect("expected Receipt");
        // Stanza id is appended LAST per WAWebHandleMsgReceiptParser.
        assert_eq!(r.message_ids, vec!["MSG-B", "MSG-C", "MSG-A"]);
        assert_eq!(r.r#type, ReceiptType::Read);
    }

    /// Simple receipt without `<list>`: only the stanza id is in message_ids.
    #[tokio::test]
    async fn test_simple_receipt_without_list_uses_stanza_id() {
        let (client, collector) = setup_client_with_collector().await;

        let node = node_to_arc(
            NodeBuilder::new("receipt")
                .attr("from", "99000000000001@s.whatsapp.net")
                .attr("id", "SOLO-MSG")
                .attr("t", "1700000000")
                .build(),
        );
        client.handle_receipt(node).await;

        let events = collector.events();
        let r = events
            .iter()
            .find_map(|e| match &**e {
                Event::Receipt(r) => Some(r),
                _ => None,
            })
            .expect("expected Receipt");
        assert_eq!(r.message_ids, vec!["SOLO-MSG"]);
        assert_eq!(r.r#type, ReceiptType::Delivered);
    }

    /// Verify that receipt nodes use JID-typed attrs for `to` and `participant`,
    /// ensuring the NodeValue::Jid optimization is not accidentally regressed to to_string.
    #[test]
    fn test_receipt_node_uses_jid_attrs() {
        use wacore_binary::NodeValue;

        let chat_jid: Jid = "120363021033254949@g.us"
            .parse()
            .expect("test JID should be valid");
        let sender_jid: Jid = "15551234567@s.whatsapp.net"
            .parse()
            .expect("test JID should be valid");

        // Build a group receipt node using the same pattern as send_delivery_receipt
        let node = NodeBuilder::new("receipt")
            .attr("id", "MSG-123")
            .attr("to", chat_jid.clone())
            .attr("participant", sender_jid.clone())
            .build();

        // "to" must be stored as NodeValue::Jid, not NodeValue::String
        let to_attr = node.attrs.get("to").expect("receipt must have 'to' attr");
        assert!(
            matches!(to_attr, NodeValue::Jid(_)),
            "'to' attr should be JID-typed, got: {:?}",
            to_attr
        );
        assert_eq!(to_attr.to_jid().unwrap(), chat_jid);

        // "participant" must also be JID-typed
        let participant_attr = node
            .attrs
            .get("participant")
            .expect("group receipt must have 'participant' attr");
        assert!(
            matches!(participant_attr, NodeValue::Jid(_)),
            "'participant' attr should be JID-typed, got: {:?}",
            participant_attr
        );
        assert_eq!(participant_attr.to_jid().unwrap(), sender_jid);
    }

    fn jid(s: &str) -> Jid {
        s.parse().expect("test JID")
    }

    #[test]
    fn played_receipt_group_is_played_with_participant() {
        let node = build_played_receipt_node(
            &jid("123@g.us"),
            Some(&jid("456@s.whatsapp.net")),
            &["M1"],
            "100",
            false,
        );
        assert_eq!(node.tag, "receipt");
        assert_eq!(
            node.attrs.get("type").map(|v| v.as_str()).as_deref(),
            Some("played")
        );
        assert_eq!(
            node.attrs
                .get("participant")
                .and_then(|v| v.to_jid().map(|j| j.to_string()))
                .as_deref(),
            Some("456@s.whatsapp.net")
        );
    }

    #[test]
    fn played_receipt_dm_is_played_without_participant() {
        // WA Web drops `participant` in DMs (PlayedReceiptJob `r.isUser() ? null`).
        let node =
            build_played_receipt_node(&jid("456@s.whatsapp.net"), None, &["M1"], "100", false);
        assert_eq!(
            node.attrs.get("type").map(|v| v.as_str()).as_deref(),
            Some("played")
        );
        assert!(node.attrs.get("participant").is_none());
    }

    #[test]
    fn played_receipt_newsletter_is_played_self() {
        let node = build_played_receipt_node(&jid("123@newsletter"), None, &["M1"], "100", false);
        assert_eq!(
            node.attrs.get("type").map(|v| v.as_str()).as_deref(),
            Some("played-self")
        );
        assert!(node.attrs.get("participant").is_none());
    }

    #[test]
    fn played_receipt_extra_ids_go_into_list() {
        let node = build_played_receipt_node(
            &jid("456@s.whatsapp.net"),
            None,
            &["M1", "M2", "M3"],
            "100",
            false,
        );
        assert_eq!(
            node.attrs.get("id").map(|v| v.as_str()).as_deref(),
            Some("M1")
        );
        let list = node
            .get_optional_child("list")
            .expect("extra ids must produce a <list>");
        assert_eq!(list.children().map(|c| c.len()).unwrap_or(0), 2);
    }

    #[test]
    fn played_receipt_status_broadcast_carries_participant() {
        let node = build_played_receipt_node(
            &jid("status@broadcast"),
            Some(&jid("456@s.whatsapp.net")),
            &["M1"],
            "100",
            false,
        );
        assert_eq!(
            node.attrs.get("type").map(|v| v.as_str()).as_deref(),
            Some("played")
        );
        assert_eq!(
            node.attrs
                .get("participant")
                .and_then(|v| v.to_jid().map(|j| j.to_string()))
                .as_deref(),
            Some("456@s.whatsapp.net")
        );
    }

    #[test]
    fn played_receipt_broadcast_list_carries_participant() {
        let node = build_played_receipt_node(
            &jid("120363000000000001@broadcast"),
            Some(&jid("456@s.whatsapp.net")),
            &["M1"],
            "100",
            false,
        );
        assert_eq!(
            node.attrs.get("type").map(|v| v.as_str()).as_deref(),
            Some("played")
        );
        assert_eq!(
            node.attrs
                .get("participant")
                .and_then(|v| v.to_jid().map(|j| j.to_string()))
                .as_deref(),
            Some("456@s.whatsapp.net")
        );
    }

    #[test]
    fn read_receipt_dm_is_read_without_context() {
        let node = build_read_receipt_node(
            &jid("456@s.whatsapp.net"),
            None,
            &["M1"],
            "100",
            None,
            false,
        );
        assert_eq!(
            node.attrs.get("type").map(|v| v.as_str()).as_deref(),
            Some("read")
        );
        assert!(node.attrs.get("context").is_none());
        assert!(node.attrs.get("peer_participant_pn").is_none());
    }

    #[test]
    fn read_receipt_newsletter_is_read_self() {
        let node =
            build_read_receipt_node(&jid("123@newsletter"), None, &["M1"], "100", None, false);
        assert_eq!(
            node.attrs.get("type").map(|v| v.as_str()).as_deref(),
            Some("read-self")
        );
    }

    #[test]
    fn read_receipt_status_carries_context_and_peer_pn() {
        let pn = jid("559980000001@s.whatsapp.net");
        let node = build_read_receipt_node(
            &jid("status@broadcast"),
            Some(&jid("100000012345678@lid")),
            &["M1"],
            "100",
            Some(&pn),
            false,
        );
        assert_eq!(
            node.attrs.get("type").map(|v| v.as_str()).as_deref(),
            Some("read")
        );
        assert_eq!(
            node.attrs.get("context").map(|v| v.as_str()).as_deref(),
            Some("status")
        );
        assert_eq!(
            node.attrs
                .get("peer_participant_pn")
                .and_then(|v| v.to_jid().map(|j| j.to_string()))
                .as_deref(),
            Some("559980000001@s.whatsapp.net")
        );
    }

    fn offline_info(id: &str, chat: &str, sender: &str, is_group: bool) -> Arc<MessageInfo> {
        let mut info = info_with(chat, sender, is_group);
        info.id = id.to_string();
        info.is_offline = true;
        Arc::new(info)
    }

    #[test]
    fn aggregate_delivery_receipts_group_by_chat_author_and_type() {
        let group_chat = "120363000000000001@g.us";
        let mut peer = info_with(
            "5511999990000@s.whatsapp.net",
            "5511999990000@s.whatsapp.net",
            false,
        );
        peer.id = "M6".to_string();
        peer.source.is_from_me = true;
        peer.category = MessageCategory::Peer;

        let infos = vec![
            offline_info(
                "M1",
                "5511999990000@s.whatsapp.net",
                "5511999990000@s.whatsapp.net",
                false,
            ),
            offline_info(
                "M2",
                "5511999990000@s.whatsapp.net",
                "5511999990000@s.whatsapp.net",
                false,
            ),
            offline_info("M3", group_chat, "5511888880000@s.whatsapp.net", true),
            offline_info("M4", group_chat, "5511888880000@s.whatsapp.net", true),
            offline_info("M5", group_chat, "5511777770000@s.whatsapp.net", true),
            Arc::new(peer),
        ];

        let groups = group_delivery_receipts(&infos, true);

        // DM sender, group author A, group author B, and the peer-typed DM
        // must each get their own stanza; same (chat, author, type) coalesce.
        assert_eq!(groups.len(), 4);
        assert_eq!(groups[0].ids, vec!["M1", "M2"]);
        assert_eq!(groups[1].ids, vec!["M3", "M4"]);
        assert_eq!(groups[2].ids, vec!["M5"]);
        assert_eq!(groups[3].ids, vec!["M6"]);
        assert_eq!(
            delivery_receipt_type(groups[3].rep, true),
            Some("peer_msg"),
            "peer messages must not coalesce into the plain delivered group"
        );
    }

    #[test]
    fn aggregate_delivery_receipt_node_shape_and_ingest_roundtrip() {
        let infos = vec![
            offline_info(
                "M1",
                "120363000000000001@g.us",
                "5511888880000@s.whatsapp.net",
                true,
            ),
            offline_info(
                "M2",
                "120363000000000001@g.us",
                "5511888880000@s.whatsapp.net",
                true,
            ),
            offline_info(
                "M3",
                "120363000000000001@g.us",
                "5511888880000@s.whatsapp.net",
                true,
            ),
        ];
        let groups = group_delivery_receipts(&infos, true);
        assert_eq!(groups.len(), 1);

        let nodes = build_aggregate_delivery_receipt_nodes(
            groups[0].rep,
            &groups[0].ids,
            true,
            "1760000000",
        );
        assert_eq!(nodes.len(), 1);
        let node = &nodes[0];

        // WA Web sendAggregateReceipts: id = first, rest in <list><item>,
        // DELIVERY drops the type attr, t carries the flush timestamp.
        assert_eq!(node.tag, "receipt");
        assert_eq!(
            node.attrs.get("id").map(|v| v.as_str()).as_deref(),
            Some("M1")
        );
        assert_eq!(
            node.attrs.get("t").map(|v| v.as_str()).as_deref(),
            Some("1760000000")
        );
        assert!(node.attrs.get("type").is_none());
        assert_eq!(
            node.attrs.get("to").map(|v| v.as_str()).as_deref(),
            Some("120363000000000001@g.us")
        );
        assert_eq!(
            node.attrs.get("participant").map(|v| v.as_str()).as_deref(),
            Some("5511888880000@s.whatsapp.net")
        );

        // The shape must round-trip through our own ingest parser (the same
        // form WA Web sends us): list items first, stanza id appended last.
        let owned = node_to_arc(node.clone());
        let parsed = wacore::stanza::receipt::collect_simple_message_ids(owned.get(), "M1", false);
        assert_eq!(
            parsed,
            vec!["M2".to_string(), "M3".to_string(), "M1".to_string()]
        );
    }

    #[test]
    fn aggregate_delivery_receipt_chunks_at_256_ids() {
        let chat = "5511999990000@s.whatsapp.net";
        let infos: Vec<Arc<MessageInfo>> = (0..257)
            .map(|i| offline_info(&format!("M{i:03}"), chat, chat, false))
            .collect();
        let groups = group_delivery_receipts(&infos, true);
        assert_eq!(groups.len(), 1);

        let nodes = build_aggregate_delivery_receipt_nodes(
            groups[0].rep,
            &groups[0].ids,
            true,
            "1760000000",
        );
        assert_eq!(nodes.len(), 2, "257 ids must split into 256 + 1 stanzas");

        let first_list_len = nodes[0]
            .children()
            .and_then(|c| c.iter().find(|n| n.tag == "list"))
            .and_then(|l| l.children())
            .map(|items| items.len());
        assert_eq!(first_list_len, Some(255), "id attr + 255 list items = 256");
        assert_eq!(
            nodes[1].attrs.get("id").map(|v| v.as_str()).as_deref(),
            Some("M256")
        );
        assert!(
            nodes[1].children().is_none(),
            "a single-id chunk must not carry an empty <list>"
        );
    }

    #[tokio::test]
    async fn offline_receipt_buffer_protocol() {
        let backend = crate::test_utils::create_test_backend().await;
        let pm = Arc::new(
            PersistenceManager::new(backend)
                .await
                .expect("persistence manager should initialize"),
        );
        let (client, _rx) = Client::new(
            Arc::new(crate::runtime_impl::TokioRuntime),
            pm,
            Arc::new(crate::transport::mock::MockTransportFactory::new()),
            Arc::new(MockHttpClient),
            None,
        )
        .await;

        // Offline messages buffer instead of sending 1:1.
        let info = offline_info(
            "OFF1",
            "5511999990000@s.whatsapp.net",
            "5511999990000@s.whatsapp.net",
            false,
        );
        client.ack_received_message(&info);
        let info2 = offline_info(
            "OFF2",
            "5511999990000@s.whatsapp.net",
            "5511999990000@s.whatsapp.net",
            false,
        );
        client.ack_received_message(&info2);
        assert_eq!(
            client.offline_receipt_buffer.lock().expect("buffer").len(),
            2
        );

        // A live (non-offline) message never touches the buffer.
        let mut live = info_with(
            "5511999990000@s.whatsapp.net",
            "5511999990000@s.whatsapp.net",
            false,
        );
        live.id = "LIVE1".to_string();
        client.ack_received_message(&Arc::new(live));
        assert_eq!(
            client.offline_receipt_buffer.lock().expect("buffer").len(),
            2
        );

        // The completion flag alone is NOT enough to go 1:1: during a
        // deferred drain-to-live transition the flag is set while the batcher
        // stays active, and receipts must keep buffering (their SKDM state
        // may still be cache-only until the deferred flush).
        client
            .offline_sync_completed
            .store(true, std::sync::atomic::Ordering::Release);
        let deferred = offline_info(
            "OFF2B",
            "5511999990000@s.whatsapp.net",
            "5511999990000@s.whatsapp.net",
            false,
        );
        assert!(client.try_buffer_offline_receipt(&deferred));
        assert_eq!(
            client.offline_receipt_buffer.lock().expect("buffer").len(),
            3
        );

        // Once the batcher goes live too, late offline receipts fall back to
        // 1:1 instead of stranding in the buffer (the exact race this guards).
        client.enter_live_mode_for_tests();
        let late = offline_info(
            "OFF3",
            "5511999990000@s.whatsapp.net",
            "5511999990000@s.whatsapp.net",
            false,
        );
        assert!(!client.try_buffer_offline_receipt(&late));
        assert_eq!(
            client.offline_receipt_buffer.lock().expect("buffer").len(),
            3
        );

        // Flush drains everything and releases the backing capacity, so no
        // memory is held between offline windows.
        client.flush_offline_receipts();
        {
            let buffer = client.offline_receipt_buffer.lock().expect("buffer");
            assert!(buffer.is_empty());
            assert_eq!(
                buffer.capacity(),
                0,
                "drained buffer must not retain capacity"
            );
        }

        // Teardown straggler: a receipt buffered after disconnect()'s drain
        // (flag still false on the next connection) must be dropped by the
        // connection-state reset instead of leaking into the next
        // connection's aggregate flush; the server redelivers its message.
        client
            .offline_sync_completed
            .store(false, std::sync::atomic::Ordering::Release);
        let straggler = offline_info(
            "OFF4",
            "5511999990000@s.whatsapp.net",
            "5511999990000@s.whatsapp.net",
            false,
        );
        assert!(client.try_buffer_offline_receipt(&straggler));
        client.clear_offline_receipt_buffer();
        assert!(
            client
                .offline_receipt_buffer
                .lock()
                .expect("buffer")
                .is_empty(),
            "connection reset must drop stale buffered receipts"
        );
    }
}