Skip to main content

vector_core/
chat.rs

1//! Chat types and management — compact message storage.
2//!
3//! `Chat` uses `CompactMessageVec` internally for memory efficiency.
4//! Use `to_serializable()` to convert to frontend-friendly `SerializableChat`.
5
6use serde::{Deserialize, Serialize};
7use std::borrow::Cow;
8use std::collections::HashMap;
9use std::sync::Arc;
10
11use crate::compact::{CompactMessage, CompactMessageVec, NpubInterner, encode_message_id, decode_message_id};
12use crate::types::Message;
13
14// ============================================================================
15// Chat (Internal Storage)
16// ============================================================================
17
18/// Metadata key a DM carries once its request was accepted without a reply.
19pub const ACCEPTED_KEY: &str = "accepted";
20
21#[derive(Clone, Debug)]
22pub struct Chat {
23    pub id: String,
24    pub chat_type: ChatType,
25    pub participants: Vec<u16>,
26    pub messages: CompactMessageVec,
27    pub last_read: [u8; 32],
28    /// "Mark as Unread" from a chosen message: while set, that message and every later message
29    /// from others count as unread; our own messages after it don't end the count. A read clears it.
30    pub unread_from: [u8; 32],
31    pub created_at: u64,
32    pub metadata: ChatMetadata,
33    pub muted: bool,
34    pub typing_participants: Vec<(u16, u64)>,
35    /// Local cached file path for the per-DM wallpaper, or empty when unset.
36    /// Populated from the most recent kind-30078 d=vector-wallpaper rumor
37    /// received for this chat (the encrypted Blossom file is fetched and
38    /// decrypted to this path).
39    pub wallpaper_path: String,
40    /// Rumor created_at (Unix seconds) that produced the current wallpaper.
41    /// Used as the latest-write-wins tiebreaker on concurrent sets.
42    pub wallpaper_ts: u64,
43    /// Blur amount in pixels applied to the wallpaper background layer
44    /// (0..=30, clamped on read). 0 means no blur.
45    pub wallpaper_blur: u8,
46    /// Brightness percent applied to the wallpaper background layer
47    /// (0..=100, clamped on read). 100 means no darkening; 0 is fully
48    /// dim. Default 70 keeps text readable on photographic wallpapers.
49    pub wallpaper_dim: u8,
50    /// Blossom URL of the encrypted wallpaper blob currently in effect.
51    /// Used to DELETE the previous blob when we (or our other device)
52    /// replace the wallpaper, so stale uploads don't linger on servers.
53    pub wallpaper_url: String,
54    /// npub (bech32) of whichever account uploaded the current wallpaper.
55    /// Gate on this before issuing the Blossom DELETE — only the original
56    /// uploader's signature satisfies the server's auth challenge.
57    pub wallpaper_uploader: String,
58    /// Whether we have ever sent a message here. A DM we never answered is a request.
59    pub replied: bool,
60}
61
62impl Chat {
63    pub fn new(id: String, chat_type: ChatType, participants: Vec<u16>) -> Self {
64        Self {
65            id,
66            chat_type,
67            participants,
68            messages: CompactMessageVec::new(),
69            last_read: [0u8; 32],
70            unread_from: [0u8; 32],
71            created_at: crate::clock::now_secs(),
72            metadata: ChatMetadata::new(),
73            muted: false,
74            typing_participants: Vec::new(),
75            wallpaper_path: String::new(),
76            wallpaper_ts: 0,
77            wallpaper_blur: 0,
78            wallpaper_dim: 50,
79            wallpaper_url: String::new(),
80            wallpaper_uploader: String::new(),
81            replied: false,
82        }
83    }
84
85    pub fn new_dm(their_npub: String, interner: &mut NpubInterner) -> Self {
86        let handle = interner.intern(&their_npub);
87        Self::new(their_npub, ChatType::DirectMessage, vec![handle])
88    }
89
90
91    /// A Community channel chat (GROUP_PROTOCOL.md). `channel_id` is the channel's
92    /// stable random id (hex); `participants` are the members known so far.
93    pub fn new_community_channel(channel_id: String, participants: Vec<String>, interner: &mut NpubInterner) -> Self {
94        let handles: Vec<u16> = participants.iter().map(|p| interner.intern(p)).collect();
95        Self::new(channel_id, ChatType::Community, handles)
96    }
97
98    // ========================================================================
99    // Message Access
100    // ========================================================================
101
102    /// A DM nobody here has answered or accepted, whether or not anything is in it yet.
103    pub fn is_unanswered(&self) -> bool {
104        self.chat_type == ChatType::DirectMessage
105            && !self.replied
106            && !self.metadata.contains_key(ACCEPTED_KEY)
107    }
108
109    /// An unanswered DM with something in it: what its sender sends, and their pictures,
110    /// stay unloaded until it's answered or accepted.
111    pub fn is_request(&self) -> bool {
112        self.is_unanswered() && !self.messages.is_empty()
113    }
114
115    #[inline]
116    pub fn message_count(&self) -> usize { self.messages.len() }
117
118    #[inline]
119    pub fn is_empty(&self) -> bool { self.messages.is_empty() }
120
121    #[inline]
122    pub fn last_message_time(&self) -> Option<u64> { self.messages.last_timestamp() }
123
124    #[inline]
125    pub fn has_message(&self, id: &str) -> bool { self.messages.contains_hex_id(id) }
126
127    #[inline]
128    pub fn get_compact_message(&self, id: &str) -> Option<&CompactMessage> {
129        self.messages.find_by_hex_id(id)
130    }
131
132    #[inline]
133    pub fn get_compact_message_mut(&mut self, id: &str) -> Option<&mut CompactMessage> {
134        self.messages.find_by_hex_id_mut(id)
135    }
136
137    pub fn get_message(&self, id: &str, interner: &NpubInterner) -> Option<Message> {
138        self.messages.find_by_hex_id(id).map(|cm| cm.to_message(interner))
139    }
140
141    #[inline]
142    pub fn iter_compact(&self) -> std::slice::Iter<'_, CompactMessage> {
143        self.messages.iter()
144    }
145
146    pub fn get_all_messages(&self, interner: &NpubInterner) -> Vec<Message> {
147        self.messages.iter().map(|cm| cm.to_message(interner)).collect()
148    }
149
150    pub fn get_last_messages(&self, n: usize, interner: &NpubInterner) -> Vec<Message> {
151        let len = self.messages.len();
152        let start = len.saturating_sub(n);
153        self.messages.messages()[start..].iter().map(|cm| cm.to_message(interner)).collect()
154    }
155
156    // ========================================================================
157    // Message Mutation
158    // ========================================================================
159
160    pub fn add_message(&mut self, message: Message, interner: &mut NpubInterner) -> bool {
161        let compact = CompactMessage::from_message_owned(message, interner);
162        self.add_compact_message(compact)
163    }
164
165    #[inline]
166    pub fn add_compact_message(&mut self, message: CompactMessage) -> bool {
167        self.replied |= message.flags.is_mine();
168        self.messages.insert(message)
169    }
170
171    pub fn set_as_read(&mut self) -> bool {
172        for msg in self.messages.iter().rev() {
173            if !msg.flags.is_mine() {
174                self.mark_read_at(*msg.id());
175                return true;
176            }
177        }
178        false
179    }
180
181    /// Advance the read marker; reading ends a "Mark as Unread" from a chosen message.
182    pub fn mark_read_at(&mut self, id: [u8; 32]) {
183        self.last_read = id;
184        self.unread_from = [0u8; 32];
185    }
186
187    pub fn internal_add_message(&mut self, message: Message, interner: &mut NpubInterner) -> bool {
188        self.add_message(message, interner)
189    }
190
191    #[inline]
192    pub fn get_message_mut(&mut self, id: &str) -> Option<&mut CompactMessage> {
193        self.get_compact_message_mut(id)
194    }
195
196    // ========================================================================
197    // Serialization
198    // ========================================================================
199
200    fn resolve_participants(&self, interner: &NpubInterner) -> Vec<String> {
201        self.participants.iter()
202            .filter_map(|&h| interner.resolve(h).map(|s| s.to_string()))
203            .collect()
204    }
205
206    pub fn to_serializable(&self, interner: &NpubInterner) -> SerializableChat {
207        let resolved = crate::notify::resolve_chat(self);
208        SerializableChat {
209            id: self.id.clone(),
210            chat_type: self.chat_type.clone(),
211            participants: self.resolve_participants(interner),
212            messages: self.get_all_messages(interner),
213            last_read: if self.last_read == [0u8; 32] { String::new() } else { decode_message_id(&self.last_read) },
214            unread_from: if self.unread_from == [0u8; 32] { String::new() } else { decode_message_id(&self.unread_from) },
215            created_at: self.created_at,
216            metadata: self.metadata.clone(),
217            muted: resolved.muted,
218            notify: resolved.ring.as_u8(),
219            everyone_pings: crate::notify::everyone_pings_for_chat(self),
220            community_muted: crate::notify::community_muted_for_chat(self),
221            wallpaper_path: self.wallpaper_path.clone(),
222            wallpaper_ts: self.wallpaper_ts,
223            wallpaper_blur: self.wallpaper_blur,
224            wallpaper_dim: self.wallpaper_dim,
225            wallpaper_url: self.wallpaper_url.clone(),
226            wallpaper_uploader: self.wallpaper_uploader.clone(),
227            replied: self.replied,
228        }
229    }
230
231    pub fn to_serializable_with_last_n(&self, n: usize, interner: &NpubInterner) -> SerializableChat {
232        let resolved = crate::notify::resolve_chat(self);
233        SerializableChat {
234            id: self.id.clone(),
235            chat_type: self.chat_type.clone(),
236            participants: self.resolve_participants(interner),
237            messages: self.get_last_messages(n, interner),
238            last_read: if self.last_read == [0u8; 32] { String::new() } else { decode_message_id(&self.last_read) },
239            unread_from: if self.unread_from == [0u8; 32] { String::new() } else { decode_message_id(&self.unread_from) },
240            created_at: self.created_at,
241            metadata: self.metadata.clone(),
242            muted: resolved.muted,
243            notify: resolved.ring.as_u8(),
244            everyone_pings: crate::notify::everyone_pings_for_chat(self),
245            community_muted: crate::notify::community_muted_for_chat(self),
246            wallpaper_path: self.wallpaper_path.clone(),
247            wallpaper_ts: self.wallpaper_ts,
248            wallpaper_blur: self.wallpaper_blur,
249            wallpaper_dim: self.wallpaper_dim,
250            wallpaper_url: self.wallpaper_url.clone(),
251            wallpaper_uploader: self.wallpaper_uploader.clone(),
252            replied: self.replied,
253        }
254    }
255
256    // ========================================================================
257    // Chat Metadata & Participants
258    // ========================================================================
259
260    pub fn get_other_participant(&self, my_npub: &str, interner: &NpubInterner) -> Option<String> {
261        match self.chat_type {
262            ChatType::DirectMessage => {
263                let my_handle = interner.lookup(my_npub);
264                self.participants.iter()
265                    .find(|&&h| Some(h) != my_handle)
266                    .and_then(|&h| interner.resolve(h).map(|s| s.to_string()))
267            }
268            // Community channels have no single "other" participant.
269            ChatType::Community => None,
270        }
271    }
272
273    pub fn is_dm_with(&self, npub: &str, interner: &NpubInterner) -> bool {
274        matches!(self.chat_type, ChatType::DirectMessage)
275            && interner.lookup(npub).is_some_and(|h| self.participants.contains(&h))
276    }
277
278    pub fn is_community(&self) -> bool { matches!(self.chat_type, ChatType::Community) }
279
280    /// Whether this Community channel is the row its community actually shows in the chat
281    /// list. Every channel is registered and synced, but a community surfaces as a SINGLE
282    /// row: the one whose id matches its `primary_channel` stamp.
283    ///
284    /// Anything deciding what the user can SEE or CLEAR must gate on this, not on the
285    /// presence of `community_id` — a sibling channel's unread would otherwise badge the
286    /// OS with no row to open. A row written before the stamp existed is assumed surfaced
287    /// (it re-stamps on the next registration), which matches the chat list's own
288    /// fallback so the two can't disagree.
289    pub fn is_surfaced_community_channel(&self) -> bool {
290        if self.metadata.community_id().is_none() {
291            return false; // bare persistence anchor from the message-persist path
292        }
293        match self.metadata.primary_channel() {
294            Some(primary) => primary == self.id,
295            None => true,
296        }
297    }
298
299    pub fn has_participant(&self, npub: &str, interner: &NpubInterner) -> bool {
300        interner.lookup(npub).is_some_and(|h| self.participants.contains(&h))
301    }
302
303    pub fn get_active_typers(&self, interner: &NpubInterner) -> Vec<String> {
304        let now = crate::clock::now_secs();
305        self.typing_participants.iter()
306            .filter(|(_, exp)| *exp > now)
307            .filter_map(|(h, _)| interner.resolve(*h).map(|s| s.to_string()))
308            .collect()
309    }
310
311    pub fn update_typing_participant(&mut self, handle: u16, expires_at: u64) {
312        if let Some(entry) = self.typing_participants.iter_mut().find(|(h, _)| *h == handle) {
313            entry.1 = expires_at;
314        } else {
315            self.typing_participants.push((handle, expires_at));
316        }
317        let now = crate::clock::now_secs();
318        self.typing_participants.retain(|(_, exp)| *exp > now);
319    }
320
321    pub fn id(&self) -> &String { &self.id }
322    pub fn chat_type(&self) -> &ChatType { &self.chat_type }
323    pub fn participants(&self) -> &[u16] { &self.participants }
324    pub fn last_read(&self) -> &[u8; 32] { &self.last_read }
325    pub fn created_at(&self) -> u64 { self.created_at }
326    pub fn metadata(&self) -> &ChatMetadata { &self.metadata }
327    pub fn muted(&self) -> bool { self.muted }
328}
329
330// ============================================================================
331// SerializableChat (Frontend Communication)
332// ============================================================================
333
334#[derive(Serialize, Deserialize, Clone, Debug)]
335pub struct SerializableChat {
336    pub id: String,
337    pub chat_type: ChatType,
338    pub participants: Vec<String>,
339    pub messages: Vec<Message>,
340    pub last_read: String,
341    /// Hex id of the message a "Mark as Unread" counts from; empty when not set.
342    #[serde(default)]
343    pub unread_from: String,
344    pub created_at: u64,
345    pub metadata: ChatMetadata,
346    /// Effective mute, after the community's own mute and any timer. The row
347    /// greys on this; `notify` is what it badges with.
348    pub muted: bool,
349    /// The resolved level AFTER the mute clamp, as `NotifyLevel::as_u8`. The
350    /// frontend badges from this alone rather than re-walking the chain.
351    #[serde(default)]
352    pub notify: u8,
353    /// Whether an authorized @everyone still counts as a ping here, i.e. the
354    /// community has not suppressed it.
355    #[serde(default = "default_everyone_pings")]
356    pub everyone_pings: bool,
357    /// Whether the COMMUNITY this chat belongs to is silenced, as opposed to the
358    /// chat itself. A surface standing for the whole space reads this one.
359    #[serde(default)]
360    pub community_muted: bool,
361    #[serde(default)]
362    pub wallpaper_path: String,
363    #[serde(default)]
364    pub wallpaper_ts: u64,
365    #[serde(default)]
366    pub wallpaper_blur: u8,
367    #[serde(default = "default_wallpaper_dim")]
368    pub wallpaper_dim: u8,
369    #[serde(default)]
370    pub wallpaper_url: String,
371    #[serde(default)]
372    pub wallpaper_uploader: String,
373    /// See [`Chat::replied`].
374    #[serde(default)]
375    pub replied: bool,
376}
377
378fn default_wallpaper_dim() -> u8 { 50 }
379fn default_everyone_pings() -> bool { true }
380
381impl SerializableChat {
382    pub fn to_chat(self, interner: &mut NpubInterner) -> Chat {
383        let handles: Vec<u16> = self.participants.iter().map(|p| interner.intern(p)).collect();
384        let mut chat = Chat::new(self.id, self.chat_type, handles);
385        chat.last_read = if self.last_read.is_empty() { [0u8; 32] } else { encode_message_id(&self.last_read) };
386        chat.unread_from = if self.unread_from.is_empty() { [0u8; 32] } else { encode_message_id(&self.unread_from) };
387        chat.created_at = self.created_at;
388        chat.metadata = self.metadata;
389        chat.muted = self.muted;
390        chat.wallpaper_path = self.wallpaper_path;
391        chat.wallpaper_ts = self.wallpaper_ts;
392        chat.wallpaper_blur = self.wallpaper_blur;
393        chat.wallpaper_dim = self.wallpaper_dim;
394        chat.wallpaper_url = self.wallpaper_url;
395        chat.wallpaper_uploader = self.wallpaper_uploader;
396        chat.replied = self.replied;
397        for msg in self.messages {
398            chat.add_message(msg, interner);
399        }
400        chat
401    }
402}
403
404// ============================================================================
405// Supporting Types
406// ============================================================================
407
408#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
409pub enum ChatType {
410    DirectMessage,
411    /// A Community channel (GROUP_PROTOCOL.md). The chat `id`
412    /// is the channel's stable random id.
413    Community,
414}
415
416impl ChatType {
417    // Discriminant 1 was the removed MlsGroup variant; Community keeps 2 for
418    // on-disk compatibility. Legacy chat_type=1 rows are dropped at the DB load layer.
419    pub fn to_i32(&self) -> i32 {
420        match self {
421            ChatType::DirectMessage => 0,
422            ChatType::Community => 2,
423        }
424    }
425    pub fn from_i32(value: i32) -> Self {
426        match value {
427            2 => ChatType::Community,
428            _ => ChatType::DirectMessage,
429        }
430    }
431}
432
433/// A chat row's display metadata: string → string, which is all the frontend and
434/// the database ever see (`{"custom_fields":{..}}`, keys in byte order).
435///
436/// A Community channel's keys are held typed, the community-wide ones in one
437/// header its sibling rows share. Any other key, and a known key whose value the
438/// typed form could not give back byte for byte, stays a plain pair.
439#[derive(Clone, Debug, PartialEq, Default)]
440pub struct ChatMetadata {
441    community: Option<Box<CommunityStamp>>,
442    /// Sorted by key; never a key whose typed slot is set.
443    other: Vec<(Box<str>, Box<str>)>,
444}
445
446#[derive(Clone, Debug, PartialEq, Default)]
447struct CommunityStamp {
448    header: Arc<CommunityHeader>,
449    channel_name: Option<Box<str>>,
450}
451
452/// The keys every channel row of one community carries alike.
453#[derive(Clone, Debug, PartialEq, Eq, Default)]
454pub(crate) struct CommunityHeader {
455    community_id: Option<Box<str>>,
456    name: Option<Box<str>>,
457    description: Option<Box<str>>,
458    primary_channel: Option<Box<str>>,
459    owner_npub: Option<Box<str>>,
460    created_at: Option<u64>,
461    is_owner: Option<bool>,
462    dissolved: Option<bool>,
463    /// Stored as `"1"`.
464    icon: bool,
465}
466
467/// What a channel registration stamps onto its row.
468pub(crate) struct CommunityRegistration<'a> {
469    pub community_id: &'a str,
470    pub name: &'a str,
471    pub description: &'a str,
472    pub primary_channel: &'a str,
473    pub owner_npub: Option<&'a str>,
474    /// `None` keeps whatever the row already holds.
475    pub created_at_ms: Option<u64>,
476    pub is_owner: bool,
477    pub dissolved: bool,
478    pub has_icon: bool,
479}
480
481/// The typed keys, in byte order of their names.
482#[derive(Clone, Copy, PartialEq, Eq)]
483enum Field {
484    ChannelName,
485    CommunityId,
486    CreatedAt,
487    Description,
488    Dissolved,
489    Icon,
490    IsOwner,
491    Name,
492    OwnerNpub,
493    PrimaryChannel,
494}
495
496impl Field {
497    const ALL: [Field; 10] = [
498        Field::ChannelName,
499        Field::CommunityId,
500        Field::CreatedAt,
501        Field::Description,
502        Field::Dissolved,
503        Field::Icon,
504        Field::IsOwner,
505        Field::Name,
506        Field::OwnerNpub,
507        Field::PrimaryChannel,
508    ];
509
510    fn key(self) -> &'static str {
511        match self {
512            Field::ChannelName => "channel_name",
513            Field::CommunityId => "community_id",
514            Field::CreatedAt => "created_at",
515            Field::Description => "description",
516            Field::Dissolved => "dissolved",
517            Field::Icon => "icon",
518            Field::IsOwner => "is_owner",
519            Field::Name => "name",
520            Field::OwnerNpub => "owner_npub",
521            Field::PrimaryChannel => "primary_channel",
522        }
523    }
524
525    fn parse(key: &str) -> Option<Field> {
526        Field::ALL.into_iter().find(|f| f.key() == key)
527    }
528}
529
530fn bool_text(b: bool) -> &'static str {
531    if b { "true" } else { "false" }
532}
533
534fn parse_bool_text(v: &str) -> Option<bool> {
535    match v {
536        "true" => Some(true),
537        "false" => Some(false),
538        _ => None,
539    }
540}
541
542/// A number only when printing it gives `v` back (no sign, no leading zero).
543fn parse_ms_text(v: &str) -> Option<u64> {
544    v.parse::<u64>().ok().filter(|n| n.to_string() == v)
545}
546
547impl CommunityHeader {
548    fn text(&self, f: Field) -> Option<&Option<Box<str>>> {
549        match f {
550            Field::CommunityId => Some(&self.community_id),
551            Field::Name => Some(&self.name),
552            Field::Description => Some(&self.description),
553            Field::PrimaryChannel => Some(&self.primary_channel),
554            Field::OwnerNpub => Some(&self.owner_npub),
555            _ => None,
556        }
557    }
558
559    fn text_mut(&mut self, f: Field) -> Option<&mut Option<Box<str>>> {
560        match f {
561            Field::CommunityId => Some(&mut self.community_id),
562            Field::Name => Some(&mut self.name),
563            Field::Description => Some(&mut self.description),
564            Field::PrimaryChannel => Some(&mut self.primary_channel),
565            Field::OwnerNpub => Some(&mut self.owner_npub),
566            _ => None,
567        }
568    }
569
570    fn heap_size(&self) -> usize {
571        [&self.community_id, &self.name, &self.description, &self.primary_channel, &self.owner_npub]
572            .into_iter()
573            .map(|s| s.as_deref().map_or(0, str::len))
574            .sum()
575    }
576}
577
578impl ChatMetadata {
579    pub fn new() -> Self { Self::default() }
580
581    pub fn set_name(&mut self, name: String) { self.insert("name", name); }
582    pub fn get_name(&self) -> Option<&str> { self.header()?.name.as_deref() }
583    pub fn set_member_count(&mut self, count: usize) { self.insert("member_count", count.to_string()); }
584    pub fn get_member_count(&self) -> Option<usize> { self.get("member_count").and_then(|s| s.parse().ok()) }
585
586    /// The owning community's id (hex) on a Community channel row.
587    pub fn community_id(&self) -> Option<&str> { self.header()?.community_id.as_deref() }
588    /// The community's primary channel id (hex), the one row the list renders.
589    pub fn primary_channel(&self) -> Option<&str> { self.header()?.primary_channel.as_deref() }
590    /// Whether the owner dissolved this row's community.
591    pub fn is_dissolved(&self) -> bool { self.header().is_some_and(|h| h.dissolved == Some(true)) }
592
593    fn header(&self) -> Option<&CommunityHeader> { self.community.as_deref().map(|s| &*s.header) }
594
595    fn typed(&self, f: Field) -> Option<Cow<'_, str>> {
596        let stamp = self.community.as_deref()?;
597        let h = &*stamp.header;
598        if let Some(text) = h.text(f) {
599            return text.as_deref().map(Cow::Borrowed);
600        }
601        match f {
602            Field::ChannelName => stamp.channel_name.as_deref().map(Cow::Borrowed),
603            Field::CreatedAt => h.created_at.map(|n| Cow::Owned(n.to_string())),
604            Field::IsOwner => h.is_owner.map(|b| Cow::Borrowed(bool_text(b))),
605            Field::Dissolved => h.dissolved.map(|b| Cow::Borrowed(bool_text(b))),
606            Field::Icon => h.icon.then_some(Cow::Borrowed("1")),
607            _ => None,
608        }
609    }
610
611    fn typed_present(&self, f: Field) -> bool {
612        let Some(stamp) = self.community.as_deref() else { return false };
613        let h = &*stamp.header;
614        match h.text(f) {
615            Some(text) => text.is_some(),
616            None => match f {
617                Field::ChannelName => stamp.channel_name.is_some(),
618                Field::CreatedAt => h.created_at.is_some(),
619                Field::IsOwner => h.is_owner.is_some(),
620                Field::Dissolved => h.dissolved.is_some(),
621                Field::Icon => h.icon,
622                _ => false,
623            },
624        }
625    }
626
627    /// Hold `value` in `f`'s typed slot; `false` when the slot can't give it back exactly.
628    fn set_typed(&mut self, f: Field, value: &str) -> bool {
629        let (mut ms, mut flag) = (None, None);
630        let fits = match f {
631            Field::CreatedAt => {
632                ms = parse_ms_text(value);
633                ms.is_some()
634            }
635            Field::IsOwner | Field::Dissolved => {
636                flag = parse_bool_text(value);
637                flag.is_some()
638            }
639            Field::Icon => value == "1",
640            _ => true,
641        };
642        if !fits {
643            return false;
644        }
645        let stamp = self.community.get_or_insert_with(Default::default);
646        if f == Field::ChannelName {
647            stamp.channel_name = Some(value.into());
648            return true;
649        }
650        let h = Arc::make_mut(&mut stamp.header);
651        match h.text_mut(f) {
652            Some(slot) => *slot = Some(value.into()),
653            None => match f {
654                Field::CreatedAt => h.created_at = ms,
655                Field::IsOwner => h.is_owner = flag,
656                Field::Dissolved => h.dissolved = flag,
657                Field::Icon => h.icon = true,
658                _ => {}
659            },
660        }
661        true
662    }
663
664    fn clear_typed(&mut self, f: Field) {
665        if !self.typed_present(f) {
666            return;
667        }
668        let Some(stamp) = self.community.as_deref_mut() else { return };
669        if f == Field::ChannelName {
670            stamp.channel_name = None;
671        } else {
672            let h = Arc::make_mut(&mut stamp.header);
673            match h.text_mut(f) {
674                Some(slot) => *slot = None,
675                None => match f {
676                    Field::CreatedAt => h.created_at = None,
677                    Field::IsOwner => h.is_owner = None,
678                    Field::Dissolved => h.dissolved = None,
679                    Field::Icon => h.icon = false,
680                    _ => {}
681                },
682            }
683        }
684        if stamp.channel_name.is_none() && *stamp.header == CommunityHeader::default() {
685            self.community = None;
686        }
687    }
688
689    fn other_index(&self, key: &str) -> Result<usize, usize> {
690        self.other.binary_search_by(|(k, _)| (**k).cmp(key))
691    }
692
693    /// One field's value, exactly as it serializes.
694    pub fn get(&self, key: &str) -> Option<Cow<'_, str>> {
695        if let Some(v) = Field::parse(key).and_then(|f| self.typed(f)) {
696            return Some(v);
697        }
698        self.other_index(key).ok().map(|i| Cow::Borrowed(&*self.other[i].1))
699    }
700
701    pub fn contains_key(&self, key: &str) -> bool {
702        Field::parse(key).is_some_and(|f| self.typed_present(f)) || self.other_index(key).is_ok()
703    }
704
705    pub fn insert(&mut self, key: &str, value: String) {
706        if let Some(f) = Field::parse(key) {
707            if self.set_typed(f, &value) {
708                self.remove_other(key);
709                return;
710            }
711            self.clear_typed(f);
712        }
713        match self.other_index(key) {
714            Ok(i) => self.other[i].1 = value.into_boxed_str(),
715            Err(i) => self.other.insert(i, (key.into(), value.into_boxed_str())),
716        }
717    }
718
719    pub fn remove(&mut self, key: &str) {
720        if let Some(f) = Field::parse(key) {
721            self.clear_typed(f);
722        }
723        self.remove_other(key);
724    }
725
726    fn remove_other(&mut self, key: &str) {
727        if let Ok(i) = self.other_index(key) {
728            self.other.remove(i);
729        }
730    }
731
732    /// Every field in byte order of its key, as it serializes.
733    pub fn entries(&self) -> Vec<(&str, Cow<'_, str>)> {
734        let mut out: Vec<(&str, Cow<'_, str>)> = Vec::with_capacity(Field::ALL.len() + self.other.len());
735        out.extend(Field::ALL.into_iter().filter_map(|f| self.typed(f).map(|v| (f.key(), v))));
736        out.extend(self.other.iter().map(|(k, v)| (&**k, Cow::Borrowed(&**v))));
737        // Both halves are sorted and share no key, so only an interleave is left to settle.
738        out.sort_unstable_by(|a, b| a.0.cmp(b.0));
739        out
740    }
741
742    pub fn from_map(map: HashMap<String, String>) -> Self {
743        let mut meta = Self::default();
744        for (k, v) in map {
745            meta.insert(&k, v);
746        }
747        meta
748    }
749
750    /// This row's header under `reg`, before any sharing.
751    pub(crate) fn registration_header(&self, reg: &CommunityRegistration<'_>) -> CommunityHeader {
752        CommunityHeader {
753            community_id: Some(reg.community_id.into()),
754            name: Some(reg.name.into()),
755            description: Some(reg.description.into()),
756            primary_channel: Some(reg.primary_channel.into()),
757            owner_npub: reg.owner_npub.map(Into::into),
758            created_at: reg.created_at_ms.or_else(|| self.header().and_then(|h| h.created_at)),
759            is_owner: Some(reg.is_owner),
760            dissolved: Some(reg.dissolved),
761            icon: reg.has_icon,
762        }
763    }
764
765    /// The header this row shares with its community's other rows.
766    pub(crate) fn community_header(&self) -> Option<&Arc<CommunityHeader>> {
767        self.community.as_deref().map(|s| &s.header)
768    }
769
770    /// Stamp a registration: every key it names now answers from `header`, except a
771    /// `created_at` the registration left to the row.
772    pub(crate) fn stamp_community(&mut self, header: Arc<CommunityHeader>, channel_name: &str, created_at_given: bool) {
773        self.community = Some(Box::new(CommunityStamp { header, channel_name: Some(channel_name.into()) }));
774        self.other.retain(|(k, _)| match Field::parse(k) {
775            Some(Field::CreatedAt) => !created_at_given,
776            Some(_) => false,
777            None => true,
778        });
779    }
780
781    /// Bytes held on the heap for this row; a shared header counts its share.
782    pub fn heap_size(&self) -> usize {
783        let other = self.other.capacity() * std::mem::size_of::<(Box<str>, Box<str>)>()
784            + self.other.iter().map(|(k, v)| k.len() + v.len()).sum::<usize>();
785        let stamp = self.community.as_deref().map_or(0, |s| {
786            std::mem::size_of::<CommunityStamp>()
787                + s.channel_name.as_deref().map_or(0, str::len)
788                + (std::mem::size_of::<CommunityHeader>() + s.header.heap_size()) / Arc::strong_count(&s.header)
789        });
790        other + stamp
791    }
792}
793
794impl Serialize for ChatMetadata {
795    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
796        use serde::ser::{SerializeMap, SerializeStruct};
797        struct Fields<'a>(&'a ChatMetadata);
798        impl Serialize for Fields<'_> {
799            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
800                let entries = self.0.entries();
801                let mut map = serializer.serialize_map(Some(entries.len()))?;
802                for (k, v) in &entries {
803                    map.serialize_entry(k, v.as_ref())?;
804                }
805                map.end()
806            }
807        }
808        let mut s = serializer.serialize_struct("ChatMetadata", 1)?;
809        s.serialize_field("custom_fields", &Fields(self))?;
810        s.end()
811    }
812}
813
814impl<'de> Deserialize<'de> for ChatMetadata {
815    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
816        #[derive(Deserialize)]
817        #[serde(rename = "ChatMetadata")]
818        struct Wire {
819            custom_fields: HashMap<String, String>,
820        }
821        Ok(Self::from_map(Wire::deserialize(deserializer)?.custom_fields))
822    }
823}
824
825#[cfg(test)]
826mod tests {
827    use super::*;
828    use crate::types::Message;
829    use crate::compact::NpubInterner;
830    use crate::simd::hex::bytes_to_hex_32;
831
832    /// The single discriminator behind three user-visible behaviours: whether a channel
833    /// gets a chat-list row, whether its unread badges the OS, and whether it rings a
834    /// notification. Every channel is registered and synced; only the primary surfaces.
835    #[test]
836    fn only_the_primary_channel_of_a_community_is_surfaced() {
837        let mut interner = NpubInterner::new();
838        let primary_id = make_hex_id(0x21);
839        let sibling_id = make_hex_id(0x22);
840
841        let mut stamp = |id: &str, community: bool, primary: Option<&str>| {
842            let mut chat = Chat::new_community_channel(id.to_string(), Vec::new(), &mut interner);
843            if community {
844                chat.metadata.insert("community_id", make_hex_id(0x99));
845            }
846            if let Some(p) = primary {
847                chat.metadata.insert("primary_channel", p.to_string());
848            }
849            chat
850        };
851
852        // A bare persistence anchor (auto-created by the message persist) has no community
853        // metadata at all and has never been surfaced.
854        assert!(!stamp(&sibling_id, false, None).is_surfaced_community_channel());
855
856        // The community's primary row: the one row the list renders.
857        assert!(stamp(&primary_id, true, Some(&primary_id)).is_surfaced_community_channel());
858
859        // A sibling channel: registered, synced, addressable — but no row, so its unread
860        // must not badge and its messages must not ring.
861        assert!(!stamp(&sibling_id, true, Some(&primary_id)).is_surfaced_community_channel());
862
863        // Written before the stamp existed: assumed surfaced, so a community can't silently
864        // vanish from the list (and it re-stamps on the next registration). Matches the chat
865        // list's own fallback — the two must not disagree.
866        assert!(stamp(&primary_id, true, None).is_surfaced_community_channel());
867    }
868
869    // ========================================================================
870    // Helpers
871    // ========================================================================
872
873    /// Create a deterministic 64-char hex ID from a u8 seed.
874    /// First byte is always >= 0x10 to avoid the pending ID marker (0x01).
875    fn make_hex_id(seed: u8) -> String {
876        let mut bytes = [seed; 32];
877        bytes[0] = seed.wrapping_add(0x10) | 0x10; // never 0x00 or 0x01
878        bytes[1] = seed.wrapping_mul(37);
879        bytes_to_hex_32(&bytes)
880    }
881
882    /// Build a test Message with the given parameters.
883    fn make_message(id_seed: u8, content: &str, timestamp_ms: u64, mine: bool) -> Message {
884        Message {
885            id: make_hex_id(id_seed),
886            content: content.to_string(),
887            at: timestamp_ms,
888            mine,
889            ..Default::default()
890        }
891    }
892
893    // ========================================================================
894    // Chat Construction
895    // ========================================================================
896
897    #[test]
898    fn a_dm_is_a_request_until_answered_or_accepted() {
899        let mut interner = NpubInterner::new();
900        let mut chat = Chat::new_dm("npub1stranger".to_string(), &mut interner);
901        assert!(!chat.is_request(), "nothing in it yet");
902        chat.add_message(make_message(1, "hey", 1700000000000, false), &mut interner);
903        assert!(chat.is_request(), "only their message");
904
905        let mut accepted = chat.clone();
906        accepted.metadata.insert(ACCEPTED_KEY, "true".into());
907        assert!(!accepted.is_request(), "accepted without a reply");
908
909        chat.add_message(make_message(2, "hi back", 1700000001000, true), &mut interner);
910        assert!(!chat.is_request(), "answered");
911
912        let mut channel = Chat::new_community_channel("ab".repeat(32), vec![], &mut interner);
913        channel.add_message(make_message(3, "gm", 1700000002000, false), &mut interner);
914        assert!(!channel.is_request(), "a channel is never a request");
915        assert!(!channel.is_unanswered(), "nor waits on an answer");
916
917        let empty = Chat::new_dm("npub1wallpaperfirst".to_string(), &mut interner);
918        assert!(empty.is_unanswered() && !empty.is_request(), "nothing in it yet, still unanswered");
919    }
920
921    #[test]
922    fn new_dm_creates_correct_type() {
923        let mut interner = NpubInterner::new();
924        let chat = Chat::new_dm("npub1alice".to_string(), &mut interner);
925
926        assert_eq!(chat.id, "npub1alice", "DM chat id should be the peer's npub");
927        assert_eq!(chat.chat_type, ChatType::DirectMessage, "should be DirectMessage type");
928        assert_eq!(chat.participants.len(), 1, "DM should have one participant");
929        assert!(chat.is_empty(), "new chat should have no messages");
930        assert!(!chat.muted, "new chat should not be muted");
931        assert_eq!(chat.last_read, [0u8; 32], "last_read should be zeroed");
932    }
933
934    #[test]
935    fn new_community_channel_with_participants() {
936        let mut interner = NpubInterner::new();
937        let participants = vec![
938            "npub1alice".to_string(),
939            "npub1bob".to_string(),
940            "npub1charlie".to_string(),
941        ];
942        let chat = Chat::new_community_channel("grp_abc".to_string(), participants, &mut interner);
943
944        assert_eq!(chat.id, "grp_abc", "group chat id should match");
945        assert_eq!(chat.chat_type, ChatType::Community, "should be Community type");
946        assert_eq!(chat.participants.len(), 3, "should have 3 participants");
947        assert!(chat.is_community(), "is_community() should return true");
948    }
949
950    #[test]
951    fn new_chat_has_creation_timestamp() {
952        let mut interner = NpubInterner::new();
953        let chat = Chat::new_dm("npub1peer".to_string(), &mut interner);
954
955        // created_at should be recent (within last 5 seconds)
956        let now = web_time::SystemTime::now()
957            .duration_since(web_time::UNIX_EPOCH).unwrap().as_secs();
958        assert!(
959            chat.created_at >= now - 5 && chat.created_at <= now + 1,
960            "created_at ({}) should be close to now ({})",
961            chat.created_at, now
962        );
963    }
964
965    // ========================================================================
966    // Message Operations
967    // ========================================================================
968
969    #[test]
970    fn add_message_and_get_message_roundtrip() {
971        let mut interner = NpubInterner::new();
972        let mut chat = Chat::new_dm("npub1peer".to_string(), &mut interner);
973
974        let msg = make_message(1, "hello world", 1700000000000, false);
975        let msg_id = msg.id.clone();
976
977        let added = chat.add_message(msg, &mut interner);
978        assert!(added, "message should be added successfully");
979
980        let retrieved = chat.get_message(&msg_id, &interner)
981            .expect("message should be retrievable");
982        assert_eq!(retrieved.content, "hello world", "content should roundtrip");
983        assert_eq!(retrieved.id, msg_id, "id should roundtrip");
984    }
985
986    #[test]
987    fn add_message_dedup() {
988        let mut interner = NpubInterner::new();
989        let mut chat = Chat::new_dm("npub1peer".to_string(), &mut interner);
990
991        let msg1 = make_message(1, "first", 1700000000000, false);
992        let msg2 = make_message(1, "duplicate id", 1700000001000, false);
993
994        assert!(chat.add_message(msg1, &mut interner), "first add should succeed");
995        assert!(!chat.add_message(msg2, &mut interner), "duplicate ID should be rejected");
996        assert_eq!(chat.message_count(), 1, "should have only one message");
997    }
998
999    #[test]
1000    fn message_count_and_is_empty() {
1001        let mut interner = NpubInterner::new();
1002        let mut chat = Chat::new_dm("npub1peer".to_string(), &mut interner);
1003
1004        assert!(chat.is_empty(), "new chat should be empty");
1005        assert_eq!(chat.message_count(), 0, "new chat should have 0 messages");
1006
1007        chat.add_message(make_message(1, "a", 1700000000000, false), &mut interner);
1008        assert!(!chat.is_empty(), "chat with message should not be empty");
1009        assert_eq!(chat.message_count(), 1, "should have 1 message");
1010
1011        chat.add_message(make_message(2, "b", 1700000001000, false), &mut interner);
1012        assert_eq!(chat.message_count(), 2, "should have 2 messages");
1013    }
1014
1015    #[test]
1016    fn has_message_check() {
1017        let mut interner = NpubInterner::new();
1018        let mut chat = Chat::new_dm("npub1peer".to_string(), &mut interner);
1019
1020        let msg = make_message(1, "test", 1700000000000, false);
1021        let msg_id = msg.id.clone();
1022        chat.add_message(msg, &mut interner);
1023
1024        assert!(chat.has_message(&msg_id), "added message should be found");
1025        assert!(!chat.has_message(&make_hex_id(99)), "unknown id should not be found");
1026    }
1027
1028    #[test]
1029    fn get_all_messages_returns_all() {
1030        let mut interner = NpubInterner::new();
1031        let mut chat = Chat::new_dm("npub1peer".to_string(), &mut interner);
1032
1033        for i in 0..5u8 {
1034            chat.add_message(
1035                make_message(i, &format!("msg {}", i), 1700000000000 + i as u64 * 1000, false),
1036                &mut interner,
1037            );
1038        }
1039
1040        let all = chat.get_all_messages(&interner);
1041        assert_eq!(all.len(), 5, "should return all 5 messages");
1042    }
1043
1044    #[test]
1045    fn get_last_messages_returns_tail() {
1046        let mut interner = NpubInterner::new();
1047        let mut chat = Chat::new_dm("npub1peer".to_string(), &mut interner);
1048
1049        for i in 0..10u8 {
1050            chat.add_message(
1051                make_message(i, &format!("msg {}", i), 1700000000000 + i as u64 * 1000, false),
1052                &mut interner,
1053            );
1054        }
1055
1056        let last3 = chat.get_last_messages(3, &interner);
1057        assert_eq!(last3.len(), 3, "should return exactly 3 messages");
1058        assert_eq!(last3[0].content, "msg 7", "first of last 3 should be msg 7");
1059        assert_eq!(last3[2].content, "msg 9", "last should be msg 9");
1060    }
1061
1062    #[test]
1063    fn last_message_time_tracks_newest() {
1064        let mut interner = NpubInterner::new();
1065        let mut chat = Chat::new_dm("npub1peer".to_string(), &mut interner);
1066
1067        assert!(chat.last_message_time().is_none(), "empty chat should have no last time");
1068
1069        chat.add_message(make_message(1, "a", 1700000001000, false), &mut interner);
1070        let t1 = chat.last_message_time().expect("should have a timestamp");
1071
1072        chat.add_message(make_message(2, "b", 1700000005000, false), &mut interner);
1073        let t2 = chat.last_message_time().expect("should have a timestamp");
1074
1075        assert!(t2 > t1, "last_message_time should increase with newer messages");
1076    }
1077
1078    // ========================================================================
1079    // set_as_read
1080    // ========================================================================
1081
1082    #[test]
1083    fn set_as_read_marks_last_non_mine() {
1084        let mut interner = NpubInterner::new();
1085        let mut chat = Chat::new_dm("npub1peer".to_string(), &mut interner);
1086
1087        let msg_theirs = make_message(1, "from them", 1700000001000, false);
1088        let msg_mine = make_message(2, "from me", 1700000002000, true);
1089        let msg_theirs2 = make_message(3, "from them again", 1700000003000, false);
1090        let last_their_id = msg_theirs2.id.clone();
1091
1092        chat.add_message(msg_theirs, &mut interner);
1093        chat.add_message(msg_mine, &mut interner);
1094        chat.add_message(msg_theirs2, &mut interner);
1095
1096        let marked = chat.set_as_read();
1097        assert!(marked, "set_as_read should succeed when there are non-mine messages");
1098
1099        let expected_bytes = crate::compact::encode_message_id(&last_their_id);
1100        assert_eq!(
1101            chat.last_read, expected_bytes,
1102            "last_read should point to the last non-mine message"
1103        );
1104    }
1105
1106    #[test]
1107    fn set_as_read_all_mine_returns_false() {
1108        let mut interner = NpubInterner::new();
1109        let mut chat = Chat::new_dm("npub1peer".to_string(), &mut interner);
1110
1111        chat.add_message(make_message(1, "mine 1", 1700000001000, true), &mut interner);
1112        chat.add_message(make_message(2, "mine 2", 1700000002000, true), &mut interner);
1113
1114        let marked = chat.set_as_read();
1115        assert!(!marked, "set_as_read should return false when all messages are mine");
1116        assert_eq!(chat.last_read, [0u8; 32], "last_read should remain zeroed");
1117    }
1118
1119    // ========================================================================
1120    // Serialization Roundtrip
1121    // ========================================================================
1122
1123    #[test]
1124    fn to_serializable_and_back_via_to_chat() {
1125        let mut interner = NpubInterner::new();
1126        let participants = vec!["npub1alice".to_string(), "npub1bob".to_string()];
1127        let mut chat = Chat::new_community_channel("grp_test".to_string(), participants.clone(), &mut interner);
1128
1129        chat.metadata.set_name("Test Group".to_string());
1130        chat.muted = true;
1131
1132        // Add messages
1133        chat.add_message(make_message(1, "hello", 1700000001000, false), &mut interner);
1134        chat.add_message(make_message(2, "world", 1700000002000, true), &mut interner);
1135
1136        // Set last_read
1137        chat.set_as_read();
1138
1139        // Serialize to SerializableChat
1140        let serializable = chat.to_serializable(&interner);
1141        assert_eq!(serializable.id, "grp_test", "serialized id should match");
1142        assert_eq!(serializable.chat_type, ChatType::Community, "serialized type should match");
1143        assert_eq!(serializable.participants.len(), 2, "should have 2 participants");
1144        assert_eq!(serializable.messages.len(), 2, "should have 2 messages");
1145        assert!(serializable.muted, "muted should be preserved");
1146        assert_eq!(
1147            serializable.metadata.get_name(),
1148            Some("Test Group"),
1149            "metadata name should be preserved"
1150        );
1151
1152        // Convert back to Chat
1153        let mut interner2 = NpubInterner::new();
1154        let restored = serializable.to_chat(&mut interner2);
1155
1156        assert_eq!(restored.id, "grp_test", "restored id should match");
1157        assert_eq!(restored.chat_type, ChatType::Community, "restored type should match");
1158        assert_eq!(restored.participants.len(), 2, "restored participants count should match");
1159        assert_eq!(restored.message_count(), 2, "restored message count should match");
1160        assert!(restored.muted, "restored muted should be true");
1161        assert_ne!(restored.last_read, [0u8; 32], "restored last_read should be non-zero");
1162    }
1163
1164    #[test]
1165    fn to_serializable_with_last_n() {
1166        let mut interner = NpubInterner::new();
1167        let mut chat = Chat::new_dm("npub1peer".to_string(), &mut interner);
1168
1169        for i in 0..10u8 {
1170            chat.add_message(
1171                make_message(i, &format!("msg {}", i), 1700000000000 + i as u64 * 1000, false),
1172                &mut interner,
1173            );
1174        }
1175
1176        let serialized = chat.to_serializable_with_last_n(3, &interner);
1177        assert_eq!(serialized.messages.len(), 3, "should only include last 3 messages");
1178    }
1179
1180    // ========================================================================
1181    // Participants
1182    // ========================================================================
1183
1184    #[test]
1185    fn has_participant_check() {
1186        let mut interner = NpubInterner::new();
1187        let chat = Chat::new_community_channel(
1188            "grp1".to_string(),
1189            vec!["npub1alice".to_string(), "npub1bob".to_string()],
1190            &mut interner,
1191        );
1192
1193        assert!(
1194            chat.has_participant("npub1alice", &interner),
1195            "alice should be a participant"
1196        );
1197        assert!(
1198            chat.has_participant("npub1bob", &interner),
1199            "bob should be a participant"
1200        );
1201        assert!(
1202            !chat.has_participant("npub1charlie", &interner),
1203            "charlie should not be a participant"
1204        );
1205    }
1206
1207    #[test]
1208    fn is_dm_with_check() {
1209        let mut interner = NpubInterner::new();
1210        let chat = Chat::new_dm("npub1alice".to_string(), &mut interner);
1211
1212        assert!(
1213            chat.is_dm_with("npub1alice", &interner),
1214            "should be a DM with alice"
1215        );
1216        assert!(
1217            !chat.is_dm_with("npub1bob", &interner),
1218            "should not be a DM with bob"
1219        );
1220    }
1221
1222    #[test]
1223    fn is_dm_with_returns_false_for_group() {
1224        let mut interner = NpubInterner::new();
1225        let chat = Chat::new_community_channel(
1226            "grp1".to_string(),
1227            vec!["npub1alice".to_string()],
1228            &mut interner,
1229        );
1230
1231        assert!(
1232            !chat.is_dm_with("npub1alice", &interner),
1233            "community channel should not match is_dm_with even if participant matches"
1234        );
1235    }
1236
1237    #[test]
1238    fn get_other_participant_dm() {
1239        let mut interner = NpubInterner::new();
1240        // In a DM, the participant list typically has the other person
1241        let chat = Chat::new_dm("npub1bob".to_string(), &mut interner);
1242
1243        let other = chat.get_other_participant("npub1alice", &interner);
1244        assert_eq!(
1245            other, Some("npub1bob".to_string()),
1246            "should return bob as the other participant"
1247        );
1248    }
1249
1250    #[test]
1251    fn get_other_participant_returns_none_for_group() {
1252        let mut interner = NpubInterner::new();
1253        let chat = Chat::new_community_channel(
1254            "grp1".to_string(),
1255            vec!["npub1alice".to_string(), "npub1bob".to_string()],
1256            &mut interner,
1257        );
1258
1259        assert!(
1260            chat.get_other_participant("npub1alice", &interner).is_none(),
1261            "community channel should return None for get_other_participant"
1262        );
1263    }
1264
1265    // ========================================================================
1266    // Typing Participants
1267    // ========================================================================
1268
1269    #[test]
1270    fn typing_participants_with_expiry() {
1271        let mut interner = NpubInterner::new();
1272        let mut chat = Chat::new_dm("npub1peer".to_string(), &mut interner);
1273
1274        let now = web_time::SystemTime::now()
1275            .duration_since(web_time::UNIX_EPOCH).unwrap().as_secs();
1276
1277        // One active, one expired
1278        let active_handle = interner.intern("npub1active");
1279        let expired_handle = interner.intern("npub1expired");
1280
1281        chat.update_typing_participant(active_handle, now + 300);
1282        chat.update_typing_participant(expired_handle, now - 10);
1283
1284        let active = chat.get_active_typers(&interner);
1285        assert_eq!(active.len(), 1, "only the active typer should be returned");
1286        assert_eq!(active[0], "npub1active", "active typer should be npub1active");
1287    }
1288
1289    #[test]
1290    fn update_typing_participant_refreshes() {
1291        let mut interner = NpubInterner::new();
1292        let mut chat = Chat::new_dm("npub1peer".to_string(), &mut interner);
1293
1294        let now = web_time::SystemTime::now()
1295            .duration_since(web_time::UNIX_EPOCH).unwrap().as_secs();
1296
1297        let handle = interner.intern("npub1typer");
1298        chat.update_typing_participant(handle, now + 100);
1299        chat.update_typing_participant(handle, now + 500);
1300
1301        // Should still be one entry, not duplicated
1302        let active = chat.get_active_typers(&interner);
1303        assert_eq!(active.len(), 1, "refreshed typer should not duplicate");
1304    }
1305
1306    #[test]
1307    fn typing_participants_empty_initially() {
1308        let interner = NpubInterner::new();
1309        let chat = Chat::new("testchat".to_string(), ChatType::DirectMessage, vec![]);
1310
1311        let active = chat.get_active_typers(&interner);
1312        assert!(active.is_empty(), "new chat should have no typers");
1313    }
1314
1315    // ========================================================================
1316    // ChatType
1317    // ========================================================================
1318
1319    #[test]
1320    fn chat_type_i32_roundtrip() {
1321        assert_eq!(ChatType::from_i32(ChatType::DirectMessage.to_i32()), ChatType::DirectMessage);
1322        assert_eq!(ChatType::from_i32(ChatType::Community.to_i32()), ChatType::Community);
1323        assert_eq!(
1324            ChatType::from_i32(999), ChatType::DirectMessage,
1325            "unknown i32 should default to DirectMessage"
1326        );
1327    }
1328
1329    // ========================================================================
1330    // ChatMetadata
1331    // ========================================================================
1332
1333    #[test]
1334    fn chat_metadata_name_and_member_count() {
1335        let mut meta = ChatMetadata::new();
1336
1337        assert!(meta.get_name().is_none(), "new metadata should have no name");
1338        assert!(meta.get_member_count().is_none(), "new metadata should have no member count");
1339
1340        meta.set_name("My Group".to_string());
1341        meta.set_member_count(42);
1342
1343        assert_eq!(meta.get_name(), Some("My Group"), "name should be set");
1344        assert_eq!(meta.get_member_count(), Some(42), "member count should be set");
1345    }
1346
1347    /// The JSON shape the frontend and DB read: a plain string map. A
1348    /// `BTreeMap`, so its keys come out in the byte order the typed form promises.
1349    #[derive(Serialize, Deserialize)]
1350    struct PlainMetadata {
1351        custom_fields: std::collections::BTreeMap<String, String>,
1352    }
1353
1354    fn plain(pairs: &[(&str, &str)]) -> std::collections::BTreeMap<String, String> {
1355        pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
1356    }
1357
1358    fn typed(pairs: &[(&str, &str)]) -> ChatMetadata {
1359        ChatMetadata::from_map(pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect())
1360    }
1361
1362    fn community_row(cid: &str, primary: &str) -> Vec<(&'static str, String)> {
1363        vec![
1364            ("name", "Rust Club".into()),
1365            ("channel_name", "general".into()),
1366            ("primary_channel", primary.into()),
1367            ("description", "".into()),
1368            ("community_id", cid.into()),
1369            ("is_owner", "false".into()),
1370            ("dissolved", "true".into()),
1371            ("created_at", "1712345678901".into()),
1372            ("owner_npub", "npub1owner".into()),
1373            ("icon", "1".into()),
1374            ("proto_version", "2".into()),
1375            ("member_count", "12".into()),
1376        ]
1377    }
1378
1379    #[test]
1380    fn custom_fields_serialize_byte_for_byte_as_a_plain_map() {
1381        let (cid, primary) = (make_hex_id(0x41), make_hex_id(0x42));
1382        let full = community_row(&cid, &primary);
1383        let full: Vec<(&str, &str)> = full.iter().map(|(k, v)| (*k, v.as_str())).collect();
1384        let rows: [&[(&str, &str)]; 5] = [
1385            // A DM.
1386            &[],
1387            // A Community channel, with keys outside the typed set alongside.
1388            &full,
1389            // Known keys holding values no typed slot gives back exactly, beside unknown ones.
1390            &[
1391                ("is_owner", "yes"),
1392                ("dissolved", "TRUE"),
1393                ("created_at", "0042"),
1394                ("icon", "true"),
1395                ("community_id", "Not-Hex!"),
1396                ("aaa", "first"),
1397                ("zzz", "last"),
1398                ("channel_name", ""),
1399            ],
1400            // A row stamped before most keys existed.
1401            &[("community_id", "c0ffee"), ("name", "old")],
1402            // A DM that was only ever named.
1403            &[("name", "Bob"), ("member_count", "2")],
1404        ];
1405        for pairs in rows {
1406            let expected = serde_json::to_string(&PlainMetadata { custom_fields: plain(pairs) }).unwrap();
1407            let meta = typed(pairs);
1408            let json = serde_json::to_string(&meta).unwrap();
1409            assert_eq!(json, expected, "the typed row must serialize exactly as the plain map");
1410            let back: ChatMetadata = serde_json::from_str(&json).unwrap();
1411            assert_eq!(back, meta, "a round trip rebuilds the same row");
1412            assert_eq!(serde_json::to_string(&back).unwrap(), expected, "and re-serializes identically");
1413            for (k, v) in pairs {
1414                assert_eq!(meta.get(k).as_deref(), Some(*v), "{k} reads back verbatim");
1415                assert!(meta.contains_key(k));
1416            }
1417            assert_eq!(meta.entries().len(), pairs.len());
1418        }
1419        assert_eq!(serde_json::to_string(&ChatMetadata::new()).unwrap(), r#"{"custom_fields":{}}"#);
1420    }
1421
1422    #[test]
1423    fn custom_fields_deserialize_like_the_derived_map_did() {
1424        for json in [
1425            r#"{"custom_fields":{"name":"x","is_owner":"true"},"unknown":1}"#,
1426            r#"{"custom_fields":{}}"#,
1427            r#"{}"#,
1428            r#"{"custom_fields":{"name":null}}"#,
1429            r#"{"custom_fields":{"n":5}}"#,
1430            r#"{"custom_fields":[]}"#,
1431            r#"[]"#,
1432        ] {
1433            let plain = serde_json::from_str::<PlainMetadata>(json);
1434            let typed = serde_json::from_str::<ChatMetadata>(json);
1435            assert_eq!(plain.is_ok(), typed.is_ok(), "{json} must be accepted or refused alike");
1436            if let (Ok(p), Ok(t)) = (plain, typed) {
1437                assert_eq!(serde_json::to_string(&t).unwrap(), serde_json::to_string(&p).unwrap());
1438            }
1439        }
1440    }
1441
1442    #[test]
1443    fn a_community_chat_serializes_its_metadata_unchanged() {
1444        let mut interner = NpubInterner::new();
1445        let (cid, primary) = (make_hex_id(0x51), make_hex_id(0x52));
1446        let mut chat = Chat::new_community_channel(primary.clone(), Vec::new(), &mut interner);
1447        let row = community_row(&cid, &primary);
1448        for (k, v) in &row {
1449            chat.metadata.insert(k, v.clone());
1450        }
1451        let pairs: Vec<(&str, &str)> = row.iter().map(|(k, v)| (*k, v.as_str())).collect();
1452        let expected = serde_json::to_value(PlainMetadata { custom_fields: plain(&pairs) }).unwrap();
1453        let sent = serde_json::to_value(chat.to_serializable(&interner)).unwrap();
1454        assert_eq!(sent["metadata"], expected);
1455        assert!(chat.is_surfaced_community_channel());
1456        assert_eq!(chat.metadata.community_id(), Some(cid.as_str()));
1457        assert!(chat.metadata.is_dissolved());
1458    }
1459
1460    #[test]
1461    fn rewriting_a_typed_key_with_an_untyped_value_moves_it_cleanly() {
1462        let mut meta = typed(&[("community_id", "abc"), ("is_owner", "true")]);
1463        meta.insert("is_owner", "maybe".into());
1464        assert_eq!(meta.get("is_owner").as_deref(), Some("maybe"));
1465        meta.insert("is_owner", "false".into());
1466        assert_eq!(meta.get("is_owner").as_deref(), Some("false"));
1467        assert_eq!(meta, typed(&[("community_id", "abc"), ("is_owner", "false")]), "one key, one place");
1468        meta.remove("community_id");
1469        meta.remove("is_owner");
1470        assert_eq!(meta, ChatMetadata::new(), "an emptied row holds nothing");
1471    }
1472
1473    // ========================================================================
1474    // Accessor Methods
1475    // ========================================================================
1476
1477    #[test]
1478    fn accessor_methods_work() {
1479        let mut interner = NpubInterner::new();
1480        let mut chat = Chat::new_dm("npub1test".to_string(), &mut interner);
1481        chat.muted = true;
1482
1483        assert_eq!(chat.id(), "npub1test");
1484        assert_eq!(*chat.chat_type(), ChatType::DirectMessage);
1485        assert_eq!(chat.participants().len(), 1);
1486        assert_eq!(*chat.last_read(), [0u8; 32]);
1487        assert!(chat.created_at() > 0);
1488        assert!(chat.muted());
1489        assert_eq!(*chat.metadata(), ChatMetadata::new());
1490    }
1491}