Skip to main content

vector_core/db/
events.rs

1//! Event storage — save_event for the flat event architecture.
2
3use crate::stored_event::{StoredEvent, event_kind};
4use rusqlite::OptionalExtension;
5use crate::types::{Message, Attachment, Reaction};
6
7/// An event's content and link preview as stored: message, file caption and edit text and every
8/// preview sealed at rest, other kinds' content as-is.
9fn seal_event_fields(event: &StoredEvent, sealer: &mut crate::crypto::AtRestSealer) -> Result<(String, Option<String>), String> {
10    let content = if event.kind == event_kind::CHAT_MESSAGE
11        || event.kind == event_kind::PRIVATE_DIRECT_MESSAGE
12        || event.kind == event_kind::FILE_ATTACHMENT
13        || event.kind == event_kind::MESSAGE_EDIT
14    {
15        sealer.seal_set(&event.content)?
16    } else {
17        event.content.clone()
18    };
19    let preview = event.preview_metadata.as_deref().map(|p| sealer.seal(p)).transpose()?;
20    Ok((content, preview))
21}
22
23// A stored message's text and tags are its original, written once: edits are their own rows, so a
24// re-save from memory (which holds the latest edit, or whatever a failed open left) never replaces them.
25const _: () = assert!(
26    event_kind::CHAT_MESSAGE == 9 && event_kind::PRIVATE_DIRECT_MESSAGE == 14 && event_kind::FILE_ATTACHMENT == 15
27);
28
29/// Upsert the event row onto the given connection or transaction (so it can commit atomically with
30/// its attachment rows), sealing its content with the caller's sealer, inside its at-rest ticket.
31///
32/// UPSERT (not INSERT OR REPLACE) so a re-save (reaction/edit) UPDATES in place and PRESERVES the
33/// rowid. get_messages_around's (created_at, received_at, rowid) cursor needs a stable final
34/// tiebreak to page through same-timestamp bursts; INSERT OR REPLACE churns the rowid and drops rows.
35fn insert_event_row(
36    conn: &rusqlite::Connection,
37    event: &StoredEvent,
38    tags_json: &str,
39    sealer: &mut crate::crypto::AtRestSealer,
40) -> Result<(), String> {
41    let (content, preview) = seal_event_fields(event, sealer)?;
42    // prepare_cached: this is the hottest write statement in the app — the cache lives on the
43    // connection, so bulk-sync batches and every realtime save skip the SQL re-parse.
44    let mut stmt = conn.prepare_cached(
45        r#"
46        INSERT INTO events (
47            id, kind, chat_id, user_id, content, tags, reference_id,
48            created_at, received_at, mine, pending, failed, wrapper_event_id, npub, preview_metadata
49        ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)
50        ON CONFLICT(id) DO UPDATE SET
51            kind = excluded.kind, chat_id = excluded.chat_id, user_id = excluded.user_id,
52            content = CASE WHEN events.kind IN (9, 14, 15) THEN events.content ELSE excluded.content END,
53            tags = CASE WHEN events.kind IN (9, 14, 15) THEN events.tags ELSE excluded.tags END,
54            reference_id = excluded.reference_id,
55            created_at = excluded.created_at, received_at = excluded.received_at,
56            mine = excluded.mine, pending = excluded.pending, failed = excluded.failed,
57            wrapper_event_id = COALESCE(excluded.wrapper_event_id, events.wrapper_event_id),
58            npub = excluded.npub, preview_metadata = excluded.preview_metadata
59        "#,
60    ).map_err(|e| format!("prepare save event: {}", e))?;
61    stmt.execute(
62        rusqlite::params![
63            event.id, event.kind as i32, event.chat_id, event.user_id, &content, tags_json,
64            event.reference_id, event.created_at as i64, event.received_at as i64,
65            event.mine as i32, event.pending as i32, event.failed as i32,
66            event.wrapper_event_id, event.npub, preview,
67        ],
68    ).map_err(|e| format!("Failed to save event: {}", e))?;
69    Ok(())
70}
71
72/// A stored community message a restricted Channel's writer address carried (CORD-03 §1).
73const WRITER_TAG: &str = "writer";
74
75fn carried_by_writer(tags: &[Vec<String>]) -> bool {
76    tags.iter().any(|t| t.len() == 1 && t[0] == WRITER_TAG)
77}
78
79/// A stored community message its writers' rules don't stand behind, kept for managers.
80const UNAUTHORIZED_TAG: &str = "unauthorized";
81
82fn held_unauthorized(tags: &[Vec<String>]) -> bool {
83    tags.iter().any(|t| t.len() == 1 && t[0] == UNAUTHORIZED_TAG)
84}
85
86/// Save a StoredEvent to the events table, its message content sealed at rest.
87pub async fn save_event(event: &StoredEvent) -> Result<(), String> {
88    let tags_json = serde_json::to_string(&event.tags).unwrap_or_else(|_| "[]".to_string());
89    let _seal = crate::crypto::gate::sealing();
90    let conn = super::get_write_connection_guard_static()?;
91    crate::crypto::seal_batch(|sealer| insert_event_row(&conn, event, &tags_json, sealer))
92}
93
94/// Extract persisted `["bot", npub]` routing tags (the write side lives in
95/// `message_to_stored_event`).
96fn extract_bot_tags(tags: &[Vec<String>]) -> Vec<String> {
97    tags.iter()
98        .filter(|t| t.len() >= 2 && t[0] == "bot")
99        .map(|t| t[1].clone())
100        .collect()
101}
102
103/// Parse the NIP-40 `["expiration", <unix secs>]` tag, if present. Drives the
104/// self-destruct countdown + purge for messages rehydrated from the DB.
105fn extract_expiration_tag(tags: &[Vec<String>]) -> Option<u64> {
106    tags.iter()
107        .find(|t| t.len() >= 2 && t[0] == "expiration")
108        .and_then(|t| t[1].parse::<u64>().ok())
109}
110
111/// Check if an event exists in the database.
112pub fn event_exists(event_id: &str) -> Result<bool, String> {
113    let conn = super::get_db_connection_guard_static()?;
114    event_exists_on(&conn, event_id)
115}
116
117/// Which of `event_ids` are stored: [`event_exists`] for a whole page in one read.
118pub fn existing_event_ids(event_ids: &[String]) -> Result<std::collections::HashSet<String>, String> {
119    if event_ids.is_empty() {
120        return Ok(Default::default());
121    }
122    let conn = super::get_db_connection_guard_static()?;
123    let mut stmt = conn
124        .prepare_cached("SELECT id FROM events WHERE id IN (SELECT value FROM json_each(?1))")
125        .map_err(|e| format!("prepare event existence: {e}"))?;
126    let rows = stmt
127        .query_map([id_list_param(event_ids)], |row| row.get::<_, String>(0))
128        .map_err(|e| format!("Failed to check event existence: {e}"))?;
129    rows.collect::<Result<_, _>>().map_err(|e| format!("Failed to check event existence: {e}"))
130}
131
132/// `event_exists` against a caller-held connection or transaction — an in-transaction check
133/// sees the batch's own uncommitted rows, which the pooled read connection cannot.
134fn event_exists_on(conn: &rusqlite::Connection, event_id: &str) -> Result<bool, String> {
135    let mut stmt = conn.prepare_cached("SELECT EXISTS(SELECT 1 FROM events WHERE id = ?1)")
136        .map_err(|e| format!("prepare event existence: {}", e))?;
137    stmt.query_row(rusqlite::params![event_id], |row| row.get(0))
138        .map_err(|e| format!("Failed to check event existence: {}", e))
139}
140
141/// Build the kind=7 StoredEvent for a reaction (shared by the single-save and batch paths).
142fn reaction_to_stored_event(
143    reaction: &Reaction,
144    chat_id: i64,
145    user_id: Option<i64>,
146    mine: bool,
147    wrapper_event_id: Option<String>,
148) -> StoredEvent {
149    // Persist the NIP-30 emoji tag alongside the `e` reference so the
150    // image URL survives reload — pure `arrEmojiPacks` lookup would
151    // fail when the user hasn't yet opened the picker or unsubscribed.
152    let mut tags: Vec<Vec<String>> = vec![
153        vec!["e".to_string(), reaction.reference_id.clone()],
154    ];
155    if let Some(url) = &reaction.emoji_url {
156        if reaction.emoji.starts_with(':') && reaction.emoji.ends_with(':') && reaction.emoji.len() >= 3 {
157            let shortcode = &reaction.emoji[1..reaction.emoji.len() - 1];
158            if !shortcode.is_empty() && !url.is_empty() {
159                tags.push(vec!["emoji".to_string(), shortcode.to_string(), url.clone()]);
160            }
161        }
162    }
163    StoredEvent {
164        id: reaction.id.clone(),
165        kind: event_kind::REACTION,
166        chat_id,
167        user_id,
168        content: reaction.emoji.clone(),
169        tags,
170        reference_id: Some(reaction.reference_id.clone()),
171        created_at: crate::clock::now_secs(),
172        received_at: crate::clock::now_ms(),
173        mine,
174        pending: false,
175        failed: false,
176        wrapper_event_id,
177        npub: Some(reaction.author_id.clone()),
178        preview_metadata: None,
179    }
180}
181
182/// Save a reaction as a kind=7 event referencing the message.
183pub async fn save_reaction_event(
184    reaction: &Reaction,
185    chat_id: i64,
186    user_id: Option<i64>,
187    mine: bool,
188    wrapper_event_id: Option<String>,
189) -> Result<(), String> {
190    let event = reaction_to_stored_event(reaction, chat_id, user_id, mine, wrapper_event_id);
191    save_event(&event).await
192}
193
194// ============================================================================
195// save_message — Message → StoredEvent → DB
196// ============================================================================
197
198/// Save a single message to the database.
199///
200/// Converts Message to StoredEvent and saves via the flat event architecture.
201/// Also saves reactions as separate kind=7 events.
202pub async fn save_message(chat_id: &str, message: &Message) -> Result<(), String> {
203    let chat_int_id = super::id_cache::get_or_create_chat_id(chat_id)?;
204
205    let user_int_id = if let Some(ref npub_str) = message.npub {
206        super::id_cache::get_or_create_user_id(npub_str)?
207    } else {
208        None
209    };
210
211    let event = message_to_stored_event(message, chat_int_id, user_int_id);
212
213    // Commit the event row and its attachment rows (the dedicated table is the sole source of truth;
214    // pre-migration events keep their legacy tag as an un-read fallback) in ONE transaction, so a
215    // file message can never persist without its attachments — new events have no tag to fall back
216    // on.
217    let tags_json = serde_json::to_string(&event.tags).unwrap_or_else(|_| "[]".to_string());
218    {
219        let _seal = crate::crypto::gate::sealing();
220        let conn = super::get_write_connection_guard_static()?;
221        let tx = conn.unchecked_transaction().map_err(|e| format!("save_message tx: {e}"))?;
222        crate::crypto::seal_batch(|sealer| {
223            insert_event_row(&tx, &event, &tags_json, sealer)?;
224            super::attachments::insert_attachment_rows(&tx, &message.id, &message.attachments, sealer)
225        })?;
226        tx.commit().map_err(|e| format!("save_message commit: {e}"))?;
227    }
228
229    save_reactions_in(chat_int_id, message).await
230}
231
232/// Store the message's reactions this database does not hold yet, leaving the message's own row
233/// alone: rewriting it from memory would put its latest edit over the original text.
234pub async fn save_new_reactions(chat_id: &str, message: &Message) -> Result<(), String> {
235    let chat_int_id = super::id_cache::get_or_create_chat_id(chat_id)?;
236    save_reactions_in(chat_int_id, message).await
237}
238
239async fn save_reactions_in(chat_int_id: i64, message: &Message) -> Result<(), String> {
240    for reaction in &message.reactions {
241        if !event_exists(&reaction.id)? {
242            let user_id = super::id_cache::get_or_create_user_id(&reaction.author_id)?;
243            let is_mine = super::get_current_account()
244                .map(|npub| reaction.author_id == npub)
245                .unwrap_or(false);
246            save_reaction_event(reaction, chat_int_id, user_id, is_mine, None).await?;
247        }
248    }
249    Ok(())
250}
251
252/// One fully-prepared batch row: the message, its event row (sealed as phase 2 writes it), its
253/// prepared reaction rows, and (DM stream only) the gift-wrap ledger entry that must commit in the
254/// SAME transaction — everything phase 2 needs with zero async work and zero id_cache calls.
255struct BatchRow<'a> {
256    message: &'a Message,
257    event: StoredEvent,
258    tags_json: String,
259    reactions: Vec<(StoredEvent, String)>,
260    /// `(wrapper_id_bytes, wrapper_created_at)` — written to `processed_wrappers` only
261    /// AFTER this row lands. The ledger is the negentropy fingerprint set: a wrapper
262    /// ledgered before its row commits marks the message "have" forever if the row is lost.
263    wrapper: Option<([u8; 32], u64)>,
264}
265
266/// `(wrapper_id_bytes, wrapper_created_at)` of the gift wrap a message arrived in.
267pub(crate) type WrapperStamp = ([u8; 32], u64);
268/// One chat's messages in a multi-chat batch save.
269pub(crate) type ChatBatch<'a> = (String, Vec<(&'a Message, Option<WrapperStamp>)>);
270
271/// Phase 1 of a batched save (async): resolve ids and build StoredEvents.
272/// ALL id_cache lookups happen here — get_or_create can write a fresh chat/user row, so it
273/// must never run while phase 2 holds the write-connection guard.
274async fn prepare_batch_rows<'a>(
275    chat_id: &str,
276    messages: &[(&'a Message, Option<WrapperStamp>)],
277    rows: &mut Vec<BatchRow<'a>>,
278) -> Result<(), String> {
279    let chat_int_id = super::id_cache::get_or_create_chat_id(chat_id)?;
280    let my_npub = super::get_current_account();
281    for (message, wrapper) in messages {
282        let user_int_id = match &message.npub {
283            Some(npub_str) => super::id_cache::get_or_create_user_id(npub_str)?,
284            None => None,
285        };
286        let event = message_to_stored_event(message, chat_int_id, user_int_id);
287        let tags_json = serde_json::to_string(&event.tags).unwrap_or_else(|_| "[]".to_string());
288        let mut reactions: Vec<(StoredEvent, String)> = Vec::with_capacity(message.reactions.len());
289        for reaction in &message.reactions {
290            let user_id = super::id_cache::get_or_create_user_id(&reaction.author_id)?;
291            let is_mine = my_npub.as_deref().map(|n| reaction.author_id == n).unwrap_or(false);
292            let rev = reaction_to_stored_event(reaction, chat_int_id, user_id, is_mine, None);
293            let rtags = serde_json::to_string(&rev.tags).unwrap_or_else(|_| "[]".to_string());
294            reactions.push((rev, rtags));
295        }
296        rows.push(BatchRow { message, event, tags_json, reactions, wrapper: *wrapper });
297    }
298    Ok(())
299}
300
301/// Phase 2 of a batched save (sync): ONE transaction for every event + attachment + reaction +
302/// wrapper-ledger row. Insert order follows slice order, preserving the rowid tiebreak
303/// that same-timestamp pagination depends on. A poison message SKIPS (logged) rather than
304/// aborting the batch — one bad row must not lose the other 49. Returns how many messages
305/// were written.
306fn write_batch_rows(rows: &[BatchRow<'_>]) -> Result<usize, String> {
307    let _seal = crate::crypto::gate::sealing();
308    let conn = super::get_write_connection_guard_static()?;
309    let tx = conn.unchecked_transaction().map_err(|e| format!("batch tx: {e}"))?;
310    // One sealer for the page: the vault is read once, not once per message.
311    let saved = crate::crypto::seal_batch(|sealer| write_batch_rows_in(&tx, rows, sealer))?;
312    tx.commit().map_err(|e| format!("batch commit: {e}"))?;
313    Ok(saved)
314}
315
316fn write_batch_rows_in(
317    tx: &rusqlite::Transaction,
318    rows: &[BatchRow<'_>],
319    sealer: &mut crate::crypto::AtRestSealer,
320) -> Result<usize, String> {
321    let mut saved = 0usize;
322    for row in rows {
323        // Per-row savepoint = save_message's per-message atomicity inside the batch: a
324        // failed event/attachment write unwinds THIS row completely — including partial
325        // attachment upserts onto a pre-existing row, which a bare DELETE would destroy
326        // (a re-saved old file message must keep its download record on a transient error).
327        tx.execute_batch("SAVEPOINT batch_row").map_err(|e| format!("batch savepoint: {e}"))?;
328        let row_written = insert_event_row(tx, &row.event, &row.tags_json, sealer)
329            .and_then(|_| super::attachments::insert_attachment_rows(tx, &row.message.id, &row.message.attachments, sealer));
330        if let Err(e) = row_written {
331            crate::log_warn!("[DB] batch skip {}: {}", &row.message.id[..8.min(row.message.id.len())], e);
332            let _ = tx.execute_batch("ROLLBACK TO batch_row; RELEASE batch_row");
333            continue;
334        }
335        saved += 1;
336        for (rev, rtags) in &row.reactions {
337            // Exists-check ON the tx so a reaction already inserted earlier in this batch dedups
338            // (a fresh reaction row must not clobber one that arrived with a wrapper id).
339            if event_exists_on(tx, &rev.id).unwrap_or(true) {
340                continue;
341            }
342            if let Err(e) = insert_event_row(tx, rev, rtags, sealer) {
343                crate::log_warn!("[DB] batch reaction {}: {}", &rev.id[..8.min(rev.id.len())], e);
344            }
345        }
346        // Ledger the gift-wrap only now that its row is in the tx — commit lands both or neither.
347        if let Some((wrapper_id, wrapper_created_at)) = &row.wrapper {
348            let mut stmt = tx.prepare_cached(
349                "INSERT OR IGNORE INTO processed_wrappers (wrapper_id, wrapper_created_at, transport) VALUES (?1, ?2, ?3)",
350            ).map_err(|e| format!("prepare wrapper ledger: {e}"))?;
351            if let Err(e) = stmt.execute(rusqlite::params![
352                &wrapper_id[..], *wrapper_created_at as i64, super::wrappers::TRANSPORT_NIP17,
353            ]) {
354                crate::log_warn!("[DB] batch wrapper ledger {}: {}", &row.message.id[..8.min(row.message.id.len())], e);
355            }
356        }
357        tx.execute_batch("RELEASE batch_row").map_err(|e| format!("batch release: {e}"))?;
358    }
359    Ok(saved)
360}
361
362/// Save many messages for one chat in a SINGLE transaction — the bulk-sync persist path
363/// (community backfill pages, negentropy catch-up). One commit amortizes the per-transaction
364/// WAL overhead across the whole page instead of paying it per message.
365///
366/// Structure mirrors `save_message`: one transaction, under one at-rest ticket and one sealer,
367/// writes every event row + its attachment rows + its reaction rows, sealing as it goes.
368pub async fn save_messages_batch(
369    chat_id: &str,
370    messages: &[&Message],
371) -> Result<usize, String> {
372    crate::db::scoped(async move {
373        if messages.is_empty() {
374            return Ok(0);
375        }
376        let with_wrappers: Vec<(&Message, Option<WrapperStamp>)> =
377            messages.iter().map(|m| (*m, None)).collect();
378        let mut rows = Vec::with_capacity(messages.len());
379        prepare_batch_rows(chat_id, &with_wrappers, &mut rows).await?;
380        write_batch_rows(&rows)
381    })
382    .await
383}
384
385/// Multi-chat variant for the DM sync stream: gift-wrapped messages span many contacts, and
386/// splitting per chat would give back most of the batching win. Each message may carry its
387/// gift-wrap ledger entry, committed in the SAME transaction right after its row (see
388/// `BatchRow::wrapper`). Groups keep their slice order; everything lands in ONE transaction.
389pub async fn save_messages_batch_multi(
390    groups: &[ChatBatch<'_>],
391) -> Result<usize, String> {
392    crate::db::scoped(async move {
393        let total: usize = groups.iter().map(|(_, m)| m.len()).sum();
394        if total == 0 {
395            return Ok(0);
396        }
397        let mut rows = Vec::with_capacity(total);
398        for (chat_id, messages) in groups {
399            prepare_batch_rows(chat_id, messages, &mut rows).await?;
400        }
401        write_batch_rows(&rows)
402    })
403    .await
404}
405
406/// Convert a Message to a StoredEvent.
407fn message_to_stored_event(message: &Message, chat_id: i64, user_id: Option<i64>) -> StoredEvent {
408    let kind = if !message.attachments.is_empty() {
409        event_kind::FILE_ATTACHMENT
410    } else {
411        event_kind::PRIVATE_DIRECT_MESSAGE
412    };
413
414    let mut tags: Vec<Vec<String>> = Vec::new();
415
416    // Millisecond precision tag
417    let ms = message.at % 1000;
418    if ms > 0 {
419        tags.push(vec!["ms".to_string(), ms.to_string()]);
420    }
421
422    // Reply reference
423    if !message.replied_to.is_empty() {
424        tags.push(vec![
425            "e".to_string(),
426            message.replied_to.clone(),
427            "".to_string(),
428            "reply".to_string(),
429        ]);
430    }
431
432    // Attachments are stored in the dedicated `attachments` table (see save_message), not a tag.
433
434    // NIP-30 emoji tags — persist so reload from DB still renders the
435    // custom emoji image instead of the literal `:shortcode:`.
436    for et in &message.emoji_tags {
437        tags.push(vec!["emoji".to_string(), et.shortcode.clone(), et.url.clone()]);
438    }
439    tags.extend(message.text_spans.iter().map(|s| s.to_tag_parts()));
440    tags.extend(crate::community::mentions::to_stored(&message.role_mentions));
441    if message.writer {
442        tags.push(vec![WRITER_TAG.to_string()]);
443    }
444    if message.unauthorized {
445        tags.push(vec![UNAUTHORIZED_TAG.to_string()]);
446    }
447
448    // Bot routing targets (npubs) — persist so the passive "ran /cmd with
449    // Bot" render survives a reload.
450    for npub in &message.addressed_bots {
451        tags.push(vec!["bot".to_string(), npub.clone()]);
452    }
453
454    // NIP-40 self-destruct expiry — persist so the countdown + purge survive a
455    // reload. Rides the same tags column as every other message-shaped tag.
456    if let Some(exp) = message.expiration {
457        tags.push(vec!["expiration".to_string(), exp.to_string()]);
458    }
459
460    let preview_metadata = message.preview_metadata.as_ref()
461        .and_then(|m| serde_json::to_string(m).ok());
462
463    StoredEvent {
464        id: message.id.clone(),
465        kind,
466        chat_id,
467        user_id,
468        content: message.content.clone(),
469        tags,
470        reference_id: None,
471        created_at: message.at / 1000,
472        received_at: crate::clock::now_ms(),
473        mine: message.mine,
474        pending: message.pending,
475        failed: message.failed,
476        wrapper_event_id: message.wrapper_event_id.clone(),
477        npub: message.npub.clone(),
478        preview_metadata,
479    }
480}
481
482/// Save a PIVX payment event, resolving chat_id from conversation identifier.
483pub async fn save_pivx_payment_event(
484    conversation_id: &str,
485    mut event: StoredEvent,
486) -> Result<(), String> {
487    event.chat_id = super::id_cache::get_or_create_chat_id(conversation_id)?;
488    save_event(&event).await
489}
490
491/// Save a system event (member joined/left/removed) with dedup.
492/// Returns true if inserted, false if duplicate.
493pub async fn save_system_event_by_id(
494    event_id: &str,
495    conversation_id: &str,
496    event_type: crate::stored_event::SystemEventType,
497    member_npub: &str,
498    member_name: Option<&str>,
499) -> Result<bool, String> {
500    let now_secs = crate::clock::now_secs();
501    save_system_event_at(event_id, conversation_id, event_type, member_npub, member_name, now_secs, None, None).await
502}
503
504/// Like [`save_system_event_by_id`] but stamps `created_at` from the event's own authenticated timestamp
505/// (clamped to not exceed local now, since the inner author sets it) so a HISTORICALLY-synced presence
506/// (join/leave) sorts at the time it happened, not at ingest-time now. `received_at` stays local now.
507#[allow(clippy::too_many_arguments)]
508pub async fn save_system_event_at(
509    event_id: &str,
510    conversation_id: &str,
511    event_type: crate::stored_event::SystemEventType,
512    member_npub: &str,
513    member_name: Option<&str>,
514    created_at_secs: u64,
515    // Join attribution (public invites): who minted the link the member joined via, and its label.
516    // Stored as queryable tags so per-link join counts fall out of a tag scan.
517    invited_by: Option<&str>,
518    invited_label: Option<&str>,
519) -> Result<bool, String> {
520    // A blank conversation id is a caller bug, never a conversation. Left to
521    // `get_or_create_chat_id` it MINTS a chat row keyed by "" — and since the
522    // identifier is UNIQUE, every such write from every community collapses into
523    // one phantom row that nothing can open and the boot sweep can only report.
524    // A blank conversation id is a caller bug, never a conversation. Left to
525    // `get_or_create_chat_id` it MINTS a chat row keyed by "" — and since the
526    // identifier is UNIQUE, every such write from every community collapses into
527    // one phantom row that nothing can open and the boot sweep can only report.
528    if conversation_id.trim().is_empty() {
529        return Err("system event has no conversation id".to_string());
530    }
531    let chat_id = super::id_cache::get_or_create_chat_id(conversation_id)?;
532
533    let now_secs = crate::clock::now_secs();
534    // Author-set timestamp: clamp forward so a future-dated event can't jump ahead of real activity.
535    let created_at = created_at_secs.min(now_secs);
536
537    let display_name = member_name.unwrap_or(member_npub);
538    let content = event_type.display_message(display_name);
539
540    let mut tags: Vec<Vec<String>> = vec![
541        vec!["d".to_string(), "system-event".to_string()],
542        vec!["event-type".to_string(), event_type.as_u8().to_string()],
543        vec!["member".to_string(), member_npub.to_string()],
544    ];
545    if let Some(by) = invited_by {
546        tags.push(vec!["invited-by".to_string(), by.to_string()]);
547        if let Some(l) = invited_label.filter(|l| !l.is_empty()) {
548            tags.push(vec!["invited-label".to_string(), l.to_string()]);
549        }
550    }
551    let tags_json = serde_json::to_string(&tags)
552        .map_err(|e| format!("Failed to serialize tags: {}", e))?;
553
554    let conn = super::get_write_connection_guard_static()?;
555    let rows = conn.execute(
556        r#"INSERT OR IGNORE INTO events (
557            id, kind, chat_id, user_id, content, tags, reference_id,
558            created_at, received_at, mine, pending, failed, wrapper_event_id, npub
559        ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)"#,
560        rusqlite::params![
561            event_id,
562            event_kind::APPLICATION_SPECIFIC as i32,
563            chat_id, None::<i64>, content, tags_json, None::<String>,
564            created_at as i64, now_secs as i64,
565            0, 0, 0, None::<String>, member_npub,
566        ],
567    ).map_err(|e| format!("Failed to save system event: {}", e))?;
568
569    Ok(rows > 0)
570}
571
572/// One edit as the reload fold reads it: when, the new content, and its emoji and colour tags.
573type FoldedEdit = (u64, String, Vec<crate::types::EmojiTag>, Vec<crate::text_spans::TextSpan>);
574
575/// Save a message edit as a kind=16 event referencing the original message.
576#[allow(clippy::too_many_arguments)]
577pub async fn save_edit_event(
578    edit_id: &str,
579    message_id: &str,
580    new_content: &str,
581    emoji_tags: &[crate::types::EmojiTag],
582    text_spans: &[crate::text_spans::TextSpan],
583    chat_id: i64,
584    user_id: Option<i64>,
585    npub: &str,
586) -> Result<(), String> {
587    let now = std::time::Duration::from_millis(crate::clock::now_ms());
588
589    // Carry NIP-30 emoji tags so a reload renders the edit's custom emoji image
590    // (the reload fold reads the latest edit's tags, not the original message's).
591    let mut tags = vec![
592        vec!["e".to_string(), message_id.to_string(), "".to_string(), "edit".to_string()],
593    ];
594    for et in emoji_tags {
595        tags.push(vec!["emoji".to_string(), et.shortcode.clone(), et.url.clone()]);
596    }
597    tags.extend(text_spans.iter().map(|s| s.to_tag_parts()));
598
599    let event = StoredEvent {
600        id: edit_id.to_string(),
601        kind: event_kind::MESSAGE_EDIT,
602        chat_id,
603        user_id,
604        content: new_content.to_string(),
605        tags,
606        reference_id: Some(message_id.to_string()),
607        created_at: now.as_secs(),
608        received_at: now.as_millis() as u64,
609        mine: true,
610        pending: false,
611        failed: false,
612        wrapper_event_id: None,
613        npub: Some(npub.to_string()),
614        preview_metadata: None,
615    };
616
617    save_event(&event).await
618}
619
620/// Delete an event from the events table by ID, with the edits and reactions that name it.
621pub async fn delete_event(event_id: &str) -> Result<(), String> {
622    let conn = super::get_write_connection_guard_static()?;
623    // If this row is a chat's read marker, retreat it to the newest surviving event before it FIRST.
624    // A deleted marker would leave `last_read` dangling and collapse the unread anchor (badge stuck
625    // at 99+). The UPDATE fires only when this chat's marker is exactly the row being deleted.
626    // An empty id would match every chat whose marker is unset.
627    if event_id.is_empty() {
628        conn.execute("DELETE FROM events WHERE id = ''", []).map_err(|e| format!("Failed to delete event: {e}"))?;
629        return Ok(());
630    }
631    if let Ok(Some((chat_row, at))) = conn.query_row(
632        "SELECT chat_id, created_at FROM events WHERE id = ?1",
633        rusqlite::params![event_id],
634        |r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)),
635    ).optional() {
636        conn.execute(
637            "UPDATE chats SET last_read = COALESCE(( \
638                 SELECT id FROM events WHERE chat_id = ?1 AND id != ?2 AND created_at <= ?3 \
639                 ORDER BY created_at DESC, id DESC LIMIT 1), '') \
640             WHERE id = ?1 AND last_read = ?2",
641            rusqlite::params![chat_row, event_id, at],
642        ).map_err(|e| format!("read-marker retreat: {e}"))?;
643        // A "Mark as Unread" from this row moves on to the next message, or ends with none left.
644        conn.execute(
645            "UPDATE chats SET unread_from = COALESCE(( \
646                 SELECT id FROM events WHERE chat_id = ?1 AND id != ?2 AND created_at >= ?3 \
647                   AND kind IN (?4, ?5, ?6) \
648                 ORDER BY created_at ASC, id ASC LIMIT 1), '') \
649             WHERE id = ?1 AND unread_from = ?2",
650            rusqlite::params![chat_row, event_id, at,
651                event_kind::CHAT_MESSAGE as i32, event_kind::PRIVATE_DIRECT_MESSAGE as i32, event_kind::FILE_ATTACHMENT as i32],
652        ).map_err(|e| format!("unread-from advance: {e}"))?;
653    }
654    conn.execute(
655        "DELETE FROM events WHERE id = ?1",
656        rusqlite::params![event_id],
657    ).map_err(|e| format!("Failed to delete event: {}", e))?;
658    // An edit row holds the message's text, so it must not outlive the message.
659    conn.execute(
660        "DELETE FROM events WHERE reference_id = ?1 AND kind IN (?2, ?3)",
661        rusqlite::params![event_id, event_kind::MESSAGE_EDIT, event_kind::REACTION],
662    ).map_err(|e| format!("Failed to delete dependent events: {}", e))?;
663    Ok(())
664}
665
666/// Record a durable delete tombstone for `event_id`. The events row is gone after a
667/// delete, so this is the only thing that lets ingest refuse a wrap a relay
668/// re-serves across restarts (NIP-09 is best-effort — relays ignore it freely).
669pub fn add_message_tombstone(event_id: &str) -> Result<(), String> {
670    let conn = super::get_write_connection_guard_static()?;
671    let now = crate::clock::now_secs() as i64;
672    conn.execute(
673        "INSERT OR IGNORE INTO deleted_messages (event_id, deleted_at) VALUES (?1, ?2)",
674        rusqlite::params![event_id, now],
675    ).map_err(|e| format!("Failed to save delete tombstone: {}", e))?;
676    Ok(())
677}
678
679/// The most hide requests held for messages not met yet.
680const MAX_PENDING_DELETIONS: i64 = 10_000;
681
682/// Hold a hide request from `requester` (hex) for `target`, a message this device hasn't met,
683/// until `expires_at` (unix secs). Only the oldest beyond the cap are let go.
684pub fn park_pending_deletion(target: &str, requester: &str, expires_at: u64) -> Result<(), String> {
685    let conn = super::get_write_connection_guard_static()?;
686    let now = crate::clock::now_secs() as i64;
687    conn.execute(
688        "INSERT OR REPLACE INTO pending_deletions (target, requester, expires_at) VALUES (?1, ?2, ?3)",
689        rusqlite::params![target, requester, expires_at as i64],
690    )
691    .map_err(|e| format!("Failed to hold a pending deletion: {}", e))?;
692    conn.execute(
693        "DELETE FROM pending_deletions WHERE expires_at <= ?1 OR target NOT IN \
694         (SELECT target FROM pending_deletions ORDER BY expires_at DESC LIMIT ?2)",
695        rusqlite::params![now, MAX_PENDING_DELETIONS],
696    )
697    .map_err(|e| format!("Failed to prune pending deletions: {}", e))?;
698    Ok(())
699}
700
701/// Who asked, while it still stands, for `target` to be deleted before it arrived. Taken: it
702/// answers once.
703pub fn take_pending_deletion(target: &str) -> Option<String> {
704    // Read first: every message a sync brings asks, and almost none is held.
705    let (requester, expires_at) = super::get_db_connection_guard_static()
706        .ok()?
707        .prepare_cached("SELECT requester, expires_at FROM pending_deletions WHERE target = ?1")
708        .and_then(|mut stmt| stmt.query_row(rusqlite::params![target], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?))))
709        .optional()
710        .ok()
711        .flatten()?;
712    if let Ok(conn) = super::get_write_connection_guard_static() {
713        let _ = conn.execute("DELETE FROM pending_deletions WHERE target = ?1", rusqlite::params![target]);
714    }
715    let now = crate::clock::now_secs() as i64;
716    (expires_at > now).then_some(requester)
717}
718
719/// Every recorded delete tombstone, for seeding the in-session set at account init.
720pub fn load_message_tombstones() -> Result<Vec<String>, String> {
721    let conn = super::get_db_connection_guard_static()?;
722    let mut stmt = conn.prepare("SELECT event_id FROM deleted_messages")
723        .map_err(|e| format!("Failed to prepare tombstone query: {}", e))?;
724    let ids = stmt.query_map([], |row| row.get::<_, String>(0))
725        .map_err(|e| format!("Failed to query tombstones: {}", e))?
726        .filter_map(|r| r.ok())
727        .collect();
728    Ok(ids)
729}
730
731/// The stored author (npub) of an event, or `None` if the row (or DB) is absent. Lets the
732/// out-of-window moderation-hide path authorize against a paged-out message's real author.
733pub fn event_author(event_id: &str) -> Result<Option<String>, String> {
734    let conn = match super::get_db_connection_guard_static() {
735        Ok(c) => c,
736        Err(_) => return Ok(None),
737    };
738    conn.prepare_cached("SELECT npub FROM events WHERE id = ?1")
739        .and_then(|mut stmt| stmt.query_row(rusqlite::params![event_id], |row| row.get::<_, Option<String>>(0)))
740        .optional()
741        .map(|o| o.flatten())
742        .map_err(|e| format!("Failed to read event author: {}", e))
743}
744
745/// The message a stored reaction is attached to.
746pub fn reaction_target(reaction_id: &str) -> Result<Option<String>, String> {
747    let conn = match super::get_db_connection_guard_static() {
748        Ok(c) => c,
749        Err(_) => return Ok(None),
750    };
751    conn.prepare_cached("SELECT reference_id FROM events WHERE id = ?1 AND kind = ?2")
752        .and_then(|mut stmt| {
753            stmt.query_row(rusqlite::params![reaction_id, event_kind::REACTION], |row| row.get::<_, Option<String>>(0))
754        })
755        .optional()
756        .map(|o| o.flatten())
757        .map_err(|e| format!("Failed to read reaction target: {}", e))
758}
759
760/// The stored NIP-40 expiry of an event, read from the row itself: no load filter hides
761/// an expired one, so a caller can tell "expired" from "permanent".
762pub fn event_expiration(event_id: &str) -> Result<Option<u64>, String> {
763    let conn = match super::get_db_connection_guard_static() {
764        Ok(c) => c,
765        Err(_) => return Ok(None),
766    };
767    let tags: Option<String> = conn
768        .prepare_cached("SELECT tags FROM events WHERE id = ?1")
769        .and_then(|mut stmt| stmt.query_row(rusqlite::params![event_id], |row| row.get(0)))
770        .optional()
771        .map_err(|e| format!("Failed to read event expiry: {}", e))?;
772    Ok(tags
773        .and_then(|t| serde_json::from_str::<Vec<Vec<String>>>(&t).ok())
774        .and_then(|t| extract_expiration_tag(&t)))
775}
776
777/// The owning chat identifier, `mine` flag, and stored author (npub) of an event, or
778/// `None` if the row (or DB) is absent. Lets delete-affordance resolution give paged-out
779/// rows the same verdict as resident ones — residency is a cache detail, not a verdict.
780pub fn event_delete_context(event_id: &str) -> Result<Option<(String, bool, Option<String>)>, String> {
781    let conn = match super::get_db_connection_guard_static() {
782        Ok(c) => c,
783        Err(_) => return Ok(None),
784    };
785    conn.query_row(
786        "SELECT c.chat_identifier, e.mine, e.npub \
787         FROM events e JOIN chats c ON c.id = e.chat_id \
788         WHERE e.id = ?1",
789        rusqlite::params![event_id],
790        |row| {
791            Ok((
792                row.get::<_, String>(0)?,
793                row.get::<_, i32>(1)? != 0,
794                row.get::<_, Option<String>>(2)?,
795            ))
796        },
797    )
798    .optional()
799    .map_err(|e| format!("Failed to read event delete context: {}", e))
800}
801
802/// Check if a message/event exists in the database. Returns false if DB unavailable.
803pub fn message_exists_in_db(message_id: &str) -> Result<bool, String> {
804    let conn = match super::get_db_connection_guard_static() {
805        Ok(c) => c,
806        Err(_) => return Ok(false),
807    };
808    conn.prepare_cached("SELECT EXISTS(SELECT 1 FROM events WHERE id = ?1)")
809        .and_then(|mut stmt| stmt.query_row(rusqlite::params![message_id], |row| row.get(0)))
810        .map_err(|e| format!("Failed to check event existence: {}", e))
811}
812
813/// Check if a wrapper (giftwrap) event ID exists. Returns false if DB unavailable.
814pub fn wrapper_event_exists(wrapper_event_id: &str) -> Result<bool, String> {
815    let conn = match super::get_db_connection_guard_static() {
816        Ok(c) => c,
817        Err(_) => return Ok(false),
818    };
819    conn.prepare_cached("SELECT EXISTS(SELECT 1 FROM events WHERE wrapper_event_id = ?1)")
820        .and_then(|mut stmt| stmt.query_row(rusqlite::params![wrapper_event_id], |row| row.get(0)))
821        .map_err(|e| format!("Failed to check wrapper event existence: {}", e))
822}
823
824/// The gift wrap that carried event `event_id` to this account, when it was read off a relay.
825pub fn wrapper_event_id_of(event_id: &str) -> Option<nostr_sdk::prelude::EventId> {
826    let conn = super::get_db_connection_guard_static().ok()?;
827    let hex: Option<String> = conn
828        .prepare_cached("SELECT wrapper_event_id FROM events WHERE id = ?1")
829        .and_then(|mut stmt| stmt.query_row(rusqlite::params![event_id], |row| row.get(0)))
830        .ok()?;
831    nostr_sdk::prelude::EventId::from_hex(&hex?).ok()
832}
833
834/// The ids of the stored edits of `message_id`, which only its author can have made.
835pub fn edits_of(message_id: &str) -> Result<Vec<String>, String> {
836    let conn = super::get_db_connection_guard_static()?;
837    let mut stmt = conn
838        .prepare_cached("SELECT id FROM events WHERE reference_id = ?1 AND kind = ?2")
839        .map_err(|e| format!("edits of: {e}"))?;
840    let rows = stmt
841        .query_map(rusqlite::params![message_id, event_kind::MESSAGE_EDIT], |row| row.get::<_, String>(0))
842        .map_err(|e| format!("edits of: {e}"))?;
843    rows.collect::<Result<_, _>>().map_err(|e| format!("edits of: {e}"))
844}
845
846/// The community wraps among `wrapper_event_ids` whose message is stored with nothing left to
847/// learn from opening it again: someone else's, or mine with its delete key kept.
848pub fn community_wraps_settled(wrapper_event_ids: &[String]) -> std::collections::HashSet<String> {
849    let Ok(conn) = super::get_db_connection_guard_static() else { return Default::default() };
850    let Ok(ids) = serde_json::to_string(wrapper_event_ids) else { return Default::default() };
851    let Ok(mut stmt) = conn.prepare_cached(
852        "SELECT DISTINCT e.wrapper_event_id FROM json_each(?1) j JOIN events e ON e.wrapper_event_id = j.value \
853         WHERE e.mine = 0 OR EXISTS(SELECT 1 FROM community_message_keys k WHERE k.message_id = e.id) \
854         OR EXISTS(SELECT 1 FROM community_wrap_owners o WHERE o.message_id = e.id)",
855    ) else {
856        return Default::default();
857    };
858    let mut settled: std::collections::HashSet<String> = stmt.query_map([ids], |row| row.get::<_, String>(0)).map(|rows| rows.flatten().collect()).unwrap_or_default();
859    // A held wrap waits on this device for a later judgment, not on a relay.
860    settled.extend(super::community::held_wrap_ids(wrapper_event_ids));
861    settled
862}
863
864/// The millisecond remainder a row carries past its `created_at` second.
865fn ms_tag(tags: &[Vec<String>]) -> u64 {
866    tags.iter().find(|t| t.len() == 2 && t[0] == "ms").and_then(|t| t[1].parse::<u64>().ok()).unwrap_or(0)
867}
868
869/// A post stored in a chat dated at or after `since_ms`, as the writers' rules judge it.
870#[derive(Debug, Clone, PartialEq, Eq)]
871pub struct StoredPost {
872    pub id: String,
873    pub npub: Option<String>,
874    pub at_ms: u64,
875    /// Read at a restricted Channel's writer address.
876    pub writer: bool,
877    pub unauthorized: bool,
878    pub wrap_id: Option<String>,
879    /// For an edit, the message it edits.
880    pub edit_of: Option<String>,
881}
882
883/// The newest message `chat_identifier` holds dated before `before_secs`, in Unix seconds.
884pub fn newest_message_before(chat_identifier: &str, before_secs: u64) -> Option<u64> {
885    let chat_id = super::id_cache::get_chat_id_by_identifier(chat_identifier).ok()?;
886    let conn = super::get_db_connection_guard_static().ok()?;
887    conn.query_row(
888        "SELECT MAX(created_at) FROM events WHERE chat_id = ?1 AND kind IN (?2, ?3, ?4) AND created_at < ?5",
889        rusqlite::params![chat_id, event_kind::CHAT_MESSAGE as i32, event_kind::FILE_ATTACHMENT as i32, event_kind::PRIVATE_DIRECT_MESSAGE as i32, before_secs as i64],
890        |r| r.get::<_, Option<i64>>(0),
891    )
892    .ok()
893    .flatten()
894    .map(|s| s.max(0) as u64)
895}
896
897/// The messages `chat_identifier` holds dated at or after `since_ms`.
898pub fn posts_since(chat_identifier: &str, since_ms: u64) -> Result<Vec<StoredPost>, String> {
899    posts_since_by(chat_identifier, since_ms, None)
900}
901
902/// [`posts_since`], of one author's (npub) posts only when `author` is given.
903pub fn posts_since_by(chat_identifier: &str, since_ms: u64, author: Option<&str>) -> Result<Vec<StoredPost>, String> {
904    let Ok(chat_id) = super::id_cache::get_chat_id_by_identifier(chat_identifier) else { return Ok(Vec::new()) };
905    let conn = super::get_db_connection_guard_static()?;
906    let mut stmt = conn
907        .prepare("SELECT id, npub, created_at, tags, wrapper_event_id, kind, reference_id FROM events WHERE chat_id = ?1 AND kind IN (?2, ?3, ?5, ?6) AND created_at >= ?4 AND (?7 IS NULL OR npub = ?7)")
908        .map_err(|e| format!("posts since: {e}"))?;
909    let rows = stmt
910        .query_map(
911            rusqlite::params![chat_id, event_kind::CHAT_MESSAGE as i32, event_kind::FILE_ATTACHMENT as i32, (since_ms / 1000) as i64, event_kind::PRIVATE_DIRECT_MESSAGE as i32, event_kind::MESSAGE_EDIT as i32, author],
912            |r| Ok((r.get::<_, String>(0)?, r.get::<_, Option<String>>(1)?, r.get::<_, i64>(2)?, r.get::<_, String>(3)?, r.get::<_, Option<String>>(4)?, r.get::<_, i32>(5)?, r.get::<_, Option<String>>(6)?)),
913        )
914        .map_err(|e| format!("posts since: {e}"))?;
915    Ok(rows
916        .flatten()
917        .filter_map(|(id, npub, secs, tags, wrap_id, kind, reference)| {
918            let tags: Vec<Vec<String>> = serde_json::from_str(&tags).unwrap_or_default();
919            let at_ms = (secs.max(0) as u64) * 1000 + ms_tag(&tags);
920            let edit_of = (kind == event_kind::MESSAGE_EDIT as i32).then_some(reference).flatten();
921            (at_ms >= since_ms).then(|| StoredPost { id, npub, at_ms, writer: carried_by_writer(&tags), unauthorized: held_unauthorized(&tags), wrap_id: wrap_id.filter(|w| !w.is_empty()), edit_of })
922        })
923        .collect())
924}
925
926/// Mark a stored message as one its Channel's rules don't stand behind, or clear the mark.
927/// Returns whether the message is stored.
928pub fn set_event_unauthorized(event_id: &str, held: bool) -> Result<bool, String> {
929    let conn = super::get_write_connection_guard_static()?;
930    let tags: Option<String> = conn
931        .query_row("SELECT tags FROM events WHERE id = ?1", rusqlite::params![event_id], |r| r.get(0))
932        .optional()
933        .map_err(|e| format!("read tags: {e}"))?;
934    let Some(tags) = tags else { return Ok(false) };
935    let mut parsed: Vec<Vec<String>> = serde_json::from_str(&tags).unwrap_or_default();
936    parsed.retain(|t| !(t.len() == 1 && t[0] == UNAUTHORIZED_TAG));
937    if held {
938        parsed.push(vec![UNAUTHORIZED_TAG.to_string()]);
939    }
940    let json = serde_json::to_string(&parsed).map_err(|e| format!("tags: {e}"))?;
941    conn.execute("UPDATE events SET tags = ?1 WHERE id = ?2", rusqlite::params![json, event_id]).map_err(|e| format!("write tags: {e}"))?;
942    Ok(true)
943}
944
945/// Update the wrapper event ID for an existing event.
946/// Returns true if updated, false if event already had a wrapper_id.
947pub fn update_wrapper_event_id(event_id: &str, wrapper_event_id: &str) -> Result<bool, String> {
948    let conn = match super::get_write_connection_guard_static() {
949        Ok(c) => c,
950        Err(_) => return Ok(false),
951    };
952    let rows = conn.execute(
953        "UPDATE events SET wrapper_event_id = ?1 WHERE id = ?2 AND (wrapper_event_id IS NULL OR wrapper_event_id = '')",
954        rusqlite::params![wrapper_event_id, event_id],
955    ).map_err(|e| format!("Failed to update wrapper event ID: {}", e))?;
956    Ok(rows > 0)
957}
958
959/// Get message count for a chat.
960pub fn get_chat_message_count(chat_id: i64) -> Result<usize, String> {
961    let conn = super::get_db_connection_guard_static()?;
962    // Must count the SAME kinds get_message_views returns (community chat 9, DM 14, file 15). A
963    // narrower set under-counts vs. the rows actually loaded, which latches the frontend cache's
964    // `isFullyLoaded` flag true and wedges the local back-pager — community channels then never
965    // page DB history past the first screen.
966    let count: i64 = conn.query_row(
967        &format!(
968            "SELECT COUNT(*) FROM events WHERE chat_id = ?1 AND kind IN ({}, {}, {})",
969            event_kind::CHAT_MESSAGE, event_kind::PRIVATE_DIRECT_MESSAGE, event_kind::FILE_ATTACHMENT
970        ),
971        rusqlite::params![chat_id],
972        |row| row.get(0),
973    ).map_err(|e| format!("Failed to count messages: {}", e))?;
974    Ok(count as usize)
975}
976
977/// DM peers the user has actually written to: chat identifiers of DirectMessage chats holding
978/// at least one own message. The contact pickers list these, not every profile ever seen.
979pub fn get_dm_contact_npubs() -> Result<Vec<String>, String> {
980    let conn = super::get_db_connection_guard_static()?;
981    let mut stmt = conn.prepare(&format!(
982        "SELECT c.chat_identifier FROM chats c \
983         WHERE c.chat_type = 0 AND EXISTS (\
984             SELECT 1 FROM events e WHERE e.chat_id = c.id AND e.mine = 1 AND e.kind IN ({}, {}))",
985        event_kind::PRIVATE_DIRECT_MESSAGE, event_kind::FILE_ATTACHMENT
986    )).map_err(|e| format!("Failed to prepare DM contact query: {}", e))?;
987    let rows = stmt.query_map([], |row| row.get::<_, String>(0))
988        .map_err(|e| format!("Failed to query DM contacts: {}", e))?;
989    Ok(rows.filter_map(|r| r.ok()).collect())
990}
991
992/// Get PIVX payment events for a chat.
993pub fn get_pivx_payments_for_chat(conversation_id: &str) -> Result<Vec<StoredEvent>, String> {
994    let conn = super::get_db_connection_guard_static()?;
995    let chat_id: i64 = conn.query_row(
996        "SELECT id FROM chats WHERE chat_identifier = ?1",
997        rusqlite::params![conversation_id], |row| row.get(0)
998    ).map_err(|_| "Chat not found")?;
999
1000    let mut stmt = conn.prepare(
1001        "SELECT id, kind, chat_id, user_id, content, tags, reference_id, \
1002         created_at, received_at, mine, pending, failed, wrapper_event_id, npub \
1003         FROM events WHERE chat_id = ?1 AND kind = ?2 ORDER BY created_at ASC, received_at ASC"
1004    ).map_err(|e| format!("Failed to prepare: {}", e))?;
1005
1006    let rows = stmt.query_map(
1007        rusqlite::params![chat_id, event_kind::APPLICATION_SPECIFIC as i32],
1008        |row| {
1009            let tags_json: String = row.get(5)?;
1010            let tags: Vec<Vec<String>> = serde_json::from_str(&tags_json).unwrap_or_default();
1011            Ok(StoredEvent {
1012                id: row.get(0)?, kind: row.get::<_, i32>(1)? as u16,
1013                chat_id: row.get(2)?, user_id: row.get(3)?, content: row.get(4)?,
1014                tags, reference_id: row.get(6)?,
1015                created_at: row.get::<_, i64>(7)? as u64, received_at: row.get::<_, i64>(8)? as u64,
1016                mine: row.get::<_, i32>(9)? != 0, pending: row.get::<_, i32>(10)? != 0,
1017                failed: row.get::<_, i32>(11)? != 0, wrapper_event_id: row.get(12)?,
1018                npub: row.get(13)?, preview_metadata: None,
1019            })
1020        }
1021    ).map_err(|e| format!("Failed to query: {}", e))?;
1022
1023    let mut payments = Vec::new();
1024    for row in rows {
1025        let event = row.map_err(|e| format!("Failed to read event: {}", e))?;
1026        if event.tags.iter().any(|t| t.len() >= 2 && t[0] == "d" && t[1] == "pivx-payment") {
1027            payments.push(event);
1028        }
1029    }
1030    Ok(payments)
1031}
1032
1033/// Get system events (member joined/left) for a chat.
1034///
1035/// Join/leave lines carry their member in `npub`, so a banned member's arrival is
1036/// dropped by the same rule that hides what they said. These have their OWN query —
1037/// the chat page never sees them — so filtering the message page alone left a wall of
1038/// "has joined" from accounts the client otherwise refuses to render.
1039pub fn get_system_events_for_chat(conversation_id: &str) -> Result<Vec<StoredEvent>, String> {
1040    let conn = super::get_db_connection_guard_static()?;
1041    let chat_id: i64 = conn.query_row(
1042        "SELECT id FROM chats WHERE chat_identifier = ?1",
1043        rusqlite::params![conversation_id], |row| row.get(0)
1044    ).map_err(|_| "Chat not found")?;
1045
1046    let mut stmt = conn.prepare(
1047        &format!("SELECT id, kind, chat_id, user_id, content, tags, reference_id, \
1048         created_at, received_at, mine, pending, failed, wrapper_event_id, npub \
1049         FROM events WHERE chat_id = ?1 AND kind = ?2{} ORDER BY created_at ASC, received_at ASC",
1050         ban_filter_sql(3))
1051    ).map_err(|e| format!("Failed to prepare: {}", e))?;
1052
1053    let rows = stmt.query_map(
1054        rusqlite::params![chat_id, event_kind::APPLICATION_SPECIFIC as i32, ban_param(&conn, chat_id)],
1055        |row| {
1056            let tags_json: String = row.get(5)?;
1057            let tags: Vec<Vec<String>> = serde_json::from_str(&tags_json).unwrap_or_default();
1058            Ok(StoredEvent {
1059                id: row.get(0)?, kind: row.get::<_, i32>(1)? as u16,
1060                chat_id: row.get(2)?, user_id: row.get(3)?, content: row.get(4)?,
1061                tags, reference_id: row.get(6)?,
1062                created_at: row.get::<_, i64>(7)? as u64, received_at: row.get::<_, i64>(8)? as u64,
1063                mine: row.get::<_, i32>(9)? != 0, pending: row.get::<_, i32>(10)? != 0,
1064                failed: row.get::<_, i32>(11)? != 0, wrapper_event_id: row.get(12)?,
1065                npub: row.get(13)?, preview_metadata: None,
1066            })
1067        }
1068    ).map_err(|e| format!("Failed to query: {}", e))?;
1069
1070    let mut events = Vec::new();
1071    for row in rows {
1072        let event = row.map_err(|e| format!("Failed to read event: {}", e))?;
1073        if event.tags.iter().any(|t| t.len() >= 2 && t[0] == "d" && t[1] == "system-event") {
1074            events.push(event);
1075        }
1076    }
1077    drop(stmt);
1078    drop(conn);
1079    // Join/Leave lines are kept even where they don't show: the member list reads them.
1080    let is_presence = |e: &StoredEvent| e.tags.iter().any(|t| t.len() >= 2 && t[0] == "event-type" && (t[1] == "0" || t[1] == "1"));
1081    if events.iter().any(is_presence) && !super::community::presence_lines_shown_in(conversation_id)? {
1082        events.retain(|e| !is_presence(e));
1083    }
1084    Ok(events)
1085}
1086
1087// ============================================================================
1088// Event Read Operations
1089// ============================================================================
1090
1091/// Helper to parse a SQLite row into a StoredEvent.
1092fn parse_event_row(row: &rusqlite::Row) -> rusqlite::Result<StoredEvent> {
1093    let tags_json: String = row.get(5)?;
1094    let tags: Vec<Vec<String>> = serde_json::from_str(&tags_json).unwrap_or_default();
1095
1096    Ok(StoredEvent {
1097        id: row.get(0)?,
1098        kind: row.get::<_, i32>(1)? as u16,
1099        chat_id: row.get(2)?,
1100        user_id: row.get(3)?,
1101        content: row.get(4)?,
1102        tags,
1103        reference_id: row.get(6)?,
1104        created_at: row.get::<_, i64>(7)? as u64,
1105        received_at: row.get::<_, i64>(8)? as u64,
1106        mine: row.get::<_, i32>(9)? != 0,
1107        pending: row.get::<_, i32>(10)? != 0,
1108        failed: row.get::<_, i32>(11)? != 0,
1109        wrapper_event_id: row.get(12)?,
1110        npub: row.get(13)?,
1111        preview_metadata: row.get(14)?,
1112    })
1113}
1114
1115/// The community this chat's channel belongs to, or `None` for a DM.
1116///
1117/// Resolved once per query rather than joined per row: the ban predicate then
1118/// seeks `community_bans`' primary key instead of walking chats -> channels for
1119/// every candidate event.
1120fn community_of_chat(conn: &rusqlite::Connection, chat_id: i64) -> Option<String> {
1121    conn.prepare_cached(
1122        "SELECT cc.community_id FROM community_channels cc \
1123         JOIN chats c ON c.chat_identifier = cc.channel_id WHERE c.id = ?1",
1124    )
1125    .ok()?
1126    .query_row(rusqlite::params![chat_id], |r| r.get::<_, String>(0))
1127    .ok()
1128}
1129
1130/// An id list as one JSON array parameter, read in SQL through `json_each(?)`: one statement
1131/// for any list length, so it prepares once per connection and stays cached.
1132pub(super) fn id_list_param(ids: &[String]) -> String {
1133    serde_json::to_string(ids).unwrap_or_else(|_| "[]".into())
1134}
1135
1136/// Excludes a banned author's events BEFORE `LIMIT`.
1137///
1138/// A ban has to hide what they already posted, not just stop the next message —
1139/// and it has to do it here, in SQL. Filtering the page after it is fetched
1140/// returns fewer rows than asked for, which reads to the caller as "end of
1141/// history": backscroll stops early, and a wall of banned events hides
1142/// everything older than itself. `?{n}` is NULL for a DM, where the whole
1143/// predicate short-circuits.
1144fn ban_filter_sql(param: usize) -> String {
1145    format!(
1146        " AND (?{param} IS NULL OR events.npub IS NULL OR events.npub NOT IN ( \
1147            SELECT value FROM json_each(?{param})))"
1148    )
1149}
1150
1151/// The banned authors of a chat's community as a JSON array of npubs, the parameter
1152/// `ban_filter_sql` reads; `None` for a DM or a community with no bans. Bans are sealed at
1153/// rest, so SQL is handed the opened list, from the write-through cache.
1154fn ban_param(conn: &rusqlite::Connection, chat_id: i64) -> Option<String> {
1155    banned_npubs_json(&community_of_chat(conn, chat_id)?)
1156}
1157
1158fn banned_npubs_json(community_id: &str) -> Option<String> {
1159    use nostr_sdk::prelude::ToBech32;
1160    let set = super::community::banned_set(community_id);
1161    if set.is_empty() {
1162        return None;
1163    }
1164    let npubs: Vec<String> = set
1165        .iter()
1166        .filter_map(|b| nostr_sdk::prelude::PublicKey::from_slice(b).ok()?.to_bech32().ok())
1167        .collect();
1168    serde_json::to_string(&npubs).ok()
1169}
1170
1171/// Every community's bans as `"<community_id> <npub>"` strings, for the all-chats unread count.
1172fn all_ban_pairs_json(conn: &rusqlite::Connection) -> String {
1173    use nostr_sdk::prelude::ToBech32;
1174    let communities: Vec<String> = conn
1175        .prepare_cached("SELECT DISTINCT community_id FROM community_bans")
1176        .and_then(|mut st| st.query_map([], |r| r.get::<_, String>(0)).map(|rows| rows.flatten().collect()))
1177        .unwrap_or_default();
1178    let mut pairs = Vec::new();
1179    for cid in communities {
1180        for b in super::community::banned_set(&cid).iter() {
1181            if let Some(npub) = nostr_sdk::prelude::PublicKey::from_slice(b).ok().and_then(|pk| pk.to_bech32().ok()) {
1182                pairs.push(format!("{cid} {npub}"));
1183            }
1184        }
1185    }
1186    serde_json::to_string(&pairs).unwrap_or_else(|_| "[]".into())
1187}
1188
1189/// Get events for a chat with pagination, optionally filtered by kind.
1190/// Message/edit content is decrypted in one at-rest batch.
1191pub async fn get_events(
1192    chat_id: i64,
1193    kinds: Option<&[u16]>,
1194    limit: usize,
1195    offset: usize,
1196) -> Result<Vec<StoredEvent>, String> {
1197    let events: Vec<StoredEvent> = {
1198        let conn = super::get_db_connection_guard_static()?;
1199        let community = ban_param(&conn, chat_id);
1200
1201        if let Some(k) = kinds {
1202            let kind_placeholders: String = (0..k.len())
1203                .map(|i| format!("?{}", i + 2))
1204                .collect::<Vec<_>>()
1205                .join(",");
1206            let limit_param = k.len() + 2;
1207            let offset_param = k.len() + 3;
1208            let community_param = k.len() + 4;
1209
1210            let sql = format!(
1211                "SELECT id, kind, chat_id, user_id, content, tags, reference_id, \
1212                 created_at, received_at, mine, pending, failed, wrapper_event_id, npub, preview_metadata \
1213                 FROM events WHERE chat_id = ?1 AND kind IN ({}){} \
1214                 ORDER BY created_at DESC, received_at DESC \
1215                 LIMIT ?{} OFFSET ?{}",
1216                kind_placeholders, ban_filter_sql(community_param), limit_param, offset_param
1217            );
1218
1219            let mut stmt = conn.prepare_cached(&sql)
1220                .map_err(|e| format!("Failed to prepare events query: {}", e))?;
1221
1222            match k.len() {
1223                1 => {
1224                    let rows = stmt.query_map(
1225                        rusqlite::params![chat_id, k[0] as i32, limit as i64, offset as i64, community],
1226                        parse_event_row
1227                    ).map_err(|e| format!("Failed to query events: {}", e))?;
1228                    rows.filter_map(|r| r.ok()).collect()
1229                },
1230                2 => {
1231                    let rows = stmt.query_map(
1232                        rusqlite::params![chat_id, k[0] as i32, k[1] as i32, limit as i64, offset as i64, community],
1233                        parse_event_row
1234                    ).map_err(|e| format!("Failed to query events: {}", e))?;
1235                    rows.filter_map(|r| r.ok()).collect()
1236                },
1237                3 => {
1238                    let rows = stmt.query_map(
1239                        rusqlite::params![chat_id, k[0] as i32, k[1] as i32, k[2] as i32, limit as i64, offset as i64, community],
1240                        parse_event_row
1241                    ).map_err(|e| format!("Failed to query events: {}", e))?;
1242                    rows.filter_map(|r| r.ok()).collect()
1243                },
1244                _ => return Err("Unsupported number of kinds".to_string()),
1245            }
1246        } else {
1247            let mut stmt = conn.prepare_cached(
1248                &format!("SELECT id, kind, chat_id, user_id, content, tags, reference_id, \
1249                 created_at, received_at, mine, pending, failed, wrapper_event_id, npub, preview_metadata \
1250                 FROM events WHERE chat_id = ?1{} \
1251                 ORDER BY created_at DESC, received_at DESC \
1252                 LIMIT ?2 OFFSET ?3", ban_filter_sql(4))
1253            ).map_err(|e| format!("Failed to prepare events query: {}", e))?;
1254
1255            let rows = stmt.query_map(
1256                rusqlite::params![chat_id, limit as i64, offset as i64, community],
1257                parse_event_row
1258            ).map_err(|e| format!("Failed to query events: {}", e))?;
1259            rows.filter_map(|r| r.ok()).collect()
1260        }
1261    };
1262
1263    // Decrypt message content
1264    let decrypted: Vec<StoredEvent> = crate::crypto::open_batch(|at_rest| events.into_iter().map(|mut event| {
1265        if event.kind == event_kind::CHAT_MESSAGE || event.kind == event_kind::PRIVATE_DIRECT_MESSAGE {
1266            event.content = at_rest.open(event.content)
1267                .unwrap_or_else(|_| "[Decryption failed]".to_string());
1268        }
1269        event
1270    }).collect());
1271
1272    Ok(decrypted)
1273}
1274
1275/// Get events that reference specific message IDs (reactions, edits).
1276pub async fn get_related_events(
1277    reference_ids: &[String],
1278) -> Result<Vec<StoredEvent>, String> {
1279    if reference_ids.is_empty() {
1280        return Ok(Vec::new());
1281    }
1282
1283    let conn = super::get_db_connection_guard_static()?;
1284    let mut stmt = conn.prepare_cached(
1285        "SELECT id, kind, chat_id, user_id, content, tags, reference_id, \
1286         created_at, received_at, mine, pending, failed, wrapper_event_id, npub, preview_metadata \
1287         FROM events WHERE reference_id IN (SELECT value FROM json_each(?1)) \
1288         ORDER BY created_at ASC, received_at ASC",
1289    )
1290    .map_err(|e| format!("Failed to prepare related events query: {}", e))?;
1291
1292    let events: Vec<StoredEvent> = stmt.query_map([id_list_param(reference_ids)], parse_event_row)
1293        .map_err(|e| format!("Failed to query related events: {}", e))?
1294        .filter_map(|r| r.ok())
1295        .collect();
1296
1297    Ok(events)
1298}
1299
1300/// Context data for a replied-to message.
1301pub struct ReplyContext {
1302    pub content: String,
1303    pub npub: Option<String>,
1304    pub has_attachment: bool,
1305    /// Extension of the attachment, when the replied-to message is a file, so
1306    /// the reply quote can label the type even when the target is off-screen.
1307    pub extension: Option<String>,
1308    /// The target's NIP-30 emoji tags — without them an off-screen quote
1309    /// renders raw `:shortcodes:` and nothing ever corrects it.
1310    pub emoji_tags: Vec<crate::types::EmojiTag>,
1311}
1312
1313/// Fetch reply context for a list of message IDs.
1314pub async fn get_reply_contexts(
1315    message_ids: &[String],
1316) -> Result<std::collections::HashMap<String, ReplyContext>, String> {
1317    use std::collections::HashMap;
1318
1319    if message_ids.is_empty() {
1320        return Ok(HashMap::new());
1321    }
1322
1323    let (events, edits) = {
1324        let conn = super::get_db_connection_guard_static()?;
1325        let ids = id_list_param(message_ids);
1326
1327        // Query original messages (tags carry the file-type/name for attachment quotes)
1328        let mut stmt = conn
1329            .prepare_cached("SELECT id, kind, content, npub, tags FROM events WHERE id IN (SELECT value FROM json_each(?1))")
1330            .map_err(|e| format!("Failed to prepare reply context query: {}", e))?;
1331
1332        let rows = stmt.query_map([&ids], |row| {
1333            Ok((row.get::<_, String>(0)?, row.get::<_, i32>(1)?,
1334                row.get::<_, String>(2)?, row.get::<_, Option<String>>(3)?,
1335                row.get::<_, Option<String>>(4)?))
1336        }).map_err(|e| format!("Failed to query reply contexts: {}", e))?;
1337        let events_result: Vec<_> = rows.filter_map(|r| r.ok()).collect();
1338        drop(stmt);
1339
1340        // Query latest edits
1341        let mut edit_stmt = conn
1342            .prepare_cached(
1343                "SELECT reference_id, content, tags FROM events \
1344                 WHERE kind = ?2 AND reference_id IN (SELECT value FROM json_each(?1)) \
1345                 ORDER BY created_at DESC, received_at DESC",
1346            )
1347            .map_err(|e| format!("Failed to prepare edit query: {}", e))?;
1348        let edit_rows = edit_stmt.query_map(rusqlite::params![&ids, event_kind::MESSAGE_EDIT as i32], |row| {
1349            Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?,
1350                row.get::<_, Option<String>>(2)?))
1351        }).map_err(|e| format!("Failed to query edits: {}", e))?;
1352        let edits_result: Vec<_> = edit_rows.filter_map(|r| r.ok()).collect();
1353
1354        (events_result, edits_result)
1355    };
1356
1357    // Build latest edit map (first = most recent since ordered DESC)
1358    let mut latest_edits: HashMap<String, (String, Option<String>)> = HashMap::new();
1359    for (ref_id, content, tags) in edits {
1360        latest_edits.entry(ref_id).or_insert((content, tags));
1361    }
1362
1363    // Batch the file replies' attachments (one query, not one per reply) for the extension below.
1364    let file_ids: Vec<String> = events.iter()
1365        .filter(|(_, kind, _, _, _)| *kind == event_kind::FILE_ATTACHMENT as i32)
1366        .map(|(id, _, _, _, _)| id.clone())
1367        .collect();
1368    let atts_by_event = super::attachments::get_attachments_for_events(&file_ids).unwrap_or_default();
1369
1370    // Decrypt and build contexts
1371    let mut contexts = HashMap::new();
1372    crate::crypto::open_batch(|at_rest| {
1373        for (id, kind, original_content, npub, tags) in events {
1374            let has_attachment = kind == event_kind::FILE_ATTACHMENT as i32;
1375            let latest_edit = latest_edits.get(&id);
1376            let content_to_decrypt = latest_edit
1377                .map(|(c, _)| c.clone())
1378                .unwrap_or(original_content);
1379
1380            // Same rule as the message loader: an edit's tags replace the
1381            // original's, so the quote's emoji match the content it shows.
1382            let parse_emoji = |json: &Option<String>| -> Vec<crate::types::EmojiTag> {
1383                json.as_deref()
1384                    .and_then(|t| serde_json::from_str::<Vec<Vec<String>>>(t).ok())
1385                    .map(|parsed| crate::types::EmojiTag::extract_from_stored(&parsed))
1386                    .unwrap_or_default()
1387            };
1388            let emoji_tags = match latest_edit {
1389                Some((_, edit_tags)) => parse_emoji(edit_tags),
1390                None => parse_emoji(&tags),
1391            };
1392
1393            let decrypted_content = if kind == event_kind::CHAT_MESSAGE as i32
1394                || kind == event_kind::PRIVATE_DIRECT_MESSAGE as i32
1395            {
1396                at_rest.open(content_to_decrypt)
1397                    .unwrap_or_else(|_| "[Decryption failed]".to_string())
1398            } else {
1399                String::new()
1400            };
1401
1402            // The first attachment's extension lets the quote show the file type. From the table, with a
1403            // legacy-tag fallback for an un-backfilled pre-migration row.
1404            let extension = if has_attachment {
1405                atts_by_event.get(&id)
1406                    .and_then(|atts| atts.first())
1407                    .map(|a| a.extension.to_lowercase())
1408                    .filter(|e| !e.is_empty())
1409                    .or_else(|| tags.as_deref()
1410                        .and_then(|t| serde_json::from_str::<Vec<Vec<String>>>(t).ok())
1411                        .and_then(|parsed| parsed.into_iter()
1412                            .find(|t| t.first().map(|k| k == "attachments").unwrap_or(false))
1413                            .and_then(|t| t.into_iter().nth(1)))
1414                        .and_then(|json| serde_json::from_str::<Vec<serde_json::Value>>(&json).ok())
1415                        .and_then(|atts| atts.into_iter().next())
1416                        .and_then(|a| a.get("extension").and_then(|e| e.as_str()).map(str::to_lowercase))
1417                        .filter(|e| !e.is_empty()))
1418            } else {
1419                None
1420            };
1421
1422            contexts.insert(id, ReplyContext { content: decrypted_content, npub, has_attachment, extension, emoji_tags });
1423        }
1424    });
1425
1426    Ok(contexts)
1427}
1428
1429/// Populate reply context for a PAGE of messages in one query — the sync/back-page
1430/// counterpart to [`populate_reply_context`]. Every path that emits a message straight to
1431/// the UI must resolve the quote first: the frontend renders the emitted payload, and a
1432/// reply whose parent lies outside the rendered window has no other source for it (a
1433/// parent inside the window is resolved from memory instead). Messages whose parent isn't
1434/// persisted yet are left untouched.
1435pub async fn populate_reply_contexts(messages: Vec<&mut Message>) -> Result<(), String> {
1436    let ids: Vec<String> = messages
1437        .iter()
1438        .filter(|m| !m.replied_to.is_empty())
1439        .map(|m| m.replied_to.clone())
1440        .collect();
1441    if ids.is_empty() {
1442        return Ok(());
1443    }
1444    let contexts = get_reply_contexts(&ids).await?;
1445    for message in messages {
1446        if let Some(ctx) = contexts.get(&message.replied_to) {
1447            message.replied_to_content = Some(ctx.content.clone());
1448            message.replied_to_npub = ctx.npub.clone();
1449            message.replied_to_has_attachment = Some(ctx.has_attachment);
1450            message.replied_to_attachment_extension = ctx.extension.clone();
1451            message.replied_to_emoji_tags = if ctx.emoji_tags.is_empty() { None } else { Some(ctx.emoji_tags.clone()) };
1452        }
1453    }
1454    Ok(())
1455}
1456
1457/// Populate reply context for a single message.
1458/// Used for real-time messages that don't go through get_message_views.
1459pub async fn populate_reply_context(message: &mut Message) -> Result<(), String> {
1460    if message.replied_to.is_empty() {
1461        return Ok(());
1462    }
1463
1464    let contexts = get_reply_contexts(std::slice::from_ref(&message.replied_to)).await?;
1465
1466    if let Some(ctx) = contexts.get(&message.replied_to) {
1467        message.replied_to_content = Some(ctx.content.clone());
1468        message.replied_to_npub = ctx.npub.clone();
1469        message.replied_to_has_attachment = Some(ctx.has_attachment);
1470        message.replied_to_attachment_extension = ctx.extension.clone();
1471        message.replied_to_emoji_tags = if ctx.emoji_tags.is_empty() { None } else { Some(ctx.emoji_tags.clone()) };
1472    }
1473
1474    Ok(())
1475}
1476
1477/// Whether `event_id` is one of our own messages (`mine = 1`). A reply to our
1478/// own message is an implicit ping, so notifications treat it like a direct
1479/// @mention (breaks through a muted channel). Missing row → not ours → false.
1480pub fn is_own_event(event_id: &str) -> bool {
1481    let Ok(conn) = super::get_db_connection_guard_static() else {
1482        return false;
1483    };
1484    conn.query_row(
1485        "SELECT mine FROM events WHERE id = ?1",
1486        [event_id],
1487        |row| row.get::<_, i64>(0),
1488    )
1489    .map(|mine| mine == 1)
1490    .unwrap_or(false)
1491}
1492
1493// ============================================================================
1494// Message Views — compose full Messages from events + reactions + edits
1495// ============================================================================
1496
1497/// Extract a single tag value from raw tags JSON without full allocation.
1498fn extract_tag_from_json(tags_json: &str, key: &str) -> Option<String> {
1499    if tags_json.len() <= 2 { return None; }
1500    let pattern = format!("[\"{}\"", key);
1501    if !tags_json.contains(&pattern) { return None; }
1502    let tags: Vec<Vec<String>> = serde_json::from_str(tags_json).ok()?;
1503    tags.into_iter()
1504        .find(|tag| tag.first().map(|s| s.as_str()) == Some(key))
1505        .and_then(|tag| tag.into_iter().nth(1))
1506}
1507
1508/// A stored message's time in ms from raw tags JSON, as [`StoredEvent::timestamp_ms`] reads it.
1509fn stored_at_ms(created_at: u64, tags_json: &str) -> u64 {
1510    let ms = extract_tag_from_json(tags_json, "ms").and_then(|s| s.parse::<u64>().ok()).filter(|ms| *ms <= 999);
1511    created_at * 1000 + ms.unwrap_or(0)
1512}
1513
1514
1515/// A stored reaction author written as 64-char hex (an early v2 ingest) reads
1516/// back as the npub the frontend contract expects — self-heals old rows with no
1517/// migration; a bech32 or unknown value passes through untouched.
1518fn normalize_reaction_author(author: String) -> String {
1519    if author.len() == 64 && author.bytes().all(|b| b.is_ascii_hexdigit()) {
1520        if let Ok(pk) = nostr_sdk::prelude::PublicKey::from_hex(&author) {
1521            use nostr_sdk::prelude::ToBech32;
1522            let Ok(npub) = pk.to_bech32();
1523            return npub;
1524        }
1525    }
1526    author
1527}
1528/// Extract the NIP-30 `["emoji", shortcode, url]` URL from a stored
1529/// reaction's tags. The reaction's content must be `:shortcode:` form
1530/// and the matching tag's shortcode must agree — otherwise we get the
1531/// URL of a stray emoji tag that doesn't actually represent the
1532/// reaction's chosen emoji.
1533fn extract_reaction_emoji_url(tags: &[Vec<String>], content: &str) -> Option<String> {
1534    if !content.starts_with(':') || !content.ends_with(':') || content.len() < 3 {
1535        return None;
1536    }
1537    let sc = &content[1..content.len() - 1];
1538    tags.iter().find_map(|t| {
1539        if t.len() >= 3 && t[0] == "emoji" && t[1] == sc {
1540            Some(t[2].clone())
1541        } else {
1542            None
1543        }
1544    })
1545}
1546
1547/// Extract a NIP-10 reply reference ("e" tag with "reply" marker at position 3).
1548fn extract_reply_tag_from_json(tags_json: &str) -> Option<String> {
1549    if tags_json.len() <= 2 { return None; }
1550    if !tags_json.contains("[\"e\"") { return None; }
1551    let tags: Vec<Vec<String>> = serde_json::from_str(tags_json).ok()?;
1552    tags.into_iter()
1553        .find(|tag| {
1554            tag.first().map(|s| s.as_str()) == Some("e")
1555                && tag.get(3).map(|s| s.as_str()) == Some("reply")
1556        })
1557        .and_then(|tag| tag.into_iter().nth(1))
1558}
1559
1560/// Get message events with reactions, edits, and attachments composed.
1561///
1562/// This is the main "get messages" function. Queries events, fetches related
1563/// reactions/edits, parses attachments, applies edits, resolves reply context.
1564pub async fn get_message_views(
1565    chat_id: i64,
1566    limit: usize,
1567    offset: usize,
1568) -> Result<Vec<Message>, String> {
1569    // Step 1: Get message events (kind 9, 14, 15)
1570    let message_kinds = [event_kind::CHAT_MESSAGE, event_kind::PRIVATE_DIRECT_MESSAGE, event_kind::FILE_ATTACHMENT];
1571    let message_events = get_events(chat_id, Some(&message_kinds), limit, offset).await?;
1572
1573    compose_message_views(message_events).await
1574}
1575
1576/// Compose Message views from already-fetched message events (kind 9/14/15):
1577/// fetch related reactions/edits, parse attachments, apply edits, resolve reply
1578/// context. Shared by `get_message_views` (offset pager) and `get_messages_around`
1579/// (anchored window). Input order is preserved in the output.
1580async fn compose_message_views(message_events: Vec<StoredEvent>) -> Result<Vec<Message>, String> {
1581    use std::collections::HashMap;
1582
1583    if message_events.is_empty() {
1584        return Ok(Vec::new());
1585    }
1586
1587    // Step 2: Get related events (reactions, edits)
1588    let message_ids: Vec<String> = message_events.iter().map(|e| e.id.clone()).collect();
1589    let related_events = get_related_events(&message_ids).await?;
1590
1591    let mut reactions_by_msg: HashMap<String, Vec<Reaction>> = HashMap::new();
1592    let mut edits_by_msg: HashMap<String, Vec<FoldedEdit>> = HashMap::new();
1593
1594    crate::crypto::open_batch(|at_rest| {
1595        for event in related_events {
1596            if let Some(ref_id) = &event.reference_id {
1597                match event.kind {
1598                    k if k == event_kind::REACTION && crate::types::is_renderable_reaction(&event.content) => {
1599                        let emoji_url = extract_reaction_emoji_url(&event.tags, &event.content);
1600                        let reaction = Reaction {
1601                            id: event.id.clone(),
1602                            reference_id: ref_id.clone(),
1603                            author_id: normalize_reaction_author(event.npub.clone().unwrap_or_default()),
1604                            emoji: event.content.clone(),
1605                            emoji_url,
1606                        };
1607                        // Rows predating the (author, emoji) rule — or written by a client
1608                        // that never had it — must not resurrect a double count on reload.
1609                        let slot = reactions_by_msg.entry(ref_id.clone()).or_default();
1610                        if !slot.iter().any(|r| r.same_slot(&reaction)) {
1611                            slot.push(reaction);
1612                        }
1613                    }
1614                    k if k == event_kind::MESSAGE_EDIT => {
1615                        let decrypted = at_rest.open(event.content.clone())
1616                            .unwrap_or_else(|_| event.content.clone());
1617                        let edit_emoji = crate::types::EmojiTag::extract_from_stored(&event.tags);
1618                        let edit_spans = crate::text_spans::from_stored(&event.tags, &decrypted);
1619                        edits_by_msg.entry(ref_id.clone()).or_default().push((event.created_at * 1000 + ms_tag(&event.tags), decrypted, edit_emoji, edit_spans));
1620                    }
1621                    _ => {}
1622                }
1623            }
1624        }
1625    });
1626
1627    for edits in edits_by_msg.values_mut() {
1628        edits.sort_by_key(|(ts, _, _, _)| *ts);
1629    }
1630
1631    // Step 3: Attachments from the dedicated table (batched), with a legacy-tag fallback for any
1632    // file event not represented in the table (an un-backfilled pre-migration row).
1633    let attach_ids: Vec<String> = message_events.iter()
1634        .filter(|e| e.kind == event_kind::FILE_ATTACHMENT || e.kind == event_kind::CHAT_MESSAGE)
1635        .map(|e| e.id.clone())
1636        .collect();
1637    let mut attachments_by_msg = super::attachments::get_attachments_for_events(&attach_ids)
1638        .unwrap_or_default();
1639    for event in &message_events {
1640        if event.kind != event_kind::FILE_ATTACHMENT && event.kind != event_kind::CHAT_MESSAGE {
1641            continue;
1642        }
1643        if attachments_by_msg.contains_key(&event.id) {
1644            continue;
1645        }
1646        if let Some(json) = event.get_tag("attachments") {
1647            if let Ok(atts) = serde_json::from_str::<Vec<Attachment>>(json) {
1648                if !atts.is_empty() {
1649                    attachments_by_msg.insert(event.id.clone(), atts);
1650                }
1651            }
1652        }
1653    }
1654
1655    // Step 4: Compose Message structs
1656    let mut messages = Vec::with_capacity(message_events.len());
1657    for event in message_events {
1658        let replied_to = event.get_reply_reference().unwrap_or("").to_string();
1659        let at = event.timestamp_ms();
1660        let reactions = reactions_by_msg.remove(&event.id).unwrap_or_default();
1661        let attachments = attachments_by_msg.remove(&event.id).unwrap_or_default();
1662
1663        let original_content = if event.kind == event_kind::FILE_ATTACHMENT {
1664            String::new()
1665        } else {
1666            event.content.clone()
1667        };
1668
1669        // Edits carry their own emoji tags; the newest edit's tags win so the
1670        // displayed (latest) content renders its custom emoji, not the original's.
1671        let original_emoji = crate::types::EmojiTag::extract_from_stored(&event.tags);
1672        let original_spans = crate::text_spans::from_stored(&event.tags, &original_content);
1673        let (content, edited, edit_history, emoji_tags, text_spans) = if let Some(edits) = edits_by_msg.remove(&event.id) {
1674            let mut history = Vec::with_capacity(edits.len() + 1);
1675            history.push(crate::types::EditEntry { content: original_content.clone(), edited_at: at });
1676            for (ts, c, _, _) in &edits {
1677                history.push(crate::types::EditEntry { content: c.clone(), edited_at: *ts });
1678            }
1679            let (latest, latest_emoji, latest_spans) = edits.last()
1680                .map(|(_, c, e, s)| (c.clone(), e.clone(), s.clone()))
1681                .unwrap_or_else(|| (original_content.clone(), original_emoji.clone(), original_spans.clone()));
1682            (latest, true, Some(history), latest_emoji, latest_spans)
1683        } else {
1684            (original_content, false, None, original_emoji, original_spans)
1685        };
1686
1687        let preview_metadata = event.preview_metadata
1688            .and_then(|json| serde_json::from_str(&crate::crypto::maybe_decrypt_text(&json)).ok());
1689
1690        let addressed_bots = extract_bot_tags(&event.tags);
1691        let expiration = extract_expiration_tag(&event.tags);
1692        messages.push(Message {
1693            expiration,
1694            id: event.id, content, replied_to,
1695            replied_to_content: None, replied_to_npub: None, replied_to_has_attachment: None,
1696            replied_to_attachment_extension: None, replied_to_emoji_tags: None,
1697            preview_metadata, attachments, reactions, at,
1698            pending: event.pending, failed: event.failed, mine: event.mine,
1699            npub: event.npub, wrapper_event_id: event.wrapper_event_id,
1700            edited, edit_history,
1701            emoji_tags,
1702            addressed_bots,
1703            text_spans,
1704            role_mentions: crate::community::mentions::from_stored(&event.tags),
1705            writer: carried_by_writer(&event.tags),
1706            unauthorized: held_unauthorized(&event.tags),
1707        });
1708    }
1709
1710    // Rows whose NIP-40 expiry passed while out of STATE (app closed, chat
1711    // unopened) must never reach a renderer — strip them here, at the single
1712    // DB→Message chokepoint, and purge their remnants in the background.
1713    crate::self_destruct::strip_expired(&mut messages);
1714
1715    // Step 5: Reply context
1716    let reply_ids: Vec<String> = messages.iter()
1717        .filter(|m| !m.replied_to.is_empty())
1718        .map(|m| m.replied_to.clone())
1719        .collect();
1720
1721    if !reply_ids.is_empty() {
1722        let contexts = get_reply_contexts(&reply_ids).await?;
1723        for msg in &mut messages {
1724            if let Some(ctx) = contexts.get(&msg.replied_to) {
1725                msg.replied_to_content = Some(ctx.content.clone());
1726                msg.replied_to_npub = ctx.npub.clone();
1727                msg.replied_to_has_attachment = Some(ctx.has_attachment);
1728                msg.replied_to_attachment_extension = ctx.extension.clone();
1729                msg.replied_to_emoji_tags = if ctx.emoji_tags.is_empty() { None } else { Some(ctx.emoji_tags.clone()) };
1730            }
1731        }
1732    }
1733
1734    Ok(messages)
1735}
1736
1737/// Anchored (random-access) message window: load `before` messages up to and
1738/// including the anchor, plus `after` messages strictly newer than it. O(window)
1739/// regardless of how deep the anchor sits in the chat — unlike the offset pager,
1740/// which is O(depth) to reach a far-back message.
1741///
1742/// Returns ASC by `created_at` (oldest first), composed with reactions/edits/
1743/// attachments. Errs if the anchor id isn't in the DB so the caller can fall back.
1744/// One message by its id, composed exactly as the pagers compose theirs —
1745/// attachments, reactions, edits and reply context — with the chat it was said
1746/// in. A citation names a message, never the room, so the room comes back too.
1747///
1748/// `None` is an ordinary answer: a citation outlives its message (a delete, a
1749/// moderation hide, an expiry, or simply history this account never synced),
1750/// and a resolver that errored on absence would make every one of those a fault.
1751pub async fn get_message_by_id(message_id: &str) -> Result<Option<(String, Message)>, String> {
1752    let kinds = [event_kind::CHAT_MESSAGE, event_kind::PRIVATE_DIRECT_MESSAGE, event_kind::FILE_ATTACHMENT]
1753        .map(|k| k.to_string())
1754        .join(",");
1755    let found = {
1756        let conn = super::get_db_connection_guard_static()?;
1757        // Column order matches `parse_event_row`; the chat identifier rides along at 15.
1758        let sql = format!(
1759            "SELECT e.id, e.kind, e.chat_id, e.user_id, e.content, e.tags, e.reference_id, \
1760             e.created_at, e.received_at, e.mine, e.pending, e.failed, e.wrapper_event_id, e.npub, \
1761             e.preview_metadata, c.chat_identifier \
1762             FROM events e JOIN chats c ON c.id = e.chat_id \
1763             WHERE e.id = ?1 AND e.kind IN ({kinds})"
1764        );
1765        let mut stmt = conn.prepare(&sql).map_err(|e| format!("prepare get_message_by_id: {e}"))?;
1766        stmt.query_row(rusqlite::params![message_id], |r| Ok((parse_event_row(r)?, r.get::<_, String>(15)?)))
1767            .optional()
1768            .map_err(|e| format!("query get_message_by_id: {e}"))?
1769    };
1770    let Some((mut event, chat_identifier)) = found else { return Ok(None) };
1771    if event.kind == event_kind::CHAT_MESSAGE || event.kind == event_kind::PRIVATE_DIRECT_MESSAGE {
1772        event.content = crate::crypto::open_batch(|at_rest| at_rest.open(event.content))
1773            .unwrap_or_else(|_| "[Decryption failed]".to_string());
1774    }
1775    Ok(compose_message_views(vec![event]).await?.pop().map(|m| (chat_identifier, m)))
1776}
1777
1778/// Where a message is on this device: the chat it was said in, or whether it was deleted here.
1779#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
1780pub struct MessageLocation {
1781    pub chat: Option<String>,
1782    pub deleted: bool,
1783}
1784
1785/// Locate a message without opening its content. A banned author's message reads as absent,
1786/// as it does on screen.
1787pub fn locate_message(message_id: &str) -> Result<MessageLocation, String> {
1788    let conn = super::get_db_connection_guard_static()?;
1789    let found = conn
1790        .query_row(
1791            "SELECT c.chat_identifier, e.chat_id, e.npub FROM events e JOIN chats c ON c.id = e.chat_id \
1792             WHERE e.id = ?1 AND e.kind IN (9, 14, 15)",
1793            rusqlite::params![message_id],
1794            |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?, r.get::<_, Option<String>>(2)?)),
1795        )
1796        .optional()
1797        .map_err(|e| format!("query locate_message: {e}"))?;
1798    let chat = found.and_then(|(chat, chat_id, npub)| {
1799        let banned = npub.as_deref().and_then(|n| nostr_sdk::prelude::PublicKey::parse(n).ok()).is_some_and(|author| {
1800            community_of_chat(&conn, chat_id).is_some_and(|c| super::community::banned_set(&c).contains(&author.to_bytes()))
1801        });
1802        (!banned).then_some(chat)
1803    });
1804    let deleted = chat.is_none()
1805        && conn
1806            .query_row("SELECT 1 FROM deleted_messages WHERE event_id = ?1", rusqlite::params![message_id], |_| Ok(()))
1807            .optional()
1808            .map_err(|e| format!("query locate_message tombstone: {e}"))?
1809            .is_some();
1810    Ok(MessageLocation { chat, deleted })
1811}
1812
1813pub async fn get_messages_around(
1814    chat_id: i64,
1815    anchor_id: &str,
1816    before: usize,
1817    after: usize,
1818) -> Result<Vec<Message>, String> {
1819    let message_kinds = [event_kind::CHAT_MESSAGE, event_kind::PRIVATE_DIRECT_MESSAGE, event_kind::FILE_ATTACHMENT];
1820
1821    let message_events: Vec<StoredEvent> = {
1822        let conn = super::get_db_connection_guard_static()?;
1823        let community = ban_param(&conn, chat_id);
1824
1825        // Resolve the anchor's FULL sort key (created_at, received_at, rowid). Paging by created_at
1826        // alone wedges on a wall of equal timestamps (a message burst): the query keeps returning the
1827        // same newest-N of the cluster, so back-paging stalls before reaching older history. The
1828        // (received_at, rowid) tiebreak — rowid being the unique final key — gives a strict total
1829        // order, so every page steps strictly past the previous, through any same-timestamp cluster.
1830        let (anchor_at, anchor_rt, anchor_rowid): (i64, i64, i64) = conn.query_row(
1831            "SELECT created_at, received_at, rowid FROM events WHERE id = ?1",
1832            rusqlite::params![anchor_id],
1833            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
1834        ).map_err(|e| format!("Anchor message not found: {}", e))?;
1835
1836        // Kinds occupy ?2..?4; then ?5 created_at, ?6 received_at, ?7 rowid, ?8 limit.
1837        let kind_placeholders: String = (0..message_kinds.len())
1838            .map(|i| format!("?{}", i + 2))
1839            .collect::<Vec<_>>()
1840            .join(",");
1841        let cols = "id, kind, chat_id, user_id, content, tags, reference_id, \
1842                    created_at, received_at, mine, pending, failed, wrapper_event_id, npub, preview_metadata";
1843
1844        // Older incl. anchor: strict key <= anchor key; newest-first then reverse to ASC.
1845        let older_sql = format!(
1846            "SELECT {} FROM events WHERE chat_id = ?1 AND kind IN ({}) \
1847             AND (created_at < ?5 OR (created_at = ?5 AND (received_at < ?6 \
1848                  OR (received_at = ?6 AND rowid <= ?7)))) \
1849             {} ORDER BY created_at DESC, received_at DESC, rowid DESC LIMIT ?8",
1850            cols, kind_placeholders, ban_filter_sql(9)
1851        );
1852        let mut older_stmt = conn.prepare(&older_sql)
1853            .map_err(|e| format!("Failed to prepare older window query: {}", e))?;
1854        let older_rows = older_stmt.query_map(
1855            rusqlite::params![
1856                chat_id,
1857                message_kinds[0] as i32, message_kinds[1] as i32, message_kinds[2] as i32,
1858                anchor_at, anchor_rt, anchor_rowid, before as i64, community
1859            ],
1860            parse_event_row,
1861        ).map_err(|e| format!("Failed to query older window: {}", e))?;
1862        let mut older: Vec<StoredEvent> = older_rows.filter_map(|r| r.ok()).collect();
1863        older.reverse(); // DESC -> ASC
1864
1865        // Newer: strictly after the anchor key.
1866        let newer_sql = format!(
1867            "SELECT {} FROM events WHERE chat_id = ?1 AND kind IN ({}) \
1868             AND (created_at > ?5 OR (created_at = ?5 AND (received_at > ?6 \
1869                  OR (received_at = ?6 AND rowid > ?7)))) \
1870             {} ORDER BY created_at ASC, received_at ASC, rowid ASC LIMIT ?8",
1871            cols, kind_placeholders, ban_filter_sql(9)
1872        );
1873        let mut newer_stmt = conn.prepare(&newer_sql)
1874            .map_err(|e| format!("Failed to prepare newer window query: {}", e))?;
1875        let newer_rows = newer_stmt.query_map(
1876            rusqlite::params![
1877                chat_id,
1878                message_kinds[0] as i32, message_kinds[1] as i32, message_kinds[2] as i32,
1879                anchor_at, anchor_rt, anchor_rowid, after as i64, community
1880            ],
1881            parse_event_row,
1882        ).map_err(|e| format!("Failed to query newer window: {}", e))?;
1883        let newer: Vec<StoredEvent> = newer_rows.filter_map(|r| r.ok()).collect();
1884
1885        older.into_iter().chain(newer).collect()
1886    };
1887
1888    // Decrypt message content (mirror get_events).
1889    let decrypted: Vec<StoredEvent> = crate::crypto::open_batch(|at_rest| message_events.into_iter().map(|mut event| {
1890        if event.kind == event_kind::CHAT_MESSAGE || event.kind == event_kind::PRIVATE_DIRECT_MESSAGE {
1891            event.content = at_rest.open(event.content)
1892                .unwrap_or_else(|_| "[Decryption failed]".to_string());
1893        }
1894        event
1895    }).collect());
1896
1897    compose_message_views(decrypted).await
1898}
1899
1900/// Where a message sits in its chat: how many messages sort after it and how many there are,
1901/// in the order and under the ban filter `get_messages_around` uses. None when it isn't held.
1902#[derive(serde::Serialize, Debug, PartialEq, Eq)]
1903pub struct MessagePosition {
1904    pub newer: usize,
1905    pub total: usize,
1906}
1907
1908pub fn get_message_position(chat_id: i64, anchor_id: &str) -> Result<Option<MessagePosition>, String> {
1909    use rusqlite::OptionalExtension;
1910    let k = [event_kind::CHAT_MESSAGE, event_kind::PRIVATE_DIRECT_MESSAGE, event_kind::FILE_ATTACHMENT].map(|k| k as i32);
1911    let conn = super::get_db_connection_guard_static()?;
1912    let community = ban_param(&conn, chat_id);
1913    let Some((at, rt, rowid)) = conn.query_row(
1914        "SELECT created_at, received_at, rowid FROM events WHERE id = ?1 AND chat_id = ?2",
1915        rusqlite::params![anchor_id, chat_id],
1916        |row| Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?, row.get::<_, i64>(2)?)),
1917    ).optional().map_err(|e| format!("Failed to find message: {}", e))? else {
1918        return Ok(None);
1919    };
1920    let kinds = "chat_id = ?1 AND kind IN (?2, ?3, ?4)";
1921    let newer: i64 = conn.query_row(
1922        &format!(
1923            "SELECT COUNT(*) FROM events WHERE {kinds} \
1924             AND (created_at > ?5 OR (created_at = ?5 AND (received_at > ?6 OR (received_at = ?6 AND rowid > ?7)))){}",
1925            ban_filter_sql(8)
1926        ),
1927        rusqlite::params![chat_id, k[0], k[1], k[2], at, rt, rowid, community],
1928        |row| row.get(0),
1929    ).map_err(|e| format!("Failed to count messages: {}", e))?;
1930    let total: i64 = conn.query_row(
1931        &format!("SELECT COUNT(*) FROM events WHERE {kinds}{}", ban_filter_sql(5)),
1932        rusqlite::params![chat_id, k[0], k[1], k[2], community],
1933        |row| row.get(0),
1934    ).map_err(|e| format!("Failed to count messages: {}", e))?;
1935    Ok(Some(MessagePosition { newer: newer as usize, total: total as usize }))
1936}
1937
1938/// When the message `newer` places from the newest was sent (ms, to the second), in the order and
1939/// under the ban filter of `get_message_position`. None past the oldest.
1940pub fn get_message_time_at(chat_id: i64, newer: usize) -> Result<Option<u64>, String> {
1941    use rusqlite::OptionalExtension;
1942    let k = [event_kind::CHAT_MESSAGE, event_kind::PRIVATE_DIRECT_MESSAGE, event_kind::FILE_ATTACHMENT].map(|k| k as i32);
1943    let conn = super::get_db_connection_guard_static()?;
1944    let community = ban_param(&conn, chat_id);
1945    conn.query_row(
1946        &format!(
1947            "SELECT created_at FROM events WHERE chat_id = ?1 AND kind IN (?2, ?3, ?4){} \
1948             ORDER BY created_at DESC, received_at DESC, rowid DESC LIMIT 1 OFFSET ?6",
1949            ban_filter_sql(5)
1950        ),
1951        rusqlite::params![chat_id, k[0], k[1], k[2], community, newer as i64],
1952        |row| row.get::<_, i64>(0),
1953    ).optional()
1954        .map(|at| at.map(|s| s.max(0) as u64 * 1000))
1955        .map_err(|e| format!("Failed to read message time: {}", e))
1956}
1957
1958/// Get the last message for ALL chats in a single batch query.
1959/// Optimized for app startup (chat list sidebar).
1960pub async fn get_all_chats_last_messages() -> Result<std::collections::HashMap<String, Vec<Message>>, String> {
1961    use std::collections::HashMap;
1962
1963    // Step 1: each chat's newest message. The query returns every message of the chat's newest
1964    // second and the ms tag picks among them, as the chat view orders them: a preview that differs
1965    // from the view's newest leaves a read marker it can't find, and the chat badges unread.
1966    let message_events: Vec<(String, StoredEvent, String)> = {
1967        let conn = super::get_db_connection_guard_static()?;
1968        let mut stmt = conn.prepare(
1969            "SELECT c.chat_identifier, \
1970             e.id, e.kind, e.chat_id, e.user_id, e.content, e.tags, e.reference_id, \
1971             e.created_at, e.received_at, e.mine, e.pending, e.failed, e.wrapper_event_id, e.npub, e.preview_metadata, e.rowid \
1972             FROM chats c JOIN events e ON e.chat_id = c.id AND e.created_at = ( \
1973                 SELECT e2.created_at FROM events e2 WHERE e2.chat_id = c.id \
1974                 AND e2.kind IN (?1, ?2, ?3) AND instr(e2.tags, '[\"unauthorized\"]') = 0 \
1975                 ORDER BY e2.created_at DESC LIMIT 1) \
1976             WHERE c.chat_type != 1 AND e.kind IN (?1, ?2, ?3) AND instr(e.tags, '[\"unauthorized\"]') = 0"
1977        ).map_err(|e| format!("Failed to prepare: {}", e))?;
1978
1979        let rows = stmt.query_map(
1980            rusqlite::params![
1981                event_kind::CHAT_MESSAGE as i32,
1982                event_kind::PRIVATE_DIRECT_MESSAGE as i32,
1983                event_kind::FILE_ATTACHMENT as i32
1984            ],
1985            |row| {
1986                let chat_id: String = row.get(0)?;
1987                let tags_json: String = row.get(6)?;
1988                let event = StoredEvent {
1989                    id: row.get(1)?, kind: row.get::<_, i32>(2)? as u16,
1990                    chat_id: row.get(3)?, user_id: row.get(4)?, content: row.get(5)?,
1991                    tags: Vec::new(), // Deferred — parsed on-demand
1992                    reference_id: row.get(7)?,
1993                    created_at: row.get::<_, i64>(8)? as u64, received_at: row.get::<_, i64>(9)? as u64,
1994                    mine: row.get::<_, i32>(10)? != 0, pending: row.get::<_, i32>(11)? != 0,
1995                    failed: row.get::<_, i32>(12)? != 0, wrapper_event_id: row.get(13)?,
1996                    npub: row.get(14)?, preview_metadata: row.get(15)?,
1997                };
1998                Ok((chat_id, event, tags_json, row.get::<_, i64>(16)?))
1999            }
2000        ).map_err(|e| format!("Failed to query: {}", e))?;
2001        let mut newest: HashMap<String, ((u64, u64, i64), StoredEvent, String)> = HashMap::new();
2002        for (chat_id, event, tags_json, rowid) in rows.filter_map(|r| r.ok()) {
2003            let key = (stored_at_ms(event.created_at, &tags_json), event.received_at, rowid);
2004            match newest.get(&chat_id) {
2005                Some((held, _, _)) if *held >= key => {}
2006                _ => { newest.insert(chat_id, (key, event, tags_json)); }
2007            }
2008        }
2009        newest.into_iter().map(|(chat_id, (_, event, tags_json))| (chat_id, event, tags_json)).collect()
2010    };
2011
2012    if message_events.is_empty() {
2013        return Ok(HashMap::new());
2014    }
2015
2016    // Step 2: Related events (reactions, edits)
2017    let message_ids: Vec<String> = message_events.iter().map(|(_, e, _)| e.id.clone()).collect();
2018    let related_events = get_related_events(&message_ids).await?;
2019
2020    let mut reactions_by_msg: HashMap<String, Vec<Reaction>> = HashMap::new();
2021    let mut edits_by_msg: HashMap<String, Vec<FoldedEdit>> = HashMap::new();
2022
2023    crate::crypto::open_batch(|at_rest| {
2024        for event in related_events {
2025            if let Some(ref_id) = &event.reference_id {
2026                match event.kind {
2027                    k if k == event_kind::REACTION && crate::types::is_renderable_reaction(&event.content) => {
2028                        let emoji_url = extract_reaction_emoji_url(&event.tags, &event.content);
2029                        let reaction = Reaction {
2030                            id: event.id.clone(), reference_id: ref_id.clone(),
2031                            author_id: normalize_reaction_author(event.npub.clone().unwrap_or_default()),
2032                            emoji: event.content.clone(),
2033                            emoji_url,
2034                        };
2035                        // Rows predating the (author, emoji) rule — or written by a client
2036                        // that never had it — must not resurrect a double count on reload.
2037                        let slot = reactions_by_msg.entry(ref_id.clone()).or_default();
2038                        if !slot.iter().any(|r| r.same_slot(&reaction)) {
2039                            slot.push(reaction);
2040                        }
2041                    }
2042                    k if k == event_kind::MESSAGE_EDIT => {
2043                        let decrypted = at_rest.open(event.content.clone())
2044                            .unwrap_or_else(|_| event.content.clone());
2045                        let edit_emoji = crate::types::EmojiTag::extract_from_stored(&event.tags);
2046                        let edit_spans = crate::text_spans::from_stored(&event.tags, &decrypted);
2047                        edits_by_msg.entry(ref_id.clone()).or_default().push((event.created_at * 1000 + ms_tag(&event.tags), decrypted, edit_emoji, edit_spans));
2048                    }
2049                    _ => {}
2050                }
2051            }
2052        }
2053    });
2054    for edits in edits_by_msg.values_mut() {
2055        edits.sort_by_key(|(ts, _, _, _)| *ts);
2056    }
2057
2058    // Step 3: Attachments from the dedicated table (batched), with a legacy-tag fallback.
2059    let attach_ids: Vec<String> = message_events.iter()
2060        .filter(|(_, e, _)| e.kind == event_kind::FILE_ATTACHMENT || e.kind == event_kind::CHAT_MESSAGE)
2061        .map(|(_, e, _)| e.id.clone())
2062        .collect();
2063    let mut attachments_by_msg = super::attachments::get_attachments_for_events(&attach_ids)
2064        .unwrap_or_default();
2065    for (_, event, tags_json) in &message_events {
2066        if event.kind != event_kind::FILE_ATTACHMENT && event.kind != event_kind::CHAT_MESSAGE {
2067            continue;
2068        }
2069        if attachments_by_msg.contains_key(&event.id) {
2070            continue;
2071        }
2072        if let Some(val) = extract_tag_from_json(tags_json, "attachments") {
2073            if let Ok(atts) = serde_json::from_str::<Vec<Attachment>>(&val) {
2074                if !atts.is_empty() {
2075                    attachments_by_msg.insert(event.id.clone(), atts);
2076                }
2077            }
2078        }
2079    }
2080
2081    // Step 4: Compose Messages grouped by chat_identifier
2082    let mut result: HashMap<String, Vec<Message>> = HashMap::new();
2083
2084    crate::crypto::open_batch(|at_rest| {
2085        for (chat_identifier, event, tags_json) in message_events {
2086            let reactions = reactions_by_msg.remove(&event.id).unwrap_or_default();
2087            let attachments = attachments_by_msg.remove(&event.id).unwrap_or_default();
2088            let replied_to = extract_reply_tag_from_json(&tags_json).unwrap_or_default();
2089
2090            // Decrypt content
2091            let original_content = if event.kind == event_kind::CHAT_MESSAGE
2092                || event.kind == event_kind::PRIVATE_DIRECT_MESSAGE
2093            {
2094                at_rest.open(event.content.clone())
2095                    .unwrap_or_else(|_| "[Decryption failed]".to_string())
2096            } else {
2097                String::new()
2098            };
2099
2100            let stored_tags = serde_json::from_str::<Vec<Vec<String>>>(&tags_json).unwrap_or_default();
2101            let original_emoji = crate::types::EmojiTag::extract_from_stored(&stored_tags);
2102            let original_spans = crate::text_spans::from_stored(&stored_tags, &original_content);
2103            let addressed_bots = extract_bot_tags(&stored_tags);
2104            let expiration = extract_expiration_tag(&stored_tags);
2105            // Newest edit's emoji and colour tags win so the latest content renders correctly.
2106            let (content, edited, edit_history, emoji_tags, text_spans) = if let Some(edits) = edits_by_msg.remove(&event.id) {
2107                let (latest, latest_emoji, latest_spans) = edits.last()
2108                    .map(|(_, c, e, s)| (c.clone(), e.clone(), s.clone()))
2109                    .unwrap_or_else(|| (original_content.clone(), original_emoji.clone(), original_spans.clone()));
2110                let history: Vec<crate::types::EditEntry> = std::iter::once(crate::types::EditEntry {
2111                    content: original_content, edited_at: event.created_at * 1000,
2112                }).chain(edits.into_iter().map(|(ts, c, _, _)| crate::types::EditEntry { content: c, edited_at: ts }))
2113                .collect();
2114                (latest, true, Some(history), latest_emoji, latest_spans)
2115            } else {
2116                (original_content, false, None, original_emoji, original_spans)
2117            };
2118
2119            let preview_metadata = event.preview_metadata
2120                .and_then(|json| serde_json::from_str(&at_rest.open_or_keep(json)).ok());
2121
2122            result.entry(chat_identifier).or_default().push(Message {
2123                expiration,
2124                id: event.id, content, replied_to,
2125                replied_to_content: None, replied_to_npub: None, replied_to_has_attachment: None,
2126                replied_to_attachment_extension: None, replied_to_emoji_tags: None,
2127                preview_metadata, attachments, reactions, at: stored_at_ms(event.created_at, &tags_json),
2128                pending: event.pending, failed: event.failed, mine: event.mine,
2129                npub: event.npub, wrapper_event_id: event.wrapper_event_id,
2130                edited, edit_history,
2131                emoji_tags,
2132                addressed_bots,
2133                text_spans,
2134                role_mentions: crate::community::mentions::from_stored(&stored_tags),
2135                writer: carried_by_writer(&stored_tags),
2136                unauthorized: held_unauthorized(&stored_tags),
2137            });
2138        }
2139    });
2140
2141    // Step 5: Reply context — the openChat pre-paint renders this boot last-message
2142    // synchronously (before the richer get_message_views load lands), so without
2143    // context here a reply shows its quote only on the second open.
2144    let reply_ids: Vec<String> = result.values()
2145        .flatten()
2146        .filter(|m| !m.replied_to.is_empty())
2147        .map(|m| m.replied_to.clone())
2148        .collect();
2149
2150    if !reply_ids.is_empty() {
2151        let contexts = get_reply_contexts(&reply_ids).await?;
2152        for msg in result.values_mut().flatten() {
2153            if let Some(ctx) = contexts.get(&msg.replied_to) {
2154                msg.replied_to_content = Some(ctx.content.clone());
2155                msg.replied_to_npub = ctx.npub.clone();
2156                msg.replied_to_has_attachment = Some(ctx.has_attachment);
2157                msg.replied_to_attachment_extension = ctx.extension.clone();
2158                msg.replied_to_emoji_tags = if ctx.emoji_tags.is_empty() { None } else { Some(ctx.emoji_tags.clone()) };
2159            }
2160        }
2161    }
2162
2163    // An expired self-destruct as a chat's last message must not flash in the
2164    // chat list — strip + background-purge; the preview shows empty until the
2165    // next boot resolves the prior message, same as a mid-session sweep.
2166    for msgs in result.values_mut() {
2167        crate::self_destruct::strip_expired(msgs);
2168    }
2169
2170    Ok(result)
2171}
2172
2173/// Per-chat unread count, computed straight from the DB so it's correct even when only the last
2174/// message is in RAM (the boot state). Mirrors the in-memory walk-back exactly: unread = non-mine
2175/// messages newer than the most recent "anchor" (our own message OR the `last_read` marker,
2176/// whichever is latest). A never-read chat (empty `last_read`, no own message) counts all its
2177/// non-mine messages. Returns `chat_identifier → count`; chats with 0 unread are omitted.
2178/// CHAT-level muted/blocked filtering is left to the caller (it lives in RAM state, cheaply).
2179/// SENDER-level filtering happens here: a message whose author's DM is muted or whose profile
2180/// is blocked never counts, in any chat — muting a person silences their community messages too.
2181/// A member BANNED from a community likewise stops counting there: a ban that still badges the
2182/// channel sends the reader to look for a message the client will not render.
2183pub async fn unread_counts() -> Result<std::collections::HashMap<String, u32>, String> {
2184    let conn = super::get_db_connection_guard_static()?;
2185    let bans = all_ban_pairs_json(&conn);
2186    // Anchor: newest own message, or the chat's `last_read` event of any kind. An unset marker is
2187    // '' and must not match a stray empty-id event row. A max per kind reads
2188    // the end of idx_events_unread rather than the whole chat; MATERIALIZED runs each CTE once.
2189    // A "Mark as Unread" from a chosen message (`unread_from`) replaces the anchor: everything from
2190    // that message's second on counts (its whole second, like the anchor), own replies after it
2191    // notwithstanding. Seconds are integers, so `>= anchor + 1` is the `> anchor` cutoff in a form
2192    // the index can range-seek either way.
2193    let mut stmt = conn
2194        .prepare_cached(
2195            "WITH anchors AS MATERIALIZED ( \
2196                SELECT c.id AS chat_id, c.chat_identifier AS chat_identifier, MAX( \
2197                    COALESCE((SELECT MAX(created_at) FROM events WHERE chat_id = c.id AND mine = 1 AND kind = ?1), 0), \
2198                    COALESCE((SELECT MAX(created_at) FROM events WHERE chat_id = c.id AND mine = 1 AND kind = ?2), 0), \
2199                    COALESCE((SELECT MAX(created_at) FROM events WHERE chat_id = c.id AND mine = 1 AND kind = ?3), 0), \
2200                    COALESCE((SELECT created_at FROM events WHERE c.last_read != '' AND id = c.last_read AND chat_id = c.id), 0) \
2201                ) AS anchor_ts, \
2202                (SELECT created_at FROM events WHERE c.unread_from != '' AND id = c.unread_from AND chat_id = c.id) AS from_ts \
2203                FROM chats c \
2204             ), \
2205             counts AS MATERIALIZED ( \
2206                SELECT a.chat_identifier AS chat_identifier, ( \
2207                    SELECT COUNT(*) FROM events e \
2208                    WHERE e.chat_id = a.chat_id AND e.mine = 0 AND e.kind IN (?1, ?2, ?3) \
2209                      AND e.created_at >= COALESCE(a.from_ts, a.anchor_ts + 1) \
2210                      AND instr(e.tags, '[\"unauthorized\"]') = 0 \
2211                      AND (e.npub IS NULL OR e.npub NOT IN ( \
2212                            SELECT chat_identifier FROM chats WHERE muted = 1 \
2213                            UNION \
2214                            SELECT npub FROM profiles WHERE is_blocked = 1)) \
2215                      AND NOT EXISTS ( \
2216                            SELECT 1 FROM community_channels cc \
2217                            WHERE cc.channel_id = a.chat_identifier \
2218                              AND (cc.community_id || ' ' || e.npub) IN (SELECT value FROM json_each(?4))) \
2219                ) AS unread \
2220                FROM anchors a \
2221             ) \
2222             SELECT chat_identifier, unread FROM counts WHERE unread > 0",
2223        )
2224        .map_err(|e| format!("prepare unread_counts: {e}"))?;
2225    let rows = stmt
2226        .query_map(
2227            rusqlite::params![
2228                event_kind::CHAT_MESSAGE as i32,
2229                event_kind::PRIVATE_DIRECT_MESSAGE as i32,
2230                event_kind::FILE_ATTACHMENT as i32,
2231                bans
2232            ],
2233            |row| Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)? as u32)),
2234        )
2235        .map_err(|e| format!("query unread_counts: {e}"))?;
2236    let mut out = std::collections::HashMap::new();
2237    for r in rows.flatten() {
2238        out.insert(r.0, r.1);
2239    }
2240    Ok(out)
2241}
2242
2243/// Unread count for a SINGLE chat, same semantics as [`unread_counts`]. The RAM cache calls this to
2244/// reconcile one chat (open / delete / retreat) without recomputing every chat's count.
2245pub async fn unread_count_for_chat(chat_identifier: &str) -> Result<u32, String> {
2246    let conn = super::get_db_connection_guard_static()?;
2247    let bans = super::community::community_id_for_channel(chat_identifier)
2248        .ok()
2249        .flatten()
2250        .and_then(|cid| banned_npubs_json(&cid));
2251    let count: i64 = conn
2252        .prepare_cached(
2253            // `unread_counts`' anchor for one chat, computed once so the count range-seeks the index.
2254            "WITH a AS MATERIALIZED ( \
2255                SELECT c.id AS chat_id, MAX( \
2256                    COALESCE((SELECT MAX(created_at) FROM events WHERE chat_id = c.id AND mine = 1 AND kind = ?1), 0), \
2257                    COALESCE((SELECT MAX(created_at) FROM events WHERE chat_id = c.id AND mine = 1 AND kind = ?2), 0), \
2258                    COALESCE((SELECT MAX(created_at) FROM events WHERE chat_id = c.id AND mine = 1 AND kind = ?3), 0), \
2259                    COALESCE((SELECT created_at FROM events WHERE c.last_read != '' AND id = c.last_read AND chat_id = c.id), 0) \
2260                ) AS anchor_ts, \
2261                (SELECT created_at FROM events WHERE c.unread_from != '' AND id = c.unread_from AND chat_id = c.id) AS from_ts \
2262                FROM chats c WHERE c.chat_identifier = ?4 \
2263             ) \
2264             SELECT COUNT(*) FROM a JOIN events e ON e.chat_id = a.chat_id AND e.mine = 0 AND e.kind IN (?1, ?2, ?3) \
2265               AND e.created_at >= COALESCE(a.from_ts, a.anchor_ts + 1) \
2266             WHERE instr(e.tags, '[\"unauthorized\"]') = 0 \
2267               AND (e.npub IS NULL OR e.npub NOT IN ( \
2268                     SELECT chat_identifier FROM chats WHERE muted = 1 \
2269                     UNION \
2270                     SELECT npub FROM profiles WHERE is_blocked = 1)) \
2271               AND (?5 IS NULL OR e.npub IS NULL OR e.npub NOT IN (SELECT value FROM json_each(?5)))",
2272        )
2273        .and_then(|mut stmt| {
2274            stmt.query_row(
2275                rusqlite::params![
2276                    event_kind::CHAT_MESSAGE as i32,
2277                    event_kind::PRIVATE_DIRECT_MESSAGE as i32,
2278                    event_kind::FILE_ATTACHMENT as i32,
2279                    chat_identifier,
2280                    bans
2281                ],
2282                |row| row.get(0),
2283            )
2284        })
2285        .map_err(|e| format!("query unread_count_for_chat: {e}"))?;
2286    Ok(count as u32)
2287}
2288
2289/// What [`compute_unread_anchor`] decided a chat's read marker should become to surface its newest
2290/// contact message as unread. Computed from the full DB history (RAM may hold only a preview
2291/// message for an unopened community).
2292#[derive(Debug, PartialEq)]
2293pub enum UnreadMark {
2294    /// Nothing to surface: no contact message, or a strictly-newer own message (we spoke last).
2295    NoOp,
2296    /// Reset to the never-read anchor: the target is the chat's earliest message.
2297    Clear,
2298    /// Retreat `last_read` to this event id (the newest message in a strictly earlier second).
2299    Anchor(String),
2300}
2301
2302/// Decide how to mark `chat_identifier` unread. Anchors on the newest message strictly before the
2303/// newest contact message's second — the count query compares whole seconds with a strict `>`, so a
2304/// same-second anchor would leave the target on the boundary and it would read as caught-up.
2305pub async fn compute_unread_anchor(chat_identifier: &str) -> Result<UnreadMark, String> {
2306    let conn = super::get_db_connection_guard_static()?;
2307    let (k0, k1, k2) = (
2308        event_kind::CHAT_MESSAGE as i32,
2309        event_kind::PRIVATE_DIRECT_MESSAGE as i32,
2310        event_kind::FILE_ATTACHMENT as i32,
2311    );
2312    // Newest non-mine message second (the target) and newest overall (to detect we spoke last).
2313    let (target_ts, newest_ts): (Option<i64>, Option<i64>) = conn
2314        .query_row(
2315            "SELECT MAX(CASE WHEN e.mine = 0 THEN e.created_at END), MAX(e.created_at) \
2316             FROM events e JOIN chats c ON e.chat_id = c.id \
2317             WHERE c.chat_identifier = ?1 AND e.kind IN (?2, ?3, ?4)",
2318            rusqlite::params![chat_identifier, k0, k1, k2],
2319            |row| Ok((row.get(0)?, row.get(1)?)),
2320        )
2321        .map_err(|e| format!("unread anchor target: {e}"))?;
2322
2323    let target_ts = match target_ts {
2324        Some(t) => t,
2325        None => return Ok(UnreadMark::NoOp), // no contact message to surface
2326    };
2327    if newest_ts.is_some_and(|n| n > target_ts) {
2328        return Ok(UnreadMark::NoOp); // a strictly-newer own message → we spoke last
2329    }
2330
2331    let anchor_id: Option<String> = conn
2332        .query_row(
2333            "SELECT e.id FROM events e JOIN chats c ON e.chat_id = c.id \
2334             WHERE c.chat_identifier = ?1 AND e.kind IN (?2, ?3, ?4) AND e.created_at < ?5 \
2335             ORDER BY e.created_at DESC LIMIT 1",
2336            rusqlite::params![chat_identifier, k0, k1, k2, target_ts],
2337            |row| row.get(0),
2338        )
2339        .optional()
2340        .map_err(|e| format!("unread anchor prev: {e}"))?;
2341
2342    Ok(match anchor_id {
2343        Some(id) => UnreadMark::Anchor(id),
2344        None => UnreadMark::Clear,
2345    })
2346}
2347
2348/// Drain a sync loop's pending message batch into one transaction. The shared flush for the
2349/// segment-flush pattern: bulk loops COLLECT message saves and call this at delete barriers +
2350/// loop end (a batched save committing AFTER a delete it originally preceded would resurrect
2351/// the deleted row — flushing first preserves wire order). Session-guarded HERE so every bulk
2352/// path gets the same swap-safety: on a stale session the batch is DROPPED, never written
2353/// into the next account's DB (the caller's loop is about to bail anyway).
2354pub async fn flush_message_batch(
2355    chat_id: &str,
2356    pending: &mut Vec<&Message>,
2357    session: &std::sync::Arc<crate::db::Session>,
2358) {
2359    crate::db::scoped(async move {
2360        if pending.is_empty() {
2361            return;
2362        }
2363        if !session.is_live() {
2364            pending.clear();
2365            return;
2366        }
2367        if let Err(e) = save_messages_batch(chat_id, pending).await {
2368            crate::log_warn!("[DB] batch flush failed for {}: {}", chat_id, e);
2369        }
2370        pending.clear();
2371    })
2372    .await
2373}
2374
2375/// Batch save messages for a chat — one transaction for the whole slice.
2376pub async fn save_chat_messages(chat_id: &str, messages: &[Message]) -> Result<(), String> {
2377    if messages.is_empty() {
2378        return Ok(());
2379    }
2380    let refs: Vec<&Message> = messages.iter().collect();
2381    save_messages_batch(chat_id, &refs).await.map(|_| ())
2382}
2383
2384#[cfg(test)]
2385mod tests {
2386    use super::*;
2387    use crate::stored_event::SystemEventType;
2388
2389    static TEST_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(71000);
2390
2391    fn make_test_npub(n: u32) -> String {
2392        const BECH32: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
2393        let mut payload = vec![b'q'; 58];
2394        let mut x = n as u64;
2395        let mut i = 58;
2396        while x > 0 && i > 0 {
2397            i -= 1;
2398            payload[i] = BECH32[(x as usize) % 32];
2399            x /= 32;
2400        }
2401        format!("npub1{}", std::str::from_utf8(&payload).unwrap())
2402    }
2403
2404    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
2405        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
2406        crate::db::close_database();
2407        // Each test rebinds to a fresh per-account DB; the row-id caches are per-account, so a stale
2408        // entry (e.g. a shared author npub) would point into the prior test's DB and FK-fail the insert.
2409        crate::db::clear_id_caches();
2410        let tmp = tempfile::tempdir().unwrap();
2411        let n = TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2412        let account = make_test_npub(n);
2413        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
2414        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
2415        crate::db::set_current_account(account.clone()).unwrap();
2416        crate::db::init_database(&account).unwrap();
2417        (tmp, guard)
2418    }
2419
2420    fn now_secs() -> u64 {
2421        web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_secs()
2422    }
2423
2424    /// A page of synced replies must come out of the batch resolver carrying their quotes.
2425    /// The sync/promote paths emit straight to the UI, and the renderer falls back to the
2426    /// in-memory parent only when the parent is inside the rendered window — so a reply to
2427    /// an OLDER message renders with no quote at all unless the backend resolved it here.
2428    /// Reopening the chat re-reads through `get_message_views` (which resolves), which is
2429    /// why the bug looked like "replies lose their context until you reopen".
2430    #[tokio::test]
2431    async fn batch_resolver_fills_quotes_for_a_synced_page() {
2432        let (_tmp, _guard) = init_test_db();
2433        let chat = "channel_reply_batch";
2434        let author = make_test_npub(90_001);
2435
2436        // An older, already-persisted parent (the case with no in-memory fallback).
2437        let mut parent = Message::default();
2438        parent.id = "parent_evt".to_string();
2439        parent.content = "the original message".to_string();
2440        parent.npub = Some(author.clone());
2441        parent.at = now_secs() - 5_000;
2442        save_message(chat, &parent).await.unwrap();
2443
2444        // The freshly-synced page: a reply to it, plus an unrelated message.
2445        let mut reply = Message::default();
2446        reply.id = "reply_evt".to_string();
2447        reply.content = "replying now".to_string();
2448        reply.replied_to = "parent_evt".to_string();
2449        reply.at = now_secs();
2450        let mut plain = Message::default();
2451        plain.id = "plain_evt".to_string();
2452        plain.content = "unrelated".to_string();
2453        plain.at = now_secs();
2454        // A reply whose parent this device has never seen must stay empty, not fabricate a quote.
2455        let mut orphan = Message::default();
2456        orphan.id = "orphan_evt".to_string();
2457        orphan.replied_to = "never_seen_evt".to_string();
2458        orphan.at = now_secs();
2459
2460        populate_reply_contexts(vec![&mut reply, &mut plain, &mut orphan]).await.unwrap();
2461
2462        assert_eq!(
2463            reply.replied_to_content.as_deref(),
2464            Some("the original message"),
2465            "the synced reply carries its parent's content"
2466        );
2467        assert_eq!(reply.replied_to_npub.as_deref(), Some(author.as_str()), "and its parent's author");
2468        assert!(plain.replied_to_content.is_none(), "a non-reply is untouched");
2469        assert!(orphan.replied_to_content.is_none(), "an unresolvable parent leaves the quote empty");
2470    }
2471
2472    /// A moderation citation names a message id and nothing else, so the room
2473    /// has to come back with it.
2474    #[tokio::test]
2475    async fn a_message_resolves_by_id_with_the_chat_it_was_said_in() {
2476        let (_tmp, _guard) = init_test_db();
2477        let chat = "channel_resolve_by_id";
2478        let author = make_test_npub(91_001);
2479
2480        let mut msg = Message::default();
2481        msg.id = "cited_evt".to_string();
2482        msg.content = "the line a rule matched".to_string();
2483        msg.npub = Some(author.clone());
2484        msg.at = now_secs();
2485        save_message(chat, &msg).await.unwrap();
2486
2487        let (found_chat, found) = get_message_by_id("cited_evt").await.unwrap().expect("stored message resolves");
2488        assert_eq!(found_chat, chat, "the citation gets the room back, not just the message");
2489        assert_eq!(found.content, "the line a rule matched", "and the text, so a mod log can quote it");
2490        assert_eq!(found.npub.as_deref(), Some(author.as_str()));
2491    }
2492
2493    /// A citation outlives its message: deletes, moderation hides, expiry, or
2494    /// history this device never synced. Absence is an answer, not a fault — a
2495    /// resolver that errored would turn every one of those into a failure.
2496    #[tokio::test]
2497    async fn a_message_locates_its_chat_and_nothing_else_does() {
2498        let (_tmp, _guard) = init_test_db();
2499        save_message("npub1locate", &Message { id: "locate_me".into(), content: "hi".into(), at: 1_000_000, ..Default::default() })
2500            .await.unwrap();
2501        let here = |chat: &str| MessageLocation { chat: Some(chat.into()), deleted: false };
2502        assert_eq!(locate_message("locate_me").unwrap(), here("npub1locate"));
2503        assert_eq!(locate_message("never_stored").unwrap(), MessageLocation::default());
2504        let cid = crate::db::id_cache::get_chat_id_by_identifier("npub1locate").unwrap();
2505        save_edit_event("an_edit", "locate_me", "hello", &[], &[], cid, None, "npub1x").await.unwrap();
2506        assert_eq!(locate_message("an_edit").unwrap(), MessageLocation::default(), "an edit is not a message to jump to");
2507        delete_event("locate_me").await.unwrap();
2508        add_message_tombstone("locate_me").unwrap();
2509        assert_eq!(locate_message("locate_me").unwrap(), MessageLocation { chat: None, deleted: true });
2510    }
2511
2512    /// A row a page served from the store, never loaded into memory, still finds its chat,
2513    /// so it can be deleted like any other.
2514    #[tokio::test]
2515    async fn a_message_outside_memory_still_finds_its_chat() {
2516        let (_tmp, _guard) = init_test_db();
2517        save_message("channel_paged", &Message { id: "paged_in".into(), content: "hi".into(), at: 1_000_000, ..Default::default() })
2518            .await.unwrap();
2519        assert!(crate::state::STATE.lock().await.find_message("paged_in").is_none());
2520        assert_eq!(crate::VectorCore.message_chat("paged_in").await.unwrap(), "channel_paged");
2521        assert!(crate::VectorCore.message_chat("never_stored").await.is_err());
2522    }
2523
2524    #[tokio::test]
2525    async fn a_missing_message_resolves_to_none_rather_than_erroring() {
2526        let (_tmp, _guard) = init_test_db();
2527        assert!(get_message_by_id("never_stored_evt").await.unwrap().is_none());
2528    }
2529
2530    /// One blob rides many messages — a forward, a re-post, or forty accounts
2531    /// posting the same image, which is the case most worth seeing whole.
2532    #[tokio::test]
2533    async fn an_attachment_hash_finds_every_message_that_carried_it() {
2534        let (_tmp, _guard) = init_test_db();
2535        let chat = "channel_same_blob";
2536        let hash = "cc".repeat(32);
2537
2538        // `Message.at` is MILLISECONDS: seconds-apart values collapse to one
2539        // created_at and leave the order to chance.
2540        let now_ms = now_secs() * 1000;
2541        for (id, at) in [("blob_older", now_ms - 500_000), ("blob_newer", now_ms)] {
2542            let mut msg = Message::default();
2543            msg.id = id.to_string();
2544            msg.npub = Some(make_test_npub(92_001));
2545            msg.at = at;
2546            msg.attachments = vec![crate::types::Attachment {
2547                id: hash.clone(),
2548                extension: "png".into(),
2549                name: "poster.png".into(),
2550                ..Default::default()
2551            }];
2552            save_message(chat, &msg).await.unwrap();
2553        }
2554
2555        let carriers = crate::db::attachments::events_with_attachment_hash(&hash).unwrap();
2556        assert_eq!(carriers, vec!["blob_newer", "blob_older"], "every carrier, newest first");
2557
2558        // Same instant, which is what a raid looks like: the order must still be
2559        // total rather than whatever the join happens to yield.
2560        for id in ["tie_a", "tie_b"] {
2561            let mut msg = Message::default();
2562            msg.id = id.to_string();
2563            msg.npub = Some(make_test_npub(92_002));
2564            msg.at = now_ms;
2565            msg.attachments = vec![crate::types::Attachment { id: hash.clone(), ..Default::default() }];
2566            save_message(chat, &msg).await.unwrap();
2567        }
2568        let a = crate::db::attachments::events_with_attachment_hash(&hash).unwrap();
2569        let b = crate::db::attachments::events_with_attachment_hash(&hash).unwrap();
2570        assert_eq!(a, b, "a same-instant cluster orders the same way every read");
2571        assert_eq!(a.len(), 4, "and every carrier is still listed");
2572        assert!(
2573            crate::db::attachments::events_with_attachment_hash(&"ab".repeat(32)).unwrap().is_empty(),
2574            "a hash nobody posted finds nothing"
2575        );
2576    }
2577
2578    /// An empty page (or one with no replies at all) must not query or error — the sync path
2579    /// calls this for every page, most of which carry no replies.
2580    #[tokio::test]
2581    async fn batch_resolver_is_a_noop_without_replies() {
2582        let (_tmp, _guard) = init_test_db();
2583        populate_reply_contexts(vec![]).await.unwrap();
2584        let mut plain = Message::default();
2585        plain.id = "solo".to_string();
2586        populate_reply_contexts(vec![&mut plain]).await.unwrap();
2587        assert!(plain.replied_to_content.is_none());
2588    }
2589
2590    // C-H2: a presence (join/leave) persisted from HISTORY must keep its authenticated timestamp so it
2591    // sorts where it happened, not at ingest-time "now"; a future-dated one is clamped so it can't jump
2592    // ahead of real activity.
2593    #[tokio::test]
2594    async fn system_event_stamps_authenticated_time_clamped_to_now() {
2595        let (_tmp, _guard) = init_test_db();
2596        let chat = "channel_ch2_timestamp";
2597        let before = now_secs();
2598        let past = before - 100_000;
2599
2600        save_system_event_at("ev_past", chat, SystemEventType::MemberJoined, "npubX", None, past, None, None).await.unwrap();
2601        save_system_event_at("ev_future", chat, SystemEventType::MemberJoined, "npubX", None, before + 100_000, None, None).await.unwrap();
2602        let after = now_secs();
2603
2604        let evs = get_system_events_for_chat(chat).unwrap();
2605        let past_ev = evs.iter().find(|e| e.id == "ev_past").expect("past event saved");
2606        assert_eq!(past_ev.created_at, past, "historical join keeps its real (authenticated) timestamp");
2607
2608        let fut_ev = evs.iter().find(|e| e.id == "ev_future").expect("future event saved");
2609        assert!(fut_ev.created_at >= before && fut_ev.created_at <= after,
2610            "future-dated event clamped to local now ({} not in {}..={})", fut_ev.created_at, before, after);
2611    }
2612
2613    // Delete-affordance resolution must work on paged-out rows: the events table is the
2614    // fallback source for (chat, mine, author) when a message isn't STATE-resident.
2615    #[tokio::test]
2616    async fn event_delete_context_resolves_from_db() {
2617        let (_tmp, _guard) = init_test_db();
2618        let chat = "npub1contactdc";
2619
2620        let mine_msg = Message { id: "dc_mine".into(), content: "x".into(), at: 1_000, mine: true, ..Default::default() };
2621        let theirs = Message {
2622            id: "dc_theirs".into(), content: "y".into(), at: 2_000, mine: false,
2623            npub: Some("npub1sender".to_string()),
2624            ..Default::default()
2625        };
2626        save_message(chat, &mine_msg).await.unwrap();
2627        save_message(chat, &theirs).await.unwrap();
2628
2629        let (chat_id, mine, _author) = event_delete_context("dc_mine").unwrap().expect("own row resolves");
2630        assert_eq!(chat_id, chat);
2631        assert!(mine);
2632
2633        let (chat_id, mine, author) = event_delete_context("dc_theirs").unwrap().expect("contact row resolves");
2634        assert_eq!(chat_id, chat);
2635        assert!(!mine);
2636        assert_eq!(author.as_deref(), Some("npub1sender"));
2637
2638        assert!(event_delete_context("dc_absent").unwrap().is_none(), "unknown id is None, not an error");
2639    }
2640
2641    // The reported bug: unread must accumulate across a restart (when only the last message per
2642    // chat is in RAM). The DB cutoff count must mirror the in-memory walk-back exactly.
2643    #[tokio::test]
2644    async fn unread_counts_match_walk_back_semantics() {
2645        let (_tmp, _guard) = init_test_db();
2646        let chat = "npub1contactdm";
2647        // `at` is ms (created_at = at/1000); use distinct seconds.
2648        let mk = |id: &str, secs: u64, mine: bool| Message {
2649            id: id.into(), content: "x".into(), at: secs * 1000, mine,
2650            npub: (!mine).then(|| "npub1sender".to_string()),
2651            ..Default::default()
2652        };
2653        let unread = || async { unread_counts().await.unwrap().get(chat).copied().unwrap_or(0) };
2654
2655        // 6 contact messages, never opened/read, no own reply → all 6 unread.
2656        for i in 0..6u64 {
2657            save_message(chat, &mk(&format!("m{i}"), 1000 + i, false)).await.unwrap();
2658        }
2659        assert_eq!(unread().await, 6, "never-read backlog counts all 6");
2660
2661        // 2 more arrive → 8, NOT replaced by 2 (the exact reported symptom).
2662        save_message(chat, &mk("m6", 2000, false)).await.unwrap();
2663        save_message(chat, &mk("m7", 2001, false)).await.unwrap();
2664        assert_eq!(unread().await, 8, "6 backlog + 2 new = 8");
2665
2666        // Our own reply clears it (walk-back stops at the newest mine).
2667        save_message(chat, &mk("mine", 2002, true)).await.unwrap();
2668        assert_eq!(unread().await, 0, "own message = read up to here");
2669
2670        // A contact message after our send is unread again.
2671        save_message(chat, &mk("m8", 2003, false)).await.unwrap();
2672        assert_eq!(unread().await, 1, "one new after our send");
2673
2674        // last_read marker advances the cutoff just like an own message.
2675        {
2676            let conn = crate::db::get_write_connection_guard_static().unwrap();
2677            conn.execute(
2678                "UPDATE chats SET last_read = ?1 WHERE chat_identifier = ?2",
2679                rusqlite::params!["m8", chat],
2680            ).unwrap();
2681        }
2682        assert_eq!(unread().await, 0, "last_read=m8 clears all");
2683        save_message(chat, &mk("m9", 2004, false)).await.unwrap();
2684        assert_eq!(unread().await, 1, "one arrival after last_read");
2685    }
2686
2687    // "Mark as Unread" from a chosen message counts from it on, past our own replies, in both the
2688    // map and the single-chat query, and the ordinary floor returns once it is cleared.
2689    #[tokio::test]
2690    async fn unread_from_counts_past_own_replies() {
2691        let (_tmp, _guard) = init_test_db();
2692        let chat = "npub1unreadfrom";
2693        let mk = |id: &str, secs: u64, mine: bool| Message {
2694            id: id.into(), content: "x".into(), at: secs * 1000, mine,
2695            npub: (!mine).then(|| "npub1sender".to_string()),
2696            ..Default::default()
2697        };
2698        let agree = || async {
2699            let map = unread_counts().await.unwrap().get(chat).copied().unwrap_or(0);
2700            let one = unread_count_for_chat(chat).await.unwrap();
2701            assert_eq!(map, one, "single-chat query diverged from the map");
2702            one
2703        };
2704        let set_from = |id: &str| {
2705            let conn = crate::db::get_write_connection_guard_static().unwrap();
2706            conn.execute("UPDATE chats SET unread_from = ?1 WHERE chat_identifier = ?2", rusqlite::params![id, chat]).unwrap();
2707        };
2708
2709        save_message(chat, &mk("a", 1000, false)).await.unwrap();
2710        save_message(chat, &mk("b", 1001, false)).await.unwrap();
2711        save_message(chat, &mk("mine1", 1002, true)).await.unwrap();
2712        save_message(chat, &mk("c", 1003, false)).await.unwrap();
2713        save_message(chat, &mk("mine2", 1004, true)).await.unwrap();
2714        assert_eq!(agree().await, 0, "our newest reply reads everything before it");
2715
2716        set_from("b");
2717        assert_eq!(agree().await, 2, "b and c count; our replies don't, nor stop the count");
2718        set_from("a");
2719        assert_eq!(agree().await, 3, "from the first message: a, b, c");
2720        set_from("mine1");
2721        assert_eq!(agree().await, 1, "from our own message: only c after it");
2722        set_from("gone");
2723        assert_eq!(agree().await, 0, "a marker whose message is gone falls back to the floor");
2724        set_from("");
2725        assert_eq!(agree().await, 0, "cleared: the own-message floor is back");
2726    }
2727
2728    // A stray event row with an empty id must not stand in for an unset marker ('' in both).
2729    #[tokio::test]
2730    async fn empty_markers_ignore_an_empty_id_event() {
2731        let (_tmp, _guard) = init_test_db();
2732        let chat = "npub1emptyidrow";
2733        let mk = |id: &str, secs: u64, mine: bool| Message {
2734            id: id.into(), content: "x".into(), at: secs * 1000, mine,
2735            npub: (!mine).then(|| "npub1sender".to_string()),
2736            ..Default::default()
2737        };
2738        save_message(chat, &mk("old", 1000, false)).await.unwrap();
2739        save_message(chat, &mk("new", 3000, false)).await.unwrap();
2740        {
2741            let conn = crate::db::get_write_connection_guard_static().unwrap();
2742            let chat_row: i64 = conn.query_row("SELECT id FROM chats WHERE chat_identifier = ?1", rusqlite::params![chat], |r| r.get(0)).unwrap();
2743            conn.execute("INSERT INTO events (id, kind, chat_id, content, tags, created_at, received_at, mine) VALUES ('', 30078, ?1, '', '[]', 2000, 2000, 0)",
2744                rusqlite::params![chat_row]).unwrap();
2745            conn.execute("UPDATE chats SET last_read = 'new', unread_from = '' WHERE id = ?1", rusqlite::params![chat_row]).unwrap();
2746        }
2747        let map = unread_counts().await.unwrap().get(chat).copied().unwrap_or(0);
2748        assert_eq!(map, 0, "read to 'new'; the empty-id row is not an unread_from marker");
2749        assert_eq!(unread_count_for_chat(chat).await.unwrap(), 0);
2750    }
2751
2752    // The mark persists, moves on when its message is deleted, and a read save clears it.
2753    #[tokio::test]
2754    async fn unread_from_persists_moves_on_delete_and_clears() {
2755        let (_tmp, _guard) = init_test_db();
2756        let chat = "npub1unreadfromlife";
2757        let mk = |id: &str, secs: u64, mine: bool| Message {
2758            id: id.into(), content: "x".into(), at: secs * 1000, mine,
2759            npub: (!mine).then(|| "npub1sender".to_string()),
2760            ..Default::default()
2761        };
2762        for (id, secs, mine) in [("a", 1000, false), ("b", 1001, false), ("mine1", 1002, true), ("c", 1003, false)] {
2763            save_message(chat, &mk(id, secs, mine)).await.unwrap();
2764        }
2765        {
2766            let conn = crate::db::get_write_connection_guard_static().unwrap();
2767            conn.execute("UPDATE chats SET unread_from = 'b' WHERE chat_identifier = ?1", rusqlite::params![chat]).unwrap();
2768        }
2769        let stored = || crate::db::chats::get_all_chats().unwrap().into_iter().find(|c| c.id == chat).unwrap();
2770        assert_eq!(stored().unread_from, "b", "the mark round-trips through the chats row");
2771        assert_eq!(unread_count_for_chat(chat).await.unwrap(), 2, "b and c");
2772
2773        delete_event("b").await.unwrap();
2774        assert_eq!(stored().unread_from, "mine1", "deleting the chosen message hands the mark to the next one");
2775        assert_eq!(unread_count_for_chat(chat).await.unwrap(), 1, "only c after it");
2776
2777        let mut slim = stored();
2778        slim.unread_from = String::new();
2779        crate::db::chats::save_slim_chat(&slim).unwrap();
2780        assert_eq!(stored().unread_from, "", "a read's save clears it");
2781        assert_eq!(unread_count_for_chat(chat).await.unwrap(), 1, "back to the own-message floor: c");
2782    }
2783
2784    // Muting a person (their DM row) or blocking them silences their messages in EVERY chat's
2785    // count — community messages from a muted sender must not badge.
2786    #[tokio::test]
2787    async fn unread_counts_exclude_muted_and_blocked_senders() {
2788        let (_tmp, _guard) = init_test_db();
2789        let chat = "channel_mute_exclusion";
2790        let mk = |id: &str, secs: u64, npub: &str| Message {
2791            id: id.into(), content: "x".into(), at: secs * 1000, mine: false,
2792            npub: Some(npub.to_string()),
2793            ..Default::default()
2794        };
2795        save_message(chat, &mk("n1", 1000, "npub1noisy")).await.unwrap();
2796        save_message(chat, &mk("q1", 1001, "npub1quiet")).await.unwrap();
2797
2798        let map = || async { unread_counts().await.unwrap().get(chat).copied().unwrap_or(0) };
2799        let one = || async { unread_count_for_chat(chat).await.unwrap() };
2800        assert_eq!(map().await, 2, "both senders count while neither is muted");
2801        assert_eq!(one().await, 2);
2802
2803        // Mute npub1noisy: their (message-less) DM row exists purely to carry the flag.
2804        {
2805            let conn = crate::db::get_write_connection_guard_static().unwrap();
2806            conn.execute(
2807                "INSERT INTO chats (chat_identifier, chat_type, participants, created_at, muted) \
2808                 VALUES ('npub1noisy', 0, '', 1000, 1)",
2809                [],
2810            ).unwrap();
2811        }
2812        assert_eq!(map().await, 1, "muted sender's message stops counting");
2813        assert_eq!(one().await, 1);
2814
2815        // Block npub1quiet: same exclusion via the profiles flag.
2816        {
2817            let conn = crate::db::get_write_connection_guard_static().unwrap();
2818            conn.execute(
2819                "INSERT INTO profiles (npub, is_blocked) VALUES ('npub1quiet', 1) \
2820                 ON CONFLICT(npub) DO UPDATE SET is_blocked = 1",
2821                [],
2822            ).unwrap();
2823        }
2824        assert_eq!(map().await, 0, "blocked sender's message stops counting too");
2825        assert_eq!(one().await, 0);
2826
2827        // Unmute → the count comes straight back (nothing was consumed).
2828        {
2829            let conn = crate::db::get_write_connection_guard_static().unwrap();
2830            conn.execute("UPDATE chats SET muted = 0 WHERE chat_identifier = 'npub1noisy'", []).unwrap();
2831        }
2832        assert_eq!(map().await, 1, "unmuting restores the sender's count");
2833        assert_eq!(one().await, 1);
2834    }
2835
2836    // The single-chat reconcile query must agree with the full map for every state the cache
2837    // reconciles from (never-read, own-reply cutoff, last_read marker).
2838    #[tokio::test]
2839    async fn unread_count_for_chat_matches_the_map() {
2840        let (_tmp, _guard) = init_test_db();
2841        let chat = "npub1reconcile";
2842        let mk = |id: &str, secs: u64, mine: bool| Message {
2843            id: id.into(), content: "x".into(), at: secs * 1000, mine,
2844            npub: (!mine).then(|| "npub1sender".to_string()),
2845            ..Default::default()
2846        };
2847        let agree = || async {
2848            let map = unread_counts().await.unwrap().get(chat).copied().unwrap_or(0);
2849            let one = unread_count_for_chat(chat).await.unwrap();
2850            assert_eq!(map, one, "single-chat query diverged from the map");
2851            one
2852        };
2853
2854        for i in 0..4u64 { save_message(chat, &mk(&format!("m{i}"), 1000 + i, false)).await.unwrap(); }
2855        assert_eq!(agree().await, 4);
2856        save_message(chat, &mk("mine", 1010, true)).await.unwrap();
2857        assert_eq!(agree().await, 0);
2858        save_message(chat, &mk("after", 1011, false)).await.unwrap();
2859        assert_eq!(agree().await, 1);
2860        {
2861            let conn = crate::db::get_write_connection_guard_static().unwrap();
2862            conn.execute("UPDATE chats SET last_read = ?1 WHERE chat_identifier = ?2",
2863                rusqlite::params!["after", chat]).unwrap();
2864        }
2865        assert_eq!(agree().await, 0);
2866        // A chat with nothing at all reconciles to 0 (no row in the map).
2867        assert_eq!(unread_count_for_chat("npub1nonexistent").await.unwrap(), 0);
2868    }
2869
2870    #[tokio::test]
2871    async fn attachments_table_round_trip_dedup_and_cascade() {
2872        let (_tmp, _guard) = init_test_db();
2873        // downloaded:false mirrors a freshly-received attachment (Attachment::default is downloaded:true).
2874        let att = |id: &str, name: &str| Attachment {
2875            id: id.into(), url: format!("https://blossom/{id}"), name: name.into(),
2876            extension: "png".into(), size: 42, downloaded: false, ..Default::default()
2877        };
2878        let msg = |mid: &str, secs: u64, atts: Vec<Attachment>| Message {
2879            id: mid.into(), content: String::new(), at: secs * 1000, mine: false,
2880            npub: Some("npub1sender".into()), attachments: atts, ..Default::default()
2881        };
2882
2883        // Save a message with two attachments → both rows, order preserved by att_index.
2884        save_message("npub1att", &msg("m1", 1000, vec![att("hashA", "a.png"), att("hashB", "b.png")])).await.unwrap();
2885        let got = crate::db::attachments::get_attachments_for_event("m1").unwrap();
2886        assert_eq!(got.len(), 2);
2887        assert_eq!((got[0].id.as_str(), got[1].id.as_str()), ("hashA", "hashB"), "att_index order");
2888        assert_eq!(got[0].name, "a.png");
2889        assert_eq!(got[0].size, 42);
2890        assert!(!got[0].downloaded);
2891
2892        // Single-row download flip (no read-modify-write of a blob).
2893        crate::db::attachments::set_attachment_downloaded("m1", "hashA", true, "/tmp/a.png").unwrap();
2894        let got = crate::db::attachments::get_attachments_for_event("m1").unwrap();
2895        assert!(got[0].downloaded && got[0].path == "/tmp/a.png");
2896        assert!(!got[1].downloaded, "sibling attachment untouched");
2897
2898        // Dedup: a second message shares hashA → backfill-by-hash marks it (indexed, no LIKE scan).
2899        save_message("npub1att", &msg("m2", 1001, vec![att("hashA", "a-again.png")])).await.unwrap();
2900        let affected = crate::db::attachments::backfill_downloaded_by_hash("hashA", "/tmp/a.png", "m1").unwrap();
2901        assert_eq!(affected, vec!["m2".to_string()]);
2902        assert!(crate::db::attachments::get_attachments_for_event("m2").unwrap()[0].downloaded);
2903
2904        // The write funnel dual-populates the legacy tag, so get_message_views (still tag-backed
2905        // during shadow-populate) composes the attachments onto the Message.
2906        let chat_int = crate::db::id_cache::get_or_create_chat_id("npub1att").unwrap();
2907        let views = get_message_views(chat_int, 10, 0).await.unwrap();
2908        let m1 = views.iter().find(|m| m.id == "m1").unwrap();
2909        assert_eq!(m1.attachments.len(), 2);
2910
2911        // Cascade: deleting the event removes its attachment rows.
2912        delete_event("m1").await.unwrap();
2913        assert!(crate::db::attachments::get_attachments_for_event("m1").unwrap().is_empty(), "ON DELETE CASCADE");
2914    }
2915
2916    #[tokio::test]
2917    async fn deleting_a_message_takes_its_edits_and_reactions_with_it() {
2918        let (_tmp, _guard) = init_test_db();
2919        let react = |id: &str, target: &str| Reaction {
2920            id: id.into(), reference_id: target.into(), author_id: "npub1reactor".into(),
2921            emoji: "🔥".into(), emoji_url: None,
2922        };
2923        let msg = |mid: &str| Message {
2924            id: mid.into(), content: "original".into(), at: 1_000_000, npub: Some("npub1sender".into()),
2925            reactions: vec![react(&format!("r-{mid}"), mid)], ..Default::default()
2926        };
2927        let chat_id = crate::db::id_cache::get_or_create_chat_id("npub1cascade").unwrap();
2928        for mid in ["gone", "kept"] {
2929            save_message("npub1cascade", &msg(mid)).await.unwrap();
2930            let edit = crate::stored_event::StoredEventBuilder::new()
2931                .id(format!("e-{mid}"))
2932                .kind(event_kind::MESSAGE_EDIT)
2933                .chat_id(chat_id)
2934                .content("edited text")
2935                .reference_id(Some(mid.into()))
2936                .created_at(1_001)
2937                .build();
2938            save_event(&edit).await.unwrap();
2939        }
2940
2941        delete_event("gone").await.unwrap();
2942        for id in ["gone", "r-gone", "e-gone"] {
2943            assert!(!event_exists(id).unwrap(), "{id} goes with its message");
2944        }
2945        for id in ["kept", "r-kept", "e-kept"] {
2946            assert!(event_exists(id).unwrap(), "{id} belongs to another message");
2947        }
2948    }
2949
2950    // The download persist path: a re-save must never DOWNGRADE download state (relay re-delivery),
2951    // but a re-save carrying a completed download (+ the nonce→content-hash id rewrite) must persist.
2952    #[tokio::test]
2953    async fn attachment_download_state_is_monotonic_across_resaves() {
2954        let (_tmp, _guard) = init_test_db();
2955        let att = |id: &str, downloaded: bool, path: &str| Attachment {
2956            id: id.into(), url: "u".into(), name: "f.png".into(), extension: "png".into(),
2957            size: 1, downloaded, path: path.into(), ..Default::default()
2958        };
2959        let msg = |atts: Vec<Attachment>| Message {
2960            id: "dl1".into(), content: String::new(), at: 1_000_000, mine: false,
2961            npub: Some("npub1s".into()), attachments: atts, ..Default::default()
2962        };
2963
2964        // Receive (not downloaded), then the user downloads → single-row flip.
2965        save_message("npub1dl", &msg(vec![att("nonceid", false, "")])).await.unwrap();
2966        crate::db::attachments::set_attachment_downloaded("dl1", "nonceid", true, "/tmp/f.png").unwrap();
2967
2968        // Relay re-delivery (downloaded=false) must NOT reset the download.
2969        save_message("npub1dl", &msg(vec![att("nonceid", false, "")])).await.unwrap();
2970        let got = crate::db::attachments::get_attachments_for_event("dl1").unwrap();
2971        assert!(got[0].downloaded && got[0].path == "/tmp/f.png", "re-delivery preserves the download");
2972
2973        // Post-download re-save: id rewritten nonce→content-hash, downloaded=true persists in one pass.
2974        save_message("npub1dl", &msg(vec![att("contenthash", true, "/tmp/f.png")])).await.unwrap();
2975        let got = crate::db::attachments::get_attachments_for_event("dl1").unwrap();
2976        assert_eq!(got[0].id, "contenthash", "hash rewritten nonce→content");
2977        assert!(got[0].downloaded && got[0].path == "/tmp/f.png");
2978
2979        // A re-delivery AFTER the rewrite must keep the content-hash key (not revert to the nonce),
2980        // so the hash-keyed download/backfill/clear helpers still resolve the row.
2981        save_message("npub1dl", &msg(vec![att("nonceid", false, "")])).await.unwrap();
2982        let got = crate::db::attachments::get_attachments_for_event("dl1").unwrap();
2983        assert_eq!(got[0].id, "contenthash", "content-hash key survives a later re-delivery");
2984        assert!(got[0].downloaded && got[0].path == "/tmp/f.png");
2985    }
2986
2987    // An un-backfilled pre-migration event (attachments only in the legacy tag, no table row) still
2988    // renders via the read fallback.
2989    #[tokio::test]
2990    async fn attachments_fall_back_to_legacy_tag_when_table_empty() {
2991        let (_tmp, _guard) = init_test_db();
2992        let a = Attachment {
2993            id: "tagonly".into(), url: "u".into(), name: "old.png".into(), extension: "png".into(),
2994            size: 7, downloaded: false, ..Default::default()
2995        };
2996        save_message("npub1old", &Message {
2997            id: "old1".into(), content: String::new(), at: 2_000_000, mine: false,
2998            npub: Some("npub1s".into()), attachments: vec![a.clone()], ..Default::default()
2999        }).await.unwrap();
3000
3001        // Simulate the pre-migration shape: drop the table rows, write the legacy tag onto the event.
3002        {
3003            let conn = crate::db::get_write_connection_guard_static().unwrap();
3004            conn.execute("DELETE FROM attachments WHERE event_id='old1'", []).unwrap();
3005            let inner = serde_json::to_string(&vec![a]).unwrap();
3006            let tags = serde_json::to_string(&vec![vec!["attachments".to_string(), inner]]).unwrap();
3007            conn.execute("UPDATE events SET tags=?1 WHERE id='old1'", rusqlite::params![tags]).unwrap();
3008        }
3009        assert!(crate::db::attachments::get_attachments_for_event("old1").unwrap().is_empty(), "table empty");
3010
3011        let chat_int = crate::db::id_cache::get_or_create_chat_id("npub1old").unwrap();
3012        let views = get_message_views(chat_int, 10, 0).await.unwrap();
3013        let old = views.iter().find(|m| m.id == "old1").unwrap();
3014        assert_eq!(old.attachments.len(), 1, "attachment served from the legacy-tag fallback");
3015        assert_eq!(old.attachments[0].name, "old.png");
3016    }
3017
3018    // Migration 75's strip logic: remove the legacy attachments tag ONLY from events that are
3019    // provably backfilled (have a table row); un-backfilled events keep their tag as the fallback.
3020    #[tokio::test]
3021    async fn attachment_tag_strip_is_gated_on_backfill() {
3022        let (_tmp, _guard) = init_test_db();
3023        let a = Attachment { id: "h1".into(), extension: "png".into(), name: "f.png".into(), downloaded: false, ..Default::default() };
3024        let mk = |id: &str, secs: u64| Message {
3025            id: id.into(), content: String::new(), at: secs * 1000, mine: false,
3026            npub: Some("npub1s".into()), attachments: vec![a.clone()], ..Default::default()
3027        };
3028        save_message("npub1s", &mk("bf", 1000)).await.unwrap();
3029        save_message("npub1s", &mk("unbf", 2000)).await.unwrap();
3030
3031        {
3032            let conn = crate::db::get_write_connection_guard_static().unwrap();
3033            let inner = serde_json::to_string(&vec![a.clone()]).unwrap();
3034            let with_tag = |ms: &str| serde_json::to_string(&vec![
3035                vec!["ms".to_string(), ms.to_string()],
3036                vec!["attachments".to_string(), inner.clone()],
3037            ]).unwrap();
3038            // Both events carry a legacy tag; only `unbf` loses its table rows (un-backfilled).
3039            conn.execute("UPDATE events SET tags=?1 WHERE id='bf'", rusqlite::params![with_tag("5")]).unwrap();
3040            conn.execute("UPDATE events SET tags=?1 WHERE id='unbf'", rusqlite::params![with_tag("6")]).unwrap();
3041            conn.execute("DELETE FROM attachments WHERE event_id='unbf'", []).unwrap();
3042
3043            // Replicate migration 75's gated strip.
3044            let events: Vec<(String, String)> = {
3045                let mut stmt = conn.prepare("SELECT id, tags FROM events WHERE tags LIKE '%attachments%' AND id IN (SELECT DISTINCT event_id FROM attachments)").unwrap();
3046                let m = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).unwrap();
3047                m.flatten().collect()
3048            };
3049            for (id, tj) in events {
3050                let mut tags: Vec<Vec<String>> = serde_json::from_str(&tj).unwrap();
3051                tags.retain(|t| t.first().map(|s| s.as_str()) != Some("attachments"));
3052                conn.execute("UPDATE events SET tags=?1 WHERE id=?2",
3053                    rusqlite::params![serde_json::to_string(&tags).unwrap(), id]).unwrap();
3054            }
3055
3056            let bf: String = conn.query_row("SELECT tags FROM events WHERE id='bf'", [], |r| r.get(0)).unwrap();
3057            assert!(!bf.contains("attachments"), "backfilled event's attachments tag stripped");
3058            assert!(bf.contains("\"ms\""), "sibling ms tag survives the strip");
3059            let unbf: String = conn.query_row("SELECT tags FROM events WHERE id='unbf'", [], |r| r.get(0)).unwrap();
3060            assert!(unbf.contains("attachments"), "un-backfilled event keeps its tag (no table row)");
3061        }
3062
3063        // The un-backfilled event still renders via the read fallback after the strip.
3064        let chat_int = crate::db::id_cache::get_or_create_chat_id("npub1s").unwrap();
3065        let views = get_message_views(chat_int, 10, 0).await.unwrap();
3066        assert_eq!(views.iter().find(|m| m.id == "unbf").unwrap().attachments.len(), 1, "fallback still renders unbf");
3067    }
3068
3069    // Mark-as-unread anchors from the FULL DB history (a community row often holds only a preview
3070    // message in RAM). The anchor lands strictly before the target's second so the count query's
3071    // strict `>` still counts the newest contact message. Covers the community repro + edge cases.
3072    #[tokio::test]
3073    async fn compute_unread_anchor_covers_the_cases() {
3074        let (_tmp, _guard) = init_test_db();
3075        let mk = |id: &str, secs: u64, mine: bool| Message {
3076            id: id.into(), content: "x".into(), at: secs * 1000, mine,
3077            npub: (!mine).then(|| "npub1sender".to_string()),
3078            ..Default::default()
3079        };
3080        let unread = |chat: &'static str| async move {
3081            unread_counts().await.unwrap().get(chat).copied().unwrap_or(0)
3082        };
3083        let set_lr = |chat: &str, lr: &str| {
3084            let conn = crate::db::get_write_connection_guard_static().unwrap();
3085            conn.execute("UPDATE chats SET last_read = ?1 WHERE chat_identifier = ?2",
3086                rusqlite::params![lr, chat]).unwrap();
3087        };
3088
3089        // (A) The community repro: we spoke long ago, they kept talking. Anchor = second-newest
3090        // contact message → exactly one unread, whatever the RAM cache held.
3091        let a = "npub1anchorA";
3092        save_message(a, &mk("a_mine", 1000, true)).await.unwrap();
3093        for i in 0..8u64 { save_message(a, &mk(&format!("a{i}"), 2000 + i, false)).await.unwrap(); }
3094        assert_eq!(compute_unread_anchor(a).await.unwrap(), UnreadMark::Anchor("a6".into()));
3095        set_lr(a, "a6");
3096        assert_eq!(unread(a).await, 1, "A: newest contact message is the sole unread");
3097
3098        // (B) We spoke last → NoOp (no phantom badge, no snap-back jiggle).
3099        let b = "npub1anchorB";
3100        save_message(b, &mk("b0", 2000, false)).await.unwrap();
3101        save_message(b, &mk("b_mine", 2001, true)).await.unwrap();
3102        assert_eq!(compute_unread_anchor(b).await.unwrap(), UnreadMark::NoOp);
3103
3104        // (C) Same-second tail: the two newest share a second. The anchor must skip to a strictly
3105        // earlier second, so both same-second messages surface instead of snapping back to read.
3106        let c = "npub1anchorC";
3107        save_message(c, &mk("c0", 3000, false)).await.unwrap();
3108        save_message(c, &mk("c1", 3005, false)).await.unwrap();
3109        save_message(c, &mk("c2", 3005, false)).await.unwrap();
3110        assert_eq!(compute_unread_anchor(c).await.unwrap(), UnreadMark::Anchor("c0".into()));
3111        set_lr(c, "c0");
3112        assert_eq!(unread(c).await, 2, "C: same-second tail both count");
3113
3114        // (D) The newest contact message is the chat's first → Clear (never-read) → it still counts.
3115        let d = "npub1anchorD";
3116        save_message(d, &mk("d0", 4000, false)).await.unwrap();
3117        assert_eq!(compute_unread_anchor(d).await.unwrap(), UnreadMark::Clear);
3118        set_lr(d, "");
3119        assert_eq!(unread(d).await, 1, "D: lone contact message surfaces");
3120
3121        // (E) No contact message at all (only our own) → NoOp.
3122        let e = "npub1anchorE";
3123        save_message(e, &mk("e_mine", 5000, true)).await.unwrap();
3124        assert_eq!(compute_unread_anchor(e).await.unwrap(), UnreadMark::NoOp);
3125    }
3126
3127    // Regression: a "read to here" marker that lands on a system event (kind 30078, not a counted
3128    // kind, e.g. the windowed jump-reveal path marking off the raw tail) must still clear unread.
3129    // The anchor keys off the marker row's time whatever its kind, so it can't wedge at 99+.
3130    /// A blank conversation id is refused, never minted into a chat row. Left to
3131    /// `get_or_create_chat_id` it created a chat keyed by "" — and because the
3132    /// identifier is UNIQUE, presence from EVERY channel-less community collapsed
3133    /// into that one unopenable row (82 events across weeks, on a live account).
3134    #[tokio::test]
3135    async fn a_system_event_with_a_blank_conversation_id_is_refused() {
3136        let (_tmp, _guard) = init_test_db();
3137        let before = chat_row_count();
3138        for blank in ["", "   "] {
3139            assert!(
3140                save_system_event_at("ev", blank, SystemEventType::MemberJoined, "npubX", None, 100, None, None)
3141                    .await
3142                    .is_err(),
3143                "a blank conversation id must be refused, not minted"
3144            );
3145        }
3146        assert_eq!(chat_row_count(), before, "and no chat row is created");
3147        // A real id still works.
3148        assert!(
3149            save_system_event_at("ev2", "real-chat", SystemEventType::MemberJoined, "npubX", None, 100, None, None)
3150                .await
3151                .unwrap()
3152        );
3153    }
3154
3155    fn chat_row_count() -> i64 {
3156        let conn = crate::db::get_db_connection_guard_static().unwrap();
3157        conn.query_row("SELECT count(*) FROM chats", [], |r| r.get(0)).unwrap()
3158    }
3159
3160    #[tokio::test]
3161    async fn unread_clears_when_last_read_is_a_system_event() {
3162        let (_tmp, _guard) = init_test_db();
3163        let chat = "npub1sysevtdm";
3164        let mk = |id: &str, secs: u64| Message {
3165            id: id.into(), content: "x".into(), at: secs * 1000, mine: false,
3166            npub: Some("npub1sender".to_string()), ..Default::default()
3167        };
3168        let unread = || async { unread_counts().await.unwrap().get(chat).copied().unwrap_or(0) };
3169
3170        // 5 contact messages, never read → all unread. No own message, so the ONLY viable anchor
3171        // is last_read (this is the case that used to stick at a permanent count).
3172        for i in 0..5u64 {
3173            save_message(chat, &mk(&format!("m{i}"), 1000 + i)).await.unwrap();
3174        }
3175        assert_eq!(unread().await, 5, "never-read backlog");
3176
3177        // A system event is the newest row (a join notification, after every contact message).
3178        save_system_event_at("sysev", chat, SystemEventType::MemberJoined, "npubX", None, 2000, None, None).await.unwrap();
3179
3180        // last_read pinned to that system event (kind 30078) — the reported bad state.
3181        {
3182            let conn = crate::db::get_write_connection_guard_static().unwrap();
3183            conn.execute(
3184                "UPDATE chats SET last_read = ?1 WHERE chat_identifier = ?2",
3185                rusqlite::params!["sysev", chat],
3186            ).unwrap();
3187        }
3188        assert_eq!(unread().await, 0, "read marker on a system event still clears the badge");
3189    }
3190
3191    // Deleting a message adjusts unread correctly: removing an UNREAD message drops the count by
3192    // one, removing the read MARKER retreats it to the prior message (never collapses to 99+), and
3193    // removing the last read message clears the marker without over-counting.
3194    #[tokio::test]
3195    async fn deleting_a_message_adjusts_unread_without_wedging() {
3196        let (_tmp, _guard) = init_test_db();
3197        let chat = "npub1delunread";
3198        let mk = |id: &str, secs: u64| Message {
3199            id: id.into(), content: "x".into(), at: secs * 1000, mine: false,
3200            npub: Some("npub1sender".to_string()), ..Default::default()
3201        };
3202        let unread = || async { unread_counts().await.unwrap().get(chat).copied().unwrap_or(0) };
3203        let set_marker = |id: &str| {
3204            let conn = crate::db::get_write_connection_guard_static().unwrap();
3205            conn.execute("UPDATE chats SET last_read = ?1 WHERE chat_identifier = ?2",
3206                rusqlite::params![id, chat]).unwrap();
3207        };
3208        let marker = || -> String {
3209            let conn = crate::db::get_db_connection_guard_static().unwrap();
3210            conn.query_row("SELECT last_read FROM chats WHERE chat_identifier = ?1",
3211                rusqlite::params![chat], |r| r.get::<_, String>(0)).unwrap()
3212        };
3213
3214        // m0..m5, read up to m1 → m2,m3,m4,m5 unread.
3215        for i in 0..6u64 { save_message(chat, &mk(&format!("m{i}"), 1000 + i)).await.unwrap(); }
3216        set_marker("m1");
3217        assert_eq!(unread().await, 4, "m2..m5 unread");
3218
3219        // Delete an UNREAD mid-block message → badge drops by one, marker untouched.
3220        delete_event("m3").await.unwrap();
3221        assert_eq!(unread().await, 3, "one unread deleted → badge minus one");
3222        assert_eq!(marker(), "m1", "deleting an unread message leaves the marker alone");
3223
3224        // Delete the read MARKER → retreats to the prior surviving message (m0), unread unchanged.
3225        delete_event("m1").await.unwrap();
3226        assert_eq!(marker(), "m0", "marker retreats to the newest survivor before it");
3227        assert_eq!(unread().await, 3, "retreat keeps the count, no collapse to 99+");
3228
3229        // Delete the last surviving read message → marker clears, still exactly the unread block.
3230        delete_event("m0").await.unwrap();
3231        assert_eq!(marker(), "", "no earlier survivor → marker clears");
3232        assert_eq!(unread().await, 3, "cleared marker counts only the true unread survivors");
3233    }
3234
3235    // Edits are event-sourced for BOTH transports: a MESSAGE_EDIT event folds into the target's
3236    // history on reload (latest content + revisions + the edit's own emoji). Community used to
3237    // overwrite the row and lose all of this — this locks in the unified fold.
3238    #[tokio::test]
3239    async fn edit_event_folds_into_history_on_reload() {
3240        let (_tmp, _guard) = init_test_db();
3241        let chat = "channel_edit_fold";
3242        save_message(chat, &Message {
3243            id: "orig1".into(), content: "original".into(), at: 5_000_000,
3244            npub: Some("npub1author".into()), ..Default::default()
3245        }).await.unwrap();
3246
3247        let cid = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3248        let emoji = vec![crate::types::EmojiTag { shortcode: "wave".into(), url: "u/wave".into() }];
3249        save_edit_event("edit1", "orig1", "edited :wave:", &emoji, &[], cid, None, "npub1author").await.unwrap();
3250
3251        let m = get_message_views(cid, 50, 0).await.unwrap()
3252            .into_iter().find(|m| m.id == "orig1").expect("message reloaded");
3253        assert!(m.edited, "folded edit sets the edited flag");
3254        let h = m.edit_history.as_ref().expect("history reconstructed from the edit event");
3255        assert_eq!(h.len(), 2, "original + one edit");
3256        assert_eq!(h[0].content, "original");
3257        assert_eq!(h[1].content, "edited :wave:");
3258        assert_eq!(m.content, "edited :wave:", "latest revision is the displayed content");
3259        assert_eq!(m.emoji_tags.len(), 1, "the edit's own emoji folds onto the message");
3260        assert_eq!(m.emoji_tags[0].shortcode, "wave");
3261    }
3262
3263    // Colour spans persist in the tags column and fold like emoji: the newest edit's
3264    // spans win, on both the chat page and the boot last-message loaders.
3265    #[tokio::test]
3266    async fn text_spans_persist_and_follow_the_latest_edit() {
3267        use crate::text_color::{ColorSpan, Effect};
3268        use crate::text_spans::{TextSpan, TimeSpan};
3269        let (_tmp, _guard) = init_test_db();
3270        let chat = "npub1colourchat";
3271        let rainbow = TextSpan::Color(ColorSpan { from: 0, to: 5, effect: Effect::Rainbow, colors: vec![] });
3272        save_message(chat, &Message {
3273            id: "c1".into(), content: "hello world".into(), at: 6_000_000,
3274            npub: Some("npub1author".into()), text_spans: vec![rainbow.clone()], ..Default::default()
3275        }).await.unwrap();
3276        let cid = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3277
3278        let page = |m: Vec<Message>| m.into_iter().find(|m| m.id == "c1").expect("message reloaded");
3279        assert_eq!(page(get_message_views(cid, 50, 0).await.unwrap()).text_spans, vec![rainbow]);
3280
3281        let pink = TextSpan::Color(ColorSpan { from: 4, to: 8, effect: Effect::Solid, colors: vec!["#f472b6".into()] });
3282        let time = TextSpan::Time(TimeSpan { from: 13, to: 33, unix: 0, style: 'R' });
3283        let edited = "bye world at 1970-01-01 00:00 UTC";
3284        save_edit_event("c1e", "c1", edited, &[], &[pink.clone(), time.clone()], cid, None, "npub1author").await.unwrap();
3285        assert_eq!(page(get_message_views(cid, 50, 0).await.unwrap()).text_spans, vec![pink.clone(), time.clone()]);
3286        let boot = get_all_chats_last_messages().await.unwrap();
3287        assert_eq!(page(boot.get(chat).cloned().unwrap_or_default()).text_spans, vec![pink, time]);
3288
3289        // A span the content can't hold is dropped, never painted past the end.
3290        save_edit_event("c1f", "c1", "bye", &[], &[TextSpan::Color(ColorSpan { from: 0, to: 9, effect: Effect::Rainbow, colors: vec![] })], cid, None, "npub1author").await.unwrap();
3291        assert!(page(get_message_views(cid, 50, 0).await.unwrap()).text_spans.is_empty());
3292    }
3293
3294    /// Local Encryption on for one test, off again however it ends.
3295    struct SealedVault;
3296    impl SealedVault {
3297        fn on(key: [u8; 32]) -> Self {
3298            crate::state::ENCRYPTION_KEY.set(key, &[]);
3299            crate::state::set_encryption_enabled(true);
3300            SealedVault
3301        }
3302    }
3303    impl Drop for SealedVault {
3304        fn drop(&mut self) {
3305            crate::state::ENCRYPTION_KEY.clear(&[]);
3306            crate::state::set_encryption_enabled(false);
3307        }
3308    }
3309
3310    fn raw_row(id: &str) -> (String, String) {
3311        let conn = crate::db::get_db_connection_guard_static().unwrap();
3312        conn.query_row("SELECT content, tags FROM events WHERE id = ?1", [id], |r| Ok((r.get(0)?, r.get(1)?))).unwrap()
3313    }
3314
3315    /// Every later touch of a stored message re-saves the copy held in memory, which carries
3316    /// the latest edit (or whatever a failed open left): a reaction, a link preview, the send
3317    /// confirming, a re-delivery. None may replace the original as it was written.
3318    #[tokio::test]
3319    async fn touching_a_stored_message_never_rewrites_its_original_under_local_encryption() {
3320        let (_tmp, _guard) = init_test_db();
3321        let _vault = SealedVault::on([0x3c; 32]);
3322        let chat = "channel_touch";
3323        let emoji = |s: &str| vec![crate::types::EmojiTag { shortcode: s.into(), url: format!("u/{s}") }];
3324        save_message(chat, &Message {
3325            id: "touch1".into(), content: "original :wave:".into(), at: 5_000_000, pending: true,
3326            npub: Some("npub1author".into()), emoji_tags: emoji("wave"), ..Default::default()
3327        }).await.unwrap();
3328        let cid = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3329        save_edit_event("touch_edit", "touch1", "edited :cat:", &emoji("cat"), &[], cid, None, "npub1author").await.unwrap();
3330        let written = raw_row("touch1");
3331        assert_eq!(crate::crypto::maybe_decrypt_text(&written.0), "original :wave:");
3332
3333        let (_, mut live) = get_message_by_id("touch1").await.unwrap().unwrap();
3334        assert_eq!(live.content, "edited :cat:", "memory holds the latest edit");
3335        live.reactions.push(Reaction {
3336            id: "touch_react".into(), reference_id: "touch1".into(), author_id: "npub1reactor".into(),
3337            emoji: "🔥".into(), emoji_url: None,
3338        });
3339        save_message(chat, &live).await.unwrap();
3340        live.preview_metadata = Some(crate::types::SiteMetadata {
3341            domain: "example.com".into(), og_title: Some("Example".into()), og_description: None, og_image: None,
3342            og_url: None, og_type: None, title: None, description: None, favicon: None,
3343        });
3344        save_message(chat, &live).await.unwrap();
3345        live.pending = false;
3346        save_message(chat, &live).await.unwrap();
3347        live.content = "[Decryption failed]".into();
3348        save_message(chat, &live).await.unwrap();
3349        save_messages_batch(chat, &[&live]).await.unwrap();
3350
3351        assert_eq!(raw_row("touch1"), written, "the original's sealed text and tags are untouched");
3352        let (_, back) = get_message_by_id("touch1").await.unwrap().unwrap();
3353        assert_eq!(back.content, "edited :cat:");
3354        assert_eq!(back.edit_history.as_ref().unwrap()[0].content, "original :wave:", "history still starts at the original");
3355        assert_eq!(back.reactions.len(), 1, "the reaction landed");
3356        assert_eq!(back.preview_metadata.as_ref().map(|p| p.domain.as_str()), Some("example.com"), "the preview landed");
3357        assert!(!back.pending, "the status moved");
3358    }
3359
3360    /// A file message re-saved when its download completes: the download lands, the row stays.
3361    #[tokio::test]
3362    async fn a_download_resave_keeps_the_row_under_local_encryption() {
3363        let (_tmp, _guard) = init_test_db();
3364        let _vault = SealedVault::on([0x3d; 32]);
3365        let att = |downloaded: bool, path: &str| Attachment {
3366            id: "filehash".into(), url: "https://x/f".into(), name: "f.png".into(), extension: "png".into(),
3367            size: 1, downloaded, path: path.into(), ..Default::default()
3368        };
3369        let msg = |caption: &str, a: Attachment| Message {
3370            id: "file1".into(), content: caption.into(), at: 1_000_000, npub: Some("npub1s".into()),
3371            attachments: vec![a], ..Default::default()
3372        };
3373        save_message("npub1file", &msg("look at this", att(false, ""))).await.unwrap();
3374        let written = raw_row("file1");
3375        save_message("npub1file", &msg("[Decryption failed]", att(true, "/tmp/f.png"))).await.unwrap();
3376        assert_eq!(raw_row("file1"), written);
3377        let (_, back) = get_message_by_id("file1").await.unwrap().unwrap();
3378        assert!(back.attachments[0].downloaded && back.attachments[0].path == "/tmp/f.png");
3379    }
3380
3381    // The bulk-sync persist path: one transaction must land events + attachments + reactions
3382    // with the same shape save_message produces, and slice order must set rowid order (the
3383    // same-timestamp pagination tiebreak).
3384    #[tokio::test]
3385    async fn batched_save_matches_single_save_shape() {
3386        let (_tmp, _guard) = init_test_db();
3387        let chat = "channel_batch1";
3388        let att = crate::types::Attachment {
3389            id: "atthash1".into(), extension: "png".into(), name: "a.png".into(),
3390            url: "https://x/att".into(), downloaded: false, ..Default::default()
3391        };
3392        let reaction = Reaction {
3393            id: "react_b1".into(), reference_id: "b1".into(),
3394            author_id: "npub1reactor".into(), emoji: "👍".into(), emoji_url: None,
3395        };
3396        // Same `at` second across the batch — rowid is the only orderer.
3397        let msgs: Vec<Message> = (0..5u64).map(|i| Message {
3398            id: format!("b{i}"), content: format!("c{i}"), at: 7_000_000,
3399            npub: Some("npub1sender".into()),
3400            attachments: if i == 2 { vec![att.clone()] } else { Vec::new() },
3401            reactions: if i == 1 { vec![reaction.clone()] } else { Vec::new() },
3402            ..Default::default()
3403        }).collect();
3404        let refs: Vec<&Message> = msgs.iter().collect();
3405
3406        let saved = save_messages_batch(chat, &refs).await.unwrap();
3407        assert_eq!(saved, 5, "every message written");
3408
3409        for i in 0..5u64 {
3410            assert!(event_exists(&format!("b{i}")).unwrap(), "b{i} row exists");
3411        }
3412        assert!(event_exists("react_b1").unwrap(), "reaction landed as its own kind-7 row");
3413        let atts = crate::db::attachments::get_attachments_for_event("b2").unwrap();
3414        assert_eq!(atts.len(), 1, "attachment row committed with its event");
3415        assert_eq!(atts[0].id, "atthash1");
3416
3417        // rowid order == slice order despite identical timestamps.
3418        let conn = crate::db::get_db_connection_guard_static().unwrap();
3419        let ids: Vec<String> = conn
3420            .prepare("SELECT id FROM events WHERE id IN ('b0','b1','b2','b3','b4') ORDER BY rowid")
3421            .unwrap()
3422            .query_map([], |r| r.get(0)).unwrap()
3423            .flatten().collect();
3424        assert_eq!(ids, vec!["b0", "b1", "b2", "b3", "b4"], "insert order preserves the rowid tiebreak");
3425    }
3426
3427    /// Register `chat` as a channel of `community` so the ban filter can resolve it.
3428    fn link_channel_to_community(chat: &str, community: &str) {
3429        let conn = crate::db::get_write_connection_guard_static().unwrap();
3430        conn.execute(
3431            "INSERT OR REPLACE INTO community_channels \
3432             (channel_id, community_id, channel_key, epoch, name, created_at) \
3433             VALUES (?1, ?2, x'00', 0, 'general', 0)",
3434            rusqlite::params![chat, community],
3435        )
3436        .unwrap();
3437    }
3438
3439    /// The banlist speaks HEX and `events.npub` speaks bech32 — the store has to
3440    /// bridge them or the filter silently matches nothing in production.
3441    fn ban_pair() -> (String, String) {
3442        let k = nostr_sdk::prelude::Keys::generate();
3443        use nostr_sdk::prelude::ToBech32;
3444        (k.public_key().to_hex(), k.public_key().to_bech32().unwrap())
3445    }
3446
3447    /// A ban hides what the author already posted — not only their next message.
3448    #[tokio::test]
3449    async fn a_banned_authors_messages_are_not_returned() {
3450        let (_tmp, _guard) = init_test_db();
3451        let chat = "channel_ban_hide";
3452        link_channel_to_community(chat, "comm_hide");
3453        let (raider_hex, raider) = ban_pair();
3454        let (_, good) = ban_pair();
3455        for (id, npub, at) in [("keep1", &good, 1_000u64), ("spam1", &raider, 2_000), ("keep2", &good, 3_000)] {
3456            let msg = Message { id: id.into(), content: "hi".into(), at, npub: Some(npub.clone()), ..Default::default() };
3457            save_message(chat, &msg).await.unwrap();
3458        }
3459        crate::db::community::set_community_banlist("comm_hide", &[raider_hex], 1).unwrap();
3460
3461        let chat_id = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3462        let got = get_events(chat_id, None, 50, 0).await.unwrap();
3463        let ids: Vec<&str> = got.iter().map(|e| e.id.as_str()).collect();
3464        assert!(!ids.contains(&"spam1"), "a banned author's existing message must not be returned: {ids:?}");
3465        assert!(ids.contains(&"keep1") && ids.contains(&"keep2"), "everyone else survives: {ids:?}");
3466    }
3467
3468    /// THE pagination guard. Filtering after `LIMIT` returns a short page, which the
3469    /// caller reads as "end of history" — backscroll stops dead behind a wall of
3470    /// banned events. Excluding before `LIMIT` keeps a full page full.
3471    #[tokio::test]
3472    async fn a_wall_of_banned_events_does_not_shorten_the_page() {
3473        let (_tmp, _guard) = init_test_db();
3474        let chat = "channel_ban_page";
3475        link_channel_to_community(chat, "comm_page");
3476        // 40 banned interleaved with 20 real ones, banned strictly newer so a
3477        // naive newest-first page would be nothing but spam.
3478        let (raider_hex, raider) = ban_pair();
3479        let (_, good) = ban_pair();
3480        for i in 0..20u64 {
3481            let msg = Message { id: format!("real{i}"), content: "hi".into(), at: 1_000 + i, npub: Some(good.clone()), ..Default::default() };
3482            save_message(chat, &msg).await.unwrap();
3483        }
3484        for i in 0..40u64 {
3485            let msg = Message { id: format!("spam{i}"), content: "buy".into(), at: 5_000 + i, npub: Some(raider.clone()), ..Default::default() };
3486            save_message(chat, &msg).await.unwrap();
3487        }
3488        crate::db::community::set_community_banlist("comm_page", &[raider_hex], 1).unwrap();
3489
3490        let chat_id = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3491        let page = get_events(chat_id, None, 20, 0).await.unwrap();
3492        assert_eq!(page.len(), 20, "a page of 20 must return 20 real messages, not what is left after filtering");
3493        assert!(page.iter().all(|e| e.npub.as_deref() == Some(good.as_str())), "no banned author leaks into the page");
3494    }
3495
3496    /// The kind-filtered path is the one the app actually calls — a page of chat
3497    /// messages. Covering only the kindless branch left it unguarded.
3498    #[tokio::test]
3499    async fn the_kind_filtered_page_excludes_banned_authors_too() {
3500        let (_tmp, _guard) = init_test_db();
3501        let chat = "channel_ban_kinds";
3502        link_channel_to_community(chat, "comm_kinds");
3503        let (raider_hex, raider) = ban_pair();
3504        let (_, good) = ban_pair();
3505        for i in 0..12u64 {
3506            let msg = Message { id: format!("real{i}"), content: "hi".into(), at: 1_000 + i, npub: Some(good.clone()), ..Default::default() };
3507            save_message(chat, &msg).await.unwrap();
3508        }
3509        for i in 0..30u64 {
3510            let msg = Message { id: format!("spam{i}"), content: "buy".into(), at: 5_000 + i, npub: Some(raider.clone()), ..Default::default() };
3511            save_message(chat, &msg).await.unwrap();
3512        }
3513        crate::db::community::set_community_banlist("comm_kinds", &[raider_hex], 1).unwrap();
3514
3515        let chat_id = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3516        let kinds = [event_kind::PRIVATE_DIRECT_MESSAGE];
3517        let page = get_events(chat_id, Some(&kinds), 12, 0).await.unwrap();
3518        assert_eq!(page.len(), 12, "the kind-filtered page must fill with real messages");
3519        assert!(page.iter().all(|e| e.npub.as_deref() == Some(good.as_str())), "no banned author in a kind-filtered page");
3520    }
3521
3522    /// A ban erases their arrival too. The "has joined" row is a system event
3523    /// carrying the same author, so nothing about a banned account should remain
3524    /// on screen — not the spam, not the trace of them walking in.
3525    #[tokio::test]
3526    async fn a_banned_members_join_event_is_hidden_with_their_messages() {
3527        let (_tmp, _guard) = init_test_db();
3528        let chat = "channel_ban_join";
3529        link_channel_to_community(chat, "comm_join");
3530        let (raider_hex, raider) = ban_pair();
3531
3532        save_system_event_at("joined_evt", chat, SystemEventType::MemberJoined, &raider, None, 4_000, None, None)
3533            .await
3534            .unwrap();
3535        let msg = Message { id: "spam_after_join".into(), content: "buy".into(), at: 5_000, npub: Some(raider.clone()), ..Default::default() };
3536        save_message(chat, &msg).await.unwrap();
3537        let chat_id = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3538        // Present BEFORE the ban, or the assertions below prove nothing.
3539        assert_eq!(get_events(chat_id, None, 50, 0).await.unwrap().len(), 2, "both rows are on record first");
3540
3541        crate::db::community::set_community_banlist("comm_join", &[raider_hex], 1).unwrap();
3542
3543        let got = get_events(chat_id, None, 50, 0).await.unwrap();
3544        let ids: Vec<&str> = got.iter().map(|e| e.id.as_str()).collect();
3545        assert!(!ids.contains(&"joined_evt"), "the join row goes with them: {ids:?}");
3546        assert!(!ids.contains(&"spam_after_join"), "and so does what they said: {ids:?}");
3547    }
3548
3549    /// A badge that counts a banned author sends the reader hunting for a message
3550    /// the client will never render.
3551    #[tokio::test]
3552    async fn a_banned_authors_messages_do_not_badge_the_channel() {
3553        let (_tmp, _guard) = init_test_db();
3554        let chat = "channel_ban_unread";
3555        link_channel_to_community(chat, "comm_unread");
3556        let (raider_hex, raider) = ban_pair();
3557        let (_, good) = ban_pair();
3558
3559        let real = Message { id: "real_unread".into(), content: "hi".into(), at: 1_000, npub: Some(good.clone()), ..Default::default() };
3560        save_message(chat, &real).await.unwrap();
3561        for i in 0..5u64 {
3562            let spam = Message { id: format!("spam_unread{i}"), content: "buy".into(), at: 2_000 + i, npub: Some(raider.clone()), ..Default::default() };
3563            save_message(chat, &spam).await.unwrap();
3564        }
3565        assert_eq!(unread_count_for_chat(chat).await.unwrap(), 6, "before the ban everything counts");
3566
3567        crate::db::community::set_community_banlist("comm_unread", &[raider_hex], 1).unwrap();
3568
3569        assert_eq!(
3570            unread_count_for_chat(chat).await.unwrap(), 1,
3571            "only the message that still renders is counted"
3572        );
3573        let all = unread_counts().await.unwrap();
3574        assert_eq!(all.get(chat).copied().unwrap_or(0), 1, "and the all-chats sweep agrees");
3575    }
3576
3577    #[tokio::test]
3578    async fn a_held_post_is_stored_marked_and_never_badges_or_previews() {
3579        let (_tmp, _guard) = init_test_db();
3580        let chat = "channel_held_unread";
3581        link_channel_to_community(chat, "comm_held");
3582        let (_, good) = ban_pair();
3583        let (_, stranger) = ban_pair();
3584        let real = Message { id: "real_held".into(), content: "hi".into(), at: 1_000, npub: Some(good.clone()), ..Default::default() };
3585        save_message(chat, &real).await.unwrap();
3586        let held = Message { id: "held_post".into(), content: "spam".into(), at: 2_000, npub: Some(stranger), unauthorized: true, ..Default::default() };
3587        save_message(chat, &held).await.unwrap();
3588        assert!(get_message_by_id("held_post").await.unwrap().unwrap().1.unauthorized, "the mark survives a reload");
3589        assert_eq!(unread_count_for_chat(chat).await.unwrap(), 1, "a held post rings nothing");
3590        assert_eq!(unread_counts().await.unwrap().get(chat).copied().unwrap_or(0), 1);
3591        let last = get_all_chats_last_messages().await.unwrap();
3592        assert_eq!(last.get(chat).and_then(|m| m.last()).map(|m| m.id.as_str()), Some("real_held"), "nor previews the chat");
3593        assert!(set_event_unauthorized("held_post", false).unwrap());
3594        assert!(!get_message_by_id("held_post").await.unwrap().unwrap().1.unauthorized);
3595        assert_eq!(unread_count_for_chat(chat).await.unwrap(), 2, "standing, it counts");
3596        assert!(set_event_unauthorized("held_post", true).unwrap());
3597        assert!(get_message_by_id("held_post").await.unwrap().unwrap().1.unauthorized);
3598        assert!(!set_event_unauthorized("missing", true).unwrap());
3599    }
3600
3601    #[tokio::test]
3602    async fn the_held_store_keeps_what_is_dated_near_now_within_its_caps() {
3603        use crate::db::community::{hold_wrap, held_wraps_in, MAX_HELD_BYTES, MAX_HELD_WRAPS};
3604        let (_tmp, _guard) = init_test_db();
3605        let (cid, ch) = ("c".repeat(64), "chan_held_caps".to_string());
3606        link_channel_to_community(&ch, &cid);
3607        let now = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_millis() as u64;
3608        let id = |i: usize| format!("{i:064x}");
3609        assert!(!hold_wrap(&cid, &ch, &id(1), "w", "", now + 2 * 3_600_000).unwrap(), "dated past the horizon, it waits on the relay");
3610        assert!(held_wraps_in(&cid, &ch).unwrap().is_empty());
3611        assert!(community_wraps_settled(&[id(1)]).contains(&id(1)), "and a read leaves it there until its date nears");
3612        // A legitimate post half an hour old outlives a flood dated just inside the horizon.
3613        assert!(hold_wrap(&cid, &ch, &id(2), "legit", "", now - 30 * 60_000).unwrap());
3614        for i in 0..MAX_HELD_WRAPS {
3615            hold_wrap(&cid, &ch, &id(10 + i), "spam", "", now + 55 * 60_000).unwrap();
3616        }
3617        assert!(held_wraps_in(&cid, &ch).unwrap().iter().any(|(w, _)| *w == id(2)), "dated nearer now, it stays");
3618        // Bytes cap too: a few huge wraps can't crowd out the rest beyond the budget.
3619        let (cid2, ch2) = ("d".repeat(64), "chan_held_bytes".to_string());
3620        let big = "x".repeat(MAX_HELD_BYTES / 3);
3621        for i in 0..4 {
3622            hold_wrap(&cid2, &ch2, &id(900 + i), &big, "", now - (i as u64 + 1) * 1_000).unwrap();
3623        }
3624        let kept: Vec<String> = held_wraps_in(&cid2, &ch2).unwrap().into_iter().map(|(w, _)| w).collect();
3625        assert!(kept.len() < 4 && !kept.contains(&id(903)), "the furthest from now goes once the bytes run out: {kept:?}");
3626        // One author can't hold more than a share of a channel, nor a community more than its bytes.
3627        use crate::db::community::{MAX_HELD_COMMUNITY_BYTES, MAX_HELD_PER_AUTHOR};
3628        let (cid3, ch3) = ("e".repeat(64), "chan_held_share".to_string());
3629        assert!(hold_wrap(&cid3, &ch3, &id(1_000), "older, someone else", "bb", now - 20 * 60_000).unwrap());
3630        for i in 0..MAX_HELD_PER_AUTHOR + 5 {
3631            hold_wrap(&cid3, &ch3, &id(1_001 + i), "flood", "aa", now - i as u64).unwrap();
3632        }
3633        let kept = held_wraps_in(&cid3, &ch3).unwrap();
3634        assert_eq!(kept.len(), MAX_HELD_PER_AUTHOR + 1, "the flood keeps its share and no more");
3635        assert!(kept.iter().any(|(w, _)| *w == id(1_000)));
3636        let cid4 = "f".repeat(64);
3637        let fifth = "y".repeat(MAX_HELD_COMMUNITY_BYTES / 5);
3638        for i in 0..6 {
3639            hold_wrap(&cid4, &format!("chan_held_c{i}"), &id(2_000 + i), &fifth, "", now - (i as u64 + 1) * 60_000).unwrap();
3640        }
3641        assert!(held_wraps_in(&cid4, "chan_held_c5").unwrap().is_empty(), "the community's bytes run out on the furthest from now");
3642        assert!(!held_wraps_in(&cid4, "chan_held_c0").unwrap().is_empty());
3643        // A flood in one Channel gives up its own before another Channel loses anything.
3644        let cid5 = "9".repeat(64);
3645        let tenth = "z".repeat(MAX_HELD_COMMUNITY_BYTES / 10);
3646        hold_wrap(&cid5, "chan_held_quiet", &id(3_000), &tenth, "q", now - 50 * 60_000).unwrap();
3647        for i in 0..4 {
3648            for c in 0..5 {
3649                hold_wrap(&cid5, &format!("chan_held_flood{c}"), &id(3_100 + c * 10 + i), &tenth, &format!("f{i}"), now - i as u64).unwrap();
3650            }
3651        }
3652        assert_eq!(held_wraps_in(&cid5, "chan_held_quiet").unwrap().len(), 1, "the quiet channel keeps its one");
3653        let flood: usize = (0..5).map(|c| held_wraps_in(&cid5, &format!("chan_held_flood{c}")).unwrap().len()).sum();
3654        assert_eq!(flood, 9, "the floods give up one between them once the community's bytes run out");
3655        // What waits for its date is bounded, the furthest-dated dropped first.
3656        use crate::db::community::MAX_DEFERRED;
3657        for i in 0..=MAX_DEFERRED {
3658            hold_wrap(&cid, &ch, &id(10_000 + i), "w", "", now + 2 * 3_600_000 + i as u64).unwrap();
3659        }
3660        assert!(!community_wraps_settled(&[id(10_000 + MAX_DEFERRED)]).contains(&id(10_000 + MAX_DEFERRED)), "dropped, it is only read again");
3661        assert!(community_wraps_settled(&[id(10_000)]).contains(&id(10_000)));
3662        // A manager's flagged copy goes with its wrap.
3663        let msg = Message { id: "held_copy".into(), content: "spam".into(), at: now - 10 * 60_000, npub: Some(ban_pair().1), unauthorized: true, wrapper_event_id: Some(id(950)), ..Default::default() };
3664        save_message(&ch, &msg).await.unwrap();
3665        assert!(get_message_by_id("held_copy").await.unwrap().is_some());
3666        hold_wrap(&cid, &ch, &id(950), "spam", "", now + 58 * 60_000).unwrap();
3667        assert!(get_message_by_id("held_copy").await.unwrap().is_none(), "evicted at once, and its copy with it");
3668    }
3669
3670    /// Join/leave lines have their OWN query — the chat page never sees them — so
3671    /// filtering the message page alone left a wall of "has joined" from accounts
3672    /// whose every message the client already refused to render.
3673    #[tokio::test]
3674    async fn a_banned_members_join_line_is_dropped_from_the_system_feed() {
3675        let (_tmp, _guard) = init_test_db();
3676        let chat = "channel_ban_sysfeed";
3677        link_channel_to_community(chat, "comm_sysfeed");
3678        let (raider_hex, raider) = ban_pair();
3679        let (_, good) = ban_pair();
3680
3681        for (id, who) in [("join_good", &good), ("join_raider", &raider)] {
3682            save_system_event_at(id, chat, SystemEventType::MemberJoined, who, None, 1_000, None, None)
3683                .await
3684                .unwrap();
3685        }
3686        assert_eq!(get_system_events_for_chat(chat).unwrap().len(), 2, "both arrivals are on record");
3687
3688        crate::db::community::set_community_banlist("comm_sysfeed", &[raider_hex], 1).unwrap();
3689
3690        let feed = get_system_events_for_chat(chat).unwrap();
3691        let ids: Vec<&str> = feed.iter().map(|e| e.id.as_str()).collect();
3692        assert_eq!(ids, vec!["join_good"], "the banned member's arrival goes with their messages");
3693    }
3694
3695    /// A moderator's delete has to outlive the row it removed.
3696    ///
3697    /// Dropping the events row alone only hides the message until the next full
3698    /// sync re-serves the original from a relay: nothing recorded that it was
3699    /// removed, so it re-ingests cleanly and the deletion silently undoes itself.
3700    /// Observed live — an image Sentinel deleted for NSFW reappeared after a
3701    /// cold resync.
3702    #[tokio::test]
3703    async fn a_moderated_delete_survives_the_message_being_re_ingested() {
3704        let (_tmp, _guard) = init_test_db();
3705        let chat = "channel_delete_resync";
3706        let (_, author) = ban_pair();
3707        let msg = Message { id: "moderated_evt".into(), content: "nsfw".into(), at: 1_000, npub: Some(author.clone()), ..Default::default() };
3708        save_message(chat, &msg).await.unwrap();
3709
3710        // What the moderation path does on receiving the delete.
3711        crate::state::note_message_deleted("moderated_evt");
3712        add_message_tombstone("moderated_evt").unwrap();
3713        delete_event("moderated_evt").await.unwrap();
3714
3715        let chat_id = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3716        assert!(get_events(chat_id, None, 50, 0).await.unwrap().is_empty(), "removed on the spot");
3717
3718        // The relay re-serves the original on the next sync.
3719        assert!(
3720            crate::state::was_message_deleted("moderated_evt"),
3721            "the refusal outlives the row, so the re-ingest is dropped rather than resurrecting it"
3722        );
3723    }
3724
3725    /// Backscroll windows around an anchor, so a ban has to hold there too —
3726    /// otherwise jump-to-message walks straight back into the spam the chat page
3727    /// refuses to show.
3728    #[tokio::test]
3729    async fn the_backscroll_window_excludes_banned_authors() {
3730        let (_tmp, _guard) = init_test_db();
3731        let chat = "channel_ban_window";
3732        link_channel_to_community(chat, "comm_window");
3733        let (raider_hex, raider) = ban_pair();
3734        let (_, good) = ban_pair();
3735
3736        for i in 0..10u64 {
3737            let m = Message { id: format!("w_real{i}"), content: "hi".into(), at: 1_000 + i, npub: Some(good.clone()), ..Default::default() };
3738            save_message(chat, &m).await.unwrap();
3739            let s = Message { id: format!("w_spam{i}"), content: "buy".into(), at: 1_500 + i, npub: Some(raider.clone()), ..Default::default() };
3740            save_message(chat, &s).await.unwrap();
3741        }
3742        crate::db::community::set_community_banlist("comm_window", &[raider_hex], 1).unwrap();
3743
3744        let chat_id = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3745        let win = get_messages_around(chat_id, "w_real5", 20, 20).await.unwrap();
3746        assert!(!win.is_empty(), "the window still returns the real messages");
3747        assert!(
3748            win.iter().all(|m| m.npub.as_deref() == Some(good.as_str())),
3749            "no banned author reachable by jumping to a message near them",
3750        );
3751    }
3752
3753    #[tokio::test]
3754    async fn a_message_position_counts_what_sorts_after_it_without_banned_authors() {
3755        let (_tmp, _guard) = init_test_db();
3756        let chat = "channel_position";
3757        link_channel_to_community(chat, "comm_position");
3758        let (raider_hex, raider) = ban_pair();
3759        let (_, good) = ban_pair();
3760        for i in 0..10u64 {
3761            let m = Message { id: format!("p_real{i}"), content: "hi".into(), at: 1_000_000 + i * 1_000, npub: Some(good.clone()), ..Default::default() };
3762            save_message(chat, &m).await.unwrap();
3763        }
3764        let spam = Message { id: "p_spam".into(), content: "buy".into(), at: 1_009_500, npub: Some(raider.clone()), ..Default::default() };
3765        save_message(chat, &spam).await.unwrap();
3766        let chat_id = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3767
3768        assert_eq!(get_message_position(chat_id, "p_real3").unwrap(), Some(MessagePosition { newer: 7, total: 11 }));
3769        crate::db::community::set_community_banlist("comm_position", &[raider_hex], 1).unwrap();
3770        assert_eq!(get_message_position(chat_id, "p_real3").unwrap(), Some(MessagePosition { newer: 6, total: 10 }));
3771        assert_eq!(get_message_position(chat_id, "p_real9").unwrap(), Some(MessagePosition { newer: 0, total: 10 }));
3772        assert_eq!(get_message_position(chat_id, "missing").unwrap(), None);
3773
3774        assert_eq!(get_message_time_at(chat_id, 0).unwrap(), Some(1_009_000));
3775        assert_eq!(get_message_time_at(chat_id, 6).unwrap(), Some(1_003_000), "the spam row no longer counts");
3776        assert_eq!(get_message_time_at(chat_id, 10).unwrap(), None);
3777    }
3778
3779    /// A DM has no community, so the predicate must not exclude anything.
3780    #[tokio::test]
3781    async fn a_dm_is_unaffected_by_the_ban_filter() {
3782        let (_tmp, _guard) = init_test_db();
3783        let chat = "npub1peer_dm";
3784        let msg = Message { id: "dm1".into(), content: "hi".into(), at: 1_000, npub: Some("npub1peer".into()), ..Default::default() };
3785        save_message(chat, &msg).await.unwrap();
3786        let chat_id = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3787        assert_eq!(get_events(chat_id, None, 50, 0).await.unwrap().len(), 1, "a DM resolves no community and filters nothing");
3788    }
3789
3790    // A batched re-save must keep save_message's upsert semantics: wrapper_event_id is
3791    // COALESCE-preserved, and a duplicate reaction in the batch never doubles its row.
3792    #[tokio::test]
3793    async fn batched_resave_preserves_wrapper_and_dedups_reactions() {
3794        let (_tmp, _guard) = init_test_db();
3795        let chat = "channel_batch2";
3796        let reaction = Reaction {
3797            id: "react_rs".into(), reference_id: "rs1".into(),
3798            author_id: "npub1reactor".into(), emoji: "🔥".into(), emoji_url: None,
3799        };
3800        let mut msg = Message {
3801            id: "rs1".into(), content: "hello".into(), at: 8_000_000,
3802            npub: Some("npub1sender".into()),
3803            wrapper_event_id: Some("wrap_original".into()),
3804            reactions: vec![reaction],
3805            ..Default::default()
3806        };
3807        save_message(chat, &msg).await.unwrap();
3808
3809        // Re-delivery re-save without a wrapper id, reaction still attached.
3810        msg.wrapper_event_id = None;
3811        let saved = save_messages_batch(chat, &[&msg]).await.unwrap();
3812        assert_eq!(saved, 1);
3813
3814        let conn = crate::db::get_db_connection_guard_static().unwrap();
3815        let wrapper: Option<String> = conn.query_row(
3816            "SELECT wrapper_event_id FROM events WHERE id = 'rs1'", [], |r| r.get(0),
3817        ).unwrap();
3818        assert_eq!(wrapper.as_deref(), Some("wrap_original"), "COALESCE keeps the known wrapper");
3819        let reaction_rows: i64 = conn.query_row(
3820            "SELECT COUNT(*) FROM events WHERE id = 'react_rs'", [], |r| r.get(0),
3821        ).unwrap();
3822        assert_eq!(reaction_rows, 1, "reaction row not duplicated by the re-save");
3823    }
3824
3825    // The DM stream's multi-chat flush: one call, one transaction, rows land under their own
3826    // chats with their gift-wrap ledger entries; a flush against a stale session drops the
3827    // buffer AND leaves the wrappers unledgered (that's what makes the drop recoverable).
3828    #[tokio::test]
3829    async fn batching_persist_flushes_multi_chat_and_drains_into_the_account_that_filled_it() {
3830        let (_tmp, _guard) = init_test_db();
3831        let handler = crate::event_handler::NoOpEventHandler;
3832        let batcher = crate::event_handler::BatchingPersist::new(&handler);
3833
3834        let mk = |id: &str, npub: &str| Message {
3835            id: id.into(), content: "x".into(), at: 9_000_000,
3836            npub: Some(npub.into()), ..Default::default()
3837        };
3838        // Mirror the commit path: buffering only ever happens AFTER the STATE add (the
3839        // flush drops anything not STATE-resident as deletion protection).
3840        let seed = |chat: &str, m: &Message| {
3841            let m = m.clone();
3842            let chat = chat.to_string();
3843            async move {
3844                let mut st = crate::state::STATE.lock().await;
3845                st.add_message_to_participant(&chat, &m);
3846            }
3847        };
3848        let wrap_a1 = ([0xA1u8; 32], 111u64);
3849        let wrap_b1 = ([0xB1u8; 32], 222u64);
3850        let a1 = mk("bp_a1", "npub1chata");
3851        let b1 = mk("bp_b1", "npub1chatb");
3852        let a2 = mk("bp_a2", "npub1chata");
3853        seed("npub1chata", &a1).await;
3854        seed("npub1chatb", &b1).await;
3855        seed("npub1chata", &a2).await;
3856
3857        use crate::event_handler::InboundEventHandler;
3858        assert!(batcher.buffer_persist("npub1chata", &a1, Some(wrap_a1)), "batcher owns the persist");
3859        assert!(batcher.buffer_persist("npub1chatb", &b1, Some(wrap_b1)));
3860        assert!(batcher.buffer_persist("npub1chata", &a2, None));
3861        assert_eq!(batcher.buffered(), 3);
3862
3863        let ledgered = |bytes: [u8; 32]| {
3864            let id = nostr_sdk::prelude::EventId::from_byte_array(bytes);
3865            crate::db::wrappers::load_negentropy_items().unwrap().iter().any(|(e, _)| *e == id)
3866        };
3867        assert!(!ledgered(wrap_a1.0), "wrapper unledgered while its message sits buffered");
3868
3869        assert_eq!(batcher.flush().await, 3, "all buffered messages written");
3870        assert_eq!(batcher.buffered(), 0);
3871        assert!(event_exists("bp_a1").unwrap() && event_exists("bp_b1").unwrap() && event_exists("bp_a2").unwrap());
3872        assert!(ledgered(wrap_a1.0) && ledgered(wrap_b1.0), "wrappers ledgered with the flush");
3873        let a = crate::db::id_cache::get_chat_id_by_identifier("npub1chata").unwrap();
3874        let b = crate::db::id_cache::get_chat_id_by_identifier("npub1chatb").unwrap();
3875        assert_ne!(a, b, "rows grouped under their own chats");
3876
3877        // A swap between buffering and flushing. The batcher holds the account
3878        // that filled it, so the drain lands there rather than in whoever is
3879        // live by the time it runs — the buffer is one account's inbox.
3880        let filled_under = crate::db::current_session();
3881        let late = mk("bp_late", "npub1chata");
3882        seed("npub1chata", &late).await;
3883        let wrap_late = ([0x5Eu8; 32], 333u64);
3884        batcher.buffer_persist("npub1chata", &late, Some(wrap_late));
3885
3886        let next = make_test_npub(TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
3887        std::fs::create_dir_all(crate::db::shared_test_data_dir().join(&next)).unwrap();
3888        crate::db::set_current_account(next.clone()).unwrap();
3889        crate::db::init_database(&next).unwrap();
3890
3891        assert_eq!(batcher.flush().await, 1, "the buffer still drains");
3892        assert!(
3893            crate::db::with_session(filled_under, async {
3894                event_exists("bp_late").unwrap() && ledgered(wrap_late.0)
3895            })
3896            .await,
3897            "written to the account that received it, and its wrapper ledgered there"
3898        );
3899        assert!(!event_exists("bp_late").unwrap(), "the account swapped in never sees it");
3900        assert_eq!(batcher.buffered(), 0, "and the buffer is empty either way");
3901    }
3902
3903    // A deletion landing while its target sits buffered must not resurrect the message:
3904    // the same-task path purges via on_message_deleted, and the cross-task path (live
3905    // subscription, different handler) is caught by the flush's deletion-tombstone filter.
3906    // The filter keys on the POSITIVE tombstone, never STATE absence — an LRU-evicted (but
3907    // not deleted) message MUST still persist and ledger, or archive sync could silently
3908    // drop the exact history it exists to persist.
3909    #[tokio::test]
3910    async fn role_mentions_survive_a_reload() {
3911        let (_tmp, _guard) = init_test_db();
3912        let ids = vec!["ab".repeat(32), "cd".repeat(32)];
3913        let msg = Message { id: "pings-a-role".into(), content: "@Raid Team go".into(), at: 1_000_000, role_mentions: ids.clone(), ..Default::default() };
3914        save_message("npub1roles", &msg).await.unwrap();
3915        let (_, back) = get_message_by_id("pings-a-role").await.unwrap().unwrap();
3916        assert_eq!(back.role_mentions, ids, "through the message view");
3917        let last = get_all_chats_last_messages().await.unwrap();
3918        let row = last.values().flatten().find(|m| m.id == "pings-a-role").unwrap();
3919        assert_eq!(row.role_mentions, ids, "and the chat list's last messages");
3920    }
3921
3922    #[tokio::test]
3923    async fn the_chat_lists_last_message_is_the_newest_to_the_millisecond() {
3924        let (_tmp, _guard) = init_test_db();
3925        let chat = "npub1samesecond";
3926        let later = Message { id: "sent-later".into(), content: "b".into(), at: 1_793_470_953_878, ..Default::default() };
3927        let earlier = Message { id: "sent-earlier".into(), content: "a".into(), at: 1_793_470_953_000, ..Default::default() };
3928        save_message(chat, &later).await.unwrap();
3929        save_message(chat, &earlier).await.unwrap();
3930        // The earlier one arrived last, as a catch-up batch can deliver them.
3931        crate::db::get_write_connection_guard_static().unwrap()
3932            .execute("UPDATE events SET received_at = received_at + 1000 WHERE id = 'sent-earlier'", [])
3933            .unwrap();
3934        let last = get_all_chats_last_messages().await.unwrap();
3935        let row = last.get(chat).and_then(|m| m.last()).unwrap();
3936        assert_eq!(row.id, "sent-later", "the newest by its ms, not by arrival");
3937        assert_eq!(row.at, 1_793_470_953_878, "and dated to the ms the chat view shows");
3938    }
3939
3940    #[tokio::test]
3941    async fn a_writer_posts_provenance_survives_a_reload() {
3942        let (_tmp, _guard) = init_test_db();
3943        let msg = Message { id: "from-a-writer".into(), content: "announced".into(), at: 1_000_000, writer: true, ..Default::default() };
3944        save_message("npub1writers", &msg).await.unwrap();
3945        let (_, back) = get_message_by_id("from-a-writer").await.unwrap().unwrap();
3946        assert!(back.writer, "through the message view");
3947        let last = get_all_chats_last_messages().await.unwrap();
3948        assert!(last.values().flatten().find(|m| m.id == "from-a-writer").unwrap().writer, "and the chat list's last messages");
3949        let plain = Message { id: "from-the-open".into(), content: "said".into(), at: 1_000_001, ..Default::default() };
3950        save_message("npub1writers", &plain).await.unwrap();
3951        assert!(!get_message_by_id("from-the-open").await.unwrap().unwrap().1.writer);
3952    }
3953
3954    #[tokio::test]
3955    async fn a_delete_tombstone_survives_a_restart() {
3956        // NIP-09 is best-effort: a relay that ignored it re-serves the wrap days
3957        // later. The events row is gone by then and the in-session tombstone set
3958        // died with the process — only the durable row lets ingest keep refusing.
3959        let (_tmp, _guard) = init_test_db();
3960        let msg = Message {
3961            id: "resurrect-me".into(), content: "note".into(), at: 1_000_000,
3962            mine: true, ..Default::default()
3963        };
3964        save_message("npub1notes", &msg).await.unwrap();
3965        add_message_tombstone("resurrect-me").unwrap();
3966        delete_event("resurrect-me").await.unwrap();
3967
3968        // Simulated restart/swap: the in-session set dies...
3969        crate::db::close_database();
3970        assert!(!crate::state::was_message_deleted("resurrect-me"), "session set cleared");
3971        // ...and account init re-seeds the refusal from the durable rows.
3972        crate::state::seed_message_tombstones(load_message_tombstones().unwrap());
3973        assert!(crate::state::was_message_deleted("resurrect-me"), "the durable tombstone re-seeds");
3974    }
3975
3976    #[tokio::test]
3977    async fn buffered_message_deleted_before_flush_never_persists() {
3978        let (_tmp, _guard) = init_test_db();
3979        let handler = crate::event_handler::NoOpEventHandler;
3980        let batcher = crate::event_handler::BatchingPersist::new(&handler);
3981        use crate::event_handler::InboundEventHandler;
3982
3983        let chat = "npub1delchat";
3984        let mk = |id: &str| Message {
3985            id: id.into(), content: "x".into(), at: 9_500_000,
3986            npub: Some(chat.into()), ..Default::default()
3987        };
3988        let ledgered = |bytes: [u8; 32]| {
3989            let id = nostr_sdk::prelude::EventId::from_byte_array(bytes);
3990            crate::db::wrappers::load_negentropy_items().unwrap().iter().any(|(e, _)| *e == id)
3991        };
3992
3993        // Same-task deletion (sync stream): commit_deletion fires on_message_deleted on
3994        // the batching handler → the buffered entry purges immediately.
3995        let m1 = mk("del_sametask");
3996        {
3997            let mut st = crate::state::STATE.lock().await;
3998            st.add_message_to_participant(chat, &m1);
3999        }
4000        batcher.buffer_persist(chat, &m1, Some(([0xD1u8; 32], 444)));
4001        {
4002            let mut st = crate::state::STATE.lock().await;
4003            st.remove_message("del_sametask");
4004        }
4005        batcher.on_message_deleted(chat, "del_sametask");
4006        assert_eq!(batcher.buffered(), 0, "deletion purges the buffered target");
4007
4008        // Cross-task deletion (live subscription, plain handler): no purge call — the
4009        // deletion tombstone (recorded by commit_deletion) drops it at flush time.
4010        let m2 = mk("del_crosstask");
4011        {
4012            let mut st = crate::state::STATE.lock().await;
4013            st.add_message_to_participant(chat, &m2);
4014        }
4015        batcher.buffer_persist(chat, &m2, Some(([0xD2u8; 32], 555)));
4016        crate::state::note_message_deleted("del_crosstask");
4017
4018        // LRU eviction is NOT deletion: gone from STATE, no tombstone → must persist.
4019        let m3 = mk("evicted_ok");
4020        let wrap_evicted = ([0xE0u8; 32], 666u64);
4021        {
4022            let mut st = crate::state::STATE.lock().await;
4023            st.add_message_to_participant(chat, &m3);
4024            st.remove_message("evicted_ok");
4025        }
4026        batcher.buffer_persist(chat, &m3, Some(wrap_evicted));
4027
4028        assert_eq!(batcher.flush().await, 1, "tombstoned target dropped, evicted message written");
4029        assert!(!event_exists("del_sametask").unwrap(), "purged message never persisted");
4030        assert!(!event_exists("del_crosstask").unwrap(), "tombstoned message never persisted");
4031        assert!(event_exists("evicted_ok").unwrap(), "evicted-but-not-deleted message persisted");
4032        assert!(ledgered(wrap_evicted.0), "evicted message's wrapper ledgered with it");
4033    }
4034}
4035
4036/// The stored context a pin proof needs to recover a message's wrap: its
4037/// `wrapper_event_id` and the rumor's stored tags (for the epoch binding).
4038/// `(wrapper_event_id, rumor tags)`.
4039type WrapContext = (Option<String>, Vec<Vec<String>>);
4040
4041pub fn get_event_wrap_context(event_id: &str) -> Result<Option<WrapContext>, String> {
4042    let conn = super::get_db_connection_guard_static()?;
4043    let row: Option<(Option<String>, String)> = conn
4044        .query_row(
4045            "SELECT wrapper_event_id, tags FROM events WHERE id = ?1",
4046            rusqlite::params![event_id],
4047            |r| Ok((r.get(0)?, r.get(1)?)),
4048        )
4049        .optional()
4050        .map_err(|e| format!("get wrap context: {e}"))?;
4051    Ok(row.map(|(wrap, tags_json)| {
4052        let tags: Vec<Vec<String>> = serde_json::from_str(&tags_json).unwrap_or_default();
4053        (wrap, tags)
4054    }))
4055}