Skip to main content

vector_core/profile/
sync.rs

1//! Profile sync — priority queue, background processor, and relay fetching.
2//!
3//! The sync queue batches profile fetches by priority (Critical → High → Medium → Low),
4//! with cache windows to avoid hammering relays. The background processor
5//! drains the queue and calls `load_profile` for each entry.
6//!
7//! Platform-specific work (DB persistence, image caching) is handled by the
8//! `ProfileSyncHandler` trait — src-tauri provides `TauriProfileSyncHandler`,
9//! CLI provides a no-op or logging implementation.
10
11use std::collections::{HashMap, HashSet, VecDeque};
12use std::sync::{Arc, Mutex};
13use std::time::Duration;
14use web_time::Instant;
15
16use nostr_sdk::prelude::*;
17
18use crate::compact::{secs_from_compact, secs_to_compact};
19use crate::profile::Profile;
20use crate::state::{nostr_client, my_public_key, STATE};
21use crate::traits::emit_event;
22
23// ============================================================================
24// SyncPriority
25// ============================================================================
26
27/// Priority levels for profile syncing, most urgent first (`Critical < Low`).
28#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]
29pub enum SyncPriority {
30    Critical,  // No metadata OR user clicked — fetch immediately
31    High,      // Active chats — fetch soon
32    Medium,    // Recent chats — fetch eventually
33    Low,       // Old chats with metadata — passive refresh
34}
35
36impl SyncPriority {
37    /// Cache window duration — how long before a profile can be re-fetched.
38    pub fn cache_window(&self) -> Duration {
39        match self {
40            SyncPriority::Critical => Duration::from_secs(0),
41            SyncPriority::High => Duration::from_secs(5 * 60),
42            SyncPriority::Medium => Duration::from_secs(30 * 60),
43            SyncPriority::Low => Duration::from_secs(24 * 60 * 60),
44        }
45    }
46
47    /// Processing delay — how long after queuing before fetching.
48    pub fn processing_delay(&self) -> Duration {
49        match self {
50            SyncPriority::Critical => Duration::from_secs(0),
51            SyncPriority::High => Duration::from_secs(5),
52            SyncPriority::Medium => Duration::from_secs(30),
53            SyncPriority::Low => Duration::from_secs(5 * 60),
54        }
55    }
56
57    /// Maximum batch size for this priority.
58    pub fn batch_size(&self) -> usize {
59        match self {
60            SyncPriority::Critical => 10,
61            SyncPriority::High => 20,
62            SyncPriority::Medium => 30,
63            SyncPriority::Low => 50,
64        }
65    }
66}
67
68// ============================================================================
69// QueueEntry
70// ============================================================================
71
72#[derive(Debug, Clone)]
73pub(crate) struct QueueEntry {
74    npub: String,
75    added_at: Instant,
76    /// Matches `ProfileSyncQueue::queued` while this is the npub's live entry; a re-add
77    /// supersedes it in place rather than sweeping the lanes for it.
78    gen: u64,
79}
80
81// ============================================================================
82// ProfileSyncQueue
83// ============================================================================
84
85/// Profile sync queue manager with four priority lanes.
86pub struct ProfileSyncQueue {
87    critical_queue: VecDeque<QueueEntry>,
88    high_queue: VecDeque<QueueEntry>,
89    medium_queue: VecDeque<QueueEntry>,
90    low_queue: VecDeque<QueueEntry>,
91    /// Each waiting npub's live entry generation and lane. Superseded entries stay in their
92    /// lane and are dropped when they reach its front.
93    queued: HashMap<String, (u64, SyncPriority)>,
94    next_gen: u64,
95    processing: HashSet<String>,
96    /// Seconds after `epoch` each npub was last fetched; pruned past the longest cache window.
97    last_fetched: crate::profile::NpubMap<u32>,
98    epoch: Instant,
99    done_since_prune: u32,
100    is_processing: bool,
101}
102
103/// `mark_done` calls between sweeps of `last_fetched`.
104const PRUNE_EVERY: u32 = 256;
105
106impl Default for ProfileSyncQueue {
107    fn default() -> Self { Self::new() }
108}
109
110impl ProfileSyncQueue {
111    pub fn new() -> Self {
112        Self {
113            critical_queue: VecDeque::new(),
114            high_queue: VecDeque::new(),
115            medium_queue: VecDeque::new(),
116            low_queue: VecDeque::new(),
117            queued: HashMap::new(),
118            next_gen: 0,
119            processing: HashSet::new(),
120            last_fetched: Default::default(),
121            epoch: Instant::now(),
122            done_since_prune: 0,
123            is_processing: false,
124        }
125    }
126
127    /// Add a profile to the sync queue.
128    pub fn add(&mut self, npub: impl AsRef<str> + Into<String>, priority: SyncPriority, force_refresh: bool) {
129        let key = npub.as_ref();
130        if self.processing.contains(key) {
131            return;
132        }
133        // An entry already waiting at this priority or higher keeps its place and age: a
134        // periodic re-add would otherwise restart the delay and never let a Low entry ripen.
135        if self.queued.get(key).is_some_and(|&(_, waiting)| waiting <= priority) {
136            return;
137        }
138
139        // Check cache window (unless force_refresh)
140        if !force_refresh {
141            if let Some(&fetched_at) = self.last_fetched.get(key) {
142                if u64::from(self.secs().saturating_sub(fetched_at)) < priority.cache_window().as_secs() {
143                    return;
144                }
145            }
146        }
147
148        let npub: String = npub.into();
149        self.next_gen += 1;
150        let gen = self.next_gen;
151        self.queued.insert(npub.clone(), (gen, priority));
152
153        let entry = QueueEntry { npub, added_at: Instant::now(), gen };
154        // Re-adds while the processor is stalled (offline) would otherwise grow the lanes
155        // without bound; one sweep once stale entries outnumber live ones keeps them linear.
156        let len = self.critical_queue.len() + self.high_queue.len() + self.medium_queue.len() + self.low_queue.len();
157        if len > 2 * self.queued.len() + 64 {
158            for lane in [&mut self.critical_queue, &mut self.high_queue, &mut self.medium_queue, &mut self.low_queue] {
159                lane.retain(|e| Self::is_live(&self.queued, e));
160            }
161        }
162        match priority {
163            SyncPriority::Critical => self.critical_queue.push_back(entry),
164            SyncPriority::High => self.high_queue.push_back(entry),
165            SyncPriority::Medium => self.medium_queue.push_back(entry),
166            SyncPriority::Low => self.low_queue.push_back(entry),
167        }
168        PROCESSOR_WAKE.notify_one();
169    }
170
171    /// How long until [`Self::get_next_batch`] has something to return; `None` when every lane
172    /// is empty. Mirrors its lane choice: a waiting higher lane holds the lower ones back.
173    fn next_ready_in(&mut self) -> Option<Duration> {
174        self.prune_fronts();
175        [
176            (&self.critical_queue, SyncPriority::Critical),
177            (&self.high_queue, SyncPriority::High),
178            (&self.medium_queue, SyncPriority::Medium),
179            (&self.low_queue, SyncPriority::Low),
180        ]
181        .into_iter()
182        .find_map(|(lane, p)| lane.front().map(|e| p.processing_delay().saturating_sub(e.added_at.elapsed())))
183    }
184
185    fn is_live(queued: &HashMap<String, (u64, SyncPriority)>, e: &QueueEntry) -> bool {
186        queued.get(&e.npub).is_some_and(|&(gen, _)| gen == e.gen)
187    }
188
189    /// Drop superseded entries from the front of every lane, so a non-empty lane has a
190    /// live entry first.
191    fn prune_fronts(&mut self) {
192        for lane in [&mut self.critical_queue, &mut self.high_queue, &mut self.medium_queue, &mut self.low_queue] {
193            while lane.front().is_some_and(|e| !Self::is_live(&self.queued, e)) {
194                lane.pop_front();
195            }
196        }
197    }
198
199    /// Drop every queued + in-flight entry. Used by `reset_session()` so a
200    /// post-reset processor doesn't keep fetching the prior account's contacts.
201    pub fn clear(&mut self) {
202        self.critical_queue.clear();
203        self.high_queue.clear();
204        self.medium_queue.clear();
205        self.low_queue.clear();
206        self.queued.clear();
207        self.processing.clear();
208        self.last_fetched.clear();
209    }
210
211    /// Get the next batch of profiles ready to process (highest priority first).
212    pub(crate) fn get_next_batch(&mut self) -> Vec<QueueEntry> {
213        let mut batch = Vec::new();
214        self.prune_fronts();
215
216        let (queue, priority) = if !self.critical_queue.is_empty() {
217            (&mut self.critical_queue, SyncPriority::Critical)
218        } else if !self.high_queue.is_empty() {
219            (&mut self.high_queue, SyncPriority::High)
220        } else if !self.medium_queue.is_empty() {
221            (&mut self.medium_queue, SyncPriority::Medium)
222        } else if !self.low_queue.is_empty() {
223            (&mut self.low_queue, SyncPriority::Low)
224        } else {
225            return batch;
226        };
227
228        let batch_size = priority.batch_size();
229        let processing_delay = priority.processing_delay();
230
231        while batch.len() < batch_size {
232            let Some(entry) = queue.front() else { break };
233            if !Self::is_live(&self.queued, entry) {
234                queue.pop_front();
235                continue;
236            }
237            if entry.added_at.elapsed() < processing_delay {
238                break;
239            }
240            let entry = queue.pop_front().unwrap();
241            self.queued.remove(&entry.npub);
242            batch.push(entry);
243        }
244
245        batch
246    }
247
248    pub fn mark_processing(&mut self, npub: &str) {
249        self.processing.insert(npub.to_string());
250    }
251
252    pub fn mark_done(&mut self, npub: &str) {
253        self.processing.remove(npub);
254        let now = self.secs();
255        self.last_fetched.insert(npub, now);
256        self.done_since_prune += 1;
257        if self.done_since_prune >= PRUNE_EVERY {
258            self.done_since_prune = 0;
259            self.prune_fetched(now);
260        }
261    }
262
263    /// Forget fetches older than every cache window: they no longer hold anything back.
264    fn prune_fetched(&mut self, now: u32) {
265        let window = [SyncPriority::Critical, SyncPriority::High, SyncPriority::Medium, SyncPriority::Low]
266            .map(|p| p.cache_window().as_secs())
267            .into_iter()
268            .max()
269            .unwrap_or(0);
270        self.last_fetched.retain(|&at| u64::from(now.saturating_sub(at)) < window);
271    }
272
273    fn secs(&self) -> u32 {
274        u32::try_from(self.epoch.elapsed().as_secs()).unwrap_or(u32::MAX)
275    }
276}
277
278// ============================================================================
279// Global queue
280// ============================================================================
281
282/// Queued work for THIS account's contacts. The processor loop is
283/// process-lifetime and services whichever queue the live session holds, so a
284/// swap leaves the prior account's entries behind rather than fetching them.
285struct ProfileSyncQueueKey;
286
287fn profile_sync_queue() -> Arc<Mutex<ProfileSyncQueue>> {
288    crate::db::current_session().scoped::<ProfileSyncQueueKey, _>()
289}
290
291/// Wakes the idle processor when an entry is queued. Process-wide like the processor itself; a
292/// stored permit covers an add that lands between its last look and its wait.
293static PROCESSOR_WAKE: tokio::sync::Notify = tokio::sync::Notify::const_new();
294
295/// Wake the idle processor to look at the live session's queue: entries added before that
296/// session went live woke it against the previous one.
297pub(crate) fn wake_processor() {
298    #[cfg(test)]
299    SESSION_WAKES.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
300    PROCESSOR_WAKE.notify_one();
301}
302
303/// Wakes sent by [`wake_processor`], apart from the ones queue adds send.
304#[cfg(test)]
305pub(crate) static SESSION_WAKES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
306
307// ============================================================================
308// ProfileSyncHandler — platform-specific callbacks
309// ============================================================================
310
311/// Callback trait for platform-specific profile sync work.
312///
313/// The core `load_profile` handles relay fetching, STATE updates, and
314/// EventEmitter notifications. This trait covers what differs per platform:
315/// - **DB persistence** (SQLite upsert)
316/// - **Image caching** (avatar/banner download + disk cache)
317pub trait ProfileSyncHandler: Send + Sync {
318    /// Called after a profile is fetched from relays and updated in STATE.
319    /// `slim` is ready for DB persistence. `avatar_url`/`banner_url` are
320    /// for image caching (may be empty).
321    fn on_profile_fetched(&self, _slim: &crate::SlimProfile, _avatar_url: &str, _banner_url: &str) {}
322
323    /// Delete a blocked profile's cached pictures from disk. No other profile points at them.
324    fn forget_images(&self, _images: Vec<super::CachedImage>) {}
325}
326
327/// `images` less any file another unblocked profile still shows: the cache is keyed by URL,
328/// so two profiles can share one copy.
329pub(crate) fn unshared(state: &crate::state::ChatState, owner: u16, images: Vec<super::CachedImage>) -> Vec<super::CachedImage> {
330    images
331        .into_iter()
332        .filter(|img| {
333            !state.profiles.iter().any(|p| {
334                p.id != owner && !p.flags.is_blocked() && (*p.avatar_cached() == *img.path || *p.banner_cached() == *img.path)
335            })
336        })
337        .collect()
338}
339
340/// No-op handler for CLI/tests.
341pub struct NoOpProfileSyncHandler;
342impl ProfileSyncHandler for NoOpProfileSyncHandler {}
343
344// ============================================================================
345// load_profile — core relay fetch + STATE update
346// ============================================================================
347
348/// The newest kind-0 the relays hold for `pubkey`, or `None` when they hold none.
349async fn fetch_newest_metadata(client: &Client, pubkey: PublicKey) -> Result<Option<Metadata>, String> {
350    // `Client::fetch_metadata` is gone: fetch the newest kind-0 and parse it.
351    client
352        .fetch_events(Filter::new().author(pubkey).kind(Kind::Metadata).limit(1))
353        .timeout(crate::relay_request_timeout(Duration::from_secs(15)))
354        .await
355        .map(|events| {
356            events
357                .into_iter()
358                .max_by_key(|e| e.created_at)
359                .and_then(|e| Metadata::from_json(&e.content).ok())
360        })
361        .map_err(|e| e.to_string())
362}
363
364/// Our kind-0 as it stands on the relays, whole: its content's JSON object with every key it
365/// holds, whatever Vector makes of them, and every tag. Profiles carry what other clients
366/// invented (emoji in names, profile fields, identity proofs); a save edits, never rebuilds.
367#[derive(Clone, Debug, PartialEq)]
368pub(crate) struct OwnKind0 {
369    content: serde_json::Map<String, serde_json::Value>,
370    tags: Vec<Vec<String>>,
371}
372
373/// What a save changes. Every other key and tag of the relay copy stands.
374#[derive(Default)]
375pub(crate) struct Kind0Edit<'a> {
376    name: &'a str,
377    avatar: &'a str,
378    banner: &'a str,
379    about: &'a str,
380    bot: bool,
381    consent: Option<bool>,
382}
383
384/// Our newest kind-0, `Ok(None)` when the relays hold none, `Err` when none of them answered or the
385/// newest is no JSON object: unreadable is not absent, and publishing over it would erase it.
386async fn fetch_own_kind0(client: &Client, pubkey: PublicKey) -> Result<Option<OwnKind0>, String> {
387    let filter = Filter::new().author(pubkey).kind(Kind::Metadata).limit(1);
388    let timeout = crate::relay_request_timeout(Duration::from_secs(15));
389    let mut events = crate::fetch_answered(client, filter.clone(), timeout).await?;
390    // The Discovery Relays too: a profile last written elsewhere may be newest there.
391    let pooled = client.relays().all().await;
392    let discovery: Vec<RelayUrl> = crate::state::discovery_relay_iter()
393        .filter_map(|u| RelayUrl::parse(u).ok())
394        .filter(|u| pooled.contains_key(u))
395        .collect();
396    drop(pooled);
397    if !discovery.is_empty() {
398        let target = ReqTarget::manual(discovery.into_iter().map(|u| (u, vec![filter.clone()])));
399        if let Ok(more) = client.fetch_events(target).timeout(timeout).await {
400            events.extend(more);
401        }
402    }
403    crate::newest_replaceable(events).map(|e| kind0_of(&e)).transpose()
404}
405
406fn kind0_of(event: &Event) -> Result<OwnKind0, String> {
407    match serde_json::from_str::<serde_json::Value>(&event.content) {
408        Ok(serde_json::Value::Object(content)) => Ok(OwnKind0 {
409            content,
410            tags: event.tags.iter().map(|t| t.as_slice().to_vec()).collect(),
411        }),
412        _ => Err("your profile on the relays isn't one Vector can read, so it was left as it is".to_string()),
413    }
414}
415
416/// `base` with `edit` applied and our client tag in place of any other: keys and tags it doesn't
417/// touch are carried verbatim.
418fn edit_kind0(base: OwnKind0, edit: &Kind0Edit) -> OwnKind0 {
419    let mut content = base.content;
420    let mut put = |key: &str, value: serde_json::Value| { content.insert(key.to_string(), value); };
421    if !edit.name.is_empty() {
422        put("name", edit.name.into());
423    }
424    if let Ok(url) = Url::parse(edit.avatar) {
425        put("picture", url.to_string().into());
426    }
427    if let Ok(url) = Url::parse(edit.banner) {
428        put("banner", url.to_string().into());
429    }
430    if !edit.about.is_empty() {
431        put("about", edit.about.into());
432    }
433    if edit.bot {
434        put("bot", true.into());
435    }
436    if edit.consent == Some(true) {
437        put(crate::profile::STREAM_CONSENT_KEY, true.into());
438    }
439    if removes(edit.banner) {
440        content.remove("banner");
441    }
442    if edit.consent == Some(false) {
443        content.remove(crate::profile::STREAM_CONSENT_KEY);
444    }
445    OwnKind0 { content, tags: with_client_tag(base.tags) }
446}
447
448/// A first kind-0, from what this device holds of the profile.
449fn fresh_kind0(local: &Profile, edit: &Kind0Edit) -> OwnKind0 {
450    let mut meta = own_metadata(local, edit.name, edit.avatar, edit.banner, edit.about, edit.bot);
451    if let Some(on) = edit.consent {
452        meta = crate::profile::with_stream_consent(meta, on);
453    }
454    let content = match serde_json::to_value(&meta) {
455        Ok(serde_json::Value::Object(map)) => map,
456        _ => serde_json::Map::new(),
457    };
458    OwnKind0 { content, tags: with_client_tag(Vec::new()) }
459}
460
461fn with_client_tag(tags: Vec<Vec<String>>) -> Vec<Vec<String>> {
462    tags.into_iter()
463        .filter(|t| t.first().map(String::as_str) != Some("client"))
464        .chain(std::iter::once(vec!["client".to_string(), "vector".to_string()]))
465        .collect()
466}
467
468fn names_vector(tags: &[Vec<String>]) -> bool {
469    tags.iter().any(|t| t.len() >= 2 && t[0] == "client" && t[1] == "vector")
470}
471
472fn consents(content: &serde_json::Map<String, serde_json::Value>) -> bool {
473    content.get(crate::profile::STREAM_CONSENT_KEY).is_some_and(|v| match v.as_bool() {
474        Some(b) => b,
475        None => v.as_str().is_some_and(|s| s.eq_ignore_ascii_case("true")),
476    })
477}
478
479/// The fields Vector reads, from a content whose keys may hold anything: a known field of an
480/// unexpected type is left out rather than failing the whole profile.
481fn metadata_view(content: &serde_json::Map<String, serde_json::Value>) -> Metadata {
482    const KNOWN: [&str; 9] = ["name", "display_name", "about", "picture", "banner", "website", "nip05", "lud06", "lud16"];
483    let readable = content
484        .iter()
485        .filter(|(k, v)| !KNOWN.contains(&k.as_str()) || v.is_string())
486        .map(|(k, v)| (k.clone(), v.clone()))
487        .collect();
488    serde_json::from_value(serde_json::Value::Object(readable)).unwrap_or_default()
489}
490
491/// Fetch a profile's metadata and status from relays, update STATE, and
492/// notify via EventEmitter + handler callback.
493///
494/// Returns `true` if the fetch succeeded (even if nothing changed).
495pub async fn load_profile(npub: String, handler: &dyn ProfileSyncHandler) -> bool {
496    let client = match nostr_client() {
497        Some(c) => c,
498        None => return false,
499    };
500
501    // Session captured for the whole load_profile lifecycle. Relay
502    // fetches can sleep multi-second; we re-check before writing back
503    // to STATE / DB so a mid-fetch swap doesn't land account A's
504    // profile in account B's storage.
505
506    let profile_pubkey = match PublicKey::from_bech32(npub.as_str()) {
507        Ok(pk) => pk,
508        Err(_) => return false,
509    };
510
511    let my_public_key = match my_public_key() {
512        Some(pk) => pk,
513        None => return false,
514    };
515
516    // Grab old status (or create profile if missing)
517    let (old_status_title, old_status_purpose, old_status_url): (String, String, String);
518    let old_status_emoji_tags: Vec<crate::types::EmojiTag>;
519    {
520        let mut state = STATE.lock().await;
521        match state.get_profile(&npub) {
522            Some(p) => {
523                old_status_title = p.status_title().to_string();
524                old_status_purpose = p.status_purpose().to_string();
525                old_status_url = p.status_url().to_string();
526                old_status_emoji_tags = p.status_emoji_tags();
527            }
528            None => {
529                state.insert_or_replace_profile(&npub, Profile::new());
530                old_status_title = String::new();
531                old_status_purpose = String::new();
532                old_status_url = String::new();
533                old_status_emoji_tags = Vec::new();
534            }
535        }
536    }
537
538    // Fetch status (kind 30315) from relays
539    let status_filter = Filter::new()
540        .author(profile_pubkey)
541        .kind(Kind::from_u16(30315))
542        .limit(1);
543
544    let (status_title, status_purpose, status_url, status_emoji_tags) = match client
545        .fetch_events(status_filter).timeout(crate::relay_request_timeout(Duration::from_secs(15)))
546        .await
547    {
548        Ok(res) => {
549            if !res.is_empty() {
550                let status_event = res.first().unwrap();
551                (
552                    clamp_status(status_event.content.clone()),
553                    status_event.tags.first()
554                        .and_then(|t| t.content())
555                        .unwrap_or_default()
556                        .to_string(),
557                    String::new(),
558                    crate::types::EmojiTag::extract_from_tags(status_event.tags.iter()),
559                )
560            } else {
561                (old_status_title, old_status_purpose, old_status_url, old_status_emoji_tags)
562            }
563        }
564        Err(_) => (old_status_title, old_status_purpose, old_status_url, old_status_emoji_tags),
565    };
566
567    let fetch_result = fetch_newest_metadata(&client, profile_pubkey).await;
568    if fetch_result.is_ok() {
569        let _ = crate::db::profiles::mark_profile_checked(&npub, now_secs());
570    }
571
572    match fetch_result {
573        Ok(meta) => {
574            if let Some(meta) = meta {
575                let save_data = {
576                    let mut state = STATE.lock().await;
577                    let id = match state.interner.lookup(&npub) {
578                        Some(id) => id,
579                        None => return false,
580                    };
581                    let (changed, avatar_url, banner_url) = {
582                        let profile = match state.get_profile_mut_by_id(id) {
583                            Some(p) => p,
584                            None => return false,
585                        };
586                        profile.flags.set_mine(my_public_key == profile_pubkey);
587
588                        // Update status
589                        let status_changed = profile.status_title() != status_title.as_str()
590                            || profile.status_purpose() != status_purpose.as_str()
591                            || profile.status_url() != status_url.as_str()
592                            || profile.status_emoji_tags() != status_emoji_tags;
593                        profile.set_status(&status_title, &status_purpose, &status_url, &status_emoji_tags);
594
595                        // Update metadata
596                        let metadata_changed = profile.from_metadata(meta);
597
598                        // Update timestamp
599                        profile.last_updated = secs_to_compact(
600                            crate::clock::now_secs()
601                        );
602
603                        // A GUI's picture with no local copy goes to the cache too: one held
604                        // while a request waited, or one an earlier download lost.
605                        let uncached = crate::requests::shielded()
606                            && ((!profile.avatar().is_empty() && !profile.has_avatar_cached())
607                                || (!profile.banner().is_empty() && !profile.has_banner_cached()));
608                        (status_changed || metadata_changed || uncached,
609                         profile.avatar().to_string(),
610                         profile.banner().to_string())
611                    };
612
613                    if changed {
614                        let slim = state.serialize_profile(id).unwrap();
615                        Some((slim, avatar_url, banner_url))
616                    } else {
617                        None
618                    }
619                };
620
621                if let Some((slim, avatar_url, banner_url)) = save_data {
622                    // Notify UI via EventEmitter
623                    emit_event("profile_update", &slim);
624                    // Platform-specific: DB persist + image caching
625                    handler.on_profile_fetched(&slim, &avatar_url, &banner_url);
626                }
627                true
628            } else {
629                // No metadata on relays — update timestamp so we don't keep retrying
630                let mut state = STATE.lock().await;
631                if let Some(profile) = state.get_profile_mut(&npub) {
632                    profile.last_updated = secs_to_compact(
633                        crate::clock::now_secs()
634                    );
635                }
636                true
637            }
638        }
639        Err(_) => false,
640    }
641}
642
643// ============================================================================
644// update_profile — publish metadata to relays
645// ============================================================================
646
647/// Update the current user's profile metadata and broadcast to relays.
648///
649/// Merges the provided fields with the existing profile (empty = keep existing).
650/// After successful broadcast, updates STATE and notifies via EventEmitter + handler.
651pub async fn update_profile(
652    name: String, avatar: String, banner: String, about: String,
653    handler: &dyn ProfileSyncHandler,
654) -> bool {
655    update_profile_inner(name, avatar, banner, about, false, handler).await
656}
657
658/// Publish the current user's profile and mark it as a bot (`bot: true` in the metadata). The SDK
659/// uses this so every bot it builds is tagged; human clients use [`update_profile`].
660pub async fn update_bot_profile(
661    name: String, avatar: String, banner: String, about: String,
662    handler: &dyn ProfileSyncHandler,
663) -> bool {
664    update_profile_inner(name, avatar, banner, about, true, handler).await
665}
666
667async fn update_profile_inner(
668    name: String, avatar: String, banner: String, about: String,
669    is_bot: bool,
670    handler: &dyn ProfileSyncHandler,
671) -> bool {
672    let client = match nostr_client() {
673        Some(c) => c,
674        None => return false,
675    };
676
677    let npub = match my_public_key().map(|pk| pk.to_bech32()) {
678        Some(Ok(n)) => n,
679        _ => return false,
680    };
681
682    let Some(pk) = my_public_key() else { return false };
683    let edit = Kind0Edit { name: &name, avatar: &avatar, banner: &banner, about: &about, bot: is_bot, consent: None };
684    // Always the relay copy, edited: a save that rebuilt from Vector's own fields would drop every
685    // key and tag another client wrote. Unread, nothing is published at all.
686    let kind0 = match fetch_own_kind0(&client, pk).await {
687        Ok(Some(base)) => edit_kind0(base, &edit),
688        Ok(None) => {
689            let local = STATE.lock().await.get_profile(&npub).cloned().unwrap_or_default();
690            fresh_kind0(&local, &edit)
691        }
692        Err(e) => {
693            crate::log_warn!("[update_profile] couldn't read the current profile: {e}");
694            return false;
695        }
696    };
697
698    match publish_kind0(&client, &npub, kind0, handler).await {
699        Ok(()) => true,
700        Err(e) => {
701            crate::log_warn!("[update_profile] {e}");
702            false
703        }
704    }
705}
706
707/// A picture argument that removes the field: blank but not empty, since empty leaves it as it is.
708fn removes(value: &str) -> bool {
709    !value.is_empty() && value.trim().is_empty()
710}
711
712/// Our kind-0 rebuilt from `profile`, with each non-empty argument replacing its field.
713///
714/// Carries stream consent forward, so editing a name or avatar never revokes it.
715pub(crate) fn own_metadata(
716    profile: &Profile, name: &str, avatar: &str, banner: &str, about: &str, is_bot: bool,
717) -> Metadata {
718    let pick = |new: &str, old: &str| if new.is_empty() { old.to_string() } else { new.to_string() };
719
720    let mut meta = Metadata::new().name(pick(name, profile.name()));
721
722    let avatar_url = pick(avatar, profile.avatar());
723    if let Ok(url) = Url::parse(&avatar_url) {
724        meta = meta.picture(url);
725    }
726    let banner_url = if removes(banner) { String::new() } else { pick(banner, profile.banner()) };
727    if let Ok(url) = Url::parse(&banner_url) {
728        meta = meta.banner(url);
729    }
730
731    if !profile.display_name().is_empty() {
732        meta = meta.display_name(profile.display_name());
733    }
734    meta = meta.about(pick(about, profile.about()));
735
736    if let Ok(url) = Url::parse(profile.website()) {
737        meta = meta.website(url);
738    }
739    if !profile.nip05().is_empty() {
740        meta = meta.nip05(profile.nip05());
741    }
742    if !profile.lud06().is_empty() {
743        meta = meta.lud06(profile.lud06());
744    }
745    if !profile.lud16().is_empty() {
746        meta = meta.lud16(profile.lud16());
747    }
748
749    // SDK-built bots carry `bot: true` so clients can badge them; human clients never set it.
750    if is_bot {
751        meta = meta.custom_field("bot", true);
752    }
753    crate::profile::with_stream_consent(meta, profile.flags.is_stream_consent())
754}
755
756/// Sign and broadcast our kind-0, then fold it into STATE, the UI and the DB.
757async fn publish_kind0(client: &Client, npub: &str, kind0: OwnKind0, handler: &dyn ProfileSyncHandler) -> Result<(), String> {
758    send_kind0(client, &kind0).await?;
759    apply_own_metadata(npub, metadata_view(&kind0.content), handler).await
760}
761
762async fn send_kind0(client: &Client, kind0: &OwnKind0) -> Result<(), String> {
763    let content = serde_json::to_string(&kind0.content).map_err(|e| e.to_string())?;
764    let builder = EventBuilder::new(Kind::Metadata, content).tags(kind0.tags.iter().filter_map(|t| Tag::parse(t).ok()));
765    let event = crate::sign_builder(builder).await?;
766    // First-ACK so the UI updates as soon as the fastest relay responds.
767    crate::inbox_relays::send_event_pool_first_ok(client, &event)
768        .await
769        .map(|_| ())
770        .map_err(|e| format!("relay broadcast failed: {e}"))
771}
772
773/// Once a login: a profile last written by another client takes our client tag, every key and
774/// tag of it kept, so servers that serve Vector's users recognise the account. Returns whether
775/// it published.
776pub async fn stamp_vector_client() -> Result<bool, String> {
777    let client = nostr_client().ok_or("Not connected")?;
778    let pk = my_public_key().ok_or("No active account")?;
779    let Some(base) = fetch_own_kind0(&client, pk).await? else { return Ok(false) };
780    if names_vector(&base.tags) {
781        return Ok(false);
782    }
783    if !crate::db::session_is_live() {
784        return Err("account changed during the operation".to_string());
785    }
786    send_kind0(&client, &OwnKind0 { tags: with_client_tag(base.tags), content: base.content }).await?;
787    Ok(true)
788}
789
790/// [`stamp_vector_client`] once the login's sync has settled: its relays are busiest before it.
791pub async fn stamp_vector_client_after_sync() {
792    crate::rt::time::sleep(Duration::from_secs(30)).await;
793    match stamp_vector_client().await {
794        Ok(true) => crate::log_info!("[Profile] added Vector's client tag to the profile"),
795        Ok(false) => {}
796        Err(e) => crate::log_warn!("[Profile] client tag not added: {e}"),
797    }
798}
799
800async fn apply_own_metadata(npub: &str, meta: Metadata, handler: &dyn ProfileSyncHandler) -> Result<(), String> {
801    let (slim, avatar_url, banner_url) = {
802        let mut state = STATE.lock().await;
803        // Creates the entry if this identity had none yet (a fresh account is interned here).
804        let mut profile = state.get_profile(npub).cloned().unwrap_or_default();
805        profile.from_metadata(meta);
806        profile.flags.set_mine(true);
807        let urls = (profile.avatar().to_string(), profile.banner().to_string());
808        state.insert_or_replace_profile(npub, profile);
809        let slim = state
810            .interner
811            .lookup(npub)
812            .and_then(|id| state.serialize_profile(id))
813            .ok_or("own profile missing after insert")?;
814        (slim, urls.0, urls.1)
815    };
816    emit_event("profile_update", &slim);
817    handler.on_profile_fetched(&slim, &avatar_url, &banner_url);
818    Ok(())
819}
820
821/// What a consent change does, decided from the relay copy (`None` = the relays hold none).
822#[derive(Debug, PartialEq)]
823pub(crate) enum ConsentPlan {
824    /// The relays already say it: adopt their copy, publish nothing.
825    Unchanged(OwnKind0),
826    Publish(OwnKind0),
827}
828
829/// A read-modify-write of the relay copy, so every key and tag another client wrote survives.
830/// With no relay copy, the local profile is carried, and refused when there is none to carry: a
831/// fresh device must never publish a blank profile over the real one.
832pub(crate) fn consent_plan(fetched: Option<OwnKind0>, local: &Profile, on: bool) -> Result<ConsentPlan, String> {
833    let edit = Kind0Edit { consent: Some(on), ..Default::default() };
834    match fetched {
835        Some(remote) if consents(&remote.content) == on => Ok(ConsentPlan::Unchanged(remote)),
836        Some(remote) => Ok(ConsentPlan::Publish(edit_kind0(remote, &edit))),
837        None => {
838            if local.name().is_empty() && local.display_name().is_empty()
839                && local.about().is_empty() && local.avatar().is_empty()
840            {
841                return Err("Couldn't find your profile on your relays".to_string());
842            }
843            let edit = Kind0Edit { bot: local.flags.is_bot(), ..edit };
844            Ok(ConsentPlan::Publish(fresh_kind0(local, &edit)))
845        }
846    }
847}
848
849/// Publish our kind-0 with stream consent set to `on`; returns the value now in effect.
850///
851/// Refused when no relay answers the read, so a fresh device never clobbers the real profile.
852pub async fn set_stream_consent(on: bool, handler: &dyn ProfileSyncHandler) -> Result<bool, String> {
853    let client = nostr_client().ok_or("Not connected")?;
854    let my_public_key = my_public_key().ok_or("No active account")?;
855    let npub = my_public_key.to_bech32().map_err(|e| e.to_string())?;
856
857    let fetched = fetch_own_kind0(&client, my_public_key)
858        .await
859        .map_err(|_| "Couldn't read your profile from your relays".to_string())?;
860    let local = STATE.lock().await.get_profile(&npub).cloned().unwrap_or_default();
861    let plan = consent_plan(fetched, &local, on)?;
862
863    if !crate::db::session_is_live() {
864        return Err("account changed during the operation".to_string());
865    }
866    match plan {
867        ConsentPlan::Unchanged(remote) => apply_own_metadata(&npub, metadata_view(&remote.content), handler).await?,
868        ConsentPlan::Publish(kind0) => publish_kind0(&client, &npub, kind0, handler).await?,
869    }
870    Ok(on)
871}
872
873// ============================================================================
874// update_status — publish status to relays
875// ============================================================================
876
877/// Update the current user's status (kind 30315) and broadcast to relays.
878///
879/// Status length cap in Unicode scalar characters, enforced on BOTH sides:
880/// our own publishes and every stored inbound status. Characters, not bytes —
881/// a byte cap would chop emoji-heavy statuses to a third of what text gets.
882pub const STATUS_MAX_CHARS: usize = 120;
883
884/// Truncate a status to [`STATUS_MAX_CHARS`] on a character boundary.
885fn clamp_status(s: String) -> String {
886    if s.chars().count() <= STATUS_MAX_CHARS {
887        s
888    } else {
889        s.chars().take(STATUS_MAX_CHARS).collect()
890    }
891}
892
893/// Status is ephemeral — updated in STATE + frontend but not persisted to DB.
894/// (Re-fetched from relays on next `load_profile` call.)
895pub async fn update_status(status: String) -> bool {
896    let status = clamp_status(status);
897    let client = match nostr_client() {
898        Some(c) => c,
899        None => return false,
900    };
901
902    let my_public_key = match my_public_key() {
903        Some(pk) => pk,
904        None => return false,
905    };
906
907    // Build and sign kind 30315 status event. `:shortcode:`s from the user's
908    // equipped packs ride along as NIP-30 tags so other clients render them.
909    let emoji_tags = crate::emoji_packs::resolve_outbound_emoji_tags(&status);
910    let mut status_builder = EventBuilder::new(Kind::from_u16(30315), status.as_str())
911        .tag(Tag::custom("d", vec!["general"]));
912    for et in &emoji_tags {
913        status_builder = status_builder.tag(Tag::custom("emoji", [et.shortcode.clone(), et.url.clone()]));
914    }
915
916    let Ok(event) = crate::sign_builder(status_builder).await else {
917        return false;
918    };
919
920    match crate::inbox_relays::send_event_pool_first_ok(&client, &event).await {
921        Ok(_) => {
922            let mut state = STATE.lock().await;
923            let npub = match my_public_key.to_bech32() {
924                Ok(n) => n,
925                Err(_) => return false,
926            };
927            let id = match state.interner.lookup(&npub) {
928                Some(id) => id,
929                None => return false,
930            };
931            {
932                let profile = match state.get_profile_mut_by_id(id) {
933                    Some(p) => p,
934                    None => return false,
935                };
936                profile.set_status_title(&status);
937                profile.set_status_purpose("general");
938                profile.set_status_emoji_tags(&emoji_tags);
939            }
940
941            let slim = state.serialize_profile(id).unwrap();
942            // Persist NOW: without this the new status (and its emoji tags)
943            // survives a reboot only if a self-profile sync happens to run
944            // before the app closes.
945            let _ = crate::db::profiles::set_profile(&slim);
946            emit_event("profile_update", &slim);
947            true
948        }
949        Err(_) => false,
950    }
951}
952
953// ============================================================================
954// block / unblock / nickname / blocked list
955// ============================================================================
956
957/// Block a user by npub. DM events from blocked users are dropped after decryption.
958/// Group messages are stored but filtered in the UI.
959///
960/// Returns `false` if trying to block yourself or if the profile can't be found.
961pub async fn block_user(npub: String, handler: &dyn ProfileSyncHandler) -> bool {
962    // Prevent blocking yourself
963    if let Some(my_pk) = my_public_key() {
964        if my_pk.to_bech32().ok().as_deref() == Some(npub.as_str()) {
965            return false;
966        }
967    }
968
969    let mut state = STATE.lock().await;
970
971    // Create profile if it doesn't exist (can block someone with no prior contact)
972    if state.interner.lookup(&npub).is_none() {
973        state.insert_or_replace_profile(&npub, Profile::new());
974    }
975
976    if let Some(id) = state.interner.lookup(&npub) {
977        {
978            let profile = match state.get_profile_mut_by_id(id) {
979                Some(p) => p,
980                None => return false,
981            };
982            profile.flags.set_blocked(true);
983        }
984        let images = state.get_profile_mut_by_id(id).map(|p| p.forget_imagery()).unwrap_or_default();
985        let images = unshared(&state, id, images);
986        let slim = state.serialize_profile(id).unwrap();
987        drop(state);
988        emit_event("profile_update", &slim);
989        handler.on_profile_fetched(&slim, "", "");
990        handler.forget_images(images);
991        crate::push::controls_changed();
992        // Their invites go unanswered with them.
993        if crate::requests::shielded() && crate::db::community::delete_pending_invites_from(&npub).unwrap_or(0) > 0 {
994            emit_event("community_invites_purged", &());
995        }
996        true
997    } else {
998        false
999    }
1000}
1001
1002/// Unblock a user by npub.
1003pub async fn unblock_user(npub: String, handler: &dyn ProfileSyncHandler) -> bool {
1004    let mut state = STATE.lock().await;
1005
1006    if let Some(id) = state.interner.lookup(&npub) {
1007        {
1008            let profile = match state.get_profile_mut_by_id(id) {
1009                Some(p) => p,
1010                None => return false,
1011            };
1012            profile.flags.set_blocked(false);
1013        }
1014        let slim = state.serialize_profile(id).unwrap();
1015        drop(state);
1016        emit_event("profile_update", &slim);
1017        handler.on_profile_fetched(&slim, "", "");
1018        crate::push::controls_changed();
1019        // Their pictures were dropped at the block: the next fetch brings them back.
1020        queue_profile_sync(npub, SyncPriority::Critical, true);
1021        true
1022    } else {
1023        false
1024    }
1025}
1026
1027/// Accept a DM request without answering it: what its sender sent, and their
1028/// pictures, may load from now on.
1029pub async fn accept_chat(npub: String) -> Result<(), String> {
1030    crate::db::scoped(async move {
1031        let slim = {
1032            let mut guard = STATE.lock().await;
1033            let state = &mut *guard;
1034            let chat = state.chats.iter_mut()
1035                .find(|c| c.id == npub && c.chat_type == crate::ChatType::DirectMessage)
1036                .ok_or_else(|| "no chat with that npub".to_string())?;
1037            if !chat.is_request() {
1038                return Ok(());
1039            }
1040            chat.metadata.insert(crate::chat::ACCEPTED_KEY, "true".into());
1041            crate::db::chats::SlimChatDB::from_chat(chat, &state.interner)
1042        };
1043        crate::db::chats::save_slim_chat(&slim)?;
1044        // Their pictures and wallpaper were held while the request waited.
1045        crate::wallpaper::release_held(&npub).await;
1046        queue_profile_sync(npub, SyncPriority::Critical, true);
1047        Ok(())
1048    }).await
1049}
1050
1051/// Persist what `ChatState::forget_blocked_imagery` dropped and delete the files.
1052pub fn persist_forgotten_imagery(handler: &dyn ProfileSyncHandler, slims: Vec<crate::SlimProfile>, images: Vec<super::CachedImage>) {
1053    if slims.is_empty() {
1054        return;
1055    }
1056    log_info!("[Profile] Dropped the pictures of {} blocked profiles", slims.len());
1057    for slim in &slims {
1058        handler.on_profile_fetched(slim, "", "");
1059    }
1060    handler.forget_images(images);
1061}
1062
1063/// Get all blocked profiles.
1064pub async fn get_blocked_users() -> Vec<crate::SlimProfile> {
1065    let state = STATE.lock().await;
1066    state.profiles.iter()
1067        .filter(|p| p.flags.is_blocked())
1068        .filter_map(|p| state.serialize_profile(p.id))
1069        .collect()
1070}
1071
1072/// Set a nickname for a profile.
1073pub async fn set_nickname(npub: String, nickname: String, handler: &dyn ProfileSyncHandler) -> bool {
1074    let mut state = STATE.lock().await;
1075
1076    if let Some(id) = state.interner.lookup(&npub) {
1077        {
1078            let profile = match state.get_profile_mut_by_id(id) {
1079                Some(p) => p,
1080                None => return false,
1081            };
1082            profile.set_nickname(&nickname);
1083        }
1084        let slim = state.serialize_profile(id).unwrap();
1085        drop(state);
1086        emit_event("profile_nick_changed", &serde_json::json!({
1087            "profile_id": &npub,
1088            "value": &slim.nickname
1089        }));
1090        handler.on_profile_fetched(&slim, "", "");
1091        true
1092    } else {
1093        false
1094    }
1095}
1096
1097// ============================================================================
1098// Background processor
1099// ============================================================================
1100
1101/// Background processor that continuously drains the profile sync queue.
1102///
1103/// Spawned once at startup. Processes batches in priority order, calling
1104/// `load_profile` for each entry with the provided handler.
1105pub async fn start_profile_sync_processor(handler: Arc<dyn ProfileSyncHandler>) {
1106    let mut last_own_profile_sync = Instant::now();
1107    let own_profile_sync_interval = Duration::from_secs(5 * 60);
1108
1109    loop {
1110        // Periodically queue our own profile to detect changes from other Nostr apps
1111        if last_own_profile_sync.elapsed() >= own_profile_sync_interval {
1112            let state = STATE.lock().await;
1113            if let Some(own_profile) = state.profiles.iter().find(|p| p.flags.is_mine()) {
1114                let npub = state.interner.resolve(own_profile.id).unwrap_or("").to_string();
1115                drop(state);
1116
1117                let owner = profile_sync_queue();
1118                let mut queue = owner.lock().unwrap();
1119                queue.add(npub, SyncPriority::Low, false);
1120            }
1121            last_own_profile_sync = Instant::now();
1122        }
1123
1124        // Get next batch (lock scoped)
1125        let (should_wait, batch) = {
1126            let owner = profile_sync_queue();
1127            let mut queue = owner.lock().unwrap();
1128
1129            if queue.is_processing {
1130                (true, vec![])
1131            } else {
1132                queue.is_processing = true;
1133                let batch = queue.get_next_batch();
1134                for entry in &batch {
1135                    queue.mark_processing(&entry.npub);
1136                }
1137                (false, batch)
1138            }
1139        };
1140
1141        if should_wait {
1142            crate::rt::time::sleep(Duration::from_secs(1)).await;
1143            continue;
1144        }
1145
1146        if batch.is_empty() {
1147            let ready_in = {
1148                let owner = profile_sync_queue();
1149                let mut queue = owner.lock().unwrap();
1150                queue.is_processing = false;
1151                queue.next_ready_in()
1152            };
1153            // Sleep until the next entry ripens or the own-profile check is due, unless an add
1154            // comes first, so an idle processor costs no wakeups.
1155            let own_due = own_profile_sync_interval.saturating_sub(last_own_profile_sync.elapsed());
1156            let wait = ready_in.map_or(own_due, |r| r.min(own_due)).max(Duration::from_millis(50));
1157            let _ = crate::rt::time::timeout(wait, PROCESSOR_WAKE.notified()).await;
1158            continue;
1159        }
1160
1161        // Session captured per-batch so a swap aborts the loop before
1162        // account A's queue work lands in account B's DB. The next
1163        // outer-loop iteration picks up the new session's queue cleanly.
1164
1165        for entry in &batch {
1166            load_profile(entry.npub.clone(), handler.as_ref()).await;
1167
1168            {
1169                let owner = profile_sync_queue();
1170                let mut queue = owner.lock().unwrap();
1171                queue.mark_done(&entry.npub);
1172            }
1173
1174            crate::rt::time::sleep(Duration::from_millis(100)).await;
1175        }
1176
1177        // Release processing lock
1178        {
1179            let owner = profile_sync_queue();
1180            let mut queue = owner.lock().unwrap();
1181            queue.is_processing = false;
1182        }
1183
1184        crate::rt::time::sleep(Duration::from_millis(500)).await;
1185    }
1186}
1187
1188// ============================================================================
1189// Public API
1190// ============================================================================
1191
1192/// Queue a single profile for syncing.
1193pub fn queue_profile_sync(npub: String, priority: SyncPriority, force_refresh: bool) {
1194    let owner = profile_sync_queue();
1195    let mut queue = owner.lock().unwrap();
1196    queue.add(npub, priority, force_refresh);
1197}
1198
1199fn now_secs() -> u64 {
1200    crate::clock::now_secs()
1201}
1202
1203/// How long a profile's last check stays good enough for one that is merely on screen.
1204const ON_SCREEN_FRESH: Duration = Duration::from_secs(6 * 60 * 60);
1205
1206/// What a profile on screen needs: a fetch now when we know nothing of it, a slow refresh when
1207/// its last check is older than [`ON_SCREEN_FRESH`], otherwise nothing.
1208fn on_screen_need(profile: Option<&Profile>, now: u64) -> Option<SyncPriority> {
1209    let Some(p) = profile else { return Some(SyncPriority::Critical) };
1210    if p.flags.is_mine() {
1211        return None;
1212    }
1213    let checked = secs_from_compact(p.last_updated);
1214    if checked == 0 {
1215        let known = !p.name().is_empty() || !p.display_name().is_empty() || !p.avatar().is_empty();
1216        return Some(if known { SyncPriority::Medium } else { SyncPriority::Critical });
1217    }
1218    (now.saturating_sub(checked) >= ON_SCREEN_FRESH.as_secs()).then_some(SyncPriority::Medium)
1219}
1220
1221/// Queue the profiles the UI has on screen (or nearly) whose last check has gone stale. Called
1222/// on every view, so it costs a lookup per npub and a fetch only for those that need one.
1223pub async fn queue_visible_profiles(npubs: Vec<String>) {
1224    const MAX_PER_CALL: usize = 200;
1225    let now = now_secs();
1226    let picks: Vec<(String, SyncPriority)> = {
1227        let state = STATE.lock().await;
1228        npubs
1229            .into_iter()
1230            .take(MAX_PER_CALL)
1231            .filter(|n| n.starts_with("npub1"))
1232            .filter_map(|npub| on_screen_need(state.get_profile(&npub), now).map(|p| (npub, p)))
1233            .collect()
1234    };
1235    if picks.is_empty() {
1236        return;
1237    }
1238    let owner = profile_sync_queue();
1239    let mut queue = owner.lock().unwrap();
1240    for (npub, priority) in picks {
1241        queue.add(npub, priority, false);
1242    }
1243}
1244
1245/// Queue all profiles for a chat. A community's members refresh as they come on screen
1246/// ([`queue_visible_profiles`]), so here a community only fetches the ones we know nothing of.
1247pub async fn queue_chat_profiles(chat_id: String, is_opening: bool) {
1248    let state = STATE.lock().await;
1249
1250    let chat = match state.get_chat(&chat_id) {
1251        Some(c) => c,
1252        None => return,
1253    };
1254
1255    let is_community = chat.is_community();
1256    let base_priority = if is_opening {
1257        SyncPriority::High
1258    } else {
1259        SyncPriority::Medium
1260    };
1261
1262    let mut profiles_to_queue = Vec::new();
1263
1264    for &handle in chat.participants() {
1265        let member_npub = match state.interner.resolve(handle) {
1266            Some(s) => s.to_string(),
1267            None => continue,
1268        };
1269
1270        let has_metadata = state.get_profile_by_id(handle)
1271            .map(|p| {
1272                let has_data = !p.name().is_empty() || !p.display_name().is_empty() || !p.avatar().is_empty();
1273                let was_fetched = p.last_updated > 0;
1274                has_data || was_fetched
1275            })
1276            .unwrap_or(false);
1277
1278        let priority = if !has_metadata {
1279            SyncPriority::Critical
1280        } else if is_community {
1281            continue;
1282        } else {
1283            base_priority
1284        };
1285
1286        profiles_to_queue.push((member_npub, priority));
1287    }
1288
1289    drop(state);
1290
1291    let owner = profile_sync_queue();
1292    let mut queue = owner.lock().unwrap();
1293    for (npub, priority) in profiles_to_queue {
1294        queue.add(npub, priority, false);
1295    }
1296}
1297
1298/// Force immediate refresh of a profile (for user clicks).
1299pub fn refresh_profile_now(npub: String) {
1300    let owner = profile_sync_queue();
1301    let mut queue = owner.lock().unwrap();
1302    queue.add(npub, SyncPriority::Critical, true);
1303}
1304
1305/// Queue every profile that has never been fetched. Known profiles refresh when their chat
1306/// opens or they come on screen ([`queue_visible_profiles`]).
1307pub async fn sync_all_profiles() {
1308    let state = STATE.lock().await;
1309    let owner = profile_sync_queue();
1310    let mut queue = owner.lock().unwrap();
1311
1312    for profile in &state.profiles {
1313        let has_metadata = !profile.name().is_empty() || !profile.display_name().is_empty() || !profile.avatar().is_empty();
1314        if has_metadata || profile.last_updated > 0 {
1315            continue;
1316        }
1317        if let Some(npub) = state.interner.resolve(profile.id) {
1318            queue.add(npub, SyncPriority::Critical, false);
1319        }
1320    }
1321}
1322
1323// ============================================================================
1324// Tests
1325// ============================================================================
1326
1327#[cfg(test)]
1328mod status_clamp_tests {
1329    use super::*;
1330
1331    #[test]
1332    fn a_status_clamps_at_120_characters_not_bytes() {
1333        assert_eq!(clamp_status("hi".to_string()), "hi");
1334        let exact: String = "a".repeat(STATUS_MAX_CHARS);
1335        assert_eq!(clamp_status(exact.clone()), exact, "at the cap is untouched");
1336        let long = "b".repeat(10_000);
1337        assert_eq!(clamp_status(long).chars().count(), STATUS_MAX_CHARS);
1338        // Characters, not bytes: 120 four-byte emoji survive whole.
1339        let emoji: String = "\u{1F980}".repeat(STATUS_MAX_CHARS);
1340        let clamped = clamp_status(format!("{emoji}overflow"));
1341        assert_eq!(clamped.chars().count(), STATUS_MAX_CHARS);
1342        assert_eq!(clamped, emoji, "truncation lands on a character boundary");
1343    }
1344}
1345
1346#[cfg(test)]
1347mod on_screen_tests {
1348    use super::*;
1349
1350    #[test]
1351    fn an_on_screen_profile_is_fetched_only_when_unknown_or_stale() {
1352        let now = 1_900_000_000;
1353        assert_eq!(on_screen_need(None, now), Some(SyncPriority::Critical));
1354        let mut p = Profile::new();
1355        assert_eq!(on_screen_need(Some(&p), now), Some(SyncPriority::Critical));
1356        p.set_name("kitty");
1357        assert_eq!(on_screen_need(Some(&p), now), Some(SyncPriority::Medium), "named but never checked");
1358        p.last_updated = secs_to_compact(now - 60);
1359        assert_eq!(on_screen_need(Some(&p), now), None, "checked a minute ago");
1360        p.last_updated = secs_to_compact(now - ON_SCREEN_FRESH.as_secs());
1361        assert_eq!(on_screen_need(Some(&p), now), Some(SyncPriority::Medium), "stale");
1362        p.flags.set_mine(true);
1363        assert_eq!(on_screen_need(Some(&p), now), None, "our own syncs on its own clock");
1364    }
1365}
1366
1367#[cfg(test)]
1368mod tests {
1369    use super::*;
1370
1371    #[test]
1372    fn sync_priority_cache_windows() {
1373        assert_eq!(SyncPriority::Critical.cache_window(), Duration::from_secs(0));
1374        assert_eq!(SyncPriority::High.cache_window(), Duration::from_secs(300));
1375        assert_eq!(SyncPriority::Medium.cache_window(), Duration::from_secs(1800));
1376        assert_eq!(SyncPriority::Low.cache_window(), Duration::from_secs(86400));
1377    }
1378
1379    #[test]
1380    fn sync_priority_batch_sizes() {
1381        assert_eq!(SyncPriority::Critical.batch_size(), 10);
1382        assert_eq!(SyncPriority::High.batch_size(), 20);
1383        assert_eq!(SyncPriority::Medium.batch_size(), 30);
1384        assert_eq!(SyncPriority::Low.batch_size(), 50);
1385    }
1386
1387    impl ProfileSyncQueue {
1388        fn push_raw(&mut self, priority: SyncPriority, npub: &str, added_at: Instant) {
1389            self.next_gen += 1;
1390            self.queued.insert(npub.to_string(), (self.next_gen, priority));
1391            let entry = QueueEntry { npub: npub.to_string(), added_at, gen: self.next_gen };
1392            match priority {
1393                SyncPriority::Critical => self.critical_queue.push_back(entry),
1394                SyncPriority::High => self.high_queue.push_back(entry),
1395                SyncPriority::Medium => self.medium_queue.push_back(entry),
1396                SyncPriority::Low => self.low_queue.push_back(entry),
1397            }
1398        }
1399
1400        fn live(&self, lane: &VecDeque<QueueEntry>) -> Vec<String> {
1401            lane.iter().filter(|e| Self::is_live(&self.queued, e)).map(|e| e.npub.clone()).collect()
1402        }
1403    }
1404
1405    #[test]
1406    fn next_ready_in_follows_the_lane_the_batch_would_take() {
1407        let mut queue = ProfileSyncQueue::new();
1408        assert_eq!(queue.next_ready_in(), None, "empty: nothing to wake for");
1409        let now = Instant::now();
1410        queue.push_raw(SyncPriority::Low, "npub1low", now - Duration::from_secs(10 * 60));
1411        assert_eq!(queue.next_ready_in(), Some(Duration::ZERO), "a ripe low entry is due now");
1412        queue.push_raw(SyncPriority::High, "npub1high", now);
1413        let wait = queue.next_ready_in().unwrap();
1414        assert!(wait > Duration::from_secs(4) && wait <= Duration::from_secs(5), "a waiting high entry holds the low lane back: {wait:?}");
1415        assert!(queue.get_next_batch().is_empty());
1416        queue.add("npub1high", SyncPriority::Critical, true);
1417        assert_eq!(queue.next_ready_in(), Some(Duration::ZERO), "the superseded high entry no longer counts");
1418    }
1419
1420    #[test]
1421    fn re_adds_while_stalled_stay_bounded() {
1422        let mut queue = ProfileSyncQueue::new();
1423        for _ in 0..100 {
1424            for i in 0..50 {
1425                queue.add(format!("npub1{i}"), SyncPriority::Low, true);
1426            }
1427        }
1428        assert_eq!(queue.live(&queue.low_queue).len(), 50);
1429        assert!(queue.low_queue.len() <= 2 * 50 + 64 + 1, "{} entries for 50 profiles", queue.low_queue.len());
1430    }
1431
1432    #[test]
1433    fn queue_add_and_dedup() {
1434        let mut queue = ProfileSyncQueue::new();
1435
1436        queue.add("npub1alice", SyncPriority::Low, false);
1437        queue.add("npub1alice", SyncPriority::High, false);
1438
1439        // Should be in High queue only (deduped from Low)
1440        assert!(queue.live(&queue.low_queue).is_empty());
1441        assert_eq!(queue.live(&queue.high_queue), ["npub1alice"]);
1442    }
1443
1444    #[test]
1445    fn queue_skips_processing() {
1446        let mut queue = ProfileSyncQueue::new();
1447        queue.mark_processing("npub1bob");
1448
1449        queue.add("npub1bob", SyncPriority::Critical, false);
1450        assert!(queue.critical_queue.is_empty(), "should skip profiles being processed");
1451    }
1452
1453    #[test]
1454    fn queue_cache_window_skips() {
1455        let mut queue = ProfileSyncQueue::new();
1456
1457        // Mark as recently fetched
1458        queue.mark_done("npub1carol");
1459
1460        // Try to add with Low priority (24h cache window) — should skip
1461        queue.add("npub1carol", SyncPriority::Low, false);
1462        assert!(queue.low_queue.is_empty(), "should skip within cache window");
1463
1464        // Force refresh should bypass cache
1465        queue.add("npub1carol", SyncPriority::Low, true);
1466        assert_eq!(queue.low_queue.len(), 1, "force_refresh should bypass cache");
1467    }
1468
1469    #[test]
1470    fn queue_critical_skips_cache() {
1471        let mut queue = ProfileSyncQueue::new();
1472
1473        // Critical has 0s cache window — always fetches
1474        queue.mark_done("npub1dave");
1475        queue.add("npub1dave", SyncPriority::Critical, false);
1476        assert_eq!(queue.critical_queue.len(), 1, "Critical should always fetch");
1477    }
1478
1479    #[test]
1480    fn re_adding_moves_an_entry_between_lanes() {
1481        let mut queue = ProfileSyncQueue::new();
1482        queue.add("npub1a", SyncPriority::Low, true);
1483        queue.add("npub1b", SyncPriority::Low, true);
1484        queue.add("npub1a", SyncPriority::Critical, true);
1485        assert_eq!(queue.live(&queue.low_queue), ["npub1b"]);
1486        assert_eq!(queue.live(&queue.critical_queue), ["npub1a"]);
1487        let batch = queue.get_next_batch();
1488        assert_eq!(batch.len(), 1);
1489        assert_eq!(batch[0].npub, "npub1a");
1490        // Its superseded Low entry never surfaces, even once the Low lane's delay passes.
1491        queue.critical_queue.clear();
1492        queue.add("npub1c", SyncPriority::Low, true);
1493        assert_eq!(queue.live(&queue.low_queue), ["npub1b", "npub1c"]);
1494    }
1495
1496    #[test]
1497    fn a_periodic_re_add_keeps_the_waiting_entry() {
1498        let mut queue = ProfileSyncQueue::new();
1499        queue.push_raw(SyncPriority::Low, "npub1low", Instant::now() - Duration::from_secs(10 * 60));
1500        queue.push_raw(SyncPriority::High, "npub1high", Instant::now() - Duration::from_secs(10));
1501        queue.add("npub1low", SyncPriority::Low, false);
1502        queue.add("npub1high", SyncPriority::Low, false);
1503        assert_eq!(queue.live(&queue.high_queue), ["npub1high"], "a lower re-add never demotes");
1504        assert_eq!(queue.get_next_batch().len(), 1);
1505        let batch = queue.get_next_batch();
1506        assert_eq!(batch.len(), 1, "the ripe Low entry keeps its age");
1507        assert_eq!(batch[0].npub, "npub1low");
1508    }
1509
1510    #[test]
1511    fn get_next_batch_priority_order() {
1512        let mut queue = ProfileSyncQueue::new();
1513
1514        // Add to Low and Critical queues
1515        queue.push_raw(SyncPriority::Low, "npub1low", Instant::now() - Duration::from_secs(600));
1516        queue.push_raw(SyncPriority::Critical, "npub1critical", Instant::now());
1517
1518        let batch = queue.get_next_batch();
1519        assert_eq!(batch.len(), 1);
1520        assert_eq!(batch[0].npub, "npub1critical", "Critical should process before Low");
1521    }
1522
1523    #[test]
1524    fn get_next_batch_respects_delay() {
1525        let mut queue = ProfileSyncQueue::new();
1526
1527        // Add a High priority entry just now (5s delay required)
1528        queue.push_raw(SyncPriority::High, "npub1new", Instant::now());
1529
1530        let batch = queue.get_next_batch();
1531        assert!(batch.is_empty(), "should not process before delay elapses");
1532    }
1533
1534    #[test]
1535    fn mark_done_updates_last_fetched() {
1536        let mut queue = ProfileSyncQueue::new();
1537        queue.mark_processing("npub1eve");
1538        assert!(queue.processing.contains("npub1eve"));
1539
1540        queue.mark_done("npub1eve");
1541        assert!(!queue.processing.contains("npub1eve"));
1542        assert!(queue.last_fetched.contains("npub1eve"));
1543    }
1544
1545    #[test]
1546    fn fetches_older_than_every_window_are_forgotten() {
1547        let mut queue = ProfileSyncQueue::new();
1548        let day = 24 * 60 * 60;
1549        let now = 3 * day;
1550        queue.last_fetched.insert("npub1stale", now - day);
1551        queue.last_fetched.insert("npub1edge", now - day + 1);
1552        queue.last_fetched.insert("npub1fresh", now - 10);
1553        queue.prune_fetched(now);
1554        assert!(!queue.last_fetched.contains("npub1stale"), "a day old gates nothing");
1555        assert!(queue.last_fetched.contains("npub1edge"), "inside the Low window it still gates a Low re-add");
1556        assert!(queue.last_fetched.contains("npub1fresh"));
1557    }
1558
1559    #[test]
1560    fn mark_done_sweeps_every_so_often() {
1561        let mut queue = ProfileSyncQueue::new();
1562        for i in 0..PRUNE_EVERY - 1 {
1563            queue.mark_done(&format!("npub1done{i}"));
1564        }
1565        assert_eq!(queue.done_since_prune, PRUNE_EVERY - 1);
1566        queue.last_fetched.insert("npub1future", u32::MAX);
1567        queue.mark_done("npub1last");
1568        assert_eq!(queue.done_since_prune, 0, "the sweep ran");
1569        assert_eq!(queue.last_fetched.len(), PRUNE_EVERY as usize + 1, "nothing recent was dropped");
1570    }
1571
1572    #[test]
1573    fn the_cache_window_reads_whole_seconds_since_the_fetch() {
1574        use nostr_sdk::prelude::{Keys, ToBech32};
1575        let npub = Keys::generate().public_key().to_bech32().unwrap();
1576        let mut queue = ProfileSyncQueue::new();
1577        let now = queue.secs();
1578        queue.last_fetched.insert(&npub, now);
1579        queue.add(npub.clone(), SyncPriority::High, false);
1580        assert!(queue.high_queue.is_empty(), "a canonical npub is found by its key bytes");
1581
1582        let mut queue = ProfileSyncQueue::new();
1583        queue.epoch = queue.epoch.checked_sub(Duration::from_secs(400)).unwrap_or(queue.epoch);
1584        if queue.secs() >= 400 {
1585            queue.last_fetched.insert(&npub, queue.secs() - 301);
1586            queue.add(npub.clone(), SyncPriority::Medium, false);
1587            assert!(queue.medium_queue.is_empty(), "301 s is inside Medium's 30 min");
1588            queue.add(npub.clone(), SyncPriority::High, false);
1589            assert_eq!(queue.live(&queue.high_queue), [npub.as_str()], "and past High's 5 min");
1590        }
1591    }
1592
1593    fn consenting_profile() -> Profile {
1594        let mut p = Profile::new();
1595        p.from_metadata(
1596            Metadata::from_json(r#"{"name":"old","about":"bio","picture":"https://x/a.png","lud16":"a@b.c","stream_consent":true}"#).unwrap(),
1597        );
1598        p
1599    }
1600
1601    #[test]
1602    fn an_own_profile_edit_carries_stream_consent_forward() {
1603        let p = consenting_profile();
1604        assert!(p.flags.is_stream_consent());
1605
1606        let meta = own_metadata(&p, "new", "", "", "", false);
1607        assert!(crate::profile::metadata_stream_consent(&meta), "a rename keeps consent");
1608        assert_eq!(meta.name.as_deref(), Some("new"));
1609        assert_eq!(meta.about.as_deref(), Some("bio"));
1610        assert_eq!(meta.picture.as_deref(), Some("https://x/a.png"));
1611        assert_eq!(meta.lud16.as_deref(), Some("a@b.c"));
1612        assert!(!meta.custom.contains_key("bot"));
1613
1614        let mut republished = p.clone();
1615        assert!(!republished.from_metadata(own_metadata(&p, "", "", "", "", false)), "a no-op edit changes nothing");
1616        assert!(republished.flags.is_stream_consent());
1617    }
1618
1619    /// A relay copy, as `fetch_own_kind0` reads one.
1620    fn kind0(content: &str, tags: &[&[&str]]) -> OwnKind0 {
1621        OwnKind0 {
1622            content: serde_json::from_str(content).unwrap(),
1623            tags: tags.iter().map(|t| t.iter().map(|s| s.to_string()).collect()).collect(),
1624        }
1625    }
1626
1627    /// A real profile that leans on what Vector doesn't model: `emoji` tags drawing a name
1628    /// from custom emoji, Ditto's `fields`, a camelCase `displayName`.
1629    fn henky() -> OwnKind0 {
1630        let content: String = serde_json::from_str(HENKY_CONTENT).unwrap();
1631        OwnKind0 { content: serde_json::from_str(&content).unwrap(), tags: serde_json::from_str(HENKY_TAGS).unwrap() }
1632    }
1633    const HENKY_CONTENT: &str = r#####""{\"about\":\"Sysadmin | AI Entertainment Enthusiast | Game Server Operator | Liberal (as in Liberty) Nationalist (each country has a right to be sovereign and should not impose their will on other countries)\\r\\n- There is only a paradox if you don't admit it\\r\\n\\r\\nSee me post with a really long address on mastodon? That's a bridge. My real profile is : https://ditto.pub/@henk.tech\\n\\nMy webhost blocks some requests behind proof of work, if my NIP-05 errors for you then you can verify it manually. I unfortunately can't disable this.\",\"bot\":false,\"name\":\":H::e::n::k::y:!!\",\"nip05\":\"Henk.Tech\",\"picture\":\"https://turbo.henk.tech/avatar/HenkyAnimated.gif\",\"fields\":[[\"KoboldAI\",\"https://koboldai.com\"]],\"website\":\"https://henk.tech\",\"displayName\":\"Henky!!\",\"banner\":\"https://turbo.henk.tech/avatar/BannerHenky.png\"}""#####;
1634    const HENKY_TAGS: &str = r#####"[["emoji", "H", "https://dl.vanderwarker.family/images/nostr/emojis/language/human/mc_font/h.png"], ["emoji", "e", "https://dl.vanderwarker.family/images/nostr/emojis/language/human/mc_font/e.png"], ["emoji", "n", "https://dl.vanderwarker.family/images/nostr/emojis/language/human/mc_font/n.png"], ["emoji", "k", "https://dl.vanderwarker.family/images/nostr/emojis/language/human/mc_font/k.png"], ["emoji", "y", "https://dl.vanderwarker.family/images/nostr/emojis/language/human/mc_font/y.png"], ["alt", "User profile for :H::e::n::k::y:!!"], ["name", ":H::e::n::k::y:!!"], ["picture", "https://turbo.henk.tech/avatar/HenkyAnimated.gif"], ["website", "https://henk.tech"], ["about", "Sysadmin | AI Entertainment Enthusiast | Game Server Operator | Liberal (as in Liberty) Nationalist (each country has a right to be sovereign and should not impose their will on other countries)\r\n- There is only a paradox if you don't admit it\r\n\r\nSee me post with a really long address on mastodon? That's a bridge. My real profile is : https://ditto.pub/@henk.tech\n\nMy webhost blocks some requests behind proof of work, if my NIP-05 errors for you then you can verify it manually. I unfortunately can't disable this."], ["nip05", "Henk.Tech"], ["client", "Amethyst"], ["banner", "https://turbo.henk.tech/avatar/BannerHenky.png"]]"#####;
1635
1636    #[test]
1637    fn a_save_keeps_every_key_and_tag_another_client_wrote() {
1638        let before = henky();
1639        let edit = Kind0Edit { about: "new bio", ..Default::default() };
1640        let after = edit_kind0(before.clone(), &edit);
1641
1642        assert_eq!(after.content.get("about"), Some(&serde_json::json!("new bio")));
1643        for (key, value) in &before.content {
1644            if key != "about" {
1645                assert_eq!(after.content.get(key), Some(value), "{key} is carried verbatim");
1646            }
1647        }
1648        let emoji = |k: &OwnKind0| k.tags.iter().filter(|t| t[0] == "emoji").cloned().collect::<Vec<_>>();
1649        assert!(!emoji(&before).is_empty());
1650        assert_eq!(emoji(&after), emoji(&before), "the name's custom emoji survive");
1651        assert!(names_vector(&after.tags));
1652        assert_eq!(after.tags.len(), before.tags.iter().filter(|t| t[0] != "client").count() + 1);
1653    }
1654
1655    #[test]
1656    fn our_client_tag_replaces_another_clients_and_is_never_doubled() {
1657        let other = kind0(r#"{"name":"a"}"#, &[&["client", "Amethyst"], &["i", "github:a", "proof"]]);
1658        let saved = edit_kind0(other, &Kind0Edit::default());
1659        assert_eq!(saved.tags, vec![vec!["i".to_string(), "github:a".into(), "proof".into()], vec!["client".into(), "vector".into()]]);
1660        let again = edit_kind0(saved.clone(), &Kind0Edit::default());
1661        assert_eq!(again.tags, saved.tags);
1662    }
1663
1664    #[test]
1665    fn a_profile_vector_reads_oddly_still_shows_what_it_can() {
1666        let odd = kind0(r#"{"name":"a","website":42,"about":["x"],"fields":[["k","v"]]}"#, &[]);
1667        let view = metadata_view(&odd.content);
1668        assert_eq!(view.name.as_deref(), Some("a"));
1669        assert_eq!(view.website, None);
1670        // Edited, the odd values go back out exactly as they came.
1671        let saved = edit_kind0(odd, &Kind0Edit { name: "b", ..Default::default() });
1672        assert_eq!(saved.content.get("website"), Some(&serde_json::json!(42)));
1673        assert_eq!(saved.content.get("fields"), Some(&serde_json::json!([["k", "v"]])));
1674    }
1675
1676    #[test]
1677    fn a_blank_banner_removes_it_and_an_empty_one_keeps_it() {
1678        let mut p = Profile::new();
1679        p.from_metadata(Metadata::from_json(r#"{"name":"a","banner":"https://x/b.png"}"#).unwrap());
1680        assert_eq!(p.banner(), "https://x/b.png");
1681
1682        assert_eq!(own_metadata(&p, "", "", "", "", false).banner.as_deref(), Some("https://x/b.png"));
1683        let removed = own_metadata(&p, "", "", " ", "", false);
1684        assert_eq!(removed.banner, None);
1685        let remote = kind0(r#"{"name":"a","banner":"https://x/b.png","website":"https://w"}"#, &[]);
1686        let kept = edit_kind0(remote.clone(), &Kind0Edit::default());
1687        assert_eq!(kept.content.get("banner"), Some(&serde_json::json!("https://x/b.png")));
1688        let edited = edit_kind0(remote, &Kind0Edit { banner: " ", ..Default::default() });
1689        assert!(!edited.content.contains_key("banner"));
1690        assert_eq!(edited.content.get("website"), Some(&serde_json::json!("https://w")), "every other key stands");
1691
1692        assert!(p.from_metadata(removed), "a kind-0 without its banner clears it");
1693        assert_eq!(p.banner(), "");
1694    }
1695
1696    #[test]
1697    fn an_own_profile_without_consent_publishes_no_key() {
1698        let mut p = consenting_profile();
1699        p.flags.set_stream_consent(false);
1700        let meta = own_metadata(&p, "", "", "", "about", true);
1701        assert!(!meta.custom.contains_key(crate::profile::STREAM_CONSENT_KEY));
1702        assert_eq!(meta.custom.get("bot"), Some(&serde_json::Value::Bool(true)));
1703    }
1704
1705    #[test]
1706    fn a_fresh_device_with_no_relay_copy_never_publishes_a_blank_profile() {
1707        assert!(consent_plan(None, &Profile::default(), true).is_err());
1708        // With a profile of its own to carry, it publishes that.
1709        let mut p = consenting_profile();
1710        p.flags.set_stream_consent(false);
1711        let Ok(ConsentPlan::Publish(kind0)) = consent_plan(None, &p, true) else { panic!("publishes the local copy") };
1712        assert!(consents(&kind0.content));
1713        assert_eq!(kind0.content.get("name"), Some(&serde_json::json!("old")));
1714        assert!(names_vector(&kind0.tags));
1715    }
1716
1717    #[test]
1718    fn a_consent_change_keeps_every_key_and_tag_the_relay_copy_holds() {
1719        let remote = kind0(r#"{"name":"r","pronouns":"they","bot":true}"#, &[&["emoji", "r", "https://x/r.png"]]);
1720        let Ok(ConsentPlan::Publish(on)) = consent_plan(Some(remote), &Profile::default(), true) else {
1721            panic!("a change is published")
1722        };
1723        assert!(consents(&on.content));
1724        assert_eq!(on.content.get("pronouns"), Some(&serde_json::json!("they")));
1725        assert_eq!(on.content.get("bot"), Some(&serde_json::json!(true)));
1726        assert_eq!(on.content.get("name"), Some(&serde_json::json!("r")), "the relay copy wins over the local one");
1727        assert!(on.tags.contains(&vec!["emoji".to_string(), "r".into(), "https://x/r.png".into()]));
1728
1729        let Ok(ConsentPlan::Publish(off)) = consent_plan(Some(on), &consenting_profile(), false) else {
1730            panic!("withdrawing is published")
1731        };
1732        assert!(!off.content.contains_key(crate::profile::STREAM_CONSENT_KEY), "off is the absent key");
1733        assert_eq!(off.content.get("pronouns"), Some(&serde_json::json!("they")));
1734    }
1735
1736    #[test]
1737    fn a_relay_copy_that_already_says_it_publishes_nothing() {
1738        let remote = kind0(r#"{"name":"r","stream_consent":true}"#, &[]);
1739        assert!(matches!(consent_plan(Some(remote), &Profile::default(), true), Ok(ConsentPlan::Unchanged(_))));
1740        let bare = kind0(r#"{"name":"r"}"#, &[]);
1741        assert!(matches!(consent_plan(Some(bare), &consenting_profile(), false), Ok(ConsentPlan::Unchanged(_))));
1742    }
1743
1744    #[test]
1745    fn an_sdk_edit_of_the_relay_copy_keeps_its_other_fields() {
1746        let remote = kind0(
1747            r#"{"name":"old","display_name":"Old","nip05":"a@b.c","lud16":"z@b.c","stream_consent":true,"pronouns":"they"}"#,
1748            &[],
1749        );
1750        let edit = Kind0Edit { name: "new", avatar: "https://x/a.png", bot: true, ..Default::default() };
1751        let saved = edit_kind0(remote, &edit);
1752        let meta = metadata_view(&saved.content);
1753        assert_eq!(meta.name.as_deref(), Some("new"));
1754        assert_eq!(meta.picture.as_deref(), Some("https://x/a.png"));
1755        assert_eq!(meta.display_name.as_deref(), Some("Old"));
1756        assert_eq!(meta.nip05.as_deref(), Some("a@b.c"));
1757        assert_eq!(meta.lud16.as_deref(), Some("z@b.c"));
1758        assert!(consents(&saved.content), "consent is not revoked by an edit");
1759        assert_eq!(saved.content.get("pronouns"), Some(&serde_json::json!("they")));
1760        assert_eq!(saved.content.get("bot"), Some(&serde_json::json!(true)));
1761    }
1762
1763    #[test]
1764    fn noop_handler_compiles() {
1765        let handler = NoOpProfileSyncHandler;
1766        let slim = crate::SlimProfile::default();
1767        handler.on_profile_fetched(&slim, "", "");
1768    }
1769}
1770
1771/// The profile processor's benchmark, run by `benches/core`: in-crate for the private queue.
1772#[cfg(feature = "bench")]
1773#[doc(hidden)]
1774pub mod bench {
1775    use super::*;
1776    use std::sync::atomic::{AtomicUsize, Ordering};
1777
1778    /// Thread wakeups while the queue sits empty, and how long a user-clicked refresh waits
1779    /// before the processor picks it up.
1780    pub fn processor() {
1781        static UNPARKS: AtomicUsize = AtomicUsize::new(0);
1782        const IDLE: Duration = Duration::from_secs(20);
1783        let rt = tokio::runtime::Builder::new_current_thread()
1784            .enable_all()
1785            .on_thread_unpark(|| {
1786                UNPARKS.fetch_add(1, Ordering::Relaxed);
1787            })
1788            .build()
1789            .unwrap();
1790        rt.block_on(async {
1791            // spawn-detached: the benchmark's own runtime, no account.
1792            tokio::spawn(start_profile_sync_processor(Arc::new(NoOpProfileSyncHandler)));
1793            tokio::time::sleep(Duration::from_millis(50)).await;
1794            let before = UNPARKS.load(Ordering::Relaxed);
1795            tokio::time::sleep(IDLE).await;
1796            let woke = UNPARKS.load(Ordering::Relaxed) - before;
1797            println!("idle wakeups: {woke} in {IDLE:?} ({:.2}/min)", woke as f64 * 60.0 / IDLE.as_secs_f64());
1798
1799            let mut waits = Vec::new();
1800            for i in 0..20u64 {
1801                tokio::time::sleep(Duration::from_millis(700 + i * 37)).await;
1802                let npub = format!("npub1bench{i}");
1803                let t = Instant::now();
1804                refresh_profile_now(npub.clone());
1805                while profile_sync_queue().lock().unwrap().last_fetched.get(&npub).is_none() {
1806                    tokio::time::sleep(Duration::from_millis(1)).await;
1807                }
1808                waits.push(t.elapsed().as_secs_f64() * 1e3);
1809            }
1810            waits.sort_by(|a, b| a.partial_cmp(b).unwrap());
1811            println!(
1812                "critical refresh pickup: median {:.1} ms, max {:.1} ms",
1813                waits[waits.len() / 2],
1814                waits[waits.len() - 1]
1815            );
1816        });
1817    }
1818}
1819
1820#[cfg(test)]
1821mod request_tests {
1822    use super::*;
1823    use crate::chat::Chat;
1824
1825    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
1826        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1827        crate::db::close_database();
1828        crate::db::clear_id_caches();
1829        let tmp = tempfile::tempdir().unwrap();
1830        let account = Keys::generate().public_key().to_bech32().unwrap();
1831        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
1832        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
1833        crate::db::set_current_account(account.clone()).unwrap();
1834        crate::db::init_database(&account).unwrap();
1835        (tmp, guard)
1836    }
1837
1838    fn theirs(seed: u8) -> crate::types::Message {
1839        crate::types::Message { id: format!("{:02x}", seed).repeat(32), content: "hi".into(), at: 1_700_000_000_000 + seed as u64, ..Default::default() }
1840    }
1841
1842    #[tokio::test]
1843    async fn accepting_a_request_releases_its_sender_and_survives_a_reload() {
1844        let (_tmp, _guard) = init_test_db();
1845        let peer = Keys::generate().public_key().to_bech32().unwrap();
1846        {
1847            let mut guard = STATE.lock().await;
1848            let state = &mut *guard;
1849            let mut chat = Chat::new_dm(peer.clone(), &mut state.interner);
1850            chat.add_message(theirs(1), &mut state.interner);
1851            state.chats.push(chat);
1852        }
1853        assert!(crate::requests::pictures_held(&peer).await, "a stranger's pictures wait");
1854
1855        accept_chat(peer.clone()).await.unwrap();
1856        assert!(!crate::requests::pictures_held(&peer).await, "accepted: their pictures may load");
1857
1858        let row = crate::db::chats::get_all_chats().unwrap().into_iter().find(|c| c.id == peer).expect("chat saved");
1859        let mut interner = crate::compact::NpubInterner::new();
1860        let mut reloaded = row.to_chat(&mut interner);
1861        reloaded.add_message(theirs(2), &mut interner);
1862        assert!(!reloaded.is_request(), "the acceptance outlives a reload");
1863    }
1864}