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
//! Shared test infrastructure.
//!
//! Most of the in-memory backend used by these tests now lives in the
//! crate itself as the public reference implementation
//! [`jmap_chat_server::memory::MemoryBackend`]. This module:
//!
//! - re-exports that public reference impl (and `MemoryError`) under the
//!   historical `common::*` paths, so existing tests can use
//!   `use common::MemoryBackend;` unchanged.
//! - keeps the test-only [`FaultyBackend`] negative-path wrapper that
//!   always returns errors. This is testing scaffolding (not a reference
//!   impl) and so stays here.
//!
//! Each integration test binary includes this module with `mod common;`.
//! Dead-code and unused-import warnings are suppressed because not all
//! items are used in every test binary.
#![allow(dead_code)]
#![allow(unused_imports)]
#![allow(async_fn_in_trait)]

use jmap_server::HandlerOutput;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

// Re-exports — keep `use common::MemoryBackend;` working for tests.
pub use jmap_chat_server::memory::{MemoryBackend, MemoryError};

use jmap_chat_server::{
    AttachmentBlob, ChatAccessPolicy, ChatBackend, ChatEvents, ChatLimits, ChatMessageLifecycle,
    ChatModeration, ChatResolvers, ChatRestrictions, ChatSettings, ChatSpaces, ChatStore,
    DelegateChatMessageLifecycle, DelegateChatResolvers, EmojiSetOp, InviteJoinRefusal, OpResult,
    SlowModeError, SpacePatchOp, SpacePolicy,
};
use jmap_server::{
    BackendChangesError, BackendQueryError, BackendSetError, ChangesResult, GetObject,
    JmapAccounts, JmapBackend, JmapObject, JmapReads, QueryChangesParams, QueryChangesResult,
    QueryObject, QueryParams, QueryResult, SetError, SetErrorType, SetObject,
};
use jmap_types::{Id, PatchObject, State, UTCDate};

// ---------------------------------------------------------------------------
// FaultyBackend — always returns errors, for negative-path testing
// ---------------------------------------------------------------------------

/// A backend that always returns errors. Used to test the handler's error paths.
#[derive(Clone, Default)]
pub struct FaultyBackend;

impl JmapAccounts for FaultyBackend {
    type Error = MemoryError;
    type CallerCtx = ();

    async fn account_exists(&self, _caller: &(), _account_id: &Id) -> Result<bool, Self::Error> {
        Err(MemoryError::new("storage unavailable"))
    }
}

impl JmapReads for FaultyBackend {
    async fn get_objects<O: GetObject + Send + Sync>(
        &self,
        _caller: &(),
        _account_id: &Id,
        _ids: Option<&[Id]>,
        _properties: Option<&[String]>,
    ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
        Err(MemoryError::new("storage unavailable"))
    }

    async fn get_state<O: JmapObject + Send + Sync>(
        &self,
        _caller: &(),
        _account_id: &Id,
    ) -> Result<State, Self::Error> {
        Err(MemoryError::new("storage unavailable"))
    }

    async fn get_changes<O: JmapObject + Send + Sync>(
        &self,
        _caller: &(),
        _account_id: &Id,
        _params: jmap_server::ChangesParams<'_>,
    ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
        Err(BackendChangesError::Other(MemoryError::new(
            "storage unavailable",
        )))
    }

    async fn query_objects<O: QueryObject + Send + Sync>(
        &self,
        _caller: &(),
        _account_id: &Id,
        _params: QueryParams<'_, O>,
    ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
        Err(BackendQueryError::Other(MemoryError::new(
            "storage unavailable",
        )))
    }

    async fn query_changes<O: QueryObject + Send + Sync>(
        &self,
        _caller: &(),
        _account_id: &Id,
        _params: QueryChangesParams<'_, O>,
    ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
        Err(BackendChangesError::Other(MemoryError::new(
            "storage unavailable",
        )))
    }
}

impl ChatStore for FaultyBackend {
    async fn create_object<O, F>(
        &self,
        _caller: &(),
        _account_id: &Id,
        _create_id: &str,
        _build: F,
    ) -> Result<(Id, O), BackendSetError<Self::Error>>
    where
        O: SetObject + Send + Sync,
        F: FnOnce(&Id) -> O + Send,
    {
        Err(BackendSetError::Other(MemoryError::new(
            "storage unavailable",
        )))
    }

    async fn update_object<O: SetObject + Send + Sync>(
        &self,
        _caller: &(),
        _account_id: &Id,
        _id: &Id,
        _patch: O::Patch,
    ) -> Result<Option<O>, BackendSetError<Self::Error>> {
        Err(BackendSetError::Other(MemoryError::new(
            "storage unavailable",
        )))
    }

    async fn destroy_object<O: SetObject + Send + Sync>(
        &self,
        _caller: &(),
        _account_id: &Id,
        _id: &Id,
    ) -> Result<(), BackendSetError<Self::Error>> {
        Err(BackendSetError::Other(MemoryError::new(
            "storage unavailable",
        )))
    }

    fn supports_type<O: JmapObject>(
        &self,
        _caller: &Self::CallerCtx,
        _account_id: &jmap_types::Id,
    ) -> bool {
        false
    }
}

impl ChatSpaces for FaultyBackend {
    async fn join_space_with_invite(
        &self,
        _caller: &(),
        _account_id: &Id,
        _invite_id: &Id,
        _joined_at: &UTCDate,
    ) -> Result<Result<(), InviteJoinRefusal>, Self::Error> {
        Err(MemoryError::new("storage unavailable"))
    }

    async fn generate_invite_code(
        &self,
        _caller: &(),
        _account_id: &Id,
    ) -> Result<String, MemoryError> {
        // test-only: not a CSPRNG
        Ok(format!(
            "{:012x}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
                & 0xffff_ffff_ffff,
        ))
    }

    async fn everyone_permissions(
        &self,
        _caller: &(),
        _account_id: &Id,
        _space: &jmap_chat_types::Space,
    ) -> Result<std::collections::HashSet<jmap_chat_types::ChatPermission>, MemoryError> {
        Err(MemoryError::new("storage unavailable"))
    }

    async fn apply_space_patch(
        &self,
        _caller: &(),
        _account_id: &Id,
        _space_id: &Id,
        _ops: Vec<SpacePatchOp>,
    ) -> Result<Vec<OpResult>, BackendSetError<Self::Error>> {
        Err(BackendSetError::Other(MemoryError::new(
            "storage unavailable",
        )))
    }

    async fn apply_space_metadata_patch(
        &self,
        _caller: &(),
        _account_id: &Id,
        _space_id: &Id,
        _patch: jmap_chat_types::SpaceMetadataPatch,
    ) -> Result<Option<jmap_chat_types::Space>, BackendSetError<Self::Error>> {
        Err(BackendSetError::Other(MemoryError::new(
            "storage unavailable",
        )))
    }
}

impl SpacePolicy for FaultyBackend {}

impl ChatAccessPolicy for FaultyBackend {}

impl ChatRestrictions for FaultyBackend {}

impl ChatModeration for FaultyBackend {}

impl ChatMessageLifecycle for FaultyBackend {
    async fn read_and_burn_message(
        &self,
        _caller: &(),
        _account_id: &Id,
        _message_id: &Id,
        _patch: PatchObject,
    ) -> Result<(), BackendSetError<Self::Error>> {
        Err(BackendSetError::Other(MemoryError::new(
            "storage unavailable",
        )))
    }
}

impl ChatEvents for FaultyBackend {}

impl ChatSettings for FaultyBackend {}

impl ChatResolvers for FaultyBackend {
    async fn attachment_blob(
        &self,
        _caller: &(),
        _account_id: &Id,
        _blob_id: &Id,
    ) -> Result<Result<Option<jmap_chat_server::AttachmentBlob>, jmap_server::SetError>, MemoryError>
    {
        Ok(Ok(None))
    }
}

// ---------------------------------------------------------------------------
// TrackingBackend — MemoryBackend with policy hooks overridable per-test
// ---------------------------------------------------------------------------

/// A `MemoryBackend` wrapper that lets a test inject custom outcomes for
/// individual [`ChatBackend`] policy hooks (`slow_mode_check`, etc.) while
/// otherwise delegating to the reference impl for storage, change-log, and
/// all read/write methods.
///
/// The current implementation only knobs `slow_mode_check`. Future Layer B
/// beads (`is_contact_blocked`, `may_set_custom_emoji`, etc.) extend the
/// configuration surface with the same wrapper pattern rather than
/// inventing a fresh test backend per method.
#[derive(Clone, Default)]
pub struct TrackingBackend {
    inner: MemoryBackend<()>,
    /// When `Some`, [`ChatAccessPolicy::slow_mode_check`](jmap_chat_server::ChatAccessPolicy::slow_mode_check) returns
    /// `Err(SlowModeError::new(<this>))`. When `None`, forwards to
    /// `inner` (which is a no-op).
    slow_mode_block: Option<UTCDate>,
    /// When `true`, [`SpacePolicy::may_set_custom_emoji`](jmap_chat_server::SpacePolicy::may_set_custom_emoji) returns
    /// `Ok(Err(SetError::new(SetErrorType::Forbidden)))` for every op
    /// (Create/Update/Destroy). When `false`, forwards to `inner`
    /// (which returns `Ok(Ok(()))`).
    emoji_set_deny: bool,
    /// When `true`, [`SpacePolicy::may_set_custom_emoji`](jmap_chat_server::SpacePolicy::may_set_custom_emoji) returns a
    /// backend error whose Display contains [`INJECTABLE_BACKEND_CANARY`].
    emoji_set_fail: bool,
    /// The `(target_space_id, op)` of every
    /// [`SpacePolicy::may_set_custom_emoji`](jmap_chat_server::SpacePolicy::may_set_custom_emoji) call, in call order.
    emoji_set_calls: Arc<Mutex<Vec<EmojiSetCall>>>,
    /// When `true`, [`ChatAccessPolicy::may_broadcast_mention`](jmap_chat_server::ChatAccessPolicy::may_broadcast_mention) returns
    /// `Ok(Err(SetError::new(SetErrorType::Forbidden)))`. When `false`,
    /// forwards to `inner` (which returns `Ok(Ok(()))`).
    broadcast_mention_deny: bool,
    /// When `true`, [`ChatAccessPolicy::may_view_chat`](jmap_chat_server::ChatAccessPolicy::may_view_chat) returns `Ok(false)`.
    /// When `false`, forwards to `inner`.
    chat_view_deny: bool,
    /// Counter incremented every time
    /// [`ChatAccessPolicy::is_contact_blocked`](jmap_chat_server::ChatAccessPolicy::is_contact_blocked) is invoked. Lets a test
    /// verify whether a handler consulted the predicate, which has no
    /// effect on the handler's wire response.
    is_contact_blocked_calls: Arc<AtomicU64>,
    /// When `true`, the per-Chat restriction hooks apply the
    /// draft-atwood-jmap-chat-mimi-00 rules to every Chat whose extension
    /// properties hold `roomId`. When `false`, they forward to `inner`.
    room_restricted: bool,
    /// [`JmapReads::get_objects`] calls per object type name, so a test
    /// can count the reads a handler makes.
    get_objects_calls: Arc<Mutex<HashMap<&'static str, u64>>>,
    /// When `Some`, [`JmapReads::get_objects`] for this type name
    /// returns an error. Other types forward to `inner`.
    get_objects_fail: Option<&'static str>,
    /// The `id` of every object the [`ChatStore::create_object`](jmap_chat_server::ChatStore::create_object) builder
    /// returned, in call order.
    create_input_ids: Arc<Mutex<Vec<serde_json::Value>>>,
    /// When `Some`, [`ChatResolvers::attachment_blob`](jmap_chat_server::ChatResolvers::attachment_blob) returns
    /// `Ok(Err(<this>))`.
    attachment_blob_reject: Option<SetError>,
    /// When `true`, [`ChatResolvers::attachment_blob`](jmap_chat_server::ChatResolvers::attachment_blob) returns `Err`.
    attachment_blob_fail: bool,
    /// When `Some`, [`ChatResolvers::filenode_attachment`](jmap_chat_server::ChatResolvers::filenode_attachment) returns
    /// `Ok(<this>.map(Some))`; when `None`, it forwards to `inner`.
    filenode_attachment: Option<Result<jmap_chat_types::Attachment, SetError>>,
    /// Count of [`ChatResolvers::filenode_attachment`](jmap_chat_server::ChatResolvers::filenode_attachment) calls.
    filenode_attachment_calls: Arc<AtomicU64>,
    /// The `(chat id, user ids)` of every [`ChatModeration::kick_chat_members`](jmap_chat_server::ChatModeration::kick_chat_members)
    /// call this wrapper accepted, in call order.
    kick_calls: Arc<Mutex<Vec<KickCall>>>,
}

/// One accepted [`ChatModeration::kick_chat_members`](jmap_chat_server::ChatModeration::kick_chat_members) call: `(chat id, user ids)`.
pub type KickCall = (String, Vec<String>);

/// One [`SpacePolicy::may_set_custom_emoji`](jmap_chat_server::SpacePolicy::may_set_custom_emoji) call: `(target_space_id, op)`.
pub type EmojiSetCall = (Option<Id>, EmojiSetOp);

/// The Chat/set patch keys draft-atwood-jmap-chat-mimi-00 L251 forbids on
/// a Chat with a `roomId`.
const ROOM_FORBIDDEN_CHAT_KEYS: &[&str] = &[
    "name",
    "description",
    "avatarBlobId",
    "addMembers",
    "removeMembers",
    "updateMemberRoles",
];

/// The Message properties draft-atwood-jmap-chat-mimi-00 L426 forbids
/// changing in a Chat with a `roomId`.
const ROOM_FROZEN_MESSAGE_PROPS: &[&str] = &["body", "bodyType", "reactions"];

fn is_room_chat(chat: &jmap_chat_types::Chat) -> bool {
    chat.extra.contains_key("roomId")
}

impl TrackingBackend {
    /// Fresh `TrackingBackend` with all policy hooks at their default
    /// no-op behaviour (slow-mode allows everything, emoji-set
    /// authorization allows everything), wrapping [`account_backend`].
    pub fn new() -> Self {
        Self {
            inner: account_backend(),
            ..Self::default()
        }
    }

    /// Configure the wrapper so [`ChatAccessPolicy::slow_mode_check`](jmap_chat_server::ChatAccessPolicy::slow_mode_check) always
    /// rejects with the given `retry_after` UTCDate. The wrapped
    /// `MemoryBackend` is otherwise functional.
    pub fn with_slow_mode_blocking(retry_after: UTCDate) -> Self {
        Self {
            slow_mode_block: Some(retry_after),
            ..Self::new()
        }
    }

    /// Configure the wrapper so [`SpacePolicy::may_set_custom_emoji`](jmap_chat_server::SpacePolicy::may_set_custom_emoji)
    /// returns a `Forbidden` SetError for every op. The wrapped
    /// `MemoryBackend` is otherwise functional.
    pub fn with_emoji_set_denied() -> Self {
        Self {
            emoji_set_deny: true,
            ..Self::new()
        }
    }

    /// Configure the wrapper so [`SpacePolicy::may_set_custom_emoji`](jmap_chat_server::SpacePolicy::may_set_custom_emoji)
    /// fails with a backend error for every op. The wrapped
    /// `MemoryBackend` is otherwise functional.
    pub fn with_emoji_set_failing() -> Self {
        Self {
            emoji_set_fail: true,
            ..Self::new()
        }
    }

    /// The `(target_space_id, op)` of every
    /// [`SpacePolicy::may_set_custom_emoji`](jmap_chat_server::SpacePolicy::may_set_custom_emoji) call so far, in call order.
    pub fn emoji_set_calls(&self) -> Vec<EmojiSetCall> {
        self.emoji_set_calls.lock().unwrap().clone()
    }

    /// Configure the wrapper so [`ChatAccessPolicy::may_broadcast_mention`](jmap_chat_server::ChatAccessPolicy::may_broadcast_mention)
    /// returns a `Forbidden` SetError. The wrapped `MemoryBackend` is
    /// otherwise functional.
    pub fn with_broadcast_mention_denied() -> Self {
        Self {
            broadcast_mention_deny: true,
            ..Self::new()
        }
    }

    /// Configure the wrapper so [`ChatAccessPolicy::may_view_chat`](jmap_chat_server::ChatAccessPolicy::may_view_chat) hides
    /// every Chat. The wrapped `MemoryBackend` is otherwise functional.
    pub fn with_chat_view_denied() -> Self {
        Self {
            chat_view_deny: true,
            ..Self::new()
        }
    }

    /// Configure the wrapper so the per-Chat restriction hooks enforce
    /// the draft-atwood-jmap-chat-mimi-00 rules for Chats with a
    /// `roomId`. The wrapped `MemoryBackend` is otherwise functional.
    pub fn with_room_restrictions() -> Self {
        Self {
            room_restricted: true,
            ..Self::new()
        }
    }

    /// Configure the wrapper so [`JmapReads::get_objects`] fails for
    /// objects of `type_name`. The wrapped `MemoryBackend` is otherwise
    /// functional.
    pub fn with_get_objects_failing(type_name: &'static str) -> Self {
        Self {
            get_objects_fail: Some(type_name),
            ..Self::new()
        }
    }

    /// Configure the wrapper so [`ChatResolvers::attachment_blob`](jmap_chat_server::ChatResolvers::attachment_blob) rejects
    /// every blob with `set_error`. The wrapped `MemoryBackend` is
    /// otherwise functional.
    pub fn with_attachment_blob_rejected(set_error: SetError) -> Self {
        Self {
            attachment_blob_reject: Some(set_error),
            ..Self::new()
        }
    }

    /// Configure the wrapper so [`ChatResolvers::attachment_blob`](jmap_chat_server::ChatResolvers::attachment_blob) fails
    /// with a backend error. The wrapped `MemoryBackend` is otherwise
    /// functional.
    pub fn with_attachment_blob_failing() -> Self {
        Self {
            attachment_blob_fail: true,
            ..Self::new()
        }
    }

    /// Configure the wrapper so [`ChatResolvers::filenode_attachment`](jmap_chat_server::ChatResolvers::filenode_attachment)
    /// resolves every `filenodeId` entry to `result`. The wrapped
    /// `MemoryBackend` is otherwise functional.
    pub fn with_filenode_attachment(result: Result<jmap_chat_types::Attachment, SetError>) -> Self {
        Self {
            filenode_attachment: Some(result),
            ..Self::new()
        }
    }

    /// Count of [`ChatResolvers::filenode_attachment`](jmap_chat_server::ChatResolvers::filenode_attachment) calls so far.
    pub fn filenode_attachment_call_count(&self) -> u64 {
        self.filenode_attachment_calls.load(Ordering::SeqCst)
    }

    /// Borrow the underlying `MemoryBackend` for test seeding (e.g.
    /// `register_account`).
    pub fn inner(&self) -> &MemoryBackend<()> {
        &self.inner
    }

    /// Return the number of [`JmapReads::get_objects`] calls for
    /// objects of `type_name`.
    pub fn get_objects_call_count(&self, type_name: &str) -> u64 {
        let calls = self.get_objects_calls.lock().expect("lock poisoned");
        calls.get(type_name).copied().unwrap_or(0)
    }

    /// Return the `id` of every object the [`ChatStore::create_object`](jmap_chat_server::ChatStore::create_object)
    /// builder returned, in call order.
    pub fn create_input_ids(&self) -> Vec<serde_json::Value> {
        self.create_input_ids.lock().expect("lock poisoned").clone()
    }

    /// Return the number of times the wrapped
    /// [`ChatAccessPolicy::is_contact_blocked`](jmap_chat_server::ChatAccessPolicy::is_contact_blocked) has been invoked. Used by
    /// tests that verify the handler reaches the predicate-call site.
    pub fn is_contact_blocked_call_count(&self) -> u64 {
        self.is_contact_blocked_calls.load(Ordering::SeqCst)
    }

    /// Return every [`ChatModeration::kick_chat_members`](jmap_chat_server::ChatModeration::kick_chat_members) call this wrapper
    /// accepted, in call order.
    pub fn kick_calls(&self) -> Vec<KickCall> {
        self.kick_calls.lock().expect("lock poisoned").clone()
    }
}

impl JmapAccounts for TrackingBackend {
    type Error = MemoryError;
    type CallerCtx = ();

    async fn account_exists(&self, caller: &(), account_id: &Id) -> Result<bool, Self::Error> {
        self.inner.account_exists(caller, account_id).await
    }
}

impl JmapReads for TrackingBackend {
    async fn get_objects<O: GetObject + Send + Sync>(
        &self,
        caller: &(),
        account_id: &Id,
        ids: Option<&[Id]>,
        properties: Option<&[String]>,
    ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
        *self
            .get_objects_calls
            .lock()
            .expect("lock poisoned")
            .entry(O::TYPE_NAME)
            .or_default() += 1;
        if self.get_objects_fail == Some(O::TYPE_NAME) {
            return Err(MemoryError::new("injected get_objects failure"));
        }
        self.inner
            .get_objects::<O>(caller, account_id, ids, properties)
            .await
    }

    async fn get_state<O: JmapObject + Send + Sync>(
        &self,
        caller: &(),
        account_id: &Id,
    ) -> Result<State, Self::Error> {
        self.inner.get_state::<O>(caller, account_id).await
    }

    async fn get_changes<O: JmapObject + Send + Sync>(
        &self,
        caller: &(),
        account_id: &Id,
        params: jmap_server::ChangesParams<'_>,
    ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
        self.inner
            .get_changes::<O>(caller, account_id, params)
            .await
    }

    async fn query_objects<O: QueryObject + Send + Sync>(
        &self,
        caller: &(),
        account_id: &Id,
        params: QueryParams<'_, O>,
    ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
        self.inner
            .query_objects::<O>(caller, account_id, params)
            .await
    }

    async fn query_changes<O: QueryObject + Send + Sync>(
        &self,
        caller: &(),
        account_id: &Id,
        params: QueryChangesParams<'_, O>,
    ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
        self.inner
            .query_changes::<O>(caller, account_id, params)
            .await
    }
}

impl ChatStore for TrackingBackend {
    async fn create_object<O, F>(
        &self,
        caller: &(),
        account_id: &Id,
        create_id: &str,
        build: F,
    ) -> Result<(Id, O), BackendSetError<Self::Error>>
    where
        O: SetObject + Send + Sync,
        F: FnOnce(&Id) -> O + Send,
    {
        let ids = Arc::clone(&self.create_input_ids);
        self.inner
            .create_object(caller, account_id, create_id, move |id: &Id| {
                let obj = build(id);
                let built = serde_json::to_value(&obj).expect("JmapObject serializes");
                ids.lock().expect("lock poisoned").push(built["id"].clone());
                obj
            })
            .await
    }

    async fn update_object<O: SetObject + Send + Sync>(
        &self,
        caller: &(),
        account_id: &Id,
        id: &Id,
        patch: O::Patch,
    ) -> Result<Option<O>, BackendSetError<Self::Error>> {
        self.inner
            .update_object::<O>(caller, account_id, id, patch)
            .await
    }

    async fn destroy_object<O: SetObject + Send + Sync>(
        &self,
        caller: &(),
        account_id: &Id,
        id: &Id,
    ) -> Result<(), BackendSetError<Self::Error>> {
        self.inner.destroy_object::<O>(caller, account_id, id).await
    }

    fn supports_type<O: JmapObject>(
        &self,
        caller: &Self::CallerCtx,
        account_id: &jmap_types::Id,
    ) -> bool {
        self.inner.supports_type::<O>(caller, account_id)
    }
}

impl ChatSpaces for TrackingBackend {
    async fn join_space_with_invite(
        &self,
        caller: &(),
        account_id: &Id,
        invite_id: &Id,
        joined_at: &UTCDate,
    ) -> Result<Result<(), InviteJoinRefusal>, Self::Error> {
        self.inner
            .join_space_with_invite(caller, account_id, invite_id, joined_at)
            .await
    }

    async fn generate_invite_code(
        &self,
        _caller: &(),
        account_id: &Id,
    ) -> Result<String, MemoryError> {
        self.inner.generate_invite_code(&(), account_id).await
    }

    async fn everyone_permissions(
        &self,
        _caller: &(),
        account_id: &Id,
        space: &jmap_chat_types::Space,
    ) -> Result<std::collections::HashSet<jmap_chat_types::ChatPermission>, MemoryError> {
        self.inner
            .everyone_permissions(&(), account_id, space)
            .await
    }

    async fn apply_space_patch(
        &self,
        caller: &(),
        account_id: &Id,
        space_id: &Id,
        ops: Vec<SpacePatchOp>,
    ) -> Result<Vec<OpResult>, BackendSetError<Self::Error>> {
        self.inner
            .apply_space_patch(caller, account_id, space_id, ops)
            .await
    }

    async fn apply_space_metadata_patch(
        &self,
        caller: &(),
        account_id: &Id,
        space_id: &Id,
        patch: jmap_chat_types::SpaceMetadataPatch,
    ) -> Result<Option<jmap_chat_types::Space>, BackendSetError<Self::Error>> {
        self.inner
            .apply_space_metadata_patch(caller, account_id, space_id, patch)
            .await
    }
}

impl SpacePolicy for TrackingBackend {
    async fn may_set_custom_emoji(
        &self,
        caller: &(),
        account_id: &Id,
        target_space_id: Option<&Id>,
        op: EmojiSetOp,
    ) -> Result<Result<(), SetError>, Self::Error> {
        self.emoji_set_calls
            .lock()
            .unwrap()
            .push((target_space_id.cloned(), op));
        if self.emoji_set_fail {
            return Err(MemoryError::new(INJECTABLE_BACKEND_CANARY));
        }
        if self.emoji_set_deny {
            Ok(Err(SetError::new(SetErrorType::Forbidden)
                .with_description(
                    "TrackingBackend deny_set_custom_emoji: emoji authorization denied for test.",
                )))
        } else {
            self.inner
                .may_set_custom_emoji(caller, account_id, target_space_id, op)
                .await
        }
    }
}

impl ChatAccessPolicy for TrackingBackend {
    async fn slow_mode_check(
        &self,
        caller: &(),
        account_id: &Id,
        chat_id: &Id,
    ) -> Result<(), SlowModeError> {
        match &self.slow_mode_block {
            Some(d) => Err(SlowModeError::new(d.clone())),
            None => {
                self.inner
                    .slow_mode_check(caller, account_id, chat_id)
                    .await
            }
        }
    }

    async fn may_broadcast_mention(
        &self,
        caller: &(),
        account_id: &Id,
        space_id: &Id,
        chat_id: &Id,
    ) -> Result<Result<(), SetError>, Self::Error> {
        if self.broadcast_mention_deny {
            Ok(Err(SetError::new(SetErrorType::Forbidden)
                .with_description(
                    "TrackingBackend deny_broadcast_mention: mention_broadcast denied for test.",
                )))
        } else {
            self.inner
                .may_broadcast_mention(caller, account_id, space_id, chat_id)
                .await
        }
    }

    async fn may_view_chat(
        &self,
        caller: &(),
        account_id: &Id,
        chat_id: &Id,
    ) -> Result<bool, Self::Error> {
        if self.chat_view_deny {
            Ok(false)
        } else {
            self.inner.may_view_chat(caller, account_id, chat_id).await
        }
    }

    async fn is_contact_blocked(
        &self,
        caller: &(),
        account_id: &Id,
        contact_id: &Id,
    ) -> Result<bool, Self::Error> {
        self.is_contact_blocked_calls.fetch_add(1, Ordering::SeqCst);
        self.inner
            .is_contact_blocked(caller, account_id, contact_id)
            .await
    }
}

impl ChatRestrictions for TrackingBackend {
    async fn may_create_message(
        &self,
        caller: &(),
        account_id: &Id,
        chat: &jmap_chat_types::Chat,
    ) -> Result<Result<(), SetError>, Self::Error> {
        if self.room_restricted && is_room_chat(chat) {
            return Ok(Err(SetError::new(SetErrorType::Forbidden)
                .with_description(
                    "messages in a MIMI room are sent with Room/send",
                )));
        }
        self.inner
            .may_create_message(caller, account_id, chat)
            .await
    }

    async fn may_update_message(
        &self,
        caller: &(),
        account_id: &Id,
        chat: &jmap_chat_types::Chat,
        message: &jmap_chat_types::Message,
        patch_keys: &[&str],
    ) -> Result<Result<(), SetError>, Self::Error> {
        if self.room_restricted && is_room_chat(chat) {
            let mut changed: Vec<String> = Vec::new();
            for key in patch_keys {
                let top = key.split('/').next().unwrap_or(key);
                if ROOM_FROZEN_MESSAGE_PROPS.contains(&top) && !changed.iter().any(|c| c == top) {
                    changed.push(top.to_owned());
                }
            }
            if !changed.is_empty() {
                return Ok(Err(
                    SetError::new(SetErrorType::InvalidProperties).with_properties(changed)
                ));
            }
        }
        self.inner
            .may_update_message(caller, account_id, chat, message, patch_keys)
            .await
    }

    async fn may_update_chat(
        &self,
        caller: &(),
        account_id: &Id,
        chat: &jmap_chat_types::Chat,
        patch_keys: &[&str],
    ) -> Result<Result<(), SetError>, Self::Error> {
        if self.room_restricted
            && is_room_chat(chat)
            && patch_keys
                .iter()
                .any(|k| ROOM_FORBIDDEN_CHAT_KEYS.contains(k))
        {
            return Ok(Err(SetError::new(SetErrorType::Forbidden)
                .with_description("a MIMI room is changed with Room/update")));
        }
        self.inner
            .may_update_chat(caller, account_id, chat, patch_keys)
            .await
    }
}

impl ChatModeration for TrackingBackend {
    /// With room restrictions on, a Chat with a `roomId` stands for one
    /// bound to a MIMI room: the kick is recorded and accepted. Any other
    /// Chat forwards to `inner`, which keeps the trait default.
    async fn kick_chat_members(
        &self,
        caller: &(),
        account_id: &Id,
        chat: &jmap_chat_types::Chat,
        user_ids: &[Id],
    ) -> Result<Result<(), SetError>, Self::Error> {
        if self.room_restricted && is_room_chat(chat) {
            self.kick_calls.lock().expect("lock poisoned").push((
                chat.id.as_ref().to_owned(),
                user_ids.iter().map(|u| u.as_ref().to_owned()).collect(),
            ));
            return Ok(Ok(()));
        }
        self.inner
            .kick_chat_members(caller, account_id, chat, user_ids)
            .await
    }
}

impl DelegateChatMessageLifecycle for TrackingBackend {
    type Target = MemoryBackend<()>;
    fn chat_message_lifecycle(&self) -> &MemoryBackend<()> {
        &self.inner
    }
}

impl ChatEvents for TrackingBackend {
    /// Records the event in `inner`, so a test can read it with
    /// `inner().take_outbound_events_for_test()`. `create_message` is
    /// not overridden: the trait default runs.
    async fn on_outbound_event(
        &self,
        caller: &(),
        account_id: &Id,
        event: &jmap_chat_server::OutboundEvent,
    ) {
        self.inner
            .on_outbound_event(caller, account_id, event)
            .await
    }
}

impl ChatSettings for TrackingBackend {
    fn limits(&self, caller: &(), account_id: &Id) -> ChatLimits {
        self.inner.limits(caller, account_id)
    }

    fn retains_edit_history(&self) -> bool {
        self.inner.retains_edit_history()
    }
}

impl ChatResolvers for TrackingBackend {
    async fn attachment_blob(
        &self,
        caller: &(),
        account_id: &Id,
        blob_id: &Id,
    ) -> Result<Result<Option<AttachmentBlob>, SetError>, Self::Error> {
        if self.attachment_blob_fail {
            return Err(MemoryError::new("injected attachment_blob failure"));
        }
        if let Some(set_error) = &self.attachment_blob_reject {
            return Ok(Err(set_error.clone()));
        }
        self.inner
            .attachment_blob(caller, account_id, blob_id)
            .await
    }

    async fn filenode_attachment(
        &self,
        caller: &(),
        account_id: &Id,
        chat: &jmap_chat_types::Chat,
        attachment: &jmap_chat_types::AttachmentCreate,
    ) -> Result<Result<Option<jmap_chat_types::Attachment>, SetError>, Self::Error> {
        self.filenode_attachment_calls
            .fetch_add(1, Ordering::SeqCst);
        match &self.filenode_attachment {
            Some(result) => Ok(result.clone().map(Some)),
            None => {
                self.inner
                    .filenode_attachment(caller, account_id, chat, attachment)
                    .await
            }
        }
    }
}

// ---------------------------------------------------------------------------
// IdentityBackend — MemoryBackend wrapper exposing a resolvable caller id
// ---------------------------------------------------------------------------

/// A test backend with `CallerCtx = Id` that overrides
/// [`JmapAccounts::principal_id`] to return the caller verbatim.
///
/// The reference `MemoryBackend` uses `CallerCtx = ()` and inherits
/// the default `principal_id` impl returning `None`. Its permission
/// and role-hierarchy gates resolve against the owner's member entry
/// (the accountId) either way; `IdentityBackend` exercises callers
/// whose resolved principal differs from the accountId, and the
/// `Space/get` member visibility check, which applies only when
/// `principal_id` returns `Some`.
///
/// The wrapper forwards every `ChatBackend` / `JmapBackend` method to
/// the inner `MemoryBackend` with `&()` (the inner backend remains
/// `CallerCtx = ()`).
///
/// Per the workspace AGENTS.md "Caller identity (foundation seam)"
/// section: "Backends that honor identity-dependent semantics MUST
/// override this method." `IdentityBackend` is the chat-server's
/// first such backend (test-only); production deployments will write
/// their own. See `bd:JMAP-g7wu.2.4.3`.
#[derive(Clone, Default)]
pub struct IdentityBackend {
    inner: MemoryBackend<()>,
    invite_code_fails: std::sync::Arc<std::sync::atomic::AtomicBool>,
}

impl IdentityBackend {
    /// Fresh `IdentityBackend` wrapping an empty `MemoryBackend`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Make every later `generate_invite_code` call return `Err`, as a
    /// backend whose entropy source is unavailable would.
    pub fn fail_invite_codes(&self) {
        self.invite_code_fails
            .store(true, std::sync::atomic::Ordering::SeqCst);
    }

    /// Borrow the wrapped `MemoryBackend` for test seeding (e.g.
    /// `register_account`, `insert_object_for_test`,
    /// `set_protect_last_admin_for_test`).
    pub fn inner(&self) -> &MemoryBackend<()> {
        &self.inner
    }
}

impl JmapAccounts for IdentityBackend {
    type Error = MemoryError;
    type CallerCtx = Id;

    fn principal_id(caller: &Self::CallerCtx) -> Option<&Id> {
        Some(caller)
    }

    async fn account_exists(&self, _caller: &Id, account_id: &Id) -> Result<bool, Self::Error> {
        self.inner.account_exists(&(), account_id).await
    }
}

impl JmapReads for IdentityBackend {
    async fn get_objects<O: GetObject + Send + Sync>(
        &self,
        _caller: &Id,
        account_id: &Id,
        ids: Option<&[Id]>,
        properties: Option<&[String]>,
    ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
        self.inner
            .get_objects::<O>(&(), account_id, ids, properties)
            .await
    }

    async fn get_state<O: JmapObject + Send + Sync>(
        &self,
        _caller: &Id,
        account_id: &Id,
    ) -> Result<State, Self::Error> {
        self.inner.get_state::<O>(&(), account_id).await
    }

    async fn get_changes<O: JmapObject + Send + Sync>(
        &self,
        _caller: &Id,
        account_id: &Id,
        params: jmap_server::ChangesParams<'_>,
    ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
        self.inner.get_changes::<O>(&(), account_id, params).await
    }

    async fn query_objects<O: QueryObject + Send + Sync>(
        &self,
        _caller: &Id,
        account_id: &Id,
        params: QueryParams<'_, O>,
    ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
        self.inner.query_objects::<O>(&(), account_id, params).await
    }

    async fn query_changes<O: QueryObject + Send + Sync>(
        &self,
        _caller: &Id,
        account_id: &Id,
        params: QueryChangesParams<'_, O>,
    ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
        self.inner.query_changes::<O>(&(), account_id, params).await
    }
}

impl ChatStore for IdentityBackend {
    async fn create_object<O, F>(
        &self,
        _caller: &Id,
        account_id: &Id,
        create_id: &str,
        build: F,
    ) -> Result<(Id, O), BackendSetError<Self::Error>>
    where
        O: SetObject + Send + Sync,
        F: FnOnce(&Id) -> O + Send,
    {
        self.inner
            .create_object(&(), account_id, create_id, build)
            .await
    }

    async fn update_object<O: SetObject + Send + Sync>(
        &self,
        _caller: &Id,
        account_id: &Id,
        id: &Id,
        patch: O::Patch,
    ) -> Result<Option<O>, BackendSetError<Self::Error>> {
        self.inner
            .update_object::<O>(&(), account_id, id, patch)
            .await
    }

    async fn destroy_object<O: SetObject + Send + Sync>(
        &self,
        _caller: &Id,
        account_id: &Id,
        id: &Id,
    ) -> Result<(), BackendSetError<Self::Error>> {
        self.inner.destroy_object::<O>(&(), account_id, id).await
    }

    fn supports_type<O: JmapObject>(&self, _caller: &Id, account_id: &Id) -> bool {
        self.inner.supports_type::<O>(&(), account_id)
    }
}

impl ChatSpaces for IdentityBackend {
    async fn join_space_with_invite(
        &self,
        _caller: &Id,
        account_id: &Id,
        invite_id: &Id,
        joined_at: &UTCDate,
    ) -> Result<Result<(), InviteJoinRefusal>, Self::Error> {
        self.inner
            .join_space_with_invite(&(), account_id, invite_id, joined_at)
            .await
    }

    async fn generate_invite_code(
        &self,
        _caller: &Id,
        account_id: &Id,
    ) -> Result<String, MemoryError> {
        if self
            .invite_code_fails
            .load(std::sync::atomic::Ordering::SeqCst)
        {
            return Err(MemoryError::new("entropy source unavailable"));
        }
        self.inner.generate_invite_code(&(), account_id).await
    }

    async fn everyone_permissions(
        &self,
        _caller: &Id,
        account_id: &Id,
        space: &jmap_chat_types::Space,
    ) -> Result<std::collections::HashSet<jmap_chat_types::ChatPermission>, MemoryError> {
        self.inner
            .everyone_permissions(&(), account_id, space)
            .await
    }

    fn protect_last_admin(&self, _caller: &Id, account_id: &Id) -> bool {
        self.inner.protect_last_admin(&(), account_id)
    }

    async fn apply_space_patch(
        &self,
        _caller: &Id,
        account_id: &Id,
        space_id: &Id,
        ops: Vec<SpacePatchOp>,
    ) -> Result<Vec<OpResult>, BackendSetError<Self::Error>> {
        self.inner
            .apply_space_patch(&(), account_id, space_id, ops)
            .await
    }

    async fn apply_space_metadata_patch(
        &self,
        _caller: &Id,
        account_id: &Id,
        space_id: &Id,
        patch: jmap_chat_types::SpaceMetadataPatch,
    ) -> Result<Option<jmap_chat_types::Space>, BackendSetError<Self::Error>> {
        self.inner
            .apply_space_metadata_patch(&(), account_id, space_id, patch)
            .await
    }
}

impl SpacePolicy for IdentityBackend {
    async fn may_set_custom_emoji(
        &self,
        _caller: &Id,
        account_id: &Id,
        target_space_id: Option<&Id>,
        op: EmojiSetOp,
    ) -> Result<Result<(), SetError>, Self::Error> {
        self.inner
            .may_set_custom_emoji(&(), account_id, target_space_id, op)
            .await
    }

    async fn may_set_space_ban(
        &self,
        _caller: &Id,
        account_id: &Id,
        space_id: &Id,
    ) -> Result<Result<(), SetError>, Self::Error> {
        self.inner
            .may_set_space_ban(&(), account_id, space_id)
            .await
    }

    async fn may_set_space_invite(
        &self,
        _caller: &Id,
        account_id: &Id,
        space_id: &Id,
        created_by: Option<&Id>,
    ) -> Result<Result<(), SetError>, Self::Error> {
        self.inner
            .may_set_space_invite(&(), account_id, space_id, created_by)
            .await
    }

    async fn may_get_space_invite(
        &self,
        _caller: &Id,
        account_id: &Id,
        invite: &jmap_chat_types::SpaceInvite,
    ) -> Result<bool, Self::Error> {
        self.inner
            .may_get_space_invite(&(), account_id, invite)
            .await
    }

    async fn may_get_space_ban(
        &self,
        _caller: &Id,
        account_id: &Id,
        ban: &jmap_chat_types::SpaceBan,
    ) -> Result<bool, Self::Error> {
        self.inner.may_get_space_ban(&(), account_id, ban).await
    }
}

impl ChatAccessPolicy for IdentityBackend {
    async fn slow_mode_check(
        &self,
        _caller: &Id,
        account_id: &Id,
        chat_id: &Id,
    ) -> Result<(), SlowModeError> {
        self.inner.slow_mode_check(&(), account_id, chat_id).await
    }

    async fn may_set_pinned_messages(
        &self,
        _caller: &Id,
        account_id: &Id,
        chat_id: &Id,
    ) -> Result<Result<(), SetError>, Self::Error> {
        self.inner
            .may_set_pinned_messages(&(), account_id, chat_id)
            .await
    }

    async fn may_send_message(
        &self,
        _caller: &Id,
        account_id: &Id,
        chat_id: &Id,
    ) -> Result<Result<(), SetError>, Self::Error> {
        self.inner.may_send_message(&(), account_id, chat_id).await
    }

    async fn may_view_chat(
        &self,
        _caller: &Id,
        account_id: &Id,
        chat_id: &Id,
    ) -> Result<bool, Self::Error> {
        self.inner.may_view_chat(&(), account_id, chat_id).await
    }

    async fn is_contact_blocked(
        &self,
        _caller: &Id,
        account_id: &Id,
        contact_id: &Id,
    ) -> Result<bool, Self::Error> {
        self.inner
            .is_contact_blocked(&(), account_id, contact_id)
            .await
    }
}

impl ChatRestrictions for IdentityBackend {}

impl ChatModeration for IdentityBackend {}

impl ChatMessageLifecycle for IdentityBackend {
    async fn expire_message(
        &self,
        _caller: &Id,
        account_id: &Id,
        message_id: &Id,
    ) -> Result<(), Self::Error> {
        self.inner.expire_message(&(), account_id, message_id).await
    }

    async fn read_and_burn_message(
        &self,
        _caller: &Id,
        account_id: &Id,
        message_id: &Id,
        patch: PatchObject,
    ) -> Result<(), BackendSetError<Self::Error>> {
        self.inner
            .read_and_burn_message(&(), account_id, message_id, patch)
            .await
    }
}

impl ChatEvents for IdentityBackend {}

impl ChatSettings for IdentityBackend {
    fn limits(&self, _caller: &Id, account_id: &Id) -> ChatLimits {
        self.inner.limits(&(), account_id)
    }

    fn retains_edit_history(&self) -> bool {
        self.inner.retains_edit_history()
    }
}

impl ChatResolvers for IdentityBackend {
    async fn attachment_blob(
        &self,
        _caller: &Id,
        account_id: &Id,
        blob_id: &Id,
    ) -> Result<Result<Option<jmap_chat_server::AttachmentBlob>, jmap_server::SetError>, MemoryError>
    {
        self.inner.attachment_blob(&(), account_id, blob_id).await
    }
}

// ---------------------------------------------------------------------------
// InjectableBackend — MemoryBackend wrapper with per-(type, op) fault injection
// ---------------------------------------------------------------------------

/// Canary literal embedded in every fault-injected `BackendSetError::Other`
/// payload. Tests assert this string does NOT appear in the wire-format
/// `/set` response, which proves the per-id `serverFail` Value path redacts
/// backend-error Display text through
/// [`jmap_server::server_fail_value_from_backend`] rather than echoing it
/// onto the wire. Shaped like a leaked credential so a future contributor
/// who breaks the redaction sees the visible footgun in the test failure.
///
/// Mirrors the canonical jmap-mail-server `FAULTY_BACKEND_CANARY` literal.
pub const INJECTABLE_BACKEND_CANARY: &str = "BACKEND-CANARY-LEAK-DO-NOT-WIRE-7f3a2";

/// A wrapper around [`MemoryBackend`] that can fault-inject
/// `BackendSetError::Other` (or `Self::Error`) for specific
/// `(type_name, operation)` pairs. The setup writes go through to the
/// inner [`MemoryBackend`] normally; only operations matching a
/// previously-injected pair fail.
///
/// Call [`InjectableBackend::inject`] before the operation under test. The
/// first matching call returns an error whose Display contains
/// [`INJECTABLE_BACKEND_CANARY`]; the flag is cleared so subsequent calls
/// go to the inner backend normally (fire-once semantics).
///
/// Mirrors the canonical jmap-mail-server `FaultyBackend` injection
/// pattern. Lives alongside [`FaultyBackend`] (the always-fails
/// negative-path wrapper) rather than extending it because the two
/// existing `FaultyBackend` test sites depend on the always-fails
/// behaviour.
///
/// # Supported injection targets
///
/// - `(O::TYPE_NAME, "create")` — fails the next
///   [`ChatStore::create_object`](jmap_chat_server::ChatStore::create_object) call for type `O`.
/// - `(O::TYPE_NAME, "update")` — fails the next
///   [`ChatStore::update_object`](jmap_chat_server::ChatStore::update_object) call for type `O`.
/// - `(O::TYPE_NAME, "destroy")` — fails the next
///   [`ChatStore::destroy_object`](jmap_chat_server::ChatStore::destroy_object) call for type `O`.
/// - `(O::TYPE_NAME, "get")` — fails the next
///   [`JmapReads::get_objects`] call for type `O`.
/// - [`InjectableBackend::queue_chat_get_fault_after_create`] — arms
///   `("Chat", "get")` after the next successful
///   [`ChatStore::create_object`](jmap_chat_server::ChatStore::create_object) call for type `Chat`, so the
///   handler's pre-create snapshot read succeeds and its post-create
///   race-detection re-fetch fails.
/// - `(O::TYPE_NAME, "query")` — the next [`JmapReads::query_objects`]
///   call for type `O` returns `BackendQueryError::Method` carrying
///   `unsupportedFilter` with description
///   [`INJECTED_QUERY_METHOD_ERROR_DESCRIPTION`] (RFC 8620 §5.5).
/// - `("Message", "read_and_burn")` — fails the next
///   [`ChatMessageLifecycle::read_and_burn_message`](jmap_chat_server::ChatMessageLifecycle::read_and_burn_message) call.
/// - `("Message", "create_message")` — fails the next
///   [`ChatStore::create_message`](jmap_chat_server::ChatStore::create_message) call before anything is stored or
///   enqueued, as a backend does when it cannot enqueue the
///   `NewMessage` event.
/// - [`InjectableBackend::queue_chat_race_phantom`] — after the next
///   [`ChatStore::create_object`](jmap_chat_server::ChatStore::create_object) call for type `Chat` returns
///   successfully, insert a phantom `Direct` Chat into the inner
///   backend with a lex-smaller id and the supplied `contact_id`.
///   This makes the handler's race-detection re-fetch see a
///   duplicate, driving it into the cleanup-destroy branch. Combine
///   with `inject("Chat", "destroy")` to exercise the
///   `chat.rs:413-428` redaction site.
///
/// Other `(type, op)` pairs are not currently honored; extend this
/// wrapper if a new redaction-canary site lands.
/// Description of the `unsupportedFilter` an injected `"query"` fault
/// returns; the handler's own `unsupportedFilter` carries no description,
/// so seeing this text proves the backend's error passed through.
pub const INJECTED_QUERY_METHOD_ERROR_DESCRIPTION: &str = "backend cannot process this filter";

pub struct InjectableBackend {
    pub inner: MemoryBackend<()>,
    failures:
        std::sync::Arc<std::sync::Mutex<std::collections::HashSet<(&'static str, &'static str)>>>,
    /// Pending race-phantom seed: when set, the next `create_object::<Chat>`
    /// call (post-success) seeds a phantom Direct Chat into the inner
    /// backend at the supplied `(account_id, phantom_id, contact_id)`.
    /// Fire-once.
    chat_race_phantom: std::sync::Arc<std::sync::Mutex<Option<ChatRacePhantom>>>,
    /// When set, the next successful `create_object::<Chat>` arms a
    /// `("Chat", "get")` fault. Fire-once.
    chat_get_fault_after_create: std::sync::Arc<std::sync::atomic::AtomicBool>,
}

/// Pre-canned phantom-Chat seed: where to insert (`account_id`), what
/// id to seed it with (`phantom_id` — must be lex-smaller than the
/// next-assigned new chat id for the race-detection canonical pick
/// to select it), and the `contact_id` of the Direct chat being
/// duplicated.
struct ChatRacePhantom {
    account_id: String,
    phantom_id: String,
    contact_id: String,
}

impl InjectableBackend {
    /// Fresh `InjectableBackend` wrapping [`account_backend`] with no
    /// faults queued.
    pub fn new() -> Self {
        Self {
            inner: account_backend(),
            failures: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashSet::new())),
            chat_race_phantom: std::sync::Arc::new(std::sync::Mutex::new(None)),
            chat_get_fault_after_create: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(
                false,
            )),
        }
    }

    /// Schedule a fault for the next call to `op` on `type_name`.
    ///
    /// Calling `inject` twice for the same `(type_name, op)` pair is a
    /// no-op — only one fault is queued; the second call is silently
    /// ignored.
    pub fn inject(&self, type_name: &'static str, op: &'static str) {
        self.failures.lock().unwrap().insert((type_name, op));
    }

    /// Schedule a phantom-Direct-Chat seed to fire after the next
    /// successful `create_object::<Chat>` call. The phantom is inserted
    /// into the inner backend (via `MemoryBackend::insert_object_for_test`)
    /// AFTER the inner create returns, so the handler's pre-create
    /// `existing_chats` snapshot does not see it, but the handler's
    /// post-create race-detection re-fetch does.
    ///
    /// `phantom_id` should be lex-smaller than the next id the inner
    /// `MemoryBackend` will assign to the about-to-be-created Chat —
    /// otherwise the race-detection code picks the new id as canonical
    /// and the cleanup-destroy branch never runs. `MemoryBackend` mints
    /// ULIDs (26 Crockford base32 chars), so `"0"`, a proper prefix of
    /// every current ULID, is lex-smaller than every id it can assign.
    ///
    /// Fire-once.
    pub fn queue_chat_race_phantom(&self, account_id: &str, phantom_id: &str, contact_id: &str) {
        *self.chat_race_phantom.lock().unwrap() = Some(ChatRacePhantom {
            account_id: account_id.to_owned(),
            phantom_id: phantom_id.to_owned(),
            contact_id: contact_id.to_owned(),
        });
    }

    /// Fail the first `get_objects::<Chat>` call that follows the next
    /// successful `create_object::<Chat>` call. Fire-once.
    pub fn queue_chat_get_fault_after_create(&self) {
        self.chat_get_fault_after_create
            .store(true, std::sync::atomic::Ordering::SeqCst);
    }

    /// Remove and return a previously-injected fault (fire-once).
    /// Returns `true` if the fault was present (and is now consumed).
    fn take_fault(&self, type_name: &'static str, op: &'static str) -> bool {
        self.failures.lock().unwrap().remove(&(type_name, op))
    }

    /// Remove and return a previously-queued chat race phantom (fire-once).
    fn take_chat_race_phantom(&self) -> Option<ChatRacePhantom> {
        self.chat_race_phantom.lock().unwrap().take()
    }
}

impl Default for InjectableBackend {
    fn default() -> Self {
        Self::new()
    }
}

impl JmapAccounts for InjectableBackend {
    type Error = MemoryError;
    type CallerCtx = ();

    async fn account_exists(&self, caller: &(), account_id: &Id) -> Result<bool, Self::Error> {
        self.inner.account_exists(caller, account_id).await
    }
}

impl JmapReads for InjectableBackend {
    async fn get_objects<O: GetObject + Send + Sync>(
        &self,
        caller: &(),
        account_id: &Id,
        ids: Option<&[Id]>,
        properties: Option<&[String]>,
    ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
        if self.take_fault(O::TYPE_NAME, "get") {
            return Err(MemoryError::new(format!(
                "injected get error {INJECTABLE_BACKEND_CANARY}"
            )));
        }
        self.inner
            .get_objects::<O>(caller, account_id, ids, properties)
            .await
    }

    async fn get_state<O: JmapObject + Send + Sync>(
        &self,
        caller: &(),
        account_id: &Id,
    ) -> Result<State, Self::Error> {
        self.inner.get_state::<O>(caller, account_id).await
    }

    async fn get_changes<O: JmapObject + Send + Sync>(
        &self,
        caller: &(),
        account_id: &Id,
        params: jmap_server::ChangesParams<'_>,
    ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
        self.inner
            .get_changes::<O>(caller, account_id, params)
            .await
    }

    async fn query_objects<O: QueryObject + Send + Sync>(
        &self,
        caller: &(),
        account_id: &Id,
        params: QueryParams<'_, O>,
    ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
        if self.take_fault(O::TYPE_NAME, "query") {
            let mut err = jmap_types::JmapError::unsupported_filter();
            err.description = Some(INJECTED_QUERY_METHOD_ERROR_DESCRIPTION.into());
            return Err(BackendQueryError::Method(err));
        }
        self.inner
            .query_objects::<O>(caller, account_id, params)
            .await
    }

    async fn query_changes<O: QueryObject + Send + Sync>(
        &self,
        caller: &(),
        account_id: &Id,
        params: QueryChangesParams<'_, O>,
    ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
        self.inner
            .query_changes::<O>(caller, account_id, params)
            .await
    }
}

impl ChatStore for InjectableBackend {
    async fn create_object<O, F>(
        &self,
        caller: &(),
        account_id: &Id,
        create_id: &str,
        build: F,
    ) -> Result<(Id, O), BackendSetError<Self::Error>>
    where
        O: SetObject + Send + Sync,
        F: FnOnce(&Id) -> O + Send,
    {
        if self.take_fault(O::TYPE_NAME, "create") {
            return Err(BackendSetError::Other(MemoryError::new(format!(
                "injected create error {INJECTABLE_BACKEND_CANARY}"
            ))));
        }
        let result = self
            .inner
            .create_object(caller, account_id, create_id, build)
            .await;
        // Race-phantom seeding only applies to Chat creates and only
        // after a successful inner create. The phantom is inserted
        // via `insert_object_for_test` which bypasses the normal
        // dedupe / change-log machinery — exactly the harness shape
        // needed to simulate "another transaction won the race".
        if O::TYPE_NAME == "Chat" && result.is_ok() {
            if self
                .chat_get_fault_after_create
                .swap(false, std::sync::atomic::Ordering::SeqCst)
            {
                self.inject("Chat", "get");
            }
            if let Some(phantom) = self.take_chat_race_phantom() {
                let phantom_val = serde_json::json!({
                    "id": &phantom.phantom_id,
                    "kind": "direct",
                    "createdAt": "2024-01-01T00:00:00Z",
                    "unreadCount": 0,
                    "pinnedMessageIds": [],
                    "muted": false,
                    "receiveTypingIndicators": true,
                    "contactId": &phantom.contact_id,
                });
                self.inner.insert_object_for_test(
                    "Chat",
                    &phantom.account_id,
                    &phantom.phantom_id,
                    phantom_val,
                );
            }
        }
        result
    }

    async fn create_message<F>(
        &self,
        caller: &(),
        account_id: &Id,
        create_id: &str,
        build: F,
    ) -> Result<(Id, jmap_chat_types::Message), BackendSetError<Self::Error>>
    where
        F: FnOnce(&Id) -> jmap_chat_types::Message + Send,
    {
        if self.take_fault("Message", "create_message") {
            return Err(BackendSetError::Other(MemoryError::new(format!(
                "injected create_message error {INJECTABLE_BACKEND_CANARY}"
            ))));
        }
        // The trait default's two steps, through this wrapper's
        // `create_object`, so a `("Message", "create")` fault still fires.
        let (id, message) = self
            .create_object::<jmap_chat_types::Message, _>(caller, account_id, create_id, build)
            .await?;
        let event = jmap_chat_server::OutboundEvent::NewMessage {
            chat_id: message.chat_id.clone(),
            message_id: message.id.clone(),
            sender_msg_id: message.sender_msg_id.clone(),
        };
        self.on_outbound_event(caller, account_id, &event).await;
        Ok((id, message))
    }

    async fn update_object<O: SetObject + Send + Sync>(
        &self,
        caller: &(),
        account_id: &Id,
        id: &Id,
        patch: O::Patch,
    ) -> Result<Option<O>, BackendSetError<Self::Error>> {
        if self.take_fault(O::TYPE_NAME, "update") {
            return Err(BackendSetError::Other(MemoryError::new(format!(
                "injected update error {INJECTABLE_BACKEND_CANARY}"
            ))));
        }
        self.inner
            .update_object::<O>(caller, account_id, id, patch)
            .await
    }

    async fn destroy_object<O: SetObject + Send + Sync>(
        &self,
        caller: &(),
        account_id: &Id,
        id: &Id,
    ) -> Result<(), BackendSetError<Self::Error>> {
        if self.take_fault(O::TYPE_NAME, "destroy") {
            return Err(BackendSetError::Other(MemoryError::new(format!(
                "injected destroy error {INJECTABLE_BACKEND_CANARY}"
            ))));
        }
        self.inner.destroy_object::<O>(caller, account_id, id).await
    }

    fn supports_type<O: JmapObject>(
        &self,
        caller: &Self::CallerCtx,
        account_id: &jmap_types::Id,
    ) -> bool {
        self.inner.supports_type::<O>(caller, account_id)
    }
}

impl ChatSpaces for InjectableBackend {
    async fn join_space_with_invite(
        &self,
        caller: &(),
        account_id: &Id,
        invite_id: &Id,
        joined_at: &UTCDate,
    ) -> Result<Result<(), InviteJoinRefusal>, Self::Error> {
        self.inner
            .join_space_with_invite(caller, account_id, invite_id, joined_at)
            .await
    }

    async fn generate_invite_code(
        &self,
        _caller: &(),
        account_id: &Id,
    ) -> Result<String, MemoryError> {
        self.inner.generate_invite_code(&(), account_id).await
    }

    async fn everyone_permissions(
        &self,
        _caller: &(),
        account_id: &Id,
        space: &jmap_chat_types::Space,
    ) -> Result<std::collections::HashSet<jmap_chat_types::ChatPermission>, MemoryError> {
        self.inner
            .everyone_permissions(&(), account_id, space)
            .await
    }

    async fn apply_space_patch(
        &self,
        caller: &(),
        account_id: &Id,
        space_id: &Id,
        ops: Vec<SpacePatchOp>,
    ) -> Result<Vec<OpResult>, BackendSetError<Self::Error>> {
        self.inner
            .apply_space_patch(caller, account_id, space_id, ops)
            .await
    }

    async fn apply_space_metadata_patch(
        &self,
        caller: &(),
        account_id: &Id,
        space_id: &Id,
        patch: jmap_chat_types::SpaceMetadataPatch,
    ) -> Result<Option<jmap_chat_types::Space>, BackendSetError<Self::Error>> {
        self.inner
            .apply_space_metadata_patch(caller, account_id, space_id, patch)
            .await
    }
}

impl SpacePolicy for InjectableBackend {}

impl ChatAccessPolicy for InjectableBackend {}

impl ChatRestrictions for InjectableBackend {}

impl ChatModeration for InjectableBackend {}

impl ChatMessageLifecycle for InjectableBackend {
    async fn expire_message(
        &self,
        caller: &(),
        account_id: &Id,
        message_id: &Id,
    ) -> Result<(), Self::Error> {
        self.inner
            .expire_message(caller, account_id, message_id)
            .await
    }

    async fn read_and_burn_message(
        &self,
        caller: &(),
        account_id: &Id,
        message_id: &Id,
        patch: PatchObject,
    ) -> Result<(), BackendSetError<Self::Error>> {
        if self.take_fault("Message", "read_and_burn") {
            return Err(BackendSetError::Other(MemoryError::new(format!(
                "injected read_and_burn error {INJECTABLE_BACKEND_CANARY}"
            ))));
        }
        self.inner
            .read_and_burn_message(caller, account_id, message_id, patch)
            .await
    }
}

impl ChatEvents for InjectableBackend {
    async fn on_outbound_event(
        &self,
        caller: &(),
        account_id: &Id,
        event: &jmap_chat_server::OutboundEvent,
    ) {
        self.inner
            .on_outbound_event(caller, account_id, event)
            .await
    }
}

impl ChatSettings for InjectableBackend {
    fn limits(&self, caller: &(), account_id: &Id) -> ChatLimits {
        self.inner.limits(caller, account_id)
    }
}

impl DelegateChatResolvers for InjectableBackend {
    type Target = MemoryBackend<()>;
    fn chat_resolvers(&self) -> &MemoryBackend<()> {
        &self.inner
    }
}

// ---------------------------------------------------------------------------
// Shared Space seeding helpers (bd:JMAP-x2gd.80)
//
// Used by the apply_space_patch integration tests
// (role_member_apply.rs, channel_category_apply.rs,
// space_metadata_apply.rs). The projection-test fixture in
// space_get_projection.rs has a structurally different shape (full
// categories/channels) and stays local to that file.
// ---------------------------------------------------------------------------

/// Default account id used by the apply_space_patch test suites and
/// by the bulk of [`integration.rs`](file://./integration.rs).
pub const ACCOUNT_ID: &str = "a1";

/// Secondary account id used by integration.rs cross-account
/// isolation tests. Sibling apply-test files do not use this.
pub const ACCOUNT_ID_B: &str = "a2";

/// A [`MemoryBackend`] with [`ACCOUNT_ID`] registered, so `/set` calls
/// on it pass the RFC 8620 §3.6.2 `accountNotFound` gate (bd:JMAP-fo38).
pub fn account_backend() -> MemoryBackend<()> {
    let backend = MemoryBackend::<()>::default();
    backend.register_account(&Id::from(ACCOUNT_ID));
    backend
}

/// Default Space id used by the apply_space_patch test suites.
pub const SPACE_ID: &str = "s1";

/// Seed a [`SPACE_ID`] in [`ACCOUNT_ID`] of the given backend with
/// the supplied `roles` and `members`. The Space is seeded with
/// `description: "original"` so the metadata-mutation tests can
/// assert the description was (or was not) mutated; the apply-tests
/// for Role/Member/Channel/Category do not inspect the description
/// and are unaffected.
///
/// Bypasses `handle_space_set` create flow (which in the reference
/// impl does NOT auto-add the creator as a member) by going through
/// [`MemoryBackend::insert_object_for_test`].
pub fn seed_space(
    backend: &IdentityBackend,
    roles: serde_json::Value,
    members: serde_json::Value,
) -> Id {
    let space_val = serde_json::json!({
        "id": SPACE_ID,
        "name": "Test Space",
        "description": "original",
        "createdAt": "2026-01-01T00:00:00Z",
        "memberCount": members.as_array().map(Vec::len).unwrap_or(0),
        "categories": [],
        "uncategorizedChannelIds": [],
        "isPublic": false,
        "isPubliclyPreviewable": false,
        "roles": roles,
        "members": members,
    });
    backend.inner().register_account(&Id::from(ACCOUNT_ID));
    backend
        .inner()
        .insert_object_for_test("Space", ACCOUNT_ID, SPACE_ID, space_val);
    Id::from(SPACE_ID)
}

/// Convenience: seed a Space where `admin_id` holds full admin
/// permissions at position 100. Returns the seeded Space id.
pub fn seed_with_admin(backend: &IdentityBackend, admin_id: &str) -> Id {
    seed_space(
        backend,
        serde_json::json!([{
            "id": "r-admin",
            "name": "Admin",
            "permissions": [
                "manage_space",
                "manage_roles",
                "manage_members",
                "manage_channels"
            ],
            "position": 100
        }]),
        serde_json::json!([{
            "id": admin_id,
            "roleIds": ["r-admin"],
            "joinedAt": "2026-01-01T00:00:00Z"
        }]),
    )
}

/// Seed a Space where `caller_id` is a non-admin member holding only
/// the implicit `@everyone` floor (no explicit roles). One admin
/// (id `"admin-user"`) is also seeded so the Space is not empty of
/// admins (relevant when last-admin-protection is active).
pub fn seed_with_non_admin_caller(backend: &IdentityBackend, caller_id: &str) {
    seed_space(
        backend,
        serde_json::json!([{
            "id": "r-admin",
            "name": "Admin",
            "permissions": [
                "manage_space",
                "manage_roles",
                "manage_members",
                "manage_channels"
            ],
            "position": 100
        }]),
        serde_json::json!([
            { "id": "admin-user", "roleIds": ["r-admin"], "joinedAt": "2026-01-01T00:00:00Z" },
            { "id": caller_id,    "roleIds": [],          "joinedAt": "2026-01-02T00:00:00Z" }
        ]),
    );
}

// ---------------------------------------------------------------------------
// Builder helpers: create-as-prerequisite for tests-of-something-else.
//
// These helpers exist to collapse the recurring 14-line boilerplate of
// "call handle_*_set in create-mode, extract the server-assigned id"
// at sites where the create is a fixture step, not the subject of the
// test. Tests that exercise the create path itself MUST call the
// underlying `handle_*_set` directly so the JSON shape under test
// remains visible at the call site (bd:JMAP-x2gd.82).
// ---------------------------------------------------------------------------

/// Create a Space with the given name in [`ACCOUNT_ID`] and return its
/// server-assigned id. Goes through the `handle_space_set` create flow.
///
/// The placeholder client id is `"s0"`. Only `name` is set on the
/// create object. For non-default props (e.g. `isPublic: true`), see
/// [`make_space_with_props`].
pub async fn make_space(backend: &MemoryBackend<()>, name: &str) -> String {
    let HandlerOutput { primary: resp, .. } = jmap_chat_server::handle_space_set(
        backend,
        &(),
        &std::collections::BTreeMap::new(),
        serde_json::json!({
            "accountId": ACCOUNT_ID,
            "create": { "s0": { "name": name } }
        }),
        &[],
    )
    .await
    .expect("make_space: handle_space_set");
    resp["created"]["s0"]["id"]
        .as_str()
        .expect("make_space: server-assigned id")
        .to_owned()
}

/// Create a Space with custom props in [`ACCOUNT_ID`] and return its
/// server-assigned id. `props` is the body of the create object — for
/// example `serde_json::json!({"name": "X", "isPublic": true})`.
///
/// Use this when [`make_space`]'s name-only shape is insufficient.
pub async fn make_space_with_props(
    backend: &MemoryBackend<()>,
    props: serde_json::Value,
) -> String {
    let HandlerOutput { primary: resp, .. } = jmap_chat_server::handle_space_set(
        backend,
        &(),
        &std::collections::BTreeMap::new(),
        serde_json::json!({
            "accountId": ACCOUNT_ID,
            "create": { "s0": props }
        }),
        &[],
    )
    .await
    .expect("make_space_with_props: handle_space_set");
    resp["created"]["s0"]["id"]
        .as_str()
        .expect("make_space_with_props: server-assigned id")
        .to_owned()
}

/// Create a Chat with `kind: "group"` and the given name in
/// [`ACCOUNT_ID`] and return its server-assigned id. Goes through the
/// `handle_chat_set` create flow.
///
/// The placeholder client id is `"c0"`. For Chats with other kinds
/// (`"direct"` / `"channel"`) or extra props (`contactId`, `spaceId`),
/// call `handle_chat_set` directly so the JSON shape under test
/// remains visible at the call site.
pub async fn make_chat_group(backend: &MemoryBackend<()>, name: &str) -> String {
    let HandlerOutput { primary: resp, .. } = jmap_chat_server::handle_chat_set(
        backend,
        &(),
        &std::collections::BTreeMap::new(),
        serde_json::json!({
            "accountId": ACCOUNT_ID,
            "create": { "c0": { "kind": "group", "name": name } }
        }),
        &[],
    )
    .await
    .expect("make_chat_group: handle_chat_set");
    resp["created"]["c0"]["id"]
        .as_str()
        .expect("make_chat_group: server-assigned id")
        .to_owned()
}

/// Store a group Chat with the given `id` in [`ACCOUNT_ID`], with the
/// account as its admin member, so a `Message/set` create naming that
/// `chatId` passes the draft-atwood-jmap-chat-00 §Input Validation
/// `chatId` check. Overwrites any Chat already stored under `id`.
pub fn seed_group_chat(backend: &MemoryBackend<()>, id: &str) {
    backend.insert_object_for_test(
        "Chat",
        ACCOUNT_ID,
        id,
        serde_json::json!({
            "id": id,
            "kind": "group",
            "name": "G",
            "createdAt": "2026-01-01T00:00:00Z",
            "unreadCount": 0,
            "pinnedMessageIds": [],
            "members": [{ "id": ACCOUNT_ID, "role": "admin", "joinedAt": "2026-01-01T00:00:00Z" }],
        }),
    );
}

/// Re-store Message `id` with `senderId` set to `"bob"`, so it is a copy
/// received from another participant. draft-atwood-jmap-chat-00
/// §Message `burnOnRead`: "Applies only to the receiving mailbox; the
/// sender's own copy is not affected."
pub async fn make_received(backend: &MemoryBackend<()>, id: &str) {
    let HandlerOutput { primary: get, .. } = jmap_chat_server::message::handle_message_get(
        backend,
        &(),
        serde_json::json!({ "accountId": ACCOUNT_ID, "ids": [id] }),
        &[],
    )
    .await
    .expect("Message/get");
    let mut msg = get["list"][0].clone();
    assert!(msg.is_object(), "message {id} not found: {get}");
    msg["senderId"] = serde_json::json!("bob");
    backend.insert_object_for_test("Message", ACCOUNT_ID, id, msg);
}