vector-core 0.13.1

Core library for Vector: the single source of truth for all Vector clients, SDKs and interfaces.
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
//! Account preferences that follow you between your own devices: the block
//! list, the mute list, nicknames, and the general settings document.
//!
//! Each is a private, parameterized-replaceable kind 30078 with its own d tag,
//! NIP-44 self-encrypted, riding the SAME self-sync subscription as the
//! Community, Invite and Pinned lists — so each inherits boot sync, reconnect
//! re-sync and live cross-device edits with no new plumbing.
//!
//! **Vector's own lists, deliberately not NIP-51.** Social clients disagree on
//! what a mute is — several treat it as a soft block — so round-tripping
//! through the shared kind-10000 would blur the mute/block separation Vector
//! draws on purpose. Isolation costs interop and buys exactness.
//!
//! **Newest wins, whole list.** These are one person's settings edited from one
//! device at a time, so the replaceable event's own last-write-wins is the
//! merge. A device that was offline can therefore republish over a change it
//! never saw; the pre-publish fetch below shrinks that window, and these are
//! deliberate, infrequent actions rather than latency-sensitive ones.

use nostr_sdk::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

use crate::stored_event::event_kind;

pub const BLOCKS_D_TAG: &str = "vector/blocks";
pub const MUTES_D_TAG: &str = "vector/mutes";
pub const NICKNAMES_D_TAG: &str = "vector/nicknames";
pub const NOTIFY_D_TAG: &str = "vector/notify";
pub const RAIL_D_TAG: &str = "vector/rail";
pub const BANNERS_D_TAG: &str = "vector/banners";
pub const SETTINGS_D_TAG: &str = "vector/settings";
pub const ARCHIVE_D_TAG: &str = "vector/archive";
pub const START_D_TAG: &str = "vector/start";

const BLOCKS_LOCAL_KEY: &str = "synced_blocks_local";
const MUTES_LOCAL_KEY: &str = "synced_mutes_local";
const NICKNAMES_LOCAL_KEY: &str = "synced_nicknames_local";
const NOTIFY_LOCAL_KEY: &str = "synced_notify_local";
const RAIL_LOCAL_KEY: &str = "synced_rail_local";
const BANNERS_LOCAL_KEY: &str = "synced_banners_local";
const SETTINGS_LOCAL_KEY: &str = "synced_settings_local";
const ARCHIVE_LOCAL_KEY: &str = "synced_archive_local";
const START_LOCAL_KEY: &str = "synced_start_local";
/// The newest `created_at` of an archive copy this device holds, adopted or published.
const ARCHIVE_SEEN_KEY: &str = "synced_archive_seen";
/// Persisted, so a change survives a quit until the relays have it.
const SETTINGS_INTENT_KEY: &str = "synced_settings_intent";
const SETTINGS_SEEN_KEY: &str = "synced_settings_seen";

/// Set when a list has local edits the relays have not seen, cleared once they
/// have. Persisted, so a quit during the rail's publish debounce is recoverable
/// at the next boot instead of being silently lost.
const RAIL_DIRTY_KEY: &str = "synced_rail_dirty";
const START_DIRTY_KEY: &str = "synced_start_dirty";
/// The newest `created_at` of a layout copy this device holds, adopted or published.
const RAIL_SEEN_KEY: &str = "synced_rail_seen";
const START_SEEN_KEY: &str = "synced_start_seen";

/// One NIP-44 event holds the whole list, and blocks and nicknames scale with contacts
/// rather than being capped like pins: the write path measures the list as it will be
/// encrypted and refuses an entry that would carry it past what a relay stores.
fn fits(json: &str) -> bool {
    crate::event_size::layer_fits(json.len())
}

const LIST_FULL: &str = "this list is full: it would no longer fit one event";

const FETCH_TIMEOUT_SECS: u64 = 10;

/// A set of ids (npubs for blocks, chat ids for mutes).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct IdList {
    #[serde(default = "one")]
    pub v: u32,
    #[serde(default)]
    pub ids: Vec<String>,
}

/// npub → nickname. A map rather than a list so a rename replaces rather than
/// duplicates, and so the wire form stays stable under reordering.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct NicknameMap {
    #[serde(default = "one")]
    pub v: u32,
    #[serde(default)]
    pub names: BTreeMap<String, String>,
}

/// An entry is about 80 bytes. Padded, encrypted and base64'd, 500 of them keep the event under the
/// 64KB that strfry relays accept by default.
const ARCHIVE_MAX_ENTRIES: usize = 500;

/// chat id → the newest message time the archiving device had seen (unix ms). A chat counts
/// as archived only while nothing newer has been said in it, so a reply brings it back on
/// every device whether or not this list has caught up.
///
/// Entries stay raw JSON, and unknown keys ride along, so an entry in a shape a newer build
/// writes survives this one's republish instead of collapsing the whole map.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ArchiveMap {
    #[serde(default = "one")]
    pub v: u32,
    #[serde(default)]
    pub chats: BTreeMap<String, serde_json::Value>,
    #[serde(flatten)]
    pub other: serde_json::Map<String, serde_json::Value>,
}

impl ArchiveMap {
    pub fn from_json(s: &str) -> Self {
        serde_json::from_str(s).unwrap_or_default()
    }
    pub fn to_json(&self) -> String {
        serde_json::to_string(self).unwrap_or_else(|_| "{\"v\":1,\"chats\":{}}".to_string())
    }
    pub fn at(&self, chat_id: &str) -> Option<u64> {
        self.chats.get(chat_id).and_then(serde_json::Value::as_u64)
    }
    /// The entries this build understands, for the page.
    pub fn times(&self) -> BTreeMap<String, u64> {
        self.chats.iter().filter_map(|(id, v)| v.as_u64().map(|at| (id.clone(), at))).collect()
    }
    pub fn set(&mut self, chat_id: &str, at: u64) -> Result<(), String> {
        if chat_id.trim().is_empty() {
            return Err("empty chat id".to_string());
        }
        if !self.chats.contains_key(chat_id) && self.chats.len() >= ARCHIVE_MAX_ENTRIES {
            return Err(format!("the archive is full ({ARCHIVE_MAX_ENTRIES} chats)"));
        }
        self.chats.insert(chat_id.to_string(), at.into());
        Ok(())
    }
    /// Drop `chat_id` if it was archived before `active_at`; a later archive stands.
    pub fn revoke(&mut self, chat_id: &str, active_at: u64) -> bool {
        match self.at(chat_id) {
            Some(at) if at < active_at => self.chats.remove(chat_id).is_some(),
            _ => false,
        }
    }
}

/// One scope's notification settings on the wire. Level is spelled out rather
/// than numbered so a future rung does not silently become an old one, and an
/// absent field means inherit, exactly as it does on disk.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct NotifyEntry {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub level: Option<String>,
    #[serde(default, skip_serializing_if = "is_zero")]
    pub mute_until: i64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub suppress_everyone: Option<bool>,
}

fn is_zero(v: &i64) -> bool {
    *v == 0
}

/// scope id → settings, for communities, channels and DMs alike.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct NotifyMap {
    #[serde(default = "one")]
    pub v: u32,
    #[serde(default)]
    pub scopes: BTreeMap<String, NotifyEntry>,
}

impl NotifyMap {
    pub fn from_json(s: &str) -> Self {
        serde_json::from_str(s).unwrap_or_default()
    }
    pub fn to_json(&self) -> String {
        serde_json::to_string(self).unwrap_or_else(|_| "{\"v\":1,\"scopes\":{}}".to_string())
    }
    /// Refuses to grow past the ceiling rather than publishing a list no
    /// reader can open, the same rule the id lists follow.
    pub fn set(&mut self, scope_id: &str, entry: NotifyEntry) -> Result<(), String> {
        if scope_id.trim().is_empty() {
            return Err("empty scope id".to_string());
        }
        if entry == NotifyEntry::default() {
            self.scopes.remove(scope_id);
            return Ok(());
        }
        let prev = self.scopes.insert(scope_id.to_string(), entry);
        if !fits(&self.to_json()) {
            match prev {
                Some(p) => self.scopes.insert(scope_id.to_string(), p),
                None => self.scopes.remove(scope_id),
            };
            return Err(LIST_FULL.to_string());
        }
        Ok(())
    }
}

/// Account-wide switches that follow the user between devices.
///
/// Keys this build does not know are carried through untouched: the document is
/// newest-wins as a whole, so an older device that dropped them on republish
/// would erase settings a newer one added.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct SyncedSettings {
    #[serde(default = "one")]
    pub v: u32,
    /// Reveals identifiers and other developer-facing detail across the app.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub advanced: bool,
    #[serde(default, skip_serializing_if = "StreamerSettings::is_default")]
    pub streamer: StreamerSettings,
    /// Embedded video players (click to play) are switched off. Stored as the opt-out so
    /// every default, an empty or unreadable document included, keeps them on.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub players_off: bool,
    #[serde(flatten)]
    pub other: serde_json::Map<String, serde_json::Value>,
}

impl SyncedSettings {
    pub fn from_json(s: &str) -> Self {
        serde_json::from_str(s).unwrap_or_default()
    }
    pub fn to_json(&self) -> String {
        serde_json::to_string(self).unwrap_or_else(|_| "{\"v\":1}".to_string())
    }
    /// What `get_synced_settings` and `synced_settings_updated` hand the page.
    pub fn view(&self) -> serde_json::Value {
        serde_json::json!({
            "advanced": self.advanced,
            "players": !self.players_off,
            "streamer": {
                "on": self.streamer.on,
                "seed": self.streamer.seed,
                "notif": self.streamer.notif,
                "hide_wallpapers": self.streamer.hide_wallpapers,
            },
        })
    }
}

/// The streaming overlay's levels, in the spelling the wire and the page share.
pub const STREAMER_NOTIF_LEVELS: [&str; 4] = ["none", "hide_content", "hide_sender", "hide_all"];

/// Streamer Mode: masks everyone who has not opted in, on every device of the account.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StreamerSettings {
    #[serde(default)]
    pub on: bool,
    /// 16 random bytes as lowercase hex, re-minted at each go-live so per-stream colours reshuffle.
    #[serde(default)]
    pub seed: String,
    /// What notifications additionally hide while live, one of [`STREAMER_NOTIF_LEVELS`].
    #[serde(default = "notif_none")]
    pub notif: String,
    /// Chats show a plain background while live: a DM's wallpaper can say who it is with.
    #[serde(default = "yes")]
    pub hide_wallpapers: bool,
    #[serde(flatten)]
    pub other: serde_json::Map<String, serde_json::Value>,
}

fn notif_none() -> String {
    "none".to_string()
}

fn yes() -> bool {
    true
}

impl Default for StreamerSettings {
    fn default() -> Self {
        Self { on: false, seed: String::new(), notif: notif_none(), hide_wallpapers: true, other: serde_json::Map::new() }
    }
}

impl StreamerSettings {
    pub fn is_default(&self) -> bool {
        *self == Self::default()
    }

    pub fn set_on(&mut self, on: bool) {
        if on && !self.on {
            self.seed = fresh_seed();
        }
        self.on = on;
    }

    pub fn set_notif(&mut self, level: &str) -> Result<(), String> {
        if !STREAMER_NOTIF_LEVELS.contains(&level) {
            return Err(format!("Unknown notification level: {level}"));
        }
        self.notif = level.to_string();
        Ok(())
    }
}

fn fresh_seed() -> String {
    use rand::RngCore;
    let mut b = [0u8; 16];
    rand::thread_rng().fill_bytes(&mut b);
    crate::simd::hex::bytes_to_hex_string(&b)
}

/// Settings changes the relays have not confirmed, re-applied over any copy adopted before they
/// do. Only the fields the user touched, so the rest of a sibling's newer copy stands.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
struct SettingsIntent {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    advanced: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    on: Option<bool>,
    /// The seed this device minted going live, so adoption keeps the colours already on screen.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    seed: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    notif: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    hide_wallpapers: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    players_off: Option<bool>,
}

impl SettingsIntent {
    fn apply(&self, s: &mut SyncedSettings) {
        if let Some(advanced) = self.advanced {
            s.advanced = advanced;
        }
        if let Some(off) = self.players_off {
            s.players_off = off;
        }
        let st = &mut s.streamer;
        if let Some(on) = self.on {
            match self.seed.as_ref().filter(|seed| !seed.is_empty()) {
                Some(seed) if on => st.seed = seed.clone(),
                _ if on && !st.on => st.seed = fresh_seed(),
                _ => {}
            }
            st.on = on;
        }
        if let Some(level) = self.notif.as_deref() {
            if STREAMER_NOTIF_LEVELS.contains(&level) {
                st.notif = level.to_string();
            }
        }
        if let Some(hide) = self.hide_wallpapers {
            st.hide_wallpapers = hide;
        }
    }
}

fn one() -> u32 {
    1
}

impl IdList {
    /// Tolerant parse: a malformed payload degrades to empty rather than
    /// erroring, so one bad event can never wedge a sync.
    pub fn from_json(s: &str) -> Self {
        serde_json::from_str(s).unwrap_or_default()
    }
    pub fn to_json(&self) -> String {
        serde_json::to_string(self).unwrap_or_else(|_| "{\"v\":1,\"ids\":[]}".to_string())
    }
    pub fn contains(&self, id: &str) -> bool {
        self.ids.iter().any(|i| i == id)
    }
    pub fn add(&mut self, id: &str) -> Result<(), String> {
        if id.trim().is_empty() {
            return Err("empty id".to_string());
        }
        if self.contains(id) {
            return Ok(());
        }
        self.ids.push(id.to_string());
        if !fits(&self.to_json()) {
            self.ids.pop();
            return Err(LIST_FULL.to_string());
        }
        Ok(())
    }
    pub fn remove(&mut self, id: &str) {
        self.ids.retain(|i| i != id);
    }
}

impl NicknameMap {
    pub fn from_json(s: &str) -> Self {
        serde_json::from_str(s).unwrap_or_default()
    }
    pub fn to_json(&self) -> String {
        serde_json::to_string(self).unwrap_or_else(|_| "{\"v\":1,\"names\":{}}".to_string())
    }
    /// An empty nickname CLEARS the entry — that is how the UI expresses
    /// "remove this nickname", and keeping a blank would republish it forever.
    pub fn set(&mut self, npub: &str, name: &str) -> Result<(), String> {
        if npub.trim().is_empty() {
            return Err("empty npub".to_string());
        }
        if name.trim().is_empty() {
            self.names.remove(npub);
            return Ok(());
        }
        let prev = self.names.insert(npub.to_string(), name.to_string());
        if !fits(&self.to_json()) {
            match prev {
                Some(p) => self.names.insert(npub.to_string(), p),
                None => self.names.remove(npub),
            };
            return Err(LIST_FULL.to_string());
        }
        Ok(())
    }
}

/// Which list a call refers to. Keeps one set of network/storage plumbing for
/// all three rather than three near-identical copies that can drift.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pref {
    Blocks,
    Mutes,
    Nicknames,
    Notify,
    Rail,
    /// Communities whose banner the user hid.
    Banners,
    /// The general settings document.
    Settings,
    /// Chats tidied out of the list until someone speaks in them again.
    Archive,
    /// The widescreen Main Menu's pins and folders.
    Start,
}

/// Every list, in the order hydration walks them. `Notify` comes after `Mutes`
/// so a device holding both applies the richer one last and wins the overlap.
pub const ALL_PREFS: [Pref; 9] = [
    Pref::Blocks,
    Pref::Mutes,
    Pref::Nicknames,
    Pref::Notify,
    Pref::Rail,
    Pref::Start,
    Pref::Banners,
    Pref::Settings,
    Pref::Archive,
];

/// Every self-synced list's d tag, for the live subscriptions: built from [`ALL_PREFS`],
/// so a new list can't be read at boot and then never heard from again.
pub fn live_d_tags() -> Vec<String> {
    std::iter::once(crate::pinned_chats::PINNED_D_TAG)
        .chain(ALL_PREFS.iter().map(|p| p.d_tag()))
        .map(str::to_string)
        .collect()
}

impl Pref {
    pub fn d_tag(self) -> &'static str {
        match self {
            Pref::Blocks => BLOCKS_D_TAG,
            Pref::Mutes => MUTES_D_TAG,
            Pref::Nicknames => NICKNAMES_D_TAG,
            Pref::Notify => NOTIFY_D_TAG,
            Pref::Rail => RAIL_D_TAG,
            Pref::Banners => BANNERS_D_TAG,
            Pref::Settings => SETTINGS_D_TAG,
            Pref::Archive => ARCHIVE_D_TAG,
            Pref::Start => START_D_TAG,
        }
    }
    fn local_key(self) -> &'static str {
        match self {
            Pref::Blocks => BLOCKS_LOCAL_KEY,
            Pref::Mutes => MUTES_LOCAL_KEY,
            Pref::Nicknames => NICKNAMES_LOCAL_KEY,
            Pref::Notify => NOTIFY_LOCAL_KEY,
            Pref::Rail => RAIL_LOCAL_KEY,
            Pref::Banners => BANNERS_LOCAL_KEY,
            Pref::Settings => SETTINGS_LOCAL_KEY,
            Pref::Archive => ARCHIVE_LOCAL_KEY,
            Pref::Start => START_LOCAL_KEY,
        }
    }
    /// The d-tag → list routing used by the self-sync handler.
    pub fn from_d_tag(d: &str) -> Option<Self> {
        match d {
            BLOCKS_D_TAG => Some(Pref::Blocks),
            MUTES_D_TAG => Some(Pref::Mutes),
            NICKNAMES_D_TAG => Some(Pref::Nicknames),
            NOTIFY_D_TAG => Some(Pref::Notify),
            RAIL_D_TAG => Some(Pref::Rail),
            BANNERS_D_TAG => Some(Pref::Banners),
            SETTINGS_D_TAG => Some(Pref::Settings),
            ARCHIVE_D_TAG => Some(Pref::Archive),
            START_D_TAG => Some(Pref::Start),
            _ => None,
        }
    }
}

/// Lists this account has reconciled with the relays this session, keyed by
/// d-tag. Per-account by construction: it lives on the Session, so a swap drops
/// it and the next account re-hydrates rather than inheriting this one's.
struct Hydrated;

fn hydrated_set() -> std::sync::Arc<std::sync::Mutex<std::collections::HashSet<&'static str>>> {
    crate::db::current_session().scoped::<Hydrated, _>()
}

/// Has `pref` been reconciled with the relays yet this session?
///
/// **The publish gate.** These lists are whole-list newest-wins projections of
/// local state, so publishing one before the relay copy has been applied would
/// overwrite another device's prefs with this device's emptier view — a fresh
/// login that mutes one chat before the subscription replay lands would erase
/// every block, mute and nickname set elsewhere. Reconcile, THEN publish.
pub fn is_hydrated(pref: Pref) -> bool {
    hydrated_set().lock().map(|h| h.contains(pref.d_tag())).unwrap_or(false)
}

/// Mark `pref` reconciled. Called when a copy is applied AND when the relays
/// confirm none exists — "there is nothing to preserve" is just as reconciled
/// as having read it, and without that a first-ever account could never publish.
pub fn mark_hydrated(pref: Pref) {
    if let Ok(mut h) = hydrated_set().lock() {
        h.insert(pref.d_tag());
    }
}

/// Pull every list once at login and apply it, so this device is reconciled
/// before the user can touch anything. The live subscription also delivers
/// these, but it races the user; this does not.
///
/// A list whose fetch FAILS stays un-hydrated, so it stays unpublishable — far
/// better to leave prefs un-synced for a session than to overwrite prefs we
/// could not read.
pub async fn hydrate_all(client: &Client) -> Vec<(Pref, String)> {
    let Some(my_pk) = crate::state::my_public_key() else { return Vec::new() };
    let mut applied = Vec::new();
    for pref in ALL_PREFS {
        // The layouts are the lists that can hold edits the relays have never
        // seen: their publish is debounced, so a quit mid-drag leaves the newer
        // copy here. Applying the relay's older one would undo it.
        if pref.is_layout() && layout_is_dirty(pref) {
            mark_hydrated(pref);
            schedule_layout_publish(pref);
            continue;
        }
        let fetched = match fetch_raw(client, my_pk, pref).await {
            Ok(fetched) => fetched,
            Err(e) => {
                crate::log_warn!("[SyncedPrefs] reading {} failed, left unpublishable: {e}", pref.d_tag());
                continue;
            }
        };
        if pref == Pref::Archive {
            match fetched.map(|copy| adopt_archive(&copy.json, copy.created_at).map(|took| (copy, took))) {
                Some(Ok((copy, true))) => {
                    mark_hydrated(pref);
                    applied.push((pref, copy.json));
                }
                // Nothing stored, or older than what this device holds: ours stands.
                None | Some(Ok((_, false))) => mark_hydrated(pref),
                Some(Err(e)) => crate::log_warn!("[SyncedPrefs] adopting {} failed: {e}", pref.d_tag()),
            }
            continue;
        }
        if pref == Pref::Settings {
            match adopt_settings(fetched.as_ref()) {
                Ok(adopted) => {
                    // A stale copy means the relays lack this device's newer one.
                    if adopted.publish || adopted.stale {
                        publish_settings_soon();
                    }
                    applied.extend(adopted.json.map(|json| (pref, json)));
                }
                Err(e) => crate::log_warn!("[SyncedPrefs] adopting {} failed: {e}", pref.d_tag()),
            }
            continue;
        }
        match fetched {
            // A relay that missed our last publish still serves the one before it.
            Some(copy) if pref.is_layout() && !adopts_layout_copy(pref, copy.created_at) => mark_hydrated(pref),
            Some(copy) => {
                if save_local_raw(pref, &copy.json).is_ok() {
                    if pref.is_layout() {
                        set_layout_seen(pref, copy.created_at);
                    }
                    mark_hydrated(pref);
                    applied.push((pref, copy.json));
                }
            }
            // No stored copy: nothing to preserve, so this device may publish.
            None => mark_hydrated(pref),
        }
    }
    applied
}

/// Raw JSON of a list's local mirror. Callers parse into whichever shape the
/// list uses; the storage layer stays shape-agnostic.
pub fn load_local_raw(pref: Pref) -> Option<String> {
    crate::db::settings::get_sql_setting(pref.local_key().to_string())
        .ok()
        .flatten()
}

pub fn save_local_raw(pref: Pref, json: &str) -> Result<(), String> {
    crate::db::settings::set_sql_setting(pref.local_key().to_string(), json.to_string())
}

pub fn load_blocks() -> IdList {
    load_local_raw(Pref::Blocks).map(|s| IdList::from_json(&s)).unwrap_or_default()
}
pub fn load_mutes() -> IdList {
    load_local_raw(Pref::Mutes).map(|s| IdList::from_json(&s)).unwrap_or_default()
}
pub fn load_nicknames() -> NicknameMap {
    load_local_raw(Pref::Nicknames).map(|s| NicknameMap::from_json(&s)).unwrap_or_default()
}
pub fn load_notify() -> NotifyMap {
    load_local_raw(Pref::Notify).map(|s| NotifyMap::from_json(&s)).unwrap_or_default()
}
pub fn load_hidden_banners() -> IdList {
    load_local_raw(Pref::Banners).map(|s| IdList::from_json(&s)).unwrap_or_default()
}

/// Hide or show a community's banner, committed locally. The caller publishes.
///
/// Refused until the relay copy has been read, or a fresh login would publish
/// its empty list over the banners hidden on another device.
pub fn set_banner_hidden(community_id: &str, hidden: bool) -> Result<IdList, String> {
    if !is_hydrated(Pref::Banners) {
        return Err("Still syncing your settings, try again in a moment".to_string());
    }
    let mut list = load_hidden_banners();
    if hidden {
        list.add(community_id)?;
    } else {
        list.remove(community_id);
    }
    save_local_raw(Pref::Banners, &list.to_json())?;
    Ok(list)
}

pub fn load_archive() -> ArchiveMap {
    load_local_raw(Pref::Archive).map(|s| ArchiveMap::from_json(&s)).unwrap_or_default()
}

/// Serialises every read-modify-write of the archive: commands run on several threads.
struct ArchiveLock;

fn archive_lock() -> std::sync::Arc<std::sync::Mutex<()>> {
    crate::db::current_session().scoped::<ArchiveLock, _>()
}

fn archive_seen() -> u64 {
    crate::db::settings::get_sql_setting(ARCHIVE_SEEN_KEY.to_string())
        .ok()
        .flatten()
        .and_then(|s| s.parse().ok())
        .unwrap_or(0)
}

/// Archive a chat as of `at` (`Some`) or bring it back (`None`), committed locally. The caller
/// publishes. Refused until the relay copy has been read, for the same reason as the banners.
pub fn set_archived(chat_id: &str, at: Option<u64>) -> Result<ArchiveMap, String> {
    if !is_hydrated(Pref::Archive) {
        return Err("Still syncing your settings, try again in a moment".to_string());
    }
    let lock = archive_lock();
    let _g = lock.lock().unwrap_or_else(|e| e.into_inner());
    let mut map = load_archive();
    match at {
        Some(at) => map.set(chat_id, at)?,
        None => {
            map.chats.remove(chat_id);
        }
    }
    save_local_raw(Pref::Archive, &map.to_json())?;
    Ok(map)
}

/// Forget an archive that activity at `active_at` has outlived, on this device only. An outlived
/// entry is harmless (every reader looks past it) and leaves the relays with the next archive
/// change; publishing it from every device the message reaches would race them against each other.
/// The bool says whether anything changed.
pub fn revoke_archive(chat_id: &str, active_at: u64) -> Result<(ArchiveMap, bool), String> {
    let lock = archive_lock();
    let _g = lock.lock().unwrap_or_else(|e| e.into_inner());
    let mut map = load_archive();
    if !map.revoke(chat_id, active_at) {
        return Ok((map, false));
    }
    save_local_raw(Pref::Archive, &map.to_json())?;
    Ok((map, true))
}

/// Take a relay copy signed at `created_at` unless this device already holds a newer one: a relay
/// that was down can replay a week-old copy, and adopting it would bring back what was since
/// unarchived and drop what was since archived.
fn adopt_archive(json: &str, created_at: u64) -> Result<bool, String> {
    let lock = archive_lock();
    let _g = lock.lock().unwrap_or_else(|e| e.into_inner());
    if created_at < archive_seen() {
        return Ok(false);
    }
    save_local_raw(Pref::Archive, json)?;
    crate::db::settings::set_sql_setting(ARCHIVE_SEEN_KEY.to_string(), created_at.to_string())?;
    Ok(true)
}

/// The archive to publish and the `created_at` to sign it with: after every copy this device has
/// seen, since relays keep the lower id when two copies tie on a second.
fn claim_archive_publish(now: u64) -> Result<(String, u64), String> {
    let lock = archive_lock();
    let _g = lock.lock().unwrap_or_else(|e| e.into_inner());
    let at = now.max(archive_seen() + 1);
    crate::db::settings::set_sql_setting(ARCHIVE_SEEN_KEY.to_string(), at.to_string())?;
    Ok((load_archive().to_json(), at))
}

async fn publish_archive(client: &Client) -> Result<(), String> {
    let my_pk = crate::state::my_public_key().ok_or_else(|| "Not logged in".to_string())?;
    let (json, at) = claim_archive_publish(crate::clock::timestamp().as_secs())?;
    send_list(client, my_pk, Pref::Archive, &json, Some(at)).await
}

pub fn load_settings() -> SyncedSettings {
    load_local_raw(Pref::Settings).map(|s| SyncedSettings::from_json(&s)).unwrap_or_default()
}

/// Serialises every read-modify-write of the settings document, including adopting
/// a relay copy, so a change cannot land between a copy being read and being saved.
struct SettingsLock;

fn settings_lock() -> std::sync::Arc<std::sync::Mutex<()>> {
    crate::db::current_session().scoped::<SettingsLock, _>()
}

/// Turn Advanced Mode on or off, committed locally. The caller publishes.
///
/// Refused until the relay copy has been read, for the same reason as the banners.
pub fn set_advanced(on: bool) -> Result<SyncedSettings, String> {
    change_settings(|s, intent| {
        if !is_hydrated(Pref::Settings) {
            return Err("Still syncing your settings, try again in a moment".to_string());
        }
        s.advanced = on;
        intent.advanced = Some(on);
        Ok(())
    })
}

/// Go live or stop, in effect at once. The caller publishes.
///
/// Never refused for want of hydration: the change is held as an intent and
/// re-applied over the relay copy when it lands, then published.
pub fn set_streamer_on(on: bool) -> Result<SyncedSettings, String> {
    change_settings(|s, intent| {
        s.streamer.set_on(on);
        intent.on = Some(on);
        intent.seed = on.then(|| s.streamer.seed.clone());
        Ok(())
    })
}

/// Choose what notifications additionally hide while live. Held like [`set_streamer_on`].
pub fn set_streamer_notif(level: &str) -> Result<SyncedSettings, String> {
    change_settings(|s, intent| {
        s.streamer.set_notif(level)?;
        intent.notif = Some(s.streamer.notif.clone());
        Ok(())
    })
}

/// Choose whether chat wallpapers stay plain while live. Held like [`set_streamer_on`].
pub fn set_streamer_wallpapers(hide: bool) -> Result<SyncedSettings, String> {
    change_settings(|s, intent| {
        s.streamer.hide_wallpapers = hide;
        intent.hide_wallpapers = Some(hide);
        Ok(())
    })
}

/// Allow or refuse embedded video players. Held like [`set_streamer_on`]: switching them
/// off is a privacy choice, so it must not wait for the relay copy.
pub fn set_players(on: bool) -> Result<SyncedSettings, String> {
    change_settings(|s, intent| {
        s.players_off = !on;
        intent.players_off = Some(!on);
        Ok(())
    })
}

/// Commit a change locally and hold it as an intent until the relays confirm it, so no copy
/// adopted meanwhile (an older one, or one adopted after a failed publish) can undo it.
fn change_settings(
    change: impl FnOnce(&mut SyncedSettings, &mut SettingsIntent) -> Result<(), String>,
) -> Result<SyncedSettings, String> {
    let lock = settings_lock();
    let _g = lock.lock().unwrap_or_else(|e| e.into_inner());
    let mut intent = load_intent().unwrap_or_default();
    let mut settings = load_settings();
    change(&mut settings, &mut intent)?;
    save_local_raw(Pref::Settings, &settings.to_json())?;
    save_intent(&intent)?;
    Ok(settings)
}

fn load_intent() -> Option<SettingsIntent> {
    crate::db::settings::get_sql_setting(SETTINGS_INTENT_KEY.to_string())
        .ok()
        .flatten()
        .and_then(|s| serde_json::from_str(&s).ok())
}

fn save_intent(intent: &SettingsIntent) -> Result<(), String> {
    let json = serde_json::to_string(intent).map_err(|e| e.to_string())?;
    crate::db::settings::set_sql_setting(SETTINGS_INTENT_KEY.to_string(), json)
}

fn clear_intent() {
    let _ = crate::db::settings::remove_setting(SETTINGS_INTENT_KEY);
}

/// `created_at` of the newest settings copy this device adopted or saw published. Anything
/// older is a copy it already superseded, however late a relay delivers it.
fn settings_seen() -> u64 {
    crate::db::settings::get_sql_setting(SETTINGS_SEEN_KEY.to_string())
        .ok()
        .flatten()
        .and_then(|s| s.parse().ok())
        .unwrap_or(0)
}

fn set_settings_seen(at: u64) -> Result<(), String> {
    crate::db::settings::set_sql_setting(SETTINGS_SEEN_KEY.to_string(), at.to_string())
}

/// The last `created_at` this session signed settings with, so each publish lands strictly after
/// the one before it even while that one is still in flight.
struct SettingsSigned;

fn settings_signed() -> std::sync::Arc<std::sync::atomic::AtomicU64> {
    crate::db::current_session().scoped::<SettingsSigned, _>()
}

/// A list as one relay copy carries it: the plaintext and when it was signed.
#[derive(Debug, Clone, PartialEq)]
pub struct RelayCopy {
    pub json: String,
    pub created_at: u64,
}

/// The outcome of taking a relay copy of the settings document.
#[derive(Debug, Clone, PartialEq)]
pub struct AdoptedSettings {
    /// The document now held, when the copy changed it.
    pub json: Option<String>,
    /// This device holds a change the relays have not seen.
    pub publish: bool,
    /// The copy is older than one this device already adopted or published, so it was ignored.
    pub stale: bool,
}

/// Take a relay copy of the settings (`None` = the relays hold none) and mark them reconciled.
///
/// A copy older than the newest this device adopted or published is ignored, so a lagging relay
/// or a late echo never rolls the document back. A held change is re-applied over a newer copy.
pub fn adopt_settings(relay: Option<&RelayCopy>) -> Result<AdoptedSettings, String> {
    let lock = settings_lock();
    let _g = lock.lock().unwrap_or_else(|e| e.into_inner());
    let intent = load_intent();
    let adopted = match relay {
        Some(copy) if copy.created_at < settings_seen() => {
            AdoptedSettings { json: None, publish: false, stale: true }
        }
        Some(copy) => {
            let theirs = SyncedSettings::from_json(&copy.json);
            let mut merged = theirs.clone();
            if let Some(intent) = &intent {
                intent.apply(&mut merged);
            }
            set_settings_seen(copy.created_at)?;
            if merged == theirs {
                // The relays already say what we meant: usually our own publish echoing back.
                if intent.is_some() {
                    clear_intent();
                }
                save_local_raw(Pref::Settings, &copy.json)?;
                AdoptedSettings { json: Some(copy.json.clone()), publish: false, stale: false }
            } else {
                let merged = merged.to_json();
                save_local_raw(Pref::Settings, &merged)?;
                AdoptedSettings { json: Some(merged), publish: true, stale: false }
            }
        }
        // Relays that lost a copy this device once had get it back.
        None => AdoptedSettings { json: None, publish: intent.is_some() || settings_seen() > 0, stale: false },
    };
    mark_hydrated(Pref::Settings);
    Ok(adopted)
}

fn publish_settings_soon() {
    crate::db::spawn_bound(async {
        let Some(client) = crate::state::nostr_client() else { return };
        if let Err(e) = publish_settings(&client, false).await {
            crate::log_warn!("[SyncedPrefs] publishing {} failed: {e}", Pref::Settings.d_tag());
        }
    });
}

/// Publish the local settings, signed after every copy this device has adopted or signed so the
/// relays keep it over them.
///
/// With `refresh`, a newer relay copy is folded in first, so a device that missed a sibling's
/// change never publishes its stale document over it. That copy is returned for the caller to show.
pub async fn publish_settings(client: &Client, refresh: bool) -> Result<Option<String>, String> {
    let my_pk = crate::state::my_public_key().ok_or_else(|| "Not logged in".to_string())?;
    let mut shown = None;
    if refresh {
        if let Ok(Some(copy)) = fetch_raw(client, my_pk, Pref::Settings).await {
            if copy.created_at > settings_seen() {
                let adopted = adopt_settings(Some(&copy))?;
                shown = adopted.json;
                if !adopted.publish {
                    return Ok(shown);
                }
            }
        }
    }
    let (json, at) = claim_publish(crate::clock::timestamp().as_secs());
    send_list(client, my_pk, Pref::Settings, &json, Some(at)).await?;
    settings_published(&json, at);
    Ok(shown)
}

/// The document to publish and the `created_at` to sign it with, taken together so a later
/// claim always carries the later document.
fn claim_publish(now: u64) -> (String, u64) {
    let lock = settings_lock();
    let _g = lock.lock().unwrap_or_else(|e| e.into_inner());
    let signed = settings_signed();
    // Two publishes in one second would tie, and relays keep the lower id, not the later one.
    let at = now
        .max(settings_seen() + 1)
        .max(signed.load(std::sync::atomic::Ordering::SeqCst) + 1);
    signed.store(at, std::sync::atomic::Ordering::SeqCst);
    (load_settings().to_json(), at)
}

/// The relays now hold `json`, signed at `at`: older copies are superseded, and a held intent is
/// done once nothing has changed since.
fn settings_published(json: &str, at: u64) {
    let lock = settings_lock();
    let _g = lock.lock().unwrap_or_else(|e| e.into_inner());
    if at > settings_seen() {
        let _ = set_settings_seen(at);
    }
    if load_intent().is_some() && SyncedSettings::from_json(json) == load_settings() {
        clear_intent();
    }
}

pub fn load_rail() -> crate::rail_layout::RailLayout {
    load_layout(Pref::Rail)
}

/// The Main Menu's pins, in the rail's shape: keys are pin keys (`crate::start_menu`).
pub fn load_start() -> crate::rail_layout::RailLayout {
    load_layout(Pref::Start)
}

fn load_layout(pref: Pref) -> crate::rail_layout::RailLayout {
    let mut layout = load_local_raw(pref)
        .map(|s| crate::rail_layout::RailLayout::from_json(&s))
        .unwrap_or_default();
    // A copy from a buggy or hostile writer can repeat a key; the menu keys its tiles by them.
    if layout.is_editable() {
        layout.normalize();
    }
    layout
}

struct LayoutEditLock;

/// Load, change and commit one layout, one edit at a time: commands run on several
/// threads, and two read-modify-writes interleaved would drop one of them. Returns the
/// layout and whether anything moved (nothing is written when nothing did).
pub fn edit_layout(
    pref: Pref,
    f: impl FnOnce(&mut crate::rail_layout::RailLayout) -> Result<(), String>,
) -> Result<(crate::rail_layout::RailLayout, bool), String> {
    if !pref.is_layout() {
        return Err(format!("{} is not a layout", pref.d_tag()));
    }
    let lock: std::sync::Arc<std::sync::Mutex<()>> = crate::db::current_session().scoped::<LayoutEditLock, _>();
    let _turn = lock.lock().unwrap_or_else(|e| e.into_inner());
    let before = load_layout(pref);
    let mut layout = before.clone();
    f(&mut layout)?;
    let changed = layout != before;
    if changed {
        save_layout_debounced(pref, &layout)?;
    }
    Ok((layout, changed))
}

async fn decrypt_event(my_pk: &PublicKey, event: &Event) -> Option<String> {
    if event.content.is_empty() {
        return None;
    }
    let signer = crate::signer::active_signer().ok()?;
    match signer.nip44_decrypt_async(my_pk, &event.content).await {
        Ok(plaintext) => Some(plaintext),
        Err(e) => {
            crate::log_warn!("[SyncedPrefs] decrypt {} failed: {}", event.kind.as_u16(), e);
            None
        }
    }
}

/// Fetch a list's newest relay copy, `Ok(None)` when the relays hold none.
///
/// `Err` when no relay answered or the copy can't be opened: neither says what the relays hold,
/// and treating it as "none" would let this device publish its emptier view over the real one.
pub async fn fetch_raw(client: &Client, my_pk: PublicKey, pref: Pref) -> Result<Option<RelayCopy>, String> {
    let filter = Filter::new()
        .author(my_pk)
        .kind(Kind::Custom(event_kind::APPLICATION_SPECIFIC))
        .identifier(pref.d_tag())
        .limit(1);
    let timeout = crate::relay_request_timeout(std::time::Duration::from_secs(FETCH_TIMEOUT_SECS));
    let events = crate::fetch_answered(client, filter, timeout).await?;
    let Some(event) = crate::newest_replaceable(events) else { return Ok(None) };
    let json = decrypt_event(&my_pk, &event)
        .await
        .ok_or_else(|| format!("couldn't open {}", pref.d_tag()))?;
    Ok(Some(RelayCopy { json, created_at: event.created_at.as_secs() }))
}

/// Persist locally, then publish self-encrypted. Settings always go out from the local copy,
/// through [`publish_settings`], which keeps their signing order.
pub async fn publish_raw(client: &Client, pref: Pref, json: &str) -> Result<(), String> {
    if pref == Pref::Settings {
        return publish_settings(client, false).await.map(|_| ());
    }
    if pref == Pref::Archive {
        return publish_archive(client).await;
    }
    let my_pk = crate::state::my_public_key().ok_or_else(|| "Not logged in".to_string())?;
    save_local_raw(pref, json)?;
    send_list(client, my_pk, pref, json, None).await
}

async fn send_list(
    client: &Client, my_pk: PublicKey, pref: Pref, json: &str, created_at: Option<u64>,
) -> Result<(), String> {
    let signer = crate::signer::active_signer().map_err(|e| format!("Signer unavailable: {e}"))?;
    let content = signer
        .nip44_encrypt_async(&my_pk, json)
        .await
        .map_err(|e| format!("nip44 encrypt {}: {e}", pref.d_tag()))?;
    let mut builder = EventBuilder::new(Kind::Custom(event_kind::APPLICATION_SPECIFIC), content)
        .tag(Tag::identifier(pref.d_tag()));
    if let Some(at) = created_at {
        builder = builder.custom_created_at(Timestamp::from_secs(at));
    }
    crate::sign_and_send(client, builder)
        .await
        .map_err(|e| format!("publish {}: {e}", pref.d_tag()))?;
    Ok(())
}

/// Consume a sibling device's update. Never answers an echo with a publish — the
/// relay echoes our own publishes back on this same subscription, and that loops
/// forever. The one republish is a held settings intent the copy lacks, which an
/// echo of our own latest publish already carries. `None` for a settings copy older
/// than this device's, which changes nothing.
pub async fn ingest_remote(my_pk: &PublicKey, event: &Event) -> Option<(Pref, String)> {
    let d = event.tags.identifier().unwrap_or_default().to_string();
    let pref = Pref::from_d_tag(&d)?;
    let json = decrypt_event(my_pk, event).await?;
    if pref == Pref::Settings {
        let copy = RelayCopy { json, created_at: event.created_at.as_secs() };
        let adopted = match adopt_settings(Some(&copy)) {
            Ok(adopted) => adopted,
            Err(e) => {
                crate::log_warn!("[SyncedPrefs] adopting {} failed: {e}", pref.d_tag());
                return None;
            }
        };
        if adopted.publish {
            publish_settings_soon();
        }
        return adopted.json.map(|json| (pref, json));
    }
    if pref == Pref::Archive {
        return match adopt_archive(&json, event.created_at.as_secs()) {
            Ok(true) => {
                mark_hydrated(pref);
                Some((pref, json))
            }
            Ok(false) => None,
            Err(e) => {
                crate::log_warn!("[SyncedPrefs] persisting {} failed: {e}", pref.d_tag());
                None
            }
        };
    }
    let created_at = event.created_at.as_secs();
    if pref.is_layout() && !adopts_layout_copy(pref, created_at) {
        mark_hydrated(pref);
        return None;
    }
    if let Err(e) = save_local_raw(pref, &json) {
        crate::log_warn!("[SyncedPrefs] persisting {} failed: {e}", pref.d_tag());
        return None;
    }
    if pref.is_layout() {
        set_layout_seen(pref, created_at);
    }
    mark_hydrated(pref);
    Some((pref, json))
}

// ============================================================================
// The rail's debounced publish
// ============================================================================

/// How long the rail must sit still before its arrangement goes out.
///
/// Rearranging is burst activity: a minute of dragging communities in and out
/// of folders is ONE document at the end of it, not forty along the way. The
/// local mirror already holds every intermediate state, so nothing is at risk
/// while the timer runs.
const RAIL_PUBLISH_IDLE: std::time::Duration = std::time::Duration::from_millis(2500);

/// Bumped by every edit of a layout. A sleeping publish that wakes to find a newer
/// generation was superseded mid-drag and simply stops, which is what collapses
/// a burst into one write.
struct RailPublishGen;
struct StartPublishGen;

fn layout_gen(pref: Pref) -> std::sync::Arc<std::sync::atomic::AtomicU64> {
    if pref == Pref::Start {
        crate::db::current_session().scoped::<StartPublishGen, _>()
    } else {
        crate::db::current_session().scoped::<RailPublishGen, _>()
    }
}

impl Pref {
    /// An arrangement the user drags about: saved at once, published once the dragging stops.
    fn is_layout(self) -> bool {
        matches!(self, Pref::Rail | Pref::Start)
    }
    fn dirty_key(self) -> &'static str {
        if self == Pref::Start { START_DIRTY_KEY } else { RAIL_DIRTY_KEY }
    }
    fn seen_key(self) -> &'static str {
        if self == Pref::Start { START_SEEN_KEY } else { RAIL_SEEN_KEY }
    }
}

/// Whether a relay's copy of a layout replaces ours. Never over unsent edits, which are
/// newer than any copy out there and publish regardless; nor when it is no newer than one
/// we hold, since relays replay what they kept, in no order, and our own echo among it.
fn adopts_layout_copy(pref: Pref, created_at: u64) -> bool {
    !layout_is_dirty(pref) && created_at > layout_seen(pref)
}

/// The newest copy of a layout this device has adopted or published.
fn layout_seen(pref: Pref) -> u64 {
    crate::db::settings::get_sql_setting(pref.seen_key().to_string())
        .ok()
        .flatten()
        .and_then(|s| s.parse().ok())
        .unwrap_or(0)
}

fn set_layout_seen(pref: Pref, at: u64) {
    if at > layout_seen(pref) {
        let _ = crate::db::settings::set_sql_setting(pref.seen_key().to_string(), at.to_string());
    }
}

/// Whether a layout holds edits the relays have not seen.
pub fn layout_is_dirty(pref: Pref) -> bool {
    pref.is_layout()
        && crate::db::settings::get_sql_setting(pref.dirty_key().to_string())
        .ok()
        .flatten()
        .as_deref()
        == Some("1")
}

fn set_layout_dirty(pref: Pref, dirty: bool) {
    let _ = crate::db::settings::set_sql_setting(
        pref.dirty_key().to_string(),
        if dirty { "1" } else { "0" }.to_string(),
    );
}

/// Commit an arrangement: on disk now, on the relays once the dragging stops.
///
/// The local mirror is the truth the rail and the Main Menu paint from, so the UI
/// never waits on a relay to show a drag landing.
pub fn save_layout_debounced(pref: Pref, layout: &crate::rail_layout::RailLayout) -> Result<(), String> {
    if !pref.is_layout() {
        return Err(format!("{} is not a layout", pref.d_tag()));
    }
    save_local_raw(pref, &layout.to_json())?;
    set_layout_dirty(pref, true);
    schedule_layout_publish(pref);
    Ok(())
}

fn schedule_layout_publish(pref: Pref) {
    let generation = layout_gen(pref).fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
    crate::db::spawn_bound(async move {
        crate::rt::time::sleep(RAIL_PUBLISH_IDLE).await;
        if layout_gen(pref).load(std::sync::atomic::Ordering::Relaxed) != generation {
            return;
        }
        flush_layout(pref).await;
    });
}

/// Publish the arrangement if it has unsent edits.
///
/// A failure leaves the dirty flag set rather than retrying in a loop: the next
/// edit reschedules, and failing that the next boot does, because the flag is
/// persisted. That is also what covers a quit inside the debounce window — the
/// publish never ran, and the arrangement is not lost.
pub async fn flush_rail() {
    flush_layout(Pref::Rail).await
}

pub async fn flush_layout(pref: Pref) {
    if !layout_is_dirty(pref) || !is_hydrated(pref) {
        return;
    }
    let (Some(client), Some(my_pk)) = (crate::state::nostr_client(), crate::state::my_public_key()) else { return };
    let generation = layout_gen(pref).load(std::sync::atomic::Ordering::Relaxed);
    let Some(json) = load_local_raw(pref) else { return };
    // Dated after every copy we hold, so ours is the newest wherever it lands.
    let at = crate::clock::timestamp().as_secs().max(layout_seen(pref) + 1);
    match send_list(&client, my_pk, pref, &json, Some(at)).await {
        // An edit made while this copy was out is still unsent; its own timer sends it.
        Ok(()) => {
            set_layout_seen(pref, at);
            if layout_gen(pref).load(std::sync::atomic::Ordering::Relaxed) == generation {
                set_layout_dirty(pref, false);
            }
        }
        Err(e) => crate::log_warn!("[SyncedPrefs] {} publish deferred: {e}", pref.d_tag()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn d_tags_round_trip_and_are_distinct() {
        for p in ALL_PREFS {
            assert_eq!(Pref::from_d_tag(p.d_tag()), Some(p));
        }
        // A tag belonging to another 30078 list must not resolve here, or the
        // self-sync router would hand a Community List to the block ingest.
        assert_eq!(Pref::from_d_tag("vector/communities"), None);
        assert_eq!(Pref::from_d_tag("vector/pinned"), None);
        assert_eq!(Pref::from_d_tag(""), None);
    }

    #[test]
    fn an_archive_is_revoked_only_by_later_activity() {
        let mut m = ArchiveMap::default();
        m.set("npub1a", 1_000).unwrap();
        assert!(!m.revoke("npub1a", 1_000), "activity at the archive moment is what was archived");
        assert!(!m.revoke("npub1a", 900));
        assert!(!m.revoke("npub1b", 5_000), "nothing to revoke");
        assert!(m.revoke("npub1a", 1_001));
        assert!(m.chats.is_empty());
        assert!(m.set(" ", 1).is_err());
    }

    #[test]
    fn an_archive_keeps_what_a_newer_build_wrote() {
        let mut m = ArchiveMap::default();
        m.set("npub1a", 1_700_000_000_123).unwrap();
        assert_eq!(ArchiveMap::from_json(&m.to_json()), m);
        assert_eq!(ArchiveMap::from_json("not json"), ArchiveMap::default());
        assert_eq!(ArchiveMap::from_json("{}").v, 1);

        let newer = r#"{"v":1,"chats":{"npub1a":5,"npub1b":{"at":7,"why":"x"}},"folders":[1]}"#;
        let m = ArchiveMap::from_json(newer);
        assert_eq!(m.at("npub1a"), Some(5));
        assert_eq!(m.at("npub1b"), None, "a shape this build can't read is not archived here");
        assert_eq!(m.times().len(), 1);
        let back: serde_json::Value = serde_json::from_str(&m.to_json()).unwrap();
        assert_eq!(back["chats"]["npub1b"]["why"], "x", "and survives our republish");
        assert_eq!(back["folders"], serde_json::json!([1]));
    }

    #[test]
    fn the_archive_caps_new_chats_but_not_existing_ones() {
        let mut m = ArchiveMap::default();
        for i in 0..ARCHIVE_MAX_ENTRIES {
            m.set(&format!("npub1{i}"), 1).unwrap();
        }
        assert!(m.set("npub1new", 1).is_err());
        assert!(m.set("npub10", 2).is_ok(), "re-archiving a chat already held still works");
        let mut full = ArchiveMap::default();
        for i in 0..ARCHIVE_MAX_ENTRIES {
            full.set(&format!("npub1{:058}", i), 1_760_000_000_000).unwrap();
        }
        // NIP-44: padded plaintext plus version, nonce, length prefix and MAC, then base64.
        let len = full.to_json().len();
        let next = (len - 1).next_power_of_two();
        let chunk = if next <= 256 { 32 } else { next / 8 };
        let padded = chunk * ((len - 1) / chunk + 1);
        let content = (padded + 67).div_ceil(3) * 4;
        assert!(content + 1024 < 65_536, "a full archive fits a relay's default 64KB event cap ({content} bytes)");
    }

    #[test]
    fn archiving_waits_for_the_relay_copy_but_forgetting_does_not() {
        let (_tmp, _guard) = init_test_db();
        assert!(set_archived("npub1a", Some(10)).is_err(), "would publish over the other devices' archive");
        assert!(adopt_archive(r#"{"v":1,"chats":{"npub1a":10}}"#, 100).unwrap());
        let (map, changed) = revoke_archive("npub1a", 11).unwrap();
        assert!(changed && map.chats.is_empty(), "an outlived entry goes without the relay copy");
        mark_hydrated(Pref::Archive);
        assert_eq!(set_archived("npub1a", Some(20)).unwrap().at("npub1a"), Some(20));
        let (_, changed) = revoke_archive("npub1a", 15).unwrap();
        assert!(!changed, "a re-archive outlives a message older than it");
    }

    #[test]
    fn an_older_archive_copy_never_replaces_a_newer_one() {
        let (_tmp, _guard) = init_test_db();
        assert!(adopt_archive(r#"{"v":1,"chats":{"npub1p":1}}"#, 200).unwrap());
        assert!(!adopt_archive(r#"{"v":1,"chats":{"npub1x":1}}"#, 150).unwrap(), "a relay replaying last week");
        assert_eq!(load_archive().at("npub1p"), Some(1));
        assert!(load_archive().at("npub1x").is_none());
        let (_, at) = claim_archive_publish(100).unwrap();
        assert!(at > 200, "our publish lands after every copy we hold");
        assert!(!adopt_archive(r#"{"v":1,"chats":{}}"#, at - 1).unwrap(), "nor does one signed before ours");
    }

    #[test]
    fn id_lists_add_idempotently_and_remove_tolerantly() {
        let mut l = IdList::default();
        l.add("npub1a").unwrap();
        l.add("npub1a").unwrap();
        assert_eq!(l.ids.len(), 1, "a second add is not a second entry");
        l.remove("never-present");
        l.remove("npub1a");
        assert!(l.ids.is_empty());
        assert!(l.add("  ").is_err(), "an empty id is refused, not stored");
    }

    #[test]
    fn an_empty_nickname_clears_rather_than_storing_a_blank() {
        let mut n = NicknameMap::default();
        n.set("npub1a", "Landlord").unwrap();
        assert_eq!(n.names.get("npub1a").map(String::as_str), Some("Landlord"));
        n.set("npub1a", "").unwrap();
        assert!(!n.names.contains_key("npub1a"), "clearing removes the key, not blanks it");
    }

    #[test]
    fn malformed_payloads_degrade_to_empty_instead_of_erroring() {
        assert!(IdList::from_json("not json").ids.is_empty());
        assert!(IdList::from_json("{}").ids.is_empty());
        assert!(NicknameMap::from_json("[]").names.is_empty());
        // An unknown version still yields its entries rather than being dropped.
        let future = IdList::from_json("{\"v\":99,\"ids\":[\"a\"],\"extra\":1}");
        assert_eq!(future.ids, vec!["a".to_string()]);
    }

    #[test]
    fn lists_refuse_to_grow_past_the_event_ceiling() {
        let npub = |i: usize| format!("npub1{i:0>58}");
        let mut l = IdList::default();
        let mut n = 0;
        while l.add(&npub(n)).is_ok() {
            n += 1;
        }
        assert!(n > 500, "a full list still holds hundreds of npubs, held {n}");
        assert_eq!(l.ids.len(), n, "the refused entry is not kept");
        assert!(fits(&l.to_json()));
        // Removing frees a slot again.
        l.remove(&npub(0));
        assert!(l.add(&npub(n)).is_ok());

        // Every list, at its fullest, is an event a relay takes.
        let me = nostr_sdk::prelude::Keys::generate();
        let mut names = NicknameMap::default();
        let mut i = 0;
        while names.set(&npub(i), &"\"".repeat(16)).is_ok() {
            i += 1;
        }
        let mut notify = NotifyMap::default();
        let mut j = 0;
        let widest = NotifyEntry { level: Some("mentions".into()), mute_until: i64::MAX, suppress_everyone: Some(true) };
        while notify.set(&format!("{j:0>64}"), widest.clone()).is_ok() {
            j += 1;
        }
        for json in [l.to_json(), names.to_json(), notify.to_json()] {
            let ck = nostr_sdk::prelude::nip44::v2::ConversationKey::derive(me.secret_key(), &me.public_key()).unwrap();
            let ct = crate::community::cipher::encrypt_with_random_nonce(&ck, json.as_bytes()).unwrap();
            let ev = nostr_sdk::prelude::EventBuilder::new(nostr_sdk::prelude::Kind::Custom(30078), crate::simd::base64::STANDARD.encode_to_string(&ct))
                .tag(nostr_sdk::prelude::Tag::identifier("vector/blocks"))
                .finalize(&me)
                .unwrap();
            assert!(crate::event_size::check(&ev).is_ok(), "{} bytes", ev.as_json().len());
        }
    }

    #[test]
    fn settings_keep_keys_this_build_does_not_know() {
        let mut s = SyncedSettings::from_json("{\"v\":1,\"advanced\":false,\"future\":{\"a\":1}}");
        assert!(!s.advanced);
        s.advanced = true;
        let back = SyncedSettings::from_json(&s.to_json());
        assert!(back.advanced);
        assert_eq!(back.other.get("future"), Some(&serde_json::json!({ "a": 1 })), "a newer device's key survives our republish");
        assert!(SyncedSettings::from_json("not json") == SyncedSettings::default());
        assert!(!SyncedSettings::default().to_json().contains("advanced"), "off is the absent default");
    }

    #[test]
    fn streamer_keys_this_build_does_not_know_survive_too() {
        let json = r#"{"v":1,"streamer":{"on":true,"seed":"ab","notif":"hide_all","tint":3},"future":1}"#;
        let mut s = SyncedSettings::from_json(json);
        assert!(s.streamer.on);
        assert_eq!(s.streamer.notif, "hide_all");
        s.advanced = true;
        let back = SyncedSettings::from_json(&s.to_json());
        assert_eq!(back.streamer.other.get("tint"), Some(&serde_json::json!(3)));
        assert_eq!(back.other.get("future"), Some(&serde_json::json!(1)));
        assert!(!back.other.contains_key("streamer"), "a known key is not double-carried");
    }

    #[test]
    fn streamer_defaults_stay_off_the_wire_and_on_the_view() {
        let s = SyncedSettings::from_json(r#"{"v":1}"#);
        assert_eq!(s.streamer.notif, "none");
        assert!(!s.to_json().contains("streamer"));
        assert_eq!(
            s.view(),
            serde_json::json!({ "advanced": false, "players": true, "streamer": { "on": false, "seed": "", "notif": "none", "hide_wallpapers": true } })
        );
    }

    #[test]
    fn wallpapers_hide_by_default_and_showing_them_is_kept_through_adoption() {
        let (_tmp, _guard) = init_test_db();
        assert!(SyncedSettings::from_json(r#"{"v":1,"streamer":{"on":true}}"#).streamer.hide_wallpapers);
        set_streamer_wallpapers(false).unwrap();
        assert!(SyncedSettings::from_json(&load_settings().to_json()).streamer.other.is_empty());
        assert!(load_settings().to_json().contains(r#""hide_wallpapers":false"#), "off is the one value on the wire");
        let adopted = adopt_settings(Some(&copy(r#"{"v":1,"streamer":{"on":true,"seed":"ab"}}"#, 100))).unwrap();
        assert!(adopted.publish, "the relays lack it");
        let held = load_settings().streamer;
        assert!(held.on && !held.hide_wallpapers, "theirs and ours both stand");
    }

    #[test]
    fn players_default_on_and_switching_them_off_is_kept_through_adoption() {
        let (_tmp, _guard) = init_test_db();
        assert!(!SyncedSettings::default().players_off && !SyncedSettings::from_json("not json").players_off);
        set_players(false).unwrap();
        assert!(load_settings().to_json().contains(r#""players_off":true"#), "off is the one value on the wire");
        let adopted = adopt_settings(Some(&copy(r#"{"v":1,"advanced":true}"#, 100))).unwrap();
        assert!(adopted.publish, "the relays lack it");
        let held = load_settings();
        assert!(held.advanced && held.players_off, "theirs and ours both stand");
        set_players(true).unwrap();
        assert!(!load_settings().to_json().contains("players_off"));
    }

    #[test]
    fn going_live_reseeds_and_staying_live_does_not() {
        let mut s = StreamerSettings::default();
        s.set_on(true);
        let first = s.seed.clone();
        assert_eq!(first.len(), 32);
        assert!(first.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)), "lowercase hex: {first}");
        s.set_on(true);
        assert_eq!(s.seed, first, "on to on keeps the colours");
        s.set_on(false);
        assert_eq!(s.seed, first, "stopping keeps the last seed");
        s.set_on(true);
        assert_ne!(s.seed, first, "each go-live reshuffles");
    }

    #[test]
    fn the_overlay_takes_only_known_levels() {
        let mut s = StreamerSettings::default();
        for level in STREAMER_NOTIF_LEVELS {
            s.set_notif(level).unwrap();
            assert_eq!(s.notif, level);
        }
        assert!(s.set_notif("hide_everything").is_err());
        assert_eq!(s.notif, "hide_all", "a refused level changes nothing");
    }

    #[test]
    fn every_synced_list_is_on_the_live_subscription() {
        let tags = live_d_tags();
        for p in ALL_PREFS {
            assert!(tags.contains(&p.d_tag().to_string()), "{} read at boot but never heard live", p.d_tag());
        }
        assert!(tags.contains(&crate::pinned_chats::PINNED_D_TAG.to_string()));
    }

    #[tokio::test]
    async fn the_two_layouts_keep_their_own_edits_and_nothing_else_is_one() {
        let (_tmp, _guard) = init_test_db();
        let (start, changed) = edit_layout(Pref::Start, |l| crate::start_menu::pin(l, "nexus").map(|_| ())).unwrap();
        assert!(changed && start.contains("nexus"));
        assert!(layout_is_dirty(Pref::Start), "unsent until the dragging stops");
        assert!(!layout_is_dirty(Pref::Rail), "the rail's state is its own");
        assert!(load_rail().nodes.is_empty());
        let (_, changed) = edit_layout(Pref::Start, |l| crate::start_menu::pin(l, "nexus").map(|_| ())).unwrap();
        assert!(!changed, "an edit that moves nothing writes nothing");
        assert!(edit_layout(Pref::Blocks, |_| Ok(())).is_err());
        assert!(save_layout_debounced(Pref::Blocks, &start).is_err(), "a layout never lands in another list");
        assert!(!layout_is_dirty(Pref::Blocks));
    }

    #[test]
    fn a_layout_takes_only_a_newer_copy_and_never_over_unsent_edits() {
        let (_tmp, _guard) = init_test_db();
        assert!(adopts_layout_copy(Pref::Start, 100), "a first copy is taken");
        set_layout_seen(Pref::Start, 100);
        assert!(!adopts_layout_copy(Pref::Start, 100), "our own echo changes nothing");
        assert!(!adopts_layout_copy(Pref::Start, 90), "a relay replaying the copy before");
        assert!(adopts_layout_copy(Pref::Start, 101));
        set_layout_seen(Pref::Start, 50);
        assert!(!adopts_layout_copy(Pref::Start, 99), "what we have seen only moves forward");
        assert!(adopts_layout_copy(Pref::Rail, 60), "each layout keeps its own");
        set_layout_dirty(Pref::Start, true);
        assert!(!adopts_layout_copy(Pref::Start, 999), "unsent edits outrank any copy");
    }

    #[test]
    fn a_layout_repeating_a_key_loads_once_each() {
        let (_tmp, _guard) = init_test_db();
        save_local_raw(Pref::Start, r#"{"v":1,"nodes":[{"type":"item","key":"nexus"},{"type":"item","key":"nexus"},{"type":"folder","id":"f","keys":["requests","nexus","settings"]}]}"#).unwrap();
        assert_eq!(load_start().flatten(), vec!["nexus".to_string(), "requests".to_string(), "settings".to_string()]);
    }

    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        crate::db::close_database();
        crate::db::clear_id_caches();
        let tmp = tempfile::tempdir().unwrap();
        let account = Keys::generate().public_key().to_bech32().unwrap();
        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
        crate::db::set_current_account(account.clone()).unwrap();
        crate::db::init_database(&account).unwrap();
        (tmp, guard)
    }

    fn copy(json: &str, created_at: u64) -> RelayCopy {
        RelayCopy { json: json.to_string(), created_at }
    }

    #[test]
    fn a_go_live_before_hydration_outlasts_the_relay_copy_and_is_published() {
        let (_tmp, _guard) = init_test_db();
        assert!(!is_hydrated(Pref::Settings));
        assert!(set_advanced(true).is_err(), "Advanced Mode still waits for the relay copy");

        let live = set_streamer_on(true).expect("never refused before hydration");
        set_streamer_notif("hide_sender").unwrap();
        assert!(load_settings().streamer.on, "in effect at once");
        let seed = live.streamer.seed.clone();

        let relay = r#"{"v":1,"advanced":true,"streamer":{"on":false,"seed":"00","notif":"none"},"future":1}"#;
        let adopted = adopt_settings(Some(&copy(relay, 100))).unwrap();
        assert!(adopted.publish, "the relays lack our change");
        assert!(is_hydrated(Pref::Settings));

        let held = load_settings();
        assert!(held.streamer.on && held.advanced, "ours and theirs both stand");
        assert_eq!(held.streamer.seed, seed, "the colours on screen are kept");
        assert_eq!(held.streamer.notif, "hide_sender");
        assert_eq!(held.other.get("future"), Some(&serde_json::json!(1)));
        assert_eq!(adopted.json.as_deref(), Some(held.to_json().as_str()), "the page is shown the merge");

        assert!(load_intent().is_some(), "held until the relays have it");
        let (json, at) = claim_publish(100);
        assert!(at > 100, "signed after the copy it supersedes");
        settings_published(&json, at);
        assert!(load_intent().is_none());
        let echo = adopt_settings(Some(&copy(&json, at))).unwrap();
        assert!(!echo.publish, "our own echo is never answered");
    }

    #[test]
    fn an_echo_that_beats_the_publish_ack_retires_the_intent() {
        let (_tmp, _guard) = init_test_db();
        set_streamer_on(true).unwrap();
        let (json, at) = claim_publish(100);
        let adopted = adopt_settings(Some(&copy(&json, at))).unwrap();
        assert!(!adopted.publish);
        assert!(load_intent().is_none());
    }

    #[test]
    fn with_no_relay_copy_a_held_change_is_published_as_is() {
        let (_tmp, _guard) = init_test_db();
        set_streamer_notif("hide_all").unwrap();
        let adopted = adopt_settings(None).unwrap();
        assert!(adopted.publish);
        assert_eq!(load_settings().streamer.notif, "hide_all");
    }

    #[test]
    fn with_nothing_held_hydration_publishes_nothing() {
        let (_tmp, _guard) = init_test_db();
        assert!(!adopt_settings(None).unwrap().publish);
        assert!(!adopt_settings(Some(&copy(r#"{"v":1,"advanced":true}"#, 100))).unwrap().publish);
        assert!(load_settings().advanced);
    }

    #[test]
    fn a_change_made_while_the_publish_is_pending_rides_the_intent() {
        let (_tmp, _guard) = init_test_db();
        set_streamer_on(true).unwrap();
        adopt_settings(Some(&copy(r#"{"v":1}"#, 100))).unwrap();
        set_streamer_notif("hide_content").unwrap();
        // A relay copy without it, after a failed publish and a restart.
        let adopted = adopt_settings(Some(&copy(r#"{"v":1}"#, 100))).unwrap();
        assert!(adopted.publish);
        assert_eq!(load_settings().streamer.notif, "hide_content");
        assert!(load_settings().streamer.on);
    }

    #[test]
    fn a_go_live_after_hydration_outlasts_a_failed_publish() {
        let (_tmp, _guard) = init_test_db();
        adopt_settings(Some(&copy(r#"{"v":1}"#, 100))).unwrap();
        set_streamer_on(true).unwrap();
        // The publish never landed; the next boot reads the old copy back.
        let adopted = adopt_settings(Some(&copy(r#"{"v":1}"#, 100))).unwrap();
        assert!(adopted.publish, "the go-live is published again");
        assert!(load_settings().streamer.on, "and is not undone meanwhile");
    }

    #[test]
    fn an_older_copy_never_rolls_the_settings_back() {
        let (_tmp, _guard) = init_test_db();
        let on = r#"{"v":1,"streamer":{"on":true,"seed":"ab","notif":"hide_all"}}"#;
        adopt_settings(Some(&copy(on, 200))).unwrap();
        let off = r#"{"v":1,"streamer":{"on":false,"seed":"ab","notif":"none"}}"#;
        let late = adopt_settings(Some(&copy(off, 150))).unwrap();
        assert!(late.stale && late.json.is_none() && !late.publish);
        let held = load_settings();
        assert!(held.streamer.on);
        assert_eq!(held.streamer.notif, "hide_all");
        // A sibling's genuinely newer change still lands.
        assert!(adopt_settings(Some(&copy(off, 201))).unwrap().json.is_some());
        assert!(!load_settings().streamer.on);
    }

    #[test]
    fn publishes_inside_one_second_are_signed_in_order() {
        let (_tmp, _guard) = init_test_db();
        adopt_settings(Some(&copy(r#"{"v":1}"#, 1_000))).unwrap();
        set_streamer_on(true).unwrap();
        let (first, a) = claim_publish(1_000);
        set_streamer_on(false).unwrap();
        let (_, b) = claim_publish(1_000);
        set_streamer_on(true).unwrap();
        let (last, c) = claim_publish(1_000);
        assert!(a > 1_000 && b > a && c > b, "{a} {b} {c}");

        // The acks land in any order; only the one matching what is held retires the intent.
        settings_published(&first, a);
        assert!(load_intent().is_some(), "the first publish is not what is held now");
        settings_published(&last, c);
        assert!(load_intent().is_none());

        // The echo of the middle publish arrives last and changes nothing.
        let off = SyncedSettings::from_json(&last);
        let mut off = off.clone();
        off.streamer.on = false;
        let echo = adopt_settings(Some(&copy(&off.to_json(), b))).unwrap();
        assert!(echo.stale);
        assert!(load_settings().streamer.on, "still live after the late echo");

        // A restart re-reads an older relay copy: ignored, and hydration republishes ours.
        let reread = adopt_settings(Some(&copy(&first, a))).unwrap();
        assert!(reread.stale);
        assert_eq!(load_settings().to_json(), last);
    }

    #[test]
    fn an_earlier_go_live_echoing_back_keeps_the_latest_seed() {
        let (_tmp, _guard) = init_test_db();
        adopt_settings(Some(&copy(r#"{"v":1}"#, 100))).unwrap();
        set_streamer_on(true).unwrap();
        let (first, a) = claim_publish(100);
        set_streamer_on(false).unwrap();
        let latest = set_streamer_on(true).unwrap().streamer.seed;
        let echo = adopt_settings(Some(&copy(&first, a))).unwrap();
        assert!(echo.publish, "the relays hold an older go-live");
        let held = load_settings().streamer;
        assert!(held.on);
        assert_eq!(held.seed, latest, "the colours on screen now are kept");
    }

    #[test]
    fn advanced_mode_rides_the_intent_too() {
        let (_tmp, _guard) = init_test_db();
        adopt_settings(Some(&copy(r#"{"v":1}"#, 100))).unwrap();
        set_advanced(true).unwrap();
        let adopted = adopt_settings(Some(&copy(r#"{"v":1}"#, 100))).unwrap();
        assert!(adopted.publish);
        assert!(load_settings().advanced);
    }

    #[test]
    fn nickname_order_is_stable_across_a_round_trip() {
        // BTreeMap, so two devices building the same set emit identical bytes —
        // no spurious republish churn from map iteration order.
        let mut a = NicknameMap::default();
        a.set("npub1z", "Zed").unwrap();
        a.set("npub1a", "Ann").unwrap();
        let mut b = NicknameMap::default();
        b.set("npub1a", "Ann").unwrap();
        b.set("npub1z", "Zed").unwrap();
        assert_eq!(a.to_json(), b.to_json(), "insertion order must not change the wire form");
    }
}