Skip to main content

vector_core/
state.rs

1//! Global state management — ChatState, globals, processing gate.
2//!
3//! All Tauri-specific globals (TAURI_APP) have been removed. Event emission
4//! uses the `EventEmitter` trait via `crate::traits::emit_event`.
5
6use nostr_sdk::prelude::*;
7use std::sync::RwLock;
8use std::collections::HashSet;
9use std::sync::atomic::{AtomicBool, Ordering};
10use tokio::sync::Mutex;
11
12use crate::chat::{Chat, ChatType};
13use crate::compact::{CompactMessage, CompactAttachment, NpubInterner, NO_NPUB};
14use crate::profile::{Profile, SlimProfile};
15use crate::types::{Message, Reaction};
16use crate::traits::emit_event;
17
18// ============================================================================
19// WrapperIdCache — Hybrid duplicate detection during sync
20// ============================================================================
21
22/// Outside a sync the ledger dedups; only a catch-up batch whose ledger writes are still
23/// buffered needs remembering.
24const IDLE_PENDING_CAP: usize = 512;
25
26pub struct WrapperIdCache {
27    historical: Vec<[u8; 32]>,
28    pending: HashSet<[u8; 32]>,
29    /// Between `load` and `clear`: every insert is kept until the dump.
30    syncing: bool,
31    /// Idle inserts, oldest first, so `pending` stays at [`IDLE_PENDING_CAP`].
32    recent: std::collections::VecDeque<[u8; 32]>,
33}
34
35impl WrapperIdCache {
36    pub fn new() -> Self {
37        Self { historical: Vec::new(), pending: HashSet::new(), syncing: false, recent: std::collections::VecDeque::new() }
38    }
39
40    pub fn load(&mut self, mut ids: Vec<[u8; 32]>) {
41        ids.sort_unstable();
42        self.historical = ids;
43        self.pending.clear();
44        self.recent = std::collections::VecDeque::new();
45        self.syncing = true;
46    }
47
48    #[inline]
49    pub fn contains(&self, id: &[u8; 32]) -> bool {
50        self.historical.binary_search(id).is_ok() || self.pending.contains(id)
51    }
52
53    #[inline]
54    pub fn insert(&mut self, id: [u8; 32]) {
55        if !self.pending.insert(id) || self.syncing {
56            return;
57        }
58        if self.recent.len() == IDLE_PENDING_CAP {
59            if let Some(old) = self.recent.pop_front() {
60                self.pending.remove(&old);
61            }
62        }
63        self.recent.push_back(id);
64    }
65
66    pub fn clear(&mut self) {
67        self.historical.clear();
68        self.historical.shrink_to_fit();
69        self.pending.clear();
70        self.pending.shrink_to_fit();
71        self.recent = std::collections::VecDeque::new();
72        self.syncing = false;
73    }
74
75    pub fn len(&self) -> usize { self.historical.len() + self.pending.len() }
76
77    pub fn is_empty(&self) -> bool { self.historical.is_empty() && self.pending.is_empty() }
78}
79
80impl Default for WrapperIdCache {
81    fn default() -> Self { Self::new() }
82}
83
84// ============================================================================
85// Globals
86// ============================================================================
87
88pub static TRUSTED_RELAYS: &[&str] = &[
89    "wss://jskitty.com/nostr",
90    "wss://asia.vectorapp.io/nostr",
91    "wss://nostr.computingcache.com",
92    // Also listed in DISCOVERY_READ_ONLY_RELAYS: Ditto once ack'd stranger
93    // kind-10050 writes with OK true and silently dropped them, so it must
94    // never count toward the relay-list freshness anchor. General traffic
95    // (DMs, communities) is unrestricted per its NIP-11.
96    "wss://relay.ditto.pub",
97];
98
99/// Discovery Relays: widely-used indexers queried/written for relay-list
100/// events (kind 10050) ONLY — never DMs, profiles, or communities. They give
101/// list syncs and publishes a rendezvous point that doesn't depend on the
102/// user's own relay set overlapping anyone else's. Every entry must be
103/// verified to ACCEPT AND SERVE kind 10050 from unknown pubkeys (write +
104/// readback); accept-then-silently-drop policy relays reduce coverage
105/// invisibly.
106pub static DISCOVERY_RELAYS: &[&str] = &[
107    "wss://purplepag.es",
108    "wss://relay.primal.net",
109    "wss://nos.lol",
110    "wss://relay.snort.social",
111];
112
113/// Read-only Discovery Relays: queried when SYNCING relay lists but never
114/// published to. Ditto acks stranger kind-10050 writes with OK true and then
115/// silently drops them, so counting it as a publish landing would falsely
116/// advance the list-freshness anchor — but it serves ESTABLISHED accounts'
117/// lists honestly, and those are exactly the users whose existing list a
118/// fresh Vector login must find before it dares bootstrap-publish.
119pub static DISCOVERY_READ_ONLY_RELAYS: &[&str] = &["wss://relay.ditto.pub"];
120
121/// Every discovery relay url (writable + read-only) — the fetch/pool/identity
122/// set. Publish copies use `DISCOVERY_RELAYS` alone.
123pub fn discovery_relay_iter() -> impl Iterator<Item = &'static str> {
124    DISCOVERY_RELAYS
125        .iter()
126        .chain(DISCOVERY_READ_ONLY_RELAYS.iter())
127        .copied()
128}
129
130pub async fn active_trusted_relays() -> Vec<&'static str> {
131    let Some(client) = nostr_client() else { return Vec::new() };
132    let pool_relays = client.relays().await;
133    TRUSTED_RELAYS.iter().copied()
134        .filter(|url| {
135            let normalized = url.trim_end_matches('/');
136            pool_relays.keys().any(|r| r.as_str().trim_end_matches('/') == normalized)
137        })
138        .collect()
139}
140
141/// Blossom media servers with failover: this account's resolved list (defaults
142/// minus its disabled ones, plus its enabled customs).
143///
144/// Per-account, and consequential — it decides where THIS account's
145/// attachments are uploaded, so account A's self-hosted destination must never
146/// still be selected under account B. Resolved from the account's settings on first
147/// use, and replaced by `blossom_servers::refresh_cache` after an edit.
148#[derive(Default)]
149struct BlossomServers(std::sync::Mutex<Option<Vec<String>>>);
150
151pub fn init_blossom_servers() -> Vec<String> {
152    crate::blossom_servers::DEFAULT_BLOSSOM_SERVERS
153        .iter().map(|s| s.to_string()).collect()
154}
155
156pub fn get_blossom_servers() -> Vec<String> {
157    let owner = crate::db::current_session().scoped::<BlossomServers, BlossomServers>();
158    if let Some(servers) = owner.0.lock().unwrap().clone() {
159        return servers;
160    }
161    // Resolved outside the lock. Until the account's database opens there is nothing to
162    // resolve from, so the defaults stand in without being kept.
163    match crate::blossom_servers::resolve_if_open() {
164        Some(servers) => owner.0.lock().unwrap().get_or_insert(servers).clone(),
165        None => init_blossom_servers(),
166    }
167}
168
169/// Install this account's resolved server list.
170pub fn set_blossom_servers(servers: Vec<String>) {
171    let owner = crate::db::current_session().scoped::<BlossomServers, BlossomServers>();
172    *owner.0.lock().unwrap() = Some(servers);
173}
174
175pub static MNEMONIC_SEED: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
176pub static PENDING_NSEC: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
177
178/// Staged bunker metadata between `connect_bunker` / `start_nostrconnect_session`
179/// and the subsequent encryption-flow commit. URL is wrapped in `Zeroizing`
180/// because it contains the NIP-46 single-use pairing secret; the pubkey hex
181/// is non-secret. `setup_encryption` / `skip_encryption` reads this when
182/// `signer_kind() == Bunker` to write the right settings rows via
183/// `commit_bunker_account_setup`.
184///
185/// Tuple order: (bunker_url, remote_pubkey_hex).
186pub static PENDING_BUNKER_SETUP:
187    std::sync::Mutex<Option<(zeroize::Zeroizing<String>, String)>> =
188    std::sync::Mutex::new(None);
189
190#[inline]
191pub fn set_pending_bunker_setup(url: String, remote_pk_hex: String) {
192    *PENDING_BUNKER_SETUP.lock().unwrap() =
193        Some((zeroize::Zeroizing::new(url), remote_pk_hex));
194}
195
196#[inline]
197pub fn pending_bunker_setup() -> Option<(String, String)> {
198    PENDING_BUNKER_SETUP.lock().unwrap()
199        .as_ref()
200        .map(|(z, pk)| (String::clone(&**z), pk.clone()))
201}
202
203#[inline]
204pub fn clear_pending_bunker_setup() {
205    *PENDING_BUNKER_SETUP.lock().unwrap() = None;
206}
207
208/// Staged NIP-55 pairing result between `login_with_nip55` and the subsequent
209/// encryption-flow commit. Both fields are public material (identity pubkey +
210/// signer package name), so no `Zeroizing` — unlike bunker, a NIP-55 account
211/// stages nothing secret. `setup_encryption` / `skip_encryption` reads this
212/// when `signer_kind() == Nip55` to write the right settings rows via
213/// `commit_nip55_account_setup`.
214///
215/// Tuple order: (user_pubkey_hex, signer_package).
216pub static PENDING_NIP55_SETUP: std::sync::Mutex<Option<(String, String)>> =
217    std::sync::Mutex::new(None);
218
219#[inline]
220pub fn set_pending_nip55_setup(user_pubkey_hex: String, signer_package: String) {
221    *PENDING_NIP55_SETUP.lock().unwrap() = Some((user_pubkey_hex, signer_package));
222}
223
224#[inline]
225pub fn pending_nip55_setup() -> Option<(String, String)> {
226    PENDING_NIP55_SETUP.lock().unwrap().clone()
227}
228
229#[inline]
230pub fn clear_pending_nip55_setup() {
231    *PENDING_NIP55_SETUP.lock().unwrap() = None;
232}
233
234pub static ENCRYPTION_KEY: crate::crypto::GuardedKey = crate::crypto::GuardedKey::empty();
235
236/// The at-rest key a PIN change just replaced, kept openable for a few seconds so a read that
237/// straddled the change still opens. Empty at every other time.
238pub static PREVIOUS_AT_REST_KEY: crate::crypto::GuardedKey = crate::crypto::GuardedKey::empty();
239
240pub static ENCRYPTION_ENABLED: AtomicBool = AtomicBool::new(false);
241
242#[inline]
243pub fn is_encryption_enabled_fast() -> bool { ENCRYPTION_ENABLED.load(Ordering::Acquire) }
244
245#[inline]
246pub fn set_encryption_enabled(enabled: bool) { ENCRYPTION_ENABLED.store(enabled, Ordering::Release); }
247
248/// Resolve "is this account encrypted?" from raw DB settings. Single
249/// source of truth — every caller (crypto::is_encryption_enabled,
250/// init_encryption_enabled, Android bg-sync) delegates here, so the
251/// answer is consistent regardless of code path.
252///
253/// Rules:
254///   * `encryption_enabled = "false"` → not encrypted (explicit opt-out)
255///   * `encryption_enabled = "true"`  → encrypted (explicit opt-in)
256///   * row missing                    → encrypted iff `security_type` exists
257///
258/// The `security_type` fallback handles pre-multi-account installs that
259/// wrote `security_type` without `encryption_enabled`. A brand-new
260/// account has neither row, so the answer is "not encrypted".
261pub fn resolve_encryption_enabled(
262    encryption_enabled_row: Option<&str>,
263    security_type_row: Option<&str>,
264) -> bool {
265    match encryption_enabled_row {
266        Some("false") => false,
267        Some(_) => true,
268        None => security_type_row.is_some(),
269    }
270}
271
272/// Resolve from the current account's DB via the global settings helper.
273/// Returns `false` if the DB is not yet open.
274pub fn resolve_encryption_enabled_from_db() -> bool {
275    let enc = crate::db::get_sql_setting("encryption_enabled".to_string()).ok().flatten();
276    let sec = crate::db::get_sql_setting("security_type".to_string()).ok().flatten();
277    resolve_encryption_enabled(enc.as_deref(), sec.as_deref())
278}
279
280pub fn init_encryption_enabled() {
281    let enabled = resolve_encryption_enabled_from_db();
282    set_encryption_enabled(enabled);
283}
284
285#[cfg(test)]
286mod resolve_encryption_enabled_tests {
287    use super::*;
288
289    #[test]
290    fn explicit_false_wins_even_with_security_type() {
291        assert!(!resolve_encryption_enabled(Some("false"), Some("password")));
292    }
293
294    #[test]
295    fn explicit_true_is_encrypted() {
296        assert!(resolve_encryption_enabled(Some("true"), None));
297    }
298
299    #[test]
300    fn missing_row_defaults_to_security_type_presence() {
301        // Pre-multi-account install that wrote security_type but not the
302        // encryption_enabled flag — must be treated as encrypted.
303        assert!(resolve_encryption_enabled(None, Some("password")));
304        // Fresh account with no rows — must be treated as unencrypted.
305        assert!(!resolve_encryption_enabled(None, None));
306    }
307
308    #[test]
309    fn explicit_non_false_value_is_encrypted() {
310        // Anything other than the literal "false" string is treated as
311        // encrypted, matching the previous behaviour of `v != "false"`.
312        assert!(resolve_encryption_enabled(Some("1"), None));
313        assert!(resolve_encryption_enabled(Some(""), None));
314    }
315}
316
317// ============================================================================
318// Per-session globals — must be resettable for inline account swap
319// ============================================================================
320//
321// `NOSTR_CLIENT` and `MY_PUBLIC_KEY` are RwLock<Option<_>> rather than OnceLock
322// so `reset_session()` can swap them atomically — mobile cannot rely on
323// `app.restart()`. Callers should prefer the helpers below over locking directly.
324
325/// The relay client and identity this account signs and publishes with.
326///
327/// On the session, not global: a task that outlived a swap would otherwise
328/// reach the NEW account's client and publish the previous account's payload
329/// under the wrong identity. A bound task reaches the client it started with,
330/// which the swap has already shut down, so its send fails instead.
331///
332/// A login fills these before its database exists — creating an account
333/// installs the keys and client, and only reaches `init_database` once the
334/// user has chosen a PIN — which is why binding a session to a database keeps
335/// what it holds rather than replacing it.
336struct ActiveClient;
337struct ActiveIdentity;
338
339fn active_client() -> std::sync::Arc<RwLock<Option<Client>>> {
340    crate::db::current_session().scoped::<ActiveClient, _>()
341}
342
343fn active_identity() -> std::sync::Arc<RwLock<Option<PublicKey>>> {
344    crate::db::current_session().scoped::<ActiveIdentity, _>()
345}
346
347pub static MY_SECRET_KEY: crate::crypto::GuardedKey = crate::crypto::GuardedKey::empty();
348
349/// Get a clone of the active Nostr client. The clone is cheap — `Client`
350/// is internally `Arc`-counted, so all clones share connections, signers,
351/// and subscription state. Returns `None` when no session is active.
352#[inline]
353pub fn nostr_client() -> Option<Client> {
354    active_client().read().unwrap().as_ref().cloned()
355}
356
357/// Returns `true` when there is an active session (client + pubkey set).
358#[inline]
359pub fn has_active_session() -> bool {
360    active_client().read().unwrap().is_some()
361}
362
363/// Get the active user's public key. `PublicKey` is `Copy`, so this is by-value.
364#[inline]
365pub fn my_public_key() -> Option<PublicKey> {
366    *active_identity().read().unwrap()
367}
368
369/// Install the Nostr client for the current session. Replaces any prior client
370/// without shutting it down — `reset_session()` is responsible for orderly
371/// teardown of the outgoing client.
372#[inline]
373pub fn set_nostr_client(client: Client) {
374    *active_client().write().unwrap() = Some(client);
375}
376
377/// Install `client` only if this session has none yet, reporting whether it
378/// took. Logins race on Android, where a service-only background sync can
379/// install a client before the Activity's login reaches this point; the loser
380/// must drop its own rather than replace a live one.
381#[inline]
382pub fn set_nostr_client_if_absent(client: Client) -> bool {
383    let owner = active_client();
384    let mut slot = owner.write().unwrap();
385    if slot.is_some() {
386        return false;
387    }
388    *slot = Some(client);
389    true
390}
391
392/// Install the active user's public key for the current session.
393#[inline]
394pub fn set_my_public_key(pk: PublicKey) {
395    *active_identity().write().unwrap() = Some(pk);
396    crate::transport::prelogin::note_identity(&pk);
397}
398
399/// Atomically take the current Nostr client out of global state.
400/// Used by `reset_session()` so the post-take shutdown call doesn't race
401/// with new readers.
402#[inline]
403pub fn take_nostr_client() -> Option<Client> {
404    active_client().write().unwrap().take()
405}
406
407/// Clear `MY_PUBLIC_KEY`. The Nostr client is taken separately via
408/// `take_nostr_client()` so the caller can shut it down before this clear.
409#[inline]
410pub fn clear_my_public_key() {
411    *active_identity().write().unwrap() = None;
412}
413
414#[derive(Clone)]
415pub struct PendingInviteAcceptance {
416    pub invite_code: String,
417    pub inviter_pubkey: PublicKey,
418}
419
420// Per-session: tracks an invite captured during account-creation that should
421// be broadcast to relays once login finishes. Must reset across accounts so a
422// pending invite captured for account A doesn't auto-execute on account B.
423/// Per-account: an invite captured while creating account A must never
424/// auto-execute once account B is live.
425struct PendingInvite;
426
427fn pending_invite_slot() -> std::sync::Arc<RwLock<Option<PendingInviteAcceptance>>> {
428    crate::db::current_session().scoped::<PendingInvite, _>()
429}
430
431#[inline]
432pub fn pending_invite() -> Option<PendingInviteAcceptance> {
433    pending_invite_slot().read().unwrap().clone()
434}
435
436#[inline]
437pub fn set_pending_invite(invite: PendingInviteAcceptance) {
438    *pending_invite_slot().write().unwrap() = Some(invite);
439}
440
441#[inline]
442pub fn clear_pending_invite() {
443    *pending_invite_slot().write().unwrap() = None;
444}
445
446// ============================================================================
447// Session generation — defends background tasks against account swaps
448// ============================================================================
449//
450
451/// Session-scoped tombstones for NIP-09-deleted DM messages. The batching flush consults
452/// this POSITIVE deletion signal — never STATE absence, which also means LRU-evicted or
453/// expired (an evicted archive message must still persist). A deletion whose target sat
454/// unflushed in a batch buffer no-ops its `delete_event`; the tombstone stops the flush
455/// from resurrecting the row. Cleared on session bump — ids are meaningless across accounts.
456/// Event ids are meaningless across accounts, so this is per-account.
457struct DeletedMessageTombstones;
458
459/// Event ids as their 32 bytes; anything that isn't lowercase 64-hex is kept verbatim, so
460/// membership is exactly the strings' own.
461#[derive(Default)]
462struct Tombstones {
463    ids: HashSet<[u8; 32]>,
464    other: HashSet<Box<str>>,
465}
466
467impl Tombstones {
468    fn key(id: &str) -> Option<[u8; 32]> {
469        crate::community::id32_from_hex(id)
470    }
471
472    fn insert(&mut self, id: &str) {
473        match Self::key(id) {
474            Some(bytes) => self.ids.insert(bytes),
475            None => self.other.insert(id.into()),
476        };
477    }
478
479    fn contains(&self, id: &str) -> bool {
480        match Self::key(id) {
481            Some(bytes) => self.ids.contains(&bytes),
482            None => self.other.contains(id),
483        }
484    }
485}
486
487fn deleted_message_tombstones() -> std::sync::Arc<std::sync::Mutex<Tombstones>> {
488    crate::db::current_session().scoped::<DeletedMessageTombstones, _>()
489}
490
491/// Record that `message_id` was deleted this session (called where the deletion is decided).
492pub fn note_message_deleted(message_id: &str) {
493    if let Ok(mut set) = deleted_message_tombstones().lock() {
494        set.insert(message_id);
495    }
496}
497
498/// Seed the tombstone set from the account's durable `deleted_messages` rows,
499/// making `was_message_deleted` survive restarts and account swaps. Called at
500/// account DB init (the set was cleared by the session bump on swap).
501pub fn seed_message_tombstones<S: AsRef<str>>(ids: impl IntoIterator<Item = S>) {
502    // In chunks: the scan feeding this can be long, and ingest reads the set meanwhile.
503    let tombstones = deleted_message_tombstones();
504    let mut ids = ids.into_iter().peekable();
505    while ids.peek().is_some() {
506        let chunk: Vec<S> = ids.by_ref().take(1024).collect();
507        let Ok(mut set) = tombstones.lock() else { return };
508        for id in &chunk {
509            set.insert(id.as_ref());
510        }
511    }
512}
513
514/// Whether `message_id` was deleted this session.
515pub fn was_message_deleted(message_id: &str) -> bool {
516    deleted_message_tombstones().lock().map(|s| s.contains(message_id)).unwrap_or(false)
517}
518
519/// Drop the delete-tombstone set on an account switch.
520///
521/// All that survives of the old session-generation counter. Everything else it
522/// invalidated now lives on the session and goes when that does; these are
523/// keyed by event id, which means nothing across accounts either way.
524#[inline]
525pub fn clear_message_tombstones() {
526    if let Ok(mut set) = deleted_message_tombstones().lock() {
527        *set = Tombstones::default();
528    }
529}
530
531#[cfg(test)]
532mod tombstone_tests {
533    use super::Tombstones;
534
535    #[test]
536    fn hex_ids_are_held_as_bytes_and_match_only_themselves() {
537        let mut t = Tombstones::default();
538        let id = "ab".repeat(32);
539        t.insert(&id);
540        assert!(t.contains(&id));
541        assert_eq!((t.ids.len(), t.other.len()), (1, 0));
542        assert!(!t.contains(&"ab".repeat(31)));
543        assert!(!t.contains(&"AB".repeat(32)), "an uppercase spelling is a different string");
544    }
545
546    #[test]
547    fn anything_else_is_kept_verbatim() {
548        let mut t = Tombstones::default();
549        let (upper, not_hex, long) = ("AB".repeat(32), "zz".repeat(32), "ab".repeat(33));
550        for id in ["moderated_evt", "", upper.as_str(), not_hex.as_str(), long.as_str()] {
551            t.insert(id);
552            assert!(t.contains(id), "{id:?}");
553        }
554        assert_eq!(t.ids.len(), 0);
555        assert!(!t.contains(&"ab".repeat(32)), "the lowercase twin of an uppercase id was never deleted");
556        assert!(!t.contains("moderated"));
557    }
558}
559
560#[cfg(test)]
561mod session_identity_tests {
562
563    /// A session held across an account switch knows it is no longer the one on
564    /// screen. This is the whole of what the generation counter used to do, and
565    /// it now falls out of the session's own identity.
566    #[test]
567    fn a_held_session_stops_being_live_once_the_account_changes() {
568        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
569        let held = crate::db::current_session();
570        assert!(held.is_live(), "it is the account on screen to begin with");
571
572        crate::db::close_database();
573
574        assert!(!held.is_live(), "and is not, once the account has switched");
575        assert!(crate::db::current_session().is_live(), "whoever came next is");
576        assert_ne!(held.id(), crate::db::current_session_id(), "they are different sessions");
577    }
578}
579
580#[cfg(test)]
581mod session_globals_tests {
582    use super::*;
583
584    /// Single combined test so the global statics aren't raced by parallel
585    /// runners. cargo runs each `#[test]` on its own thread, so anything
586    /// touching `MY_PUBLIC_KEY`/`PENDING_INVITE` lives here.
587    #[test]
588    fn session_helpers_round_trip_and_clear() {
589        // It swaps the live session, which every transport test reads.
590        let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
591        // Defensive cleanup: a previous test panic could have left global
592        // state behind. Start every run from a known-empty baseline so the
593        // assertions below aren't fooled by leftover values.
594        clear_my_public_key();
595        clear_pending_invite();
596
597        // PublicKey: set → get → clear.
598        // Use a deterministic key from a hex seed; nostr_sdk::prelude::Keys::generate()
599        // would also work but the deterministic form makes failures easier
600        // to reproduce.
601        let keys = Keys::parse(
602            "nsec1vl029mgpspedva04g90vltkh6fvh240zqtv9k0t9af8935ke9laqsnlfe5",
603        ).expect("parse test nsec");
604        let pk = keys.public_key();
605
606        assert_eq!(my_public_key(), None, "starts as None");
607
608        set_my_public_key(pk);
609        assert_eq!(my_public_key(), Some(pk));
610
611        clear_my_public_key();
612        assert_eq!(my_public_key(), None, "cleared returns None");
613
614        // PendingInvite: set → get → clear.
615        let invite = PendingInviteAcceptance {
616            invite_code: "abc123".to_string(),
617            inviter_pubkey: pk,
618        };
619
620        assert!(pending_invite().is_none(), "starts as None");
621
622        set_pending_invite(invite.clone());
623        let got = pending_invite().expect("set then read");
624        assert_eq!(got.invite_code, invite.invite_code);
625        assert_eq!(got.inviter_pubkey, invite.inviter_pubkey);
626
627        clear_pending_invite();
628        assert!(pending_invite().is_none(), "cleared returns None");
629
630        // Take semantics for nostr_client: with no client installed,
631        // `take_nostr_client()` returns None and is_active is false.
632        assert!(!has_active_session(), "no client installed");
633        assert!(take_nostr_client().is_none(), "take from empty returns None");
634        assert!(!has_active_session(), "still none after take-of-empty");
635
636        // PendingBunkerSetup: set → peek → clear. The URL slot is wrapped in
637        // Zeroizing<String> because it carries the NIP-46 single-use pairing
638        // secret. The accessors return plain String clones so callers don't
639        // accidentally consume the protected buffer.
640        clear_pending_bunker_setup();
641        assert!(pending_bunker_setup().is_none(), "starts as None");
642
643        let url = "bunker://0123456789abcdef?relay=wss%3A%2F%2Frelay.example&secret=topsecret".to_string();
644        let pk_hex = "0123456789abcdef".to_string();
645        set_pending_bunker_setup(url.clone(), pk_hex.clone());
646
647        // Peek twice — the underlying Zeroizing<String> must NOT be consumed
648        // by either read, so successive reads return identical contents.
649        let first = pending_bunker_setup().expect("first peek");
650        let second = pending_bunker_setup().expect("second peek");
651        assert_eq!(first.0, url, "url survives clone-out from Zeroizing");
652        assert_eq!(first.0, second.0, "successive peeks return same data");
653        assert_eq!(first.1, pk_hex);
654
655        // Overwrite — replacing the slot scrubs the prior Zeroizing<String>
656        // on Drop. We can't assert heap-residue from a test, but we CAN
657        // assert the new value is what's exposed.
658        let url2 = "bunker://feedface?relay=wss%3A%2F%2Falt".to_string();
659        set_pending_bunker_setup(url2.clone(), "feedface".to_string());
660        let after = pending_bunker_setup().expect("overwritten read");
661        assert_eq!(after.0, url2);
662        assert_eq!(after.1, "feedface");
663
664        clear_pending_bunker_setup();
665        assert!(pending_bunker_setup().is_none(), "cleared returns None");
666
667        // PendingNip55Setup: set → peek → clear. Both fields are public
668        // material (identity pubkey + signer package), so no Zeroizing — a
669        // NIP-55 account stages nothing secret.
670        clear_pending_nip55_setup();
671        assert!(pending_nip55_setup().is_none(), "starts as None");
672
673        let user_pk = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".to_string();
674        let package = "com.greenart7c3.nostrsigner".to_string();
675        set_pending_nip55_setup(user_pk.clone(), package.clone());
676        let peek1 = pending_nip55_setup().expect("first peek");
677        let peek2 = pending_nip55_setup().expect("second peek");
678        assert_eq!(peek1.0, user_pk);
679        assert_eq!(peek1.1, package);
680        assert_eq!(peek1, peek2, "successive peeks return same data");
681
682        // Overwrite replaces cleanly.
683        set_pending_nip55_setup("beef".to_string(), "org.other.signer".to_string());
684        let after55 = pending_nip55_setup().expect("overwritten read");
685        assert_eq!(after55.0, "beef");
686        assert_eq!(after55.1, "org.other.signer");
687
688        clear_pending_nip55_setup();
689        assert!(pending_nip55_setup().is_none(), "cleared returns None");
690
691        // A session held across the switch knows it is no longer current.
692        let held = crate::db::current_session();
693        assert!(held.is_live(), "the account on screen to begin with");
694        crate::db::close_database();
695        assert!(!held.is_live(), "and not, once the account has switched");
696    }
697}
698
699/// Which wrapper events this account has already ingested.
700///
701/// Per-account: the ids come from its relays and gate writes to its database.
702/// Same handle shape as [`STATE`], and for the same reason.
703pub struct WrapperIdCacheHandle;
704
705pub static WRAPPER_ID_CACHE: WrapperIdCacheHandle = WrapperIdCacheHandle;
706
707impl WrapperIdCacheHandle {
708    pub async fn lock(&self) -> tokio::sync::OwnedMutexGuard<WrapperIdCache> {
709        crate::db::current_session().scoped::<Self, Mutex<WrapperIdCache>>().lock_owned().await
710    }
711}
712
713/// The account's chats and profiles in memory.
714///
715/// Locking resolves the session THIS work belongs to, so a task bound by
716/// [`crate::db::spawn_bound`] reaches the state of the account it started
717/// under — for its whole life, whoever logs in meanwhile. A swap installs a
718/// fresh session, and with it a fresh state; the previous account's is dropped
719/// with the session rather than cleared field by field.
720///
721/// Deliberately a handle rather than the `Mutex` itself: `STATE.lock().await`
722/// reads the same at every call site, and cannot be hoisted into a `static` or
723/// a long-lived struct where it would freeze one account's state in place.
724pub struct ChatStateHandle;
725
726pub static STATE: ChatStateHandle = ChatStateHandle;
727
728impl ChatStateHandle {
729    pub async fn lock(&self) -> tokio::sync::OwnedMutexGuard<ChatState> {
730        crate::db::current_session().chat_state().lock_owned().await
731    }
732
733    /// For callers that must not block — notably Android's WebView threads,
734    /// which have no tokio runtime.
735    pub fn try_lock(&self) -> Result<tokio::sync::OwnedMutexGuard<ChatState>, tokio::sync::TryLockError> {
736        crate::db::current_session().chat_state().try_lock_owned()
737    }
738}
739
740/// Chat id currently visible to the user with auto-mark eligibility — set by
741/// the frontend when the chat is open AND pinned to bottom AND the window is
742/// active. Used by the inbound event handler to mark new messages read on
743/// arrival, so the dock badge never bumps for messages the user is actively
744/// watching. Cleared when any of those conditions flips.
745/// Per-account: the id is one of this account's chats, and a contact shared
746/// with another account would otherwise let A's open chat mark B's messages read.
747struct ActiveChat;
748
749fn active_chat() -> std::sync::Arc<RwLock<Option<String>>> {
750    crate::db::current_session().scoped::<ActiveChat, _>()
751}
752
753pub fn set_active_chat(chat_id: Option<String>) {
754    if let Ok(mut guard) = active_chat().write() {
755        *guard = chat_id;
756    }
757}
758
759pub fn get_active_chat() -> Option<String> {
760    active_chat().read().ok().and_then(|g| g.clone())
761}
762
763/// Chats whose messages the UI holds (a page was served, not since evicted). The rest keep
764/// only a short tail in memory: their pages are read from the database when opened.
765struct UiHeldChats;
766
767fn ui_held_chats() -> std::sync::Arc<RwLock<std::collections::HashSet<String>>> {
768    crate::db::current_session().scoped::<UiHeldChats, _>()
769}
770
771pub fn note_chat_held(chat_id: &str) {
772    let held = ui_held_chats();
773    if held.read().is_ok_and(|g| g.contains(chat_id)) {
774        return;
775    }
776    if let Ok(mut g) = held.write() {
777        g.insert(chat_id.to_string());
778    };
779}
780
781pub fn note_chat_released(chat_id: &str) {
782    if let Ok(mut g) = ui_held_chats().write() {
783        g.remove(chat_id);
784    };
785}
786
787/// Messages a chat the UI doesn't hold keeps in memory: enough for its preview and unread run.
788pub const UNHELD_CHAT_TAIL: usize = 20;
789
790// ============================================================================
791// Processing Gate — Controls event processing during encryption migration
792// ============================================================================
793
794pub static PROCESSING_GATE: AtomicBool = AtomicBool::new(true);
795/// Events parked while the processing gate is closed (encryption migration).
796/// Per-account: they are this account's inbound traffic, awaiting its key.
797pub struct PendingEventsHandle;
798
799pub static PENDING_EVENTS: PendingEventsHandle = PendingEventsHandle;
800
801impl PendingEventsHandle {
802    pub async fn lock(&self) -> tokio::sync::OwnedMutexGuard<Vec<(Event, bool)>> {
803        crate::db::current_session().scoped::<Self, Mutex<Vec<(Event, bool)>>>().lock_owned().await
804    }
805}
806
807#[inline]
808pub fn is_processing_allowed() -> bool { PROCESSING_GATE.load(Ordering::Acquire) }
809pub fn close_processing_gate() { PROCESSING_GATE.store(false, Ordering::Release); }
810pub fn open_processing_gate() { PROCESSING_GATE.store(true, Ordering::Release); }
811
812// ============================================================================
813// ChatState
814// ============================================================================
815
816#[derive(Clone, Debug)]
817pub struct ChatState {
818    pub profiles: Vec<Profile>,
819    pub chats: Vec<Chat>,
820    pub interner: NpubInterner,
821    pub is_syncing: bool,
822    pub db_loaded: bool,
823    /// Authoritative per-chat unread counts (chat_identifier → count), so the badge recount is an
824    /// in-RAM fold instead of a whole-DB scan. Seeded once per account from `db::unread_counts` (see
825    /// `unread_seeded`), then kept current per-chat: cleared on read, reconciled from the DB
826    /// (`db::unread_count_for_chat`) on inbound / delete / mark-unread. SENDER-level muted/blocked
827    /// filtering is baked into the DB-sourced values (mute/block toggles reseed); CHAT-level
828    /// filtering happens at fold time, matching `sum_unread_from`. Cleared on account reset.
829    pub unread_cache: std::collections::HashMap<String, u32>,
830    /// False until `unread_cache` has been seeded from the DB for this account. Guards the one-time
831    /// seed so the full-scan query runs once per login, never per message.
832    pub unread_seeded: bool,
833    #[cfg(debug_assertions)]
834    pub cache_stats: crate::stats::CacheStats,
835}
836
837/// Whether a Community chat is one the user can actually reach.
838///
839/// Widescreen gives every LISTED channel a row, so a sibling's unread counts
840/// like any other. Two kinds of row still have nowhere to go: a bare
841/// persistence anchor with no community stamp, and a channel its community
842/// stopped listing — a tombstoned or no-longer-readable one keeps its chat row
843/// and history on disk, so its unread could never be seen or cleared.
844fn chat_has_a_row(chat: &crate::chat::Chat) -> bool {
845    if chat.metadata.community_id().is_none() {
846        return false;
847    }
848    chat.is_surfaced_community_channel() || crate::notify::channel_is_listed(&chat.id)
849}
850
851impl ChatState {
852    pub fn new() -> Self {
853        Self {
854            profiles: Vec::new(),
855            chats: Vec::new(),
856            interner: NpubInterner::new(),
857            is_syncing: false,
858            db_loaded: false,
859            unread_cache: std::collections::HashMap::new(),
860            unread_seeded: false,
861            #[cfg(debug_assertions)]
862            cache_stats: crate::stats::CacheStats::new(),
863        }
864    }
865
866    // ========================================================================
867    // Profile Management
868    // ========================================================================
869
870    /// Drop the pictures every blocked profile still holds, for blocks made before a block
871    /// erased them. Returns each changed profile to persist and the files to delete
872    /// (`profile::sync::persist_forgotten_imagery`).
873    pub fn forget_blocked_imagery(&mut self) -> (Vec<SlimProfile>, Vec<crate::profile::CachedImage>) {
874        let ids: Vec<u16> = self.profiles.iter().filter(|p| p.flags.is_blocked() && p.has_imagery()).map(|p| p.id).collect();
875        let mut slims = Vec::with_capacity(ids.len());
876        let mut images = Vec::new();
877        for id in ids {
878            let held = self.get_profile_mut_by_id(id).map(|p| p.forget_imagery()).unwrap_or_default();
879            images.extend(crate::profile::sync::unshared(self, id, held));
880            slims.extend(self.serialize_profile(id));
881        }
882        (slims, images)
883    }
884
885    pub fn merge_db_profiles(&mut self, slim_profiles: Vec<SlimProfile>, my_npub: &str) {
886        self.profiles.reserve(slim_profiles.len());
887        self.interner.reserve(slim_profiles.len());
888        for slim in slim_profiles {
889            let mut full_profile = slim.to_profile();
890            full_profile.flags.set_mine(slim.id == my_npub);
891            self.insert_or_replace_profile(&slim.id, full_profile);
892        }
893    }
894
895    /// Drop the growth slack in the profile list and interner once the DB load is in.
896    pub fn shrink_after_load(&mut self) {
897        self.profiles.shrink_to_fit();
898        self.interner.shrink_to_fit();
899    }
900
901    pub fn insert_or_replace_profile(&mut self, npub: &str, mut profile: Profile) {
902        let id = self.interner.intern(npub);
903        profile.id = id;
904        match self.profiles.binary_search_by(|p| p.id.cmp(&id)) {
905            Ok(idx) => self.profiles[idx] = profile,
906            Err(idx) => self.profiles.insert(idx, profile),
907        }
908    }
909
910    /// The people whose DM requests wait on us. Their pictures wait too, unless a Community
911    /// counts them: see `requests::held_pictures`.
912    pub fn request_senders(&self) -> std::collections::HashSet<&str> {
913        self.chats.iter().filter(|c| c.is_request()).map(|c| c.id.as_str()).collect()
914    }
915
916    /// Whether this person's DM request waits on us. Whether their pictures do is
917    /// `requests::pictures_held`.
918    pub fn sent_request(&self, npub: &str) -> bool {
919        self.chats.iter().any(|c| c.id == npub && c.is_request())
920    }
921
922    /// Whether what this person sends waits for an answer or an accept: someone we've
923    /// never written to, including someone with no chat here yet.
924    pub fn dm_unanswered(&self, npub: &str) -> bool {
925        self.chats.iter().find(|c| c.id == npub).is_none_or(|c| c.is_unanswered())
926    }
927
928    pub fn get_profile(&self, npub: &str) -> Option<&Profile> {
929        self.interner.lookup(npub).and_then(|id| self.get_profile_by_id(id))
930    }
931
932    pub fn get_profile_mut(&mut self, npub: &str) -> Option<&mut Profile> {
933        self.interner.lookup(npub).and_then(move |id| self.get_profile_mut_by_id(id))
934    }
935
936    #[inline]
937    pub fn get_profile_by_id(&self, id: u16) -> Option<&Profile> {
938        self.profiles.binary_search_by(|p| p.id.cmp(&id)).ok().map(|idx| &self.profiles[idx])
939    }
940
941    #[inline]
942    pub fn get_profile_mut_by_id(&mut self, id: u16) -> Option<&mut Profile> {
943        self.profiles.binary_search_by(|p| p.id.cmp(&id)).ok().map(move |idx| &mut self.profiles[idx])
944    }
945
946    pub fn serialize_profile(&self, id: u16) -> Option<SlimProfile> {
947        self.get_profile_by_id(id).map(|p| SlimProfile::from_profile(p, &self.interner))
948    }
949
950    // ========================================================================
951    // Chat Management
952    // ========================================================================
953
954    pub fn get_chat(&self, id: &str) -> Option<&Chat> { self.chats.iter().find(|c| c.id == id) }
955    pub fn get_chat_mut(&mut self, id: &str) -> Option<&mut Chat> { self.chats.iter_mut().find(|c| c.id == id) }
956
957    pub fn create_dm_chat(&mut self, their_npub: &str) -> String {
958        if self.get_chat(their_npub).is_none() {
959            let chat = Chat::new_dm(their_npub.to_string(), &mut self.interner);
960            self.chats.push(chat);
961        }
962        their_npub.to_string()
963    }
964
965    // ========================================================================
966    // Message Management
967    // ========================================================================
968
969    /// Ensure a Community channel chat exists, created as `ChatType::Community`.
970    pub fn ensure_community_chat(&mut self, channel_id: &str) {
971        // An empty id would make a chat nothing can open or delete.
972        if channel_id.is_empty() {
973            return;
974        }
975        if !self.chats.iter().any(|c| c.id == channel_id) {
976            let chat =
977                Chat::new_community_channel(channel_id.to_string(), Vec::new(), &mut self.interner);
978            self.chats.push(chat);
979        }
980    }
981
982    /// Create-or-update a Community channel chat with its display metadata, so the chat
983    /// row carries name/description/owning-community directly (and persists + loads like
984    /// any DM — no separate hydrate). `is_owner`/`has_icon` read as "true"/"1"
985    /// strings in `custom_fields`. The caller persists the row (`save_slim_chat`).
986    /// Sibling rows of one community share one header.
987    ///
988    /// `name` is the COMMUNITY's name (every channel row carries it, so the chat list can
989    /// label a community from any one of its rows); `channel_name` is this channel's own.
990    /// `primary_channel` is the community's primary channel id — equal to `channel_id` on
991    /// that row, and what the UI uses to render one list row per community while still
992    /// holding a chat per channel.
993    #[allow(clippy::too_many_arguments)]
994    pub fn upsert_community_chat(
995        &mut self,
996        channel_id: &str,
997        name: &str,
998        description: &str,
999        community_id: &str,
1000        is_owner: bool,
1001        has_icon: bool,
1002        owner_npub: Option<&str>,
1003        created_at_ms: Option<u64>,
1004        dissolved: bool,
1005        channel_name: &str,
1006        primary_channel: &str,
1007    ) {
1008        self.ensure_community_chat(channel_id);
1009        let Some(idx) = self.chats.iter().position(|c| c.id == channel_id) else { return };
1010        let reg = crate::chat::CommunityRegistration {
1011            community_id,
1012            name,
1013            description,
1014            primary_channel,
1015            // The PROVEN owner npub (verified upstream) — for the crown/hoist + in-chat tag.
1016            owner_npub,
1017            // Join time — sorts a not-yet-active community by when we joined, not to the bottom.
1018            created_at_ms,
1019            is_owner,
1020            // Owner-dissolution seal — the GUI reads this to lock the composer + show the end divider.
1021            dissolved,
1022            has_icon,
1023        };
1024        let header = self.chats[idx].metadata.registration_header(&reg);
1025        let header = self
1026            .chats
1027            .iter()
1028            .filter_map(|c| c.metadata.community_header())
1029            .find(|h| ***h == header)
1030            .cloned()
1031            .unwrap_or_else(|| std::sync::Arc::new(header));
1032        self.chats[idx].metadata.stamp_community(header, channel_name, created_at_ms.is_some());
1033    }
1034
1035    pub fn add_message_to_chat(&mut self, chat_id: &str, message: &Message) -> bool {
1036        let compact = CompactMessage::from_message(message, &mut self.interner);
1037
1038        let (is_msg_added, chat_idx) = if let Some(idx) = self.chats.iter().position(|c| c.id == chat_id) {
1039            let added = self.chats[idx].add_compact_message(compact);
1040            (added, idx)
1041        } else {
1042            let mut chat = if chat_id.starts_with("npub1") {
1043                Chat::new_dm(chat_id.to_string(), &mut self.interner)
1044            } else {
1045                Chat::new(chat_id.to_string(), ChatType::Community, vec![])
1046            };
1047            let was_added = chat.add_compact_message(compact);
1048            self.chats.push(chat);
1049            (was_added, self.chats.len() - 1)
1050        };
1051
1052        if is_msg_added && chat_idx > 0 {
1053            let this_time = self.chats[chat_idx].last_message_time();
1054            let target = self.chats[..chat_idx].iter()
1055                .position(|c| c.last_message_time() <= this_time)
1056                .unwrap_or(chat_idx);
1057            if target < chat_idx {
1058                self.chats[target..=chat_idx].rotate_right(1);
1059            }
1060        }
1061
1062        is_msg_added
1063    }
1064
1065    /// Trim every chat the UI doesn't hold down to its tail. Amortised: a chat is only cut
1066    /// once it holds twice the tail, so one arriving message never triggers a trim.
1067    pub fn trim_unheld_chats(&mut self) -> usize {
1068        let held = ui_held_chats();
1069        let Ok(held) = held.read() else { return 0 };
1070        self.chats
1071            .iter_mut()
1072            .filter(|c| c.messages.len() > UNHELD_CHAT_TAIL * 2 && !held.contains(&c.id))
1073            .map(|c| c.messages.retain_newest(UNHELD_CHAT_TAIL))
1074            .sum()
1075    }
1076
1077    pub fn add_messages_to_chat_batch(&mut self, chat_id: &str, messages: Vec<Message>) -> usize {
1078        if messages.is_empty() { return 0; }
1079
1080        let compact_messages: Vec<_> = messages.into_iter()
1081            .map(|msg| CompactMessage::from_message_owned(msg, &mut self.interner))
1082            .collect();
1083
1084        let chat_idx = if let Some(idx) = self.chats.iter().position(|c| c.id == chat_id) {
1085            idx
1086        } else {
1087            let chat = if chat_id.starts_with("npub1") {
1088                Chat::new_dm(chat_id.to_string(), &mut self.interner)
1089            } else {
1090                Chat::new(chat_id.to_string(), ChatType::Community, vec![])
1091            };
1092            self.chats.push(chat);
1093            self.chats.len() - 1
1094        };
1095
1096        let old_last_time = self.chats[chat_idx].messages.last_timestamp();
1097        self.chats[chat_idx].replied |= compact_messages.iter().any(|m| m.flags.is_mine());
1098        let added = self.chats[chat_idx].messages.insert_batch(compact_messages);
1099
1100        if added > 0 && self.chats[chat_idx].messages.last_timestamp() != old_last_time && chat_idx > 0 {
1101            let this_time = self.chats[chat_idx].last_message_time();
1102            let target = self.chats[..chat_idx].iter()
1103                .position(|c| c.last_message_time() <= this_time)
1104                .unwrap_or(chat_idx);
1105            if target < chat_idx {
1106                self.chats[target..=chat_idx].rotate_right(1);
1107            }
1108        }
1109
1110        added
1111    }
1112
1113    /// Add a message to a participant's DM chat. Creates profile if missing.
1114    ///
1115    /// Unlike the src-tauri version, emitting `profile_update` is the caller's responsibility.
1116    pub fn add_message_to_participant(&mut self, their_npub: &str, message: &Message) -> bool {
1117        let id = self.interner.intern(their_npub);
1118        if self.get_profile_by_id(id).is_none() {
1119            let profile = Profile::new();
1120            self.insert_or_replace_profile(their_npub, profile);
1121
1122            // Emit profile update via EventEmitter trait (replaces TAURI_APP.emit)
1123            if let Some(slim) = self.serialize_profile(id) {
1124                emit_event("profile_update", &slim);
1125            }
1126        }
1127
1128        let chat_id = self.create_dm_chat(their_npub);
1129        self.add_message_to_chat(&chat_id, message)
1130    }
1131
1132    // ========================================================================
1133    // Message Lookup
1134    // ========================================================================
1135
1136    /// Index of the chat holding `message_id`, decoding the id once rather than per chat.
1137    fn chat_index_of_message(&self, message_id: &str) -> Option<usize> {
1138        if message_id.is_empty() { return None; }
1139        let id = crate::compact::encode_message_id(message_id);
1140        self.chats.iter().position(|chat| chat.messages.contains_id(&id))
1141    }
1142
1143    pub fn find_message(&self, message_id: &str) -> Option<(&Chat, Message)> {
1144        if message_id.is_empty() { return None; }
1145        let id = crate::compact::encode_message_id(message_id);
1146        self.chats.iter().find_map(|chat| chat.messages.find_by_id(&id).map(|m| (chat, m.to_message(&self.interner))))
1147    }
1148
1149    pub fn find_chat_for_message(&self, message_id: &str) -> Option<(usize, String)> {
1150        let idx = self.chat_index_of_message(message_id)?;
1151        Some((idx, self.chats[idx].id.clone()))
1152    }
1153
1154    pub fn update_message<F>(&mut self, message_id: &str, f: F) -> Option<(String, Message)>
1155    where F: FnOnce(&mut CompactMessage)
1156    {
1157        self.update_message_with(message_id, |m, _| f(m))
1158    }
1159
1160    /// [`Self::update_message`] for a change that interns (an edit's emoji).
1161    pub fn update_message_with<F>(&mut self, message_id: &str, f: F) -> Option<(String, Message)>
1162    where F: FnOnce(&mut CompactMessage, &mut NpubInterner)
1163    {
1164        if message_id.is_empty() { return None; }
1165        let id = crate::compact::encode_message_id(message_id);
1166        let chat = self.chats.iter_mut().find(|c| c.messages.contains_id(&id))?;
1167        let msg = chat.messages.find_by_id_mut(&id)?;
1168        f(msg, &mut self.interner);
1169        Some((chat.id.clone(), msg.to_message(&self.interner)))
1170    }
1171
1172    pub fn update_message_in_chat<F>(&mut self, chat_id: &str, message_id: &str, f: F) -> Option<Message>
1173    where F: FnOnce(&mut CompactMessage)
1174    {
1175        self.update_message_in_chat_with(chat_id, message_id, |m, _| f(m))
1176    }
1177
1178    /// [`Self::update_message_in_chat`] for a change that interns (an edit's emoji).
1179    pub fn update_message_in_chat_with<F>(&mut self, chat_id: &str, message_id: &str, f: F) -> Option<Message>
1180    where F: FnOnce(&mut CompactMessage, &mut NpubInterner)
1181    {
1182        let chat = self.chats.iter_mut().find(|c| c.id == chat_id)?;
1183        let msg = chat.messages.find_by_hex_id_mut(message_id)?;
1184        f(msg, &mut self.interner);
1185        Some(msg.to_message(&self.interner))
1186    }
1187
1188    pub fn finalize_pending_message(&mut self, chat_id: &str, pending_id: &str, real_id: &str) -> Option<(String, Message)> {
1189        let chat_idx = self.chats.iter().position(|c| c.id == chat_id)?;
1190        let messages = &mut self.chats[chat_idx].messages;
1191        let pending = crate::compact::encode_message_id(pending_id);
1192        let real = crate::simd::hex::hex_to_bytes_32(real_id);
1193        if let Some(msg) = messages.find_by_id_mut(&pending) {
1194            msg.set_pending(false);
1195        }
1196        // The real id can already be held (an echo landed first): that copy stands, the
1197        // pending one goes rather than leaving two rows under one id.
1198        if !messages.rekey(&pending, real) && messages.contains_id(&real) {
1199            messages.remove_by_id(&pending);
1200        }
1201        self.chats[chat_idx].get_compact_message(real_id)
1202            .map(|m| (pending_id.to_string(), m.to_message(&self.interner)))
1203    }
1204
1205    pub fn update_attachment<F>(&mut self, chat_hint: &str, msg_id: &str, attachment_id: &str, f: F) -> bool
1206    where F: FnOnce(&mut CompactAttachment)
1207    {
1208        for chat in &mut self.chats {
1209            let is_target = match &chat.chat_type {
1210                // Community channels are addressed by their id.
1211                ChatType::Community => chat.id == chat_hint,
1212                ChatType::DirectMessage => chat.has_participant(chat_hint, &self.interner),
1213            };
1214            if is_target {
1215                if let Some(msg) = chat.messages.find_by_hex_id_mut(msg_id) {
1216                    if let Some(att) = msg.attachments.iter_mut().find(|a| a.id_eq(attachment_id)) {
1217                        f(att);
1218                        return true;
1219                    }
1220                }
1221            }
1222        }
1223        false
1224    }
1225
1226    pub fn add_attachment_to_message(&mut self, chat_id: &str, msg_id: &str, attachment: CompactAttachment) -> bool {
1227        let chat_idx = match self.chats.iter().position(|c| c.id == chat_id || c.has_participant(chat_id, &self.interner)) {
1228            Some(idx) => idx,
1229            None => return false,
1230        };
1231        if let Some(msg) = self.chats[chat_idx].messages.find_by_hex_id_mut(msg_id) {
1232            msg.attachments.push(attachment);
1233            true
1234        } else { false }
1235    }
1236
1237    pub fn add_reaction_to_message(&mut self, message_id: &str, reaction: Reaction) -> Option<(String, bool)> {
1238        if message_id.is_empty() { return None; }
1239        let chat_idx = self.chat_index_of_message(message_id)?;
1240        let chat_id = self.chats[chat_idx].id.clone();
1241        let msg = self.chats[chat_idx].get_compact_message_mut(message_id)?;
1242        let added = msg.add_reaction(reaction, &mut self.interner);
1243        Some((chat_id, added))
1244    }
1245
1246    /// Locate a reaction by its event id across all chats.
1247    /// Returns `(chat_id, parent_message_id, author_npub, is_community)`.
1248    pub fn find_reaction(&self, reaction_id: &str) -> Option<(String, String, String, bool)> {
1249        if reaction_id.is_empty() { return None; }
1250        let target = crate::simd::hex::hex_to_bytes_32(reaction_id);
1251        for chat in &self.chats {
1252            for msg in chat.iter_compact() {
1253                if let Some(r) = msg.reactions.iter().find(|r| r.id == target) {
1254                    let author = self.interner.resolve(r.author_idx).unwrap_or("").to_string();
1255                    return Some((chat.id.clone(), msg.id_hex(), author, chat.is_community()));
1256                }
1257            }
1258        }
1259        None
1260    }
1261
1262    /// Remove a reaction from its parent message. Returns `(chat_id, updated Message)`
1263    /// for the UI refresh, or `None` if the reaction wasn't present.
1264    pub fn remove_reaction_from_message(&mut self, message_id: &str, reaction_id: &str) -> Option<(String, Message)> {
1265        if message_id.is_empty() { return None; }
1266        let chat_idx = self.chat_index_of_message(message_id)?;
1267        let removed = self.chats[chat_idx]
1268            .get_compact_message_mut(message_id)
1269            .map(|m| m.remove_reaction(reaction_id))
1270            .unwrap_or(false);
1271        if !removed { return None; }
1272        let chat_id = self.chats[chat_idx].id.clone();
1273        self.chats[chat_idx]
1274            .get_compact_message(message_id)
1275            .map(|m| (chat_id, m.to_message(&self.interner)))
1276    }
1277
1278    pub fn remove_message(&mut self, message_id: &str) -> Option<(String, Message)> {
1279        if message_id.is_empty() { return None; }
1280        for chat in &mut self.chats {
1281            if let Some(compact) = chat.messages.find_by_hex_id(message_id) {
1282                let msg = compact.to_message(&self.interner);
1283                let removed_id = *compact.id();
1284                let removed_at = compact.at;
1285                let chat_id = chat.id.clone();
1286                let was_marker = chat.last_read == removed_id;
1287                let was_unread_from = chat.unread_from == removed_id;
1288                chat.messages.remove_by_hex_id(message_id);
1289                // A "Mark as Unread" from it moves on to the next message, or ends with none left.
1290                if was_unread_from {
1291                    chat.unread_from = chat.messages.iter()
1292                        .find(|m| m.at >= removed_at)
1293                        .map(|m| *m.id())
1294                        .unwrap_or([0u8; 32]);
1295                }
1296                // A deleted read marker leaves `last_read` dangling and collapses the unread anchor
1297                // (badge stuck at 99+); retreat it to the newest surviving contact message before the
1298                // deleted one, or clear it. Mirrors the DB retreat in `db::events::delete_event`.
1299                if was_marker {
1300                    chat.last_read = chat.messages.iter().rev()
1301                        .find(|m| m.at <= removed_at && !m.flags.is_mine())
1302                        .map(|m| *m.id())
1303                        .unwrap_or([0u8; 32]);
1304                }
1305                return Some((chat_id, msg));
1306            }
1307        }
1308        None
1309    }
1310
1311    pub fn message_exists(&self, message_id: &str) -> bool {
1312        self.chat_index_of_message(message_id).is_some()
1313    }
1314
1315    // ========================================================================
1316    // Unread Count
1317    // ========================================================================
1318
1319    /// Sum DB-computed per-chat unread counts, applying the same muted/blocked filters as
1320    /// [`count_unread_messages`](Self::count_unread_messages) but sourcing each COUNT from `counts` (chat_identifier → unread)
1321    /// rather than walking in-memory messages — so it's correct even when only the last message per
1322    /// chat is in RAM (the boot state). Muted chats and blocked-DM contacts contribute 0.
1323    pub fn sum_unread_from(&self, counts: &std::collections::HashMap<String, u32>) -> u32 {
1324        let mut total = 0u32;
1325        for chat in &self.chats {
1326            // Only a room that rings for everything pushes the OS badge. At Mentions or
1327            // Nothing its traffic is the row's own business, and the row shows pings.
1328            if crate::notify::ring_for_chat(chat) != crate::notify::NotifyLevel::All {
1329                continue;
1330            }
1331            if !chat.is_community() {
1332                if let Some(id) = self.interner.lookup(&chat.id) {
1333                    if self.get_profile_by_id(id).is_some_and(|p| p.flags.is_blocked()) {
1334                        continue;
1335                    }
1336                }
1337            } else if !chat_has_a_row(chat) {
1338                continue;
1339            }
1340            total += counts.get(&chat.id).copied().unwrap_or(0);
1341        }
1342        total
1343    }
1344
1345    // ------------------------------------------------------------------------
1346    // Unread cache — in-RAM per-chat counts, so the per-message badge recount
1347    // never re-scans the DB. See the `unread_cache` field doc.
1348    // ------------------------------------------------------------------------
1349
1350    /// Seed the whole cache from a DB `unread_counts()` result and mark it seeded. Idempotent per
1351    /// login; a later call replaces the map wholesale (used only if a reseed is ever forced).
1352    pub fn unread_seed(&mut self, counts: std::collections::HashMap<String, u32>) {
1353        self.unread_cache = counts;
1354        self.unread_seeded = true;
1355    }
1356
1357    /// The chat was read (opened / marked): zero its unread.
1358    pub fn unread_clear(&mut self, chat_id: &str) {
1359        self.unread_cache.remove(chat_id);
1360    }
1361
1362    /// A live message landed: it is newer than any read point, so it counts here without a DB
1363    /// recount. An author the user blocked or muted counts for nothing, as in the seed.
1364    pub fn unread_bump(&mut self, chat_id: &str, author: Option<&str>) {
1365        if let Some(npub) = author {
1366            if self.get_profile(npub).is_some_and(|p| p.flags.is_blocked()) || self.get_chat(npub).is_some_and(|c| c.muted) {
1367                return;
1368            }
1369        }
1370        *self.unread_cache.entry(chat_id.to_string()).or_insert(0) += 1;
1371    }
1372
1373    /// Reconcile a chat to an exact DB-computed count (delete / retreat / backfill). A zero drops the
1374    /// entry so the map stays small and `unwrap_or(0)` reads it as caught-up.
1375    pub fn unread_set(&mut self, chat_id: &str, count: u32) {
1376        if count == 0 {
1377            self.unread_cache.remove(chat_id);
1378        } else {
1379            self.unread_cache.insert(chat_id.to_string(), count);
1380        }
1381    }
1382
1383    /// Total unread for the badge, from the cache, applying the same muted/blocked filters as
1384    /// [`sum_unread_from`](Self::sum_unread_from).
1385    pub fn sum_unread(&self) -> u32 {
1386        self.sum_unread_from(&self.unread_cache)
1387    }
1388
1389    /// A snapshot of the raw per-chat counts, for the frontend's boot badges.
1390    pub fn unread_snapshot(&self) -> std::collections::HashMap<String, u32> {
1391        self.unread_cache.clone()
1392    }
1393
1394    pub fn count_unread_messages(&self) -> u32 {
1395        // Sender-level mutes: a muted DM silences that person's community messages too.
1396        let muted_senders: std::collections::HashSet<u16> = self
1397            .chats
1398            .iter()
1399            .filter(|c| !c.is_community() && crate::notify::muted_for_chat(c))
1400            .filter_map(|c| self.interner.lookup(&c.id))
1401            .collect();
1402        let mut total_unread = 0;
1403        for chat in &self.chats {
1404            if crate::notify::ring_for_chat(chat) != crate::notify::NotifyLevel::All { continue; }
1405            let is_group = chat.is_community();
1406            if !is_group {
1407                if let Some(id) = self.interner.lookup(&chat.id) {
1408                    if self.get_profile_by_id(id).is_some_and(|p| p.flags.is_blocked()) { continue; }
1409                }
1410            } else if !chat_has_a_row(chat) {
1411                continue;
1412            }
1413            let mut unread_count = 0u32;
1414            // A "Mark as Unread" from a chosen message counts back to it, past own replies.
1415            let from = (chat.unread_from != [0u8; 32]).then_some(chat.unread_from);
1416            for msg in chat.iter_compact().rev() {
1417                if let Some(from) = from {
1418                    let reached = *msg.id() == from;
1419                    if !msg.flags.is_mine() && !(is_group && msg.npub_idx != NO_NPUB
1420                        && (muted_senders.contains(&msg.npub_idx)
1421                            || self.get_profile_by_id(msg.npub_idx).is_some_and(|p| p.flags.is_blocked())))
1422                    {
1423                        unread_count += 1;
1424                    }
1425                    if reached { break; }
1426                    continue;
1427                }
1428                if msg.flags.is_mine() { break; }
1429                if chat.last_read != [0u8; 32] && *msg.id() == chat.last_read { break; }
1430                if is_group && msg.npub_idx != NO_NPUB {
1431                    if muted_senders.contains(&msg.npub_idx) { continue; }
1432                    if self.get_profile_by_id(msg.npub_idx).is_some_and(|p| p.flags.is_blocked()) { continue; }
1433                }
1434                unread_count += 1;
1435            }
1436            // Debug: log which chat has unread messages
1437            #[cfg(debug_assertions)]
1438            if unread_count > 0 {
1439                let last_read_hex = crate::compact::decode_message_id(&chat.last_read);
1440                let last_msg_hex = chat.messages.last().map(|m| crate::compact::decode_message_id(m.id())).unwrap_or_default();
1441                let msg_count = chat.message_count();
1442                eprintln!("[Unread] chat={} unread={} msgs_in_memory={} last_read={} last_msg={}",
1443                    &chat.id[..20.min(chat.id.len())], unread_count, msg_count,
1444                    &last_read_hex[..16.min(last_read_hex.len())], &last_msg_hex[..16.min(last_msg_hex.len())]);
1445            }
1446            total_unread += unread_count;
1447        }
1448        total_unread
1449    }
1450
1451    // ========================================================================
1452    // Typing Indicators
1453    // ========================================================================
1454
1455    /// A blocked user's typing is never shown, in any chat: neither recorded nor listed.
1456    pub fn update_typing_and_get_active(&mut self, chat_id: &str, npub: &str, expires_at: u64) -> Vec<String> {
1457        let blocked = |state: &Self, npub: &str| state.get_profile(npub).is_some_and(|p| p.flags.is_blocked());
1458        let handle = (!blocked(self, npub)).then(|| self.interner.intern(npub));
1459        let Some(chat) = self.chats.iter_mut().find(|c| c.id == chat_id) else {
1460            return Vec::new();
1461        };
1462        if let Some(handle) = handle {
1463            chat.update_typing_participant(handle, expires_at);
1464        }
1465        let typers = chat.get_active_typers(&self.interner);
1466        typers.into_iter().filter(|t| !blocked(self, t)).collect()
1467    }
1468}
1469
1470impl Default for ChatState {
1471    fn default() -> Self { Self::new() }
1472}
1473
1474#[cfg(test)]
1475mod tests {
1476    use super::*;
1477    use crate::types::Message;
1478    use crate::profile::{Profile, SlimProfile, Status};
1479    use crate::simd::hex::bytes_to_hex_32;
1480
1481    // ========================================================================
1482    // Helpers
1483    // ========================================================================
1484
1485    /// Create a deterministic 64-char hex ID from a u8 seed.
1486    /// First byte is always >= 0x10 to avoid the pending ID marker (0x01).
1487    fn make_hex_id(seed: u8) -> String {
1488        let mut bytes = [seed; 32];
1489        bytes[0] = seed.wrapping_add(0x10) | 0x10; // never 0x00 or 0x01
1490        bytes[1] = seed.wrapping_mul(37);
1491        bytes_to_hex_32(&bytes)
1492    }
1493
1494    /// One channel registration, as `upsert_community_chat` takes it.
1495    struct Reg<'a> {
1496        name: &'a str,
1497        description: &'a str,
1498        community_id: &'a str,
1499        is_owner: bool,
1500        has_icon: bool,
1501        owner_npub: Option<&'a str>,
1502        created_at_ms: Option<u64>,
1503        dissolved: bool,
1504        channel_name: &'a str,
1505        primary_channel: &'a str,
1506    }
1507
1508    impl Reg<'_> {
1509        fn apply(&self, state: &mut ChatState, channel_id: &str) {
1510            state.upsert_community_chat(
1511                channel_id, self.name, self.description, self.community_id, self.is_owner, self.has_icon,
1512                self.owner_npub, self.created_at_ms, self.dissolved, self.channel_name, self.primary_channel,
1513            );
1514        }
1515
1516        /// The registration as a plain string map holds it.
1517        fn apply_plain(&self, cf: &mut std::collections::BTreeMap<String, String>) {
1518            let mut put = |k: &str, v: String| cf.insert(k.to_string(), v);
1519            put("name", self.name.into());
1520            put("channel_name", self.channel_name.into());
1521            put("primary_channel", self.primary_channel.into());
1522            put("description", self.description.into());
1523            put("community_id", self.community_id.into());
1524            put("is_owner", self.is_owner.to_string());
1525            put("dissolved", self.dissolved.to_string());
1526            if let Some(ms) = self.created_at_ms {
1527                put("created_at", ms.to_string());
1528            }
1529            match self.owner_npub {
1530                Some(n) => { cf.insert("owner_npub".into(), n.into()); }
1531                None => { cf.remove("owner_npub"); }
1532            }
1533            if self.has_icon {
1534                cf.insert("icon".into(), "1".into());
1535            } else {
1536                cf.remove("icon");
1537            }
1538        }
1539    }
1540
1541    #[test]
1542    fn a_registration_stamps_exactly_what_the_plain_map_upsert_did() {
1543        let (cid, primary, sibling) = (make_hex_id(0x61), make_hex_id(0x62), make_hex_id(0x63));
1544        let first = Reg {
1545            name: "Club", description: "about", community_id: &cid, is_owner: true, has_icon: true,
1546            owner_npub: Some("npub1owner"), created_at_ms: Some(1_700_000_000_123), dissolved: false,
1547            channel_name: "general", primary_channel: &primary,
1548        };
1549        let later = Reg {
1550            name: "Club 2", description: "", has_icon: false, owner_npub: None, created_at_ms: None,
1551            dissolved: true, ..first
1552        };
1553        // Rows as they might have been stored: empty, keys outside the typed set, and typed
1554        // keys holding values only a plain pair can carry.
1555        let priors: [&[(&str, &str)]; 3] = [
1556            &[],
1557            &[("member_count", "9"), ("proto_version", "2")],
1558            &[("is_owner", "yes"), ("icon", "true"), ("created_at", "0042"), ("zz", "kept")],
1559        ];
1560        for prior in priors {
1561            for regs in [&[&first][..], &[&first, &later][..], &[&later][..]] {
1562                let mut state = ChatState::new();
1563                let mut cf: std::collections::BTreeMap<String, String> =
1564                    prior.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
1565                state.ensure_community_chat(&sibling);
1566                state.chats[0].metadata = crate::chat::ChatMetadata::from_map(cf.clone().into_iter().collect());
1567                for reg in regs {
1568                    reg.apply(&mut state, &sibling);
1569                    reg.apply_plain(&mut cf);
1570                }
1571                let got: std::collections::BTreeMap<String, String> = state.chats[0]
1572                    .metadata
1573                    .entries()
1574                    .into_iter()
1575                    .map(|(k, v)| (k.to_string(), v.into_owned()))
1576                    .collect();
1577                assert_eq!(got, cf, "prior {prior:?}");
1578            }
1579        }
1580    }
1581
1582    #[test]
1583    fn sibling_channels_share_their_communitys_header() {
1584        let (cid, other, primary) = (make_hex_id(0x71), make_hex_id(0x72), make_hex_id(0x73));
1585        let reg = Reg {
1586            name: "Club", description: "", community_id: &cid, is_owner: false, has_icon: false,
1587            owner_npub: None, created_at_ms: Some(5), dissolved: false, channel_name: "general",
1588            primary_channel: &primary,
1589        };
1590        let mut state = ChatState::new();
1591        reg.apply(&mut state, &primary);
1592        Reg { channel_name: "random", ..reg }.apply(&mut state, &make_hex_id(0x74));
1593        Reg { community_id: &other, ..reg }.apply(&mut state, &make_hex_id(0x75));
1594        let header = |state: &ChatState, i: usize| state.chats[i].metadata.community_header().unwrap().clone();
1595        assert!(std::sync::Arc::ptr_eq(&header(&state, 0), &header(&state, 1)), "one community, one header");
1596        assert!(!std::sync::Arc::ptr_eq(&header(&state, 0), &header(&state, 2)), "another community keeps its own");
1597        assert_eq!(state.chats[1].metadata.get("channel_name").as_deref(), Some("random"));
1598        // A rename re-stamps every row onto a new shared header.
1599        let before = header(&state, 0);
1600        Reg { name: "Renamed", ..reg }.apply(&mut state, &primary);
1601        Reg { name: "Renamed", channel_name: "random", ..reg }.apply(&mut state, &make_hex_id(0x74));
1602        assert!(std::sync::Arc::ptr_eq(&header(&state, 0), &header(&state, 1)));
1603        assert!(!std::sync::Arc::ptr_eq(&header(&state, 0), &before));
1604        assert_eq!(state.chats[1].metadata.get_name(), Some("Renamed"));
1605    }
1606
1607    /// Build a test Message with the given parameters.
1608    fn make_message(id_seed: u8, content: &str, timestamp_ms: u64, mine: bool) -> Message {
1609        Message {
1610            id: make_hex_id(id_seed),
1611            content: content.to_string(),
1612            at: timestamp_ms,
1613            mine,
1614            ..Default::default()
1615        }
1616    }
1617
1618    /// Build a message with an npub sender.
1619    fn make_message_from(id_seed: u8, content: &str, timestamp_ms: u64, npub: &str) -> Message {
1620        Message {
1621            id: make_hex_id(id_seed),
1622            content: content.to_string(),
1623            at: timestamp_ms,
1624            mine: false,
1625            npub: Some(npub.to_string()),
1626            ..Default::default()
1627        }
1628    }
1629
1630    /// Build a SlimProfile for testing.
1631    fn make_slim_profile(id: &str, name: &str) -> SlimProfile {
1632        SlimProfile {
1633            id: id.to_string(),
1634            name: name.to_string(),
1635            display_name: String::new(),
1636            nickname: String::new(),
1637            lud06: String::new(),
1638            lud16: String::new(),
1639            banner: String::new(),
1640            avatar: String::new(),
1641            about: String::new(),
1642            website: String::new(),
1643            nip05: String::new(),
1644            status: Status::new(),
1645            last_updated: 0,
1646            mine: false,
1647            bot: false,
1648            is_blocked: false,
1649            avatar_cached: String::new(),
1650            banner_cached: String::new(),
1651            stream_consent: false,
1652        }
1653    }
1654
1655    // ========================================================================
1656    // Profile Management
1657    // ========================================================================
1658
1659    #[test]
1660    fn insert_or_replace_profile_creates_new() {
1661        let mut state = ChatState::new();
1662        let profile = Profile::new();
1663        state.insert_or_replace_profile("npub1alice", profile);
1664
1665        assert!(
1666            state.get_profile("npub1alice").is_some(),
1667            "newly inserted profile should be retrievable"
1668        );
1669        assert_eq!(state.profiles.len(), 1, "should have exactly one profile");
1670    }
1671
1672    #[test]
1673    fn insert_or_replace_profile_updates_existing() {
1674        let mut state = ChatState::new();
1675        let mut p1 = Profile::new();
1676        p1.set_name("Alice");
1677        state.insert_or_replace_profile("npub1alice", p1);
1678
1679        let mut p2 = Profile::new();
1680        p2.set_name("Alice Updated");
1681        state.insert_or_replace_profile("npub1alice", p2);
1682
1683        let fetched = state.get_profile("npub1alice").expect("profile should exist");
1684        assert_eq!(
1685            fetched.name(), "Alice Updated",
1686            "profile name should be updated after replace"
1687        );
1688        assert_eq!(state.profiles.len(), 1, "should still be one profile, not duplicated");
1689    }
1690
1691    #[test]
1692    fn get_profile_by_npub() {
1693        let mut state = ChatState::new();
1694        let mut profile = Profile::new();
1695        profile.set_name("Bob");
1696        state.insert_or_replace_profile("npub1bob", profile);
1697
1698        let fetched = state.get_profile("npub1bob").expect("profile should be found");
1699        assert_eq!(fetched.name(), "Bob", "fetched profile name should match");
1700    }
1701
1702    #[test]
1703    fn get_profile_returns_none_for_unknown() {
1704        let state = ChatState::new();
1705        assert!(
1706            state.get_profile("npub1unknown").is_none(),
1707            "unknown npub should return None"
1708        );
1709    }
1710
1711    #[test]
1712    fn get_profile_by_id_works() {
1713        let mut state = ChatState::new();
1714        let mut profile = Profile::new();
1715        profile.set_name("Charlie");
1716        state.insert_or_replace_profile("npub1charlie", profile);
1717
1718        let id = state.interner.lookup("npub1charlie").expect("npub should be interned");
1719        let fetched = state.get_profile_by_id(id).expect("profile should be found by id");
1720        assert_eq!(fetched.name(), "Charlie", "profile looked up by id should match");
1721    }
1722
1723    #[test]
1724    fn get_profile_by_id_returns_none_for_invalid() {
1725        let state = ChatState::new();
1726        assert!(
1727            state.get_profile_by_id(9999).is_none(),
1728            "invalid interner id should return None"
1729        );
1730    }
1731
1732    #[test]
1733    fn merge_db_profiles_sets_mine_flag() {
1734        let mut state = ChatState::new();
1735        let slim_mine = make_slim_profile("npub1me", "Me");
1736        let slim_other = make_slim_profile("npub1other", "Other");
1737
1738        state.merge_db_profiles(vec![slim_mine, slim_other], "npub1me");
1739
1740        let me = state.get_profile("npub1me").expect("my profile should exist");
1741        assert!(me.flags.is_mine(), "my profile should have mine flag set");
1742
1743        let other = state.get_profile("npub1other").expect("other profile should exist");
1744        assert!(!other.flags.is_mine(), "other profile should not have mine flag");
1745    }
1746
1747    #[test]
1748    fn serialize_profile_roundtrip() {
1749        let mut state = ChatState::new();
1750        let mut profile = Profile::new();
1751        profile.set_name("Roundtrip");
1752        profile.set_about("Test about");
1753        profile.flags.set_blocked(true);
1754        state.insert_or_replace_profile("npub1round", profile);
1755
1756        let id = state.interner.lookup("npub1round").unwrap();
1757        let slim = state.serialize_profile(id).expect("serialization should succeed");
1758
1759        assert_eq!(slim.id, "npub1round", "serialized id should match");
1760        assert_eq!(slim.name, "Roundtrip", "serialized name should match");
1761        assert_eq!(slim.about, "Test about", "serialized about should match");
1762        assert!(slim.is_blocked, "serialized blocked flag should be true");
1763
1764        // Convert back to profile and re-insert
1765        let restored = slim.to_profile();
1766        assert_eq!(restored.name(), "Roundtrip", "restored name should match");
1767        assert!(restored.flags.is_blocked(), "restored blocked flag should be true");
1768    }
1769
1770    #[test]
1771    fn binary_search_maintains_sorted_order_with_100_profiles() {
1772        let mut state = ChatState::new();
1773
1774        // Insert 100 profiles in random-ish order
1775        let npubs: Vec<String> = (0..100).map(|i| format!("npub1user{:04}", i)).collect();
1776        let mut shuffled = npubs.clone();
1777        // Simple deterministic shuffle
1778        for i in (1..shuffled.len()).rev() {
1779            let j = (i * 37 + 13) % (i + 1);
1780            shuffled.swap(i, j);
1781        }
1782
1783        for npub in &shuffled {
1784            let mut profile = Profile::new();
1785            profile.set_name(&npub);
1786            state.insert_or_replace_profile(npub, profile);
1787        }
1788
1789        // All should be findable
1790        for npub in &npubs {
1791            assert!(
1792                state.get_profile(npub).is_some(),
1793                "profile {} should be retrievable after bulk insert",
1794                npub
1795            );
1796        }
1797
1798        // Internal profiles vec should be sorted by id
1799        for window in state.profiles.windows(2) {
1800            assert!(
1801                window[0].id < window[1].id,
1802                "profiles should be sorted by interner id"
1803            );
1804        }
1805
1806        assert_eq!(state.profiles.len(), 100, "should have exactly 100 profiles");
1807    }
1808
1809    #[test]
1810    fn insert_same_npub_twice_updates_not_duplicates() {
1811        let mut state = ChatState::new();
1812
1813        for i in 0..5 {
1814            let mut profile = Profile::new();
1815            profile.set_name(&format!("version_{}", i));
1816            state.insert_or_replace_profile("npub1repeated", profile);
1817        }
1818
1819        assert_eq!(state.profiles.len(), 1, "repeated inserts should not create duplicates");
1820        let p = state.get_profile("npub1repeated").unwrap();
1821        assert_eq!(p.name(), "version_4", "should retain the last update");
1822    }
1823
1824    #[test]
1825    fn get_profile_mut_modifies_in_place() {
1826        let mut state = ChatState::new();
1827        let profile = Profile::new();
1828        state.insert_or_replace_profile("npub1mutable", profile);
1829
1830        let p = state.get_profile_mut("npub1mutable").expect("profile should exist");
1831        p.set_name("Mutated");
1832
1833        let fetched = state.get_profile("npub1mutable").unwrap();
1834        assert_eq!(fetched.name(), "Mutated", "mutation should persist");
1835    }
1836
1837    // ========================================================================
1838    // Chat Management
1839    // ========================================================================
1840
1841    #[test]
1842    fn create_dm_chat_creates_new() {
1843        let mut state = ChatState::new();
1844        let id = state.create_dm_chat("npub1peer");
1845
1846        assert_eq!(id, "npub1peer", "returned id should match the npub");
1847        assert!(state.get_chat("npub1peer").is_some(), "chat should be created");
1848        assert_eq!(state.chats.len(), 1, "should have exactly one chat");
1849    }
1850
1851    #[test]
1852    fn create_dm_chat_is_idempotent() {
1853        let mut state = ChatState::new();
1854        state.create_dm_chat("npub1peer");
1855        state.create_dm_chat("npub1peer");
1856        state.create_dm_chat("npub1peer");
1857
1858        assert_eq!(state.chats.len(), 1, "repeated creates should not duplicate");
1859    }
1860
1861    #[test]
1862    fn ensure_community_chat_idempotent() {
1863        let mut state = ChatState::new();
1864        state.ensure_community_chat("grp1");
1865        state.ensure_community_chat("grp1");
1866
1867        assert_eq!(state.chats.len(), 1, "second call should not create a duplicate");
1868        let chat = state.get_chat("grp1").expect("community chat should exist");
1869        assert!(chat.is_community(), "should be a Community chat");
1870    }
1871
1872    #[test]
1873    fn get_chat_by_id() {
1874        let mut state = ChatState::new();
1875        state.create_dm_chat("npub1x");
1876
1877        let chat = state.get_chat("npub1x").expect("chat should exist");
1878        assert_eq!(chat.id, "npub1x", "chat id should match");
1879    }
1880
1881    #[test]
1882    fn get_chat_returns_none_for_missing() {
1883        let state = ChatState::new();
1884        assert!(state.get_chat("nonexistent").is_none(), "missing chat should return None");
1885    }
1886
1887    #[test]
1888    fn get_chat_mut_modifies_in_place() {
1889        let mut state = ChatState::new();
1890        state.create_dm_chat("npub1editable");
1891
1892        let chat = state.get_chat_mut("npub1editable").expect("chat should exist");
1893        chat.muted = true;
1894
1895        let refetched = state.get_chat("npub1editable").unwrap();
1896        assert!(refetched.muted, "muted flag should persist after mutation");
1897    }
1898
1899    #[test]
1900    fn multiple_different_chats() {
1901        let mut state = ChatState::new();
1902        state.create_dm_chat("npub1alice");
1903        state.create_dm_chat("npub1bob");
1904        state.ensure_community_chat("grp1");
1905
1906        assert_eq!(state.chats.len(), 3, "should have three distinct chats");
1907    }
1908
1909    // ========================================================================
1910    // Message Management
1911    // ========================================================================
1912
1913    #[test]
1914    fn add_message_to_chat_single() {
1915        let mut state = ChatState::new();
1916        state.create_dm_chat("npub1peer");
1917
1918        let msg = make_message(1, "hello", 1700000000000, false);
1919        let added = state.add_message_to_chat("npub1peer", &msg);
1920
1921        assert!(added, "first message should be added successfully");
1922        let chat = state.get_chat("npub1peer").unwrap();
1923        assert_eq!(chat.message_count(), 1, "chat should have one message");
1924    }
1925
1926    #[test]
1927    fn add_message_to_chat_dedup_rejects_same_id() {
1928        let mut state = ChatState::new();
1929        state.create_dm_chat("npub1peer");
1930
1931        let msg1 = make_message(1, "hello", 1700000000000, false);
1932        let msg2 = make_message(1, "duplicate", 1700000001000, false);
1933
1934        let added1 = state.add_message_to_chat("npub1peer", &msg1);
1935        let added2 = state.add_message_to_chat("npub1peer", &msg2);
1936
1937        assert!(added1, "first insert should succeed");
1938        assert!(!added2, "duplicate ID should be rejected");
1939        assert_eq!(
1940            state.get_chat("npub1peer").unwrap().message_count(), 1,
1941            "should still have only one message"
1942        );
1943    }
1944
1945    #[test]
1946    fn add_messages_to_chat_batch_works() {
1947        let mut state = ChatState::new();
1948        state.create_dm_chat("npub1peer");
1949
1950        let msgs: Vec<Message> = (0..10).map(|i| {
1951            make_message(i, &format!("msg {}", i), 1700000000000 + i as u64 * 1000, false)
1952        }).collect();
1953
1954        let added = state.add_messages_to_chat_batch("npub1peer", msgs);
1955        assert_eq!(added, 10, "all 10 messages should be added");
1956        assert_eq!(
1957            state.get_chat("npub1peer").unwrap().message_count(), 10,
1958            "chat should have 10 messages"
1959        );
1960    }
1961
1962    #[test]
1963    fn add_messages_to_chat_batch_dedup() {
1964        let mut state = ChatState::new();
1965        state.create_dm_chat("npub1peer");
1966
1967        // Add first batch
1968        let msgs1: Vec<Message> = (0..5).map(|i| {
1969            make_message(i, &format!("msg {}", i), 1700000000000 + i as u64 * 1000, false)
1970        }).collect();
1971        state.add_messages_to_chat_batch("npub1peer", msgs1);
1972
1973        // Add overlapping batch (IDs 3,4 overlap, 5,6,7 are new)
1974        let msgs2: Vec<Message> = (3..8).map(|i| {
1975            make_message(i, &format!("msg {}", i), 1700000000000 + i as u64 * 1000, false)
1976        }).collect();
1977        let added = state.add_messages_to_chat_batch("npub1peer", msgs2);
1978
1979        assert_eq!(added, 3, "only 3 new messages should be added (5, 6, 7)");
1980        assert_eq!(
1981            state.get_chat("npub1peer").unwrap().message_count(), 8,
1982            "total should be 8 unique messages"
1983        );
1984    }
1985
1986    #[test]
1987    fn add_message_to_participant_creates_profile_and_chat() {
1988        let mut state = ChatState::new();
1989
1990        let msg = make_message(1, "hi there", 1700000000000, false);
1991        let added = state.add_message_to_participant("npub1stranger", &msg);
1992
1993        assert!(added, "message should be added");
1994        assert!(
1995            state.get_profile("npub1stranger").is_some(),
1996            "profile should be auto-created for unknown participant"
1997        );
1998        assert!(
1999            state.get_chat("npub1stranger").is_some(),
2000            "DM chat should be auto-created"
2001        );
2002    }
2003
2004    #[test]
2005    fn add_message_to_participant_uses_existing_profile() {
2006        let mut state = ChatState::new();
2007
2008        // Pre-create profile
2009        let mut profile = Profile::new();
2010        profile.set_name("Known User");
2011        state.insert_or_replace_profile("npub1known", profile);
2012
2013        let msg = make_message(1, "hello", 1700000000000, false);
2014        state.add_message_to_participant("npub1known", &msg);
2015
2016        // Profile should not be replaced
2017        let p = state.get_profile("npub1known").unwrap();
2018        assert_eq!(p.name(), "Known User", "existing profile should not be overwritten");
2019    }
2020
2021    #[test]
2022    fn find_message_across_chats() {
2023        let mut state = ChatState::new();
2024        state.create_dm_chat("npub1a");
2025        state.create_dm_chat("npub1b");
2026
2027        let msg_a = make_message(1, "in chat a", 1700000000000, false);
2028        let msg_b = make_message(2, "in chat b", 1700000001000, false);
2029        let msg_id_b = msg_b.id.clone();
2030
2031        state.add_message_to_chat("npub1a", &msg_a);
2032        state.add_message_to_chat("npub1b", &msg_b);
2033
2034        let (chat, found_msg) = state.find_message(&msg_id_b).expect("message should be found");
2035        assert_eq!(chat.id, "npub1b", "should find in correct chat");
2036        assert_eq!(found_msg.content, "in chat b", "content should match");
2037    }
2038
2039    #[test]
2040    fn find_message_returns_none_for_unknown() {
2041        let state = ChatState::new();
2042        assert!(
2043            state.find_message(&make_hex_id(99)).is_none(),
2044            "unknown message id should return None"
2045        );
2046    }
2047
2048    #[test]
2049    fn find_message_empty_id_returns_none() {
2050        let state = ChatState::new();
2051        assert!(state.find_message("").is_none(), "empty id should return None");
2052    }
2053
2054    #[test]
2055    fn update_message_mutates_and_returns() {
2056        let mut state = ChatState::new();
2057        state.create_dm_chat("npub1peer");
2058
2059        let msg = make_message(1, "original", 1700000000000, false);
2060        let msg_id = msg.id.clone();
2061        state.add_message_to_chat("npub1peer", &msg);
2062
2063        let result = state.update_message(&msg_id, |cm| {
2064            cm.at += 1;
2065        });
2066
2067        let (chat_id, updated) = result.expect("update should return Some");
2068        assert_eq!(chat_id, "npub1peer", "should return correct chat id");
2069        assert_eq!(updated.at, 1700000000001, "the update should land");
2070    }
2071
2072    #[test]
2073    fn update_message_returns_none_for_missing() {
2074        let mut state = ChatState::new();
2075        let result = state.update_message(&make_hex_id(99), |_cm| {});
2076        assert!(result.is_none(), "updating nonexistent message should return None");
2077    }
2078
2079    #[test]
2080    fn finalize_pending_message_changes_id() {
2081        let mut state = ChatState::new();
2082        state.create_dm_chat("npub1peer");
2083
2084        let mut msg = make_message(1, "pending msg", 1700000000000, true);
2085        msg.pending = true;
2086        let pending_id = msg.id.clone();
2087        state.add_message_to_chat("npub1peer", &msg);
2088
2089        let real_id = make_hex_id(2);
2090        let result = state.finalize_pending_message("npub1peer", &pending_id, &real_id);
2091
2092        let (old_id, finalized) = result.expect("finalize should succeed");
2093        assert_eq!(old_id, pending_id, "should return old pending id");
2094        assert_eq!(finalized.id, real_id, "message id should now be the real id");
2095        assert!(!finalized.pending, "message should no longer be pending");
2096
2097        // Old ID should no longer be findable
2098        assert!(
2099            state.find_message(&pending_id).is_none(),
2100            "pending id should no longer resolve"
2101        );
2102        // New ID should be findable
2103        assert!(
2104            state.find_message(&real_id).is_some(),
2105            "real id should now resolve"
2106        );
2107    }
2108
2109    #[test]
2110    fn remove_message_works() {
2111        let mut state = ChatState::new();
2112        state.create_dm_chat("npub1peer");
2113
2114        let msg = make_message(1, "deleteme", 1700000000000, false);
2115        let msg_id = msg.id.clone();
2116        state.add_message_to_chat("npub1peer", &msg);
2117
2118        let result = state.remove_message(&msg_id);
2119        assert!(result.is_some(), "remove should return the removed message");
2120
2121        let (chat_id, removed) = result.unwrap();
2122        assert_eq!(chat_id, "npub1peer", "should return correct chat id");
2123        assert_eq!(removed.content, "deleteme", "content should match");
2124
2125        assert!(
2126            state.find_message(&msg_id).is_none(),
2127            "removed message should no longer be findable"
2128        );
2129    }
2130
2131    #[test]
2132    fn remove_message_retreats_last_read_marker() {
2133        let mut state = ChatState::new();
2134        state.create_dm_chat("npub1peer");
2135        let m1 = make_message(1, "one", 1_700_000_000_000, false);
2136        let m2 = make_message(2, "two", 1_700_000_001_000, false);
2137        let (m1_id, m2_id) = (m1.id.clone(), m2.id.clone());
2138        state.add_message_to_chat("npub1peer", &m1);
2139        state.add_message_to_chat("npub1peer", &m2);
2140
2141        // Read up to the newest — m2 is the marker.
2142        state.chats.iter_mut().find(|c| c.id == "npub1peer").unwrap().last_read =
2143            crate::compact::encode_message_id(&m2_id);
2144
2145        // Deleting the marker retreats it to the prior survivor, never leaves it dangling.
2146        state.remove_message(&m2_id);
2147        assert_eq!(state.get_chat("npub1peer").unwrap().last_read,
2148            crate::compact::encode_message_id(&m1_id), "marker retreats to m1");
2149
2150        // Deleting the last survivor clears the marker (no predecessor).
2151        state.remove_message(&m1_id);
2152        assert_eq!(state.get_chat("npub1peer").unwrap().last_read, [0u8; 32],
2153            "no predecessor → marker clears");
2154    }
2155
2156    #[test]
2157    fn remove_message_returns_none_for_missing() {
2158        let mut state = ChatState::new();
2159        assert!(
2160            state.remove_message(&make_hex_id(99)).is_none(),
2161            "removing nonexistent message should return None"
2162        );
2163    }
2164
2165    #[test]
2166    fn message_exists_check() {
2167        let mut state = ChatState::new();
2168        state.create_dm_chat("npub1peer");
2169
2170        let msg = make_message(1, "exists", 1700000000000, false);
2171        let msg_id = msg.id.clone();
2172        state.add_message_to_chat("npub1peer", &msg);
2173
2174        assert!(state.message_exists(&msg_id), "added message should exist");
2175        assert!(!state.message_exists(&make_hex_id(99)), "unknown id should not exist");
2176        assert!(!state.message_exists(""), "empty id should not exist");
2177    }
2178
2179    #[test]
2180    fn chat_reordering_newest_first_after_message_add() {
2181        let mut state = ChatState::new();
2182        state.create_dm_chat("npub1old");
2183        state.create_dm_chat("npub1new");
2184
2185        // Add an old message to the first chat
2186        let old_msg = make_message(1, "old", 1700000000000, false);
2187        state.add_message_to_chat("npub1old", &old_msg);
2188
2189        // Add a newer message to the second chat
2190        let new_msg = make_message(2, "new", 1700000002000, false);
2191        state.add_message_to_chat("npub1new", &new_msg);
2192
2193        assert_eq!(
2194            state.chats[0].id, "npub1new",
2195            "chat with newest message should be first"
2196        );
2197        assert_eq!(
2198            state.chats[1].id, "npub1old",
2199            "chat with older message should be second"
2200        );
2201    }
2202
2203    #[test]
2204    fn batch_add_does_not_reorder_for_old_messages() {
2205        let mut state = ChatState::new();
2206        state.create_dm_chat("npub1active");
2207        state.create_dm_chat("npub1history");
2208
2209        // Give active chat a recent message
2210        let recent = make_message(1, "recent", 1700000010000, false);
2211        state.add_message_to_chat("npub1active", &recent);
2212
2213        // Batch-add old messages to history chat (pagination loading)
2214        let old_msgs: Vec<Message> = (10..15).map(|i| {
2215            make_message(i, &format!("old {}", i), 1700000000000 + i as u64 * 100, false)
2216        }).collect();
2217        state.add_messages_to_chat_batch("npub1history", old_msgs);
2218
2219        assert_eq!(
2220            state.chats[0].id, "npub1active",
2221            "active chat should remain first when batch has only old messages"
2222        );
2223    }
2224
2225    #[test]
2226    fn stress_test_50_messages_in_5_chats() {
2227        let mut state = ChatState::new();
2228
2229        for i in 0..5 {
2230            state.create_dm_chat(&format!("npub1chat{}", i));
2231        }
2232
2233        let mut total_added = 0;
2234        for i in 0..50u8 {
2235            let chat_idx = i as usize % 5;
2236            let chat_id = format!("npub1chat{}", chat_idx);
2237            let msg = make_message(i, &format!("msg {}", i), 1700000000000 + i as u64 * 1000, i % 3 == 0);
2238            if state.add_message_to_chat(&chat_id, &msg) {
2239                total_added += 1;
2240            }
2241        }
2242
2243        assert_eq!(total_added, 50, "all 50 unique messages should be added");
2244
2245        let total_in_chats: usize = state.chats.iter().map(|c| c.message_count()).sum();
2246        assert_eq!(total_in_chats, 50, "total messages across all chats should be 50");
2247
2248        // Each chat should have 10 messages
2249        for i in 0..5 {
2250            let chat = state.get_chat(&format!("npub1chat{}", i)).unwrap();
2251            assert_eq!(
2252                chat.message_count(), 10,
2253                "chat {} should have 10 messages",
2254                i
2255            );
2256        }
2257
2258        // All messages should be findable
2259        for i in 0..50u8 {
2260            assert!(
2261                state.message_exists(&make_hex_id(i)),
2262                "message {} should exist",
2263                i
2264            );
2265        }
2266    }
2267
2268    #[test]
2269    fn add_message_auto_creates_dm_chat() {
2270        let mut state = ChatState::new();
2271
2272        // Add message to a chat that doesn't exist yet (npub-style ID)
2273        let msg = make_message(1, "auto create", 1700000000000, false);
2274        let added = state.add_message_to_chat("npub1auto", &msg);
2275
2276        assert!(added, "message should be added");
2277        assert!(state.get_chat("npub1auto").is_some(), "DM chat should be auto-created");
2278    }
2279
2280    #[test]
2281    fn add_message_auto_creates_community_chat() {
2282        let mut state = ChatState::new();
2283
2284        // Add message to a non-npub ID (should create a Community chat)
2285        let msg = make_message(1, "group msg", 1700000000000, false);
2286        let added = state.add_message_to_chat("group_abc123", &msg);
2287
2288        assert!(added, "message should be added");
2289        let chat = state.get_chat("group_abc123").expect("community chat should be auto-created");
2290        assert!(chat.is_community(), "auto-created non-npub chat should be a Community chat");
2291    }
2292
2293    // ========================================================================
2294    // Unread Count
2295    // ========================================================================
2296
2297    #[test]
2298    fn count_unread_messages_basic() {
2299        let mut state = ChatState::new();
2300        state.create_dm_chat("npub1peer");
2301
2302        for i in 0..5u8 {
2303            let msg = make_message(i, &format!("msg {}", i), 1700000000000 + i as u64 * 1000, false);
2304            state.add_message_to_chat("npub1peer", &msg);
2305        }
2306
2307        assert_eq!(state.count_unread_messages(), 5, "all 5 non-mine messages should be unread");
2308    }
2309
2310    #[test]
2311    fn count_unread_muted_chat_skipped() {
2312        let mut state = ChatState::new();
2313        state.create_dm_chat("npub1muted");
2314
2315        let msg = make_message(1, "muted msg", 1700000000000, false);
2316        state.add_message_to_chat("npub1muted", &msg);
2317
2318        state.get_chat_mut("npub1muted").unwrap().muted = true;
2319
2320        assert_eq!(state.count_unread_messages(), 0, "muted chat should not count toward unread");
2321    }
2322
2323    #[test]
2324    fn count_unread_blocked_user_skipped() {
2325        let mut state = ChatState::new();
2326
2327        let mut profile = Profile::new();
2328        profile.flags.set_blocked(true);
2329        state.insert_or_replace_profile("npub1blocked", profile);
2330        state.create_dm_chat("npub1blocked");
2331
2332        let msg = make_message(1, "blocked msg", 1700000000000, false);
2333        state.add_message_to_chat("npub1blocked", &msg);
2334
2335        assert_eq!(state.count_unread_messages(), 0, "blocked user DM should not count");
2336    }
2337
2338    #[test]
2339    fn blocked_pictures_are_forgotten_but_a_file_another_profile_shows_is_kept() {
2340        let mut state = ChatState::new();
2341        let mut shown = |npub: &str, blocked: bool, avatar: &str| {
2342            let mut p = Profile::new();
2343            p.set_avatar(&format!("https://x/{avatar}"));
2344            p.set_avatar_cached(&format!("/cache/avatars/{avatar}"));
2345            p.flags.set_blocked(blocked);
2346            state.insert_or_replace_profile(npub, p);
2347        };
2348        shown("npub1blocked", true, "own.png");
2349        shown("npub1alsoblocked", true, "shared.png");
2350        shown("npub1friend", false, "shared.png");
2351
2352        let (slims, files) = state.forget_blocked_imagery();
2353        let mut ids: Vec<&str> = slims.iter().map(|s| s.id.as_str()).collect();
2354        ids.sort();
2355        assert_eq!(ids, ["npub1alsoblocked", "npub1blocked"]);
2356        assert!(slims.iter().all(|s| s.avatar.is_empty() && s.avatar_cached.is_empty()));
2357        let paths: Vec<&str> = files.iter().map(|f| f.path.as_str()).collect();
2358        assert_eq!(paths, ["/cache/avatars/own.png"], "the friend still shows shared.png");
2359        assert!(state.get_profile("npub1friend").unwrap().has_avatar_cached());
2360        assert!(state.forget_blocked_imagery().0.is_empty(), "a second sweep finds nothing");
2361    }
2362
2363    #[test]
2364    fn a_live_message_counts_in_ram_unless_its_author_is_blocked_or_muted() {
2365        let mut state = ChatState::new();
2366        state.create_dm_chat("npub1room");
2367        let mut blocked = Profile::new();
2368        blocked.flags.set_blocked(true);
2369        state.insert_or_replace_profile("npub1blocked", blocked);
2370        state.create_dm_chat("npub1muted");
2371        state.get_chat_mut("npub1muted").unwrap().muted = true;
2372
2373        state.unread_bump("npub1room", Some("npub1friend"));
2374        state.unread_bump("npub1room", None);
2375        state.unread_bump("npub1room", Some("npub1blocked"));
2376        state.unread_bump("npub1room", Some("npub1muted"));
2377        assert_eq!(state.unread_cache.get("npub1room"), Some(&2));
2378    }
2379
2380    #[test]
2381    fn unread_cache_seed_clear_set_and_sum() {
2382        let mut state = ChatState::new();
2383        state.create_dm_chat("npub1a");
2384        state.create_dm_chat("npub1b");
2385
2386        let mut seed = std::collections::HashMap::new();
2387        seed.insert("npub1a".to_string(), 3u32);
2388        seed.insert("npub1b".to_string(), 2u32);
2389        state.unread_seed(seed);
2390        assert!(state.unread_seeded);
2391        assert_eq!(state.sum_unread(), 5);
2392
2393        state.unread_clear("npub1a");
2394        assert_eq!(state.sum_unread(), 2, "clear drops a's 3");
2395
2396        state.unread_set("npub1b", 4);
2397        assert_eq!(state.sum_unread(), 4, "reconcile b to exact 4");
2398        state.unread_set("npub1b", 0);
2399        assert_eq!(state.sum_unread(), 0);
2400        assert!(!state.unread_cache.contains_key("npub1b"), "a zero count drops the entry");
2401    }
2402
2403    #[test]
2404    fn unread_cache_sum_honours_muted_and_blocked() {
2405        let mut state = ChatState::new();
2406        let mut blocked = Profile::new();
2407        blocked.flags.set_blocked(true);
2408        state.insert_or_replace_profile("npub1blk", blocked);
2409        state.create_dm_chat("npub1blk");
2410        state.create_dm_chat("npub1mut");
2411        state.get_chat_mut("npub1mut").unwrap().muted = true;
2412        state.create_dm_chat("npub1ok");
2413
2414        let mut seed = std::collections::HashMap::new();
2415        seed.insert("npub1blk".to_string(), 5u32);
2416        seed.insert("npub1mut".to_string(), 7u32);
2417        seed.insert("npub1ok".to_string(), 2u32);
2418        state.unread_seed(seed);
2419
2420        // Blocked + muted chats are filtered exactly like sum_unread_from; only the normal chat counts.
2421        assert_eq!(state.sum_unread(), 2);
2422    }
2423
2424    #[test]
2425    fn count_unread_own_messages_break_count() {
2426        let mut state = ChatState::new();
2427        state.create_dm_chat("npub1peer");
2428
2429        // 3 from them, then 1 from me, then 2 from them
2430        let msg1 = make_message(1, "them 1", 1700000001000, false);
2431        let msg2 = make_message(2, "them 2", 1700000002000, false);
2432        let msg3 = make_message(3, "them 3", 1700000003000, false);
2433        let msg_mine = make_message(4, "me", 1700000004000, true);
2434        let msg5 = make_message(5, "them 4", 1700000005000, false);
2435        let msg6 = make_message(6, "them 5", 1700000006000, false);
2436
2437        for m in [msg1, msg2, msg3, msg_mine, msg5, msg6] {
2438            state.add_message_to_chat("npub1peer", &m);
2439        }
2440
2441        // Counting from the end: msg6 (unread), msg5 (unread), then msg_mine breaks
2442        assert_eq!(
2443            state.count_unread_messages(), 2,
2444            "only messages after last 'mine' should count as unread"
2445        );
2446    }
2447
2448    #[test]
2449    fn count_unread_from_counts_past_own_messages() {
2450        let mut state = ChatState::new();
2451        state.create_dm_chat("npub1peer");
2452        for m in [
2453            make_message(1, "them 1", 1700000001000, false),
2454            make_message(2, "them 2", 1700000002000, false),
2455            make_message(3, "me", 1700000003000, true),
2456            make_message(4, "them 3", 1700000004000, false),
2457            make_message(5, "me", 1700000005000, true),
2458        ] {
2459            state.add_message_to_chat("npub1peer", &m);
2460        }
2461        assert_eq!(state.count_unread_messages(), 0, "our newest reply reads everything");
2462
2463        let chat = state.chats.iter_mut().find(|c| c.id == "npub1peer").unwrap();
2464        chat.unread_from = crate::compact::encode_message_id(&make_hex_id(2));
2465        assert_eq!(state.count_unread_messages(), 2, "them 2 and them 3, past our replies");
2466
2467        let chat = state.chats.iter_mut().find(|c| c.id == "npub1peer").unwrap();
2468        assert!(chat.set_as_read());
2469        assert_eq!(chat.unread_from, [0u8; 32], "a read clears the mark");
2470        assert_eq!(state.count_unread_messages(), 0);
2471    }
2472
2473    #[test]
2474    fn count_unread_last_read_marker_breaks_count() {
2475        let mut state = ChatState::new();
2476        state.create_dm_chat("npub1peer");
2477
2478        let msg1 = make_message(1, "old", 1700000001000, false);
2479        let msg2 = make_message(2, "read up to here", 1700000002000, false);
2480        let msg3 = make_message(3, "new 1", 1700000003000, false);
2481        let msg4 = make_message(4, "new 2", 1700000004000, false);
2482        let read_marker_id = msg2.id.clone();
2483
2484        for m in [msg1, msg2, msg3, msg4] {
2485            state.add_message_to_chat("npub1peer", &m);
2486        }
2487
2488        // Set last_read to msg2's ID
2489        let chat = state.get_chat_mut("npub1peer").unwrap();
2490        chat.last_read = crate::simd::hex::hex_to_bytes_32(&read_marker_id);
2491
2492        assert_eq!(
2493            state.count_unread_messages(), 2,
2494            "only messages after last_read marker should count"
2495        );
2496    }
2497
2498    #[test]
2499    fn count_unread_empty_chats_is_zero() {
2500        let mut state = ChatState::new();
2501        state.create_dm_chat("npub1empty1");
2502        state.create_dm_chat("npub1empty2");
2503
2504        assert_eq!(state.count_unread_messages(), 0, "empty chats should have zero unread");
2505    }
2506
2507    #[test]
2508    fn count_unread_blocked_group_member_messages_skipped() {
2509        let mut state = ChatState::new();
2510
2511        // Create a blocked profile
2512        let mut blocked_profile = Profile::new();
2513        blocked_profile.flags.set_blocked(true);
2514        state.insert_or_replace_profile("npub1blockedmember", blocked_profile);
2515
2516        // Create a normal profile
2517        let normal_profile = Profile::new();
2518        state.insert_or_replace_profile("npub1normal", normal_profile);
2519
2520        // A SURFACED community row (carries its owning community_id) — a bare
2521        // anchor row is excluded from unread totals by design.
2522        state.ensure_community_chat("grp1");
2523        if let Some(chat) = state.chats.iter_mut().find(|c| c.id == "grp1") {
2524            chat.metadata.insert("community_id", "c".repeat(64));
2525        }
2526
2527        // Message from blocked member
2528        let msg_blocked = make_message_from(1, "blocked says hi", 1700000001000, "npub1blockedmember");
2529        state.add_message_to_chat("grp1", &msg_blocked);
2530
2531        // Message from normal member
2532        let msg_normal = make_message_from(2, "normal says hi", 1700000002000, "npub1normal");
2533        state.add_message_to_chat("grp1", &msg_normal);
2534
2535        assert_eq!(
2536            state.count_unread_messages(), 1,
2537            "only the non-blocked member's message should count"
2538        );
2539    }
2540
2541    #[test]
2542    fn count_unread_muted_sender_group_messages_skipped() {
2543        let mut state = ChatState::new();
2544        state.insert_or_replace_profile("npub1mutedmember", Profile::new());
2545        state.insert_or_replace_profile("npub1normal", Profile::new());
2546
2547        // Muting a person = muting their (possibly message-less) DM row.
2548        state.create_dm_chat("npub1mutedmember");
2549        state.get_chat_mut("npub1mutedmember").unwrap().muted = true;
2550
2551        state.ensure_community_chat("grp1");
2552        if let Some(chat) = state.chats.iter_mut().find(|c| c.id == "grp1") {
2553            chat.metadata.insert("community_id", "c".repeat(64));
2554        }
2555
2556        let msg_muted = make_message_from(1, "muted says hi", 1700000001000, "npub1mutedmember");
2557        state.add_message_to_chat("grp1", &msg_muted);
2558        let msg_normal = make_message_from(2, "normal says hi", 1700000002000, "npub1normal");
2559        state.add_message_to_chat("grp1", &msg_normal);
2560
2561        assert_eq!(
2562            state.count_unread_messages(), 1,
2563            "a muted sender's community messages should not count"
2564        );
2565    }
2566
2567    #[test]
2568    fn count_unread_multiple_chats_summed() {
2569        let mut state = ChatState::new();
2570
2571        for i in 0..3 {
2572            let npub = format!("npub1chat{}", i);
2573            state.create_dm_chat(&npub);
2574            for j in 0..3u8 {
2575                let msg = make_message(
2576                    i * 10 + j,
2577                    &format!("msg {}-{}", i, j),
2578                    1700000000000 + j as u64 * 1000,
2579                    false,
2580                );
2581                state.add_message_to_chat(&npub, &msg);
2582            }
2583        }
2584
2585        assert_eq!(
2586            state.count_unread_messages(), 9,
2587            "3 chats x 3 unread each = 9 total"
2588        );
2589    }
2590
2591    // ========================================================================
2592    // Typing Indicators
2593    // ========================================================================
2594
2595    #[test]
2596    fn update_typing_and_get_active_basic() {
2597        let mut state = ChatState::new();
2598        state.create_dm_chat("npub1peer");
2599
2600        // Set a far-future expiry so it's definitely active
2601        let far_future = web_time::SystemTime::now()
2602            .duration_since(web_time::UNIX_EPOCH).unwrap().as_secs() + 300;
2603
2604        let active = state.update_typing_and_get_active("npub1peer", "npub1typer", far_future);
2605        assert_eq!(active.len(), 1, "should have one active typer");
2606        assert_eq!(active[0], "npub1typer", "typer npub should match");
2607    }
2608
2609    #[test]
2610    fn a_blocked_user_never_shows_as_typing() {
2611        let mut state = ChatState::new();
2612        state.create_dm_chat("npub1peer");
2613        let far_future = web_time::SystemTime::now()
2614            .duration_since(web_time::UNIX_EPOCH).unwrap().as_secs() + 300;
2615        let mut profile = Profile::new();
2616        profile.flags.set_blocked(true);
2617        state.insert_or_replace_profile("npub1blocked", profile);
2618
2619        assert!(state.update_typing_and_get_active("npub1peer", "npub1blocked", far_future).is_empty());
2620        assert_eq!(state.update_typing_and_get_active("npub1peer", "npub1typer", far_future), vec!["npub1typer"]);
2621
2622        // Blocked mid-typing: gone from the next list.
2623        let mut typer = Profile::new();
2624        typer.flags.set_blocked(true);
2625        state.insert_or_replace_profile("npub1typer", typer);
2626        assert!(state.update_typing_and_get_active("npub1peer", "npub1other", 0).is_empty());
2627    }
2628
2629    #[test]
2630    fn update_typing_expired_typers_filtered() {
2631        let mut state = ChatState::new();
2632        state.create_dm_chat("npub1peer");
2633
2634        // Expired timestamp (in the past)
2635        let expired = 1000;
2636        let active = state.update_typing_and_get_active("npub1peer", "npub1expired", expired);
2637
2638        assert!(active.is_empty(), "expired typer should be filtered out");
2639    }
2640
2641    #[test]
2642    fn update_typing_multiple_typers() {
2643        let mut state = ChatState::new();
2644        state.create_dm_chat("npub1peer");
2645
2646        let far_future = web_time::SystemTime::now()
2647            .duration_since(web_time::UNIX_EPOCH).unwrap().as_secs() + 300;
2648
2649        state.update_typing_and_get_active("npub1peer", "npub1typer1", far_future);
2650        let active = state.update_typing_and_get_active("npub1peer", "npub1typer2", far_future);
2651
2652        assert_eq!(active.len(), 2, "should have two active typers");
2653    }
2654
2655    #[test]
2656    fn update_typing_unknown_chat_returns_empty() {
2657        let mut state = ChatState::new();
2658        let far_future = web_time::SystemTime::now()
2659            .duration_since(web_time::UNIX_EPOCH).unwrap().as_secs() + 300;
2660
2661        let active = state.update_typing_and_get_active("npub1nonexistent", "npub1typer", far_future);
2662        assert!(active.is_empty(), "unknown chat should return empty typers");
2663    }
2664
2665    #[test]
2666    fn update_typing_refreshes_existing_typer() {
2667        let mut state = ChatState::new();
2668        state.create_dm_chat("npub1peer");
2669
2670        let far_future = web_time::SystemTime::now()
2671            .duration_since(web_time::UNIX_EPOCH).unwrap().as_secs() + 300;
2672
2673        state.update_typing_and_get_active("npub1peer", "npub1typer", far_future);
2674        // Update the same typer with a new expiry
2675        let active = state.update_typing_and_get_active("npub1peer", "npub1typer", far_future + 100);
2676
2677        assert_eq!(active.len(), 1, "should still have only one typer entry after refresh");
2678    }
2679
2680    // ========================================================================
2681    // WrapperIdCache
2682    // ========================================================================
2683
2684    #[test]
2685    fn wrapper_id_cache_historical_and_pending() {
2686        let mut cache = WrapperIdCache::new();
2687
2688        let id1 = [1u8; 32];
2689        let id2 = [2u8; 32];
2690        let id3 = [3u8; 32];
2691
2692        cache.load(vec![id1, id2]);
2693        cache.insert(id3);
2694
2695        assert!(cache.contains(&id1), "historical id should be found");
2696        assert!(cache.contains(&id2), "historical id should be found");
2697        assert!(cache.contains(&id3), "pending id should be found");
2698        assert!(!cache.contains(&[4u8; 32]), "unknown id should not be found");
2699        assert_eq!(cache.len(), 3, "total count should be 3");
2700    }
2701
2702    #[test]
2703    fn an_idle_wrapper_cache_keeps_only_the_newest_inserts() {
2704        let mut cache = WrapperIdCache::new();
2705        let id = |n: u32| {
2706            let mut b = [0u8; 32];
2707            b[..4].copy_from_slice(&n.to_le_bytes());
2708            b
2709        };
2710        let extra = 5u32;
2711        for n in 0..IDLE_PENDING_CAP as u32 + extra {
2712            cache.insert(id(n));
2713        }
2714        cache.insert(id(IDLE_PENDING_CAP as u32 + extra - 1));
2715        assert_eq!(cache.len(), IDLE_PENDING_CAP);
2716        for n in 0..extra {
2717            assert!(!cache.contains(&id(n)), "id {n} was among the oldest");
2718        }
2719        assert!(cache.contains(&id(extra)), "the oldest kept");
2720        assert!(cache.contains(&id(IDLE_PENDING_CAP as u32 + extra - 1)), "the newest kept");
2721
2722        cache.load(vec![]);
2723        for n in 0..IDLE_PENDING_CAP as u32 * 2 {
2724            cache.insert(id(n));
2725        }
2726        assert_eq!(cache.len(), IDLE_PENDING_CAP * 2, "a sync keeps everything until the dump");
2727        assert!(cache.contains(&id(0)));
2728
2729        cache.clear();
2730        for n in 0..IDLE_PENDING_CAP as u32 + 1 {
2731            cache.insert(id(n));
2732        }
2733        assert_eq!(cache.len(), IDLE_PENDING_CAP, "idle again after the dump");
2734        assert!(!cache.contains(&id(0)) && cache.contains(&id(1)));
2735    }
2736
2737    #[test]
2738    fn wrapper_id_cache_clear() {
2739        let mut cache = WrapperIdCache::new();
2740        cache.load(vec![[1u8; 32]]);
2741        cache.insert([2u8; 32]);
2742
2743        cache.clear();
2744
2745        assert_eq!(cache.len(), 0, "cache should be empty after clear");
2746        assert!(!cache.contains(&[1u8; 32]), "cleared historical should not be found");
2747        assert!(!cache.contains(&[2u8; 32]), "cleared pending should not be found");
2748    }
2749}