jmap-chat-server 0.6.1

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
//! Chat/* method handlers (draft-atwood-jmap-chat-00 §Chat).
//!
//! # 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 §Chat. The returned
//! `Value` is the corresponding method-response object per the same
//! section refs. `Chat/typing` (draft §Chat) is a Chat-specific signal
//! method with its own request/response shape.
//!
//! 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` surface in the `notCreated` / `notUpdated`
//! / `notDestroyed` maps within `Ok((Value, ...))`, not as `Err`.

use std::collections::{BTreeMap, HashMap, HashSet};

use jmap_chat_types::ChatComparator;
use jmap_chat_types::SPEC_CHAT_MEMBER_ROLES;
use jmap_chat_types::{Chat, ChatKind, ChatMember, ChatMemberRole, Message, ReadPosition};
use jmap_types::{Id, JmapError, PatchObject, UTCDate};
use serde::Deserialize;
use serde_json::{Value, json};

use crate::ChatBackend;
use crate::helpers::{
    MetadataMaps, PropType, check_metadata_entry, create_metadata, mistyped_create_props,
};
use crate::helpers::{
    SetAccumulators, default_sort, enforce_max_objects_in_set, extract_account_id,
    finalize_set_response, now_utc_string, refusal_value, reject_unsupported_sort,
};
use crate::helpers::{resolve_entry_refs, resolve_refs, resolved_create, strip_read_only_patch};
use crate::outbound::{GroupUpdateAction, OutboundEvent};
use jmap_server::{
    HandlerOutput, backend_set_error_value, is_client_updatable, reject_server_set,
    server_fail_from_backend, server_fail_value_from_backend,
};
use jmap_server::{SetError, SetErrorType};

/// `Chat/set` update keys that change a group Chat's member list
/// (draft-atwood-jmap-chat-00 §Chat/set "Updating a Chat").
const MEMBER_PATCH_KEYS: &[&str] = &["addMembers", "removeMembers", "updateMemberRoles"];

/// `Chat/set` update keys, beyond [`MEMBER_PATCH_KEYS`], that a closed
/// group rejects (draft-atwood-jmap-chat-00 §Chat `closedAt`).
const SHARED_GROUP_KEYS: &[&str] = &["name", "description", "avatarBlobId", "pinnedMessageIds"];

/// `Chat/set` update keys only a group Chat's admins may change
/// (draft-atwood-jmap-chat-00 §Chat/set "Updating a Chat": "For group
/// chats, admins additionally may update: `name`, `description`,
/// `avatarBlobId`.").
const GROUP_ADMIN_KEYS: &[&str] = &["name", "description", "avatarBlobId"];

/// Chat properties draft-atwood-jmap-chat-00 §Chat Object Fields scopes
/// to one kind ("**Direct chats only.**", "**Group chats only.**",
/// "**Channel Chats only.**"), with that kind. `name` is "**Group and
/// channel Chats.**", and `Chat/set` never creates a channel, so a group
/// is the only created kind that carries it. A `Chat/set` create of
/// another kind that carries one is `invalidProperties` (RFC 8620 §5.3).
const KIND_SCOPED_CREATE_PROPS: &[(&str, ChatKind)] = &[
    ("contactId", ChatKind::Direct),
    ("name", ChatKind::Group),
    ("description", ChatKind::Group),
    ("avatarBlobId", ChatKind::Group),
    ("spaceId", ChatKind::Channel),
];

/// Whether `account_id` holds the `"admin"` role in `chat.members`.
pub(crate) fn is_chat_admin(chat: &Chat, account_id: &Id) -> bool {
    chat.members
        .iter()
        .flatten()
        .any(|m| m.id == *account_id && m.role == ChatMemberRole::Admin)
}

/// One `addMembers` or `updateMemberRoles` entry.
#[derive(Deserialize)]
struct MemberRoleEntry {
    id: Id,
    role: Option<ChatMemberRole>,
}

/// Apply the member patch keys in `patch` to `chat.members` on behalf of
/// `owner_id` and return the resulting member list, and whether the
/// patch closes the group.
///
/// Per draft-atwood-jmap-chat-00 §Chat/set "Updating a Chat":
/// - a malformed entry, or a `role` other than `"admin"` or `"member"`,
///   is `invalidProperties` naming the key; an `updateMemberRoles` entry
///   must carry a `role` and name a current member;
/// - "all require admin role, except leaving the group": a non-admin may
///   only send `removeMembers` listing just their own id, else
///   `forbidden`. `owner_id` is the accountId, which references the owner
///   (draft §Terminology), so a non-admin owner leaves with
///   `removeMembers: [accountId]`; the keys apply to group chats only;
/// - more members than `max_members` after `addMembers` is `overQuota`;
/// - "If the owner is the last admin and other members remain, leaving
///   closes the group": the caller was an admin, is removed, and members
///   but no admin remain.
///
/// Per the implementer guide's "Deployments SHOULD avoid admin-less open
/// groups by refusing to let the last admin demote themselves via
/// `updateMemberRoles`", an `updateMemberRoles` patch that leaves members
/// but no admin is `forbidden`.
fn apply_member_patch_keys(
    chat: &Chat,
    owner_id: &Id,
    patch: &serde_json::Map<String, Value>,
    max_members: u32,
) -> Result<(Vec<ChatMember>, bool), Box<SetError>> {
    fn parse<T: serde::de::DeserializeOwned>(
        patch: &serde_json::Map<String, Value>,
        key: &str,
    ) -> Result<Option<T>, Box<SetError>> {
        patch
            .get(key)
            .map(|v| serde_json::from_value(v.clone()))
            .transpose()
            .map_err(|_| {
                Box::new(SetError::new(SetErrorType::InvalidProperties).with_properties([key]))
            })
    }
    let valid_role = |role: &ChatMemberRole| SPEC_CHAT_MEMBER_ROLES.contains(&role.as_str());
    let invalid =
        |key: &str| Box::new(SetError::new(SetErrorType::InvalidProperties).with_properties([key]));
    let forbidden =
        |desc: &str| Box::new(SetError::new(SetErrorType::Forbidden).with_description(desc));

    let add: Option<Vec<MemberRoleEntry>> = parse(patch, "addMembers")?;
    let remove: Option<Vec<Id>> = parse(patch, "removeMembers")?;
    let update: Option<Vec<MemberRoleEntry>> = parse(patch, "updateMemberRoles")?;
    if add
        .iter()
        .flatten()
        .any(|e| e.role.as_ref().is_some_and(|r| !valid_role(r)))
    {
        return Err(invalid("addMembers"));
    }
    if update
        .iter()
        .flatten()
        .any(|e| !e.role.as_ref().is_some_and(valid_role))
    {
        return Err(invalid("updateMemberRoles"));
    }

    if chat.kind != ChatKind::Group {
        return Err(forbidden("member patch keys apply to group chats only"));
    }
    let is_admin = is_chat_admin(chat, owner_id);
    let mut members = chat.members.clone().unwrap_or_default();
    let self_leave = add.is_none()
        && update.is_none()
        && remove.as_deref() == Some(std::slice::from_ref(owner_id));
    if !is_admin && !self_leave {
        return Err(forbidden("only group chat admins may change members"));
    }

    if let Some(add) = &add {
        let now = UTCDate::from(now_utc_string().as_ref());
        for entry in add {
            if members.iter().all(|m| m.id != entry.id) {
                let role = entry.role.clone().unwrap_or(ChatMemberRole::Member);
                let mut m = ChatMember::new(entry.id.clone(), role, now.clone());
                m.invited_by = Some(owner_id.clone());
                members.push(m);
            }
        }
        if members.len() > max_members as usize {
            return Err(Box::new(
                SetError::new(SetErrorType::OverQuota)
                    .with_description("group chat member limit exceeded"),
            ));
        }
    }
    if let Some(remove) = &remove {
        members.retain(|m| !remove.contains(&m.id));
    }
    if let Some(update) = &update {
        for entry in update {
            let member = members
                .iter_mut()
                .find(|m| m.id == entry.id)
                .ok_or_else(|| invalid("updateMemberRoles"))?;
            member.role = entry.role.clone().expect("role checked above");
        }
        if !members.is_empty() && members.iter().all(|m| m.role != ChatMemberRole::Admin) {
            return Err(forbidden("the last admin may not demote themselves"));
        }
    }
    let closes = is_admin
        && members.iter().all(|m| m.id != *owner_id)
        && !members.is_empty()
        && members.iter().all(|m| m.role != ChatMemberRole::Admin);
    Ok((members, closes))
}

/// Whether a `ChatBan` in force bans any of `user_ids` from Chat `chat_id`
/// (draft-atwood-jmap-chat-00 §`ChatBan`).
///
/// ponytail: loads every `ChatBan` of the account per call. A backend with
/// many bans should index them by Chat.
async fn banned_among<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    chat_id: &Id,
    user_ids: &[&Id],
) -> Result<bool, B::Error> {
    let (bans, _) = backend
        .get_objects::<jmap_chat_types::ChatBan>(caller, account_id, None, None)
        .await?;
    let now = UTCDate::from(now_utc_string().as_ref());
    Ok(bans.iter().any(|b| {
        b.chat_id == *chat_id
            && user_ids.contains(&&b.user_id)
            && crate::chat_ban::chat_ban_is_active(b, &now)
    }))
}

/// Ids of `members` other than the owner, who is referenced by the
/// accountId (draft-atwood-jmap-chat-00 §Terminology).
fn other_member_ids<'a>(
    members: impl IntoIterator<Item = &'a ChatMember>,
    owner_id: &Id,
) -> Vec<Id> {
    members
        .into_iter()
        .filter(|m| m.id != *owner_id)
        .map(|m| m.id.clone())
        .collect()
}

/// The `Peer/groupUpdate` events for a successful `Chat/set` update of
/// the group `before`, in [`GroupUpdateAction`] order.
///
/// `after` is the member list the update stored (`None` when it did not
/// touch members) and `closes` whether it closed the group;
/// `metadata_changed` is whether it patched `name`, `description` or
/// `avatarBlobId`. The member actions are the difference between the two
/// lists, so a no-op entry (adding a current member, re-assigning a
/// member's role) reports nothing. The owner's own removal is `"leave"`
/// or `"close"`, not `"removeMembers"`
/// (draft-atwood-jmap-chat-federation-00 §Peer/groupUpdate: `"leave"` "is
/// equivalent to `"removeMembers"` with `removedMemberIds:
/// [senderUserId]`"). Recipients follow draft-atwood-jmap-chat-00
/// §Chat/set "Updating a Chat".
fn group_update_events(
    chat_id: &Id,
    owner_id: &Id,
    before: &[ChatMember],
    after: Option<&[ChatMember]>,
    closes: bool,
    metadata_changed: bool,
) -> Vec<OutboundEvent> {
    let after = after.unwrap_or(before);
    let find = |list: &[ChatMember], id: &Id| list.iter().find(|m| m.id == *id).cloned();
    let everyone = other_member_ids(after, owner_id);
    let mut actions = Vec::new();
    if metadata_changed {
        actions.push((GroupUpdateAction::UpdateMetadata, everyone.clone()));
    }
    let added: Vec<ChatMember> = after
        .iter()
        .filter(|m| find(before, &m.id).is_none())
        .cloned()
        .collect();
    if !added.is_empty() {
        actions.push((GroupUpdateAction::AddMembers { added }, everyone.clone()));
    }
    let removed_ids = other_member_ids(
        before.iter().filter(|m| find(after, &m.id).is_none()),
        owner_id,
    );
    if !removed_ids.is_empty() {
        let mut recipients = everyone.clone();
        recipients.extend(removed_ids.iter().cloned());
        actions.push((GroupUpdateAction::RemoveMembers { removed_ids }, recipients));
    }
    let updated: Vec<ChatMember> = after
        .iter()
        .filter(|m| find(before, &m.id).is_some_and(|old| old.role != m.role))
        .cloned()
        .collect();
    if !updated.is_empty() {
        actions.push((GroupUpdateAction::UpdateRoles { updated }, everyone.clone()));
    }
    if find(before, owner_id).is_some() && find(after, owner_id).is_none() {
        let action = if closes {
            GroupUpdateAction::Close
        } else {
            GroupUpdateAction::Leave
        };
        actions.push((action, everyone));
    }
    actions
        .into_iter()
        .map(|(action, recipients)| OutboundEvent::GroupUpdate {
            chat_id: chat_id.clone(),
            action,
            recipients,
        })
        .collect()
}

// ---------------------------------------------------------------------------
// Chat/get
// ---------------------------------------------------------------------------

/// Handle a `Chat/get` method call (draft-atwood-jmap-chat-00 §Chat).
///
/// `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`).
///
/// `unreadCount` is computed on every call (§Chat, jmap-chat-spec aa01dd7
/// L635): "Candidates are the Messages whose `id` ULID is
/// lexicographically greater than `ReadPosition.lastReadMessageId`, or
/// all Messages in the Chat if `lastReadMessageId` is absent. Which
/// candidates count is implementation-defined; for example, a server MAY
/// exclude Messages the owner sent." This server does not count Messages
/// the owner sent (`senderId` is the accountId), so a Chat with no
/// [`ReadPosition`] counts every Message from others. A backend whose
/// [`ChatSettings::maintains_unread_count`](crate::ChatSettings::maintains_unread_count) is `true` gets its stored
/// value back instead.
///
/// `using` is the request's capability list (pass
/// [`jmap_server::CallContext::using`]). When the backend lists Chat 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::handle_get_with_metadata`].
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
///
/// # Errors
///
/// Returns a method-level [`JmapError`]: those of
/// [`jmap_server::handle_get_with_metadata`], and `serverFail` when reading
/// the Messages and `ReadPosition`s behind `unreadCount` fails.
// NOTE: properties forwarded via handle_get
pub async fn handle_chat_get<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
    using: &[String],
) -> Result<HandlerOutput, JmapError> {
    let mut out =
        jmap_server::handle_get_with_metadata::<Chat, B>(backend, caller, args, using).await?;
    fill_unread_counts(backend, caller, &mut out.primary).await?;
    Ok(out)
}

/// Overwrite `unreadCount` on each Chat in a `Chat/get` response `list`
/// that carries the property (it is absent when `properties` leaves it
/// out), unless the backend maintains the count itself
/// ([`ChatSettings::maintains_unread_count`](crate::ChatSettings::maintains_unread_count)).
// ponytail: scans every Message and ReadPosition in the account per call
// (O(messages) per Chat/get); a backend with many messages keeps its own
// count via ChatSettings::maintains_unread_count.
async fn fill_unread_counts<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    response: &mut Value,
) -> Result<(), JmapError> {
    if backend.maintains_unread_count() {
        return Ok(());
    }
    // Id::from: the accountId this handler already validated and echoed.
    let account_id = Id::from(response["accountId"].as_str().unwrap_or_default());
    let Some(list) = response["list"].as_array_mut() else {
        return Ok(());
    };
    if !list.iter().any(|c| c.get("unreadCount").is_some()) {
        return Ok(());
    }
    let (messages, positions) = messages_and_positions(backend, caller, &account_id).await?;
    for chat in list.iter_mut() {
        let Some(chat) = chat.as_object_mut() else {
            continue;
        };
        if !chat.contains_key("unreadCount") {
            continue;
        }
        let Some(chat_id) = chat.get("id").and_then(Value::as_str) else {
            continue;
        };
        let unread = unread_count(&messages, &positions, &account_id, chat_id);
        chat.insert("unreadCount".to_owned(), Value::from(unread));
    }
    Ok(())
}

async fn messages_and_positions<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
) -> Result<(Vec<Message>, Vec<ReadPosition>), JmapError> {
    let (messages, _) = 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))?;
    Ok((messages, positions))
}

/// §Chat `unreadCount` for `chat_id`: Messages in the Chat not sent by
/// the owner (`senderId` is not `account_id`) whose `id` sorts after the
/// owner's `lastReadMessageId`, or all of them when it is absent.
/// jmap-chat-spec aa01dd7 L635: "Which candidates count is
/// implementation-defined; for example, a server MAY exclude Messages the
/// owner sent." The owner's own messages never count, so a sender does
/// not see a message they just sent as unread.
pub(crate) fn unread_count(
    messages: &[Message],
    positions: &[ReadPosition],
    account_id: &Id,
    chat_id: &str,
) -> u64 {
    let last_read = positions
        .iter()
        .find(|p| p.chat_id.as_ref() == chat_id)
        .and_then(|p| p.last_read_message_id.as_ref());
    messages
        .iter()
        .filter(|m| m.chat_id.as_ref() == chat_id && m.sender_id != *account_id)
        .filter(|m| last_read.is_none_or(|l| m.id.as_ref() > l.as_ref()))
        .count() as u64
}

/// Write the recomputed `unreadCount` to each Chat in `chat_ids` so the
/// `Chat` state advances and `Chat/changes` reports the Chat as updated.
///
/// RFC 8620 §5.1: "If the data changes, this string MUST change", and
/// §ReadPosition/set (jmap-chat-spec 33702a5 L1434) "updates
/// `Chat.unreadCount` for the affected Chat, possibly later". `Chat/get`
/// derives the count on every call, so a [`ReadPosition`] update or a Message
/// create/destroy changes Chat data; this records that change through
/// [`ChatStore::update_object`](crate::ChatStore::update_object), whose contract bumps the type state
/// and logs the id as updated. Does nothing when the backend maintains
/// the count itself ([`ChatSettings::maintains_unread_count`](crate::ChatSettings::maintains_unread_count)).
///
/// Best-effort, like [`crate::message::ensure_read_positions`]: the
/// caller's own write already succeeded and its response must report
/// it, so a failure here (including a Chat that no longer exists) is
/// not surfaced.
pub(crate) async fn record_unread_count_changes<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    mut chat_ids: Vec<Id>,
) {
    if chat_ids.is_empty() || backend.maintains_unread_count() {
        return;
    }
    let Ok((messages, positions)) = messages_and_positions(backend, caller, account_id).await
    else {
        return;
    };
    chat_ids.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
    chat_ids.dedup();
    for chat_id in chat_ids {
        let unread = unread_count(&messages, &positions, account_id, chat_id.as_ref());
        let mut patch = PatchObject::new();
        patch
            .as_map_mut()
            .insert("unreadCount".to_owned(), Value::from(unread));
        let _ = backend
            .update_object::<Chat>(caller, account_id, &chat_id, patch)
            .await;
    }
}

// ---------------------------------------------------------------------------
// Chat/changes
// ---------------------------------------------------------------------------

/// Handle a `Chat/changes` method call (draft-atwood-jmap-chat-00 §Chat).
///
/// `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.
///
/// # Errors
///
/// Returns a method-level [`JmapError`]:
///
/// - `invalidArguments` when `accountId` is missing or not a valid Id,
///   `sinceState` is missing, `maxChanges` is not a positive integer, or
///   `ignoreMetadataOnlyChanges` is not a boolean;
/// - `accountNotFound` when the backend does not know `accountId`;
/// - `cannotCalculateChanges` when the backend cannot compute the changes
///   since `sinceState`;
/// - `serverFail` when the backend fails.
pub async fn handle_chat_changes<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
    using: &[String],
) -> Result<HandlerOutput, JmapError> {
    jmap_server::handle_changes::<Chat, B>(backend, caller, args, using).await
}

// ---------------------------------------------------------------------------
// Chat/query
// ---------------------------------------------------------------------------

/// Handle a `Chat/query` method call (draft-atwood-jmap-chat-00 §Chat).
///
/// `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).
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
///
/// # Errors
///
/// Returns a method-level [`JmapError`]:
///
/// - `invalidArguments` when `accountId` is missing or not a valid Id, or
///   when `filter`, `sort`, `position`, `anchor`, `anchorOffset` or `limit`
///   is malformed;
/// - `accountNotFound` when the backend does not know `accountId`;
/// - `unsupportedFilter` when the filter does not decode as a Chat filter, or
///   holds a draft-ietf-jmap-metadata-05 §3.6 condition without
///   `urn:ietf:params:jmap:metadata` in `using`;
/// - `unsupportedSort` when `sort` names a property this server does not
///   define;
/// - `anchorNotFound` when `anchor` is not in the results;
/// - `serverFail` when the backend fails, or any other RFC 8620 §5.5 error
///   the backend returns.
pub async fn handle_chat_query<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::ChatFilterCondition::has_metadata_condition,
        using,
    )?;
    // §Chat/query: "Default sort: `lastMessageAt` descending; chats
    // without messages sort last."
    if let Value::Object(map) = &mut args {
        default_sort(
            map,
            json!([{ "property": "lastMessageAt", "isAscending": false }]),
        );
    }
    reject_unsupported_sort::<ChatComparator>(args.get("sort"))?;
    jmap_server::handle_query::<Chat, B>(backend, caller, args).await
}

// ---------------------------------------------------------------------------
// Chat/queryChanges
// ---------------------------------------------------------------------------

/// Handle a `Chat/queryChanges` method call (draft-atwood-jmap-chat-00 §Chat).
///
/// `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`).
///
/// `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).
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
///
/// # Errors
///
/// Returns a method-level [`JmapError`]:
///
/// - `invalidArguments` when `accountId` is missing or not a valid Id,
///   `sinceQueryState` is missing, or `filter`, `sort`, `maxChanges` or
///   `upToId` is malformed;
/// - `accountNotFound` when the backend does not know `accountId`;
/// - `unsupportedFilter` when the filter does not decode as a Chat filter, or
///   holds a draft-ietf-jmap-metadata-05 §3.6 condition without
///   `urn:ietf:params:jmap:metadata` in `using`;
/// - `unsupportedSort` when `sort` names a property this server does not
///   define;
/// - `cannotCalculateChanges` when the backend cannot compute the changes
///   since `sinceQueryState`;
/// - `serverFail` when the backend fails, or any other RFC 8620 §5.6 error
///   the backend returns.
pub async fn handle_chat_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::ChatFilterCondition::has_metadata_condition,
        using,
    )?;
    // RFC 8620 §5.6: the `filter` and `sort` are those of the original
    // query, so the §Chat/query default sort applies here too.
    if let Value::Object(map) = &mut args {
        default_sort(
            map,
            json!([{ "property": "lastMessageAt", "isAscending": false }]),
        );
    }
    reject_unsupported_sort::<ChatComparator>(args.get("sort"))?;
    jmap_server::handle_query_changes::<Chat, B>(backend, caller, args).await
}

// ---------------------------------------------------------------------------
// Chat/set
// ---------------------------------------------------------------------------

/// The Chat create and update properties that hold the id of another record, which a
/// client may set to a `#creationId` reference (RFC 8620 §5.3).
const CHAT_ID_PROPERTIES: &[&str] = &[
    "contactId",
    "memberIds",
    "pinnedMessageIds",
    "removeMembers",
    KICK_MEMBERS_KEY,
];

/// The `Chat/set` update key draft-atwood-jmap-chat-mimi-00 §Moderation
/// adds "for Chats bound to a room" (String\[], `ChatContact` ids).
const KICK_MEMBERS_KEY: &str = "kickMembers";

/// Remove [`KICK_MEMBERS_KEY`] from `patch` and return its ids, or `None`
/// when the key is absent or lists no one (a kick of nobody is a no-op).
///
/// # Errors
///
/// A value that is not an array of strings, or an element that is not a
/// valid Id (RFC 8620 §1.2), is `invalidProperties` naming the key.
fn take_kick_members(
    patch: &mut serde_json::Map<String, Value>,
) -> Result<Option<Vec<Id>>, Box<SetError>> {
    let Some(value) = patch.remove(KICK_MEMBERS_KEY) else {
        return Ok(None);
    };
    let invalid = || {
        Box::new(SetError::new(SetErrorType::InvalidProperties).with_properties([KICK_MEMBERS_KEY]))
    };
    let Value::Array(items) = value else {
        return Err(invalid());
    };
    let ids = items
        .iter()
        .map(|v| {
            v.as_str()
                .and_then(|s| jmap_server::parse_wire_id(s, KICK_MEMBERS_KEY).ok())
                .ok_or_else(invalid)
        })
        .collect::<Result<Vec<Id>, _>>()?;
    Ok((!ids.is_empty()).then_some(ids))
}

/// The Chat update entry fields that hold a `ChatContact` id, as
/// `(patch key, entry field, property named on failure)`: draft-atwood-jmap-chat-00
/// §Chat/set "Updating a Chat" gives each `addMembers` and
/// `updateMemberRoles` entry an `id`, a `ChatContact` id.
const CHAT_ENTRY_ID_PROPERTIES: &[(&str, &str, &str)] = &[
    ("addMembers", "id", "addMembers"),
    ("updateMemberRoles", "id", "updateMemberRoles"),
];

/// Handle a `Chat/set` method call (draft-atwood-jmap-chat-00 §Chat).
///
/// `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):
/// - `kind` is required on create.
/// - `direct` chats require `contactId`.
/// - `channel` chats are `forbidden` on create and destroy (managed via
///   `Space/set` `addChannels` / `removeChannels`).
/// - a group create whose membership exceeds
///   [`ChatLimits::max_group_chat_members`](crate::ChatLimits::max_group_chat_members)
///   is `overQuota`.
/// - an update key outside §Chat/set "Updating a Chat" is
///   `invalidProperties`; `name`, `description` and `avatarBlobId` updates
///   are `forbidden` unless the Chat is a group and the caller is an admin.
/// - `pinnedMessageIds` updates are gated by
///   [`ChatAccessPolicy::may_set_pinned_messages`](crate::ChatAccessPolicy::may_set_pinned_messages).
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
///
/// A `contactId`, a `memberIds`, `pinnedMessageIds` or `removeMembers`
/// element, or the `id` of an `addMembers` or `updateMemberRoles` entry,
/// that is a `#creationId` reference names a record created earlier in the request and resolves against
/// `created_ids` (pass [`jmap_server::CallContext::created_ids`]; RFC 8620
/// §5.3); an unknown reference is `invalidProperties` naming the property.
///
/// `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.
///
/// # Errors
///
/// Returns a method-level [`JmapError`]:
///
/// - `invalidArguments` when `accountId` is missing or not a valid Id, or
///   an element of `destroy` is not a string;
/// - `accountNotFound` when the backend does not know `accountId`;
/// - `requestTooLarge` when `create`, `update` and `destroy` together hold
///   more than `maxObjectsInSet` objects;
/// - `stateMismatch` when `ifInState` is not the current state;
/// - `serverFail` when the backend fails.
///
/// A create, update or destroy that fails on its own is a [`SetError`] in
/// the response, not an `Err`.
pub async fn handle_chat_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, &["avatarBlobId"], 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::<Chat>(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 ctx = SetCtx {
        backend,
        caller,
        account_id: &account_id,
        created_ids,
        using,
    };
    let mut acc = SetAccumulators::default();
    let mut mutated = set_create(&ctx, &mut args, &mut acc).await?;
    // 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, &acc.created);
    mutated |= set_update(&ctx, &mut args, &mut acc).await?;
    mutated |= set_destroy(&ctx, &mut args, &mut acc).await?;

    finalize_set_response::<B, Chat>(backend, caller, &account_id, old_state, mutated, acc).await
}

/// What every `Chat/set` sub-function needs from the request
/// (docs/design/set-handler-split.md).
struct SetCtx<'a, B: ChatBackend> {
    backend: &'a B,
    caller: &'a B::CallerCtx,
    account_id: &'a Id,
    /// The request-wide `#creationId` map (RFC 8620 §5.3).
    created_ids: &'a BTreeMap<Id, Id>,
    /// The request's `using` capabilities.
    using: &'a [String],
}

/// What the `Chat/set` create loop carries from one entry to the next:
/// the Direct-chat contact ids already taken.
struct CreateRun {
    /// The account's Chats, read once before the loop when the batch has
    /// a Direct create; empty otherwise.
    existing_chats: Vec<Chat>,
    /// `contactId`s of the account's Direct chats, including those created
    /// earlier in this batch.
    known_direct_contact_ids: HashSet<String>,
    /// Maps contactId -> assigned `new_id` for Direct chats successfully
    /// created earlier in this batch. Used to resolve intra-batch
    /// duplicates without a re-fetch (JMAP-63k.12).
    batch_direct_ids: HashMap<String, Id>,
}

/// The `create` part of `Chat/set`. Returns whether the backend was
/// written.
async fn set_create<B: ChatBackend>(
    ctx: &SetCtx<'_, B>,
    args: &mut serde_json::Map<String, Value>,
    acc: &mut SetAccumulators,
) -> Result<bool, JmapError> {
    let mut mutated = false;
    if let Some(create_map) = args.get("create").and_then(|v| v.as_object()) {
        let mut run = create_run(ctx, create_map).await?;
        for (create_id, obj_val) in create_map {
            mutated |= create_one(ctx, create_id, obj_val, acc, &mut run).await?;
        }
    }
    Ok(mutated)
}

/// The [`CreateRun`] a `Chat/set` create batch starts with.
async fn create_run<B: ChatBackend>(
    ctx: &SetCtx<'_, B>,
    create_map: &serde_json::Map<String, Value>,
) -> Result<CreateRun, JmapError> {
    // Only pay the cost of a full get_objects fetch when the batch contains
    // at least one Direct create (JMAP-63k.4).
    let has_direct_create = create_map.values().any(|v| {
        v.get("kind")
            .and_then(|k| k.as_str())
            .is_some_and(|s| s.eq_ignore_ascii_case("direct"))
    });

    // Fetch all existing chats once before the loop. For a batch of N
    // creates against an account with K existing chats this is O(K + N)
    // reads (one full-account scan + a HashSet lookup per create) rather
    // than the naive O(N * K) of one fetch per create. The per-batch fetch
    // still scales linearly in the account's chat count K, so production
    // backends serving accounts with large K should push the
    // contact-id-uniqueness check into a typed query method on
    // ChatBackend rather than rely on this hoisted scan (tracked by
    // JMAP-63k.9). Skipped entirely for non-Direct batches.
    let (existing_chats, known_direct_contact_ids): (Vec<Chat>, HashSet<String>) =
        if has_direct_create {
            let (chats, _) = ctx
                .backend
                .get_objects::<Chat>(ctx.caller, ctx.account_id, None, None)
                .await
                .map_err(|e| server_fail_from_backend(&e))?;
            let known = chats
                .iter()
                .filter(|c| c.kind == ChatKind::Direct)
                .filter_map(|c| c.contact_id.as_ref().map(|id| id.as_ref().to_owned()))
                .collect();
            (chats, known)
        } else {
            (Vec::new(), HashSet::new())
        };
    Ok(CreateRun {
        existing_chats,
        known_direct_contact_ids,
        batch_direct_ids: HashMap::new(),
    })
}

/// One `create` entry of `Chat/set`. Returns whether the backend was
/// written.
async fn create_one<B: ChatBackend>(
    ctx: &SetCtx<'_, B>,
    create_id: &str,
    obj_val: &Value,
    acc: &mut SetAccumulators,
    run: &mut CreateRun,
) -> Result<bool, JmapError> {
    let resolved = match resolved_create(obj_val, CHAT_ID_PROPERTIES, ctx.created_ids) {
        Ok(v) => v,
        Err(err) => {
            acc.not_created
                .insert(create_id.to_owned(), serde_json::Value::from(&*err));
            return Ok(false);
        }
    };
    let obj_val = &resolved;
    let checked =
        check_create_props(obj_val, ctx.using).and_then(|maps| Ok((maps, create_kind(obj_val)?)));
    let ((metadata, private_metadata), kind) = match checked {
        Ok(checked) => checked,
        Err(err) => {
            acc.not_created.insert(create_id.to_owned(), err);
            return Ok(false);
        }
    };
    let direct_contact_id_str = match direct_contact_id(&kind, obj_val, run)? {
        Ok(contact) => contact,
        Err(err) => {
            acc.not_created.insert(create_id.to_owned(), err);
            return Ok(false);
        }
    };
    let now_str = now_utc_string();
    let now: UTCDate = UTCDate::from(now_str.as_ref());
    let members = match create_members(ctx, &kind, obj_val, &now) {
        Ok(members) => members,
        Err(err) => {
            acc.not_created.insert(create_id.to_owned(), err);
            return Ok(false);
        }
    };

    let opts = match create_optionals(obj_val) {
        Ok(opts) => opts,
        Err(err) => {
            acc.not_created.insert(create_id.to_owned(), err);
            return Ok(false);
        }
    };
    let build = |id: &Id| {
        let mut chat = Chat::new(
            id.clone(),
            kind,
            now,
            0,
            vec![],
            opts.muted,
            opts.receive_typing_indicators,
        );
        chat.contact_id = opts.contact_id;
        chat.name = opts.name;
        chat.description = opts.description;
        chat.avatar_blob_id = opts.avatar_blob_id;
        chat.message_expiry_seconds = opts.message_expiry_seconds;
        chat.members = members;
        chat.metadata = metadata;
        chat.private_metadata = private_metadata;
        chat
    };

    match ctx
        .backend
        .create_object::<Chat, _>(ctx.caller, ctx.account_id, create_id, build)
        .await
    {
        Ok((new_id, created_obj)) => {
            // The create is committed; every branch below (including
            // rollback and cleanup failure) has moved backend state,
            // so newState must be re-read (RFC 8620 §5.3).
            let direct = direct_contact_id_str.as_deref();
            after_create(ctx, create_id, new_id, created_obj, direct, acc, run).await?;
            Ok(true)
        }
        Err(e) => {
            acc.not_created
                .insert(create_id.to_owned(), backend_set_error_value(e));
            Ok(false)
        }
    }
}

/// Check the metadata and wrongly-typed properties of one `Chat/set`
/// create object and return its metadata maps, or the [`SetError`] value for
/// `notCreated`.
fn check_create_props(obj_val: &Value, using: &[String]) -> Result<MetadataMaps, Value> {
    if let Some(Err(err)) = obj_val
        .as_object()
        .map(|o| check_metadata_entry(o, true, using))
    {
        return Err(serde_json::Value::from(&*err));
    }
    // draft-ietf-jmap-metadata-05 §3.2: the create sets the
    // metadata properties; the backend validates them.
    let maps = create_metadata(obj_val)?;
    // 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,
        &[
            ("contactId", PropType::Str),
            ("name", PropType::Str),
            ("description", PropType::Str),
            ("avatarBlobId", PropType::Str),
            ("messageExpirySeconds", PropType::UnsignedInt),
            ("spaceId", PropType::Str),
            ("muted", PropType::Bool),
            ("receiveTypingIndicators", PropType::Bool),
        ],
    ) {
        return Err(err);
    }
    Ok(maps)
}

/// The `kind` of one `Chat/set` create object, checked together with the
/// kind-scoped and server-set properties, or the [`SetError`] value for
/// `notCreated`.
fn create_kind(obj_val: &Value) -> Result<ChatKind, Value> {
    // kind is required.
    let Some(kind_str) = obj_val
        .get("kind")
        .and_then(|v| v.as_str())
        .map(str::to_owned)
    else {
        return Err(json!({ "type": "invalidProperties", "properties": ["kind"] }));
    };

    // ChatKind::Other(_) is the deserialize-from-wire forward-compat
    // catch-all: it preserves round-trip fidelity when reading data
    // produced by a future server that knows a new spec variant. It
    // is NOT a legitimate value on /set create — a client supplying
    // an unrecognised kind must be rejected with invalidProperties,
    // otherwise junk Chats end up in storage and break every
    // downstream kind-dispatched invariant (kind-specific required
    // field checks, /get response shape, Message/set chatId
    // resolution, etc.).
    let kind = match serde_json::from_value::<ChatKind>(Value::String(kind_str)) {
        Ok(k) if !matches!(k, ChatKind::Other(_)) => k,
        _ => return Err(json!({ "type": "invalidProperties", "properties": ["kind"] })),
    };

    // A channel create is `forbidden` below whatever it carries.
    // `null` is read as absent, as in `mistyped_create_props`.
    if kind != ChatKind::Channel {
        let foreign: Vec<&str> = KIND_SCOPED_CREATE_PROPS
            .iter()
            .filter(|(prop, scope)| {
                *scope != kind && obj_val.get(*prop).is_some_and(|v| !v.is_null())
            })
            .map(|(prop, _)| *prop)
            .collect();
        if !foreign.is_empty() {
            return Err(json!({ "type": "invalidProperties", "properties": foreign }));
        }
        if let Some(err) = obj_val.as_object().and_then(reject_server_set::<Chat>) {
            return Err(serde_json::Value::from(&err));
        }
    }
    Ok(kind)
}

/// The `contactId` of a Direct `Chat/set` create, checked against the
/// Direct chats already known to `run`; `None` for a group. The inner
/// `Err` is the [`SetError`] value for `notCreated`.
///
/// `Some(id)` for Direct chats and `None` for all other kinds — it
/// simultaneously encodes the "is direct" flag and the contact ID,
/// avoiding a bool+Option pair whose invariant (Some iff direct) would
/// otherwise be implicit.
fn direct_contact_id(
    kind: &ChatKind,
    obj_val: &Value,
    run: &CreateRun,
) -> Result<Result<Option<String>, Value>, JmapError> {
    match kind {
        ChatKind::Direct => {
            let Some(contact_id_str) = obj_val
                .get("contactId")
                .and_then(|v| v.as_str())
                .map(str::to_owned)
            else {
                return Ok(Err(
                    json!({ "type": "invalidProperties", "properties": ["contactId"] }),
                ));
            };
            let stored_direct = |c: &&Chat| {
                c.kind == ChatKind::Direct
                    && c.contact_id.as_ref().map(|id| id.as_ref()) == Some(contact_id_str.as_str())
            };

            // Pre-check: reject if a direct chat with this contactId is
            // already known from the hoisted fetch.
            if let Some(dup) = run.existing_chats.iter().find(stored_direct) {
                return Ok(Err(serde_json::Value::from(
                    SetError::new(SetErrorType::AlreadyExists).with_existing_id(dup.id.clone()),
                )));
            }
            // Also check contactIds created earlier in this same batch.
            // Resolve the canonical id from the hoisted pre-fetch data or
            // from the batch map — no re-fetch required (JMAP-63k.12).
            if run.known_direct_contact_ids.contains(&contact_id_str) {
                // Try the pre-fetch snapshot first (pre-existing chat).
                let canonical_id = if let Some(c) = run.existing_chats.iter().find(stored_direct) {
                    c.id.clone()
                } else if let Some(id) = run.batch_direct_ids.get(&contact_id_str) {
                    // Created earlier in this batch.
                    id.clone()
                } else {
                    // Should not happen: known_direct_contact_ids is only
                    // populated from existing_chats and batch_direct_ids.
                    return Ok(Err(json!({
                        "type": "serverFail",
                        "description": "direct chat for contact not found after concurrent operation; retry"
                    })));
                };
                return Ok(Err(jmap_server::serialize_value(
                    SetError::new(SetErrorType::AlreadyExists).with_existing_id(canonical_id),
                )?));
            }
            Ok(Ok(Some(contact_id_str)))
        }
        // §Chat/set: "Creating a Chat with `kind: "channel"` via
        // `Chat/set` is not supported; the server MUST return a
        // SetError of type `forbidden`."
        ChatKind::Channel => Ok(Err(json!({ "type": "forbidden" }))),
        _ => Ok(Ok(None)),
    }
}

/// The `memberIds` of a group `Chat/set` create (`None` for another
/// kind), or the [`SetError`] value for `notCreated`.
///
/// Group create: "`memberIds` (String[], required): ChatContact.ids
/// of additional initial members." Absent is tolerated for
/// backward compatibility; a non-String[] value is rejected.
fn create_member_ids(kind: &ChatKind, obj_val: &Value) -> Result<Option<Vec<Id>>, Value> {
    if *kind != ChatKind::Group {
        return Ok(None);
    }
    match obj_val.get("memberIds") {
        None => Ok(Some(Vec::new())),
        Some(v) => match serde_json::from_value::<Vec<String>>(v.clone()) {
            Ok(ids) => ids
                .iter()
                .map(|s| jmap_server::parse_wire_id(s, "memberIds"))
                .collect::<Result<Vec<Id>, _>>()
                .map(Some)
                .map_err(|err| serde_json::Value::from(&*err)),
            Err(_) => Err(json!({ "type": "invalidProperties", "properties": ["memberIds"] })),
        },
    }
}

/// The initial `members` of a group `Chat/set` create (`None` for another
/// kind), or the [`SetError`] value for `notCreated`.
fn create_members<B: ChatBackend>(
    ctx: &SetCtx<'_, B>,
    kind: &ChatKind,
    obj_val: &Value,
    now: &UTCDate,
) -> Result<Option<Vec<ChatMember>>, Value> {
    let members = initial_members(create_member_ids(kind, obj_val)?, ctx.account_id, now);

    // Group create `memberIds`: "If the resulting membership would
    // exceed a server-defined limit on the number of members per
    // group Chat, the server MUST return an `overQuota` SetError".
    let max_members = ctx
        .backend
        .limits(ctx.caller, ctx.account_id)
        .max_group_chat_members;
    if members
        .as_ref()
        .is_some_and(|m| m.len() > max_members as usize)
    {
        return Err(json!({
            "type": "overQuota",
            "description": "group chat member limit exceeded",
        }));
    }
    Ok(members)
}

/// The initial `members` of a created group Chat, from its checked
/// `memberIds`.
///
/// "The server [...] adds the creator to `members` with at least
/// one role granting permissions sufficient to administer the
/// chat": the creator is `"admin"`, each distinct memberIds entry
/// is `"member"` invited by the creator. The creator is the owner,
/// referenced by the accountId (§Terminology).
fn initial_members(
    member_ids: Option<Vec<Id>>,
    account_id: &Id,
    now: &UTCDate,
) -> Option<Vec<ChatMember>> {
    member_ids.map(|ids| {
        let creator: Id = account_id.clone();
        let mut members = vec![ChatMember::new(
            creator.clone(),
            ChatMemberRole::Admin,
            now.clone(),
        )];
        for id in ids {
            if members.iter().all(|m| m.id != id) {
                let mut m = ChatMember::new(id, ChatMemberRole::Member, now.clone());
                m.invited_by = Some(creator.clone());
                members.push(m);
            }
        }
        members
    })
}

/// The optional properties of a `Chat/set` create, checked.
struct CreateOptionals {
    contact_id: Option<Id>,
    name: Option<String>,
    description: Option<String>,
    muted: bool,
    receive_typing_indicators: bool,
    avatar_blob_id: Option<Id>,
    message_expiry_seconds: Option<u64>,
}

/// The [`CreateOptionals`] of one `Chat/set` create object, or the
/// [`SetError`] value for `notCreated`.
fn create_optionals(obj_val: &Value) -> Result<CreateOptionals, Value> {
    let contact_id: Option<Id> = match obj_val.get("contactId").and_then(|v| v.as_str()) {
        Some(s) => Some(
            jmap_server::parse_wire_id(s, "contactId")
                .map_err(|err| serde_json::Value::from(&*err))?,
        ),
        None => None,
    };
    let name: Option<String> = obj_val
        .get("name")
        .and_then(|v| v.as_str())
        .map(str::to_owned);
    let description: Option<String> = obj_val
        .get("description")
        .and_then(|v| v.as_str())
        .map(str::to_owned);
    let muted: bool = obj_val
        .get("muted")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let receive_typing_indicators: bool = obj_val
        .get("receiveTypingIndicators")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);

    // "Optional at creation: `description` (String), `avatarBlobId`
    // (String), `messageExpirySeconds` (UnsignedInt)."
    let avatar_blob_id = match obj_val.get("avatarBlobId").and_then(Value::as_str) {
        Some(s) => Some(
            jmap_server::parse_wire_id(s, "avatarBlobId")
                .map_err(|err| serde_json::Value::from(&*err))?,
        ),
        None => None,
    };
    let message_expiry_seconds = obj_val.get("messageExpirySeconds").and_then(Value::as_u64);
    Ok(CreateOptionals {
        contact_id,
        name,
        description,
        muted,
        receive_typing_indicators,
        avatar_blob_id,
        message_expiry_seconds,
    })
}

/// What follows a committed `Chat/set` create: the Direct-chat duplicate
/// re-check (which may roll the create back into `notCreated`), the group
/// `Peer/groupUpdate`, and the `created` entry.
async fn after_create<B: ChatBackend>(
    ctx: &SetCtx<'_, B>,
    create_id: &str,
    new_id: Id,
    created_obj: Chat,
    direct_contact_id_str: Option<&str>,
    acc: &mut SetAccumulators,
    run: &mut CreateRun,
) -> Result<(), JmapError> {
    if let Some(contact_id_str) = direct_contact_id_str {
        if let Some(err) = direct_race_error(ctx, &new_id, contact_id_str).await {
            acc.not_created.insert(create_id.to_owned(), err);
            return Ok(());
        }
        // Exactly one (or we won): record contactId as known so
        // subsequent creates in this batch are pre-checked.
        run.known_direct_contact_ids
            .insert(contact_id_str.to_owned());
        run.batch_direct_ids
            .insert(contact_id_str.to_owned(), new_id.clone());
    }
    // §Creating a Chat: the server "MUST send
    // `Peer/groupUpdate` to each initial member".
    if created_obj.kind == ChatKind::Group {
        let event = OutboundEvent::GroupUpdate {
            chat_id: new_id.clone(),
            action: GroupUpdateAction::Create,
            recipients: other_member_ids(created_obj.members.iter().flatten(), ctx.account_id),
        };
        ctx.backend
            .on_outbound_event(ctx.caller, ctx.account_id, &event)
            .await;
    }
    acc.created.insert(
        create_id.to_owned(),
        jmap_server::serialize_value(&created_obj)?,
    );
    Ok(())
}

/// Re-check a committed Direct-chat create `new_id` for a concurrent
/// duplicate with the same `contactId`, and roll it back when it lost.
/// Returns the [`SetError`] value for `notCreated`, or `None` when the create
/// stands.
///
/// Optimistic create-then-validate, required for JMAP-0c9. We fetch all
/// chats because the backend does not currently expose a filter-by-kind
/// query; a tighter fetch (Direct only) would be preferable but requires
/// backend support (JMAP-63k.9).
async fn direct_race_error<B: ChatBackend>(
    ctx: &SetCtx<'_, B>,
    new_id: &Id,
    contact_id_str: &str,
) -> Option<Value> {
    let current_chats = match ctx
        .backend
        .get_objects::<Chat>(ctx.caller, ctx.account_id, None, None)
        .await
    {
        Ok((chats, _)) => chats,
        Err(read_err) => {
            // The Chat (and earlier creates in this
            // batch) are already committed, so a
            // method-level serverFail would break
            // RFC 8620 §3.6.2 ("The method call made
            // no changes to the server's state").
            // Without the re-check the draft's
            // alreadyExists rule cannot be enforced,
            // so roll this create back and fail it
            // per id; the batch continues.
            let value = match ctx
                .backend
                .destroy_object::<Chat>(ctx.caller, ctx.account_id, new_id)
                .await
            {
                Ok(()) => server_fail_value_from_backend(&read_err),
                Err(e) => server_fail_value_from_backend(&e),
            };
            return Some(value);
        }
    };
    let duplicates: Vec<&Chat> = current_chats
        .iter()
        .filter(|c| {
            c.kind == ChatKind::Direct
                && c.contact_id.as_ref().map(|id| id.as_ref()) == Some(contact_id_str)
        })
        .collect();
    if duplicates.len() > 1 {
        // Race occurred: pick lexicographically smallest id
        // as the canonical winner.
        let canonical_id: Id = duplicates
            .iter()
            .map(|c| c.id.as_ref())
            .min()
            .map(Id::from)
            .unwrap_or_else(|| new_id.clone());
        if *new_id != canonical_id {
            // We lost the race: destroy our copy.
            if let Err(e) = ctx
                .backend
                .destroy_object::<Chat>(ctx.caller, ctx.account_id, new_id)
                .await
            {
                // Cleanup failed — the duplicate is still
                // live. Return a retryable server error
                // rather than alreadyExists with a
                // potentially inconsistent state.
                //
                // Route through server_fail_value_from_backend
                // to redact backend Display text from the
                // wire description per workspace redaction
                // discipline.
                return Some(server_fail_value_from_backend(&e));
            }
            // Cleanup succeeded: report alreadyExists
            // pointing to the canonical winner.
            return Some(
                serde_json::to_value(
                    SetError::new(SetErrorType::AlreadyExists).with_existing_id(canonical_id),
                )
                .unwrap_or_else(|e| server_fail_value_from_backend(&e)),
            );
        }
        // We won the race (our id is canonical): fall through
        // to success path below.
    }
    None
}

/// The `update` part of `Chat/set`. Returns whether the backend was
/// written.
async fn set_update<B: ChatBackend>(
    ctx: &SetCtx<'_, B>,
    args: &mut serde_json::Map<String, Value>,
    acc: &mut SetAccumulators,
) -> Result<bool, JmapError> {
    let mut mutated = false;
    if let Some(Value::Object(update_map)) = args.remove("update") {
        for (id_str, patch_val) in update_map {
            mutated |= update_one(ctx, id_str, patch_val, acc).await?;
        }
    }
    Ok(mutated)
}

/// One `update` entry of `Chat/set`. Returns whether the backend was
/// written.
async fn update_one<B: ChatBackend>(
    ctx: &SetCtx<'_, B>,
    id_str: String,
    patch_val: Value,
    acc: &mut SetAccumulators,
) -> Result<bool, JmapError> {
    let id = match jmap_server::parse_wire_id(&id_str, "id") {
        Ok(id) => id,
        Err(err) => {
            acc.not_updated
                .insert(id_str, serde_json::Value::from(&*err));
            return Ok(false);
        }
    };
    let mut patch = match update_patch(patch_val, ctx.created_ids, ctx.using) {
        Ok(patch) => patch,
        Err(err) => {
            acc.not_updated.insert(id_str, err);
            return Ok(false);
        }
    };
    let chat = match update_target(ctx, &id, &patch).await {
        Ok(chat) => chat,
        Err(err) => {
            acc.not_updated.insert(id_str, err);
            return Ok(false);
        }
    };

    // Existence and permission come before shape (DECISIONS.md 44):
    // a changed read-only value and an undefined key are held in
    // `shape_err` and reported only after the `forbidden` checks
    // below, which look at patch keys alone.
    let shape_err = update_shape_error(&mut patch, &chat);
    let (kick, group_before) = match update_gates(ctx, &chat, &mut patch).await {
        Ok(gates) => gates,
        Err(err) => {
            acc.not_updated.insert(id_str, err);
            return Ok(false);
        }
    };

    // Nothing left once identical values are dropped (or a literal
    // `{}`): a no-op success with no write (RFC 8620 §5.3).
    if patch.is_empty() && kick.is_none() {
        acc.updated.insert(id_str, Value::Null);
        return Ok(false);
    }

    let member_change = match apply_member_keys(ctx, &chat, &mut patch)? {
        Ok(change) => change,
        Err(err) => {
            acc.not_updated.insert(id_str, err);
            return Ok(false);
        }
    };
    if let Some(err) = update_policy_error(ctx, &id, &chat, &patch, member_change.as_ref()).await {
        acc.not_updated.insert(id_str, err);
        return Ok(false);
    }

    // Every `forbidden` check that needs no write has run: report a
    // held shape error now (DECISIONS.md 44).
    if let Some(err) = shape_err {
        acc.not_updated.insert(id_str, err);
        return Ok(false);
    }
    if let Some(err) = pinned_ids_error(ctx, &id, &chat, &patch).await {
        acc.not_updated.insert(id_str, err);
        return Ok(false);
    }

    // draft-atwood-jmap-chat-mimi-00 §Moderation: `kickMembers`
    // "removes the listed users' clients from the group but keeps
    // them in the participant list". `members` is not touched; the
    // backend decides whether the Chat is bound to a room and the
    // caller may kick (`canKick`).
    // ponytail: the kick and the rest of the patch are two backend
    // calls; a failed write after a kick leaves the kick applied.
    if let Some(user_ids) = &kick {
        let outcome = ctx
            .backend
            .kick_chat_members(ctx.caller, ctx.account_id, &chat, user_ids)
            .await;
        if let Some(err) = refusal_value(outcome) {
            acc.not_updated.insert(id_str, err);
            return Ok(false);
        }
        // Nothing else to write: the Chat record is unchanged.
        if patch.is_empty() {
            acc.updated.insert(id_str, Value::Null);
            return Ok(false);
        }
    }

    write_update(ctx, id_str, &id, patch, group_before, member_change, acc).await
}

/// Resolve the `#creationId` references of one `Chat/set` update patch and
/// convert it into a typed [`PatchObject`], or return the [`SetError`] value for
/// `notUpdated`.
fn update_patch(
    mut patch_val: Value,
    created_ids: &BTreeMap<Id, Id>,
    using: &[String],
) -> Result<PatchObject, Value> {
    if let Err(err) = resolve_refs(&mut patch_val, CHAT_ID_PROPERTIES, created_ids)
        .and_then(|()| resolve_entry_refs(&mut patch_val, CHAT_ENTRY_ID_PROPERTIES, created_ids))
    {
        return Err(serde_json::Value::from(&*err));
    }

    // 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))
    {
        return Err(serde_json::Value::from(&*err));
    }
    if let Some(Err(e)) = patch_val.as_object().map(jmap_server::check_patch_paths) {
        return Err(json!({ "type": "invalidPatch", "description": e.to_string() }));
    }

    // Convert wire-format Value into a typed PatchObject. RFC 8620
    // §5.3 mandates a PatchObject is a JSON Object; non-object
    // values produce an `invalidPatch` SetError.
    serde_json::from_value::<PatchObject>(patch_val)
        .map_err(|e| json!({ "type": "invalidPatch", "description": e.to_string() }))
}

/// The stored Chat `id` a `Chat/set` update targets, read once for every
/// check, or the [`SetError`] value for `notUpdated`.
async fn update_target<B: ChatBackend>(
    ctx: &SetCtx<'_, B>,
    id: &Id,
    patch: &PatchObject,
) -> Result<Chat, Value> {
    let stored = match ctx
        .backend
        .get_objects::<Chat>(
            ctx.caller,
            ctx.account_id,
            Some(std::slice::from_ref(id)),
            None,
        )
        .await
    {
        Ok((chats, _)) => chats.into_iter().next(),
        Err(e) => return Err(server_fail_value_from_backend(&e)),
    };
    let Some(mut chat) = stored else {
        return Err(Value::from(&SetError::new(SetErrorType::NotFound)));
    };

    // `unreadCount` is server-set, and when the backend does not
    // maintain it the "current server value" a client can echo is
    // the one Chat/get computes (fill_unread_counts), not the stored
    // field, so compare against that (bd:JMAP-t8ej.32 item 3).
    if patch.as_map().contains_key("unreadCount") && !ctx.backend.maintains_unread_count() {
        let (messages, positions) = messages_and_positions(ctx.backend, ctx.caller, ctx.account_id)
            .await
            .map_err(|e| server_fail_value_from_backend(&e))?;
        chat.unread_count = unread_count(&messages, &positions, ctx.account_id, chat.id.as_ref());
    }
    Ok(chat)
}

/// Whether `k` is a `Chat/set` update key §Chat/set "Updating a Chat"
/// defines: the client-settable Chat properties that are not immutable,
/// and [`MEMBER_PATCH_KEYS`], plus the mimi draft's [`KICK_MEMBERS_KEY`]
/// (whole key only). JSON Pointer paths count by their first segment.
fn is_defined_update_key(k: &str) -> bool {
    let top = k.split('/').next().unwrap_or(k);
    is_client_updatable::<Chat>(top) || MEMBER_PATCH_KEYS.contains(&top) || k == KICK_MEMBERS_KEY
}

/// Drop the read-only values of a `Chat/set` update patch that are
/// identical to `chat`, and return the shape error the patch still has:
/// a changed read-only value, or an undefined key (`invalidProperties`).
///
/// 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.
fn update_shape_error(patch: &mut PatchObject, chat: &Chat) -> Option<Value> {
    let shape_err = strip_read_only_patch::<Chat>(patch.as_map_mut(), chat).err();
    if shape_err.is_some() {
        return shape_err;
    }
    // Only the keys §Chat/set "Updating a Chat" defines may be
    // patched (`is_defined_update_key`). Any other key is
    // `invalidProperties`.
    let bad_props: Vec<&str> = patch
        .as_map()
        .keys()
        .map(String::as_str)
        .filter(|k| !is_defined_update_key(k))
        .collect();
    (!bad_props.is_empty()).then(|| json!({ "type": "invalidProperties", "properties": bad_props }))
}

/// The `forbidden` gates of a `Chat/set` update that look at patch keys
/// alone: `ChatRestrictions::may_update_chat`, the `kickMembers` shape,
/// a closed group, and the group admin keys. Takes `kickMembers` out of
/// `patch` and returns its ids and, for a group update that touches
/// members or shared settings, the stored member list for
/// `group_update_events`. `Err` is the [`SetError`] value for `notUpdated`.
async fn update_gates<B: ChatBackend>(
    ctx: &SetCtx<'_, B>,
    chat: &Chat,
    patch: &mut PatchObject,
) -> Result<(Option<Vec<Id>>, Option<Vec<ChatMember>>), Value> {
    // Per-Chat restrictions of extension-bound Chats; see
    // `ChatRestrictions::may_update_chat`. It sees only the keys
    // the update may change.
    let patch_keys: Vec<&str> = patch
        .as_map()
        .keys()
        .map(String::as_str)
        .filter(|k| is_defined_update_key(k))
        .collect();
    let outcome = ctx
        .backend
        .may_update_chat(ctx.caller, ctx.account_id, chat, &patch_keys)
        .await;
    if let Some(err) = refusal_value(outcome) {
        return Err(err);
    }

    // draft-atwood-jmap-chat-mimi-00 §Moderation `kickMembers`: an
    // operation, not a property, taken out of the patch here and
    // handed to `ChatModeration::kick_chat_members` before the write.
    let kick =
        take_kick_members(patch.as_map_mut()).map_err(|err| serde_json::Value::from(&*err))?;

    // draft-atwood-jmap-chat-00 §Chat `closedAt`: "After it is
    // set, the server MUST reject with a `forbidden` SetError ...
    // every `Chat/set` update that changes membership ... or
    // shared group settings". Pointer paths beneath them count.
    // The stored group and the member list the update stores, for
    // `group_update_events` once the update succeeds.
    let mut group_before: Option<Vec<ChatMember>> = None;
    let touches_closed_keys = patch.as_map().keys().any(|k| {
        let top = k.split('/').next().unwrap_or(k);
        MEMBER_PATCH_KEYS.contains(&top) || SHARED_GROUP_KEYS.contains(&top)
    });
    if touches_closed_keys {
        if chat.closed_at.is_some() {
            return Err(json!({ "type": "forbidden", "description": "the group is closed" }));
        }
        // "For group chats, admins additionally may update:
        // `name`, `description`, `avatarBlobId`."
        let touches_admin_keys = patch
            .as_map()
            .keys()
            .any(|k| GROUP_ADMIN_KEYS.contains(&k.split('/').next().unwrap_or(k)));
        if touches_admin_keys
            && !(chat.kind == ChatKind::Group && is_chat_admin(chat, ctx.account_id))
        {
            return Err(json!({
                "type": "forbidden",
                "description": "only group chat admins may update name, description and avatarBlobId",
            }));
        }
        if chat.kind == ChatKind::Group {
            group_before = Some(chat.members.clone().unwrap_or_default());
        }
    }
    Ok((kick, group_before))
}

/// The member list a `Chat/set` update stores, and whether it closes the
/// group.
type MemberChange = (Vec<ChatMember>, bool);

/// Apply the member patch keys of a `Chat/set` update to the stored list
/// and replace them in `patch` by the resulting `members` (and
/// `closedAt` when the change closes the group). Returns that member list
/// and whether it closes the group, or `None` when the patch has no
/// member key. The inner `Err` is the [`SetError`] value for `notUpdated`.
///
/// draft-atwood-jmap-chat-00 §Chat/set "Updating a Chat": the
/// member patch keys are operations on `members`, not
/// properties. They are applied to the stored list here and
/// replaced by the resulting `members`, so the backend never
/// stores them.
/// ponytail: check-then-update is not atomic; two concurrent
/// member patches can lose one. A backend needing strictness
/// re-checks inside its update transaction.
fn apply_member_keys<B: ChatBackend>(
    ctx: &SetCtx<'_, B>,
    chat: &Chat,
    patch: &mut PatchObject,
) -> Result<Result<Option<MemberChange>, Value>, JmapError> {
    if !MEMBER_PATCH_KEYS
        .iter()
        .any(|k| patch.as_map().contains_key(*k))
    {
        return Ok(Ok(None));
    }
    let max_members = ctx
        .backend
        .limits(ctx.caller, ctx.account_id)
        .max_group_chat_members;
    match apply_member_patch_keys(chat, ctx.account_id, patch.as_map(), max_members) {
        Ok((members, closes)) => {
            let member_change = Some((members.clone(), closes));
            let map = patch.as_map_mut();
            for key in MEMBER_PATCH_KEYS {
                map.remove(*key);
            }
            map.insert("members".to_owned(), jmap_server::serialize_value(members)?);
            // "the server MUST set `closedAt` ({{chat}}) in
            // the same operation".
            if closes {
                map.insert("closedAt".to_owned(), json!(now_utc_string()));
            }
            Ok(Ok(member_change))
        }
        Err(set_err) => Ok(Err(serde_json::Value::from(&*set_err))),
    }
}

/// The `forbidden` checks of a `Chat/set` update that read backend state:
/// a banned user among the added members, and the `pinnedMessageIds`
/// policy. Returns the [`SetError`] value for `notUpdated`, or `None`.
async fn update_policy_error<B: ChatBackend>(
    ctx: &SetCtx<'_, B>,
    id: &Id,
    chat: &Chat,
    patch: &PatchObject,
    member_change: Option<&MemberChange>,
) -> Option<Value> {
    // draft-atwood-jmap-chat-00 §ChatBan/set: "while the ban lasts
    // the server MUST reject adding the user with an `addMembers`
    // entry, returning a `forbidden` SetError." Only users the
    // update adds count; a ban whose `expiresAt` has passed is not
    // in force.
    if let Some((members, _)) = member_change {
        let added: Vec<&Id> = members
            .iter()
            .filter(|m| chat.members.iter().flatten().all(|old| old.id != m.id))
            .map(|m| &m.id)
            .collect();
        if !added.is_empty() {
            match banned_among(ctx.backend, ctx.caller, ctx.account_id, id, &added).await {
                Ok(false) => {}
                Ok(true) => {
                    return Some(json!({
                        "type": "forbidden",
                        "description": "addMembers names a user banned from this chat",
                    }));
                }
                Err(e) => return Some(server_fail_value_from_backend(&e)),
            }
        }
    }

    // draft-atwood-jmap-chat-00 §Chat `pinnedMessageIds`: who may
    // modify the list depends on the chat kind; the backend decides.
    // Pointer paths beneath the property are gated too.
    let touches_pins = patch
        .as_map()
        .keys()
        .any(|k| k == "pinnedMessageIds" || k.starts_with("pinnedMessageIds/"));
    if touches_pins {
        let outcome = ctx
            .backend
            .may_set_pinned_messages(ctx.caller, ctx.account_id, id)
            .await;
        return refusal_value(outcome);
    }
    None
}

/// The [`SetError`] value when a `Chat/set` update's `pinnedMessageIds` would
/// add an id that does not name a Message in this Chat, or `None`.
///
/// draft-atwood-jmap-chat-00 §Chat `pinnedMessageIds`: an update
/// that would add an id not naming a Message in this Chat is
/// `invalidProperties`. RFC 8620 §5.3 forbids pointers into
/// arrays (`update_object` rejects them as invalidPatch), so only
/// the whole-property key can add ids, and its value is the
/// post-patch list. Only ids absent from the stored list count
/// as added; see `ChatAccessPolicy::validate_pinned_message_ids`.
/// ponytail: check-then-update is not atomic; a Message
/// hard-deleted between the two leaves a stale pin. A backend
/// needing strictness re-checks inside its update transaction.
async fn pinned_ids_error<B: ChatBackend>(
    ctx: &SetCtx<'_, B>,
    id: &Id,
    chat: &Chat,
    patch: &PatchObject,
) -> Option<Value> {
    let Some(Value::Array(new_pins)) = patch.as_map().get("pinnedMessageIds") else {
        return None;
    };
    let pins = match new_pins
        .iter()
        .filter_map(Value::as_str)
        .map(|s| jmap_server::parse_wire_id(s, "pinnedMessageIds"))
        .collect::<Result<Vec<Id>, _>>()
    {
        Ok(pins) => pins,
        Err(err) => return Some(serde_json::Value::from(&*err)),
    };
    let added: Vec<Id> = pins
        .into_iter()
        .filter(|pin| !chat.pinned_message_ids.contains(pin))
        .collect();
    if added.is_empty() {
        return None;
    }
    let outcome = ctx
        .backend
        .validate_pinned_message_ids(ctx.caller, ctx.account_id, id, &added)
        .await;
    refusal_value(outcome)
}

/// Write one checked `Chat/set` update and send the group's
/// `Peer/groupUpdate` events once it succeeded. Returns whether the
/// backend was written.
async fn write_update<B: ChatBackend>(
    ctx: &SetCtx<'_, B>,
    id_str: String,
    id: &Id,
    patch: PatchObject,
    group_before: Option<Vec<ChatMember>>,
    member_change: Option<MemberChange>,
    acc: &mut SetAccumulators,
) -> Result<bool, JmapError> {
    let metadata_changed = patch
        .as_map()
        .keys()
        .any(|k| GROUP_ADMIN_KEYS.contains(&k.split('/').next().unwrap_or(k)));
    let outcome = ctx
        .backend
        .update_object::<Chat>(ctx.caller, ctx.account_id, id, patch)
        .await;
    if let (Ok(_), Some(before)) = (&outcome, &group_before) {
        let (after, closes) = match &member_change {
            Some((members, closes)) => (Some(members.as_slice()), *closes),
            None => (None, false),
        };
        for event in
            group_update_events(id, ctx.account_id, before, after, closes, metadata_changed)
        {
            ctx.backend
                .on_outbound_event(ctx.caller, ctx.account_id, &event)
                .await;
        }
    }
    match outcome {
        Ok(Some(obj)) => {
            acc.updated
                .insert(id_str, jmap_server::serialize_value(&obj)?);
            Ok(true)
        }
        Ok(None) => {
            acc.updated.insert(id_str, Value::Null);
            Ok(true)
        }
        Err(e) => {
            acc.not_updated.insert(id_str, backend_set_error_value(e));
            Ok(false)
        }
    }
}

/// The `destroy` part of `Chat/set`. Returns whether the backend was
/// written.
async fn set_destroy<B: ChatBackend>(
    ctx: &SetCtx<'_, B>,
    args: &mut serde_json::Map<String, Value>,
    acc: &mut SetAccumulators,
) -> Result<bool, JmapError> {
    let mut mutated = false;
    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<_, _>>()?;
        // §Destroying a Chat: "For channel Chats, destroy via `Chat/set` is
        // not supported; the server MUST return a SetError of type
        // `forbidden`." An id that does not resolve is left for
        // destroy_object to surface `notFound`.
        let mut ids: Vec<Id> = Vec::new();
        for raw in id_strs {
            match jmap_server::parse_wire_id(raw, "id") {
                Ok(id) => ids.push(id),
                Err(err) => {
                    acc.not_destroyed
                        .insert(raw.to_owned(), serde_json::Value::from(&*err));
                }
            }
        }
        // A failed read is per-id `serverFail`, not a method error: the
        // creates and updates above are already committed, and a method
        // `serverFail` means "The method call made no changes to the
        // server's state" (RFC 8620 §3.6.2). Without the kinds no id can
        // be checked, so none is destroyed.
        let channel_ids: HashSet<Id> = if ids.is_empty() {
            HashSet::new()
        } else {
            match ctx
                .backend
                .get_objects::<Chat>(ctx.caller, ctx.account_id, Some(&ids), None)
                .await
            {
                Ok((chats, _)) => chats
                    .into_iter()
                    .filter(|c| c.kind == ChatKind::Channel)
                    .map(|c| c.id)
                    .collect(),
                Err(e) => {
                    let err = server_fail_value_from_backend(&e);
                    for id in ids.drain(..) {
                        acc.not_destroyed
                            .insert(id.as_ref().to_owned(), err.clone());
                    }
                    HashSet::new()
                }
            }
        };
        for id in ids {
            let id_str = id.as_ref();
            if channel_ids.contains(&id) {
                acc.not_destroyed.insert(
                    id_str.to_owned(),
                    json!({
                        "type": "forbidden",
                        "description": "channel Chats are removed via Space/set removeChannels",
                    }),
                );
                continue;
            }

            match ctx
                .backend
                .destroy_object::<Chat>(ctx.caller, ctx.account_id, &id)
                .await
            {
                Ok(()) => {
                    mutated = true;
                    acc.destroyed.push(Value::String(id_str.to_owned()));
                    ctx.backend
                        .on_chat_destroyed(ctx.caller, ctx.account_id, &id)
                        .await;
                }
                Err(e) => {
                    acc.not_destroyed
                        .insert(id_str.to_owned(), backend_set_error_value(e));
                }
            }
        }
    }
    Ok(mutated)
}

// ---------------------------------------------------------------------------
// Chat/typing
// ---------------------------------------------------------------------------

/// Handle a `Chat/typing` method call (draft-atwood-jmap-chat-00 §Chat).
///
/// `args` is the draft §Chat `Chat/typing` request shape (`accountId`,
/// `chatId`); the returned `Value` is the §Chat response shape
/// (`accountId` echo). No persistent state is changed.
///
/// This method is ephemeral — it signals the user is typing in a chat.
/// No state is persisted. In a full implementation, the server would
/// fan out a typing event to chat participants; this handler validates
/// and returns. An unknown `chatId` and a Chat the account does not
/// participate in both yield the same `invalidArguments` error. The
/// sender identity is always derived server-side from `accountId` —
/// clients MUST NOT supply a `senderId` field.
///
/// # Blocked-sender suppression
///
/// Per draft-atwood-jmap-chat-00 commit `d68b4e3` ("close blocked-sender
/// suppression gaps for typing/presence"): when the requesting account
/// corresponds to a [`ChatContact`] whose `blocked` is `true` on the
/// recipient's contact list, the server MUST silently suppress the
/// typing event for that recipient. The sender is NOT informed.
///
/// [`ChatContact`]: jmap_chat_types::ChatContact
///
/// This handler does not call [`ChatAccessPolicy::is_contact_blocked`](crate::ChatAccessPolicy::is_contact_blocked): that
/// check reads the recipient's contact list, and the request names only
/// the sender's `accountId`. The transport that fans the event out knows
/// each recipient's account and MUST call [`crate::should_deliver_typing`]
/// per recipient, which applies this check and the
/// `receiveTypingIndicators` and membership checks.
/// The wire response (echo `accountId`) is the same either way.
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
///
/// # Errors
///
/// Returns a method-level [`JmapError`]:
///
/// - `invalidArguments` when `accountId` is missing or not a valid Id,
///   `chatId` is missing or not a valid Id, `typing` is missing or not a
///   boolean, or `chatId` names no Chat the account participates in;
/// - `accountNotFound` when the backend does not know `accountId`;
/// - `serverFail` when the backend fails.
pub async fn handle_chat_typing<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    let (account_id, 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 chat_id: Id = match args.get("chatId").and_then(|v| v.as_str()) {
        Some(s) => Id::new_validated(s)
            .map_err(|e| JmapError::invalid_arguments(format!("chatId: {e}")))?,
        None => return Err(JmapError::invalid_arguments("chatId is required")),
    };

    let typing: bool = match args.get("typing") {
        Some(Value::Bool(b)) => *b,
        None => return Err(JmapError::invalid_arguments("typing is required")),
        Some(_) => return Err(JmapError::invalid_arguments("typing must be a boolean")),
    };

    // draft-atwood-jmap-chat-00 §Chat/typing `chatId` (jmap-chat-spec
    // 77c3474 L1164): "The server SHOULD return an `invalidArguments`
    // method error if `chatId` does not exist or the account is not a
    // participant in that Chat, and SHOULD NOT distinguish the two cases."
    // This crate performs the recommended behaviour by choice. A group chat's participants are its
    // `members`, where the owner is referenced by the accountId
    // (§Terminology).
    let (found, _not_found) = backend
        .get_objects::<Chat>(
            caller,
            &account_id,
            Some(std::slice::from_ref(&chat_id)),
            None,
        )
        .await
        .map_err(|e| server_fail_from_backend(&e))?;
    found
        .into_iter()
        .next()
        .filter(|c| {
            c.kind != ChatKind::Group || c.members.iter().flatten().any(|m| m.id == account_id)
        })
        .ok_or_else(|| {
            JmapError::invalid_arguments("chatId is not a Chat the account participates in")
        })?;

    // §Chat/typing Server Behavior: deliver a `typing` push event to the
    // other local participants and, "For federated Chats, the server SHOULD
    // invoke `Peer/typing`". The backend does both from this event.
    backend
        .on_outbound_event(
            caller,
            &account_id,
            &OutboundEvent::Typing { chat_id, typing },
        )
        .await;

    Ok(HandlerOutput::new(json!({
        "accountId": account_id.as_ref(),
    })))
}