jmap-chat-server 0.6.0

JMAP Chat extension method handlers — backend-agnostic, plugs into jmap-server Dispatcher
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
//! Message/* method handlers (draft-atwood-jmap-chat-00 §Message).
//!
//! # Wire-shape contract
//!
//! Every `handle_*` function in this module conforms to the canonical JMAP
//! method shape. The `args: serde_json::Value` parameter MUST be a JSON
//! Object whose fields match the corresponding RFC 8620 §5 method shape
//! (`/get` → §5.1, `/changes` → §5.2, `/set` → §5.3,
//! `/query` → §5.5, `/queryChanges` → §5.6), with the type-specific
//! arguments defined by draft-atwood-jmap-chat-00 §Message. The
//! returned `Value` is the corresponding method-response object per the
//! same section refs.
//!
//! The returned `HandlerOutput::extra_invocations` carries any invocations
//! that this handler injected into the request stream (RFC 8620 §6.3);
//! for the handlers in this module the vector is **always empty**.
//!
//! Each handler returns `Err(JmapError)` for method-level failures (RFC 8620
//! §3.6.2 and §5):
//!
//! - every handler: `accountNotFound`, `invalidArguments`, `serverFail`;
//! - `/get`, `/set`: `requestTooLarge` past `maxObjectsInGet` /
//!   `maxObjectsInSet`;
//! - `/set`: `stateMismatch`;
//! - `/changes`, `/queryChanges`: `cannotCalculateChanges`;
//! - `/queryChanges`: `tooManyChanges`;
//! - `/query`, `/queryChanges`: `unsupportedFilter`;
//! - `/query`: `unsupportedSort`, `anchorNotFound`.
//!
//! Per-target failures inside `/set` (including the `slow_mode_check`
//! `rateLimit` and reaction-patch `invalidPatch` paths) surface in the
//! `notCreated` / `notUpdated` / `notDestroyed` maps within `Ok((Value, ...))`,
//! not as `Err`.

use jmap_chat_types::{
    Attachment, AttachmentCreate, BROADCAST_MENTION_SCOPES, BroadcastMention, Chat, DeliveryState,
    Mention, Message, MessageAction, PresenceStatus, ReadPosition, Space,
};
use jmap_chat_types::{Filter, MessageComparator, MessageFilter, MessageFilterCondition};
use jmap_types::{Id, JmapError, PatchObject, UTCDate};
use serde::Deserialize;
use serde_json::{Map, Value, json};

use crate::chat::record_unread_count_changes;
use crate::outbound::{OutboundEvent, ReactionAction};
use crate::{ChatBackend, ChatLimits};
use jmap_server::{BackendSetError, SetError, SetErrorType};
use std::collections::{BTreeMap, HashMap, HashSet};
use subtle::ConstantTimeEq;

use crate::helpers::{
    PropType, check_metadata_entry, create_metadata, is_metadata_key, mistyped_create_props,
};
use crate::helpers::{
    SetAccumulators, default_sort, enforce_max_objects_in_get, enforce_max_objects_in_set,
    extract_account_id, filter_properties, finalize_set_response, iso8601_before, not_found_json,
    now_utc_string, optional_arg, reject_unsupported_sort, serialize_value, strip_read_only_patch,
};
use crate::helpers::{parents_first, resolve_entry_refs, resolved_create};
use jmap_server::{
    HandlerOutput, MetadataProjection, QueryParams, backend_set_error_value, bool_arg, filter_arg,
    is_client_updatable, query_anchor_args, reject_server_set, server_fail_from_backend,
    server_fail_value_from_backend,
};

// ---------------------------------------------------------------------------
// Message/get
// ---------------------------------------------------------------------------

/// Handle a `Message/get` method call (draft-atwood-jmap-chat-00 §Message).
///
/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
/// `ids`, optional `properties`); the returned `Value` is the §5.1
/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
///
/// `using` is the request's capability list (pass
/// [`jmap_server::CallContext::using`]). When the backend lists Message for
/// draft-ietf-jmap-metadata-05 ([`JmapAccounts::metadata_info`](jmap_server::JmapAccounts::metadata_info)),
/// `metadata` is returned as an object, by default only with
/// `urn:ietf:params:jmap:metadata` in `using`, and with that capability
/// `properties` may hold `metadata/<namespace>` subselectors (-05 §2,
/// §3.1); see
/// [`jmap_server::MetadataProjection`].
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
pub async fn handle_message_get<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
    using: &[String],
) -> Result<HandlerOutput, JmapError> {
    let (account_id, mut args) = extract_account_id(args)?;

    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-dtpe).
    if !backend
        .account_exists(caller, &account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?
    {
        return Err(JmapError::account_not_found());
    }
    enforce_max_objects_in_get(&args, backend.max_objects_in_get(caller, &account_id))?;

    let ids: Option<Vec<Id>> = match args.remove("ids") {
        None | Some(Value::Null) => None,
        Some(v) => Some(
            serde_json::from_value(v)
                .map_err(|_| JmapError::invalid_arguments("ids must be an Id array"))?,
        ),
    };

    // RFC 8620 §5.1: when `properties` is specified, return only those fields
    // (plus `id` which is always included). `None` means return all fields.
    let properties: Option<Vec<String>> = match args.remove("properties") {
        None | Some(Value::Null) => None,
        Some(v) => Some(
            serde_json::from_value(v)
                .map_err(|_| JmapError::invalid_arguments("properties must be a string array"))?,
        ),
    };

    let projection = MetadataProjection::new(
        properties.as_deref(),
        true,
        using,
        backend
            .metadata_info::<Message>(caller, &account_id)
            .as_ref(),
    )?;

    let ids_slice = ids.as_deref();
    let (fetched, mut not_found) = backend
        .get_objects::<Message>(caller, &account_id, ids_slice, properties.as_deref())
        .await
        .map_err(|e| server_fail_from_backend(&e))?;

    // draft-atwood-jmap-chat-00 §Message/query (jmap-chat-spec 77c3474
    // L1301): "messages in channels the caller cannot view SHOULD be
    // omitted" from `Message/get`; done by choice. A hidden
    // message is reported like a missing one: a requested id goes to
    // notFound, and a full fetch drops it (RFC 8620 §5.1 notFound lists
    // only requested ids).
    let mut viewable: HashMap<Id, bool> = HashMap::new();
    let mut list = Vec::with_capacity(fetched.len());
    for msg in fetched {
        let visible = match viewable.get(&msg.chat_id) {
            Some(&v) => v,
            None => {
                let v = backend
                    .may_view_chat(caller, &account_id, &msg.chat_id)
                    .await
                    .map_err(|e| server_fail_from_backend(&e))?;
                viewable.insert(msg.chat_id.clone(), v);
                v
            }
        };
        if visible {
            list.push(msg);
        } else if ids_slice.is_some() {
            not_found.push(msg.id);
        }
    }

    // Edit-history retention gate (draft-atwood-jmap-chat-00 commit
    // `0783fc4` + §Message editHistory). When the backend does not
    // retain edit history, the `editHistory` field MUST be omitted
    // from every returned Message. Setting `edit_history = None`
    // here causes serde's `skip_serializing_if = "Option::is_none"`
    // to collapse it on the wire, satisfying the spec MUST.
    //
    // `Message/changes` per RFC 8620 §5.2 returns id arrays only
    // (no Message objects), so the spec's "omit from /changes" has
    // no wire-level effect — only `Message/get` needs this gate.
    if !backend.retains_edit_history() {
        for msg in list.iter_mut() {
            msg.edit_history = None;
        }
    }

    let wants_counts = properties.as_ref().is_none_or(|p| {
        p.iter()
            .any(|k| k == "replyCount" || k == "unreadReplyCount")
    });
    if wants_counts && backend.limits(caller, &account_id).supports_threads {
        fill_reply_counts(backend, caller, &account_id, &mut list).await?;
    }

    let state = backend
        .get_state::<Message>(caller, &account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?;

    let prop_set: Option<HashSet<&str>> = properties.as_ref().map(|props| {
        let mut set: HashSet<&str> = props.iter().map(|s| s.as_str()).collect();
        set.insert("id");
        set
    });
    let list_json: Vec<Value> = list
        .iter()
        .map(|obj| {
            let val = serialize_value(obj)?;
            let mut out = match &prop_set {
                Some(set) => filter_properties(&val, set),
                None => val.clone(),
            };
            projection.apply(&val, &mut out);
            Ok(out)
        })
        .collect::<Result<Vec<_>, JmapError>>()?;

    Ok(HandlerOutput::new(json!({
        "accountId": account_id.as_ref(),
        "state": state.as_ref(),
        "list": list_json,
        "notFound": not_found_json(&not_found),
    })))
}

/// Set the server-computed thread counts on each Message in `list`
/// (draft-atwood-jmap-chat-00 §Message, used when `supportsThreads` is
/// `true`).
///
/// `replyCount`: "Count of messages in this chat with `replyTo` equal to
/// this message's `id`." `unreadReplyCount`, only on a thread root
/// (`threadRootId` absent): "Count of replies to this message received
/// after the owner's `ReadPosition.lastReadMessageId` in this Chat".
/// Message ids are ULIDs "lexicographically ordered by time" (§Message
/// IDs), so a reply counts as unread when its `id` sorts after
/// `lastReadMessageId`, or always when that is absent, and the owner did
/// not send it (`senderId` is not the accountId), as for
/// `Chat.unreadCount`.
// ponytail: scans every Message and ReadPosition in the account per
// call (O(messages) per Message/get); a backend with many messages
// needs a reply-count index behind a ChatBackend hook.
async fn fill_reply_counts<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    list: &mut [Message],
) -> Result<(), JmapError> {
    if list.is_empty() {
        return Ok(());
    }
    let (all, _) = backend
        .get_objects::<Message>(caller, account_id, None, None)
        .await
        .map_err(|e| server_fail_from_backend(&e))?;
    let (positions, _) = backend
        .get_objects::<ReadPosition>(caller, account_id, None, None)
        .await
        .map_err(|e| server_fail_from_backend(&e))?;
    for msg in list.iter_mut() {
        let replies = || {
            all.iter()
                .filter(|r| r.chat_id == msg.chat_id && r.reply_to.as_ref() == Some(&msg.id))
        };
        let reply_count = replies().count() as u64;
        msg.unread_reply_count = if msg.thread_root_id.is_none() {
            let last_read = positions
                .iter()
                .find(|p| p.chat_id == msg.chat_id)
                .and_then(|p| p.last_read_message_id.as_ref());
            let unread = replies()
                .filter(|r| r.sender_id != *account_id)
                .filter(|r| last_read.is_none_or(|l| r.id.as_ref() > l.as_ref()))
                .count();
            Some(unread as u64)
        } else {
            None
        };
        msg.reply_count = Some(reply_count);
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Message/changes
// ---------------------------------------------------------------------------

/// Handle a `Message/changes` method call (draft-atwood-jmap-chat-00 §Message).
///
/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
/// `sinceState`, optional `maxChanges`); the returned `Value` is the
/// §5.2 `/changes` response shape (`accountId`, `oldState`, `newState`,
/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
///
/// `using` is the request's capability list (pass
/// [`jmap_server::CallContext::using`]); with
/// `urn:ietf:params:jmap:metadata` the request may set
/// draft-ietf-jmap-metadata-05 §3.3 `ignoreMetadataOnlyChanges`, and
/// without it metadata-only changes are left out (-05 §3).
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
pub async fn handle_message_changes<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
    using: &[String],
) -> Result<HandlerOutput, JmapError> {
    jmap_server::handle_changes::<Message, B>(backend, caller, args, using).await
}

// ---------------------------------------------------------------------------
// Message/query
// ---------------------------------------------------------------------------

/// Handle a `Message/query` method call (draft-atwood-jmap-chat-00 §Message).
///
/// `args` is the RFC 8620 §5.5 `/query` request shape (`accountId`, optional
/// `filter`, optional `sort`, optional `position` / `anchor` /
/// `anchorOffset`, optional `limit`, optional `calculateTotal`); the
/// returned `Value` is the §5.5 `/query` response shape (`accountId`,
/// `queryState`, `canCalculateChanges`, `position`, `ids`, optional
/// `total`, optional `limit`).
///
/// Unknown filter clauses and sort properties are refused with
/// `unsupportedFilter` / `unsupportedSort` (RFC 8620 §5.5).
///
/// `using` is the request's capability list (pass
/// [`jmap_server::CallContext::using`]); without
/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-05 §3.6
/// filter condition is `unsupportedFilter` (-05 §3). A JMAP Search
/// `where` (crate-jmap docs/specs/jmap-search.md) needs
/// `urn:ietf:params:jmap:search` in `using` and `"Message"` in
/// [`ChatSettings::search_capability`](crate::ChatSettings::search_capability), else `unsupportedFilter`; it is
/// checked with [`jmap_search::check_where_filter`] and makes
/// `canCalculateChanges` `false`. It does not lift the `chatId` /
/// `hasMention: true` rule.
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
pub async fn handle_message_query<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
    using: &[String],
) -> Result<HandlerOutput, JmapError> {
    jmap_server::reject_metadata_filter_arg(
        &args,
        jmap_chat_types::MessageFilterCondition::has_metadata_condition,
        using,
    )?;
    let (account_id, mut args) = extract_account_id(args)?;

    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-dtpe).
    if !backend
        .account_exists(caller, &account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?
    {
        return Err(JmapError::account_not_found());
    }

    let searched =
        check_message_search(backend, caller, &account_id, args.get("filter"), using).await?;

    let calculate_total: bool = bool_arg(&args, "calculateTotal", false);

    let limit: Option<u64> = match args.remove("limit") {
        None | Some(Value::Null) => None,
        Some(v) => match v.as_u64() {
            Some(n) => Some(n),
            None => {
                return Err(JmapError::invalid_arguments(format!(
                    "limit: expected a non-negative integer, got {}",
                    jmap_server::json_type_name(&v)
                )));
            }
        },
    };

    let position: i64 = match args.remove("position") {
        None | Some(Value::Null) => 0,
        Some(v) => v.as_i64().ok_or_else(|| {
            JmapError::invalid_arguments(format!(
                "position: expected an integer, got {}",
                jmap_server::json_type_name(&v)
            ))
        })?,
    };

    let (anchor, anchor_offset) = query_anchor_args(&args)?;

    reject_unsupported_sort::<MessageComparator>(args.get("sort"))?;
    let filter: Option<MessageFilter> = filter_arg(&mut args)?;

    let supports_threads = backend.limits(caller, &account_id).supports_threads;
    let top = check_message_filter(filter.as_ref(), supports_threads)?;

    // §Message/query: "Default sort: `receivedAt` ascending when `chatId`
    // is present; `receivedAt` descending when `chatId` is absent."
    let in_one_chat = top.chat_id.is_some();
    default_sort(
        &mut args,
        json!([{ "property": "receivedAt", "isAscending": in_one_chat }]),
    );
    let sort: Option<Vec<MessageComparator>> = optional_arg(&mut args, "sort", || {
        JmapError::invalid_arguments("sort must be an array")
    })?;

    // draft-atwood-jmap-chat-00 §Message/query (jmap-chat-spec 77c3474
    // L1301): "messages in channels the caller cannot view SHOULD be
    // omitted"; done by choice. A query scoped to one Chat the
    // caller cannot view matches nothing; a query without `chatId` relies
    // on the backend (see `ChatAccessPolicy::may_view_chat`).
    let hidden = match top.chat_id.as_ref() {
        Some(chat_id) => !backend
            .may_view_chat(caller, &account_id, chat_id)
            .await
            .map_err(|e| server_fail_from_backend(&e))?,
        None => false,
    };

    let result = backend
        .query_objects::<Message>(
            caller,
            &account_id,
            QueryParams::new()
                .filter(filter.as_ref())
                .sort(sort.as_deref())
                .limit(limit)
                .position(position)
                .anchor(anchor.as_ref())
                .anchor_offset(anchor_offset),
        )
        .await
        .map_err(JmapError::from)?;
    let (ids, position, total) = if hidden {
        (Vec::new(), 0, Some(0))
    } else {
        (result.ids, result.position, result.total)
    };

    let mut resp = json!({
        "accountId": account_id.as_ref(),
        "queryState": result.query_state.as_ref(),
        "canCalculateChanges": result.can_calculate_changes && !searched,
        "position": position,
        "ids": ids.iter().map(|id| id.as_ref()).collect::<Vec<_>>(),
    });
    if calculate_total && let Some(t) = total {
        resp["total"] = json!(t);
    }

    Ok(HandlerOutput::new(resp))
}

/// Check the JMAP Search `where` of the undecoded Message `filter`
/// against `using` and [`ChatSettings::search_capability`](crate::ChatSettings::search_capability), and return
/// whether there was one (crate-jmap docs/specs/jmap-search.md §Errors,
/// §Opting In a Data Type). The capability is read only for a filter with
/// `where`.
///
/// # Errors
///
/// As [`jmap_search::check_where_filter`] for the `"Message"` data type,
/// and `serverFail` when the backend fails.
async fn check_message_search<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    filter: Option<&Value>,
    using: &[String],
) -> Result<bool, JmapError> {
    if !filter.is_some_and(jmap_search::filter_uses_where) {
        return Ok(false);
    }
    let cap = backend
        .search_capability(caller, account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?;
    jmap_search::check_where_filter(filter, "Message", using, cap.as_ref())
}

/// Apply the draft-atwood-jmap-chat-00 §Message/query `unsupportedFilter`
/// refusals and return the top-level filter condition.
///
/// Shared by `Message/query` and `Message/queryChanges`, whose filter is
/// that of the original query (RFC 8620 §5.6).
///
/// # Errors
///
/// `unsupportedFilter` when the filter is not a top-level condition with
/// `chatId` or `hasMention: true` ("Servers MUST return an
/// `unsupportedFilter` error for any request that omits `chatId` without
/// also including `hasMention: true`"), sets `text` ("Servers that do not
/// support full-text search MUST return `unsupportedFilter`"), or sets
/// `threadRootId` while `supports_threads` is `false` ("Valid only when
/// `supportsThreads` is `true`; otherwise servers MUST return
/// `unsupportedFilter`").
///
/// ponytail: no backend implements `text`, so it is refused for every
/// backend; a backend that adds it needs a ChatBackend capability hook to
/// lift the refusal.
fn check_message_filter(
    filter: Option<&MessageFilter>,
    supports_threads: bool,
) -> Result<&MessageFilterCondition, JmapError> {
    let unsupported = |description: &str| {
        let mut err = JmapError::unsupported_filter();
        err.description = Some(description.to_owned());
        err
    };
    let Some(Filter::Condition(c)) = filter else {
        return Err(unsupported(
            "the filter must be a single condition with chatId or hasMention: true",
        ));
    };
    if c.chat_id.is_none() && c.has_mention != Some(true) {
        return Err(unsupported(
            "the filter must set chatId or hasMention: true",
        ));
    }
    if c.text.is_some() {
        return Err(unsupported("full-text search (text) is not supported"));
    }
    if c.thread_root_id.is_some() && !supports_threads {
        return Err(unsupported(
            "threadRootId is valid only when supportsThreads is true",
        ));
    }
    Ok(c)
}

// ---------------------------------------------------------------------------
// Message/queryChanges
// ---------------------------------------------------------------------------

/// Handle a `Message/queryChanges` method call (draft-atwood-jmap-chat-00 §Message).
///
/// `args` is the RFC 8620 §5.6 `/queryChanges` request shape (`accountId`,
/// optional `filter`, optional `sort`, `sinceQueryState`, optional
/// `maxChanges`, optional `upToId`, optional `calculateTotal`); the
/// returned `Value` is the §5.6 `/queryChanges` response shape
/// (`accountId`, `oldQueryState`, `newQueryState`, optional `total`,
/// `removed`, `added`).
///
/// A query scoped to one Chat the caller cannot view fails with
/// `cannotCalculateChanges`, so the client re-runs `Message/query`, which
/// returns nothing for that Chat (see [`handle_message_query`]).
///
/// `using` is the request's capability list (pass
/// [`jmap_server::CallContext::using`]); without
/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-05 §3.6
/// filter condition is `unsupportedFilter` (-05 §3). A filter with a
/// JMAP Search `where` is checked as for [`handle_message_query`] and then
/// answered with `cannotCalculateChanges` (jmap-search §Query Changes).
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
pub async fn handle_message_query_changes<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    mut args: Value,
    using: &[String],
) -> Result<HandlerOutput, JmapError> {
    jmap_server::reject_metadata_filter_arg(
        &args,
        jmap_chat_types::MessageFilterCondition::has_metadata_condition,
        using,
    )?;
    // RFC 8620 §5.6: the `filter` and `sort` are those of the original
    // query, so the §Message/query default sort applies here too.
    let chat_id = args
        .get("filter")
        .and_then(|f| f.get("chatId"))
        .and_then(Value::as_str)
        .map(Id::from);
    if let Value::Object(map) = &mut args {
        default_sort(
            map,
            json!([{ "property": "receivedAt", "isAscending": chat_id.is_some() }]),
        );
    }
    reject_unsupported_sort::<MessageComparator>(args.get("sort"))?;

    // RFC 8620 §5.6: the filter is that of the original query, so the
    // §Message/query `unsupportedFilter` refusals apply here too.
    let account_id = args.get("accountId").and_then(Value::as_str).map(Id::from);
    if let Some(account_id) = &account_id {
        // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-dtpe), before the
        // may_view_chat read below.
        if !backend
            .account_exists(caller, account_id)
            .await
            .map_err(|e| server_fail_from_backend(&e))?
        {
            return Err(JmapError::account_not_found());
        }
        let mut probe = serde_json::Map::new();
        if let Some(f) = args.get("filter") {
            probe.insert("filter".into(), f.clone());
        }
        let filter: Option<MessageFilter> = filter_arg(&mut probe)?;
        let supports_threads = backend.limits(caller, account_id).supports_threads;
        check_message_filter(filter.as_ref(), supports_threads)?;
        // jmap-search §Query Changes: "Servers MAY return
        // `cannotCalculateChanges` for any `/queryChanges` call whose
        // filter uses `where`".
        if check_message_search(backend, caller, account_id, args.get("filter"), using).await? {
            return Err(JmapError::cannot_calculate_changes());
        }
    }

    // §Message/query (jmap-chat-spec 77c3474 L1301): "messages in channels
    // the caller cannot view SHOULD be omitted"; by choice, changes to such
    // a Chat's messages are not reported.
    if let (Some(account_id), Some(chat_id)) = (account_id, chat_id)
        && !backend
            .may_view_chat(caller, &account_id, &chat_id)
            .await
            .map_err(|e| server_fail_from_backend(&e))?
    {
        return Err(JmapError::cannot_calculate_changes());
    }
    jmap_server::handle_query_changes::<Message, B>(backend, caller, args).await
}

// ---------------------------------------------------------------------------
// BroadcastMention validation
// ---------------------------------------------------------------------------

/// Validate broadcast mentions against spec §4.4.1 / §4.16 constraints.
///
/// Returns the SetError value on failure, None on success. §BroadcastMention:
/// "Servers MUST reject a BroadcastMention with an unrecognized `scope`
/// value; in `Message/set` the rejection is an `invalidProperties` SetError
/// naming `broadcastMentions`." A missing or non-string `scope` takes the
/// §Input Validation default, which is the same SetError.
fn validate_broadcast_mentions(broadcast_mentions: &[serde_json::Value]) -> Option<Value> {
    let invalid_properties = |desc: String| {
        json!({
            "type": "invalidProperties",
            "properties": ["broadcastMentions"],
            "description": desc,
        })
    };
    for (i, bm) in broadcast_mentions.iter().enumerate() {
        // scope validation
        let scope = match bm.get("scope").and_then(|v| v.as_str()) {
            Some(s) => s,
            None => {
                return Some(invalid_properties(format!(
                    "broadcastMentions[{i}]: missing or non-string scope"
                )));
            }
        };
        if !BROADCAST_MENTION_SCOPES.contains(&scope) {
            return Some(invalid_properties(format!(
                "broadcastMentions[{i}]: unrecognized scope \"{scope}\""
            )));
        }
    }
    None
}

// ---------------------------------------------------------------------------
// Optional create properties
// ---------------------------------------------------------------------------

/// Default `bodyType` values that indicate an end-to-end encrypted body:
/// the one type draft-atwood-jmap-chat-00 §Message `body` names. A backend
/// adds others, such as `"application/mimi-fanout"`
/// (draft-atwood-jmap-chat-mimi-00 §MLS Messages), through
/// [`ChatLimits::encrypted_body_types`](crate::ChatLimits::encrypted_body_types).
pub const ENCRYPTED_BODY_TYPES: &[&str] = &["application/mls-ciphertext"];

/// Default `bodyType` values this server accepts, advertised as the
/// `supportedBodyTypes` capability (draft-atwood-jmap-chat-00
/// §Account-Level Capability Object). A backend lists other types through
/// [`ChatLimits::supported_body_types`](crate::ChatLimits::supported_body_types).
pub const SUPPORTED_BODY_TYPES: &[&str] = &[
    "text/plain",
    "text/markdown",
    "application/jmap-chat-rich",
    "application/mls-ciphertext",
];

/// draft-atwood-jmap-chat-00 §Fields Inside the Ciphertext: Message fields
/// that "MUST be empty or absent" when `bodyType` indicates an encrypted type.
const CIPHERTEXT_ONLY_FIELDS: [&str; 8] = [
    "mentions",
    "broadcastMentions",
    "attachments",
    "actions",
    "replyTo",
    "threadRootId",
    "topicId",
    "subject",
];

/// Check the create fields that `bodyType` requires to be empty: all of
/// [`CIPHERTEXT_ONLY_FIELDS`] when `body_type` is one of the account's
/// `encrypted` types (§Fields Inside the Ciphertext).
///
/// Returns every offending field, in [`CIPHERTEXT_ONLY_FIELDS`] order, for
/// an `invalidProperties` SetError "whose `properties` lists each such
/// field"; empty on success.
fn body_type_field_conflicts(
    obj: &Value,
    body_type: &str,
    encrypted: &[&str],
) -> Vec<&'static str> {
    if !encrypted.contains(&body_type) {
        return Vec::new();
    }
    let non_empty = |key: &str| {
        obj.get(key)
            .is_some_and(|v| !(v.is_null() || v == "" || v.as_array().is_some_and(Vec::is_empty)))
    };
    CIPHERTEXT_ONLY_FIELDS
        .into_iter()
        .filter(|&k| non_empty(k))
        .collect()
}

/// Check a `Message/set` edit `patch` of the stored `msg` against
/// `maxBodyBytes` and the encrypted-`bodyType` empty-field rule, which
/// apply to updates as well as creates.
///
/// draft-atwood-jmap-chat-00 §Account-Level Capability Object
/// `maxBodyBytes`: "in `Message/set` the rejection is a `tooLarge`
/// SetError." §Fields Inside the Ciphertext (jmap-chat-spec 77c3474
/// L1823): "Servers SHOULD reject a `Message/set` create or update that has
/// an encrypted `bodyType` and any of these fields non-empty"; this crate
/// performs the recommended rejection by choice. The field rule runs on the Message as it
/// would be after the patch, so a `bodyType`-only patch to an encrypted
/// type is rejected when the stored Message keeps such a field.
///
/// Returns the SetError, or `None` when the edit passes.
fn edit_limit_error(msg: &Message, patch: &Value, limits: &ChatLimits) -> Option<Value> {
    if let Some(body) = patch.get("body").and_then(Value::as_str)
        && u64::try_from(body.len()).map_or(true, |n| n > limits.max_body_bytes)
    {
        return Some(json!({
            "type": "tooLarge",
            "description": format!("body exceeds maxBodyBytes ({})", limits.max_body_bytes),
        }));
    }
    let mut merged = serde_json::to_value(msg).ok()?;
    if let (Some(dst), Some(src)) = (merged.as_object_mut(), patch.as_object()) {
        dst.extend(src.iter().map(|(k, v)| (k.clone(), v.clone())));
    }
    let body_type = merged.get("bodyType").and_then(Value::as_str)?.to_owned();
    let conflicts = body_type_field_conflicts(&merged, &body_type, limits.encrypted_body_types);
    (!conflicts.is_empty()).then(|| {
        json!({
            "type": "invalidProperties",
            "properties": conflicts,
            "description": format!("must be empty or absent when bodyType is {body_type}"),
        })
    })
}

/// Implementation-defined maximum byte length of `subject`
/// (draft-atwood-jmap-chat-00 §Input Validation).
const MAX_SUBJECT_BYTES: usize = 1024;

/// RFC 8620 §1.3 UnsignedInt upper bound, 2^53 - 1.
const MAX_UNSIGNED_INT: u64 = (1 << 53) - 1;

/// Parse the optional `Message/set` create properties `mentions`,
/// `broadcastMentions`, `actions`, `topicId`, `subject` and
/// `expiresAfterReadSeconds` from `obj`, applying the
/// draft-atwood-jmap-chat-00 §Input Validation checks, and return a
/// function that copies them onto a Message. An absent or `null`
/// property keeps the default. `broadcastMentions` must already have
/// passed [`validate_broadcast_mentions`].
///
/// On error, returns the wire name of the first offending property, for an
/// `invalidProperties` SetError.
fn apply_create_optionals(
    obj: &Value,
) -> Result<impl FnOnce(&mut Message) + Send + use<>, &'static str> {
    let get = |key: &str| obj.get(key).filter(|v| !v.is_null());
    let mentions = get("mentions")
        .map(|v| Vec::<Mention>::deserialize(v).map_err(|_| "mentions"))
        .transpose()?;
    let broadcast_mentions = get("broadcastMentions")
        .map(|v| Vec::<BroadcastMention>::deserialize(v).map_err(|_| "broadcastMentions"))
        .transpose()?;
    // §MessageAction: "Servers MUST store and forward MessageAction
    // records without inspection or transformation."
    let actions = get("actions")
        .map(|v| Vec::<MessageAction>::deserialize(v).map_err(|_| "actions"))
        .transpose()?;
    let topic_id = match get("topicId") {
        None => None,
        Some(v) => match v.as_str() {
            Some(s) if !s.is_empty() && s.len() <= 255 => Some(s.to_owned()),
            _ => return Err("topicId"),
        },
    };
    let subject = match get("subject") {
        None => None,
        Some(v) => match v.as_str() {
            Some(s) if topic_id.is_some() && s.len() <= MAX_SUBJECT_BYTES => Some(s.to_owned()),
            _ => return Err("subject"),
        },
    };
    let expires_after_read_seconds = match get("expiresAfterReadSeconds") {
        None => None,
        Some(v) => match v.as_u64() {
            Some(n) if n <= MAX_UNSIGNED_INT => Some(n),
            _ => return Err("expiresAfterReadSeconds"),
        },
    };
    Ok(move |msg: &mut Message| {
        if let Some(v) = mentions {
            msg.mentions = v;
        }
        if let Some(v) = broadcast_mentions {
            msg.broadcast_mentions = v;
        }
        if let Some(v) = actions {
            msg.actions = v;
        }
        if topic_id.is_some() {
            msg.topic_id = topic_id;
        }
        if subject.is_some() {
            msg.subject = subject;
        }
        if expires_after_read_seconds.is_some() {
            msg.expires_after_read_seconds = expires_after_read_seconds;
        }
    })
}

/// Build a `Message/set` create's `attachments` from its wire value `v`
/// for target Chat `chat`; `Err` holds the SetError value.
///
/// draft-atwood-jmap-chat-00 §Denial of Service: "Enforce
/// `maxAttachmentsPerMessage` at creation and update time"; it is checked
/// first, so no entry is resolved past the cap, and is `tooLarge`, the
/// error §Account-Level Capability Object names for `maxBodyBytes`. An
/// entry with `filenodeId` goes to [`ChatResolvers::filenode_attachment`](crate::ChatResolvers::filenode_attachment)
/// (draft-atwood-jmap-chat-filenode-00 §filenodeId). Any other entry, or
/// one the hook leaves unresolved, must carry every Attachment field. Each
/// result must pass [`valid_attachment`]. A malformed entry is
/// `invalidProperties` naming `attachments`.
async fn create_attachments<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    limits: &ChatLimits,
    chat: &Chat,
    v: &Value,
) -> Result<Vec<Attachment>, Value> {
    let invalid = || json!({ "type": "invalidProperties", "properties": ["attachments"] });
    let entries = v.as_array().ok_or_else(invalid)?;
    if u64::try_from(entries.len()).map_or(true, |n| n > limits.max_attachments_per_message) {
        return Err(json!({
            "type": "tooLarge",
            "description": format!(
                "attachments exceed maxAttachmentsPerMessage ({})",
                limits.max_attachments_per_message
            ),
        }));
    }
    let mut attachments = Vec::with_capacity(entries.len());
    for entry in entries {
        let requested = AttachmentCreate::deserialize(entry).map_err(|_| invalid())?;
        let filled = if requested.filenode_id.is_some() {
            match backend
                .filenode_attachment(caller, account_id, chat, &requested)
                .await
            {
                Ok(Ok(filled)) => filled,
                Ok(Err(set_err)) => return Err(serde_json::Value::from(&set_err)),
                Err(e) => return Err(server_fail_value_from_backend(&e)),
            }
        } else {
            None
        };
        let attachment = match filled {
            Some(a) => a,
            None => Attachment::deserialize(entry).map_err(|_| invalid())?,
        };
        if !valid_attachment(&attachment) {
            return Err(invalid());
        }
        attachments.push(attachment);
    }
    Ok(attachments)
}

/// draft-atwood-jmap-chat-00 §Attachment and §Input Validation:
/// `filename` holds no `/`, `\` or null byte and `contentType` is a
/// syntactically valid MIME type. `sha256` is lowercase hex by its type.
///
/// `size` and `sha256` are checked against the blob in [`check_attachments`].
fn valid_attachment(a: &Attachment) -> bool {
    !a.filename.contains(['/', '\\', '\0']) && valid_media_type(&a.content_type)
}

/// Enforce the size limit and blob checks on a `Message/set` create's
/// `attachments` from [`create_attachments`]; `None` on success, else the
/// SetError value.
///
/// draft-atwood-jmap-chat-00 §Denial of Service: "Enforce `maxBodyBytes`
/// and `maxAttachmentBytes` at parse time, before any fetch or storage."
/// The limit is `tooLarge`, the error §Account-Level Capability Object
/// names for `maxBodyBytes`. Then each Attachment's `size` and `sha256` are
/// checked against [`ChatResolvers::attachment_blob`](crate::ChatResolvers::attachment_blob); a mismatch is
/// `invalidProperties` naming `attachments` (§Input Validation).
async fn check_attachments<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    limits: &ChatLimits,
    attachments: &[Attachment],
) -> Option<Value> {
    if attachments
        .iter()
        .any(|a| a.size > limits.max_attachment_bytes)
    {
        return Some(json!({
            "type": "tooLarge",
            "description": format!(
                "an attachment exceeds maxAttachmentBytes ({})",
                limits.max_attachment_bytes
            ),
        }));
    }
    for a in attachments {
        match backend
            .attachment_blob(caller, account_id, &a.blob_id)
            .await
        {
            Ok(Ok(None)) => {}
            Ok(Ok(Some(blob))) => {
                // Constant-time digest comparison (compliance tests §14.13:
                // "Verify that blob hash comparison uses constant-time
                // comparison").
                if blob.size != a.size || !bool::from(a.sha256.to_bytes().ct_eq(&blob.sha256)) {
                    return Some(json!({
                        "type": "invalidProperties",
                        "properties": ["attachments"],
                        "description": format!(
                            "attachment {} does not match the blob's size or sha256",
                            a.blob_id
                        ),
                    }));
                }
            }
            Ok(Err(set_err)) => return Some(serde_json::Value::from(&set_err)),
            Err(e) => return Some(server_fail_value_from_backend(&e)),
        }
    }
    None
}

/// RFC 2045 §5.1 `type "/" subtype`, each an RFC 2045 `token`.
///
/// ponytail: parameters after `;` are not parsed; add an RFC 2045
/// parameter parser if they ever need validating.
fn valid_media_type(s: &str) -> bool {
    let is_token = |t: &str| {
        !t.is_empty()
            && t.bytes()
                .all(|b| b.is_ascii_graphic() && !b"()<>@,;:\\\"/[]?=".contains(&b))
    };
    let essence = s.split(';').next().unwrap_or_default().trim();
    essence
        .split_once('/')
        .is_some_and(|(t, sub)| is_token(t) && is_token(sub))
}

// ---------------------------------------------------------------------------
// Message/set
// ---------------------------------------------------------------------------

/// Create the owner's ReadPosition for each Chat in `chat_ids` that has
/// none yet. draft-atwood-jmap-chat-00 §ReadPosition: "For direct and
/// group Chats, a ReadPosition is created when the first message is
/// delivered. For channel Chats, a ReadPosition is created when the
/// owner joins the containing Space." Called by `Message/set` and by
/// `Space/join` ([`crate::space::handle_space_join`]).
///
/// Best effort: the Messages are already stored, so a backend failure
/// here must not become a method-level error (RFC 8620 §3.6.2: "the
/// externally visible state of the server MUST NOT have changed if an
/// error is returned at the method level"). A record missed here is
/// created by the next delivery to that Chat. `alreadyExists` means a
/// concurrent delivery created it first (see the ReadPosition uniqueness
/// contract on `ChatStore::create_object`).
///
/// ponytail: does not look up the Chat's kind, so `Message/set` also
/// fills in a missing channel position (for example a channel added
/// after the owner joined). One full ReadPosition scan per `Message/set` call that created a
/// message; a backend with a `(account, chatId)` index can replace it.
pub(crate) async fn ensure_read_positions<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    mut chat_ids: Vec<Id>,
) {
    if chat_ids.is_empty() {
        return;
    }
    let Ok((existing, _)) = backend
        .get_objects::<ReadPosition>(caller, account_id, None, None)
        .await
    else {
        return;
    };
    chat_ids.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
    chat_ids.dedup();
    chat_ids.retain(|c| !existing.iter().any(|p| p.chat_id == *c));
    for chat_id in chat_ids {
        let _ = backend
            .create_object(caller, account_id, chat_id.as_ref(), |id: &Id| {
                ReadPosition::new(id.clone(), chat_id.clone())
            })
            .await;
    }
}

/// Find the Message in `chat_id` whose `senderMsgId` is `sender_msg_id`.
///
/// draft-atwood-jmap-chat-00 §Message: "Servers MUST maintain a durable
/// index of `senderMsgId` values per chat to support idempotent
/// delivery, `Peer/retract` lookup, and resolution of `replyTo` /
/// `threadRootId` references." The same `senderMsgId` in another Chat is
/// a different Message.
///
/// ponytail: one full Message scan of the account per call, not an
/// index. A backend with a `(chatId, senderMsgId)` index can serve the
/// same contract from it once this becomes a hot path.
///
/// # Errors
///
/// Returns the backend error if reading the account's Messages fails.
pub async fn find_message_by_sender_msg_id<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    chat_id: &Id,
    sender_msg_id: &Id,
) -> Result<Option<Message>, B::Error> {
    let (messages, _) = backend
        .get_objects::<Message>(caller, account_id, None, None)
        .await?;
    Ok(messages
        .into_iter()
        .find(|m| m.chat_id == *chat_id && m.sender_msg_id == *sender_msg_id))
}

/// The result of [`store_server_message`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum StoreOutcome {
    /// The Message was stored under this server-assigned id.
    Stored(Id),
    /// The Chat already holds a Message with the same `senderMsgId`; this
    /// is its id, and nothing was written.
    Duplicate(Id),
}

/// Store a Message that the server, not a client, creates: for example a
/// MIMI fanout Message (draft-atwood-jmap-chat-mimi-00
/// §application/mimi-fanout) or a federation `Peer/deliver` Message.
///
/// `build` makes the Message for the id the backend assigns, as for
/// [`ChatStore::create_object`](crate::ChatStore::create_object). It sets every other field, including
/// the server-set `senderMsgId`, `senderId`, `sentAt` and `receivedAt` and
/// a body type that [`ChatLimits::server_reserved_body_types`] keeps out
/// of `Message/set`. Its `chatId` and `senderMsgId` are then overwritten
/// with `chat_id` and `sender_msg_id`, so the stored Message always matches
/// the duplicate check. None of the `Message/set` client-input checks run.
///
/// Before storing, `chat_id` is searched for `sender_msg_id` with
/// [`find_message_by_sender_msg_id`]. A hit returns
/// [`StoreOutcome::Duplicate`] and writes nothing. The mimi draft
/// requires this: "The server MUST NOT store a FanoutMessage whose
/// `senderMsgId` it has already stored in the Chat". After a store, the
/// owner's ReadPosition for the Chat is created if missing and the
/// Chat's `unreadCount` is recomputed, as for `Message/set`
/// (draft-atwood-jmap-chat-00 §ReadPosition: "For direct and group
/// Chats, a ReadPosition is created when the first message is
/// delivered.").
///
/// ponytail: the duplicate check and the create are separate backend
/// calls. Two concurrent calls with one `senderMsgId` can both store, so
/// a caller that can race (such as parallel `/notify` deliveries)
/// serializes calls per Chat.
///
/// # Errors
///
/// Returns the backend's error from the lookup (as
/// [`BackendSetError::Other`]) or from
/// [`ChatStore::create_object`](crate::ChatStore::create_object), unchanged.
// Same error type as `ChatStore::create_object`, passed through unboxed.
pub async fn store_server_message<B, F>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    chat_id: &Id,
    sender_msg_id: &Id,
    build: F,
) -> Result<StoreOutcome, BackendSetError<B::Error>>
where
    B: ChatBackend,
    F: FnOnce(&Id) -> Message + Send,
{
    if let Some(existing) =
        find_message_by_sender_msg_id(backend, caller, account_id, chat_id, sender_msg_id)
            .await
            .map_err(BackendSetError::Other)?
    {
        return Ok(StoreOutcome::Duplicate(existing.id));
    }
    let (chat, smid) = (chat_id.clone(), sender_msg_id.clone());
    let (id, stored) = backend
        .create_object(
            caller,
            account_id,
            sender_msg_id.as_ref(),
            move |id: &Id| {
                let mut m = build(id);
                m.chat_id = chat;
                m.sender_msg_id = smid;
                m
            },
        )
        .await?;
    ensure_read_positions(backend, caller, account_id, vec![stored.chat_id.clone()]).await;
    record_unread_count_changes(backend, caller, account_id, vec![stored.chat_id]).await;
    Ok(StoreOutcome::Stored(id))
}

/// The owner's effective receipt-sharing preference for `chat_id`.
///
/// draft-atwood-jmap-chat-federation-00 §Peer/receipt "Sender Behavior":
/// "if `Chat.receiptSharing` is present for the relevant Chat, that value
/// is used; otherwise the account-level `PresenceStatus.receiptSharing`
/// applies". A missing PresenceStatus takes the draft-atwood-jmap-chat-00
/// default, `true`. A failed lookup yields `false`: the read has already
/// been written, and a receipt not shown to be permitted is not sent.
async fn shares_receipts<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    chat_id: &Id,
) -> bool {
    let chat_override = match backend
        .get_objects::<Chat>(
            caller,
            account_id,
            Some(std::slice::from_ref(chat_id)),
            None,
        )
        .await
    {
        Ok((found, _not_found)) => found.first().and_then(|c| c.receipt_sharing),
        Err(_) => return false,
    };
    if let Some(shares) = chat_override {
        return shares;
    }
    match backend
        .get_objects::<PresenceStatus>(caller, account_id, None, None)
        .await
    {
        Ok((found, _not_found)) => found.first().is_none_or(|p| p.receipt_sharing),
        Err(_) => false,
    }
}

/// The Message create properties that hold the id of another record, which a
/// client may set to a `#creationId` reference (RFC 8620 §5.3).
const MESSAGE_ID_PROPERTIES: &[&str] = &["chatId", "replyTo", "threadRootId"];

/// A Mention `id`, a ChatContact id (draft-atwood-jmap-chat-00 §Mention),
/// as `(property, entry field, property named on failure)` for
/// [`resolve_entry_refs`].
const MENTION_ID: (&str, &str, &str) = ("mentions", "id", "mentions");

/// An Attachment `filenodeId`, a FileNode id; failed validation names
/// `filenodeId` (draft-atwood-jmap-chat-filenode-00 §filenodeId).
const ATTACHMENT_FILENODE_ID: (&str, &str, &str) = ("attachments", "filenodeId", "filenodeId");

/// Handle a `Message/set` method call (draft-atwood-jmap-chat-00 §Message).
///
/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
/// `ifInState`, optional `create` / `update` / `destroy` maps); the
/// returned `Value` is the §5.3 `/set` response shape (`accountId`,
/// `oldState`, `newState`, plus the per-operation `created` /
/// `notCreated` / `updated` / `notUpdated` / `destroyed` / `notDestroyed`
/// maps).
///
/// Validation enforced here (not in the backend):
/// - `chatId` and `body` are required on create.
/// - `id`, `senderMsgId`, `senderId`, `sentAt`, `receivedAt`, `deliveryState`
///   are server-set and rejected in updates.
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
///
/// A `chatId`, `replyTo` or `threadRootId` that is a `#creationId`
/// reference names a record created earlier in the request and resolves
/// against `created_ids` (pass [`jmap_server::CallContext::created_ids`]) or
/// against a create of this call, which runs replied-to messages first (RFC
/// 8620 §5.3). So does a Mention `id` in a create or an edit, and an
/// Attachment `filenodeId` in a create. An unknown reference is
/// `invalidProperties` naming the property (`filenodeId` for an
/// Attachment).
///
/// `using` is the request's capability list (pass
/// [`jmap_server::CallContext::using`]): a write to `metadata` or
/// `privateMetadata` without `urn:ietf:params:jmap:metadata` is
/// `invalidProperties` (draft-ietf-jmap-metadata-05 §3), as is `null` for
/// either in a create (-05 §3.2). The backend validates the rest.
pub async fn handle_message_set<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    created_ids: &BTreeMap<Id, Id>,
    mut args: Value,
    using: &[String],
) -> Result<HandlerOutput, JmapError> {
    // A `#creationId` blob reference names a blob created earlier in the
    // request (RFC 8620 §5.3; draft-ietf-jmap-blobext-03 §8); an unknown one
    // is left for the Id checks below.
    jmap_server::resolve_blob_refs(&mut args, &["blobId", "thumbnailBlobId"], created_ids);
    let (account_id, mut args) = extract_account_id(args)?;

    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-fo38).
    if !backend
        .account_exists(caller, &account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?
    {
        return Err(JmapError::account_not_found());
    }

    // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.3). Reject
    // unbounded /set batches before touching the storage layer.
    enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;

    let old_state = backend
        .get_state::<Message>(caller, &account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?;

    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
        && if_in_state != old_state.as_ref()
    {
        return Err(JmapError::state_mismatch());
    }

    let mut created = serde_json::Map::new();
    let mut not_created = serde_json::Map::new();
    let mut updated = serde_json::Map::new();
    let mut not_updated = serde_json::Map::new();
    let mut destroyed_list: Vec<Value> = Vec::new();
    let mut not_destroyed = serde_json::Map::new();
    let mut mutated = false;
    let limits = backend.limits(caller, &account_id);

    // -----------------------------------------------------------------------
    // create
    // -----------------------------------------------------------------------
    if let Some(create_map) = args.get("create").and_then(|v| v.as_object()) {
        let mut delivered_chat_ids: Vec<Id> = Vec::new();
        // RFC 8620 §5.3: creates of this call join the request-wide map so
        // later creates in this call can reference them.
        let mut created_ids = created_ids.clone();
        for (create_id, obj_val) in parents_first(create_map, &["replyTo", "threadRootId"]) {
            let resolved = match resolved_create(obj_val, MESSAGE_ID_PROPERTIES, &created_ids)
                .and_then(|mut v| {
                    resolve_entry_refs(&mut v, &[MENTION_ID, ATTACHMENT_FILENODE_ID], &created_ids)
                        .map(|()| v)
                }) {
                Ok(v) => v,
                Err(err) => {
                    not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
                    continue;
                }
            };
            let obj_val = &resolved;
            if let Some(err) = obj_val.as_object().and_then(reject_server_set::<Message>) {
                not_created.insert(create_id.clone(), serde_json::Value::from(&err));
                continue;
            }
            if let Some(Err(err)) = obj_val
                .as_object()
                .map(|o| check_metadata_entry(o, true, using))
            {
                not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
                continue;
            }
            // draft-ietf-jmap-metadata-05 §3.2: the create sets the
            // metadata properties; the backend validates them.
            let (metadata, private_metadata) = match create_metadata(obj_val) {
                Ok(maps) => maps,
                Err(err) => {
                    not_created.insert(create_id.clone(), err);
                    continue;
                }
            };
            // Optional properties: a wrongly-typed value is invalidProperties
            // (RFC 8620 §5.3), not a silent absence.
            if let Some(err) = mistyped_create_props(
                obj_val,
                &[
                    ("broadcastMentions", PropType::Array),
                    ("replyTo", PropType::Str),
                    ("threadRootId", PropType::Str),
                    ("senderExpiresAt", PropType::Str),
                    ("burnOnRead", PropType::Bool),
                ],
            ) {
                not_created.insert(create_id.clone(), err);
                continue;
            }
            let Some(chat_id_str) = obj_val.get("chatId").and_then(|v| v.as_str()) else {
                not_created.insert(
                    create_id.clone(),
                    json!({ "type": "invalidProperties", "properties": ["chatId"] }),
                );
                continue;
            };
            let chat_id = match jmap_server::parse_wire_id(chat_id_str, "chatId") {
                Ok(id) => id,
                Err(err) => {
                    not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
                    continue;
                }
            };

            let Some(body) = obj_val
                .get("body")
                .and_then(|v| v.as_str())
                .map(str::to_owned)
            else {
                not_created.insert(
                    create_id.clone(),
                    json!({ "type": "invalidProperties", "properties": ["body"] }),
                );
                continue;
            };
            // §Account-Level Capability Object `maxBodyBytes`: "Servers
            // MUST reject messages exceeding this limit; in `Message/set`
            // the rejection is a `tooLarge` SetError."
            if u64::try_from(body.len()).map_or(true, |n| n > limits.max_body_bytes) {
                not_created.insert(
                    create_id.clone(),
                    json!({
                        "type": "tooLarge",
                        "description": format!("body exceeds maxBodyBytes ({})", limits.max_body_bytes),
                    }),
                );
                continue;
            }

            // sentAt is a UTCDate per RFC 8620 §1.4 (20-char
            // YYYY-MM-DDTHH:MM:SSZ). Validate the wire shape via
            // UTCDate::new_validated; a malformed value produces
            // invalidProperties rather than silently flowing through
            // to storage where downstream lex-compares and slice ops
            // (helpers::iso8601_before) assume a validated 20-byte
            // ASCII shape.
            let Some(sent_at_str) = obj_val.get("sentAt").and_then(|v| v.as_str()) else {
                not_created.insert(
                    create_id.clone(),
                    json!({ "type": "invalidProperties", "properties": ["sentAt"] }),
                );
                continue;
            };
            let Ok(sent_at) = UTCDate::new_validated(sent_at_str) else {
                not_created.insert(
                    create_id.clone(),
                    json!({ "type": "invalidProperties", "properties": ["sentAt"] }),
                );
                continue;
            };

            // §Input Validation: "`bodyType`: reject a value not listed in
            // `supportedBodyTypes`; in `Message/set` create, also reject a
            // type that a companion specification reserves for
            // server-created Messages."
            let Some(body_type) = obj_val
                .get("bodyType")
                .filter(|v| !v.is_null())
                .map_or(Some("text/plain"), Value::as_str)
                .filter(|s| limits.supported_body_types.contains(s))
            else {
                not_created.insert(
                    create_id.clone(),
                    json!({ "type": "invalidProperties", "properties": ["bodyType"] }),
                );
                continue;
            };
            // draft-atwood-jmap-chat-mimi-00 §application/mimi-fanout, the
            // one reserving companion: "the server MUST reject a
            // `Message/set` create with this body type with an
            // `invalidProperties` SetError naming `bodyType`."
            if limits.server_reserved_body_types.contains(&body_type) {
                not_created.insert(
                    create_id.clone(),
                    json!({
                        "type": "invalidProperties",
                        "properties": ["bodyType"],
                        "description": format!("bodyType {body_type} is reserved for server-created Messages")
                    }),
                );
                continue;
            }
            let body_type = body_type.to_owned();

            // §Fields Inside the Ciphertext: "an `invalidProperties`
            // SetError whose `properties` lists each such field".
            let conflicts =
                body_type_field_conflicts(obj_val, &body_type, limits.encrypted_body_types);
            if !conflicts.is_empty() {
                not_created.insert(
                    create_id.clone(),
                    json!({
                        "type": "invalidProperties",
                        "properties": conflicts,
                        "description": format!("must be empty or absent when bodyType is {body_type}"),
                    }),
                );
                continue;
            }

            // BroadcastMention structural validation (§4.4.1 / §4.16).
            let broadcast_mentions_val: Vec<Value> = obj_val
                .get("broadcastMentions")
                .and_then(|v| v.as_array())
                .cloned()
                .unwrap_or_default();
            if let Some(err) = validate_broadcast_mentions(&broadcast_mentions_val) {
                not_created.insert(create_id.clone(), err);
                continue;
            }

            // draft-atwood-jmap-chat-00 §Input Validation: "`chatId`:
            // verify per {{chat-id}} — confirm match with stored id"; a
            // failed check is "an `invalidProperties` SetError ... whose
            // `properties` names the offending property".
            let chat = match backend
                .get_objects::<Chat>(
                    caller,
                    &account_id,
                    Some(std::slice::from_ref(&chat_id)),
                    None,
                )
                .await
            {
                Ok((found, _)) => match found.into_iter().next() {
                    Some(chat) => chat,
                    None => {
                        not_created.insert(
                            create_id.clone(),
                            json!({
                                "type": "invalidProperties",
                                "properties": ["chatId"],
                                "description": format!("no Chat with id {chat_id}"),
                            }),
                        );
                        continue;
                    }
                },
                Err(e) => {
                    not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
                    continue;
                }
            };

            match backend.may_create_message(caller, &account_id, &chat).await {
                Ok(Ok(())) => {}
                Ok(Err(set_err)) => {
                    not_created.insert(create_id.clone(), serde_json::Value::from(&set_err));
                    continue;
                }
                Err(e) => {
                    not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
                    continue;
                }
            }

            // draft-atwood-jmap-chat-00 §Chat `closedAt`: "After it is
            // set, the server MUST reject with a `forbidden` SetError
            // every `Message/set` create in this Chat".
            if chat.closed_at.is_some() {
                not_created.insert(
                    create_id.clone(),
                    json!({ "type": "forbidden", "description": "the group is closed" }),
                );
                continue;
            }

            // draft-atwood-jmap-chat-00 §Space `closedAt`: "After it is
            // set, the Space's channels are read-only: the server MUST
            // reject every `Message/set` create in them with a
            // `forbidden` SetError."
            if let Some(sid) = &chat.space_id {
                match backend
                    .get_objects::<Space>(
                        caller,
                        &account_id,
                        Some(std::slice::from_ref(sid)),
                        None,
                    )
                    .await
                {
                    Ok((spaces, _)) if spaces.first().is_some_and(|s| s.closed_at.is_some()) => {
                        not_created.insert(
                            create_id.clone(),
                            json!({ "type": "forbidden", "description": "the Space is closed" }),
                        );
                        continue;
                    }
                    Ok(_) => {}
                    Err(e) => {
                        not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
                        continue;
                    }
                }
            }

            // draft-atwood-jmap-chat-00 §Message/set: the sender MUST be a
            // current member of the target Chat and, in a channel, hold
            // `"send"`; otherwise `forbidden`.
            match backend
                .may_send_message(caller, &account_id, &chat_id)
                .await
            {
                Ok(Ok(())) => {}
                Ok(Err(set_err)) => {
                    not_created.insert(create_id.clone(), serde_json::Value::from(&set_err));
                    continue;
                }
                Err(e) => {
                    not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
                    continue;
                }
            }

            // BroadcastMention permission check (§4.4.1).
            // Non-empty broadcastMentions in a Space-backed channel
            // requires mention_broadcast permission; rich-body spans are
            // display-only and never consulted (§Rich Body Format).
            // Group/direct chats (no spaceId) are unrestricted per spec.
            if let Some(sid) = chat
                .space_id
                .as_ref()
                .filter(|_| !broadcast_mentions_val.is_empty())
            {
                match backend
                    .may_broadcast_mention(caller, &account_id, sid, &chat_id)
                    .await
                {
                    Ok(Ok(())) => {}
                    Ok(Err(set_err)) => {
                        not_created.insert(create_id.clone(), serde_json::Value::from(&set_err));
                        continue;
                    }
                    Err(e) => {
                        not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
                        continue;
                    }
                }
            }

            let reply_to: Option<Id> = match obj_val.get("replyTo").and_then(|v| v.as_str()) {
                Some(s) => match jmap_server::parse_wire_id(s, "replyTo") {
                    Ok(id) => Some(id),
                    Err(err) => {
                        not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
                        continue;
                    }
                },
                None => None,
            };

            let supplied_root: Option<Id> =
                match obj_val.get("threadRootId").and_then(|v| v.as_str()) {
                    Some(s) => match jmap_server::parse_wire_id(s, "threadRootId") {
                        Ok(id) => Some(id),
                        Err(err) => {
                            not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
                            continue;
                        }
                    },
                    None => None,
                };

            // §Message `replyTo`: "Servers MUST validate that this ID
            // exists in the same Chat before storing." §Thread Model:
            // the root of a reply is the referenced message's
            // `threadRootId`, or the referenced message itself when that
            // is absent; a message with no `replyTo` has no root.
            // "Servers SHOULD validate them and MAY correct
            // `threadRootId`": a wrong value is rejected and an omitted
            // one is filled in. §Input Validation names no other error,
            // so both failures are `invalidProperties`.
            let expected_root: Option<Id> = match reply_to.as_ref() {
                None => None,
                Some(parent_id) => {
                    let parent = match backend
                        .get_objects::<Message>(
                            caller,
                            &account_id,
                            Some(std::slice::from_ref(parent_id)),
                            None,
                        )
                        .await
                    {
                        Ok((found, _)) => found.into_iter().find(|m| m.chat_id == chat_id),
                        Err(e) => {
                            not_created
                                .insert(create_id.clone(), server_fail_value_from_backend(&e));
                            continue;
                        }
                    };
                    let Some(parent) = parent else {
                        not_created.insert(
                            create_id.clone(),
                            json!({
                                "type": "invalidProperties",
                                "properties": ["replyTo"],
                                "description": "replyTo is not a Message in this Chat",
                            }),
                        );
                        continue;
                    };
                    Some(parent.thread_root_id.unwrap_or(parent.id))
                }
            };
            if supplied_root.is_some() && supplied_root != expected_root {
                not_created.insert(
                    create_id.clone(),
                    json!({
                        "type": "invalidProperties",
                        "properties": ["threadRootId"],
                        "description": "threadRootId does not match the thread of replyTo",
                    }),
                );
                continue;
            }
            let thread_root_id = expected_root;

            // senderExpiresAt is a UTCDate per RFC 8620 §1.4 (20-char
            // YYYY-MM-DDTHH:MM:SSZ). Validate the wire shape via
            // UTCDate::new_validated; a malformed value produces
            // invalidProperties rather than silently flowing through to
            // a downstream string compare with undefined ordering.
            let sender_expires_at: Option<UTCDate> =
                if let Some(s) = obj_val.get("senderExpiresAt").and_then(|v| v.as_str()) {
                    let Ok(d) = UTCDate::new_validated(s) else {
                        not_created.insert(
                            create_id.clone(),
                            json!({
                                "type": "invalidProperties",
                                "properties": ["senderExpiresAt"],
                            }),
                        );
                        continue;
                    };
                    Some(d)
                } else {
                    None
                };

            let burn_on_read: Option<bool> = obj_val.get("burnOnRead").and_then(|v| v.as_bool());

            if let Some(ref expires_at) = sender_expires_at {
                let now = now_utc_string();
                if !iso8601_before(&now, expires_at) {
                    not_created.insert(
                        create_id.clone(),
                        json!({ "type": "invalidProperties", "properties": ["senderExpiresAt"] }),
                    );
                    continue;
                }
            }

            let now_str = now_utc_string();
            let received_at: UTCDate = UTCDate::from(now_str.as_ref());

            let mut attachments = Vec::new();
            if let Some(v) = obj_val.get("attachments").filter(|v| !v.is_null()) {
                match create_attachments(backend, caller, &account_id, &limits, &chat, v).await {
                    Ok(a) => attachments = a,
                    Err(err) => {
                        not_created.insert(create_id.clone(), err);
                        continue;
                    }
                }
            }
            let apply_optionals = match apply_create_optionals(obj_val) {
                Ok(f) => f,
                Err(property) => {
                    not_created.insert(
                        create_id.clone(),
                        json!({ "type": "invalidProperties", "properties": [property] }),
                    );
                    continue;
                }
            };
            if let Some(err) =
                check_attachments(backend, caller, &account_id, &limits, &attachments).await
            {
                not_created.insert(create_id.clone(), err);
                continue;
            }

            // Slow-mode rate-limit gate (draft-atwood-jmap-chat-00
            // §Chat `slowModeSeconds` + spec commit `de60acb`).
            //
            // Runs AFTER wire-format validation so malformed requests
            // don't consume rate-tracker slots, and BEFORE the
            // `create_object` call so a throttled sender never sees the
            // message touch storage. On a Throttled return the backend
            // tells us when the caller may retry; we surface that
            // verbatim as the `serverRetryAfter` extra field on the
            // `rateLimit` SetError, built via the typed
            // `SetError::with_extra` builder added in bd:JMAP-dha0.
            // The spec requires "a `rateLimit` SetError ({{RFC8620,
            // Section 5.3}}) on the offending `Message/set` create",
            // not the method-level `rateLimited` (which is reserved
            // for the Peer/* methods). `serverRetryAfter` is a
            // workspace extension field. The reference `MemoryBackend`
            // never returns an Err here.
            if let Err(slow_err) = backend.slow_mode_check(caller, &account_id, &chat_id).await {
                let retry_after_str: String = slow_err.retry_after.as_ref().to_owned();
                let set_err = SetError::new(SetErrorType::RateLimit)
                    .with_description("Slow mode is active for this chat")
                    .with_extra("serverRetryAfter", json!(retry_after_str));
                not_created.insert(create_id.clone(), serde_json::Value::from(&set_err));
                continue;
            }

            // draft-atwood-jmap-chat-00 §Message `senderMsgId`: "Equals
            // `id` for messages composed by the owner."
            let build = |id: &Id| {
                let mut msg = Message::new(
                    id.clone(),
                    id.clone(),
                    account_id.clone(),
                    chat_id,
                    body,
                    body_type,
                    sent_at,
                    received_at,
                    DeliveryState::Pending,
                );
                msg.reply_to = reply_to;
                msg.thread_root_id = thread_root_id;
                msg.sender_expires_at = sender_expires_at;
                msg.burn_on_read = burn_on_read;
                msg.attachments = attachments;
                msg.metadata = metadata;
                msg.private_metadata = private_metadata;
                apply_optionals(&mut msg);
                msg
            };
            // draft-atwood-jmap-chat-00 §Message/set: the server sets the
            // server-assigned fields "then enqueues the message for
            // outbound delivery"; `create_message` does both as one unit.
            match backend
                .create_message(caller, &account_id, create_id, build)
                .await
            {
                Ok((server_id, created_obj)) => {
                    mutated = true;
                    created_ids.insert(Id::from(create_id.as_str()), server_id);
                    delivered_chat_ids.push(created_obj.chat_id.clone());
                    created.insert(
                        create_id.clone(),
                        jmap_server::serialize_value(&created_obj)?,
                    );
                }
                Err(e) => {
                    not_created.insert(create_id.clone(), backend_set_error_value(e));
                }
            }
        }
        ensure_read_positions(backend, caller, &account_id, delivered_chat_ids.clone()).await;
        record_unread_count_changes(backend, caller, &account_id, delivered_chat_ids).await;
    }

    // -----------------------------------------------------------------------
    // update
    // -----------------------------------------------------------------------
    // RFC 8620 §5.3: update keys and destroy ids may name this call's creates.
    jmap_server::resolve_set_id_refs(&mut args, created_ids, &created);
    if let Some(Value::Object(update_map)) = args.remove("update") {
        for (id_str, mut patch_val) in update_map {
            let id = match jmap_server::parse_wire_id(&id_str, "id") {
                Ok(id) => id,
                Err(err) => {
                    not_updated.insert(id_str, serde_json::Value::from(&*err));
                    continue;
                }
            };
            // An edit may replace `mentions`; `attachments` is immutable.
            if let Err(err) = resolve_entry_refs(&mut patch_val, &[MENTION_ID], created_ids) {
                not_updated.insert(id_str, serde_json::Value::from(&*err));
                continue;
            }

            // RFC 8620 §5.3: "There MUST NOT be two patches in the
            // PatchObject where the pointer of one is the prefix of the
            // pointer of the other" or the update "MUST be rejected with an
            // "invalidPatch" error".
            if patch_val.get("reactions").is_some()
                && patch_val
                    .as_object()
                    .is_some_and(|obj| obj.keys().any(|k| k.starts_with("reactions/")))
            {
                not_updated.insert(
                    id_str,
                    json!({
                        "type": "invalidPatch",
                        "description":
                            "patch must not combine top-level `reactions` with `reactions/{id}` entries",
                    }),
                );
                continue;
            }

            // draft-ietf-jmap-metadata-05 §3.2: patch errors "that can be
            // determined from the request alone ... MUST be reported with
            // "invalidPatch"" before `notFound`.
            if let Some(Err(err)) = patch_val
                .as_object()
                .map(|o| check_metadata_entry(o, false, using))
            {
                not_updated.insert(id_str, serde_json::Value::from(&*err));
                continue;
            }
            if let Some(Err(e)) = patch_val.as_object().map(jmap_server::check_patch_paths) {
                not_updated.insert(
                    id_str,
                    json!({ "type": "invalidPatch", "description": e.to_string() }),
                );
                continue;
            }

            // The stored Message and its Chat, read once for every check
            // below.
            let stored = match backend
                .get_objects::<Message>(caller, &account_id, Some(std::slice::from_ref(&id)), None)
                .await
            {
                Ok((found, _)) => found.into_iter().next(),
                Err(e) => {
                    not_updated.insert(id_str, server_fail_value_from_backend(&e));
                    continue;
                }
            };
            let Some(stored) = stored else {
                not_updated.insert(id_str, Value::from(&SetError::new(SetErrorType::NotFound)));
                continue;
            };
            let stored_chat = match backend
                .get_objects::<Chat>(
                    caller,
                    &account_id,
                    Some(std::slice::from_ref(&stored.chat_id)),
                    None,
                )
                .await
            {
                Ok((found, _)) => found.into_iter().next(),
                Err(e) => {
                    not_updated.insert(id_str, server_fail_value_from_backend(&e));
                    continue;
                }
            };

            // RFC 8620 §5.3: "Any server-set properties MAY be included in
            // the patch if their value is identical to the current server
            // value ... Otherwise, the update MUST be rejected with an
            // "invalidProperties" SetError." Identical values are dropped
            // here, so the checks below see only the client changes.
            //
            // Existence and permission come before shape (DECISIONS.md 44):
            // the shape errors below are held in `shape_err` and reported
            // only after the `forbidden` checks, which look at patch keys
            // and values the read-only check does not touch.
            let mut shape_err: Option<Value> = None;
            if let Value::Object(map) = &mut patch_val
                && let Err(err) = strip_read_only_patch::<Message>(map, &stored)
            {
                shape_err = Some(err);
            }
            // A whole `reactions` identical to the stored map changes
            // nothing: drop it, as an identical server-set value is
            // (RFC 8620 §5.3), so only a real whole-map write is rejected
            // below (bd:JMAP-t8ej.32 item 4).
            if let Value::Object(map) = &mut patch_val
                && map.get("reactions").is_some_and(|r| {
                    serde_json::to_value(&stored)
                        .ok()
                        .is_some_and(|s| s.get("reactions").unwrap_or(&Value::Null) == r)
                })
            {
                map.remove("reactions");
            }

            // draft-atwood-jmap-chat-00 §Message/set defines the only
            // client updates: Editing (`body`, `bodyType`, `mentions`,
            // `broadcastMentions`), Adding and Removing Reactions
            // (`reactions/<senderReactionId>` JSON Pointer keys), Deleting
            // (`deletedAt`, `deletedForAll`) and Marking as Read (`readAt`,
            // `readDisposition`): the client-settable Message properties
            // that are not immutable, with `reactions` changed only per
            // entry. Every other key names a server-set or immutable
            // property, so it is rejected with RFC 8620 §5.3
            // `invalidProperties`. draft-ietf-jmap-metadata-05 §3.2 adds
            // `metadata` and `privateMetadata`, written whole or by patch
            // path.
            let defined = |k: &str| {
                k.starts_with("reactions/")
                    || is_metadata_key(k)
                    || (k != "reactions" && is_client_updatable::<Message>(k))
            };
            let bad_props: Vec<&str> = patch_val
                .as_object()
                .map(|obj| {
                    obj.keys()
                        .map(String::as_str)
                        .filter(|k| !defined(k))
                        .collect()
                })
                .unwrap_or_default();
            if shape_err.is_none() && !bad_props.is_empty() {
                shape_err = Some(json!({ "type": "invalidProperties", "properties": bad_props }));
            }

            // draft-atwood-jmap-chat-00 §Message `readDisposition`: "the
            // server MUST reject an update that sets `readDisposition`
            // without `readAt` with an `invalidProperties` SetError naming
            // `readDisposition`." A null `readAt` clears it, not sets it.
            let sets = |field: &str| patch_val.get(field).is_some_and(|v| !v.is_null());
            if shape_err.is_none() && sets("readDisposition") && !sets("readAt") {
                shape_err =
                    Some(json!({ "type": "invalidProperties", "properties": ["readDisposition"] }));
            }

            // §Input Validation: "`bodyType`: reject a value not listed in
            // `supportedBodyTypes`".
            if shape_err.is_none()
                && patch_val.get("bodyType").is_some_and(|v| {
                    !v.as_str()
                        .is_some_and(|s| limits.supported_body_types.contains(&s))
                })
            {
                shape_err =
                    Some(json!({ "type": "invalidProperties", "properties": ["bodyType"] }));
            }

            // Per-Chat restrictions of extension-bound Chats; see
            // `ChatRestrictions::may_update_message`. It sees only the keys
            // the update may change.
            if let Some(chat) = &stored_chat {
                let patch_keys: Vec<&str> = patch_val
                    .as_object()
                    .map(|obj| {
                        obj.keys()
                            .map(String::as_str)
                            .filter(|k| defined(k))
                            .collect()
                    })
                    .unwrap_or_default();
                match backend
                    .may_update_message(caller, &account_id, chat, &stored, &patch_keys)
                    .await
                {
                    Ok(Ok(())) => {}
                    Ok(Err(set_err)) => {
                        not_updated.insert(id_str, serde_json::Value::from(&set_err));
                        continue;
                    }
                    Err(e) => {
                        not_updated.insert(id_str, server_fail_value_from_backend(&e));
                        continue;
                    }
                }
            }

            // draft-atwood-jmap-chat-00 §Deleting a Message: servers MUST
            // reject `deletedForAll: true` when `senderId` is not the
            // accountId. §Editing a Message: an edit of `body`, `bodyType`,
            // `mentions` or `broadcastMentions` is only permitted where
            // `senderId` is the accountId and `deletedAt` is absent; any other edit is
            // `forbidden`.
            let deletes_for_all =
                patch_val.get("deletedForAll").and_then(|v| v.as_bool()) == Some(true);
            let edits = ["body", "bodyType", "mentions", "broadcastMentions"]
                .iter()
                .any(|&field| patch_val.get(field).is_some());
            // The event for `ChatEvents::on_outbound_event`, built from
            // the stored Message once the checks below pass.
            let mut outbound: Option<OutboundEvent> = None;
            if deletes_for_all || edits {
                let description = if deletes_for_all && stored.sender_id != account_id {
                    Some(
                        "deletedForAll is only permitted on messages whose senderId is the accountId",
                    )
                } else if edits && (stored.sender_id != account_id || stored.deleted_at.is_some()) {
                    Some(
                        "edits are only permitted on messages whose senderId is the accountId and deletedAt is absent",
                    )
                } else {
                    None
                };
                if let Some(description) = description {
                    not_updated.insert(
                        id_str,
                        json!({ "type": "forbidden", "description": description }),
                    );
                    continue;
                }
                if let Some(err) = shape_err.take() {
                    not_updated.insert(id_str, err);
                    continue;
                }
                if let Some(err) = edit_limit_error(&stored, &patch_val, &limits) {
                    not_updated.insert(id_str, err);
                    continue;
                }
                outbound = Some({
                    let (chat_id, message_id, sender_msg_id) = (
                        stored.chat_id.clone(),
                        stored.id.clone(),
                        stored.sender_msg_id.clone(),
                    );
                    if deletes_for_all {
                        OutboundEvent::Retract {
                            chat_id,
                            message_id,
                            sender_msg_id,
                        }
                    } else {
                        OutboundEvent::Edit {
                            chat_id,
                            message_id,
                            sender_msg_id,
                        }
                    }
                });
            }

            // Every `forbidden` check has run: report a held shape error.
            if let Some(err) = shape_err.take() {
                not_updated.insert(id_str, err);
                continue;
            }

            // Nothing left once identical values are dropped (or a literal
            // `{}`): a no-op success with no write (RFC 8620 §5.3).
            if patch_val.as_object().is_some_and(Map::is_empty) {
                updated.insert(id_str, Value::Null);
                continue;
            }

            // Build augmented patch with server-side timestamps.
            let mut augmented = patch_val;
            if augmented.get("body").is_some()
                && let Some(obj) = augmented.as_object_mut()
            {
                obj.insert("editedAt".to_owned(), json!(now_utc_string()));
            }
            // draft-atwood-jmap-chat-00 §Message deletedAt: a deleted
            // Message has an empty `body`, empty `attachments`, and no
            // `editHistory`, whether the deletion is local or for all. The
            // merge-patch null purges the stored revisions rather than
            // merely hiding them.
            let deletes =
                deletes_for_all || augmented.get("deletedAt").is_some_and(|v| !v.is_null());
            if deletes && let Some(obj) = augmented.as_object_mut() {
                if deletes_for_all {
                    obj.insert("deletedAt".to_owned(), json!(now_utc_string()));
                }
                obj.insert("body".to_owned(), json!(""));
                obj.insert("attachments".to_owned(), json!([]));
                obj.insert("editHistory".to_owned(), Value::Null);
            }
            // Spec §557 + §1029: when readAt is set without readDisposition, default to "displayed".
            // draft-atwood-jmap-chat-00 §Message `readDisposition`: "Absent
            // when `readAt` is not set." so clearing readAt clears it too.
            if let Some(obj) = augmented.as_object_mut() {
                match obj.get("readAt") {
                    Some(Value::Null) => {
                        obj.insert("readDisposition".to_owned(), Value::Null);
                    }
                    Some(_) if !obj.contains_key("readDisposition") => {
                        obj.insert("readDisposition".to_owned(), json!("displayed"));
                    }
                    _ => {}
                }
            }

            // Reaction patch processing
            // (draft-atwood-jmap-chat-00 §Message/set, §Reaction).
            //
            // Reactions are added/removed by patching
            // `reactions/{senderReactionId}` as RFC 8620 §5.3 JSON
            // Pointer entries:
            //
            // - value is an object: add or modify the reaction
            // - value is `null`: remove the reaction
            //
            // The backend applies these paths into the stored
            // `reactions` map. Before forwarding, the handler:
            //
            // 1. Rejects `reactions/{id}` keys containing `/` or `~`
            //    (RFC 6901 escape characters — the chat-client also
            //    rejects them; this is defense-in-depth).
            // 2. Rejects non-null non-object values as `invalidPatch`.
            // 3. Pre-fetches the Message and rejects with `forbidden`
            //    if the patched key targets an existing reaction whose
            //    `senderId` is not the accountId — per spec, only the
            //    original sender may modify their own reactions.
            // 4. Server-overrides `senderId` to the accountId on every add
            //    (spec MUST; defense-in-depth).
            // 5. Server-injects `sentAt` to the current time on adds
            //    that lack it, so the resulting `Reaction` round-trips
            //    through the typed shape (which requires `sentAt`).
            let reaction_pointer_keys: Vec<String> = augmented
                .as_object()
                .map(|obj| {
                    obj.keys()
                        .filter(|k| k.starts_with("reactions/"))
                        .cloned()
                        .collect()
                })
                .unwrap_or_default();

            // One `OutboundEvent::ReactionUpdate` per patched key, built
            // from the pre-fetched Message and reported after the write.
            let mut reaction_events: Vec<OutboundEvent> = Vec::new();
            if !reaction_pointer_keys.is_empty() {
                // Validate each pointer key + value shape. The
                // `.collect::<Result<Vec<_>, _>>()` form short-circuits
                // on the first Err and is the idiomatic Rust expression
                // of "validate-or-fail" over an iterator. A future
                // contributor adding a new validation rule appends an
                // `if ... { return Err(...) }` inside the closure; the
                // short-circuit behavior is structural, not a hand-coded
                // flag invariant.
                let decoded: Result<Vec<(String, String)>, String> = reaction_pointer_keys
                    .iter()
                    .map(|raw_key| {
                        let suffix = &raw_key["reactions/".len()..];
                        if suffix.is_empty() || suffix.contains('/') || suffix.contains('~') {
                            return Err(format!(
                                "reactions/{{id}} pointer key {raw_key:?} has empty or forbidden suffix; '/' and '~' are reserved by RFC 6901",
                            ));
                        }
                        let val = augmented.get(raw_key).unwrap_or(&Value::Null);
                        if !val.is_null() {
                            let ok = val.as_object().is_some_and(|m| {
                                m.get("emoji")
                                    .and_then(|v| v.as_str())
                                    .is_some_and(|s| !s.is_empty())
                            });
                            if !ok {
                                return Err(format!(
                                    "reaction value for {raw_key:?} must be null or an object with a non-empty `emoji` string",
                                ));
                            }
                        }
                        Ok((raw_key.clone(), suffix.to_owned()))
                    })
                    .collect();
                let decoded = match decoded {
                    Ok(d) => d,
                    Err(desc) => {
                        not_updated.insert(
                            id_str,
                            json!({ "type": "invalidPatch", "description": desc }),
                        );
                        continue;
                    }
                };

                // Inspect the stored Message's existing reactions.
                let mut forbidden: Vec<String> = Vec::new();
                for (raw_key, suffix) in &decoded {
                    let existing = stored.reactions.get(suffix);
                    if existing.is_some_and(|r| r.sender_id != account_id) {
                        forbidden.push(suffix.clone());
                    }
                    // A null on a key with no stored reaction
                    // removes nothing, so nothing propagates.
                    let action = match augmented.get(raw_key) {
                        Some(Value::Object(_)) => Some(ReactionAction::Add),
                        _ => existing.map(|r| ReactionAction::Remove { removed: r.clone() }),
                    };
                    if let Some(action) = action {
                        reaction_events.push(OutboundEvent::ReactionUpdate {
                            chat_id: stored.chat_id.clone(),
                            message_id: stored.id.clone(),
                            sender_msg_id: stored.sender_msg_id.clone(),
                            sender_reaction_id: suffix.clone(),
                            action,
                        });
                    }
                }
                if !forbidden.is_empty() {
                    not_updated.insert(
                        id_str,
                        json!({
                            "type": "forbidden",
                            "description": format!(
                                "cannot modify reactions authored by another sender: {}",
                                forbidden.join(", "),
                            ),
                        }),
                    );
                    continue;
                }

                // Server-override `senderId` and inject `sentAt` where
                // absent on every `reactions/{key}` add, so the stored
                // Reaction round-trips through the typed shape.
                let now_str = now_utc_string();
                if let Some(obj) = augmented.as_object_mut() {
                    for (raw_key, _) in &decoded {
                        if let Some(Value::Object(map)) = obj.get_mut(raw_key) {
                            // Spec MUST: server overrides senderId to
                            // the accountId on every add, regardless of
                            // what the client supplied.
                            map.insert("senderId".to_owned(), json!(account_id));
                            map.entry("sentAt").or_insert_with(|| json!(now_str));
                        }
                    }
                }
            }

            // Detect a non-null readAt assignment in the patch. A
            // `readAt: null` is a PatchObject clear (RFC 8620 §5.3), not a
            // "mark as read" event, so it does not trigger burn-on-read.
            // draft-atwood-jmap-chat-00 §Message `burnOnRead` (jmap-chat-spec
            // 77c3474 L750): the receiving server SHOULD hard-delete
            // immediately after setting readAt on a message whose
            // `burnOnRead` is `true`; this crate does so by choice.
            let patch_sets_read_at = augmented.get("readAt").is_some_and(|v| !v.is_null());

            // If the patch sets readAt, the stored Message decides whether
            // it is burn-on-read. We deliberately consult the pre-patch
            // state: a recipient setting readAt for the first time should
            // fire the burn. draft-atwood-jmap-chat-00 §Message
            // `burnOnRead`: "Applies only to the receiving mailbox; the
            // sender's own copy is not affected."
            let pre_patch_read: Option<Message> = if patch_sets_read_at {
                Some(stored.clone())
            } else {
                None
            };
            let pre_patch_burn_on_read = pre_patch_read
                .as_ref()
                .is_some_and(|m| m.burn_on_read == Some(true) && m.sender_id != account_id);

            // BroadcastMention validation and permission check on edit
            // (§4.4.1 / §4.16). The post-patch broadcastMentions fall back
            // to the stored message where the patch leaves them unchanged,
            // so an edit that retains a broadcast mention is gated like one
            // that adds it.
            if edits {
                let current_has_bm = !stored.broadcast_mentions.is_empty();
                // Structural validation only when broadcastMentions is part
                // of the patch.
                let has_bm = match augmented.get("broadcastMentions") {
                    Some(bm) => {
                        let bm_arr: Vec<Value> = bm.as_array().cloned().unwrap_or_default();
                        if let Some(err) = validate_broadcast_mentions(&bm_arr) {
                            not_updated.insert(id_str, err);
                            continue;
                        }
                        !bm_arr.is_empty()
                    }
                    None => current_has_bm,
                };

                // BroadcastMention permission check on update (§4.4.1).
                // A post-patch broadcastMentions entry in a Space-backed
                // channel requires mention_broadcast permission; rich-body
                // spans are display-only and never consulted. Group/direct
                // chats (no spaceId) are unrestricted per spec.
                // A Chat not found is left for update_object to surface
                // downstream.
                let channel = stored_chat
                    .as_ref()
                    .and_then(|c| Some((c.space_id.as_ref()?, &c.id)));
                if let (true, Some((sid, chat_id))) = (has_bm, channel) {
                    match backend
                        .may_broadcast_mention(caller, &account_id, sid, chat_id)
                        .await
                    {
                        Ok(Ok(())) => {}
                        Ok(Err(set_err)) => {
                            not_updated.insert(id_str, serde_json::Value::from(&set_err));
                            continue;
                        }
                        Err(e) => {
                            not_updated.insert(id_str, server_fail_value_from_backend(&e));
                            continue;
                        }
                    }
                }
            }

            // draft-atwood-jmap-chat-federation-00 §Peer/receipt: the
            // owner read a Message another participant sent. The read
            // fields come from the patch, since a burned Message is gone.
            let receipt = pre_patch_read
                .filter(|m| m.sender_id != account_id)
                .and_then(|m| {
                    let read_at =
                        serde_json::from_value::<UTCDate>(augmented.get("readAt")?.clone()).ok()?;
                    let read_disposition = augmented
                        .get("readDisposition")
                        .and_then(|v| serde_json::from_value(v.clone()).ok());
                    Some(OutboundEvent::Receipt {
                        chat_id: m.chat_id,
                        message_id: m.id,
                        sender_msg_id: m.sender_msg_id,
                        sender_id: m.sender_id,
                        read_at,
                        read_disposition,
                    })
                });
            // Convert the augmented wire-format Value into a typed
            // PatchObject (RFC 8620 §5.3). Non-object values yield
            // invalidPatch.
            let patch = match serde_json::from_value::<PatchObject>(augmented) {
                Ok(p) => p,
                Err(e) => {
                    not_updated.insert(
                        id_str,
                        json!({ "type": "invalidPatch", "description": e.to_string() }),
                    );
                    continue;
                }
            };
            // draft-atwood-jmap-chat-00 §Message `burnOnRead` (jmap-chat-spec
            // 77c3474 L750): "SHOULD permanently hard-delete this message
            // (row removal, not tombstone) immediately after setting
            // `readAt`." Done by choice, as one atomic
            // backend call, so a failure commits nothing and a retry
            // burns again.
            let burns = patch_sets_read_at && pre_patch_burn_on_read;
            let update_outcome = if burns {
                backend
                    .read_and_burn_message(caller, &account_id, &id, patch)
                    .await
                    .map(|()| None)
            } else {
                backend
                    .update_object::<Message>(caller, &account_id, &id, patch)
                    .await
            };
            let maybe_updated_obj = match update_outcome {
                Ok(maybe_obj) => maybe_obj,
                Err(e) => {
                    not_updated.insert(id_str, backend_set_error_value(e));
                    continue;
                }
            };

            // Update (or burn) succeeded.
            mutated = true;
            // draft-atwood-jmap-chat-federation-00 §Peer/retract "Sender
            // Behavior": an update that sets `deletedForAll: true` "MUST
            // send `Peer/retract` to the server of every other participant
            // in the Chat". Reported only once the update is written, so a
            // failed write retracts nothing on peers.
            if let Some(event @ OutboundEvent::Retract { .. }) = &outbound {
                backend.on_outbound_event(caller, &account_id, event).await;
            }
            // draft-atwood-jmap-chat-00 §Editing a Message: "Send
            // `Peer/deliver` carrying an `edit` payload to all
            // recipients". A patch that also deletes or burns the Message
            // leaves nothing to deliver.
            if let Some(event @ OutboundEvent::Edit { .. }) = &outbound
                && !deletes
                && !burns
            {
                backend.on_outbound_event(caller, &account_id, event).await;
            }
            // draft-atwood-jmap-chat-00 §Adding and Removing Reactions:
            // propagate each add and removal "via `Peer/deliver`
            // `reactionUpdate` payload". As for edits, a patch that also
            // deletes or burns the Message leaves nothing to deliver.
            if !deletes && !burns {
                for event in &reaction_events {
                    backend.on_outbound_event(caller, &account_id, event).await;
                }
            }
            // §Peer/receipt "Sender Behavior": "If the effective preference
            // is `false`, the server SHOULD NOT invoke `Peer/receipt`". A
            // burned Message was still read, so its receipt is reported.
            if let Some(event @ OutboundEvent::Receipt { chat_id, .. }) = &receipt
                && shares_receipts(backend, caller, &account_id, chat_id).await
            {
                backend.on_outbound_event(caller, &account_id, event).await;
            }
            match maybe_updated_obj {
                Some(obj) => {
                    updated.insert(id_str, jmap_server::serialize_value(&obj)?);
                }
                None => {
                    updated.insert(id_str, Value::Null);
                }
            }
        }
    }

    // -----------------------------------------------------------------------
    // destroy
    // -----------------------------------------------------------------------
    if let Some(destroy_arr) = args.get("destroy").and_then(|v| v.as_array()) {
        // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
        // Reject the whole request if any element is non-string rather than
        // silently skipping it, which would produce a misleading response.
        let id_strs: Vec<&str> = destroy_arr
            .iter()
            .map(|v| {
                v.as_str().ok_or_else(|| {
                    JmapError::invalid_arguments(format!(
                        "destroy: every element must be a string Id; got {}",
                        jmap_server::json_type_name(v)
                    ))
                })
            })
            .collect::<Result<_, _>>()?;
        // The destroyed Messages' Chats, read before the destroy, for
        // `record_unread_count_changes` (§Chat `unreadCount`).
        // A malformed id is skipped here and rejected per entry below.
        let destroy_ids: Vec<Id> = destroy_arr
            .iter()
            .filter_map(Value::as_str)
            .filter_map(|s| Id::new_validated(s).ok())
            .collect();
        let chat_of: HashMap<Id, Id> = backend
            .get_objects::<Message>(caller, &account_id, Some(&destroy_ids), None)
            .await
            .map(|(found, _)| found.into_iter().map(|m| (m.id, m.chat_id)).collect())
            .unwrap_or_default();
        let mut destroyed_chat_ids: Vec<Id> = Vec::new();
        for id_str in id_strs {
            let id = match jmap_server::parse_wire_id(id_str, "id") {
                Ok(id) => id,
                Err(err) => {
                    not_destroyed.insert(id_str.to_owned(), serde_json::Value::from(&*err));
                    continue;
                }
            };

            match backend
                .destroy_object::<Message>(caller, &account_id, &id)
                .await
            {
                Ok(()) => {
                    mutated = true;
                    destroyed_chat_ids.extend(chat_of.get(&id).cloned());
                    destroyed_list.push(Value::String(id_str.to_owned()));
                }
                Err(e) => {
                    not_destroyed.insert(id_str.to_owned(), backend_set_error_value(e));
                }
            }
        }
        record_unread_count_changes(backend, caller, &account_id, destroyed_chat_ids).await;
    }

    finalize_set_response::<B, Message>(
        backend,
        caller,
        &account_id,
        old_state,
        mutated,
        SetAccumulators {
            created,
            updated,
            destroyed: destroyed_list,
            not_created,
            not_updated,
            not_destroyed,
        },
    )
    .await
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::memory::MemoryBackend;
    use serde_json::json;

    const ACCOUNT_ID: &str = "a1";

    // Oracles in this module are hand-built per workspace test-integrity
    // policy. Each test asserts the wire shape of a known-invalid or
    // known-valid broadcastMentions payload against the validation rules
    // from spec §4.4.1 / §4.16. The independent oracle is the spec text
    // itself; no assertion uses the code under test as its own reference.

    /// §BroadcastMention: "Servers MUST reject a BroadcastMention with an
    /// unrecognized `scope` value; in `Message/set` the rejection is an
    /// `invalidProperties` SetError naming `broadcastMentions`."
    #[tokio::test]
    async fn broadcast_mention_validation_rejects_unknown_scope() {
        let backend = MemoryBackend::<()>::default();
        backend.register_account(&Id::from(ACCOUNT_ID));
        let HandlerOutput { primary: resp, .. } = handle_message_set(
            &backend,
            &(),
            &std::collections::BTreeMap::new(),
            json!({
                "accountId": ACCOUNT_ID,
                "create": {
                    "m0": {
                        "chatId": "c1",
                        "body": "Hello @channel",
                        "sentAt": "2024-01-01T00:00:00Z",
                        "broadcastMentions": [
                            { "scope": "channel", "offset": 6, "length": 8 }
                        ]
                    }
                }
            }),
            &[],
        )
        .await
        .expect("handle_message_set");

        assert!(resp["notCreated"]["m0"].is_object());
        assert_eq!(resp["notCreated"]["m0"]["type"], "invalidProperties");
        assert_eq!(
            resp["notCreated"]["m0"]["properties"],
            json!(["broadcastMentions"])
        );
        let desc = resp["notCreated"]["m0"]["description"]
            .as_str()
            .expect("description");
        assert!(
            desc.contains("unrecognized scope"),
            "expected 'unrecognized scope' in description, got: {desc}"
        );
    }

    /// A valid @everyone mention at the correct body offset succeeds.
    #[tokio::test]
    async fn broadcast_mention_validation_accepts_valid() {
        let backend = MemoryBackend::<()>::default();
        let chat_id = make_group_chat(&backend).await;
        let body = "Hello @everyone!";
        let HandlerOutput { primary: resp, .. } = handle_message_set(
            &backend,
            &(),
            &std::collections::BTreeMap::new(),
            json!({
                "accountId": ACCOUNT_ID,
                "create": {
                    "m0": {
                        "chatId": chat_id,
                        "body": body,
                        "sentAt": "2024-01-01T00:00:00Z",
                        "broadcastMentions": [
                            { "scope": "everyone", "offset": 6, "length": 9 }
                        ]
                    }
                }
            }),
            &[],
        )
        .await
        .expect("handle_message_set");

        assert!(
            resp["created"]["m0"].is_object(),
            "expected created, got notCreated: {}",
            resp["notCreated"]["m0"]
        );
    }

    /// An empty broadcastMentions array is always valid.
    #[tokio::test]
    async fn broadcast_mention_validation_accepts_empty() {
        let backend = MemoryBackend::<()>::default();
        let chat_id = make_group_chat(&backend).await;
        let HandlerOutput { primary: resp, .. } = handle_message_set(
            &backend,
            &(),
            &std::collections::BTreeMap::new(),
            json!({
                "accountId": ACCOUNT_ID,
                "create": {
                    "m0": {
                        "chatId": chat_id,
                        "body": "Hello, world!",
                        "sentAt": "2024-01-01T00:00:00Z",
                        "broadcastMentions": []
                    }
                }
            }),
            &[],
        )
        .await
        .expect("handle_message_set");

        assert!(
            resp["created"]["m0"].is_object(),
            "expected created, got notCreated: {}",
            resp["notCreated"]["m0"]
        );
    }

    // -----------------------------------------------------------------------
    // BroadcastMention permission-check tests (§4.4.1 mention_broadcast)
    //
    // Oracle: the spec text itself. Group/direct chats without a spaceId
    // are unrestricted; channel chats with a spaceId must pass the
    // mention_broadcast gate. The channel fixture's owner role holds
    // mention_broadcast, so these tests verify the handler CODE PATH is
    // wired correctly and that the gate is skipped or invoked in the
    // right circumstances; tests/message_broadcast_permission_memory.rs
    // covers denial.
    // -----------------------------------------------------------------------

    /// Helper: create a group Chat (no spaceId) via handle_chat_set and
    /// return its server-assigned id.
    async fn make_group_chat(backend: &MemoryBackend<()>) -> String {
        backend.register_account(&Id::from(ACCOUNT_ID));
        let HandlerOutput { primary: resp, .. } = crate::chat::handle_chat_set(
            backend,
            &(),
            &std::collections::BTreeMap::new(),
            json!({
                "accountId": ACCOUNT_ID,
                "create": { "c0": { "kind": "group", "name": "test-group" } }
            }),
            &[],
        )
        .await
        .expect("make_group_chat");
        resp["created"]["c0"]["id"]
            .as_str()
            .expect("group chat id")
            .to_owned()
    }

    /// Helper: seed a Space whose owner member (the accountId, per
    /// §SpaceMember `id`) holds `manage_channels` and `send` (§Message/set,
    /// jmap-chat-spec 77c3474 L1220: "For channel Chats, the server SHOULD
    /// verify the sender holds the `"send"` permission"), then create a channel Chat inside it, and
    /// return the channel's server-assigned id.
    async fn make_channel_chat(backend: &MemoryBackend<()>) -> String {
        let space_id = "s0";
        backend.insert_object_for_test(
            "Space",
            ACCOUNT_ID,
            space_id,
            json!({
                "id": space_id,
                "name": "test-space",
                "createdAt": "2026-01-01T00:00:00Z",
                "memberCount": 1,
                "categories": [],
                "uncategorizedChannelIds": [],
                "isPublic": false,
                "isPubliclyPreviewable": false,
                "roles": [{ "id": "r-owner", "name": "Owner", "permissions": ["manage_channels", "mention_broadcast", "send"], "position": 10 }],
                "members": [{ "id": ACCOUNT_ID, "roleIds": ["r-owner"], "joinedAt": "2026-01-01T00:00:00Z" }],
            }),
        );

        // Create a channel Chat in that Space. §Chat/set: "Channel Chats
        // are created exclusively via the `addChannels` patch key in
        // `Space/set`." §Space/set `addChannels`: "Requires
        // `"manage_channels"`."
        crate::space::handle_space_set(
            backend,
            &(),
            &std::collections::BTreeMap::new(),
            json!({
                "accountId": ACCOUNT_ID,
                "update": { space_id: { "addChannels": [{ "name": "general" }] } }
            }),
            &[],
        )
        .await
        .expect("make_channel_chat: addChannels");
        let HandlerOutput {
            primary: get_resp, ..
        } = crate::space::handle_space_get(
            backend,
            &(),
            json!({ "accountId": ACCOUNT_ID, "ids": [space_id] }),
            &[],
        )
        .await
        .expect("make_channel_chat: Space/get");
        get_resp["list"][0]["uncategorizedChannelIds"][0]
            .as_str()
            .expect("channel chat id")
            .to_owned()
    }

    /// Create a Message with broadcastMentions in a group chat (no spaceId).
    /// The permission check must be SKIPPED (unrestricted per spec),
    /// and the message must succeed.
    #[tokio::test]
    async fn broadcast_mention_create_without_space_unrestricted() {
        let backend = MemoryBackend::<()>::default();
        let chat_id = make_group_chat(&backend).await;

        let body = "Hello @everyone!";
        let HandlerOutput { primary: resp, .. } = handle_message_set(
            &backend,
            &(),
            &std::collections::BTreeMap::new(),
            json!({
                "accountId": ACCOUNT_ID,
                "create": {
                    "m0": {
                        "chatId": chat_id,
                        "body": body,
                        "sentAt": "2024-01-01T00:00:00Z",
                        "broadcastMentions": [
                            { "scope": "everyone", "offset": 6, "length": 9 }
                        ]
                    }
                }
            }),
            &[],
        )
        .await
        .expect("handle_message_set");

        assert!(
            resp["created"]["m0"].is_object(),
            "expected created in group chat (no spaceId), got notCreated: {}",
            resp["notCreated"]["m0"]
        );
    }

    /// Create a Message with broadcastMentions in a channel chat (has spaceId).
    /// The owner holds mention_broadcast in the Space, so the message
    /// must succeed.
    #[tokio::test]
    async fn broadcast_mention_create_in_channel_succeeds() {
        let backend = MemoryBackend::<()>::default();
        let chat_id = make_channel_chat(&backend).await;

        let body = "Hello @everyone!";
        let HandlerOutput { primary: resp, .. } = handle_message_set(
            &backend,
            &(),
            &std::collections::BTreeMap::new(),
            json!({
                "accountId": ACCOUNT_ID,
                "create": {
                    "m0": {
                        "chatId": chat_id,
                        "body": body,
                        "sentAt": "2024-01-01T00:00:00Z",
                        "broadcastMentions": [
                            { "scope": "everyone", "offset": 6, "length": 9 }
                        ]
                    }
                }
            }),
            &[],
        )
        .await
        .expect("handle_message_set");

        assert!(
            resp["created"]["m0"].is_object(),
            "expected created in channel chat, got notCreated: {}",
            resp["notCreated"]["m0"]
        );
    }

    /// Create a Message with empty broadcastMentions in a channel chat.
    /// The permission check must NOT fire (empty array skips the gate).
    #[tokio::test]
    async fn broadcast_mention_create_empty_skips_permission_check() {
        let backend = MemoryBackend::<()>::default();
        let chat_id = make_channel_chat(&backend).await;

        let HandlerOutput { primary: resp, .. } = handle_message_set(
            &backend,
            &(),
            &std::collections::BTreeMap::new(),
            json!({
                "accountId": ACCOUNT_ID,
                "create": {
                    "m0": {
                        "chatId": chat_id,
                        "body": "Hello, world!",
                        "sentAt": "2024-01-01T00:00:00Z",
                        "broadcastMentions": []
                    }
                }
            }),
            &[],
        )
        .await
        .expect("handle_message_set");

        assert!(
            resp["created"]["m0"].is_object(),
            "expected created with empty broadcastMentions, got notCreated: {}",
            resp["notCreated"]["m0"]
        );
    }

    /// Update a Message to retain non-empty broadcastMentions in a channel chat.
    /// The owner holds mention_broadcast in the Space, so the update
    /// must succeed.
    #[tokio::test]
    async fn broadcast_mention_update_retaining_broadcast_succeeds() {
        let backend = MemoryBackend::<()>::default();
        let chat_id = make_channel_chat(&backend).await;

        // Create a message with broadcastMentions first.
        let body = "Hello @everyone!";
        let HandlerOutput {
            primary: create_resp,
            ..
        } = handle_message_set(
            &backend,
            &(),
            &std::collections::BTreeMap::new(),
            json!({
                "accountId": ACCOUNT_ID,
                "create": {
                    "m0": {
                        "chatId": chat_id,
                        "body": body,
                        "sentAt": "2024-01-01T00:00:00Z",
                        "broadcastMentions": [
                            { "scope": "everyone", "offset": 6, "length": 9 }
                        ]
                    }
                }
            }),
            &[],
        )
        .await
        .expect("create message");
        let msg_id = create_resp["created"]["m0"]["id"]
            .as_str()
            .expect("message id");

        // Update the message, retaining a non-empty broadcastMentions.
        let new_body = "Hey @here now!";
        let HandlerOutput {
            primary: update_resp,
            ..
        } = handle_message_set(
            &backend,
            &(),
            &std::collections::BTreeMap::new(),
            json!({
                "accountId": ACCOUNT_ID,
                "update": {
                    (msg_id): {
                        "body": new_body,
                        "broadcastMentions": [
                            { "scope": "here", "offset": 4, "length": 5 }
                        ]
                    }
                }
            }),
            &[],
        )
        .await
        .expect("update message");

        assert!(
            update_resp["updated"][msg_id].is_null() || update_resp["updated"][msg_id].is_object(),
            "expected updated, got notUpdated: {}",
            update_resp["notUpdated"][msg_id]
        );
        assert!(
            update_resp["notUpdated"].is_null()
                || !update_resp["notUpdated"]
                    .as_object()
                    .is_some_and(|m| m.contains_key(msg_id)),
            "message should not be in notUpdated"
        );
    }
}