Skip to main content

vector_core/
synced_prefs.rs

1//! Account preferences that follow you between your own devices: the block
2//! list, the mute list, nicknames, and the general settings document.
3//!
4//! Each is a private, parameterized-replaceable kind 30078 with its own d tag,
5//! NIP-44 self-encrypted, riding the SAME self-sync subscription as the
6//! Community, Invite and Pinned lists — so each inherits boot sync, reconnect
7//! re-sync and live cross-device edits with no new plumbing.
8//!
9//! **Vector's own lists, deliberately not NIP-51.** Social clients disagree on
10//! what a mute is — several treat it as a soft block — so round-tripping
11//! through the shared kind-10000 would blur the mute/block separation Vector
12//! draws on purpose. Isolation costs interop and buys exactness.
13//!
14//! **Newest wins, whole list.** These are one person's settings edited from one
15//! device at a time, so the replaceable event's own last-write-wins is the
16//! merge. A device that was offline can therefore republish over a change it
17//! never saw; the pre-publish fetch below shrinks that window, and these are
18//! deliberate, infrequent actions rather than latency-sensitive ones.
19
20use nostr_sdk::prelude::*;
21use serde::{Deserialize, Serialize};
22use std::collections::BTreeMap;
23
24use crate::stored_event::event_kind;
25
26pub const BLOCKS_D_TAG: &str = "vector/blocks";
27pub const MUTES_D_TAG: &str = "vector/mutes";
28pub const NICKNAMES_D_TAG: &str = "vector/nicknames";
29pub const NOTIFY_D_TAG: &str = "vector/notify";
30pub const RAIL_D_TAG: &str = "vector/rail";
31pub const BANNERS_D_TAG: &str = "vector/banners";
32pub const SETTINGS_D_TAG: &str = "vector/settings";
33pub const ARCHIVE_D_TAG: &str = "vector/archive";
34pub const START_D_TAG: &str = "vector/start";
35
36const BLOCKS_LOCAL_KEY: &str = "synced_blocks_local";
37const MUTES_LOCAL_KEY: &str = "synced_mutes_local";
38const NICKNAMES_LOCAL_KEY: &str = "synced_nicknames_local";
39const NOTIFY_LOCAL_KEY: &str = "synced_notify_local";
40const RAIL_LOCAL_KEY: &str = "synced_rail_local";
41const BANNERS_LOCAL_KEY: &str = "synced_banners_local";
42const SETTINGS_LOCAL_KEY: &str = "synced_settings_local";
43const ARCHIVE_LOCAL_KEY: &str = "synced_archive_local";
44const START_LOCAL_KEY: &str = "synced_start_local";
45/// The newest `created_at` of an archive copy this device holds, adopted or published.
46const ARCHIVE_SEEN_KEY: &str = "synced_archive_seen";
47/// Persisted, so a change survives a quit until the relays have it.
48const SETTINGS_INTENT_KEY: &str = "synced_settings_intent";
49const SETTINGS_SEEN_KEY: &str = "synced_settings_seen";
50
51/// Set when a list has local edits the relays have not seen, cleared once they
52/// have. Persisted, so a quit during the rail's publish debounce is recoverable
53/// at the next boot instead of being silently lost.
54const RAIL_DIRTY_KEY: &str = "synced_rail_dirty";
55const START_DIRTY_KEY: &str = "synced_start_dirty";
56/// The newest `created_at` of a layout copy this device holds, adopted or published.
57const RAIL_SEEN_KEY: &str = "synced_rail_seen";
58const START_SEEN_KEY: &str = "synced_start_seen";
59
60/// One NIP-44 event holds the whole list, and blocks and nicknames scale with contacts
61/// rather than being capped like pins: the write path measures the list as it will be
62/// encrypted and refuses an entry that would carry it past what a relay stores.
63fn fits(json: &str) -> bool {
64    crate::event_size::layer_fits(json.len())
65}
66
67const LIST_FULL: &str = "this list is full: it would no longer fit one event";
68
69const FETCH_TIMEOUT_SECS: u64 = 10;
70
71/// A set of ids (npubs for blocks, chat ids for mutes).
72#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
73pub struct IdList {
74    #[serde(default = "one")]
75    pub v: u32,
76    #[serde(default)]
77    pub ids: Vec<String>,
78}
79
80/// npub → nickname. A map rather than a list so a rename replaces rather than
81/// duplicates, and so the wire form stays stable under reordering.
82#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
83pub struct NicknameMap {
84    #[serde(default = "one")]
85    pub v: u32,
86    #[serde(default)]
87    pub names: BTreeMap<String, String>,
88}
89
90/// An entry is about 80 bytes. Padded, encrypted and base64'd, 500 of them keep the event under the
91/// 64KB that strfry relays accept by default.
92const ARCHIVE_MAX_ENTRIES: usize = 500;
93
94/// chat id → the newest message time the archiving device had seen (unix ms). A chat counts
95/// as archived only while nothing newer has been said in it, so a reply brings it back on
96/// every device whether or not this list has caught up.
97///
98/// Entries stay raw JSON, and unknown keys ride along, so an entry in a shape a newer build
99/// writes survives this one's republish instead of collapsing the whole map.
100#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
101pub struct ArchiveMap {
102    #[serde(default = "one")]
103    pub v: u32,
104    #[serde(default)]
105    pub chats: BTreeMap<String, serde_json::Value>,
106    #[serde(flatten)]
107    pub other: serde_json::Map<String, serde_json::Value>,
108}
109
110impl ArchiveMap {
111    pub fn from_json(s: &str) -> Self {
112        serde_json::from_str(s).unwrap_or_default()
113    }
114    pub fn to_json(&self) -> String {
115        serde_json::to_string(self).unwrap_or_else(|_| "{\"v\":1,\"chats\":{}}".to_string())
116    }
117    pub fn at(&self, chat_id: &str) -> Option<u64> {
118        self.chats.get(chat_id).and_then(serde_json::Value::as_u64)
119    }
120    /// The entries this build understands, for the page.
121    pub fn times(&self) -> BTreeMap<String, u64> {
122        self.chats.iter().filter_map(|(id, v)| v.as_u64().map(|at| (id.clone(), at))).collect()
123    }
124    pub fn set(&mut self, chat_id: &str, at: u64) -> Result<(), String> {
125        if chat_id.trim().is_empty() {
126            return Err("empty chat id".to_string());
127        }
128        if !self.chats.contains_key(chat_id) && self.chats.len() >= ARCHIVE_MAX_ENTRIES {
129            return Err(format!("the archive is full ({ARCHIVE_MAX_ENTRIES} chats)"));
130        }
131        self.chats.insert(chat_id.to_string(), at.into());
132        Ok(())
133    }
134    /// Drop `chat_id` if it was archived before `active_at`; a later archive stands.
135    pub fn revoke(&mut self, chat_id: &str, active_at: u64) -> bool {
136        match self.at(chat_id) {
137            Some(at) if at < active_at => self.chats.remove(chat_id).is_some(),
138            _ => false,
139        }
140    }
141}
142
143/// One scope's notification settings on the wire. Level is spelled out rather
144/// than numbered so a future rung does not silently become an old one, and an
145/// absent field means inherit, exactly as it does on disk.
146#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
147pub struct NotifyEntry {
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub level: Option<String>,
150    #[serde(default, skip_serializing_if = "is_zero")]
151    pub mute_until: i64,
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub suppress_everyone: Option<bool>,
154}
155
156fn is_zero(v: &i64) -> bool {
157    *v == 0
158}
159
160/// scope id → settings, for communities, channels and DMs alike.
161#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
162pub struct NotifyMap {
163    #[serde(default = "one")]
164    pub v: u32,
165    #[serde(default)]
166    pub scopes: BTreeMap<String, NotifyEntry>,
167}
168
169impl NotifyMap {
170    pub fn from_json(s: &str) -> Self {
171        serde_json::from_str(s).unwrap_or_default()
172    }
173    pub fn to_json(&self) -> String {
174        serde_json::to_string(self).unwrap_or_else(|_| "{\"v\":1,\"scopes\":{}}".to_string())
175    }
176    /// Refuses to grow past the ceiling rather than publishing a list no
177    /// reader can open, the same rule the id lists follow.
178    pub fn set(&mut self, scope_id: &str, entry: NotifyEntry) -> Result<(), String> {
179        if scope_id.trim().is_empty() {
180            return Err("empty scope id".to_string());
181        }
182        if entry == NotifyEntry::default() {
183            self.scopes.remove(scope_id);
184            return Ok(());
185        }
186        let prev = self.scopes.insert(scope_id.to_string(), entry);
187        if !fits(&self.to_json()) {
188            match prev {
189                Some(p) => self.scopes.insert(scope_id.to_string(), p),
190                None => self.scopes.remove(scope_id),
191            };
192            return Err(LIST_FULL.to_string());
193        }
194        Ok(())
195    }
196}
197
198/// Account-wide switches that follow the user between devices.
199///
200/// Keys this build does not know are carried through untouched: the document is
201/// newest-wins as a whole, so an older device that dropped them on republish
202/// would erase settings a newer one added.
203#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
204pub struct SyncedSettings {
205    #[serde(default = "one")]
206    pub v: u32,
207    /// Reveals identifiers and other developer-facing detail across the app.
208    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
209    pub advanced: bool,
210    #[serde(default, skip_serializing_if = "StreamerSettings::is_default")]
211    pub streamer: StreamerSettings,
212    /// Embedded video players (click to play) are switched off. Stored as the opt-out so
213    /// every default, an empty or unreadable document included, keeps them on.
214    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
215    pub players_off: bool,
216    #[serde(flatten)]
217    pub other: serde_json::Map<String, serde_json::Value>,
218}
219
220impl SyncedSettings {
221    pub fn from_json(s: &str) -> Self {
222        serde_json::from_str(s).unwrap_or_default()
223    }
224    pub fn to_json(&self) -> String {
225        serde_json::to_string(self).unwrap_or_else(|_| "{\"v\":1}".to_string())
226    }
227    /// What `get_synced_settings` and `synced_settings_updated` hand the page.
228    pub fn view(&self) -> serde_json::Value {
229        serde_json::json!({
230            "advanced": self.advanced,
231            "players": !self.players_off,
232            "streamer": {
233                "on": self.streamer.on,
234                "seed": self.streamer.seed,
235                "notif": self.streamer.notif,
236                "hide_wallpapers": self.streamer.hide_wallpapers,
237            },
238        })
239    }
240}
241
242/// The streaming overlay's levels, in the spelling the wire and the page share.
243pub const STREAMER_NOTIF_LEVELS: [&str; 4] = ["none", "hide_content", "hide_sender", "hide_all"];
244
245/// Streamer Mode: masks everyone who has not opted in, on every device of the account.
246#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
247pub struct StreamerSettings {
248    #[serde(default)]
249    pub on: bool,
250    /// 16 random bytes as lowercase hex, re-minted at each go-live so per-stream colours reshuffle.
251    #[serde(default)]
252    pub seed: String,
253    /// What notifications additionally hide while live, one of [`STREAMER_NOTIF_LEVELS`].
254    #[serde(default = "notif_none")]
255    pub notif: String,
256    /// Chats show a plain background while live: a DM's wallpaper can say who it is with.
257    #[serde(default = "yes")]
258    pub hide_wallpapers: bool,
259    #[serde(flatten)]
260    pub other: serde_json::Map<String, serde_json::Value>,
261}
262
263fn notif_none() -> String {
264    "none".to_string()
265}
266
267fn yes() -> bool {
268    true
269}
270
271impl Default for StreamerSettings {
272    fn default() -> Self {
273        Self { on: false, seed: String::new(), notif: notif_none(), hide_wallpapers: true, other: serde_json::Map::new() }
274    }
275}
276
277impl StreamerSettings {
278    pub fn is_default(&self) -> bool {
279        *self == Self::default()
280    }
281
282    pub fn set_on(&mut self, on: bool) {
283        if on && !self.on {
284            self.seed = fresh_seed();
285        }
286        self.on = on;
287    }
288
289    pub fn set_notif(&mut self, level: &str) -> Result<(), String> {
290        if !STREAMER_NOTIF_LEVELS.contains(&level) {
291            return Err(format!("Unknown notification level: {level}"));
292        }
293        self.notif = level.to_string();
294        Ok(())
295    }
296}
297
298fn fresh_seed() -> String {
299    use rand::RngCore;
300    let mut b = [0u8; 16];
301    rand::thread_rng().fill_bytes(&mut b);
302    crate::simd::hex::bytes_to_hex_string(&b)
303}
304
305/// Settings changes the relays have not confirmed, re-applied over any copy adopted before they
306/// do. Only the fields the user touched, so the rest of a sibling's newer copy stands.
307#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
308struct SettingsIntent {
309    #[serde(default, skip_serializing_if = "Option::is_none")]
310    advanced: Option<bool>,
311    #[serde(default, skip_serializing_if = "Option::is_none")]
312    on: Option<bool>,
313    /// The seed this device minted going live, so adoption keeps the colours already on screen.
314    #[serde(default, skip_serializing_if = "Option::is_none")]
315    seed: Option<String>,
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    notif: Option<String>,
318    #[serde(default, skip_serializing_if = "Option::is_none")]
319    hide_wallpapers: Option<bool>,
320    #[serde(default, skip_serializing_if = "Option::is_none")]
321    players_off: Option<bool>,
322}
323
324impl SettingsIntent {
325    fn apply(&self, s: &mut SyncedSettings) {
326        if let Some(advanced) = self.advanced {
327            s.advanced = advanced;
328        }
329        if let Some(off) = self.players_off {
330            s.players_off = off;
331        }
332        let st = &mut s.streamer;
333        if let Some(on) = self.on {
334            match self.seed.as_ref().filter(|seed| !seed.is_empty()) {
335                Some(seed) if on => st.seed = seed.clone(),
336                _ if on && !st.on => st.seed = fresh_seed(),
337                _ => {}
338            }
339            st.on = on;
340        }
341        if let Some(level) = self.notif.as_deref() {
342            if STREAMER_NOTIF_LEVELS.contains(&level) {
343                st.notif = level.to_string();
344            }
345        }
346        if let Some(hide) = self.hide_wallpapers {
347            st.hide_wallpapers = hide;
348        }
349    }
350}
351
352fn one() -> u32 {
353    1
354}
355
356impl IdList {
357    /// Tolerant parse: a malformed payload degrades to empty rather than
358    /// erroring, so one bad event can never wedge a sync.
359    pub fn from_json(s: &str) -> Self {
360        serde_json::from_str(s).unwrap_or_default()
361    }
362    pub fn to_json(&self) -> String {
363        serde_json::to_string(self).unwrap_or_else(|_| "{\"v\":1,\"ids\":[]}".to_string())
364    }
365    pub fn contains(&self, id: &str) -> bool {
366        self.ids.iter().any(|i| i == id)
367    }
368    pub fn add(&mut self, id: &str) -> Result<(), String> {
369        if id.trim().is_empty() {
370            return Err("empty id".to_string());
371        }
372        if self.contains(id) {
373            return Ok(());
374        }
375        self.ids.push(id.to_string());
376        if !fits(&self.to_json()) {
377            self.ids.pop();
378            return Err(LIST_FULL.to_string());
379        }
380        Ok(())
381    }
382    pub fn remove(&mut self, id: &str) {
383        self.ids.retain(|i| i != id);
384    }
385}
386
387impl NicknameMap {
388    pub fn from_json(s: &str) -> Self {
389        serde_json::from_str(s).unwrap_or_default()
390    }
391    pub fn to_json(&self) -> String {
392        serde_json::to_string(self).unwrap_or_else(|_| "{\"v\":1,\"names\":{}}".to_string())
393    }
394    /// An empty nickname CLEARS the entry — that is how the UI expresses
395    /// "remove this nickname", and keeping a blank would republish it forever.
396    pub fn set(&mut self, npub: &str, name: &str) -> Result<(), String> {
397        if npub.trim().is_empty() {
398            return Err("empty npub".to_string());
399        }
400        if name.trim().is_empty() {
401            self.names.remove(npub);
402            return Ok(());
403        }
404        let prev = self.names.insert(npub.to_string(), name.to_string());
405        if !fits(&self.to_json()) {
406            match prev {
407                Some(p) => self.names.insert(npub.to_string(), p),
408                None => self.names.remove(npub),
409            };
410            return Err(LIST_FULL.to_string());
411        }
412        Ok(())
413    }
414}
415
416/// Which list a call refers to. Keeps one set of network/storage plumbing for
417/// all three rather than three near-identical copies that can drift.
418#[derive(Debug, Clone, Copy, PartialEq, Eq)]
419pub enum Pref {
420    Blocks,
421    Mutes,
422    Nicknames,
423    Notify,
424    Rail,
425    /// Communities whose banner the user hid.
426    Banners,
427    /// The general settings document.
428    Settings,
429    /// Chats tidied out of the list until someone speaks in them again.
430    Archive,
431    /// The widescreen Main Menu's pins and folders.
432    Start,
433}
434
435/// Every list, in the order hydration walks them. `Notify` comes after `Mutes`
436/// so a device holding both applies the richer one last and wins the overlap.
437pub const ALL_PREFS: [Pref; 9] = [
438    Pref::Blocks,
439    Pref::Mutes,
440    Pref::Nicknames,
441    Pref::Notify,
442    Pref::Rail,
443    Pref::Start,
444    Pref::Banners,
445    Pref::Settings,
446    Pref::Archive,
447];
448
449/// Every self-synced list's d tag, for the live subscriptions: built from [`ALL_PREFS`],
450/// so a new list can't be read at boot and then never heard from again.
451pub fn live_d_tags() -> Vec<String> {
452    std::iter::once(crate::pinned_chats::PINNED_D_TAG)
453        .chain(ALL_PREFS.iter().map(|p| p.d_tag()))
454        .map(str::to_string)
455        .collect()
456}
457
458impl Pref {
459    pub fn d_tag(self) -> &'static str {
460        match self {
461            Pref::Blocks => BLOCKS_D_TAG,
462            Pref::Mutes => MUTES_D_TAG,
463            Pref::Nicknames => NICKNAMES_D_TAG,
464            Pref::Notify => NOTIFY_D_TAG,
465            Pref::Rail => RAIL_D_TAG,
466            Pref::Banners => BANNERS_D_TAG,
467            Pref::Settings => SETTINGS_D_TAG,
468            Pref::Archive => ARCHIVE_D_TAG,
469            Pref::Start => START_D_TAG,
470        }
471    }
472    fn local_key(self) -> &'static str {
473        match self {
474            Pref::Blocks => BLOCKS_LOCAL_KEY,
475            Pref::Mutes => MUTES_LOCAL_KEY,
476            Pref::Nicknames => NICKNAMES_LOCAL_KEY,
477            Pref::Notify => NOTIFY_LOCAL_KEY,
478            Pref::Rail => RAIL_LOCAL_KEY,
479            Pref::Banners => BANNERS_LOCAL_KEY,
480            Pref::Settings => SETTINGS_LOCAL_KEY,
481            Pref::Archive => ARCHIVE_LOCAL_KEY,
482            Pref::Start => START_LOCAL_KEY,
483        }
484    }
485    /// The d-tag → list routing used by the self-sync handler.
486    pub fn from_d_tag(d: &str) -> Option<Self> {
487        match d {
488            BLOCKS_D_TAG => Some(Pref::Blocks),
489            MUTES_D_TAG => Some(Pref::Mutes),
490            NICKNAMES_D_TAG => Some(Pref::Nicknames),
491            NOTIFY_D_TAG => Some(Pref::Notify),
492            RAIL_D_TAG => Some(Pref::Rail),
493            BANNERS_D_TAG => Some(Pref::Banners),
494            SETTINGS_D_TAG => Some(Pref::Settings),
495            ARCHIVE_D_TAG => Some(Pref::Archive),
496            START_D_TAG => Some(Pref::Start),
497            _ => None,
498        }
499    }
500}
501
502/// Lists this account has reconciled with the relays this session, keyed by
503/// d-tag. Per-account by construction: it lives on the Session, so a swap drops
504/// it and the next account re-hydrates rather than inheriting this one's.
505struct Hydrated;
506
507fn hydrated_set() -> std::sync::Arc<std::sync::Mutex<std::collections::HashSet<&'static str>>> {
508    crate::db::current_session().scoped::<Hydrated, _>()
509}
510
511/// Has `pref` been reconciled with the relays yet this session?
512///
513/// **The publish gate.** These lists are whole-list newest-wins projections of
514/// local state, so publishing one before the relay copy has been applied would
515/// overwrite another device's prefs with this device's emptier view — a fresh
516/// login that mutes one chat before the subscription replay lands would erase
517/// every block, mute and nickname set elsewhere. Reconcile, THEN publish.
518pub fn is_hydrated(pref: Pref) -> bool {
519    hydrated_set().lock().map(|h| h.contains(pref.d_tag())).unwrap_or(false)
520}
521
522/// Mark `pref` reconciled. Called when a copy is applied AND when the relays
523/// confirm none exists — "there is nothing to preserve" is just as reconciled
524/// as having read it, and without that a first-ever account could never publish.
525pub fn mark_hydrated(pref: Pref) {
526    if let Ok(mut h) = hydrated_set().lock() {
527        h.insert(pref.d_tag());
528    }
529}
530
531/// Pull every list once at login and apply it, so this device is reconciled
532/// before the user can touch anything. The live subscription also delivers
533/// these, but it races the user; this does not.
534///
535/// A list whose fetch FAILS stays un-hydrated, so it stays unpublishable — far
536/// better to leave prefs un-synced for a session than to overwrite prefs we
537/// could not read.
538pub async fn hydrate_all(client: &Client) -> Vec<(Pref, String)> {
539    let Some(my_pk) = crate::state::my_public_key() else { return Vec::new() };
540    let mut applied = Vec::new();
541    for pref in ALL_PREFS {
542        // The layouts are the lists that can hold edits the relays have never
543        // seen: their publish is debounced, so a quit mid-drag leaves the newer
544        // copy here. Applying the relay's older one would undo it.
545        if pref.is_layout() && layout_is_dirty(pref) {
546            mark_hydrated(pref);
547            schedule_layout_publish(pref);
548            continue;
549        }
550        let fetched = match fetch_raw(client, my_pk, pref).await {
551            Ok(fetched) => fetched,
552            Err(e) => {
553                crate::log_warn!("[SyncedPrefs] reading {} failed, left unpublishable: {e}", pref.d_tag());
554                continue;
555            }
556        };
557        if pref == Pref::Archive {
558            match fetched.map(|copy| adopt_archive(&copy.json, copy.created_at).map(|took| (copy, took))) {
559                Some(Ok((copy, true))) => {
560                    mark_hydrated(pref);
561                    applied.push((pref, copy.json));
562                }
563                // Nothing stored, or older than what this device holds: ours stands.
564                None | Some(Ok((_, false))) => mark_hydrated(pref),
565                Some(Err(e)) => crate::log_warn!("[SyncedPrefs] adopting {} failed: {e}", pref.d_tag()),
566            }
567            continue;
568        }
569        if pref == Pref::Settings {
570            match adopt_settings(fetched.as_ref()) {
571                Ok(adopted) => {
572                    // A stale copy means the relays lack this device's newer one.
573                    if adopted.publish || adopted.stale {
574                        publish_settings_soon();
575                    }
576                    applied.extend(adopted.json.map(|json| (pref, json)));
577                }
578                Err(e) => crate::log_warn!("[SyncedPrefs] adopting {} failed: {e}", pref.d_tag()),
579            }
580            continue;
581        }
582        match fetched {
583            // A relay that missed our last publish still serves the one before it.
584            Some(copy) if pref.is_layout() && !adopts_layout_copy(pref, copy.created_at) => mark_hydrated(pref),
585            Some(copy) => {
586                if save_local_raw(pref, &copy.json).is_ok() {
587                    if pref.is_layout() {
588                        set_layout_seen(pref, copy.created_at);
589                    }
590                    mark_hydrated(pref);
591                    applied.push((pref, copy.json));
592                }
593            }
594            // No stored copy: nothing to preserve, so this device may publish.
595            None => mark_hydrated(pref),
596        }
597    }
598    applied
599}
600
601/// Raw JSON of a list's local mirror. Callers parse into whichever shape the
602/// list uses; the storage layer stays shape-agnostic.
603pub fn load_local_raw(pref: Pref) -> Option<String> {
604    crate::db::settings::get_sql_setting(pref.local_key().to_string())
605        .ok()
606        .flatten()
607}
608
609pub fn save_local_raw(pref: Pref, json: &str) -> Result<(), String> {
610    crate::db::settings::set_sql_setting(pref.local_key().to_string(), json.to_string())
611}
612
613pub fn load_blocks() -> IdList {
614    load_local_raw(Pref::Blocks).map(|s| IdList::from_json(&s)).unwrap_or_default()
615}
616pub fn load_mutes() -> IdList {
617    load_local_raw(Pref::Mutes).map(|s| IdList::from_json(&s)).unwrap_or_default()
618}
619pub fn load_nicknames() -> NicknameMap {
620    load_local_raw(Pref::Nicknames).map(|s| NicknameMap::from_json(&s)).unwrap_or_default()
621}
622pub fn load_notify() -> NotifyMap {
623    load_local_raw(Pref::Notify).map(|s| NotifyMap::from_json(&s)).unwrap_or_default()
624}
625pub fn load_hidden_banners() -> IdList {
626    load_local_raw(Pref::Banners).map(|s| IdList::from_json(&s)).unwrap_or_default()
627}
628
629/// Hide or show a community's banner, committed locally. The caller publishes.
630///
631/// Refused until the relay copy has been read, or a fresh login would publish
632/// its empty list over the banners hidden on another device.
633pub fn set_banner_hidden(community_id: &str, hidden: bool) -> Result<IdList, String> {
634    if !is_hydrated(Pref::Banners) {
635        return Err("Still syncing your settings, try again in a moment".to_string());
636    }
637    let mut list = load_hidden_banners();
638    if hidden {
639        list.add(community_id)?;
640    } else {
641        list.remove(community_id);
642    }
643    save_local_raw(Pref::Banners, &list.to_json())?;
644    Ok(list)
645}
646
647pub fn load_archive() -> ArchiveMap {
648    load_local_raw(Pref::Archive).map(|s| ArchiveMap::from_json(&s)).unwrap_or_default()
649}
650
651/// Serialises every read-modify-write of the archive: commands run on several threads.
652struct ArchiveLock;
653
654fn archive_lock() -> std::sync::Arc<std::sync::Mutex<()>> {
655    crate::db::current_session().scoped::<ArchiveLock, _>()
656}
657
658fn archive_seen() -> u64 {
659    crate::db::settings::get_sql_setting(ARCHIVE_SEEN_KEY.to_string())
660        .ok()
661        .flatten()
662        .and_then(|s| s.parse().ok())
663        .unwrap_or(0)
664}
665
666/// Archive a chat as of `at` (`Some`) or bring it back (`None`), committed locally. The caller
667/// publishes. Refused until the relay copy has been read, for the same reason as the banners.
668pub fn set_archived(chat_id: &str, at: Option<u64>) -> Result<ArchiveMap, String> {
669    if !is_hydrated(Pref::Archive) {
670        return Err("Still syncing your settings, try again in a moment".to_string());
671    }
672    let lock = archive_lock();
673    let _g = lock.lock().unwrap_or_else(|e| e.into_inner());
674    let mut map = load_archive();
675    match at {
676        Some(at) => map.set(chat_id, at)?,
677        None => {
678            map.chats.remove(chat_id);
679        }
680    }
681    save_local_raw(Pref::Archive, &map.to_json())?;
682    Ok(map)
683}
684
685/// Forget an archive that activity at `active_at` has outlived, on this device only. An outlived
686/// entry is harmless (every reader looks past it) and leaves the relays with the next archive
687/// change; publishing it from every device the message reaches would race them against each other.
688/// The bool says whether anything changed.
689pub fn revoke_archive(chat_id: &str, active_at: u64) -> Result<(ArchiveMap, bool), String> {
690    let lock = archive_lock();
691    let _g = lock.lock().unwrap_or_else(|e| e.into_inner());
692    let mut map = load_archive();
693    if !map.revoke(chat_id, active_at) {
694        return Ok((map, false));
695    }
696    save_local_raw(Pref::Archive, &map.to_json())?;
697    Ok((map, true))
698}
699
700/// Take a relay copy signed at `created_at` unless this device already holds a newer one: a relay
701/// that was down can replay a week-old copy, and adopting it would bring back what was since
702/// unarchived and drop what was since archived.
703fn adopt_archive(json: &str, created_at: u64) -> Result<bool, String> {
704    let lock = archive_lock();
705    let _g = lock.lock().unwrap_or_else(|e| e.into_inner());
706    if created_at < archive_seen() {
707        return Ok(false);
708    }
709    save_local_raw(Pref::Archive, json)?;
710    crate::db::settings::set_sql_setting(ARCHIVE_SEEN_KEY.to_string(), created_at.to_string())?;
711    Ok(true)
712}
713
714/// The archive to publish and the `created_at` to sign it with: after every copy this device has
715/// seen, since relays keep the lower id when two copies tie on a second.
716fn claim_archive_publish(now: u64) -> Result<(String, u64), String> {
717    let lock = archive_lock();
718    let _g = lock.lock().unwrap_or_else(|e| e.into_inner());
719    let at = now.max(archive_seen() + 1);
720    crate::db::settings::set_sql_setting(ARCHIVE_SEEN_KEY.to_string(), at.to_string())?;
721    Ok((load_archive().to_json(), at))
722}
723
724async fn publish_archive(client: &Client) -> Result<(), String> {
725    let my_pk = crate::state::my_public_key().ok_or_else(|| "Not logged in".to_string())?;
726    let (json, at) = claim_archive_publish(crate::clock::timestamp().as_secs())?;
727    send_list(client, my_pk, Pref::Archive, &json, Some(at)).await
728}
729
730pub fn load_settings() -> SyncedSettings {
731    load_local_raw(Pref::Settings).map(|s| SyncedSettings::from_json(&s)).unwrap_or_default()
732}
733
734/// Serialises every read-modify-write of the settings document, including adopting
735/// a relay copy, so a change cannot land between a copy being read and being saved.
736struct SettingsLock;
737
738fn settings_lock() -> std::sync::Arc<std::sync::Mutex<()>> {
739    crate::db::current_session().scoped::<SettingsLock, _>()
740}
741
742/// Turn Advanced Mode on or off, committed locally. The caller publishes.
743///
744/// Refused until the relay copy has been read, for the same reason as the banners.
745pub fn set_advanced(on: bool) -> Result<SyncedSettings, String> {
746    change_settings(|s, intent| {
747        if !is_hydrated(Pref::Settings) {
748            return Err("Still syncing your settings, try again in a moment".to_string());
749        }
750        s.advanced = on;
751        intent.advanced = Some(on);
752        Ok(())
753    })
754}
755
756/// Go live or stop, in effect at once. The caller publishes.
757///
758/// Never refused for want of hydration: the change is held as an intent and
759/// re-applied over the relay copy when it lands, then published.
760pub fn set_streamer_on(on: bool) -> Result<SyncedSettings, String> {
761    change_settings(|s, intent| {
762        s.streamer.set_on(on);
763        intent.on = Some(on);
764        intent.seed = on.then(|| s.streamer.seed.clone());
765        Ok(())
766    })
767}
768
769/// Choose what notifications additionally hide while live. Held like [`set_streamer_on`].
770pub fn set_streamer_notif(level: &str) -> Result<SyncedSettings, String> {
771    change_settings(|s, intent| {
772        s.streamer.set_notif(level)?;
773        intent.notif = Some(s.streamer.notif.clone());
774        Ok(())
775    })
776}
777
778/// Choose whether chat wallpapers stay plain while live. Held like [`set_streamer_on`].
779pub fn set_streamer_wallpapers(hide: bool) -> Result<SyncedSettings, String> {
780    change_settings(|s, intent| {
781        s.streamer.hide_wallpapers = hide;
782        intent.hide_wallpapers = Some(hide);
783        Ok(())
784    })
785}
786
787/// Allow or refuse embedded video players. Held like [`set_streamer_on`]: switching them
788/// off is a privacy choice, so it must not wait for the relay copy.
789pub fn set_players(on: bool) -> Result<SyncedSettings, String> {
790    change_settings(|s, intent| {
791        s.players_off = !on;
792        intent.players_off = Some(!on);
793        Ok(())
794    })
795}
796
797/// Commit a change locally and hold it as an intent until the relays confirm it, so no copy
798/// adopted meanwhile (an older one, or one adopted after a failed publish) can undo it.
799fn change_settings(
800    change: impl FnOnce(&mut SyncedSettings, &mut SettingsIntent) -> Result<(), String>,
801) -> Result<SyncedSettings, String> {
802    let lock = settings_lock();
803    let _g = lock.lock().unwrap_or_else(|e| e.into_inner());
804    let mut intent = load_intent().unwrap_or_default();
805    let mut settings = load_settings();
806    change(&mut settings, &mut intent)?;
807    save_local_raw(Pref::Settings, &settings.to_json())?;
808    save_intent(&intent)?;
809    Ok(settings)
810}
811
812fn load_intent() -> Option<SettingsIntent> {
813    crate::db::settings::get_sql_setting(SETTINGS_INTENT_KEY.to_string())
814        .ok()
815        .flatten()
816        .and_then(|s| serde_json::from_str(&s).ok())
817}
818
819fn save_intent(intent: &SettingsIntent) -> Result<(), String> {
820    let json = serde_json::to_string(intent).map_err(|e| e.to_string())?;
821    crate::db::settings::set_sql_setting(SETTINGS_INTENT_KEY.to_string(), json)
822}
823
824fn clear_intent() {
825    let _ = crate::db::settings::remove_setting(SETTINGS_INTENT_KEY);
826}
827
828/// `created_at` of the newest settings copy this device adopted or saw published. Anything
829/// older is a copy it already superseded, however late a relay delivers it.
830fn settings_seen() -> u64 {
831    crate::db::settings::get_sql_setting(SETTINGS_SEEN_KEY.to_string())
832        .ok()
833        .flatten()
834        .and_then(|s| s.parse().ok())
835        .unwrap_or(0)
836}
837
838fn set_settings_seen(at: u64) -> Result<(), String> {
839    crate::db::settings::set_sql_setting(SETTINGS_SEEN_KEY.to_string(), at.to_string())
840}
841
842/// The last `created_at` this session signed settings with, so each publish lands strictly after
843/// the one before it even while that one is still in flight.
844struct SettingsSigned;
845
846fn settings_signed() -> std::sync::Arc<std::sync::atomic::AtomicU64> {
847    crate::db::current_session().scoped::<SettingsSigned, _>()
848}
849
850/// A list as one relay copy carries it: the plaintext and when it was signed.
851#[derive(Debug, Clone, PartialEq)]
852pub struct RelayCopy {
853    pub json: String,
854    pub created_at: u64,
855}
856
857/// The outcome of taking a relay copy of the settings document.
858#[derive(Debug, Clone, PartialEq)]
859pub struct AdoptedSettings {
860    /// The document now held, when the copy changed it.
861    pub json: Option<String>,
862    /// This device holds a change the relays have not seen.
863    pub publish: bool,
864    /// The copy is older than one this device already adopted or published, so it was ignored.
865    pub stale: bool,
866}
867
868/// Take a relay copy of the settings (`None` = the relays hold none) and mark them reconciled.
869///
870/// A copy older than the newest this device adopted or published is ignored, so a lagging relay
871/// or a late echo never rolls the document back. A held change is re-applied over a newer copy.
872pub fn adopt_settings(relay: Option<&RelayCopy>) -> Result<AdoptedSettings, String> {
873    let lock = settings_lock();
874    let _g = lock.lock().unwrap_or_else(|e| e.into_inner());
875    let intent = load_intent();
876    let adopted = match relay {
877        Some(copy) if copy.created_at < settings_seen() => {
878            AdoptedSettings { json: None, publish: false, stale: true }
879        }
880        Some(copy) => {
881            let theirs = SyncedSettings::from_json(&copy.json);
882            let mut merged = theirs.clone();
883            if let Some(intent) = &intent {
884                intent.apply(&mut merged);
885            }
886            set_settings_seen(copy.created_at)?;
887            if merged == theirs {
888                // The relays already say what we meant: usually our own publish echoing back.
889                if intent.is_some() {
890                    clear_intent();
891                }
892                save_local_raw(Pref::Settings, &copy.json)?;
893                AdoptedSettings { json: Some(copy.json.clone()), publish: false, stale: false }
894            } else {
895                let merged = merged.to_json();
896                save_local_raw(Pref::Settings, &merged)?;
897                AdoptedSettings { json: Some(merged), publish: true, stale: false }
898            }
899        }
900        // Relays that lost a copy this device once had get it back.
901        None => AdoptedSettings { json: None, publish: intent.is_some() || settings_seen() > 0, stale: false },
902    };
903    mark_hydrated(Pref::Settings);
904    Ok(adopted)
905}
906
907fn publish_settings_soon() {
908    crate::db::spawn_bound(async {
909        let Some(client) = crate::state::nostr_client() else { return };
910        if let Err(e) = publish_settings(&client, false).await {
911            crate::log_warn!("[SyncedPrefs] publishing {} failed: {e}", Pref::Settings.d_tag());
912        }
913    });
914}
915
916/// Publish the local settings, signed after every copy this device has adopted or signed so the
917/// relays keep it over them.
918///
919/// With `refresh`, a newer relay copy is folded in first, so a device that missed a sibling's
920/// change never publishes its stale document over it. That copy is returned for the caller to show.
921pub async fn publish_settings(client: &Client, refresh: bool) -> Result<Option<String>, String> {
922    let my_pk = crate::state::my_public_key().ok_or_else(|| "Not logged in".to_string())?;
923    let mut shown = None;
924    if refresh {
925        if let Ok(Some(copy)) = fetch_raw(client, my_pk, Pref::Settings).await {
926            if copy.created_at > settings_seen() {
927                let adopted = adopt_settings(Some(&copy))?;
928                shown = adopted.json;
929                if !adopted.publish {
930                    return Ok(shown);
931                }
932            }
933        }
934    }
935    let (json, at) = claim_publish(crate::clock::timestamp().as_secs());
936    send_list(client, my_pk, Pref::Settings, &json, Some(at)).await?;
937    settings_published(&json, at);
938    Ok(shown)
939}
940
941/// The document to publish and the `created_at` to sign it with, taken together so a later
942/// claim always carries the later document.
943fn claim_publish(now: u64) -> (String, u64) {
944    let lock = settings_lock();
945    let _g = lock.lock().unwrap_or_else(|e| e.into_inner());
946    let signed = settings_signed();
947    // Two publishes in one second would tie, and relays keep the lower id, not the later one.
948    let at = now
949        .max(settings_seen() + 1)
950        .max(signed.load(std::sync::atomic::Ordering::SeqCst) + 1);
951    signed.store(at, std::sync::atomic::Ordering::SeqCst);
952    (load_settings().to_json(), at)
953}
954
955/// The relays now hold `json`, signed at `at`: older copies are superseded, and a held intent is
956/// done once nothing has changed since.
957fn settings_published(json: &str, at: u64) {
958    let lock = settings_lock();
959    let _g = lock.lock().unwrap_or_else(|e| e.into_inner());
960    if at > settings_seen() {
961        let _ = set_settings_seen(at);
962    }
963    if load_intent().is_some() && SyncedSettings::from_json(json) == load_settings() {
964        clear_intent();
965    }
966}
967
968pub fn load_rail() -> crate::rail_layout::RailLayout {
969    load_layout(Pref::Rail)
970}
971
972/// The Main Menu's pins, in the rail's shape: keys are pin keys (`crate::start_menu`).
973pub fn load_start() -> crate::rail_layout::RailLayout {
974    load_layout(Pref::Start)
975}
976
977fn load_layout(pref: Pref) -> crate::rail_layout::RailLayout {
978    let mut layout = load_local_raw(pref)
979        .map(|s| crate::rail_layout::RailLayout::from_json(&s))
980        .unwrap_or_default();
981    // A copy from a buggy or hostile writer can repeat a key; the menu keys its tiles by them.
982    if layout.is_editable() {
983        layout.normalize();
984    }
985    layout
986}
987
988struct LayoutEditLock;
989
990/// Load, change and commit one layout, one edit at a time: commands run on several
991/// threads, and two read-modify-writes interleaved would drop one of them. Returns the
992/// layout and whether anything moved (nothing is written when nothing did).
993pub fn edit_layout(
994    pref: Pref,
995    f: impl FnOnce(&mut crate::rail_layout::RailLayout) -> Result<(), String>,
996) -> Result<(crate::rail_layout::RailLayout, bool), String> {
997    if !pref.is_layout() {
998        return Err(format!("{} is not a layout", pref.d_tag()));
999    }
1000    let lock: std::sync::Arc<std::sync::Mutex<()>> = crate::db::current_session().scoped::<LayoutEditLock, _>();
1001    let _turn = lock.lock().unwrap_or_else(|e| e.into_inner());
1002    let before = load_layout(pref);
1003    let mut layout = before.clone();
1004    f(&mut layout)?;
1005    let changed = layout != before;
1006    if changed {
1007        save_layout_debounced(pref, &layout)?;
1008    }
1009    Ok((layout, changed))
1010}
1011
1012async fn decrypt_event(my_pk: &PublicKey, event: &Event) -> Option<String> {
1013    if event.content.is_empty() {
1014        return None;
1015    }
1016    let signer = crate::signer::active_signer().ok()?;
1017    match signer.nip44_decrypt_async(my_pk, &event.content).await {
1018        Ok(plaintext) => Some(plaintext),
1019        Err(e) => {
1020            crate::log_warn!("[SyncedPrefs] decrypt {} failed: {}", event.kind.as_u16(), e);
1021            None
1022        }
1023    }
1024}
1025
1026/// Fetch a list's newest relay copy, `Ok(None)` when the relays hold none.
1027///
1028/// `Err` when no relay answered or the copy can't be opened: neither says what the relays hold,
1029/// and treating it as "none" would let this device publish its emptier view over the real one.
1030pub async fn fetch_raw(client: &Client, my_pk: PublicKey, pref: Pref) -> Result<Option<RelayCopy>, String> {
1031    let filter = Filter::new()
1032        .author(my_pk)
1033        .kind(Kind::Custom(event_kind::APPLICATION_SPECIFIC))
1034        .identifier(pref.d_tag())
1035        .limit(1);
1036    let timeout = crate::relay_request_timeout(std::time::Duration::from_secs(FETCH_TIMEOUT_SECS));
1037    let events = crate::fetch_answered(client, filter, timeout).await?;
1038    let Some(event) = crate::newest_replaceable(events) else { return Ok(None) };
1039    let json = decrypt_event(&my_pk, &event)
1040        .await
1041        .ok_or_else(|| format!("couldn't open {}", pref.d_tag()))?;
1042    Ok(Some(RelayCopy { json, created_at: event.created_at.as_secs() }))
1043}
1044
1045/// Persist locally, then publish self-encrypted. Settings always go out from the local copy,
1046/// through [`publish_settings`], which keeps their signing order.
1047pub async fn publish_raw(client: &Client, pref: Pref, json: &str) -> Result<(), String> {
1048    if pref == Pref::Settings {
1049        return publish_settings(client, false).await.map(|_| ());
1050    }
1051    if pref == Pref::Archive {
1052        return publish_archive(client).await;
1053    }
1054    let my_pk = crate::state::my_public_key().ok_or_else(|| "Not logged in".to_string())?;
1055    save_local_raw(pref, json)?;
1056    send_list(client, my_pk, pref, json, None).await
1057}
1058
1059async fn send_list(
1060    client: &Client, my_pk: PublicKey, pref: Pref, json: &str, created_at: Option<u64>,
1061) -> Result<(), String> {
1062    let signer = crate::signer::active_signer().map_err(|e| format!("Signer unavailable: {e}"))?;
1063    let content = signer
1064        .nip44_encrypt_async(&my_pk, json)
1065        .await
1066        .map_err(|e| format!("nip44 encrypt {}: {e}", pref.d_tag()))?;
1067    let mut builder = EventBuilder::new(Kind::Custom(event_kind::APPLICATION_SPECIFIC), content)
1068        .tag(Tag::identifier(pref.d_tag()));
1069    if let Some(at) = created_at {
1070        builder = builder.custom_created_at(Timestamp::from_secs(at));
1071    }
1072    crate::sign_and_send(client, builder)
1073        .await
1074        .map_err(|e| format!("publish {}: {e}", pref.d_tag()))?;
1075    Ok(())
1076}
1077
1078/// Consume a sibling device's update. Never answers an echo with a publish — the
1079/// relay echoes our own publishes back on this same subscription, and that loops
1080/// forever. The one republish is a held settings intent the copy lacks, which an
1081/// echo of our own latest publish already carries. `None` for a settings copy older
1082/// than this device's, which changes nothing.
1083pub async fn ingest_remote(my_pk: &PublicKey, event: &Event) -> Option<(Pref, String)> {
1084    let d = event.tags.identifier().unwrap_or_default().to_string();
1085    let pref = Pref::from_d_tag(&d)?;
1086    let json = decrypt_event(my_pk, event).await?;
1087    if pref == Pref::Settings {
1088        let copy = RelayCopy { json, created_at: event.created_at.as_secs() };
1089        let adopted = match adopt_settings(Some(&copy)) {
1090            Ok(adopted) => adopted,
1091            Err(e) => {
1092                crate::log_warn!("[SyncedPrefs] adopting {} failed: {e}", pref.d_tag());
1093                return None;
1094            }
1095        };
1096        if adopted.publish {
1097            publish_settings_soon();
1098        }
1099        return adopted.json.map(|json| (pref, json));
1100    }
1101    if pref == Pref::Archive {
1102        return match adopt_archive(&json, event.created_at.as_secs()) {
1103            Ok(true) => {
1104                mark_hydrated(pref);
1105                Some((pref, json))
1106            }
1107            Ok(false) => None,
1108            Err(e) => {
1109                crate::log_warn!("[SyncedPrefs] persisting {} failed: {e}", pref.d_tag());
1110                None
1111            }
1112        };
1113    }
1114    let created_at = event.created_at.as_secs();
1115    if pref.is_layout() && !adopts_layout_copy(pref, created_at) {
1116        mark_hydrated(pref);
1117        return None;
1118    }
1119    if let Err(e) = save_local_raw(pref, &json) {
1120        crate::log_warn!("[SyncedPrefs] persisting {} failed: {e}", pref.d_tag());
1121        return None;
1122    }
1123    if pref.is_layout() {
1124        set_layout_seen(pref, created_at);
1125    }
1126    mark_hydrated(pref);
1127    Some((pref, json))
1128}
1129
1130// ============================================================================
1131// The rail's debounced publish
1132// ============================================================================
1133
1134/// How long the rail must sit still before its arrangement goes out.
1135///
1136/// Rearranging is burst activity: a minute of dragging communities in and out
1137/// of folders is ONE document at the end of it, not forty along the way. The
1138/// local mirror already holds every intermediate state, so nothing is at risk
1139/// while the timer runs.
1140const RAIL_PUBLISH_IDLE: std::time::Duration = std::time::Duration::from_millis(2500);
1141
1142/// Bumped by every edit of a layout. A sleeping publish that wakes to find a newer
1143/// generation was superseded mid-drag and simply stops, which is what collapses
1144/// a burst into one write.
1145struct RailPublishGen;
1146struct StartPublishGen;
1147
1148fn layout_gen(pref: Pref) -> std::sync::Arc<std::sync::atomic::AtomicU64> {
1149    if pref == Pref::Start {
1150        crate::db::current_session().scoped::<StartPublishGen, _>()
1151    } else {
1152        crate::db::current_session().scoped::<RailPublishGen, _>()
1153    }
1154}
1155
1156impl Pref {
1157    /// An arrangement the user drags about: saved at once, published once the dragging stops.
1158    fn is_layout(self) -> bool {
1159        matches!(self, Pref::Rail | Pref::Start)
1160    }
1161    fn dirty_key(self) -> &'static str {
1162        if self == Pref::Start { START_DIRTY_KEY } else { RAIL_DIRTY_KEY }
1163    }
1164    fn seen_key(self) -> &'static str {
1165        if self == Pref::Start { START_SEEN_KEY } else { RAIL_SEEN_KEY }
1166    }
1167}
1168
1169/// Whether a relay's copy of a layout replaces ours. Never over unsent edits, which are
1170/// newer than any copy out there and publish regardless; nor when it is no newer than one
1171/// we hold, since relays replay what they kept, in no order, and our own echo among it.
1172fn adopts_layout_copy(pref: Pref, created_at: u64) -> bool {
1173    !layout_is_dirty(pref) && created_at > layout_seen(pref)
1174}
1175
1176/// The newest copy of a layout this device has adopted or published.
1177fn layout_seen(pref: Pref) -> u64 {
1178    crate::db::settings::get_sql_setting(pref.seen_key().to_string())
1179        .ok()
1180        .flatten()
1181        .and_then(|s| s.parse().ok())
1182        .unwrap_or(0)
1183}
1184
1185fn set_layout_seen(pref: Pref, at: u64) {
1186    if at > layout_seen(pref) {
1187        let _ = crate::db::settings::set_sql_setting(pref.seen_key().to_string(), at.to_string());
1188    }
1189}
1190
1191/// Whether a layout holds edits the relays have not seen.
1192pub fn layout_is_dirty(pref: Pref) -> bool {
1193    pref.is_layout()
1194        && crate::db::settings::get_sql_setting(pref.dirty_key().to_string())
1195        .ok()
1196        .flatten()
1197        .as_deref()
1198        == Some("1")
1199}
1200
1201fn set_layout_dirty(pref: Pref, dirty: bool) {
1202    let _ = crate::db::settings::set_sql_setting(
1203        pref.dirty_key().to_string(),
1204        if dirty { "1" } else { "0" }.to_string(),
1205    );
1206}
1207
1208/// Commit an arrangement: on disk now, on the relays once the dragging stops.
1209///
1210/// The local mirror is the truth the rail and the Main Menu paint from, so the UI
1211/// never waits on a relay to show a drag landing.
1212pub fn save_layout_debounced(pref: Pref, layout: &crate::rail_layout::RailLayout) -> Result<(), String> {
1213    if !pref.is_layout() {
1214        return Err(format!("{} is not a layout", pref.d_tag()));
1215    }
1216    save_local_raw(pref, &layout.to_json())?;
1217    set_layout_dirty(pref, true);
1218    schedule_layout_publish(pref);
1219    Ok(())
1220}
1221
1222fn schedule_layout_publish(pref: Pref) {
1223    let generation = layout_gen(pref).fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
1224    crate::db::spawn_bound(async move {
1225        crate::rt::time::sleep(RAIL_PUBLISH_IDLE).await;
1226        if layout_gen(pref).load(std::sync::atomic::Ordering::Relaxed) != generation {
1227            return;
1228        }
1229        flush_layout(pref).await;
1230    });
1231}
1232
1233/// Publish the arrangement if it has unsent edits.
1234///
1235/// A failure leaves the dirty flag set rather than retrying in a loop: the next
1236/// edit reschedules, and failing that the next boot does, because the flag is
1237/// persisted. That is also what covers a quit inside the debounce window — the
1238/// publish never ran, and the arrangement is not lost.
1239pub async fn flush_rail() {
1240    flush_layout(Pref::Rail).await
1241}
1242
1243pub async fn flush_layout(pref: Pref) {
1244    if !layout_is_dirty(pref) || !is_hydrated(pref) {
1245        return;
1246    }
1247    let (Some(client), Some(my_pk)) = (crate::state::nostr_client(), crate::state::my_public_key()) else { return };
1248    let generation = layout_gen(pref).load(std::sync::atomic::Ordering::Relaxed);
1249    let Some(json) = load_local_raw(pref) else { return };
1250    // Dated after every copy we hold, so ours is the newest wherever it lands.
1251    let at = crate::clock::timestamp().as_secs().max(layout_seen(pref) + 1);
1252    match send_list(&client, my_pk, pref, &json, Some(at)).await {
1253        // An edit made while this copy was out is still unsent; its own timer sends it.
1254        Ok(()) => {
1255            set_layout_seen(pref, at);
1256            if layout_gen(pref).load(std::sync::atomic::Ordering::Relaxed) == generation {
1257                set_layout_dirty(pref, false);
1258            }
1259        }
1260        Err(e) => crate::log_warn!("[SyncedPrefs] {} publish deferred: {e}", pref.d_tag()),
1261    }
1262}
1263
1264#[cfg(test)]
1265mod tests {
1266    use super::*;
1267
1268    #[test]
1269    fn d_tags_round_trip_and_are_distinct() {
1270        for p in ALL_PREFS {
1271            assert_eq!(Pref::from_d_tag(p.d_tag()), Some(p));
1272        }
1273        // A tag belonging to another 30078 list must not resolve here, or the
1274        // self-sync router would hand a Community List to the block ingest.
1275        assert_eq!(Pref::from_d_tag("vector/communities"), None);
1276        assert_eq!(Pref::from_d_tag("vector/pinned"), None);
1277        assert_eq!(Pref::from_d_tag(""), None);
1278    }
1279
1280    #[test]
1281    fn an_archive_is_revoked_only_by_later_activity() {
1282        let mut m = ArchiveMap::default();
1283        m.set("npub1a", 1_000).unwrap();
1284        assert!(!m.revoke("npub1a", 1_000), "activity at the archive moment is what was archived");
1285        assert!(!m.revoke("npub1a", 900));
1286        assert!(!m.revoke("npub1b", 5_000), "nothing to revoke");
1287        assert!(m.revoke("npub1a", 1_001));
1288        assert!(m.chats.is_empty());
1289        assert!(m.set(" ", 1).is_err());
1290    }
1291
1292    #[test]
1293    fn an_archive_keeps_what_a_newer_build_wrote() {
1294        let mut m = ArchiveMap::default();
1295        m.set("npub1a", 1_700_000_000_123).unwrap();
1296        assert_eq!(ArchiveMap::from_json(&m.to_json()), m);
1297        assert_eq!(ArchiveMap::from_json("not json"), ArchiveMap::default());
1298        assert_eq!(ArchiveMap::from_json("{}").v, 1);
1299
1300        let newer = r#"{"v":1,"chats":{"npub1a":5,"npub1b":{"at":7,"why":"x"}},"folders":[1]}"#;
1301        let m = ArchiveMap::from_json(newer);
1302        assert_eq!(m.at("npub1a"), Some(5));
1303        assert_eq!(m.at("npub1b"), None, "a shape this build can't read is not archived here");
1304        assert_eq!(m.times().len(), 1);
1305        let back: serde_json::Value = serde_json::from_str(&m.to_json()).unwrap();
1306        assert_eq!(back["chats"]["npub1b"]["why"], "x", "and survives our republish");
1307        assert_eq!(back["folders"], serde_json::json!([1]));
1308    }
1309
1310    #[test]
1311    fn the_archive_caps_new_chats_but_not_existing_ones() {
1312        let mut m = ArchiveMap::default();
1313        for i in 0..ARCHIVE_MAX_ENTRIES {
1314            m.set(&format!("npub1{i}"), 1).unwrap();
1315        }
1316        assert!(m.set("npub1new", 1).is_err());
1317        assert!(m.set("npub10", 2).is_ok(), "re-archiving a chat already held still works");
1318        let mut full = ArchiveMap::default();
1319        for i in 0..ARCHIVE_MAX_ENTRIES {
1320            full.set(&format!("npub1{:058}", i), 1_760_000_000_000).unwrap();
1321        }
1322        // NIP-44: padded plaintext plus version, nonce, length prefix and MAC, then base64.
1323        let len = full.to_json().len();
1324        let next = (len - 1).next_power_of_two();
1325        let chunk = if next <= 256 { 32 } else { next / 8 };
1326        let padded = chunk * ((len - 1) / chunk + 1);
1327        let content = (padded + 67).div_ceil(3) * 4;
1328        assert!(content + 1024 < 65_536, "a full archive fits a relay's default 64KB event cap ({content} bytes)");
1329    }
1330
1331    #[test]
1332    fn archiving_waits_for_the_relay_copy_but_forgetting_does_not() {
1333        let (_tmp, _guard) = init_test_db();
1334        assert!(set_archived("npub1a", Some(10)).is_err(), "would publish over the other devices' archive");
1335        assert!(adopt_archive(r#"{"v":1,"chats":{"npub1a":10}}"#, 100).unwrap());
1336        let (map, changed) = revoke_archive("npub1a", 11).unwrap();
1337        assert!(changed && map.chats.is_empty(), "an outlived entry goes without the relay copy");
1338        mark_hydrated(Pref::Archive);
1339        assert_eq!(set_archived("npub1a", Some(20)).unwrap().at("npub1a"), Some(20));
1340        let (_, changed) = revoke_archive("npub1a", 15).unwrap();
1341        assert!(!changed, "a re-archive outlives a message older than it");
1342    }
1343
1344    #[test]
1345    fn an_older_archive_copy_never_replaces_a_newer_one() {
1346        let (_tmp, _guard) = init_test_db();
1347        assert!(adopt_archive(r#"{"v":1,"chats":{"npub1p":1}}"#, 200).unwrap());
1348        assert!(!adopt_archive(r#"{"v":1,"chats":{"npub1x":1}}"#, 150).unwrap(), "a relay replaying last week");
1349        assert_eq!(load_archive().at("npub1p"), Some(1));
1350        assert!(load_archive().at("npub1x").is_none());
1351        let (_, at) = claim_archive_publish(100).unwrap();
1352        assert!(at > 200, "our publish lands after every copy we hold");
1353        assert!(!adopt_archive(r#"{"v":1,"chats":{}}"#, at - 1).unwrap(), "nor does one signed before ours");
1354    }
1355
1356    #[test]
1357    fn id_lists_add_idempotently_and_remove_tolerantly() {
1358        let mut l = IdList::default();
1359        l.add("npub1a").unwrap();
1360        l.add("npub1a").unwrap();
1361        assert_eq!(l.ids.len(), 1, "a second add is not a second entry");
1362        l.remove("never-present");
1363        l.remove("npub1a");
1364        assert!(l.ids.is_empty());
1365        assert!(l.add("  ").is_err(), "an empty id is refused, not stored");
1366    }
1367
1368    #[test]
1369    fn an_empty_nickname_clears_rather_than_storing_a_blank() {
1370        let mut n = NicknameMap::default();
1371        n.set("npub1a", "Landlord").unwrap();
1372        assert_eq!(n.names.get("npub1a").map(String::as_str), Some("Landlord"));
1373        n.set("npub1a", "").unwrap();
1374        assert!(!n.names.contains_key("npub1a"), "clearing removes the key, not blanks it");
1375    }
1376
1377    #[test]
1378    fn malformed_payloads_degrade_to_empty_instead_of_erroring() {
1379        assert!(IdList::from_json("not json").ids.is_empty());
1380        assert!(IdList::from_json("{}").ids.is_empty());
1381        assert!(NicknameMap::from_json("[]").names.is_empty());
1382        // An unknown version still yields its entries rather than being dropped.
1383        let future = IdList::from_json("{\"v\":99,\"ids\":[\"a\"],\"extra\":1}");
1384        assert_eq!(future.ids, vec!["a".to_string()]);
1385    }
1386
1387    #[test]
1388    fn lists_refuse_to_grow_past_the_event_ceiling() {
1389        let npub = |i: usize| format!("npub1{i:0>58}");
1390        let mut l = IdList::default();
1391        let mut n = 0;
1392        while l.add(&npub(n)).is_ok() {
1393            n += 1;
1394        }
1395        assert!(n > 500, "a full list still holds hundreds of npubs, held {n}");
1396        assert_eq!(l.ids.len(), n, "the refused entry is not kept");
1397        assert!(fits(&l.to_json()));
1398        // Removing frees a slot again.
1399        l.remove(&npub(0));
1400        assert!(l.add(&npub(n)).is_ok());
1401
1402        // Every list, at its fullest, is an event a relay takes.
1403        let me = nostr_sdk::prelude::Keys::generate();
1404        let mut names = NicknameMap::default();
1405        let mut i = 0;
1406        while names.set(&npub(i), &"\"".repeat(16)).is_ok() {
1407            i += 1;
1408        }
1409        let mut notify = NotifyMap::default();
1410        let mut j = 0;
1411        let widest = NotifyEntry { level: Some("mentions".into()), mute_until: i64::MAX, suppress_everyone: Some(true) };
1412        while notify.set(&format!("{j:0>64}"), widest.clone()).is_ok() {
1413            j += 1;
1414        }
1415        for json in [l.to_json(), names.to_json(), notify.to_json()] {
1416            let ck = nostr_sdk::prelude::nip44::v2::ConversationKey::derive(me.secret_key(), &me.public_key()).unwrap();
1417            let ct = crate::community::cipher::encrypt_with_random_nonce(&ck, json.as_bytes()).unwrap();
1418            let ev = nostr_sdk::prelude::EventBuilder::new(nostr_sdk::prelude::Kind::Custom(30078), crate::simd::base64::STANDARD.encode_to_string(&ct))
1419                .tag(nostr_sdk::prelude::Tag::identifier("vector/blocks"))
1420                .finalize(&me)
1421                .unwrap();
1422            assert!(crate::event_size::check(&ev).is_ok(), "{} bytes", ev.as_json().len());
1423        }
1424    }
1425
1426    #[test]
1427    fn settings_keep_keys_this_build_does_not_know() {
1428        let mut s = SyncedSettings::from_json("{\"v\":1,\"advanced\":false,\"future\":{\"a\":1}}");
1429        assert!(!s.advanced);
1430        s.advanced = true;
1431        let back = SyncedSettings::from_json(&s.to_json());
1432        assert!(back.advanced);
1433        assert_eq!(back.other.get("future"), Some(&serde_json::json!({ "a": 1 })), "a newer device's key survives our republish");
1434        assert!(SyncedSettings::from_json("not json") == SyncedSettings::default());
1435        assert!(!SyncedSettings::default().to_json().contains("advanced"), "off is the absent default");
1436    }
1437
1438    #[test]
1439    fn streamer_keys_this_build_does_not_know_survive_too() {
1440        let json = r#"{"v":1,"streamer":{"on":true,"seed":"ab","notif":"hide_all","tint":3},"future":1}"#;
1441        let mut s = SyncedSettings::from_json(json);
1442        assert!(s.streamer.on);
1443        assert_eq!(s.streamer.notif, "hide_all");
1444        s.advanced = true;
1445        let back = SyncedSettings::from_json(&s.to_json());
1446        assert_eq!(back.streamer.other.get("tint"), Some(&serde_json::json!(3)));
1447        assert_eq!(back.other.get("future"), Some(&serde_json::json!(1)));
1448        assert!(!back.other.contains_key("streamer"), "a known key is not double-carried");
1449    }
1450
1451    #[test]
1452    fn streamer_defaults_stay_off_the_wire_and_on_the_view() {
1453        let s = SyncedSettings::from_json(r#"{"v":1}"#);
1454        assert_eq!(s.streamer.notif, "none");
1455        assert!(!s.to_json().contains("streamer"));
1456        assert_eq!(
1457            s.view(),
1458            serde_json::json!({ "advanced": false, "players": true, "streamer": { "on": false, "seed": "", "notif": "none", "hide_wallpapers": true } })
1459        );
1460    }
1461
1462    #[test]
1463    fn wallpapers_hide_by_default_and_showing_them_is_kept_through_adoption() {
1464        let (_tmp, _guard) = init_test_db();
1465        assert!(SyncedSettings::from_json(r#"{"v":1,"streamer":{"on":true}}"#).streamer.hide_wallpapers);
1466        set_streamer_wallpapers(false).unwrap();
1467        assert!(SyncedSettings::from_json(&load_settings().to_json()).streamer.other.is_empty());
1468        assert!(load_settings().to_json().contains(r#""hide_wallpapers":false"#), "off is the one value on the wire");
1469        let adopted = adopt_settings(Some(&copy(r#"{"v":1,"streamer":{"on":true,"seed":"ab"}}"#, 100))).unwrap();
1470        assert!(adopted.publish, "the relays lack it");
1471        let held = load_settings().streamer;
1472        assert!(held.on && !held.hide_wallpapers, "theirs and ours both stand");
1473    }
1474
1475    #[test]
1476    fn players_default_on_and_switching_them_off_is_kept_through_adoption() {
1477        let (_tmp, _guard) = init_test_db();
1478        assert!(!SyncedSettings::default().players_off && !SyncedSettings::from_json("not json").players_off);
1479        set_players(false).unwrap();
1480        assert!(load_settings().to_json().contains(r#""players_off":true"#), "off is the one value on the wire");
1481        let adopted = adopt_settings(Some(&copy(r#"{"v":1,"advanced":true}"#, 100))).unwrap();
1482        assert!(adopted.publish, "the relays lack it");
1483        let held = load_settings();
1484        assert!(held.advanced && held.players_off, "theirs and ours both stand");
1485        set_players(true).unwrap();
1486        assert!(!load_settings().to_json().contains("players_off"));
1487    }
1488
1489    #[test]
1490    fn going_live_reseeds_and_staying_live_does_not() {
1491        let mut s = StreamerSettings::default();
1492        s.set_on(true);
1493        let first = s.seed.clone();
1494        assert_eq!(first.len(), 32);
1495        assert!(first.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)), "lowercase hex: {first}");
1496        s.set_on(true);
1497        assert_eq!(s.seed, first, "on to on keeps the colours");
1498        s.set_on(false);
1499        assert_eq!(s.seed, first, "stopping keeps the last seed");
1500        s.set_on(true);
1501        assert_ne!(s.seed, first, "each go-live reshuffles");
1502    }
1503
1504    #[test]
1505    fn the_overlay_takes_only_known_levels() {
1506        let mut s = StreamerSettings::default();
1507        for level in STREAMER_NOTIF_LEVELS {
1508            s.set_notif(level).unwrap();
1509            assert_eq!(s.notif, level);
1510        }
1511        assert!(s.set_notif("hide_everything").is_err());
1512        assert_eq!(s.notif, "hide_all", "a refused level changes nothing");
1513    }
1514
1515    #[test]
1516    fn every_synced_list_is_on_the_live_subscription() {
1517        let tags = live_d_tags();
1518        for p in ALL_PREFS {
1519            assert!(tags.contains(&p.d_tag().to_string()), "{} read at boot but never heard live", p.d_tag());
1520        }
1521        assert!(tags.contains(&crate::pinned_chats::PINNED_D_TAG.to_string()));
1522    }
1523
1524    #[tokio::test]
1525    async fn the_two_layouts_keep_their_own_edits_and_nothing_else_is_one() {
1526        let (_tmp, _guard) = init_test_db();
1527        let (start, changed) = edit_layout(Pref::Start, |l| crate::start_menu::pin(l, "nexus").map(|_| ())).unwrap();
1528        assert!(changed && start.contains("nexus"));
1529        assert!(layout_is_dirty(Pref::Start), "unsent until the dragging stops");
1530        assert!(!layout_is_dirty(Pref::Rail), "the rail's state is its own");
1531        assert!(load_rail().nodes.is_empty());
1532        let (_, changed) = edit_layout(Pref::Start, |l| crate::start_menu::pin(l, "nexus").map(|_| ())).unwrap();
1533        assert!(!changed, "an edit that moves nothing writes nothing");
1534        assert!(edit_layout(Pref::Blocks, |_| Ok(())).is_err());
1535        assert!(save_layout_debounced(Pref::Blocks, &start).is_err(), "a layout never lands in another list");
1536        assert!(!layout_is_dirty(Pref::Blocks));
1537    }
1538
1539    #[test]
1540    fn a_layout_takes_only_a_newer_copy_and_never_over_unsent_edits() {
1541        let (_tmp, _guard) = init_test_db();
1542        assert!(adopts_layout_copy(Pref::Start, 100), "a first copy is taken");
1543        set_layout_seen(Pref::Start, 100);
1544        assert!(!adopts_layout_copy(Pref::Start, 100), "our own echo changes nothing");
1545        assert!(!adopts_layout_copy(Pref::Start, 90), "a relay replaying the copy before");
1546        assert!(adopts_layout_copy(Pref::Start, 101));
1547        set_layout_seen(Pref::Start, 50);
1548        assert!(!adopts_layout_copy(Pref::Start, 99), "what we have seen only moves forward");
1549        assert!(adopts_layout_copy(Pref::Rail, 60), "each layout keeps its own");
1550        set_layout_dirty(Pref::Start, true);
1551        assert!(!adopts_layout_copy(Pref::Start, 999), "unsent edits outrank any copy");
1552    }
1553
1554    #[test]
1555    fn a_layout_repeating_a_key_loads_once_each() {
1556        let (_tmp, _guard) = init_test_db();
1557        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();
1558        assert_eq!(load_start().flatten(), vec!["nexus".to_string(), "requests".to_string(), "settings".to_string()]);
1559    }
1560
1561    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
1562        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1563        crate::db::close_database();
1564        crate::db::clear_id_caches();
1565        let tmp = tempfile::tempdir().unwrap();
1566        let account = Keys::generate().public_key().to_bech32().unwrap();
1567        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
1568        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
1569        crate::db::set_current_account(account.clone()).unwrap();
1570        crate::db::init_database(&account).unwrap();
1571        (tmp, guard)
1572    }
1573
1574    fn copy(json: &str, created_at: u64) -> RelayCopy {
1575        RelayCopy { json: json.to_string(), created_at }
1576    }
1577
1578    #[test]
1579    fn a_go_live_before_hydration_outlasts_the_relay_copy_and_is_published() {
1580        let (_tmp, _guard) = init_test_db();
1581        assert!(!is_hydrated(Pref::Settings));
1582        assert!(set_advanced(true).is_err(), "Advanced Mode still waits for the relay copy");
1583
1584        let live = set_streamer_on(true).expect("never refused before hydration");
1585        set_streamer_notif("hide_sender").unwrap();
1586        assert!(load_settings().streamer.on, "in effect at once");
1587        let seed = live.streamer.seed.clone();
1588
1589        let relay = r#"{"v":1,"advanced":true,"streamer":{"on":false,"seed":"00","notif":"none"},"future":1}"#;
1590        let adopted = adopt_settings(Some(&copy(relay, 100))).unwrap();
1591        assert!(adopted.publish, "the relays lack our change");
1592        assert!(is_hydrated(Pref::Settings));
1593
1594        let held = load_settings();
1595        assert!(held.streamer.on && held.advanced, "ours and theirs both stand");
1596        assert_eq!(held.streamer.seed, seed, "the colours on screen are kept");
1597        assert_eq!(held.streamer.notif, "hide_sender");
1598        assert_eq!(held.other.get("future"), Some(&serde_json::json!(1)));
1599        assert_eq!(adopted.json.as_deref(), Some(held.to_json().as_str()), "the page is shown the merge");
1600
1601        assert!(load_intent().is_some(), "held until the relays have it");
1602        let (json, at) = claim_publish(100);
1603        assert!(at > 100, "signed after the copy it supersedes");
1604        settings_published(&json, at);
1605        assert!(load_intent().is_none());
1606        let echo = adopt_settings(Some(&copy(&json, at))).unwrap();
1607        assert!(!echo.publish, "our own echo is never answered");
1608    }
1609
1610    #[test]
1611    fn an_echo_that_beats_the_publish_ack_retires_the_intent() {
1612        let (_tmp, _guard) = init_test_db();
1613        set_streamer_on(true).unwrap();
1614        let (json, at) = claim_publish(100);
1615        let adopted = adopt_settings(Some(&copy(&json, at))).unwrap();
1616        assert!(!adopted.publish);
1617        assert!(load_intent().is_none());
1618    }
1619
1620    #[test]
1621    fn with_no_relay_copy_a_held_change_is_published_as_is() {
1622        let (_tmp, _guard) = init_test_db();
1623        set_streamer_notif("hide_all").unwrap();
1624        let adopted = adopt_settings(None).unwrap();
1625        assert!(adopted.publish);
1626        assert_eq!(load_settings().streamer.notif, "hide_all");
1627    }
1628
1629    #[test]
1630    fn with_nothing_held_hydration_publishes_nothing() {
1631        let (_tmp, _guard) = init_test_db();
1632        assert!(!adopt_settings(None).unwrap().publish);
1633        assert!(!adopt_settings(Some(&copy(r#"{"v":1,"advanced":true}"#, 100))).unwrap().publish);
1634        assert!(load_settings().advanced);
1635    }
1636
1637    #[test]
1638    fn a_change_made_while_the_publish_is_pending_rides_the_intent() {
1639        let (_tmp, _guard) = init_test_db();
1640        set_streamer_on(true).unwrap();
1641        adopt_settings(Some(&copy(r#"{"v":1}"#, 100))).unwrap();
1642        set_streamer_notif("hide_content").unwrap();
1643        // A relay copy without it, after a failed publish and a restart.
1644        let adopted = adopt_settings(Some(&copy(r#"{"v":1}"#, 100))).unwrap();
1645        assert!(adopted.publish);
1646        assert_eq!(load_settings().streamer.notif, "hide_content");
1647        assert!(load_settings().streamer.on);
1648    }
1649
1650    #[test]
1651    fn a_go_live_after_hydration_outlasts_a_failed_publish() {
1652        let (_tmp, _guard) = init_test_db();
1653        adopt_settings(Some(&copy(r#"{"v":1}"#, 100))).unwrap();
1654        set_streamer_on(true).unwrap();
1655        // The publish never landed; the next boot reads the old copy back.
1656        let adopted = adopt_settings(Some(&copy(r#"{"v":1}"#, 100))).unwrap();
1657        assert!(adopted.publish, "the go-live is published again");
1658        assert!(load_settings().streamer.on, "and is not undone meanwhile");
1659    }
1660
1661    #[test]
1662    fn an_older_copy_never_rolls_the_settings_back() {
1663        let (_tmp, _guard) = init_test_db();
1664        let on = r#"{"v":1,"streamer":{"on":true,"seed":"ab","notif":"hide_all"}}"#;
1665        adopt_settings(Some(&copy(on, 200))).unwrap();
1666        let off = r#"{"v":1,"streamer":{"on":false,"seed":"ab","notif":"none"}}"#;
1667        let late = adopt_settings(Some(&copy(off, 150))).unwrap();
1668        assert!(late.stale && late.json.is_none() && !late.publish);
1669        let held = load_settings();
1670        assert!(held.streamer.on);
1671        assert_eq!(held.streamer.notif, "hide_all");
1672        // A sibling's genuinely newer change still lands.
1673        assert!(adopt_settings(Some(&copy(off, 201))).unwrap().json.is_some());
1674        assert!(!load_settings().streamer.on);
1675    }
1676
1677    #[test]
1678    fn publishes_inside_one_second_are_signed_in_order() {
1679        let (_tmp, _guard) = init_test_db();
1680        adopt_settings(Some(&copy(r#"{"v":1}"#, 1_000))).unwrap();
1681        set_streamer_on(true).unwrap();
1682        let (first, a) = claim_publish(1_000);
1683        set_streamer_on(false).unwrap();
1684        let (_, b) = claim_publish(1_000);
1685        set_streamer_on(true).unwrap();
1686        let (last, c) = claim_publish(1_000);
1687        assert!(a > 1_000 && b > a && c > b, "{a} {b} {c}");
1688
1689        // The acks land in any order; only the one matching what is held retires the intent.
1690        settings_published(&first, a);
1691        assert!(load_intent().is_some(), "the first publish is not what is held now");
1692        settings_published(&last, c);
1693        assert!(load_intent().is_none());
1694
1695        // The echo of the middle publish arrives last and changes nothing.
1696        let off = SyncedSettings::from_json(&last);
1697        let mut off = off.clone();
1698        off.streamer.on = false;
1699        let echo = adopt_settings(Some(&copy(&off.to_json(), b))).unwrap();
1700        assert!(echo.stale);
1701        assert!(load_settings().streamer.on, "still live after the late echo");
1702
1703        // A restart re-reads an older relay copy: ignored, and hydration republishes ours.
1704        let reread = adopt_settings(Some(&copy(&first, a))).unwrap();
1705        assert!(reread.stale);
1706        assert_eq!(load_settings().to_json(), last);
1707    }
1708
1709    #[test]
1710    fn an_earlier_go_live_echoing_back_keeps_the_latest_seed() {
1711        let (_tmp, _guard) = init_test_db();
1712        adopt_settings(Some(&copy(r#"{"v":1}"#, 100))).unwrap();
1713        set_streamer_on(true).unwrap();
1714        let (first, a) = claim_publish(100);
1715        set_streamer_on(false).unwrap();
1716        let latest = set_streamer_on(true).unwrap().streamer.seed;
1717        let echo = adopt_settings(Some(&copy(&first, a))).unwrap();
1718        assert!(echo.publish, "the relays hold an older go-live");
1719        let held = load_settings().streamer;
1720        assert!(held.on);
1721        assert_eq!(held.seed, latest, "the colours on screen now are kept");
1722    }
1723
1724    #[test]
1725    fn advanced_mode_rides_the_intent_too() {
1726        let (_tmp, _guard) = init_test_db();
1727        adopt_settings(Some(&copy(r#"{"v":1}"#, 100))).unwrap();
1728        set_advanced(true).unwrap();
1729        let adopted = adopt_settings(Some(&copy(r#"{"v":1}"#, 100))).unwrap();
1730        assert!(adopted.publish);
1731        assert!(load_settings().advanced);
1732    }
1733
1734    #[test]
1735    fn nickname_order_is_stable_across_a_round_trip() {
1736        // BTreeMap, so two devices building the same set emit identical bytes —
1737        // no spurious republish churn from map iteration order.
1738        let mut a = NicknameMap::default();
1739        a.set("npub1z", "Zed").unwrap();
1740        a.set("npub1a", "Ann").unwrap();
1741        let mut b = NicknameMap::default();
1742        b.set("npub1a", "Ann").unwrap();
1743        b.set("npub1z", "Zed").unwrap();
1744        assert_eq!(a.to_json(), b.to_json(), "insertion order must not change the wire form");
1745    }
1746}