vector-core 0.12.0

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
//! Notification levels and mutes, for communities, channels and DMs alike.
//!
//! Two settings per scope, doing different jobs. **Level** decides what rings:
//! every message, only your name, or nothing. **Mute** greys the row, drops its
//! unread weight, and clamps the level to at most `Mentions` — a volume knob,
//! not an off switch, which is why `Nothing` is not a synonym for it.
//!
//! Level resolves down the chain Community → Channel, most specific opinion
//! winning. Mute unions down it: muting a community mutes every channel in it.
//! With no opinion stored anywhere, what the conversation IS picks the level: a
//! DM or a group chat rings for everything, a community only for your name.

use std::collections::HashMap;
use std::sync::{Arc, RwLock};

/// What rings. Ordered loudest first, so the numeric rank orders "quieter".
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(u8)]
pub enum NotifyLevel {
    All = 0,
    Mentions = 1,
    Nothing = 2,
}

impl NotifyLevel {
    pub fn as_u8(self) -> u8 {
        self as u8
    }

    pub fn from_u8(v: u8) -> Option<Self> {
        match v {
            0 => Some(Self::All),
            1 => Some(Self::Mentions),
            2 => Some(Self::Nothing),
            _ => None,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::All => "all",
            Self::Mentions => "mentions",
            Self::Nothing => "nothing",
        }
    }

    pub fn from_label(s: &str) -> Option<Self> {
        match s {
            "all" => Some(Self::All),
            "mentions" => Some(Self::Mentions),
            "nothing" | "none" => Some(Self::Nothing),
            _ => None,
        }
    }

    /// The quieter of the two, which is how a mute clamps a level.
    pub fn quieter_of(self, other: Self) -> Self {
        if self >= other { self } else { other }
    }
}

/// What a message is, loudest first. Resolved once at classification so a
/// suppressed @everyone is `Normal` everywhere downstream: notification,
/// ping badge and muted-row count alike.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MessageClass {
    Everyone,
    Mention,
    Normal,
}

/// Whether a message of this class rings at this level.
pub fn passes(level: NotifyLevel, class: MessageClass) -> bool {
    match level {
        NotifyLevel::All => true,
        NotifyLevel::Mentions => !matches!(class, MessageClass::Normal),
        NotifyLevel::Nothing => false,
    }
}

/// `mute_until` sentinel for a mute with no end.
pub const MUTE_FOREVER: i64 = -1;
/// `mute_until` sentinel for "not muted".
pub const MUTE_OFF: i64 = 0;

pub fn is_muted_at(mute_until: i64, now_ms: i64) -> bool {
    mute_until == MUTE_FOREVER || mute_until > now_ms
}

pub fn now_ms() -> i64 {
    crate::clock::now_ms() as i64
}

/// One scope's stored settings. `None` means inherit; `suppress_everyone` is
/// only ever set at community scope.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ScopePrefs {
    pub level: Option<NotifyLevel>,
    pub mute_until: i64,
    pub suppress_everyone: Option<bool>,
}

impl ScopePrefs {
    pub fn is_default(&self) -> bool {
        self.level.is_none() && self.mute_until == MUTE_OFF && self.suppress_everyone.is_none()
    }
    pub fn muted_at(&self, now_ms: i64) -> bool {
        is_muted_at(self.mute_until, now_ms)
    }
}

/// A scope's settings after the chain has been walked.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Resolved {
    /// The level in force before the mute clamp, which is what a menu ticks.
    pub level: NotifyLevel,
    pub muted: bool,
    /// The level after the clamp, which is what actually rings and badges.
    pub ring: NotifyLevel,
}

// ============================================================================
// Per-account cache
// ============================================================================

#[derive(Default)]
struct Store {
    loaded: bool,
    scopes: HashMap<String, ScopePrefs>,
    /// Channel ids their community still lists. A tombstoned channel keeps its
    /// chat row and its history, so "has a `community_id`" is not the same
    /// question as "has a row you can open and clear".
    live_channels: Option<std::collections::HashSet<[u8; 32]>>,
    /// Concord groups that are communities rather than group chats: more than one
    /// channel, or a live invite link anyone can join by.
    communities: Option<std::collections::HashSet<[u8; 32]>>,
}

/// Whether `id` names a member of `set`, which holds ids decoded from canonical hex.
fn holds(set: &std::collections::HashSet<[u8; 32]>, id: &str) -> bool {
    crate::community::id32_from_hex(id).is_some_and(|b| set.contains(&b))
}

struct NotifyStore;

fn store() -> Arc<RwLock<Store>> {
    crate::db::current_session().scoped::<NotifyStore, _>()
}

/// Read the table into memory. Called once when a database is opened, because
/// every badge recount resolves every chat and a lazy load would put a SQLite
/// round trip on that path.
///
/// A failed read leaves the cache unloaded rather than latching an empty map,
/// and [`is_loaded`] is what tells a writer not to act on the emptiness.
pub fn warm() {
    let cell = store();
    if cell.read().map(|g| g.loaded).unwrap_or(false) {
        return;
    }
    let rows = match crate::db::notify::load_all() {
        Ok(rows) => rows,
        Err(_) => return,
    };
    if let Ok(mut g) = cell.write() {
        g.scopes = rows;
        g.loaded = true;
    };
}

/// Whether the table has actually been read. An unloaded cache answers
/// "default" for every scope, which is indistinguishable from "nothing is
/// stored" — so anything that WRITES state derived from it must check this
/// first, the same rule `synced_prefs::is_hydrated` applies to publishing.
pub fn is_loaded() -> bool {
    store().read().map(|g| g.loaded).unwrap_or(false)
}

/// Drop the cache so the next warm re-reads the table.
pub fn invalidate() {
    if let Ok(mut g) = store().write() {
        g.loaded = false;
        g.scopes.clear();
        g.live_channels = None;
        g.communities = None;
    }
}

/// Forget what was read off the communities: a channel set or an invite-link
/// registry was rewritten, which can change both what is listed and whether a
/// group is a group chat or a community.
pub fn invalidate_communities() {
    if let Ok(mut g) = store().write() {
        g.live_channels = None;
        g.communities = None;
    }
}

/// Whether `community_id` is a community rather than a group chat. A group chat
/// is one channel behind no invite link; anything bigger or open to strangers
/// is a community, and a busy one can't ring for every message.
pub fn is_community(community_id: &str) -> bool {
    let cell = store();
    if let Ok(g) = cell.read() {
        if let Some(set) = g.communities.as_ref() {
            return holds(set, community_id);
        }
    }
    // Unknown keeps the louder default: a missed ping costs more than an extra one.
    let ids = match crate::db::community::community_ids_beyond_group_chat() {
        Ok(ids) => ids,
        Err(_) => return false,
    };
    let found = holds(&ids, community_id);
    if let Ok(mut g) = cell.write() {
        g.communities = Some(ids);
    }
    found
}

/// The level a scope starts at when nothing on its chain says otherwise.
/// `group_id` is the Concord group the scope belongs to (or is), if any.
pub fn default_level(group_id: Option<&str>) -> NotifyLevel {
    if group_id.is_some_and(is_community) { NotifyLevel::Mentions } else { NotifyLevel::All }
}

/// Whether `channel_id` is one its community still lists. A channel nobody
/// lists has no row to open, so its unread can never be seen or cleared.
pub fn channel_is_listed(channel_id: &str) -> bool {
    let cell = store();
    if let Ok(g) = cell.read() {
        if let Some(set) = g.live_channels.as_ref() {
            return holds(set, channel_id);
        }
    }
    // Unknown beats silently dropping a room's unread.
    let ids: std::collections::HashSet<[u8; 32]> = match crate::db::notify::live_channel_ids() {
        Ok(ids) => ids.iter().filter_map(|id| crate::community::id32_from_hex(id)).collect(),
        Err(_) => return true,
    };
    let listed = holds(&ids, channel_id);
    if let Ok(mut g) = cell.write() {
        g.live_channels = Some(ids);
    }
    listed
}

pub fn prefs(scope_id: &str) -> ScopePrefs {
    store()
        .read()
        .ok()
        .and_then(|g| g.scopes.get(scope_id).copied())
        .unwrap_or_default()
}

pub fn all_prefs() -> HashMap<String, ScopePrefs> {
    store().read().map(|g| g.scopes.clone()).unwrap_or_default()
}

/// Write a scope through to the database and the cache.
pub fn set_prefs(scope_id: &str, next: ScopePrefs) -> Result<(), String> {
    warm();
    crate::db::notify::save(scope_id, &next)?;
    if let Ok(mut g) = store().write() {
        if next.is_default() {
            g.scopes.remove(scope_id);
        } else {
            g.scopes.insert(scope_id.to_string(), next);
        }
    }
    // A muted contact's pushes are held at the pusher: iOS can't drop one once it arrives.
    crate::push::controls_changed();
    Ok(())
}

pub fn set_level(scope_id: &str, level: Option<NotifyLevel>) -> Result<(), String> {
    let mut next = prefs(scope_id);
    next.level = level;
    set_prefs(scope_id, next)
}

pub fn set_mute(scope_id: &str, mute_until: i64) -> Result<(), String> {
    let mut next = prefs(scope_id);
    next.mute_until = mute_until;
    set_prefs(scope_id, next)
}

pub fn set_suppress_everyone(scope_id: &str, suppress: Option<bool>) -> Result<(), String> {
    let mut next = prefs(scope_id);
    next.suppress_everyone = suppress;
    set_prefs(scope_id, next)
}

// ============================================================================
// Resolution
// ============================================================================

/// Whether an authorized @everyone may ping, for a community. Two levers: the
/// App Settings kill switch, which wins outright, and the community's own
/// choice under it. A channel has no say, deliberately.
///
/// Separate from [`resolve`] because it reads a setting from the database and
/// `resolve` runs once per chat on every badge recount.
pub fn everyone_allowed(community_id: Option<&str>) -> bool {
    let globally_muted = crate::db::settings::get_sql_setting("notif_mute_everyone".to_string())
        .ok()
        .flatten()
        .is_some_and(|v| v == "true");
    if globally_muted {
        return false;
    }
    !community_id.is_some_and(|cid| prefs(cid).suppress_everyone.unwrap_or(false))
}

/// Walk the chain for one scope. `community_id` is the channel's community, or
/// `None` for a DM or for a community resolving itself.
pub fn resolve(scope_id: &str, community_id: Option<&str>, now_ms: i64) -> Resolved {
    let own = prefs(scope_id);
    let parent = community_id
        .filter(|cid| *cid != scope_id)
        .map(prefs)
        .unwrap_or_default();
    let fallback = default_level(Some(community_id.unwrap_or(scope_id)));
    resolve_from(own, parent, fallback, now_ms)
}

/// The chain arithmetic on its own: level takes the most specific opinion,
/// then `fallback`; mute takes either, and the mute clamps the level it hands back.
pub fn resolve_from(own: ScopePrefs, parent: ScopePrefs, fallback: NotifyLevel, now_ms: i64) -> Resolved {
    let level = own.level.or(parent.level).unwrap_or(fallback);
    let muted = own.muted_at(now_ms) || parent.muted_at(now_ms);
    let ring = level.quieter_of(if muted { NotifyLevel::Mentions } else { NotifyLevel::All });
    Resolved { level, muted, ring }
}

/// The community a chat belongs to, or `None` for a DM.
fn community_of(chat: &crate::chat::Chat) -> Option<&str> {
    chat.metadata.community_id()
}

/// A chat's settings, with its stored `muted` flag folded in. That flag is the
/// mirror this module keeps for the paths that predate it, and the landing
/// point for a mute arriving over the older `vector/mutes` projection, so it
/// counts as a mute in its own right rather than being assumed to agree.
pub fn resolve_chat(chat: &crate::chat::Chat) -> Resolved {
    let mut resolved = resolve(&chat.id, community_of(chat), now_ms());
    if chat.muted && !resolved.muted {
        resolved.muted = true;
        resolved.ring = resolved.level.quieter_of(NotifyLevel::Mentions);
    }
    resolved
}

/// What a chat's row should badge with: full unread at `All`, pings at
/// `Mentions`, nothing at `Nothing`.
pub fn ring_for_chat(chat: &crate::chat::Chat) -> NotifyLevel {
    resolve_chat(chat).ring
}

pub fn muted_for_chat(chat: &crate::chat::Chat) -> bool {
    resolve_chat(chat).muted
}

/// Whether a chat's COMMUNITY is itself silenced, rather than this one room inside it.
/// A surface that stands for the whole space must not grey because one channel is quiet.
pub fn community_muted_for_chat(chat: &crate::chat::Chat) -> bool {
    community_of(chat).is_some_and(|id| prefs(id).muted_at(now_ms()))
}

/// The predicate the older `vector/mutes` projection is both WRITTEN and READ
/// with. Publishing one shape and applying another is how an inherited mute
/// ratchets into a permanent per-channel one.
///
/// Chain-resolved, so a client that predates levels silences the same rooms
/// this one does. Indefinite-only, because that list cannot carry a deadline:
/// a timed mute in it comes back as a mute with no end, and the expiry that
/// should have corrected it happens at boot, where publishing is not allowed.
pub fn in_legacy_mute_list(own: ScopePrefs, parent: ScopePrefs, now_ms: i64) -> bool {
    (own.muted_at(now_ms) || parent.muted_at(now_ms))
        && (own.mute_until == MUTE_FOREVER || parent.mute_until == MUTE_FOREVER)
}

/// [`in_legacy_mute_list`] for a chat, stored flag folded in like [`resolve_chat`].
pub fn legacy_muted_for_chat(chat: &crate::chat::Chat) -> bool {
    let own = prefs(&chat.id);
    let parent = community_of(chat)
        .filter(|cid| *cid != chat.id)
        .map(prefs)
        .unwrap_or_default();
    in_legacy_mute_list(own, parent, now_ms())
        // A mute that only exists as the legacy mirror is indefinite by nature.
        || (chat.muted && !own.muted_at(now_ms()) && !parent.muted_at(now_ms()))
}

/// Whether an @everyone in this chat still counts as someone calling your name.
///
/// Reads the community's own setting only, never the App Settings switch: this
/// runs once per chat on every serialization, and that switch lives in the
/// database. It has never affected badge counts anyway, only delivery.
pub fn everyone_pings_for_chat(chat: &crate::chat::Chat) -> bool {
    !community_of(chat)
        .map(prefs)
        .and_then(|p| p.suppress_everyone)
        .unwrap_or(false)
}

// ============================================================================
// Expiry
// ============================================================================

/// The soonest mute expiry still ahead of `now_ms`, for arming one timer
/// rather than one per mute.
pub fn next_expiry(now_ms: i64) -> Option<i64> {
    store().read().ok().and_then(|g| {
        g.scopes
            .values()
            .map(|p| p.mute_until)
            .filter(|&u| u > now_ms)
            .min()
    })
}

/// Clear every mute whose timer has run out, returning the scopes that just
/// lapsed. Expiry is a write rather than a read: the callers of `muted` read a
/// cached boolean, and making them all consult the clock instead would be the
/// wrong fix.
pub fn sweep_expired(now_ms: i64) -> Vec<String> {
    warm();
    let cell = store();
    let lapsed: Vec<String> = match cell.read() {
        Ok(g) => g
            .scopes
            .iter()
            .filter(|(_, p)| p.mute_until > MUTE_OFF && p.mute_until <= now_ms)
            .map(|(id, _)| id.clone())
            .collect(),
        Err(_) => return Vec::new(),
    };
    if lapsed.is_empty() {
        return lapsed;
    }
    if crate::db::notify::clear_expired_mutes(now_ms).is_err() {
        return Vec::new();
    }
    if let Ok(mut g) = cell.write() {
        for id in &lapsed {
            let drop_row = match g.scopes.get_mut(id) {
                Some(p) => {
                    p.mute_until = MUTE_OFF;
                    p.is_default()
                }
                None => false,
            };
            if drop_row {
                g.scopes.remove(id);
            }
        }
    }
    lapsed
}

// ============================================================================
// Cross-device projection
// ============================================================================

impl ScopePrefs {
    pub fn to_wire(self) -> crate::synced_prefs::NotifyEntry {
        crate::synced_prefs::NotifyEntry {
            level: self.level.map(|l| l.as_str().to_string()),
            mute_until: self.mute_until,
            suppress_everyone: self.suppress_everyone,
        }
    }

    pub fn from_wire(entry: &crate::synced_prefs::NotifyEntry) -> Self {
        Self {
            level: entry.level.as_deref().and_then(NotifyLevel::from_label),
            mute_until: entry.mute_until,
            suppress_everyone: entry.suppress_everyone,
        }
    }
}

/// This device's table as the publishable projection.
pub fn to_wire() -> crate::synced_prefs::NotifyMap {
    let mut map = crate::synced_prefs::NotifyMap::default();
    for (scope_id, prefs) in all_prefs() {
        let _ = map.set(&scope_id, prefs.to_wire());
    }
    map
}

/// Adopt a sibling device's list wholesale. Returns the scopes whose settings
/// actually moved, so the caller only has to repaint those.
pub fn apply_wire(map: &crate::synced_prefs::NotifyMap) -> Result<Vec<String>, String> {
    // Adopting a list REPLACES the table, so an unloaded cache would compare the
    // incoming set against an emptiness that only means "could not read" and
    // report nothing moved.
    warm();
    if !is_loaded() {
        return Err("notification preferences not read yet".to_string());
    }
    let next: HashMap<String, ScopePrefs> = map
        .scopes
        .iter()
        .map(|(id, entry)| (id.clone(), ScopePrefs::from_wire(entry)))
        .filter(|(_, p)| !p.is_default())
        .collect();
    let before = all_prefs();
    crate::db::notify::replace_all(&next)?;
    if let Ok(mut g) = store().write() {
        g.scopes = next.clone();
        g.loaded = true;
    }
    let mut moved: Vec<String> = next
        .iter()
        .filter(|(id, p)| before.get(*id) != Some(p))
        .map(|(id, _)| id.clone())
        .collect();
    crate::push::controls_changed();
    moved.extend(before.keys().filter(|id| !next.contains_key(*id)).cloned());
    Ok(moved)
}

/// How much of a message a system notification reveals: the account's
/// `notif_content_privacy` setting, read at notify time.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContentPrivacy {
    /// Sender and message.
    Full,
    /// Who wrote, not what.
    HideContent,
    /// What was written, not who.
    HideSender,
    /// Only that something arrived.
    HideAll,
}

impl ContentPrivacy {
    /// What a notification may reveal right now: the account's setting, joined with
    /// the streaming overlay while Streamer Mode is on.
    pub fn load() -> Self {
        Self::effective(Self::load_base(), &crate::synced_prefs::load_settings().streamer)
    }

    /// The account's own setting, without the streaming overlay.
    pub fn load_base() -> Self {
        Self::parse(crate::db::get_sql_setting("notif_content_privacy".to_string()).ok().flatten().as_deref())
    }

    /// Joined before applying: applying two levels in turn does not hide what their union does.
    pub fn effective(base: Self, streamer: &crate::synced_prefs::StreamerSettings) -> Self {
        if streamer.on {
            base.join(Self::parse(Some(&streamer.notif)))
        } else {
            base
        }
    }

    /// Hides whatever either one hides.
    pub fn join(self, other: Self) -> Self {
        Self::from_bits(self.bits() | other.bits())
    }

    fn bits(self) -> u8 {
        match self {
            Self::Full => 0b00,
            Self::HideContent => 0b01,
            Self::HideSender => 0b10,
            Self::HideAll => 0b11,
        }
    }

    fn from_bits(bits: u8) -> Self {
        match bits & 0b11 {
            0b00 => Self::Full,
            0b01 => Self::HideContent,
            0b10 => Self::HideSender,
            _ => Self::HideAll,
        }
    }

    /// The stored spelling, which the web service worker also reads.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Full => "full",
            Self::HideContent => "hide_content",
            Self::HideSender => "hide_sender",
            Self::HideAll => "hide_all",
        }
    }

    fn parse(value: Option<&str>) -> Self {
        match value {
            Some("hide_content") => Self::HideContent,
            Some("hide_sender") => Self::HideSender,
            Some("hide_all") => Self::HideAll,
            _ => Self::Full,
        }
    }
}

/// Stands in for every name Streamer Mode hides. Fixed length, so it says nothing about the name.
pub const STREAM_MASK: &str = "•••••";

/// Who Streamer Mode hides. Read once per notification, outside any state lock.
#[derive(Debug, Clone, Default)]
pub struct StreamGate {
    on: bool,
    me: Option<String>,
}

impl StreamGate {
    pub fn load() -> Self {
        if !crate::synced_prefs::load_settings().streamer.on {
            return Self::default();
        }
        // The background service on Android binds an account without an identity.
        let me = crate::state::my_public_key()
            .and_then(|pk| nostr_sdk::prelude::ToBech32::to_bech32(&pk).ok())
            .or_else(|| crate::db::get_current_account().ok());
        Self { on: true, me }
    }

    pub fn new(on: bool, me: Option<String>) -> Self {
        Self { on, me }
    }

    pub fn is_on(&self) -> bool {
        self.on
    }

    /// Everyone but the active account is hidden unless they opted in. Someone not
    /// fetched yet cannot have, so they are hidden too.
    pub fn hides(&self, npub: &str, profile: Option<&crate::profile::Profile>) -> bool {
        if !self.on || self.me.as_deref() == Some(npub) {
            return false;
        }
        !profile.is_some_and(|p| p.flags.is_mine() || p.flags.is_stream_consent())
    }
}

/// The name and avatar a notification shows for someone.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Sender {
    pub name: String,
    pub avatar: Option<String>,
}

/// Nickname, then name, then display name, else `fallback`; masked with no avatar
/// when the gate hides them. Every platform's notification names a sender through this.
pub fn sender(state: &crate::state::ChatState, gate: &StreamGate, npub: &str, fallback: &str) -> Sender {
    let profile = state.get_profile(npub);
    if gate.hides(npub, profile) {
        return Sender { name: STREAM_MASK.to_string(), avatar: None };
    }
    let Some(p) = profile else {
        return Sender { name: fallback.to_string(), avatar: None };
    };
    Sender {
        name: display_name(p).unwrap_or(fallback).to_string(),
        avatar: p.has_avatar_cached().then(|| p.avatar_cached().into_owned()),
    }
}

/// [`sender`] inside a community: the `nickname` they go by there, unless you named them yourself.
pub fn sender_in(state: &crate::state::ChatState, gate: &StreamGate, npub: &str, fallback: &str, nickname: Option<String>) -> Sender {
    let shown = sender(state, gate, npub, fallback);
    let profile = state.get_profile(npub);
    match nickname {
        Some(name) if !gate.hides(npub, profile) && profile.is_none_or(|p| p.nickname().is_empty()) => Sender { name, ..shown },
        _ => shown,
    }
}

fn display_name(p: &crate::profile::Profile) -> Option<&str> {
    [p.nickname(), p.name(), p.display_name()].into_iter().find(|n| !n.is_empty())
}

/// `content` without terminal escape sequences: an ```ansi block's colour codes are
/// styling, and a notification has no way to show them.
pub fn strip_ansi(content: &str) -> std::borrow::Cow<'_, str> {
    if !content.contains('\x1b') {
        return std::borrow::Cow::Borrowed(content);
    }
    let mut out = String::with_capacity(content.len());
    let mut chars = content.chars().peekable();
    while let Some(c) = chars.next() {
        if c != '\x1b' {
            out.push(c);
            continue;
        }
        match chars.peek() {
            // CSI: parameter and intermediate bytes, ended by one final byte.
            Some('[') => {
                chars.next();
                while let Some(&n) = chars.peek() {
                    if !('\x20'..='\x3f').contains(&n) {
                        if ('\x40'..='\x7e').contains(&n) {
                            chars.next();
                        }
                        break;
                    }
                    chars.next();
                }
            }
            Some(n) if ('\x40'..='\x5f').contains(n) => {
                chars.next();
            }
            _ => {}
        }
    }
    std::borrow::Cow::Owned(out)
}

/// `content` with each mention (`@npub1…`, `nostr:npub1…`, a bare npub, or the same
/// forms of an nprofile) read as `@name`. An unknown npub stays as written, except while streaming, where it and
/// anyone hidden read as `@•••••`.
pub fn resolve_mentions(content: &str, state: &crate::state::ChatState, gate: &StreamGate) -> String {
    scan_mentions(content, |npub| {
        let profile = state.get_profile(npub);
        if gate.hides(npub, profile) {
            return Some(STREAM_MASK.to_string());
        }
        profile.and_then(display_name).map(str::to_string)
    })
}

/// The scanner behind [`resolve_mentions`]. `lookup` names a bare npub, or `None`
/// to leave its token as written. An nprofile is looked up by the npub it encodes.
///
/// Anchors on byte offsets only inside the entity, which is always ASCII, so the
/// text around it (emoji included) is copied whole.
pub fn scan_mentions<F: Fn(&str) -> Option<String>>(content: &str, lookup: F) -> String {
    const NPUB_LEN: usize = 63;
    const BECH32: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";

    let bytes = content.as_bytes();
    let len = bytes.len();
    let mut result = String::with_capacity(len);
    let mut cursor = 0;

    let mut i = 0;
    while i + NPUB_LEN <= len {
        if bytes[i..].starts_with(b"nprofile1") {
            let end = i + 9 + bytes[i + 9..].iter().take_while(|b| BECH32.contains(&b.to_ascii_lowercase())).count();
            let npub = <nostr_sdk::prelude::Nip19Profile as nostr_sdk::prelude::FromBech32>::from_bech32(&content[i..end])
                .ok()
                .and_then(|p| nostr_sdk::prelude::ToBech32::to_bech32(&p.public_key).ok());
            if let Some(name) = npub.as_deref().and_then(&lookup) {
                let mstart = mention_start(bytes, i);
                result.push_str(&content[cursor..mstart]);
                result.push('@');
                result.push_str(&name);
                cursor = end;
            }
            i = end;
            continue;
        }
        let is_npub = &bytes[i..i + 5] == b"npub1"
            && bytes[i + 5..i + NPUB_LEN]
                .iter()
                .all(|b| BECH32.contains(&b.to_ascii_lowercase()));
        if is_npub {
            let npub_end = i + NPUB_LEN;
            if let Some(name) = lookup(&content[i..npub_end]) {
                let mstart = mention_start(bytes, i);
                result.push_str(&content[cursor..mstart]);
                result.push('@');
                result.push_str(&name);
                cursor = npub_end;
            }
            i = npub_end;
            continue;
        }
        i += 1;
    }

    result.push_str(&content[cursor..]);
    result
}

/// Where the mention token at `i` starts: its `@` or `nostr:` prefix is swallowed, so the
/// whole token collapses to one @name.
fn mention_start(bytes: &[u8], i: usize) -> usize {
    if i >= 1 && bytes[i - 1] == b'@' {
        i - 1
    } else if i >= 6 && &bytes[i - 6..i] == b"nostr:" {
        i - 6
    } else {
        i
    }
}

/// What a notification shows. Every platform passes its notification through
/// [`Preview::apply`], so the setting means the same thing everywhere.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Preview {
    pub title: String,
    pub body: String,
    pub sender: Option<String>,
    pub avatar: Option<String>,
    /// Where a community message was posted; None in a DM.
    pub group: Option<String>,
    pub group_avatar: Option<String>,
}

impl Preview {
    /// Rewrite what is shown. Idempotent: a notification may pass through twice.
    pub fn apply(&mut self, privacy: ContentPrivacy) {
        match privacy {
            ContentPrivacy::Full => {}
            ContentPrivacy::HideContent => {
                self.body = if self.group.is_some() { "Sent a message" } else { "Sent you a message" }.to_string();
            }
            ContentPrivacy::HideSender => {
                self.title = self.group.clone().unwrap_or_else(|| "New message".to_string());
                self.sender = None;
                self.avatar = None;
            }
            ContentPrivacy::HideAll => {
                *self = Preview {
                    title: "Vector".to_string(),
                    body: "You received a message".to_string(),
                    ..Default::default()
                };
            }
        }
    }
}

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

    #[test]
    fn strip_ansi_drops_escape_sequences() {
        assert_eq!(strip_ansi("plain"), "plain");
        assert_eq!(strip_ansi("\x1b[2;31mred\x1b[0m and \x1b[38;2;88;101;242mblurple\x1b[0m"), "red and blurple");
        assert_eq!(strip_ansi("a\x1b[1;4mb\x1b[mc"), "abc");
        assert_eq!(strip_ansi("lone \x1b and \x1bM up, cut \x1b[31"), "lone  and  up, cut ");
        assert_eq!(strip_ansi("\x1b[31m\u{1F600}\x1b[\u{e9}"), "\u{1F600}\u{e9}");
    }

    fn dm() -> Preview {
        Preview {
            title: "Alice".into(),
            body: "see you at 8".into(),
            sender: Some("Alice".into()),
            avatar: Some("/a.png".into()),
            ..Default::default()
        }
    }

    fn channel() -> Preview {
        Preview {
            title: "Alice - Rust Club".into(),
            body: "see you at 8".into(),
            sender: Some("Alice".into()),
            avatar: Some("/a.png".into()),
            group: Some("Rust Club".into()),
            group_avatar: Some("/club.png".into()),
        }
    }

    #[test]
    fn content_privacy_reads_every_stored_value() {
        assert_eq!(ContentPrivacy::parse(None), ContentPrivacy::Full);
        assert_eq!(ContentPrivacy::parse(Some("full")), ContentPrivacy::Full);
        assert_eq!(ContentPrivacy::parse(Some("hide_content")), ContentPrivacy::HideContent);
        assert_eq!(ContentPrivacy::parse(Some("hide_sender")), ContentPrivacy::HideSender);
        assert_eq!(ContentPrivacy::parse(Some("hide_all")), ContentPrivacy::HideAll);
        assert_eq!(ContentPrivacy::parse(Some("true")), ContentPrivacy::Full);
    }

    #[test]
    fn hiding_the_sender_keeps_the_message_and_the_community() {
        let mut p = dm();
        p.apply(ContentPrivacy::HideSender);
        assert_eq!((p.title.as_str(), p.body.as_str()), ("New message", "see you at 8"));
        assert_eq!((p.sender, p.avatar), (None, None));

        let mut p = channel();
        p.apply(ContentPrivacy::HideSender);
        assert_eq!((p.title.as_str(), p.body.as_str()), ("Rust Club", "see you at 8"));
        assert_eq!((p.sender, p.avatar), (None, None));
        assert_eq!(p.group_avatar.as_deref(), Some("/club.png"));
    }

    #[test]
    fn hiding_the_message_keeps_the_sender() {
        let mut p = dm();
        p.apply(ContentPrivacy::HideContent);
        assert_eq!((p.title.as_str(), p.body.as_str()), ("Alice", "Sent you a message"));
        assert_eq!(p.avatar.as_deref(), Some("/a.png"));

        let mut p = channel();
        p.apply(ContentPrivacy::HideContent);
        assert_eq!(p.body, "Sent a message");
        assert_eq!(p.sender.as_deref(), Some("Alice"));
    }

    #[test]
    fn hiding_everything_leaves_nothing_identifying() {
        for mut p in [dm(), channel()] {
            p.apply(ContentPrivacy::HideAll);
            assert_eq!(p, Preview { title: "Vector".into(), body: "You received a message".into(), ..Default::default() });
        }
    }

    #[test]
    fn content_privacy_is_idempotent() {
        for privacy in [ContentPrivacy::Full, ContentPrivacy::HideContent, ContentPrivacy::HideSender, ContentPrivacy::HideAll] {
            for base in [dm(), channel()] {
                let mut once = base.clone();
                once.apply(privacy);
                let mut twice = once.clone();
                twice.apply(privacy);
                assert_eq!(once, twice, "{privacy:?}");
            }
        }
    }

    const ALL_PRIVACY: [ContentPrivacy; 4] =
        [ContentPrivacy::Full, ContentPrivacy::HideContent, ContentPrivacy::HideSender, ContentPrivacy::HideAll];

    #[test]
    fn privacy_joins_as_a_two_bit_union() {
        for x in ALL_PRIVACY {
            assert_eq!(ContentPrivacy::Full.join(x), x, "Full adds nothing to {x:?}");
            assert_eq!(x.join(ContentPrivacy::Full), x);
            assert_eq!(x.join(x), x, "joining {x:?} with itself is idempotent");
            assert_eq!(x.join(ContentPrivacy::HideAll), ContentPrivacy::HideAll);
            for y in ALL_PRIVACY {
                assert_eq!(x.join(y), y.join(x), "{x:?} with {y:?} commutes");
            }
        }
        assert_eq!(ContentPrivacy::HideContent.join(ContentPrivacy::HideSender), ContentPrivacy::HideAll);
    }

    #[test]
    fn joining_first_hides_more_than_applying_twice() {
        let mut twice = channel();
        twice.apply(ContentPrivacy::HideSender);
        twice.apply(ContentPrivacy::HideContent);
        let mut joined = channel();
        joined.apply(ContentPrivacy::HideSender.join(ContentPrivacy::HideContent));
        assert_ne!(twice, joined, "applying in turn leaves the community showing");
        assert_eq!(joined.group, None);
    }

    #[test]
    fn privacy_spelling_round_trips() {
        for x in ALL_PRIVACY {
            assert_eq!(ContentPrivacy::parse(Some(x.as_str())), x);
        }
        assert_eq!(ContentPrivacy::parse(Some("none")), ContentPrivacy::Full, "the overlay's off spelling");
    }

    fn streaming(on: bool, notif: &str) -> crate::synced_prefs::StreamerSettings {
        crate::synced_prefs::StreamerSettings { on, notif: notif.into(), ..Default::default() }
    }

    #[test]
    fn the_overlay_counts_only_while_live() {
        let base = ContentPrivacy::HideContent;
        assert_eq!(ContentPrivacy::effective(base, &streaming(false, "hide_sender")), base);
        assert_eq!(ContentPrivacy::effective(base, &streaming(true, "hide_sender")), ContentPrivacy::HideAll);
        assert_eq!(ContentPrivacy::effective(base, &streaming(true, "none")), base);
        assert_eq!(
            ContentPrivacy::effective(ContentPrivacy::Full, &streaming(true, "hide_content")),
            ContentPrivacy::HideContent
        );
    }

    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();
        use nostr_sdk::prelude::ToBech32;
        let tmp = tempfile::tempdir().unwrap();
        let account = nostr_sdk::prelude::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)
    }

    #[test]
    fn load_reads_the_setting_and_the_overlay() {
        let (_tmp, _guard) = init_test_db();
        use crate::synced_prefs::{save_local_raw, Pref, SyncedSettings};
        crate::db::set_sql_setting("notif_content_privacy".into(), "hide_content".into()).unwrap();
        let mut settings = SyncedSettings::default();
        settings.streamer = streaming(true, "hide_sender");
        save_local_raw(Pref::Settings, &settings.to_json()).unwrap();
        assert_eq!(ContentPrivacy::load_base(), ContentPrivacy::HideContent);
        assert_eq!(ContentPrivacy::load(), ContentPrivacy::HideAll);

        settings.streamer.on = false;
        save_local_raw(Pref::Settings, &settings.to_json()).unwrap();
        assert_eq!(ContentPrivacy::load(), ContentPrivacy::HideContent, "off, the overlay is ignored");
    }

    const ME: &str = "npub1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq";
    const FAN: &str = "npub1pppppppppppppppppppppppppppppppppppppppppppppppppppppppppp";
    const SHY: &str = "npub1zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
    const STRANGER: &str = "npub1rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr";

    fn people() -> crate::state::ChatState {
        let mut state = crate::state::ChatState::new();
        let person = |name: &str, consent: bool| {
            let mut p = crate::profile::Profile::new();
            p.set_name(name);
            p.set_avatar_cached(&format!("/{name}.png"));
            p.flags.set_stream_consent(consent);
            p
        };
        state.insert_or_replace_profile(ME, person("Me", false));
        let mut fan = person("Fan", true);
        fan.set_nickname("Bestie");
        state.insert_or_replace_profile(FAN, fan);
        state.insert_or_replace_profile(SHY, person("Shy", false));
        state
    }

    #[test]
    fn streaming_masks_everyone_but_me_and_those_who_opted_in() {
        let state = people();
        let live = StreamGate::new(true, Some(ME.into()));
        let shown = |npub| sender(&state, &live, npub, "New Message");

        assert_eq!(shown(ME), Sender { name: "Me".into(), avatar: Some("/Me.png".into()) });
        assert_eq!(shown(FAN), Sender { name: "Bestie".into(), avatar: Some("/Fan.png".into()) }, "opted in reads as normal, nickname too");
        for hidden in [SHY, STRANGER] {
            assert_eq!(shown(hidden), Sender { name: STREAM_MASK.into(), avatar: None }, "{hidden}");
        }
        assert_eq!(STREAM_MASK.chars().count(), 5);

        let off = StreamGate::default();
        assert_eq!(sender(&state, &off, SHY, "New Message").name, "Shy");
        assert_eq!(sender(&state, &off, STRANGER, "New Message"), Sender { name: "New Message".into(), avatar: None });
    }

    #[test]
    fn my_own_profile_shows_even_without_an_identity() {
        let mut state = people();
        state.get_profile_mut(SHY).unwrap().flags.set_mine(true);
        let live = StreamGate::new(true, None);
        assert_eq!(sender(&state, &live, SHY, "x").name, "Shy");
        assert_eq!(sender(&state, &live, ME, "x").name, STREAM_MASK, "another local account is hidden");
    }

    #[test]
    fn mentions_are_masked_while_live_and_named_otherwise() {
        let state = people();
        let text = format!("@{SHY} meet nostr:{FAN} and {STRANGER}, from @{ME}");
        let live = StreamGate::new(true, Some(ME.into()));
        assert_eq!(resolve_mentions(&text, &state, &live), "@••••• meet @Bestie and @•••••, from @Me");

        let off = StreamGate::default();
        assert_eq!(
            resolve_mentions(&text, &state, &off),
            format!("@Shy meet @Bestie and {STRANGER}, from @Me"),
            "an unknown npub stays as written when not live"
        );
    }

    #[test]
    fn an_nprofile_mention_reads_as_the_npub_it_encodes() {
        use nostr_sdk::prelude::{Keys, Nip19Profile, RelayUrl, ToBech32};
        let mut state = people();
        let pk = Keys::generate().public_key();
        let npub = pk.to_bech32().unwrap();
        let mut p = crate::profile::Profile::new();
        p.set_name("Hidden");
        state.insert_or_replace_profile(&npub, p);
        let relay = RelayUrl::parse("wss://relay.example.com").unwrap();
        let nprofile = Nip19Profile::new(pk, [relay]).to_bech32().unwrap();

        let live = StreamGate::new(true, Some(ME.into()));
        assert_eq!(resolve_mentions(&format!("ask nostr:{nprofile} now"), &state, &live), "ask @••••• now");
        assert_eq!(resolve_mentions(&format!("ask @{nprofile}"), &state, &StreamGate::default()), "ask @Hidden");
        let stranger = Nip19Profile::new(Keys::generate().public_key(), []).to_bech32().unwrap();
        assert_eq!(resolve_mentions(&format!("hi {stranger}"), &state, &live), "hi @•••••", "unknown is hidden too");
        assert_eq!(scan_mentions("nprofile1qqqq broken", |_| Some("x".into())), "nprofile1qqqq broken");
    }

    #[test]
    fn mention_scanner_reads_every_form() {
        let npub = format!("npub1{}", "q".repeat(58));
        let unknown = format!("npub1{}", "p".repeat(58));
        let known: &str = &npub;
        let lookup = |n: &str| (n == known).then(|| "Alice".to_string());

        assert_eq!(scan_mentions(&format!("hey @{npub}!"), lookup), "hey @Alice!");
        assert_eq!(scan_mentions(&format!("hey nostr:{npub}!"), lookup), "hey @Alice!");
        assert_eq!(scan_mentions(&format!("hey {npub}!"), lookup), "hey @Alice!");
        assert_eq!(scan_mentions(&format!("hi nostr:{unknown}"), lookup), format!("hi nostr:{unknown}"));
        assert_eq!(scan_mentions(&format!("{npub} and nostr:{npub} done"), lookup), "@Alice and @Alice done");
        assert_eq!(scan_mentions("just a normal line 🎉", lookup), "just a normal line 🎉");
    }

    #[test]
    fn mute_clamps_the_level_to_mentions() {
        assert_eq!(NotifyLevel::All.quieter_of(NotifyLevel::Mentions), NotifyLevel::Mentions);
        // Nothing is already quieter than the clamp, so a mute cannot make it louder.
        assert_eq!(NotifyLevel::Nothing.quieter_of(NotifyLevel::Mentions), NotifyLevel::Nothing);
        assert_eq!(NotifyLevel::Mentions.quieter_of(NotifyLevel::All), NotifyLevel::Mentions);
    }

    #[test]
    fn level_decides_which_classes_ring() {
        for class in [MessageClass::Everyone, MessageClass::Mention, MessageClass::Normal] {
            assert!(passes(NotifyLevel::All, class));
            assert!(!passes(NotifyLevel::Nothing, class));
        }
        assert!(passes(NotifyLevel::Mentions, MessageClass::Mention));
        assert!(passes(NotifyLevel::Mentions, MessageClass::Everyone));
        assert!(!passes(NotifyLevel::Mentions, MessageClass::Normal));
    }

    #[test]
    fn mute_sentinels() {
        assert!(is_muted_at(MUTE_FOREVER, 10_000));
        assert!(!is_muted_at(MUTE_OFF, 10_000));
        assert!(is_muted_at(10_001, 10_000));
        assert!(!is_muted_at(10_000, 10_000), "an expiry that has arrived is over");
    }

    #[test]
    fn a_scope_at_every_default_stores_nothing() {
        assert!(ScopePrefs::default().is_default());
        assert!(!ScopePrefs { mute_until: MUTE_FOREVER, ..Default::default() }.is_default());
        assert!(!ScopePrefs { level: Some(NotifyLevel::Nothing), ..Default::default() }.is_default());
    }

    fn at(level: Option<NotifyLevel>, mute_until: i64) -> ScopePrefs {
        ScopePrefs { level, mute_until, suppress_everyone: None }
    }

    #[test]
    fn a_channel_opinion_beats_its_community() {
        let r = resolve_from(at(Some(NotifyLevel::All), 0), at(Some(NotifyLevel::Nothing), 0), NotifyLevel::All, 0);
        assert_eq!(r.level, NotifyLevel::All);
        assert_eq!(r.ring, NotifyLevel::All);
    }

    #[test]
    fn a_channel_with_no_opinion_takes_its_community() {
        let r = resolve_from(at(None, 0), at(Some(NotifyLevel::Mentions), 0), NotifyLevel::All, 0);
        assert_eq!(r.level, NotifyLevel::Mentions);
    }

    #[test]
    fn nothing_stored_anywhere_takes_what_the_conversation_is() {
        let chat = resolve_from(ScopePrefs::default(), ScopePrefs::default(), NotifyLevel::All, 0);
        assert_eq!(chat.level, NotifyLevel::All);
        assert!(!chat.muted);
        let community = resolve_from(ScopePrefs::default(), ScopePrefs::default(), NotifyLevel::Mentions, 0);
        assert_eq!(community.ring, NotifyLevel::Mentions);
    }

    #[test]
    fn any_stored_opinion_beats_the_default() {
        let own = resolve_from(at(Some(NotifyLevel::All), 0), ScopePrefs::default(), NotifyLevel::Mentions, 0);
        assert_eq!(own.level, NotifyLevel::All);
        let inherited = resolve_from(ScopePrefs::default(), at(Some(NotifyLevel::All), 0), NotifyLevel::Mentions, 0);
        assert_eq!(inherited.level, NotifyLevel::All, "a community set to All keeps its channels loud");
    }

    #[test]
    fn a_community_mute_reaches_a_channel_that_set_none_itself() {
        // Mute unions downward, unlike level: the channel cannot opt out of it.
        let r = resolve_from(at(Some(NotifyLevel::All), MUTE_OFF), at(None, MUTE_FOREVER), NotifyLevel::All, 0);
        assert!(r.muted);
        assert_eq!(r.level, NotifyLevel::All, "the level underneath is untouched");
        assert_eq!(r.ring, NotifyLevel::Mentions, "but the mute clamps what rings");
    }

    #[test]
    fn a_mute_never_makes_a_quiet_channel_louder() {
        let r = resolve_from(at(Some(NotifyLevel::Nothing), MUTE_FOREVER), ScopePrefs::default(), NotifyLevel::All, 0);
        assert_eq!(r.ring, NotifyLevel::Nothing);
    }

    #[test]
    fn a_lapsed_timer_stops_muting_without_anything_being_written() {
        let prefs = at(None, 5_000);
        assert!(resolve_from(prefs, ScopePrefs::default(), NotifyLevel::All, 4_999).muted);
        assert!(!resolve_from(prefs, ScopePrefs::default(), NotifyLevel::All, 5_000).muted);
    }

    #[test]
    fn the_legacy_list_names_a_channel_its_community_muted() {
        // Chain-resolved, so a client that predates levels goes quiet in the same rooms.
        let channel = in_legacy_mute_list(ScopePrefs::default(), at(None, MUTE_FOREVER), 0);
        assert!(channel);
    }

    #[test]
    fn publishing_and_applying_the_legacy_list_agree() {
        // The bug this guards: publish with one predicate and apply with another, and
        // an inherited mute round-trips into a permanent per-channel one.
        let community = at(None, MUTE_FOREVER);
        let channel = ScopePrefs::default();
        let published = in_legacy_mute_list(channel, community, 0);
        let on_apply = in_legacy_mute_list(channel, community, 0);
        assert_eq!(published, on_apply, "the applier must read what the publisher wrote");
        assert!(published);
    }

    #[test]
    fn a_timed_mute_never_enters_the_legacy_list() {
        // It carries no deadline, so anything in it comes back indefinite, and the
        // expiry that should correct that happens at boot where publishing is barred.
        assert!(!in_legacy_mute_list(at(None, 9_000), ScopePrefs::default(), 0));
        assert!(!in_legacy_mute_list(ScopePrefs::default(), at(None, 9_000), 0));
        assert!(in_legacy_mute_list(at(None, MUTE_FOREVER), ScopePrefs::default(), 0));
    }

    #[test]
    fn a_lapsed_indefinite_free_scope_leaves_the_legacy_list() {
        let expired = at(None, 5_000);
        assert!(!in_legacy_mute_list(expired, ScopePrefs::default(), 6_000));
    }

    #[test]
    fn sweep_picks_exactly_the_timers_that_have_arrived() {
        // Mirrors `db::notify::clear_expired_mutes`'s `mute_until > 0 AND <= ?1`.
        let lapsed = |until: i64, now: i64| until > MUTE_OFF && until <= now;
        assert!(!lapsed(MUTE_FOREVER, 10_000), "indefinite never lapses");
        assert!(!lapsed(MUTE_OFF, 10_000), "unmuted has no timer");
        assert!(lapsed(10_000, 10_000), "an expiry that has arrived is over");
        assert!(!lapsed(10_001, 10_000));
    }

    #[test]
    fn scope_prefs_round_trip_through_the_wire_shape() {
        let prefs = ScopePrefs {
            level: Some(NotifyLevel::Mentions),
            mute_until: 1_700_000_000_000,
            suppress_everyone: Some(true),
        };
        assert_eq!(ScopePrefs::from_wire(&prefs.to_wire()), prefs);
        // An entry that says nothing must come back as the default, or a sync
        // would keep resurrecting rows the writer meant to drop.
        assert!(ScopePrefs::from_wire(&crate::synced_prefs::NotifyEntry::default()).is_default());
    }

    #[test]
    fn level_round_trips_through_both_wire_forms() {
        for level in [NotifyLevel::All, NotifyLevel::Mentions, NotifyLevel::Nothing] {
            assert_eq!(NotifyLevel::from_u8(level.as_u8()), Some(level));
            assert_eq!(NotifyLevel::from_label(level.as_str()), Some(level));
        }
        // The sync payload predates the rename, so both spellings must read.
        assert_eq!(NotifyLevel::from_label("none"), Some(NotifyLevel::Nothing));
        assert_eq!(NotifyLevel::from_label("whatever"), None);
        assert_eq!(NotifyLevel::from_u8(9), None);
    }
}