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    Ok(events)
1078}
1079
1080// ============================================================================
1081// Event Read Operations
1082// ============================================================================
1083
1084/// Helper to parse a SQLite row into a StoredEvent.
1085fn parse_event_row(row: &rusqlite::Row) -> rusqlite::Result<StoredEvent> {
1086    let tags_json: String = row.get(5)?;
1087    let tags: Vec<Vec<String>> = serde_json::from_str(&tags_json).unwrap_or_default();
1088
1089    Ok(StoredEvent {
1090        id: row.get(0)?,
1091        kind: row.get::<_, i32>(1)? as u16,
1092        chat_id: row.get(2)?,
1093        user_id: row.get(3)?,
1094        content: row.get(4)?,
1095        tags,
1096        reference_id: row.get(6)?,
1097        created_at: row.get::<_, i64>(7)? as u64,
1098        received_at: row.get::<_, i64>(8)? as u64,
1099        mine: row.get::<_, i32>(9)? != 0,
1100        pending: row.get::<_, i32>(10)? != 0,
1101        failed: row.get::<_, i32>(11)? != 0,
1102        wrapper_event_id: row.get(12)?,
1103        npub: row.get(13)?,
1104        preview_metadata: row.get(14)?,
1105    })
1106}
1107
1108/// The community this chat's channel belongs to, or `None` for a DM.
1109///
1110/// Resolved once per query rather than joined per row: the ban predicate then
1111/// seeks `community_bans`' primary key instead of walking chats -> channels for
1112/// every candidate event.
1113fn community_of_chat(conn: &rusqlite::Connection, chat_id: i64) -> Option<String> {
1114    conn.prepare_cached(
1115        "SELECT cc.community_id FROM community_channels cc \
1116         JOIN chats c ON c.chat_identifier = cc.channel_id WHERE c.id = ?1",
1117    )
1118    .ok()?
1119    .query_row(rusqlite::params![chat_id], |r| r.get::<_, String>(0))
1120    .ok()
1121}
1122
1123/// An id list as one JSON array parameter, read in SQL through `json_each(?)`: one statement
1124/// for any list length, so it prepares once per connection and stays cached.
1125pub(super) fn id_list_param(ids: &[String]) -> String {
1126    serde_json::to_string(ids).unwrap_or_else(|_| "[]".into())
1127}
1128
1129/// Excludes a banned author's events BEFORE `LIMIT`.
1130///
1131/// A ban has to hide what they already posted, not just stop the next message —
1132/// and it has to do it here, in SQL. Filtering the page after it is fetched
1133/// returns fewer rows than asked for, which reads to the caller as "end of
1134/// history": backscroll stops early, and a wall of banned events hides
1135/// everything older than itself. `?{n}` is NULL for a DM, where the whole
1136/// predicate short-circuits.
1137fn ban_filter_sql(param: usize) -> String {
1138    format!(
1139        " AND (?{param} IS NULL OR events.npub IS NULL OR events.npub NOT IN ( \
1140            SELECT value FROM json_each(?{param})))"
1141    )
1142}
1143
1144/// The banned authors of a chat's community as a JSON array of npubs, the parameter
1145/// `ban_filter_sql` reads; `None` for a DM or a community with no bans. Bans are sealed at
1146/// rest, so SQL is handed the opened list, from the write-through cache.
1147fn ban_param(conn: &rusqlite::Connection, chat_id: i64) -> Option<String> {
1148    banned_npubs_json(&community_of_chat(conn, chat_id)?)
1149}
1150
1151fn banned_npubs_json(community_id: &str) -> Option<String> {
1152    use nostr_sdk::prelude::ToBech32;
1153    let set = super::community::banned_set(community_id);
1154    if set.is_empty() {
1155        return None;
1156    }
1157    let npubs: Vec<String> = set
1158        .iter()
1159        .filter_map(|b| nostr_sdk::prelude::PublicKey::from_slice(b).ok()?.to_bech32().ok())
1160        .collect();
1161    serde_json::to_string(&npubs).ok()
1162}
1163
1164/// Every community's bans as `"<community_id> <npub>"` strings, for the all-chats unread count.
1165fn all_ban_pairs_json(conn: &rusqlite::Connection) -> String {
1166    use nostr_sdk::prelude::ToBech32;
1167    let communities: Vec<String> = conn
1168        .prepare_cached("SELECT DISTINCT community_id FROM community_bans")
1169        .and_then(|mut st| st.query_map([], |r| r.get::<_, String>(0)).map(|rows| rows.flatten().collect()))
1170        .unwrap_or_default();
1171    let mut pairs = Vec::new();
1172    for cid in communities {
1173        for b in super::community::banned_set(&cid).iter() {
1174            if let Some(npub) = nostr_sdk::prelude::PublicKey::from_slice(b).ok().and_then(|pk| pk.to_bech32().ok()) {
1175                pairs.push(format!("{cid} {npub}"));
1176            }
1177        }
1178    }
1179    serde_json::to_string(&pairs).unwrap_or_else(|_| "[]".into())
1180}
1181
1182/// Get events for a chat with pagination, optionally filtered by kind.
1183/// Message/edit content is decrypted in one at-rest batch.
1184pub async fn get_events(
1185    chat_id: i64,
1186    kinds: Option<&[u16]>,
1187    limit: usize,
1188    offset: usize,
1189) -> Result<Vec<StoredEvent>, String> {
1190    let events: Vec<StoredEvent> = {
1191        let conn = super::get_db_connection_guard_static()?;
1192        let community = ban_param(&conn, chat_id);
1193
1194        if let Some(k) = kinds {
1195            let kind_placeholders: String = (0..k.len())
1196                .map(|i| format!("?{}", i + 2))
1197                .collect::<Vec<_>>()
1198                .join(",");
1199            let limit_param = k.len() + 2;
1200            let offset_param = k.len() + 3;
1201            let community_param = k.len() + 4;
1202
1203            let sql = format!(
1204                "SELECT id, kind, chat_id, user_id, content, tags, reference_id, \
1205                 created_at, received_at, mine, pending, failed, wrapper_event_id, npub, preview_metadata \
1206                 FROM events WHERE chat_id = ?1 AND kind IN ({}){} \
1207                 ORDER BY created_at DESC, received_at DESC \
1208                 LIMIT ?{} OFFSET ?{}",
1209                kind_placeholders, ban_filter_sql(community_param), limit_param, offset_param
1210            );
1211
1212            let mut stmt = conn.prepare_cached(&sql)
1213                .map_err(|e| format!("Failed to prepare events query: {}", e))?;
1214
1215            match k.len() {
1216                1 => {
1217                    let rows = stmt.query_map(
1218                        rusqlite::params![chat_id, k[0] as i32, limit as i64, offset as i64, community],
1219                        parse_event_row
1220                    ).map_err(|e| format!("Failed to query events: {}", e))?;
1221                    rows.filter_map(|r| r.ok()).collect()
1222                },
1223                2 => {
1224                    let rows = stmt.query_map(
1225                        rusqlite::params![chat_id, k[0] as i32, k[1] 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                3 => {
1231                    let rows = stmt.query_map(
1232                        rusqlite::params![chat_id, k[0] as i32, k[1] as i32, k[2] 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                _ => return Err("Unsupported number of kinds".to_string()),
1238            }
1239        } else {
1240            let mut stmt = conn.prepare_cached(
1241                &format!("SELECT id, kind, chat_id, user_id, content, tags, reference_id, \
1242                 created_at, received_at, mine, pending, failed, wrapper_event_id, npub, preview_metadata \
1243                 FROM events WHERE chat_id = ?1{} \
1244                 ORDER BY created_at DESC, received_at DESC \
1245                 LIMIT ?2 OFFSET ?3", ban_filter_sql(4))
1246            ).map_err(|e| format!("Failed to prepare events query: {}", e))?;
1247
1248            let rows = stmt.query_map(
1249                rusqlite::params![chat_id, limit as i64, offset as i64, community],
1250                parse_event_row
1251            ).map_err(|e| format!("Failed to query events: {}", e))?;
1252            rows.filter_map(|r| r.ok()).collect()
1253        }
1254    };
1255
1256    // Decrypt message content
1257    let decrypted: Vec<StoredEvent> = crate::crypto::open_batch(|at_rest| events.into_iter().map(|mut event| {
1258        if event.kind == event_kind::CHAT_MESSAGE || event.kind == event_kind::PRIVATE_DIRECT_MESSAGE {
1259            event.content = at_rest.open(event.content)
1260                .unwrap_or_else(|_| "[Decryption failed]".to_string());
1261        }
1262        event
1263    }).collect());
1264
1265    Ok(decrypted)
1266}
1267
1268/// Get events that reference specific message IDs (reactions, edits).
1269pub async fn get_related_events(
1270    reference_ids: &[String],
1271) -> Result<Vec<StoredEvent>, String> {
1272    if reference_ids.is_empty() {
1273        return Ok(Vec::new());
1274    }
1275
1276    let conn = super::get_db_connection_guard_static()?;
1277    let mut stmt = conn.prepare_cached(
1278        "SELECT id, kind, chat_id, user_id, content, tags, reference_id, \
1279         created_at, received_at, mine, pending, failed, wrapper_event_id, npub, preview_metadata \
1280         FROM events WHERE reference_id IN (SELECT value FROM json_each(?1)) \
1281         ORDER BY created_at ASC, received_at ASC",
1282    )
1283    .map_err(|e| format!("Failed to prepare related events query: {}", e))?;
1284
1285    let events: Vec<StoredEvent> = stmt.query_map([id_list_param(reference_ids)], parse_event_row)
1286        .map_err(|e| format!("Failed to query related events: {}", e))?
1287        .filter_map(|r| r.ok())
1288        .collect();
1289
1290    Ok(events)
1291}
1292
1293/// Context data for a replied-to message.
1294pub struct ReplyContext {
1295    pub content: String,
1296    pub npub: Option<String>,
1297    pub has_attachment: bool,
1298    /// Extension of the attachment, when the replied-to message is a file, so
1299    /// the reply quote can label the type even when the target is off-screen.
1300    pub extension: Option<String>,
1301    /// The target's NIP-30 emoji tags — without them an off-screen quote
1302    /// renders raw `:shortcodes:` and nothing ever corrects it.
1303    pub emoji_tags: Vec<crate::types::EmojiTag>,
1304}
1305
1306/// Fetch reply context for a list of message IDs.
1307pub async fn get_reply_contexts(
1308    message_ids: &[String],
1309) -> Result<std::collections::HashMap<String, ReplyContext>, String> {
1310    use std::collections::HashMap;
1311
1312    if message_ids.is_empty() {
1313        return Ok(HashMap::new());
1314    }
1315
1316    let (events, edits) = {
1317        let conn = super::get_db_connection_guard_static()?;
1318        let ids = id_list_param(message_ids);
1319
1320        // Query original messages (tags carry the file-type/name for attachment quotes)
1321        let mut stmt = conn
1322            .prepare_cached("SELECT id, kind, content, npub, tags FROM events WHERE id IN (SELECT value FROM json_each(?1))")
1323            .map_err(|e| format!("Failed to prepare reply context query: {}", e))?;
1324
1325        let rows = stmt.query_map([&ids], |row| {
1326            Ok((row.get::<_, String>(0)?, row.get::<_, i32>(1)?,
1327                row.get::<_, String>(2)?, row.get::<_, Option<String>>(3)?,
1328                row.get::<_, Option<String>>(4)?))
1329        }).map_err(|e| format!("Failed to query reply contexts: {}", e))?;
1330        let events_result: Vec<_> = rows.filter_map(|r| r.ok()).collect();
1331        drop(stmt);
1332
1333        // Query latest edits
1334        let mut edit_stmt = conn
1335            .prepare_cached(
1336                "SELECT reference_id, content, tags FROM events \
1337                 WHERE kind = ?2 AND reference_id IN (SELECT value FROM json_each(?1)) \
1338                 ORDER BY created_at DESC, received_at DESC",
1339            )
1340            .map_err(|e| format!("Failed to prepare edit query: {}", e))?;
1341        let edit_rows = edit_stmt.query_map(rusqlite::params![&ids, event_kind::MESSAGE_EDIT as i32], |row| {
1342            Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?,
1343                row.get::<_, Option<String>>(2)?))
1344        }).map_err(|e| format!("Failed to query edits: {}", e))?;
1345        let edits_result: Vec<_> = edit_rows.filter_map(|r| r.ok()).collect();
1346
1347        (events_result, edits_result)
1348    };
1349
1350    // Build latest edit map (first = most recent since ordered DESC)
1351    let mut latest_edits: HashMap<String, (String, Option<String>)> = HashMap::new();
1352    for (ref_id, content, tags) in edits {
1353        latest_edits.entry(ref_id).or_insert((content, tags));
1354    }
1355
1356    // Batch the file replies' attachments (one query, not one per reply) for the extension below.
1357    let file_ids: Vec<String> = events.iter()
1358        .filter(|(_, kind, _, _, _)| *kind == event_kind::FILE_ATTACHMENT as i32)
1359        .map(|(id, _, _, _, _)| id.clone())
1360        .collect();
1361    let atts_by_event = super::attachments::get_attachments_for_events(&file_ids).unwrap_or_default();
1362
1363    // Decrypt and build contexts
1364    let mut contexts = HashMap::new();
1365    crate::crypto::open_batch(|at_rest| {
1366        for (id, kind, original_content, npub, tags) in events {
1367            let has_attachment = kind == event_kind::FILE_ATTACHMENT as i32;
1368            let latest_edit = latest_edits.get(&id);
1369            let content_to_decrypt = latest_edit
1370                .map(|(c, _)| c.clone())
1371                .unwrap_or(original_content);
1372
1373            // Same rule as the message loader: an edit's tags replace the
1374            // original's, so the quote's emoji match the content it shows.
1375            let parse_emoji = |json: &Option<String>| -> Vec<crate::types::EmojiTag> {
1376                json.as_deref()
1377                    .and_then(|t| serde_json::from_str::<Vec<Vec<String>>>(t).ok())
1378                    .map(|parsed| crate::types::EmojiTag::extract_from_stored(&parsed))
1379                    .unwrap_or_default()
1380            };
1381            let emoji_tags = match latest_edit {
1382                Some((_, edit_tags)) => parse_emoji(edit_tags),
1383                None => parse_emoji(&tags),
1384            };
1385
1386            let decrypted_content = if kind == event_kind::CHAT_MESSAGE as i32
1387                || kind == event_kind::PRIVATE_DIRECT_MESSAGE as i32
1388            {
1389                at_rest.open(content_to_decrypt)
1390                    .unwrap_or_else(|_| "[Decryption failed]".to_string())
1391            } else {
1392                String::new()
1393            };
1394
1395            // The first attachment's extension lets the quote show the file type. From the table, with a
1396            // legacy-tag fallback for an un-backfilled pre-migration row.
1397            let extension = if has_attachment {
1398                atts_by_event.get(&id)
1399                    .and_then(|atts| atts.first())
1400                    .map(|a| a.extension.to_lowercase())
1401                    .filter(|e| !e.is_empty())
1402                    .or_else(|| tags.as_deref()
1403                        .and_then(|t| serde_json::from_str::<Vec<Vec<String>>>(t).ok())
1404                        .and_then(|parsed| parsed.into_iter()
1405                            .find(|t| t.first().map(|k| k == "attachments").unwrap_or(false))
1406                            .and_then(|t| t.into_iter().nth(1)))
1407                        .and_then(|json| serde_json::from_str::<Vec<serde_json::Value>>(&json).ok())
1408                        .and_then(|atts| atts.into_iter().next())
1409                        .and_then(|a| a.get("extension").and_then(|e| e.as_str()).map(str::to_lowercase))
1410                        .filter(|e| !e.is_empty()))
1411            } else {
1412                None
1413            };
1414
1415            contexts.insert(id, ReplyContext { content: decrypted_content, npub, has_attachment, extension, emoji_tags });
1416        }
1417    });
1418
1419    Ok(contexts)
1420}
1421
1422/// Populate reply context for a PAGE of messages in one query — the sync/back-page
1423/// counterpart to [`populate_reply_context`]. Every path that emits a message straight to
1424/// the UI must resolve the quote first: the frontend renders the emitted payload, and a
1425/// reply whose parent lies outside the rendered window has no other source for it (a
1426/// parent inside the window is resolved from memory instead). Messages whose parent isn't
1427/// persisted yet are left untouched.
1428pub async fn populate_reply_contexts(messages: Vec<&mut Message>) -> Result<(), String> {
1429    let ids: Vec<String> = messages
1430        .iter()
1431        .filter(|m| !m.replied_to.is_empty())
1432        .map(|m| m.replied_to.clone())
1433        .collect();
1434    if ids.is_empty() {
1435        return Ok(());
1436    }
1437    let contexts = get_reply_contexts(&ids).await?;
1438    for message in messages {
1439        if let Some(ctx) = contexts.get(&message.replied_to) {
1440            message.replied_to_content = Some(ctx.content.clone());
1441            message.replied_to_npub = ctx.npub.clone();
1442            message.replied_to_has_attachment = Some(ctx.has_attachment);
1443            message.replied_to_attachment_extension = ctx.extension.clone();
1444            message.replied_to_emoji_tags = if ctx.emoji_tags.is_empty() { None } else { Some(ctx.emoji_tags.clone()) };
1445        }
1446    }
1447    Ok(())
1448}
1449
1450/// Populate reply context for a single message.
1451/// Used for real-time messages that don't go through get_message_views.
1452pub async fn populate_reply_context(message: &mut Message) -> Result<(), String> {
1453    if message.replied_to.is_empty() {
1454        return Ok(());
1455    }
1456
1457    let contexts = get_reply_contexts(std::slice::from_ref(&message.replied_to)).await?;
1458
1459    if let Some(ctx) = contexts.get(&message.replied_to) {
1460        message.replied_to_content = Some(ctx.content.clone());
1461        message.replied_to_npub = ctx.npub.clone();
1462        message.replied_to_has_attachment = Some(ctx.has_attachment);
1463        message.replied_to_attachment_extension = ctx.extension.clone();
1464        message.replied_to_emoji_tags = if ctx.emoji_tags.is_empty() { None } else { Some(ctx.emoji_tags.clone()) };
1465    }
1466
1467    Ok(())
1468}
1469
1470/// Whether `event_id` is one of our own messages (`mine = 1`). A reply to our
1471/// own message is an implicit ping, so notifications treat it like a direct
1472/// @mention (breaks through a muted channel). Missing row → not ours → false.
1473pub fn is_own_event(event_id: &str) -> bool {
1474    let Ok(conn) = super::get_db_connection_guard_static() else {
1475        return false;
1476    };
1477    conn.query_row(
1478        "SELECT mine FROM events WHERE id = ?1",
1479        [event_id],
1480        |row| row.get::<_, i64>(0),
1481    )
1482    .map(|mine| mine == 1)
1483    .unwrap_or(false)
1484}
1485
1486// ============================================================================
1487// Message Views — compose full Messages from events + reactions + edits
1488// ============================================================================
1489
1490/// Extract a single tag value from raw tags JSON without full allocation.
1491fn extract_tag_from_json(tags_json: &str, key: &str) -> Option<String> {
1492    if tags_json.len() <= 2 { return None; }
1493    let pattern = format!("[\"{}\"", key);
1494    if !tags_json.contains(&pattern) { return None; }
1495    let tags: Vec<Vec<String>> = serde_json::from_str(tags_json).ok()?;
1496    tags.into_iter()
1497        .find(|tag| tag.first().map(|s| s.as_str()) == Some(key))
1498        .and_then(|tag| tag.into_iter().nth(1))
1499}
1500
1501/// A stored message's time in ms from raw tags JSON, as [`StoredEvent::timestamp_ms`] reads it.
1502fn stored_at_ms(created_at: u64, tags_json: &str) -> u64 {
1503    let ms = extract_tag_from_json(tags_json, "ms").and_then(|s| s.parse::<u64>().ok()).filter(|ms| *ms <= 999);
1504    created_at * 1000 + ms.unwrap_or(0)
1505}
1506
1507
1508/// A stored reaction author written as 64-char hex (an early v2 ingest) reads
1509/// back as the npub the frontend contract expects — self-heals old rows with no
1510/// migration; a bech32 or unknown value passes through untouched.
1511fn normalize_reaction_author(author: String) -> String {
1512    if author.len() == 64 && author.bytes().all(|b| b.is_ascii_hexdigit()) {
1513        if let Ok(pk) = nostr_sdk::prelude::PublicKey::from_hex(&author) {
1514            use nostr_sdk::prelude::ToBech32;
1515            let Ok(npub) = pk.to_bech32();
1516            return npub;
1517        }
1518    }
1519    author
1520}
1521/// Extract the NIP-30 `["emoji", shortcode, url]` URL from a stored
1522/// reaction's tags. The reaction's content must be `:shortcode:` form
1523/// and the matching tag's shortcode must agree — otherwise we get the
1524/// URL of a stray emoji tag that doesn't actually represent the
1525/// reaction's chosen emoji.
1526fn extract_reaction_emoji_url(tags: &[Vec<String>], content: &str) -> Option<String> {
1527    if !content.starts_with(':') || !content.ends_with(':') || content.len() < 3 {
1528        return None;
1529    }
1530    let sc = &content[1..content.len() - 1];
1531    tags.iter().find_map(|t| {
1532        if t.len() >= 3 && t[0] == "emoji" && t[1] == sc {
1533            Some(t[2].clone())
1534        } else {
1535            None
1536        }
1537    })
1538}
1539
1540/// Extract a NIP-10 reply reference ("e" tag with "reply" marker at position 3).
1541fn extract_reply_tag_from_json(tags_json: &str) -> Option<String> {
1542    if tags_json.len() <= 2 { return None; }
1543    if !tags_json.contains("[\"e\"") { return None; }
1544    let tags: Vec<Vec<String>> = serde_json::from_str(tags_json).ok()?;
1545    tags.into_iter()
1546        .find(|tag| {
1547            tag.first().map(|s| s.as_str()) == Some("e")
1548                && tag.get(3).map(|s| s.as_str()) == Some("reply")
1549        })
1550        .and_then(|tag| tag.into_iter().nth(1))
1551}
1552
1553/// Get message events with reactions, edits, and attachments composed.
1554///
1555/// This is the main "get messages" function. Queries events, fetches related
1556/// reactions/edits, parses attachments, applies edits, resolves reply context.
1557pub async fn get_message_views(
1558    chat_id: i64,
1559    limit: usize,
1560    offset: usize,
1561) -> Result<Vec<Message>, String> {
1562    // Step 1: Get message events (kind 9, 14, 15)
1563    let message_kinds = [event_kind::CHAT_MESSAGE, event_kind::PRIVATE_DIRECT_MESSAGE, event_kind::FILE_ATTACHMENT];
1564    let message_events = get_events(chat_id, Some(&message_kinds), limit, offset).await?;
1565
1566    compose_message_views(message_events).await
1567}
1568
1569/// Compose Message views from already-fetched message events (kind 9/14/15):
1570/// fetch related reactions/edits, parse attachments, apply edits, resolve reply
1571/// context. Shared by `get_message_views` (offset pager) and `get_messages_around`
1572/// (anchored window). Input order is preserved in the output.
1573async fn compose_message_views(message_events: Vec<StoredEvent>) -> Result<Vec<Message>, String> {
1574    use std::collections::HashMap;
1575
1576    if message_events.is_empty() {
1577        return Ok(Vec::new());
1578    }
1579
1580    // Step 2: Get related events (reactions, edits)
1581    let message_ids: Vec<String> = message_events.iter().map(|e| e.id.clone()).collect();
1582    let related_events = get_related_events(&message_ids).await?;
1583
1584    let mut reactions_by_msg: HashMap<String, Vec<Reaction>> = HashMap::new();
1585    let mut edits_by_msg: HashMap<String, Vec<FoldedEdit>> = HashMap::new();
1586
1587    crate::crypto::open_batch(|at_rest| {
1588        for event in related_events {
1589            if let Some(ref_id) = &event.reference_id {
1590                match event.kind {
1591                    k if k == event_kind::REACTION && crate::types::is_renderable_reaction(&event.content) => {
1592                        let emoji_url = extract_reaction_emoji_url(&event.tags, &event.content);
1593                        let reaction = Reaction {
1594                            id: event.id.clone(),
1595                            reference_id: ref_id.clone(),
1596                            author_id: normalize_reaction_author(event.npub.clone().unwrap_or_default()),
1597                            emoji: event.content.clone(),
1598                            emoji_url,
1599                        };
1600                        // Rows predating the (author, emoji) rule — or written by a client
1601                        // that never had it — must not resurrect a double count on reload.
1602                        let slot = reactions_by_msg.entry(ref_id.clone()).or_default();
1603                        if !slot.iter().any(|r| r.same_slot(&reaction)) {
1604                            slot.push(reaction);
1605                        }
1606                    }
1607                    k if k == event_kind::MESSAGE_EDIT => {
1608                        let decrypted = at_rest.open(event.content.clone())
1609                            .unwrap_or_else(|_| event.content.clone());
1610                        let edit_emoji = crate::types::EmojiTag::extract_from_stored(&event.tags);
1611                        let edit_spans = crate::text_spans::from_stored(&event.tags, &decrypted);
1612                        edits_by_msg.entry(ref_id.clone()).or_default().push((event.created_at * 1000 + ms_tag(&event.tags), decrypted, edit_emoji, edit_spans));
1613                    }
1614                    _ => {}
1615                }
1616            }
1617        }
1618    });
1619
1620    for edits in edits_by_msg.values_mut() {
1621        edits.sort_by_key(|(ts, _, _, _)| *ts);
1622    }
1623
1624    // Step 3: Attachments from the dedicated table (batched), with a legacy-tag fallback for any
1625    // file event not represented in the table (an un-backfilled pre-migration row).
1626    let attach_ids: Vec<String> = message_events.iter()
1627        .filter(|e| e.kind == event_kind::FILE_ATTACHMENT || e.kind == event_kind::CHAT_MESSAGE)
1628        .map(|e| e.id.clone())
1629        .collect();
1630    let mut attachments_by_msg = super::attachments::get_attachments_for_events(&attach_ids)
1631        .unwrap_or_default();
1632    for event in &message_events {
1633        if event.kind != event_kind::FILE_ATTACHMENT && event.kind != event_kind::CHAT_MESSAGE {
1634            continue;
1635        }
1636        if attachments_by_msg.contains_key(&event.id) {
1637            continue;
1638        }
1639        if let Some(json) = event.get_tag("attachments") {
1640            if let Ok(atts) = serde_json::from_str::<Vec<Attachment>>(json) {
1641                if !atts.is_empty() {
1642                    attachments_by_msg.insert(event.id.clone(), atts);
1643                }
1644            }
1645        }
1646    }
1647
1648    // Step 4: Compose Message structs
1649    let mut messages = Vec::with_capacity(message_events.len());
1650    for event in message_events {
1651        let replied_to = event.get_reply_reference().unwrap_or("").to_string();
1652        let at = event.timestamp_ms();
1653        let reactions = reactions_by_msg.remove(&event.id).unwrap_or_default();
1654        let attachments = attachments_by_msg.remove(&event.id).unwrap_or_default();
1655
1656        let original_content = if event.kind == event_kind::FILE_ATTACHMENT {
1657            String::new()
1658        } else {
1659            event.content.clone()
1660        };
1661
1662        // Edits carry their own emoji tags; the newest edit's tags win so the
1663        // displayed (latest) content renders its custom emoji, not the original's.
1664        let original_emoji = crate::types::EmojiTag::extract_from_stored(&event.tags);
1665        let original_spans = crate::text_spans::from_stored(&event.tags, &original_content);
1666        let (content, edited, edit_history, emoji_tags, text_spans) = if let Some(edits) = edits_by_msg.remove(&event.id) {
1667            let mut history = Vec::with_capacity(edits.len() + 1);
1668            history.push(crate::types::EditEntry { content: original_content.clone(), edited_at: at });
1669            for (ts, c, _, _) in &edits {
1670                history.push(crate::types::EditEntry { content: c.clone(), edited_at: *ts });
1671            }
1672            let (latest, latest_emoji, latest_spans) = edits.last()
1673                .map(|(_, c, e, s)| (c.clone(), e.clone(), s.clone()))
1674                .unwrap_or_else(|| (original_content.clone(), original_emoji.clone(), original_spans.clone()));
1675            (latest, true, Some(history), latest_emoji, latest_spans)
1676        } else {
1677            (original_content, false, None, original_emoji, original_spans)
1678        };
1679
1680        let preview_metadata = event.preview_metadata
1681            .and_then(|json| serde_json::from_str(&crate::crypto::maybe_decrypt_text(&json)).ok());
1682
1683        let addressed_bots = extract_bot_tags(&event.tags);
1684        let expiration = extract_expiration_tag(&event.tags);
1685        messages.push(Message {
1686            expiration,
1687            id: event.id, content, replied_to,
1688            replied_to_content: None, replied_to_npub: None, replied_to_has_attachment: None,
1689            replied_to_attachment_extension: None, replied_to_emoji_tags: None,
1690            preview_metadata, attachments, reactions, at,
1691            pending: event.pending, failed: event.failed, mine: event.mine,
1692            npub: event.npub, wrapper_event_id: event.wrapper_event_id,
1693            edited, edit_history,
1694            emoji_tags,
1695            addressed_bots,
1696            text_spans,
1697            role_mentions: crate::community::mentions::from_stored(&event.tags),
1698            writer: carried_by_writer(&event.tags),
1699            unauthorized: held_unauthorized(&event.tags),
1700        });
1701    }
1702
1703    // Rows whose NIP-40 expiry passed while out of STATE (app closed, chat
1704    // unopened) must never reach a renderer — strip them here, at the single
1705    // DB→Message chokepoint, and purge their remnants in the background.
1706    crate::self_destruct::strip_expired(&mut messages);
1707
1708    // Step 5: Reply context
1709    let reply_ids: Vec<String> = messages.iter()
1710        .filter(|m| !m.replied_to.is_empty())
1711        .map(|m| m.replied_to.clone())
1712        .collect();
1713
1714    if !reply_ids.is_empty() {
1715        let contexts = get_reply_contexts(&reply_ids).await?;
1716        for msg in &mut messages {
1717            if let Some(ctx) = contexts.get(&msg.replied_to) {
1718                msg.replied_to_content = Some(ctx.content.clone());
1719                msg.replied_to_npub = ctx.npub.clone();
1720                msg.replied_to_has_attachment = Some(ctx.has_attachment);
1721                msg.replied_to_attachment_extension = ctx.extension.clone();
1722                msg.replied_to_emoji_tags = if ctx.emoji_tags.is_empty() { None } else { Some(ctx.emoji_tags.clone()) };
1723            }
1724        }
1725    }
1726
1727    Ok(messages)
1728}
1729
1730/// Anchored (random-access) message window: load `before` messages up to and
1731/// including the anchor, plus `after` messages strictly newer than it. O(window)
1732/// regardless of how deep the anchor sits in the chat — unlike the offset pager,
1733/// which is O(depth) to reach a far-back message.
1734///
1735/// Returns ASC by `created_at` (oldest first), composed with reactions/edits/
1736/// attachments. Errs if the anchor id isn't in the DB so the caller can fall back.
1737/// One message by its id, composed exactly as the pagers compose theirs —
1738/// attachments, reactions, edits and reply context — with the chat it was said
1739/// in. A citation names a message, never the room, so the room comes back too.
1740///
1741/// `None` is an ordinary answer: a citation outlives its message (a delete, a
1742/// moderation hide, an expiry, or simply history this account never synced),
1743/// and a resolver that errored on absence would make every one of those a fault.
1744pub async fn get_message_by_id(message_id: &str) -> Result<Option<(String, Message)>, String> {
1745    let kinds = [event_kind::CHAT_MESSAGE, event_kind::PRIVATE_DIRECT_MESSAGE, event_kind::FILE_ATTACHMENT]
1746        .map(|k| k.to_string())
1747        .join(",");
1748    let found = {
1749        let conn = super::get_db_connection_guard_static()?;
1750        // Column order matches `parse_event_row`; the chat identifier rides along at 15.
1751        let sql = format!(
1752            "SELECT e.id, e.kind, e.chat_id, e.user_id, e.content, e.tags, e.reference_id, \
1753             e.created_at, e.received_at, e.mine, e.pending, e.failed, e.wrapper_event_id, e.npub, \
1754             e.preview_metadata, c.chat_identifier \
1755             FROM events e JOIN chats c ON c.id = e.chat_id \
1756             WHERE e.id = ?1 AND e.kind IN ({kinds})"
1757        );
1758        let mut stmt = conn.prepare(&sql).map_err(|e| format!("prepare get_message_by_id: {e}"))?;
1759        stmt.query_row(rusqlite::params![message_id], |r| Ok((parse_event_row(r)?, r.get::<_, String>(15)?)))
1760            .optional()
1761            .map_err(|e| format!("query get_message_by_id: {e}"))?
1762    };
1763    let Some((mut event, chat_identifier)) = found else { return Ok(None) };
1764    if event.kind == event_kind::CHAT_MESSAGE || event.kind == event_kind::PRIVATE_DIRECT_MESSAGE {
1765        event.content = crate::crypto::open_batch(|at_rest| at_rest.open(event.content))
1766            .unwrap_or_else(|_| "[Decryption failed]".to_string());
1767    }
1768    Ok(compose_message_views(vec![event]).await?.pop().map(|m| (chat_identifier, m)))
1769}
1770
1771/// Where a message is on this device: the chat it was said in, or whether it was deleted here.
1772#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
1773pub struct MessageLocation {
1774    pub chat: Option<String>,
1775    pub deleted: bool,
1776}
1777
1778/// Locate a message without opening its content. A banned author's message reads as absent,
1779/// as it does on screen.
1780pub fn locate_message(message_id: &str) -> Result<MessageLocation, String> {
1781    let conn = super::get_db_connection_guard_static()?;
1782    let found = conn
1783        .query_row(
1784            "SELECT c.chat_identifier, e.chat_id, e.npub FROM events e JOIN chats c ON c.id = e.chat_id \
1785             WHERE e.id = ?1 AND e.kind IN (9, 14, 15)",
1786            rusqlite::params![message_id],
1787            |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?, r.get::<_, Option<String>>(2)?)),
1788        )
1789        .optional()
1790        .map_err(|e| format!("query locate_message: {e}"))?;
1791    let chat = found.and_then(|(chat, chat_id, npub)| {
1792        let banned = npub.as_deref().and_then(|n| nostr_sdk::prelude::PublicKey::parse(n).ok()).is_some_and(|author| {
1793            community_of_chat(&conn, chat_id).is_some_and(|c| super::community::banned_set(&c).contains(&author.to_bytes()))
1794        });
1795        (!banned).then_some(chat)
1796    });
1797    let deleted = chat.is_none()
1798        && conn
1799            .query_row("SELECT 1 FROM deleted_messages WHERE event_id = ?1", rusqlite::params![message_id], |_| Ok(()))
1800            .optional()
1801            .map_err(|e| format!("query locate_message tombstone: {e}"))?
1802            .is_some();
1803    Ok(MessageLocation { chat, deleted })
1804}
1805
1806pub async fn get_messages_around(
1807    chat_id: i64,
1808    anchor_id: &str,
1809    before: usize,
1810    after: usize,
1811) -> Result<Vec<Message>, String> {
1812    let message_kinds = [event_kind::CHAT_MESSAGE, event_kind::PRIVATE_DIRECT_MESSAGE, event_kind::FILE_ATTACHMENT];
1813
1814    let message_events: Vec<StoredEvent> = {
1815        let conn = super::get_db_connection_guard_static()?;
1816        let community = ban_param(&conn, chat_id);
1817
1818        // Resolve the anchor's FULL sort key (created_at, received_at, rowid). Paging by created_at
1819        // alone wedges on a wall of equal timestamps (a message burst): the query keeps returning the
1820        // same newest-N of the cluster, so back-paging stalls before reaching older history. The
1821        // (received_at, rowid) tiebreak — rowid being the unique final key — gives a strict total
1822        // order, so every page steps strictly past the previous, through any same-timestamp cluster.
1823        let (anchor_at, anchor_rt, anchor_rowid): (i64, i64, i64) = conn.query_row(
1824            "SELECT created_at, received_at, rowid FROM events WHERE id = ?1",
1825            rusqlite::params![anchor_id],
1826            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
1827        ).map_err(|e| format!("Anchor message not found: {}", e))?;
1828
1829        // Kinds occupy ?2..?4; then ?5 created_at, ?6 received_at, ?7 rowid, ?8 limit.
1830        let kind_placeholders: String = (0..message_kinds.len())
1831            .map(|i| format!("?{}", i + 2))
1832            .collect::<Vec<_>>()
1833            .join(",");
1834        let cols = "id, kind, chat_id, user_id, content, tags, reference_id, \
1835                    created_at, received_at, mine, pending, failed, wrapper_event_id, npub, preview_metadata";
1836
1837        // Older incl. anchor: strict key <= anchor key; newest-first then reverse to ASC.
1838        let older_sql = format!(
1839            "SELECT {} FROM events WHERE chat_id = ?1 AND kind IN ({}) \
1840             AND (created_at < ?5 OR (created_at = ?5 AND (received_at < ?6 \
1841                  OR (received_at = ?6 AND rowid <= ?7)))) \
1842             {} ORDER BY created_at DESC, received_at DESC, rowid DESC LIMIT ?8",
1843            cols, kind_placeholders, ban_filter_sql(9)
1844        );
1845        let mut older_stmt = conn.prepare(&older_sql)
1846            .map_err(|e| format!("Failed to prepare older window query: {}", e))?;
1847        let older_rows = older_stmt.query_map(
1848            rusqlite::params![
1849                chat_id,
1850                message_kinds[0] as i32, message_kinds[1] as i32, message_kinds[2] as i32,
1851                anchor_at, anchor_rt, anchor_rowid, before as i64, community
1852            ],
1853            parse_event_row,
1854        ).map_err(|e| format!("Failed to query older window: {}", e))?;
1855        let mut older: Vec<StoredEvent> = older_rows.filter_map(|r| r.ok()).collect();
1856        older.reverse(); // DESC -> ASC
1857
1858        // Newer: strictly after the anchor key.
1859        let newer_sql = format!(
1860            "SELECT {} FROM events WHERE chat_id = ?1 AND kind IN ({}) \
1861             AND (created_at > ?5 OR (created_at = ?5 AND (received_at > ?6 \
1862                  OR (received_at = ?6 AND rowid > ?7)))) \
1863             {} ORDER BY created_at ASC, received_at ASC, rowid ASC LIMIT ?8",
1864            cols, kind_placeholders, ban_filter_sql(9)
1865        );
1866        let mut newer_stmt = conn.prepare(&newer_sql)
1867            .map_err(|e| format!("Failed to prepare newer window query: {}", e))?;
1868        let newer_rows = newer_stmt.query_map(
1869            rusqlite::params![
1870                chat_id,
1871                message_kinds[0] as i32, message_kinds[1] as i32, message_kinds[2] as i32,
1872                anchor_at, anchor_rt, anchor_rowid, after as i64, community
1873            ],
1874            parse_event_row,
1875        ).map_err(|e| format!("Failed to query newer window: {}", e))?;
1876        let newer: Vec<StoredEvent> = newer_rows.filter_map(|r| r.ok()).collect();
1877
1878        older.into_iter().chain(newer).collect()
1879    };
1880
1881    // Decrypt message content (mirror get_events).
1882    let decrypted: Vec<StoredEvent> = crate::crypto::open_batch(|at_rest| message_events.into_iter().map(|mut event| {
1883        if event.kind == event_kind::CHAT_MESSAGE || event.kind == event_kind::PRIVATE_DIRECT_MESSAGE {
1884            event.content = at_rest.open(event.content)
1885                .unwrap_or_else(|_| "[Decryption failed]".to_string());
1886        }
1887        event
1888    }).collect());
1889
1890    compose_message_views(decrypted).await
1891}
1892
1893/// Where a message sits in its chat: how many messages sort after it and how many there are,
1894/// in the order and under the ban filter `get_messages_around` uses. None when it isn't held.
1895#[derive(serde::Serialize, Debug, PartialEq, Eq)]
1896pub struct MessagePosition {
1897    pub newer: usize,
1898    pub total: usize,
1899}
1900
1901pub fn get_message_position(chat_id: i64, anchor_id: &str) -> Result<Option<MessagePosition>, String> {
1902    use rusqlite::OptionalExtension;
1903    let k = [event_kind::CHAT_MESSAGE, event_kind::PRIVATE_DIRECT_MESSAGE, event_kind::FILE_ATTACHMENT].map(|k| k as i32);
1904    let conn = super::get_db_connection_guard_static()?;
1905    let community = ban_param(&conn, chat_id);
1906    let Some((at, rt, rowid)) = conn.query_row(
1907        "SELECT created_at, received_at, rowid FROM events WHERE id = ?1 AND chat_id = ?2",
1908        rusqlite::params![anchor_id, chat_id],
1909        |row| Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?, row.get::<_, i64>(2)?)),
1910    ).optional().map_err(|e| format!("Failed to find message: {}", e))? else {
1911        return Ok(None);
1912    };
1913    let kinds = "chat_id = ?1 AND kind IN (?2, ?3, ?4)";
1914    let newer: i64 = conn.query_row(
1915        &format!(
1916            "SELECT COUNT(*) FROM events WHERE {kinds} \
1917             AND (created_at > ?5 OR (created_at = ?5 AND (received_at > ?6 OR (received_at = ?6 AND rowid > ?7)))){}",
1918            ban_filter_sql(8)
1919        ),
1920        rusqlite::params![chat_id, k[0], k[1], k[2], at, rt, rowid, community],
1921        |row| row.get(0),
1922    ).map_err(|e| format!("Failed to count messages: {}", e))?;
1923    let total: i64 = conn.query_row(
1924        &format!("SELECT COUNT(*) FROM events WHERE {kinds}{}", ban_filter_sql(5)),
1925        rusqlite::params![chat_id, k[0], k[1], k[2], community],
1926        |row| row.get(0),
1927    ).map_err(|e| format!("Failed to count messages: {}", e))?;
1928    Ok(Some(MessagePosition { newer: newer as usize, total: total as usize }))
1929}
1930
1931/// When the message `newer` places from the newest was sent (ms, to the second), in the order and
1932/// under the ban filter of `get_message_position`. None past the oldest.
1933pub fn get_message_time_at(chat_id: i64, newer: usize) -> Result<Option<u64>, String> {
1934    use rusqlite::OptionalExtension;
1935    let k = [event_kind::CHAT_MESSAGE, event_kind::PRIVATE_DIRECT_MESSAGE, event_kind::FILE_ATTACHMENT].map(|k| k as i32);
1936    let conn = super::get_db_connection_guard_static()?;
1937    let community = ban_param(&conn, chat_id);
1938    conn.query_row(
1939        &format!(
1940            "SELECT created_at FROM events WHERE chat_id = ?1 AND kind IN (?2, ?3, ?4){} \
1941             ORDER BY created_at DESC, received_at DESC, rowid DESC LIMIT 1 OFFSET ?6",
1942            ban_filter_sql(5)
1943        ),
1944        rusqlite::params![chat_id, k[0], k[1], k[2], community, newer as i64],
1945        |row| row.get::<_, i64>(0),
1946    ).optional()
1947        .map(|at| at.map(|s| s.max(0) as u64 * 1000))
1948        .map_err(|e| format!("Failed to read message time: {}", e))
1949}
1950
1951/// Get the last message for ALL chats in a single batch query.
1952/// Optimized for app startup (chat list sidebar).
1953pub async fn get_all_chats_last_messages() -> Result<std::collections::HashMap<String, Vec<Message>>, String> {
1954    use std::collections::HashMap;
1955
1956    // Step 1: each chat's newest message. The query returns every message of the chat's newest
1957    // second and the ms tag picks among them, as the chat view orders them: a preview that differs
1958    // from the view's newest leaves a read marker it can't find, and the chat badges unread.
1959    let message_events: Vec<(String, StoredEvent, String)> = {
1960        let conn = super::get_db_connection_guard_static()?;
1961        let mut stmt = conn.prepare(
1962            "SELECT c.chat_identifier, \
1963             e.id, e.kind, e.chat_id, e.user_id, e.content, e.tags, e.reference_id, \
1964             e.created_at, e.received_at, e.mine, e.pending, e.failed, e.wrapper_event_id, e.npub, e.preview_metadata, e.rowid \
1965             FROM chats c JOIN events e ON e.chat_id = c.id AND e.created_at = ( \
1966                 SELECT e2.created_at FROM events e2 WHERE e2.chat_id = c.id \
1967                 AND e2.kind IN (?1, ?2, ?3) AND instr(e2.tags, '[\"unauthorized\"]') = 0 \
1968                 ORDER BY e2.created_at DESC LIMIT 1) \
1969             WHERE c.chat_type != 1 AND e.kind IN (?1, ?2, ?3) AND instr(e.tags, '[\"unauthorized\"]') = 0"
1970        ).map_err(|e| format!("Failed to prepare: {}", e))?;
1971
1972        let rows = stmt.query_map(
1973            rusqlite::params![
1974                event_kind::CHAT_MESSAGE as i32,
1975                event_kind::PRIVATE_DIRECT_MESSAGE as i32,
1976                event_kind::FILE_ATTACHMENT as i32
1977            ],
1978            |row| {
1979                let chat_id: String = row.get(0)?;
1980                let tags_json: String = row.get(6)?;
1981                let event = StoredEvent {
1982                    id: row.get(1)?, kind: row.get::<_, i32>(2)? as u16,
1983                    chat_id: row.get(3)?, user_id: row.get(4)?, content: row.get(5)?,
1984                    tags: Vec::new(), // Deferred — parsed on-demand
1985                    reference_id: row.get(7)?,
1986                    created_at: row.get::<_, i64>(8)? as u64, received_at: row.get::<_, i64>(9)? as u64,
1987                    mine: row.get::<_, i32>(10)? != 0, pending: row.get::<_, i32>(11)? != 0,
1988                    failed: row.get::<_, i32>(12)? != 0, wrapper_event_id: row.get(13)?,
1989                    npub: row.get(14)?, preview_metadata: row.get(15)?,
1990                };
1991                Ok((chat_id, event, tags_json, row.get::<_, i64>(16)?))
1992            }
1993        ).map_err(|e| format!("Failed to query: {}", e))?;
1994        let mut newest: HashMap<String, ((u64, u64, i64), StoredEvent, String)> = HashMap::new();
1995        for (chat_id, event, tags_json, rowid) in rows.filter_map(|r| r.ok()) {
1996            let key = (stored_at_ms(event.created_at, &tags_json), event.received_at, rowid);
1997            match newest.get(&chat_id) {
1998                Some((held, _, _)) if *held >= key => {}
1999                _ => { newest.insert(chat_id, (key, event, tags_json)); }
2000            }
2001        }
2002        newest.into_iter().map(|(chat_id, (_, event, tags_json))| (chat_id, event, tags_json)).collect()
2003    };
2004
2005    if message_events.is_empty() {
2006        return Ok(HashMap::new());
2007    }
2008
2009    // Step 2: Related events (reactions, edits)
2010    let message_ids: Vec<String> = message_events.iter().map(|(_, e, _)| e.id.clone()).collect();
2011    let related_events = get_related_events(&message_ids).await?;
2012
2013    let mut reactions_by_msg: HashMap<String, Vec<Reaction>> = HashMap::new();
2014    let mut edits_by_msg: HashMap<String, Vec<FoldedEdit>> = HashMap::new();
2015
2016    crate::crypto::open_batch(|at_rest| {
2017        for event in related_events {
2018            if let Some(ref_id) = &event.reference_id {
2019                match event.kind {
2020                    k if k == event_kind::REACTION && crate::types::is_renderable_reaction(&event.content) => {
2021                        let emoji_url = extract_reaction_emoji_url(&event.tags, &event.content);
2022                        let reaction = Reaction {
2023                            id: event.id.clone(), reference_id: ref_id.clone(),
2024                            author_id: normalize_reaction_author(event.npub.clone().unwrap_or_default()),
2025                            emoji: event.content.clone(),
2026                            emoji_url,
2027                        };
2028                        // Rows predating the (author, emoji) rule — or written by a client
2029                        // that never had it — must not resurrect a double count on reload.
2030                        let slot = reactions_by_msg.entry(ref_id.clone()).or_default();
2031                        if !slot.iter().any(|r| r.same_slot(&reaction)) {
2032                            slot.push(reaction);
2033                        }
2034                    }
2035                    k if k == event_kind::MESSAGE_EDIT => {
2036                        let decrypted = at_rest.open(event.content.clone())
2037                            .unwrap_or_else(|_| event.content.clone());
2038                        let edit_emoji = crate::types::EmojiTag::extract_from_stored(&event.tags);
2039                        let edit_spans = crate::text_spans::from_stored(&event.tags, &decrypted);
2040                        edits_by_msg.entry(ref_id.clone()).or_default().push((event.created_at * 1000 + ms_tag(&event.tags), decrypted, edit_emoji, edit_spans));
2041                    }
2042                    _ => {}
2043                }
2044            }
2045        }
2046    });
2047    for edits in edits_by_msg.values_mut() {
2048        edits.sort_by_key(|(ts, _, _, _)| *ts);
2049    }
2050
2051    // Step 3: Attachments from the dedicated table (batched), with a legacy-tag fallback.
2052    let attach_ids: Vec<String> = message_events.iter()
2053        .filter(|(_, e, _)| e.kind == event_kind::FILE_ATTACHMENT || e.kind == event_kind::CHAT_MESSAGE)
2054        .map(|(_, e, _)| e.id.clone())
2055        .collect();
2056    let mut attachments_by_msg = super::attachments::get_attachments_for_events(&attach_ids)
2057        .unwrap_or_default();
2058    for (_, event, tags_json) in &message_events {
2059        if event.kind != event_kind::FILE_ATTACHMENT && event.kind != event_kind::CHAT_MESSAGE {
2060            continue;
2061        }
2062        if attachments_by_msg.contains_key(&event.id) {
2063            continue;
2064        }
2065        if let Some(val) = extract_tag_from_json(tags_json, "attachments") {
2066            if let Ok(atts) = serde_json::from_str::<Vec<Attachment>>(&val) {
2067                if !atts.is_empty() {
2068                    attachments_by_msg.insert(event.id.clone(), atts);
2069                }
2070            }
2071        }
2072    }
2073
2074    // Step 4: Compose Messages grouped by chat_identifier
2075    let mut result: HashMap<String, Vec<Message>> = HashMap::new();
2076
2077    crate::crypto::open_batch(|at_rest| {
2078        for (chat_identifier, event, tags_json) in message_events {
2079            let reactions = reactions_by_msg.remove(&event.id).unwrap_or_default();
2080            let attachments = attachments_by_msg.remove(&event.id).unwrap_or_default();
2081            let replied_to = extract_reply_tag_from_json(&tags_json).unwrap_or_default();
2082
2083            // Decrypt content
2084            let original_content = if event.kind == event_kind::CHAT_MESSAGE
2085                || event.kind == event_kind::PRIVATE_DIRECT_MESSAGE
2086            {
2087                at_rest.open(event.content.clone())
2088                    .unwrap_or_else(|_| "[Decryption failed]".to_string())
2089            } else {
2090                String::new()
2091            };
2092
2093            let stored_tags = serde_json::from_str::<Vec<Vec<String>>>(&tags_json).unwrap_or_default();
2094            let original_emoji = crate::types::EmojiTag::extract_from_stored(&stored_tags);
2095            let original_spans = crate::text_spans::from_stored(&stored_tags, &original_content);
2096            let addressed_bots = extract_bot_tags(&stored_tags);
2097            let expiration = extract_expiration_tag(&stored_tags);
2098            // Newest edit's emoji and colour tags win so the latest content renders correctly.
2099            let (content, edited, edit_history, emoji_tags, text_spans) = if let Some(edits) = edits_by_msg.remove(&event.id) {
2100                let (latest, latest_emoji, latest_spans) = edits.last()
2101                    .map(|(_, c, e, s)| (c.clone(), e.clone(), s.clone()))
2102                    .unwrap_or_else(|| (original_content.clone(), original_emoji.clone(), original_spans.clone()));
2103                let history: Vec<crate::types::EditEntry> = std::iter::once(crate::types::EditEntry {
2104                    content: original_content, edited_at: event.created_at * 1000,
2105                }).chain(edits.into_iter().map(|(ts, c, _, _)| crate::types::EditEntry { content: c, edited_at: ts }))
2106                .collect();
2107                (latest, true, Some(history), latest_emoji, latest_spans)
2108            } else {
2109                (original_content, false, None, original_emoji, original_spans)
2110            };
2111
2112            let preview_metadata = event.preview_metadata
2113                .and_then(|json| serde_json::from_str(&at_rest.open_or_keep(json)).ok());
2114
2115            result.entry(chat_identifier).or_default().push(Message {
2116                expiration,
2117                id: event.id, content, replied_to,
2118                replied_to_content: None, replied_to_npub: None, replied_to_has_attachment: None,
2119                replied_to_attachment_extension: None, replied_to_emoji_tags: None,
2120                preview_metadata, attachments, reactions, at: stored_at_ms(event.created_at, &tags_json),
2121                pending: event.pending, failed: event.failed, mine: event.mine,
2122                npub: event.npub, wrapper_event_id: event.wrapper_event_id,
2123                edited, edit_history,
2124                emoji_tags,
2125                addressed_bots,
2126                text_spans,
2127                role_mentions: crate::community::mentions::from_stored(&stored_tags),
2128                writer: carried_by_writer(&stored_tags),
2129                unauthorized: held_unauthorized(&stored_tags),
2130            });
2131        }
2132    });
2133
2134    // Step 5: Reply context — the openChat pre-paint renders this boot last-message
2135    // synchronously (before the richer get_message_views load lands), so without
2136    // context here a reply shows its quote only on the second open.
2137    let reply_ids: Vec<String> = result.values()
2138        .flatten()
2139        .filter(|m| !m.replied_to.is_empty())
2140        .map(|m| m.replied_to.clone())
2141        .collect();
2142
2143    if !reply_ids.is_empty() {
2144        let contexts = get_reply_contexts(&reply_ids).await?;
2145        for msg in result.values_mut().flatten() {
2146            if let Some(ctx) = contexts.get(&msg.replied_to) {
2147                msg.replied_to_content = Some(ctx.content.clone());
2148                msg.replied_to_npub = ctx.npub.clone();
2149                msg.replied_to_has_attachment = Some(ctx.has_attachment);
2150                msg.replied_to_attachment_extension = ctx.extension.clone();
2151                msg.replied_to_emoji_tags = if ctx.emoji_tags.is_empty() { None } else { Some(ctx.emoji_tags.clone()) };
2152            }
2153        }
2154    }
2155
2156    // An expired self-destruct as a chat's last message must not flash in the
2157    // chat list — strip + background-purge; the preview shows empty until the
2158    // next boot resolves the prior message, same as a mid-session sweep.
2159    for msgs in result.values_mut() {
2160        crate::self_destruct::strip_expired(msgs);
2161    }
2162
2163    Ok(result)
2164}
2165
2166/// Per-chat unread count, computed straight from the DB so it's correct even when only the last
2167/// message is in RAM (the boot state). Mirrors the in-memory walk-back exactly: unread = non-mine
2168/// messages newer than the most recent "anchor" (our own message OR the `last_read` marker,
2169/// whichever is latest). A never-read chat (empty `last_read`, no own message) counts all its
2170/// non-mine messages. Returns `chat_identifier → count`; chats with 0 unread are omitted.
2171/// CHAT-level muted/blocked filtering is left to the caller (it lives in RAM state, cheaply).
2172/// SENDER-level filtering happens here: a message whose author's DM is muted or whose profile
2173/// is blocked never counts, in any chat — muting a person silences their community messages too.
2174/// A member BANNED from a community likewise stops counting there: a ban that still badges the
2175/// channel sends the reader to look for a message the client will not render.
2176pub async fn unread_counts() -> Result<std::collections::HashMap<String, u32>, String> {
2177    let conn = super::get_db_connection_guard_static()?;
2178    let bans = all_ban_pairs_json(&conn);
2179    // Anchor: newest own message, or the chat's `last_read` event of any kind. An unset marker is
2180    // '' and must not match a stray empty-id event row. A max per kind reads
2181    // the end of idx_events_unread rather than the whole chat; MATERIALIZED runs each CTE once.
2182    // A "Mark as Unread" from a chosen message (`unread_from`) replaces the anchor: everything from
2183    // that message's second on counts (its whole second, like the anchor), own replies after it
2184    // notwithstanding. Seconds are integers, so `>= anchor + 1` is the `> anchor` cutoff in a form
2185    // the index can range-seek either way.
2186    let mut stmt = conn
2187        .prepare_cached(
2188            "WITH anchors AS MATERIALIZED ( \
2189                SELECT c.id AS chat_id, c.chat_identifier AS chat_identifier, MAX( \
2190                    COALESCE((SELECT MAX(created_at) FROM events WHERE chat_id = c.id AND mine = 1 AND kind = ?1), 0), \
2191                    COALESCE((SELECT MAX(created_at) FROM events WHERE chat_id = c.id AND mine = 1 AND kind = ?2), 0), \
2192                    COALESCE((SELECT MAX(created_at) FROM events WHERE chat_id = c.id AND mine = 1 AND kind = ?3), 0), \
2193                    COALESCE((SELECT created_at FROM events WHERE c.last_read != '' AND id = c.last_read AND chat_id = c.id), 0) \
2194                ) AS anchor_ts, \
2195                (SELECT created_at FROM events WHERE c.unread_from != '' AND id = c.unread_from AND chat_id = c.id) AS from_ts \
2196                FROM chats c \
2197             ), \
2198             counts AS MATERIALIZED ( \
2199                SELECT a.chat_identifier AS chat_identifier, ( \
2200                    SELECT COUNT(*) FROM events e \
2201                    WHERE e.chat_id = a.chat_id AND e.mine = 0 AND e.kind IN (?1, ?2, ?3) \
2202                      AND e.created_at >= COALESCE(a.from_ts, a.anchor_ts + 1) \
2203                      AND instr(e.tags, '[\"unauthorized\"]') = 0 \
2204                      AND (e.npub IS NULL OR e.npub NOT IN ( \
2205                            SELECT chat_identifier FROM chats WHERE muted = 1 \
2206                            UNION \
2207                            SELECT npub FROM profiles WHERE is_blocked = 1)) \
2208                      AND NOT EXISTS ( \
2209                            SELECT 1 FROM community_channels cc \
2210                            WHERE cc.channel_id = a.chat_identifier \
2211                              AND (cc.community_id || ' ' || e.npub) IN (SELECT value FROM json_each(?4))) \
2212                ) AS unread \
2213                FROM anchors a \
2214             ) \
2215             SELECT chat_identifier, unread FROM counts WHERE unread > 0",
2216        )
2217        .map_err(|e| format!("prepare unread_counts: {e}"))?;
2218    let rows = stmt
2219        .query_map(
2220            rusqlite::params![
2221                event_kind::CHAT_MESSAGE as i32,
2222                event_kind::PRIVATE_DIRECT_MESSAGE as i32,
2223                event_kind::FILE_ATTACHMENT as i32,
2224                bans
2225            ],
2226            |row| Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)? as u32)),
2227        )
2228        .map_err(|e| format!("query unread_counts: {e}"))?;
2229    let mut out = std::collections::HashMap::new();
2230    for r in rows.flatten() {
2231        out.insert(r.0, r.1);
2232    }
2233    Ok(out)
2234}
2235
2236/// Unread count for a SINGLE chat, same semantics as [`unread_counts`]. The RAM cache calls this to
2237/// reconcile one chat (open / delete / retreat) without recomputing every chat's count.
2238pub async fn unread_count_for_chat(chat_identifier: &str) -> Result<u32, String> {
2239    let conn = super::get_db_connection_guard_static()?;
2240    let bans = super::community::community_id_for_channel(chat_identifier)
2241        .ok()
2242        .flatten()
2243        .and_then(|cid| banned_npubs_json(&cid));
2244    let count: i64 = conn
2245        .prepare_cached(
2246            // `unread_counts`' anchor for one chat, computed once so the count range-seeks the index.
2247            "WITH a AS MATERIALIZED ( \
2248                SELECT c.id AS chat_id, MAX( \
2249                    COALESCE((SELECT MAX(created_at) FROM events WHERE chat_id = c.id AND mine = 1 AND kind = ?1), 0), \
2250                    COALESCE((SELECT MAX(created_at) FROM events WHERE chat_id = c.id AND mine = 1 AND kind = ?2), 0), \
2251                    COALESCE((SELECT MAX(created_at) FROM events WHERE chat_id = c.id AND mine = 1 AND kind = ?3), 0), \
2252                    COALESCE((SELECT created_at FROM events WHERE c.last_read != '' AND id = c.last_read AND chat_id = c.id), 0) \
2253                ) AS anchor_ts, \
2254                (SELECT created_at FROM events WHERE c.unread_from != '' AND id = c.unread_from AND chat_id = c.id) AS from_ts \
2255                FROM chats c WHERE c.chat_identifier = ?4 \
2256             ) \
2257             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) \
2258               AND e.created_at >= COALESCE(a.from_ts, a.anchor_ts + 1) \
2259             WHERE instr(e.tags, '[\"unauthorized\"]') = 0 \
2260               AND (e.npub IS NULL OR e.npub NOT IN ( \
2261                     SELECT chat_identifier FROM chats WHERE muted = 1 \
2262                     UNION \
2263                     SELECT npub FROM profiles WHERE is_blocked = 1)) \
2264               AND (?5 IS NULL OR e.npub IS NULL OR e.npub NOT IN (SELECT value FROM json_each(?5)))",
2265        )
2266        .and_then(|mut stmt| {
2267            stmt.query_row(
2268                rusqlite::params![
2269                    event_kind::CHAT_MESSAGE as i32,
2270                    event_kind::PRIVATE_DIRECT_MESSAGE as i32,
2271                    event_kind::FILE_ATTACHMENT as i32,
2272                    chat_identifier,
2273                    bans
2274                ],
2275                |row| row.get(0),
2276            )
2277        })
2278        .map_err(|e| format!("query unread_count_for_chat: {e}"))?;
2279    Ok(count as u32)
2280}
2281
2282/// What [`compute_unread_anchor`] decided a chat's read marker should become to surface its newest
2283/// contact message as unread. Computed from the full DB history (RAM may hold only a preview
2284/// message for an unopened community).
2285#[derive(Debug, PartialEq)]
2286pub enum UnreadMark {
2287    /// Nothing to surface: no contact message, or a strictly-newer own message (we spoke last).
2288    NoOp,
2289    /// Reset to the never-read anchor: the target is the chat's earliest message.
2290    Clear,
2291    /// Retreat `last_read` to this event id (the newest message in a strictly earlier second).
2292    Anchor(String),
2293}
2294
2295/// Decide how to mark `chat_identifier` unread. Anchors on the newest message strictly before the
2296/// newest contact message's second — the count query compares whole seconds with a strict `>`, so a
2297/// same-second anchor would leave the target on the boundary and it would read as caught-up.
2298pub async fn compute_unread_anchor(chat_identifier: &str) -> Result<UnreadMark, String> {
2299    let conn = super::get_db_connection_guard_static()?;
2300    let (k0, k1, k2) = (
2301        event_kind::CHAT_MESSAGE as i32,
2302        event_kind::PRIVATE_DIRECT_MESSAGE as i32,
2303        event_kind::FILE_ATTACHMENT as i32,
2304    );
2305    // Newest non-mine message second (the target) and newest overall (to detect we spoke last).
2306    let (target_ts, newest_ts): (Option<i64>, Option<i64>) = conn
2307        .query_row(
2308            "SELECT MAX(CASE WHEN e.mine = 0 THEN e.created_at END), MAX(e.created_at) \
2309             FROM events e JOIN chats c ON e.chat_id = c.id \
2310             WHERE c.chat_identifier = ?1 AND e.kind IN (?2, ?3, ?4)",
2311            rusqlite::params![chat_identifier, k0, k1, k2],
2312            |row| Ok((row.get(0)?, row.get(1)?)),
2313        )
2314        .map_err(|e| format!("unread anchor target: {e}"))?;
2315
2316    let target_ts = match target_ts {
2317        Some(t) => t,
2318        None => return Ok(UnreadMark::NoOp), // no contact message to surface
2319    };
2320    if newest_ts.is_some_and(|n| n > target_ts) {
2321        return Ok(UnreadMark::NoOp); // a strictly-newer own message → we spoke last
2322    }
2323
2324    let anchor_id: Option<String> = conn
2325        .query_row(
2326            "SELECT e.id FROM events e JOIN chats c ON e.chat_id = c.id \
2327             WHERE c.chat_identifier = ?1 AND e.kind IN (?2, ?3, ?4) AND e.created_at < ?5 \
2328             ORDER BY e.created_at DESC LIMIT 1",
2329            rusqlite::params![chat_identifier, k0, k1, k2, target_ts],
2330            |row| row.get(0),
2331        )
2332        .optional()
2333        .map_err(|e| format!("unread anchor prev: {e}"))?;
2334
2335    Ok(match anchor_id {
2336        Some(id) => UnreadMark::Anchor(id),
2337        None => UnreadMark::Clear,
2338    })
2339}
2340
2341/// Drain a sync loop's pending message batch into one transaction. The shared flush for the
2342/// segment-flush pattern: bulk loops COLLECT message saves and call this at delete barriers +
2343/// loop end (a batched save committing AFTER a delete it originally preceded would resurrect
2344/// the deleted row — flushing first preserves wire order). Session-guarded HERE so every bulk
2345/// path gets the same swap-safety: on a stale session the batch is DROPPED, never written
2346/// into the next account's DB (the caller's loop is about to bail anyway).
2347pub async fn flush_message_batch(
2348    chat_id: &str,
2349    pending: &mut Vec<&Message>,
2350    session: &std::sync::Arc<crate::db::Session>,
2351) {
2352    crate::db::scoped(async move {
2353        if pending.is_empty() {
2354            return;
2355        }
2356        if !session.is_live() {
2357            pending.clear();
2358            return;
2359        }
2360        if let Err(e) = save_messages_batch(chat_id, pending).await {
2361            crate::log_warn!("[DB] batch flush failed for {}: {}", chat_id, e);
2362        }
2363        pending.clear();
2364    })
2365    .await
2366}
2367
2368/// Batch save messages for a chat — one transaction for the whole slice.
2369pub async fn save_chat_messages(chat_id: &str, messages: &[Message]) -> Result<(), String> {
2370    if messages.is_empty() {
2371        return Ok(());
2372    }
2373    let refs: Vec<&Message> = messages.iter().collect();
2374    save_messages_batch(chat_id, &refs).await.map(|_| ())
2375}
2376
2377#[cfg(test)]
2378mod tests {
2379    use super::*;
2380    use crate::stored_event::SystemEventType;
2381
2382    static TEST_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(71000);
2383
2384    fn make_test_npub(n: u32) -> String {
2385        const BECH32: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
2386        let mut payload = vec![b'q'; 58];
2387        let mut x = n as u64;
2388        let mut i = 58;
2389        while x > 0 && i > 0 {
2390            i -= 1;
2391            payload[i] = BECH32[(x as usize) % 32];
2392            x /= 32;
2393        }
2394        format!("npub1{}", std::str::from_utf8(&payload).unwrap())
2395    }
2396
2397    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
2398        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
2399        crate::db::close_database();
2400        // Each test rebinds to a fresh per-account DB; the row-id caches are per-account, so a stale
2401        // entry (e.g. a shared author npub) would point into the prior test's DB and FK-fail the insert.
2402        crate::db::clear_id_caches();
2403        let tmp = tempfile::tempdir().unwrap();
2404        let n = TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2405        let account = make_test_npub(n);
2406        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
2407        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
2408        crate::db::set_current_account(account.clone()).unwrap();
2409        crate::db::init_database(&account).unwrap();
2410        (tmp, guard)
2411    }
2412
2413    fn now_secs() -> u64 {
2414        web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_secs()
2415    }
2416
2417    /// A page of synced replies must come out of the batch resolver carrying their quotes.
2418    /// The sync/promote paths emit straight to the UI, and the renderer falls back to the
2419    /// in-memory parent only when the parent is inside the rendered window — so a reply to
2420    /// an OLDER message renders with no quote at all unless the backend resolved it here.
2421    /// Reopening the chat re-reads through `get_message_views` (which resolves), which is
2422    /// why the bug looked like "replies lose their context until you reopen".
2423    #[tokio::test]
2424    async fn batch_resolver_fills_quotes_for_a_synced_page() {
2425        let (_tmp, _guard) = init_test_db();
2426        let chat = "channel_reply_batch";
2427        let author = make_test_npub(90_001);
2428
2429        // An older, already-persisted parent (the case with no in-memory fallback).
2430        let mut parent = Message::default();
2431        parent.id = "parent_evt".to_string();
2432        parent.content = "the original message".to_string();
2433        parent.npub = Some(author.clone());
2434        parent.at = now_secs() - 5_000;
2435        save_message(chat, &parent).await.unwrap();
2436
2437        // The freshly-synced page: a reply to it, plus an unrelated message.
2438        let mut reply = Message::default();
2439        reply.id = "reply_evt".to_string();
2440        reply.content = "replying now".to_string();
2441        reply.replied_to = "parent_evt".to_string();
2442        reply.at = now_secs();
2443        let mut plain = Message::default();
2444        plain.id = "plain_evt".to_string();
2445        plain.content = "unrelated".to_string();
2446        plain.at = now_secs();
2447        // A reply whose parent this device has never seen must stay empty, not fabricate a quote.
2448        let mut orphan = Message::default();
2449        orphan.id = "orphan_evt".to_string();
2450        orphan.replied_to = "never_seen_evt".to_string();
2451        orphan.at = now_secs();
2452
2453        populate_reply_contexts(vec![&mut reply, &mut plain, &mut orphan]).await.unwrap();
2454
2455        assert_eq!(
2456            reply.replied_to_content.as_deref(),
2457            Some("the original message"),
2458            "the synced reply carries its parent's content"
2459        );
2460        assert_eq!(reply.replied_to_npub.as_deref(), Some(author.as_str()), "and its parent's author");
2461        assert!(plain.replied_to_content.is_none(), "a non-reply is untouched");
2462        assert!(orphan.replied_to_content.is_none(), "an unresolvable parent leaves the quote empty");
2463    }
2464
2465    /// A moderation citation names a message id and nothing else, so the room
2466    /// has to come back with it.
2467    #[tokio::test]
2468    async fn a_message_resolves_by_id_with_the_chat_it_was_said_in() {
2469        let (_tmp, _guard) = init_test_db();
2470        let chat = "channel_resolve_by_id";
2471        let author = make_test_npub(91_001);
2472
2473        let mut msg = Message::default();
2474        msg.id = "cited_evt".to_string();
2475        msg.content = "the line a rule matched".to_string();
2476        msg.npub = Some(author.clone());
2477        msg.at = now_secs();
2478        save_message(chat, &msg).await.unwrap();
2479
2480        let (found_chat, found) = get_message_by_id("cited_evt").await.unwrap().expect("stored message resolves");
2481        assert_eq!(found_chat, chat, "the citation gets the room back, not just the message");
2482        assert_eq!(found.content, "the line a rule matched", "and the text, so a mod log can quote it");
2483        assert_eq!(found.npub.as_deref(), Some(author.as_str()));
2484    }
2485
2486    /// A citation outlives its message: deletes, moderation hides, expiry, or
2487    /// history this device never synced. Absence is an answer, not a fault — a
2488    /// resolver that errored would turn every one of those into a failure.
2489    #[tokio::test]
2490    async fn a_message_locates_its_chat_and_nothing_else_does() {
2491        let (_tmp, _guard) = init_test_db();
2492        save_message("npub1locate", &Message { id: "locate_me".into(), content: "hi".into(), at: 1_000_000, ..Default::default() })
2493            .await.unwrap();
2494        let here = |chat: &str| MessageLocation { chat: Some(chat.into()), deleted: false };
2495        assert_eq!(locate_message("locate_me").unwrap(), here("npub1locate"));
2496        assert_eq!(locate_message("never_stored").unwrap(), MessageLocation::default());
2497        let cid = crate::db::id_cache::get_chat_id_by_identifier("npub1locate").unwrap();
2498        save_edit_event("an_edit", "locate_me", "hello", &[], &[], cid, None, "npub1x").await.unwrap();
2499        assert_eq!(locate_message("an_edit").unwrap(), MessageLocation::default(), "an edit is not a message to jump to");
2500        delete_event("locate_me").await.unwrap();
2501        add_message_tombstone("locate_me").unwrap();
2502        assert_eq!(locate_message("locate_me").unwrap(), MessageLocation { chat: None, deleted: true });
2503    }
2504
2505    /// A row a page served from the store, never loaded into memory, still finds its chat,
2506    /// so it can be deleted like any other.
2507    #[tokio::test]
2508    async fn a_message_outside_memory_still_finds_its_chat() {
2509        let (_tmp, _guard) = init_test_db();
2510        save_message("channel_paged", &Message { id: "paged_in".into(), content: "hi".into(), at: 1_000_000, ..Default::default() })
2511            .await.unwrap();
2512        assert!(crate::state::STATE.lock().await.find_message("paged_in").is_none());
2513        assert_eq!(crate::VectorCore.message_chat("paged_in").await.unwrap(), "channel_paged");
2514        assert!(crate::VectorCore.message_chat("never_stored").await.is_err());
2515    }
2516
2517    #[tokio::test]
2518    async fn a_missing_message_resolves_to_none_rather_than_erroring() {
2519        let (_tmp, _guard) = init_test_db();
2520        assert!(get_message_by_id("never_stored_evt").await.unwrap().is_none());
2521    }
2522
2523    /// One blob rides many messages — a forward, a re-post, or forty accounts
2524    /// posting the same image, which is the case most worth seeing whole.
2525    #[tokio::test]
2526    async fn an_attachment_hash_finds_every_message_that_carried_it() {
2527        let (_tmp, _guard) = init_test_db();
2528        let chat = "channel_same_blob";
2529        let hash = "cc".repeat(32);
2530
2531        // `Message.at` is MILLISECONDS: seconds-apart values collapse to one
2532        // created_at and leave the order to chance.
2533        let now_ms = now_secs() * 1000;
2534        for (id, at) in [("blob_older", now_ms - 500_000), ("blob_newer", now_ms)] {
2535            let mut msg = Message::default();
2536            msg.id = id.to_string();
2537            msg.npub = Some(make_test_npub(92_001));
2538            msg.at = at;
2539            msg.attachments = vec![crate::types::Attachment {
2540                id: hash.clone(),
2541                extension: "png".into(),
2542                name: "poster.png".into(),
2543                ..Default::default()
2544            }];
2545            save_message(chat, &msg).await.unwrap();
2546        }
2547
2548        let carriers = crate::db::attachments::events_with_attachment_hash(&hash).unwrap();
2549        assert_eq!(carriers, vec!["blob_newer", "blob_older"], "every carrier, newest first");
2550
2551        // Same instant, which is what a raid looks like: the order must still be
2552        // total rather than whatever the join happens to yield.
2553        for id in ["tie_a", "tie_b"] {
2554            let mut msg = Message::default();
2555            msg.id = id.to_string();
2556            msg.npub = Some(make_test_npub(92_002));
2557            msg.at = now_ms;
2558            msg.attachments = vec![crate::types::Attachment { id: hash.clone(), ..Default::default() }];
2559            save_message(chat, &msg).await.unwrap();
2560        }
2561        let a = crate::db::attachments::events_with_attachment_hash(&hash).unwrap();
2562        let b = crate::db::attachments::events_with_attachment_hash(&hash).unwrap();
2563        assert_eq!(a, b, "a same-instant cluster orders the same way every read");
2564        assert_eq!(a.len(), 4, "and every carrier is still listed");
2565        assert!(
2566            crate::db::attachments::events_with_attachment_hash(&"ab".repeat(32)).unwrap().is_empty(),
2567            "a hash nobody posted finds nothing"
2568        );
2569    }
2570
2571    /// An empty page (or one with no replies at all) must not query or error — the sync path
2572    /// calls this for every page, most of which carry no replies.
2573    #[tokio::test]
2574    async fn batch_resolver_is_a_noop_without_replies() {
2575        let (_tmp, _guard) = init_test_db();
2576        populate_reply_contexts(vec![]).await.unwrap();
2577        let mut plain = Message::default();
2578        plain.id = "solo".to_string();
2579        populate_reply_contexts(vec![&mut plain]).await.unwrap();
2580        assert!(plain.replied_to_content.is_none());
2581    }
2582
2583    // C-H2: a presence (join/leave) persisted from HISTORY must keep its authenticated timestamp so it
2584    // sorts where it happened, not at ingest-time "now"; a future-dated one is clamped so it can't jump
2585    // ahead of real activity.
2586    #[tokio::test]
2587    async fn system_event_stamps_authenticated_time_clamped_to_now() {
2588        let (_tmp, _guard) = init_test_db();
2589        let chat = "channel_ch2_timestamp";
2590        let before = now_secs();
2591        let past = before - 100_000;
2592
2593        save_system_event_at("ev_past", chat, SystemEventType::MemberJoined, "npubX", None, past, None, None).await.unwrap();
2594        save_system_event_at("ev_future", chat, SystemEventType::MemberJoined, "npubX", None, before + 100_000, None, None).await.unwrap();
2595        let after = now_secs();
2596
2597        let evs = get_system_events_for_chat(chat).unwrap();
2598        let past_ev = evs.iter().find(|e| e.id == "ev_past").expect("past event saved");
2599        assert_eq!(past_ev.created_at, past, "historical join keeps its real (authenticated) timestamp");
2600
2601        let fut_ev = evs.iter().find(|e| e.id == "ev_future").expect("future event saved");
2602        assert!(fut_ev.created_at >= before && fut_ev.created_at <= after,
2603            "future-dated event clamped to local now ({} not in {}..={})", fut_ev.created_at, before, after);
2604    }
2605
2606    // Delete-affordance resolution must work on paged-out rows: the events table is the
2607    // fallback source for (chat, mine, author) when a message isn't STATE-resident.
2608    #[tokio::test]
2609    async fn event_delete_context_resolves_from_db() {
2610        let (_tmp, _guard) = init_test_db();
2611        let chat = "npub1contactdc";
2612
2613        let mine_msg = Message { id: "dc_mine".into(), content: "x".into(), at: 1_000, mine: true, ..Default::default() };
2614        let theirs = Message {
2615            id: "dc_theirs".into(), content: "y".into(), at: 2_000, mine: false,
2616            npub: Some("npub1sender".to_string()),
2617            ..Default::default()
2618        };
2619        save_message(chat, &mine_msg).await.unwrap();
2620        save_message(chat, &theirs).await.unwrap();
2621
2622        let (chat_id, mine, _author) = event_delete_context("dc_mine").unwrap().expect("own row resolves");
2623        assert_eq!(chat_id, chat);
2624        assert!(mine);
2625
2626        let (chat_id, mine, author) = event_delete_context("dc_theirs").unwrap().expect("contact row resolves");
2627        assert_eq!(chat_id, chat);
2628        assert!(!mine);
2629        assert_eq!(author.as_deref(), Some("npub1sender"));
2630
2631        assert!(event_delete_context("dc_absent").unwrap().is_none(), "unknown id is None, not an error");
2632    }
2633
2634    // The reported bug: unread must accumulate across a restart (when only the last message per
2635    // chat is in RAM). The DB cutoff count must mirror the in-memory walk-back exactly.
2636    #[tokio::test]
2637    async fn unread_counts_match_walk_back_semantics() {
2638        let (_tmp, _guard) = init_test_db();
2639        let chat = "npub1contactdm";
2640        // `at` is ms (created_at = at/1000); use distinct seconds.
2641        let mk = |id: &str, secs: u64, mine: bool| Message {
2642            id: id.into(), content: "x".into(), at: secs * 1000, mine,
2643            npub: (!mine).then(|| "npub1sender".to_string()),
2644            ..Default::default()
2645        };
2646        let unread = || async { unread_counts().await.unwrap().get(chat).copied().unwrap_or(0) };
2647
2648        // 6 contact messages, never opened/read, no own reply → all 6 unread.
2649        for i in 0..6u64 {
2650            save_message(chat, &mk(&format!("m{i}"), 1000 + i, false)).await.unwrap();
2651        }
2652        assert_eq!(unread().await, 6, "never-read backlog counts all 6");
2653
2654        // 2 more arrive → 8, NOT replaced by 2 (the exact reported symptom).
2655        save_message(chat, &mk("m6", 2000, false)).await.unwrap();
2656        save_message(chat, &mk("m7", 2001, false)).await.unwrap();
2657        assert_eq!(unread().await, 8, "6 backlog + 2 new = 8");
2658
2659        // Our own reply clears it (walk-back stops at the newest mine).
2660        save_message(chat, &mk("mine", 2002, true)).await.unwrap();
2661        assert_eq!(unread().await, 0, "own message = read up to here");
2662
2663        // A contact message after our send is unread again.
2664        save_message(chat, &mk("m8", 2003, false)).await.unwrap();
2665        assert_eq!(unread().await, 1, "one new after our send");
2666
2667        // last_read marker advances the cutoff just like an own message.
2668        {
2669            let conn = crate::db::get_write_connection_guard_static().unwrap();
2670            conn.execute(
2671                "UPDATE chats SET last_read = ?1 WHERE chat_identifier = ?2",
2672                rusqlite::params!["m8", chat],
2673            ).unwrap();
2674        }
2675        assert_eq!(unread().await, 0, "last_read=m8 clears all");
2676        save_message(chat, &mk("m9", 2004, false)).await.unwrap();
2677        assert_eq!(unread().await, 1, "one arrival after last_read");
2678    }
2679
2680    // "Mark as Unread" from a chosen message counts from it on, past our own replies, in both the
2681    // map and the single-chat query, and the ordinary floor returns once it is cleared.
2682    #[tokio::test]
2683    async fn unread_from_counts_past_own_replies() {
2684        let (_tmp, _guard) = init_test_db();
2685        let chat = "npub1unreadfrom";
2686        let mk = |id: &str, secs: u64, mine: bool| Message {
2687            id: id.into(), content: "x".into(), at: secs * 1000, mine,
2688            npub: (!mine).then(|| "npub1sender".to_string()),
2689            ..Default::default()
2690        };
2691        let agree = || async {
2692            let map = unread_counts().await.unwrap().get(chat).copied().unwrap_or(0);
2693            let one = unread_count_for_chat(chat).await.unwrap();
2694            assert_eq!(map, one, "single-chat query diverged from the map");
2695            one
2696        };
2697        let set_from = |id: &str| {
2698            let conn = crate::db::get_write_connection_guard_static().unwrap();
2699            conn.execute("UPDATE chats SET unread_from = ?1 WHERE chat_identifier = ?2", rusqlite::params![id, chat]).unwrap();
2700        };
2701
2702        save_message(chat, &mk("a", 1000, false)).await.unwrap();
2703        save_message(chat, &mk("b", 1001, false)).await.unwrap();
2704        save_message(chat, &mk("mine1", 1002, true)).await.unwrap();
2705        save_message(chat, &mk("c", 1003, false)).await.unwrap();
2706        save_message(chat, &mk("mine2", 1004, true)).await.unwrap();
2707        assert_eq!(agree().await, 0, "our newest reply reads everything before it");
2708
2709        set_from("b");
2710        assert_eq!(agree().await, 2, "b and c count; our replies don't, nor stop the count");
2711        set_from("a");
2712        assert_eq!(agree().await, 3, "from the first message: a, b, c");
2713        set_from("mine1");
2714        assert_eq!(agree().await, 1, "from our own message: only c after it");
2715        set_from("gone");
2716        assert_eq!(agree().await, 0, "a marker whose message is gone falls back to the floor");
2717        set_from("");
2718        assert_eq!(agree().await, 0, "cleared: the own-message floor is back");
2719    }
2720
2721    // A stray event row with an empty id must not stand in for an unset marker ('' in both).
2722    #[tokio::test]
2723    async fn empty_markers_ignore_an_empty_id_event() {
2724        let (_tmp, _guard) = init_test_db();
2725        let chat = "npub1emptyidrow";
2726        let mk = |id: &str, secs: u64, mine: bool| Message {
2727            id: id.into(), content: "x".into(), at: secs * 1000, mine,
2728            npub: (!mine).then(|| "npub1sender".to_string()),
2729            ..Default::default()
2730        };
2731        save_message(chat, &mk("old", 1000, false)).await.unwrap();
2732        save_message(chat, &mk("new", 3000, false)).await.unwrap();
2733        {
2734            let conn = crate::db::get_write_connection_guard_static().unwrap();
2735            let chat_row: i64 = conn.query_row("SELECT id FROM chats WHERE chat_identifier = ?1", rusqlite::params![chat], |r| r.get(0)).unwrap();
2736            conn.execute("INSERT INTO events (id, kind, chat_id, content, tags, created_at, received_at, mine) VALUES ('', 30078, ?1, '', '[]', 2000, 2000, 0)",
2737                rusqlite::params![chat_row]).unwrap();
2738            conn.execute("UPDATE chats SET last_read = 'new', unread_from = '' WHERE id = ?1", rusqlite::params![chat_row]).unwrap();
2739        }
2740        let map = unread_counts().await.unwrap().get(chat).copied().unwrap_or(0);
2741        assert_eq!(map, 0, "read to 'new'; the empty-id row is not an unread_from marker");
2742        assert_eq!(unread_count_for_chat(chat).await.unwrap(), 0);
2743    }
2744
2745    // The mark persists, moves on when its message is deleted, and a read save clears it.
2746    #[tokio::test]
2747    async fn unread_from_persists_moves_on_delete_and_clears() {
2748        let (_tmp, _guard) = init_test_db();
2749        let chat = "npub1unreadfromlife";
2750        let mk = |id: &str, secs: u64, mine: bool| Message {
2751            id: id.into(), content: "x".into(), at: secs * 1000, mine,
2752            npub: (!mine).then(|| "npub1sender".to_string()),
2753            ..Default::default()
2754        };
2755        for (id, secs, mine) in [("a", 1000, false), ("b", 1001, false), ("mine1", 1002, true), ("c", 1003, false)] {
2756            save_message(chat, &mk(id, secs, mine)).await.unwrap();
2757        }
2758        {
2759            let conn = crate::db::get_write_connection_guard_static().unwrap();
2760            conn.execute("UPDATE chats SET unread_from = 'b' WHERE chat_identifier = ?1", rusqlite::params![chat]).unwrap();
2761        }
2762        let stored = || crate::db::chats::get_all_chats().unwrap().into_iter().find(|c| c.id == chat).unwrap();
2763        assert_eq!(stored().unread_from, "b", "the mark round-trips through the chats row");
2764        assert_eq!(unread_count_for_chat(chat).await.unwrap(), 2, "b and c");
2765
2766        delete_event("b").await.unwrap();
2767        assert_eq!(stored().unread_from, "mine1", "deleting the chosen message hands the mark to the next one");
2768        assert_eq!(unread_count_for_chat(chat).await.unwrap(), 1, "only c after it");
2769
2770        let mut slim = stored();
2771        slim.unread_from = String::new();
2772        crate::db::chats::save_slim_chat(&slim).unwrap();
2773        assert_eq!(stored().unread_from, "", "a read's save clears it");
2774        assert_eq!(unread_count_for_chat(chat).await.unwrap(), 1, "back to the own-message floor: c");
2775    }
2776
2777    // Muting a person (their DM row) or blocking them silences their messages in EVERY chat's
2778    // count — community messages from a muted sender must not badge.
2779    #[tokio::test]
2780    async fn unread_counts_exclude_muted_and_blocked_senders() {
2781        let (_tmp, _guard) = init_test_db();
2782        let chat = "channel_mute_exclusion";
2783        let mk = |id: &str, secs: u64, npub: &str| Message {
2784            id: id.into(), content: "x".into(), at: secs * 1000, mine: false,
2785            npub: Some(npub.to_string()),
2786            ..Default::default()
2787        };
2788        save_message(chat, &mk("n1", 1000, "npub1noisy")).await.unwrap();
2789        save_message(chat, &mk("q1", 1001, "npub1quiet")).await.unwrap();
2790
2791        let map = || async { unread_counts().await.unwrap().get(chat).copied().unwrap_or(0) };
2792        let one = || async { unread_count_for_chat(chat).await.unwrap() };
2793        assert_eq!(map().await, 2, "both senders count while neither is muted");
2794        assert_eq!(one().await, 2);
2795
2796        // Mute npub1noisy: their (message-less) DM row exists purely to carry the flag.
2797        {
2798            let conn = crate::db::get_write_connection_guard_static().unwrap();
2799            conn.execute(
2800                "INSERT INTO chats (chat_identifier, chat_type, participants, created_at, muted) \
2801                 VALUES ('npub1noisy', 0, '', 1000, 1)",
2802                [],
2803            ).unwrap();
2804        }
2805        assert_eq!(map().await, 1, "muted sender's message stops counting");
2806        assert_eq!(one().await, 1);
2807
2808        // Block npub1quiet: same exclusion via the profiles flag.
2809        {
2810            let conn = crate::db::get_write_connection_guard_static().unwrap();
2811            conn.execute(
2812                "INSERT INTO profiles (npub, is_blocked) VALUES ('npub1quiet', 1) \
2813                 ON CONFLICT(npub) DO UPDATE SET is_blocked = 1",
2814                [],
2815            ).unwrap();
2816        }
2817        assert_eq!(map().await, 0, "blocked sender's message stops counting too");
2818        assert_eq!(one().await, 0);
2819
2820        // Unmute → the count comes straight back (nothing was consumed).
2821        {
2822            let conn = crate::db::get_write_connection_guard_static().unwrap();
2823            conn.execute("UPDATE chats SET muted = 0 WHERE chat_identifier = 'npub1noisy'", []).unwrap();
2824        }
2825        assert_eq!(map().await, 1, "unmuting restores the sender's count");
2826        assert_eq!(one().await, 1);
2827    }
2828
2829    // The single-chat reconcile query must agree with the full map for every state the cache
2830    // reconciles from (never-read, own-reply cutoff, last_read marker).
2831    #[tokio::test]
2832    async fn unread_count_for_chat_matches_the_map() {
2833        let (_tmp, _guard) = init_test_db();
2834        let chat = "npub1reconcile";
2835        let mk = |id: &str, secs: u64, mine: bool| Message {
2836            id: id.into(), content: "x".into(), at: secs * 1000, mine,
2837            npub: (!mine).then(|| "npub1sender".to_string()),
2838            ..Default::default()
2839        };
2840        let agree = || async {
2841            let map = unread_counts().await.unwrap().get(chat).copied().unwrap_or(0);
2842            let one = unread_count_for_chat(chat).await.unwrap();
2843            assert_eq!(map, one, "single-chat query diverged from the map");
2844            one
2845        };
2846
2847        for i in 0..4u64 { save_message(chat, &mk(&format!("m{i}"), 1000 + i, false)).await.unwrap(); }
2848        assert_eq!(agree().await, 4);
2849        save_message(chat, &mk("mine", 1010, true)).await.unwrap();
2850        assert_eq!(agree().await, 0);
2851        save_message(chat, &mk("after", 1011, false)).await.unwrap();
2852        assert_eq!(agree().await, 1);
2853        {
2854            let conn = crate::db::get_write_connection_guard_static().unwrap();
2855            conn.execute("UPDATE chats SET last_read = ?1 WHERE chat_identifier = ?2",
2856                rusqlite::params!["after", chat]).unwrap();
2857        }
2858        assert_eq!(agree().await, 0);
2859        // A chat with nothing at all reconciles to 0 (no row in the map).
2860        assert_eq!(unread_count_for_chat("npub1nonexistent").await.unwrap(), 0);
2861    }
2862
2863    #[tokio::test]
2864    async fn attachments_table_round_trip_dedup_and_cascade() {
2865        let (_tmp, _guard) = init_test_db();
2866        // downloaded:false mirrors a freshly-received attachment (Attachment::default is downloaded:true).
2867        let att = |id: &str, name: &str| Attachment {
2868            id: id.into(), url: format!("https://blossom/{id}"), name: name.into(),
2869            extension: "png".into(), size: 42, downloaded: false, ..Default::default()
2870        };
2871        let msg = |mid: &str, secs: u64, atts: Vec<Attachment>| Message {
2872            id: mid.into(), content: String::new(), at: secs * 1000, mine: false,
2873            npub: Some("npub1sender".into()), attachments: atts, ..Default::default()
2874        };
2875
2876        // Save a message with two attachments → both rows, order preserved by att_index.
2877        save_message("npub1att", &msg("m1", 1000, vec![att("hashA", "a.png"), att("hashB", "b.png")])).await.unwrap();
2878        let got = crate::db::attachments::get_attachments_for_event("m1").unwrap();
2879        assert_eq!(got.len(), 2);
2880        assert_eq!((got[0].id.as_str(), got[1].id.as_str()), ("hashA", "hashB"), "att_index order");
2881        assert_eq!(got[0].name, "a.png");
2882        assert_eq!(got[0].size, 42);
2883        assert!(!got[0].downloaded);
2884
2885        // Single-row download flip (no read-modify-write of a blob).
2886        crate::db::attachments::set_attachment_downloaded("m1", "hashA", true, "/tmp/a.png").unwrap();
2887        let got = crate::db::attachments::get_attachments_for_event("m1").unwrap();
2888        assert!(got[0].downloaded && got[0].path == "/tmp/a.png");
2889        assert!(!got[1].downloaded, "sibling attachment untouched");
2890
2891        // Dedup: a second message shares hashA → backfill-by-hash marks it (indexed, no LIKE scan).
2892        save_message("npub1att", &msg("m2", 1001, vec![att("hashA", "a-again.png")])).await.unwrap();
2893        let affected = crate::db::attachments::backfill_downloaded_by_hash("hashA", "/tmp/a.png", "m1").unwrap();
2894        assert_eq!(affected, vec!["m2".to_string()]);
2895        assert!(crate::db::attachments::get_attachments_for_event("m2").unwrap()[0].downloaded);
2896
2897        // The write funnel dual-populates the legacy tag, so get_message_views (still tag-backed
2898        // during shadow-populate) composes the attachments onto the Message.
2899        let chat_int = crate::db::id_cache::get_or_create_chat_id("npub1att").unwrap();
2900        let views = get_message_views(chat_int, 10, 0).await.unwrap();
2901        let m1 = views.iter().find(|m| m.id == "m1").unwrap();
2902        assert_eq!(m1.attachments.len(), 2);
2903
2904        // Cascade: deleting the event removes its attachment rows.
2905        delete_event("m1").await.unwrap();
2906        assert!(crate::db::attachments::get_attachments_for_event("m1").unwrap().is_empty(), "ON DELETE CASCADE");
2907    }
2908
2909    #[tokio::test]
2910    async fn deleting_a_message_takes_its_edits_and_reactions_with_it() {
2911        let (_tmp, _guard) = init_test_db();
2912        let react = |id: &str, target: &str| Reaction {
2913            id: id.into(), reference_id: target.into(), author_id: "npub1reactor".into(),
2914            emoji: "🔥".into(), emoji_url: None,
2915        };
2916        let msg = |mid: &str| Message {
2917            id: mid.into(), content: "original".into(), at: 1_000_000, npub: Some("npub1sender".into()),
2918            reactions: vec![react(&format!("r-{mid}"), mid)], ..Default::default()
2919        };
2920        let chat_id = crate::db::id_cache::get_or_create_chat_id("npub1cascade").unwrap();
2921        for mid in ["gone", "kept"] {
2922            save_message("npub1cascade", &msg(mid)).await.unwrap();
2923            let edit = crate::stored_event::StoredEventBuilder::new()
2924                .id(format!("e-{mid}"))
2925                .kind(event_kind::MESSAGE_EDIT)
2926                .chat_id(chat_id)
2927                .content("edited text")
2928                .reference_id(Some(mid.into()))
2929                .created_at(1_001)
2930                .build();
2931            save_event(&edit).await.unwrap();
2932        }
2933
2934        delete_event("gone").await.unwrap();
2935        for id in ["gone", "r-gone", "e-gone"] {
2936            assert!(!event_exists(id).unwrap(), "{id} goes with its message");
2937        }
2938        for id in ["kept", "r-kept", "e-kept"] {
2939            assert!(event_exists(id).unwrap(), "{id} belongs to another message");
2940        }
2941    }
2942
2943    // The download persist path: a re-save must never DOWNGRADE download state (relay re-delivery),
2944    // but a re-save carrying a completed download (+ the nonce→content-hash id rewrite) must persist.
2945    #[tokio::test]
2946    async fn attachment_download_state_is_monotonic_across_resaves() {
2947        let (_tmp, _guard) = init_test_db();
2948        let att = |id: &str, downloaded: bool, path: &str| Attachment {
2949            id: id.into(), url: "u".into(), name: "f.png".into(), extension: "png".into(),
2950            size: 1, downloaded, path: path.into(), ..Default::default()
2951        };
2952        let msg = |atts: Vec<Attachment>| Message {
2953            id: "dl1".into(), content: String::new(), at: 1_000_000, mine: false,
2954            npub: Some("npub1s".into()), attachments: atts, ..Default::default()
2955        };
2956
2957        // Receive (not downloaded), then the user downloads → single-row flip.
2958        save_message("npub1dl", &msg(vec![att("nonceid", false, "")])).await.unwrap();
2959        crate::db::attachments::set_attachment_downloaded("dl1", "nonceid", true, "/tmp/f.png").unwrap();
2960
2961        // Relay re-delivery (downloaded=false) must NOT reset the download.
2962        save_message("npub1dl", &msg(vec![att("nonceid", false, "")])).await.unwrap();
2963        let got = crate::db::attachments::get_attachments_for_event("dl1").unwrap();
2964        assert!(got[0].downloaded && got[0].path == "/tmp/f.png", "re-delivery preserves the download");
2965
2966        // Post-download re-save: id rewritten nonce→content-hash, downloaded=true persists in one pass.
2967        save_message("npub1dl", &msg(vec![att("contenthash", true, "/tmp/f.png")])).await.unwrap();
2968        let got = crate::db::attachments::get_attachments_for_event("dl1").unwrap();
2969        assert_eq!(got[0].id, "contenthash", "hash rewritten nonce→content");
2970        assert!(got[0].downloaded && got[0].path == "/tmp/f.png");
2971
2972        // A re-delivery AFTER the rewrite must keep the content-hash key (not revert to the nonce),
2973        // so the hash-keyed download/backfill/clear helpers still resolve the row.
2974        save_message("npub1dl", &msg(vec![att("nonceid", false, "")])).await.unwrap();
2975        let got = crate::db::attachments::get_attachments_for_event("dl1").unwrap();
2976        assert_eq!(got[0].id, "contenthash", "content-hash key survives a later re-delivery");
2977        assert!(got[0].downloaded && got[0].path == "/tmp/f.png");
2978    }
2979
2980    // An un-backfilled pre-migration event (attachments only in the legacy tag, no table row) still
2981    // renders via the read fallback.
2982    #[tokio::test]
2983    async fn attachments_fall_back_to_legacy_tag_when_table_empty() {
2984        let (_tmp, _guard) = init_test_db();
2985        let a = Attachment {
2986            id: "tagonly".into(), url: "u".into(), name: "old.png".into(), extension: "png".into(),
2987            size: 7, downloaded: false, ..Default::default()
2988        };
2989        save_message("npub1old", &Message {
2990            id: "old1".into(), content: String::new(), at: 2_000_000, mine: false,
2991            npub: Some("npub1s".into()), attachments: vec![a.clone()], ..Default::default()
2992        }).await.unwrap();
2993
2994        // Simulate the pre-migration shape: drop the table rows, write the legacy tag onto the event.
2995        {
2996            let conn = crate::db::get_write_connection_guard_static().unwrap();
2997            conn.execute("DELETE FROM attachments WHERE event_id='old1'", []).unwrap();
2998            let inner = serde_json::to_string(&vec![a]).unwrap();
2999            let tags = serde_json::to_string(&vec![vec!["attachments".to_string(), inner]]).unwrap();
3000            conn.execute("UPDATE events SET tags=?1 WHERE id='old1'", rusqlite::params![tags]).unwrap();
3001        }
3002        assert!(crate::db::attachments::get_attachments_for_event("old1").unwrap().is_empty(), "table empty");
3003
3004        let chat_int = crate::db::id_cache::get_or_create_chat_id("npub1old").unwrap();
3005        let views = get_message_views(chat_int, 10, 0).await.unwrap();
3006        let old = views.iter().find(|m| m.id == "old1").unwrap();
3007        assert_eq!(old.attachments.len(), 1, "attachment served from the legacy-tag fallback");
3008        assert_eq!(old.attachments[0].name, "old.png");
3009    }
3010
3011    // Migration 75's strip logic: remove the legacy attachments tag ONLY from events that are
3012    // provably backfilled (have a table row); un-backfilled events keep their tag as the fallback.
3013    #[tokio::test]
3014    async fn attachment_tag_strip_is_gated_on_backfill() {
3015        let (_tmp, _guard) = init_test_db();
3016        let a = Attachment { id: "h1".into(), extension: "png".into(), name: "f.png".into(), downloaded: false, ..Default::default() };
3017        let mk = |id: &str, secs: u64| Message {
3018            id: id.into(), content: String::new(), at: secs * 1000, mine: false,
3019            npub: Some("npub1s".into()), attachments: vec![a.clone()], ..Default::default()
3020        };
3021        save_message("npub1s", &mk("bf", 1000)).await.unwrap();
3022        save_message("npub1s", &mk("unbf", 2000)).await.unwrap();
3023
3024        {
3025            let conn = crate::db::get_write_connection_guard_static().unwrap();
3026            let inner = serde_json::to_string(&vec![a.clone()]).unwrap();
3027            let with_tag = |ms: &str| serde_json::to_string(&vec![
3028                vec!["ms".to_string(), ms.to_string()],
3029                vec!["attachments".to_string(), inner.clone()],
3030            ]).unwrap();
3031            // Both events carry a legacy tag; only `unbf` loses its table rows (un-backfilled).
3032            conn.execute("UPDATE events SET tags=?1 WHERE id='bf'", rusqlite::params![with_tag("5")]).unwrap();
3033            conn.execute("UPDATE events SET tags=?1 WHERE id='unbf'", rusqlite::params![with_tag("6")]).unwrap();
3034            conn.execute("DELETE FROM attachments WHERE event_id='unbf'", []).unwrap();
3035
3036            // Replicate migration 75's gated strip.
3037            let events: Vec<(String, String)> = {
3038                let mut stmt = conn.prepare("SELECT id, tags FROM events WHERE tags LIKE '%attachments%' AND id IN (SELECT DISTINCT event_id FROM attachments)").unwrap();
3039                let m = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).unwrap();
3040                m.flatten().collect()
3041            };
3042            for (id, tj) in events {
3043                let mut tags: Vec<Vec<String>> = serde_json::from_str(&tj).unwrap();
3044                tags.retain(|t| t.first().map(|s| s.as_str()) != Some("attachments"));
3045                conn.execute("UPDATE events SET tags=?1 WHERE id=?2",
3046                    rusqlite::params![serde_json::to_string(&tags).unwrap(), id]).unwrap();
3047            }
3048
3049            let bf: String = conn.query_row("SELECT tags FROM events WHERE id='bf'", [], |r| r.get(0)).unwrap();
3050            assert!(!bf.contains("attachments"), "backfilled event's attachments tag stripped");
3051            assert!(bf.contains("\"ms\""), "sibling ms tag survives the strip");
3052            let unbf: String = conn.query_row("SELECT tags FROM events WHERE id='unbf'", [], |r| r.get(0)).unwrap();
3053            assert!(unbf.contains("attachments"), "un-backfilled event keeps its tag (no table row)");
3054        }
3055
3056        // The un-backfilled event still renders via the read fallback after the strip.
3057        let chat_int = crate::db::id_cache::get_or_create_chat_id("npub1s").unwrap();
3058        let views = get_message_views(chat_int, 10, 0).await.unwrap();
3059        assert_eq!(views.iter().find(|m| m.id == "unbf").unwrap().attachments.len(), 1, "fallback still renders unbf");
3060    }
3061
3062    // Mark-as-unread anchors from the FULL DB history (a community row often holds only a preview
3063    // message in RAM). The anchor lands strictly before the target's second so the count query's
3064    // strict `>` still counts the newest contact message. Covers the community repro + edge cases.
3065    #[tokio::test]
3066    async fn compute_unread_anchor_covers_the_cases() {
3067        let (_tmp, _guard) = init_test_db();
3068        let mk = |id: &str, secs: u64, mine: bool| Message {
3069            id: id.into(), content: "x".into(), at: secs * 1000, mine,
3070            npub: (!mine).then(|| "npub1sender".to_string()),
3071            ..Default::default()
3072        };
3073        let unread = |chat: &'static str| async move {
3074            unread_counts().await.unwrap().get(chat).copied().unwrap_or(0)
3075        };
3076        let set_lr = |chat: &str, lr: &str| {
3077            let conn = crate::db::get_write_connection_guard_static().unwrap();
3078            conn.execute("UPDATE chats SET last_read = ?1 WHERE chat_identifier = ?2",
3079                rusqlite::params![lr, chat]).unwrap();
3080        };
3081
3082        // (A) The community repro: we spoke long ago, they kept talking. Anchor = second-newest
3083        // contact message → exactly one unread, whatever the RAM cache held.
3084        let a = "npub1anchorA";
3085        save_message(a, &mk("a_mine", 1000, true)).await.unwrap();
3086        for i in 0..8u64 { save_message(a, &mk(&format!("a{i}"), 2000 + i, false)).await.unwrap(); }
3087        assert_eq!(compute_unread_anchor(a).await.unwrap(), UnreadMark::Anchor("a6".into()));
3088        set_lr(a, "a6");
3089        assert_eq!(unread(a).await, 1, "A: newest contact message is the sole unread");
3090
3091        // (B) We spoke last → NoOp (no phantom badge, no snap-back jiggle).
3092        let b = "npub1anchorB";
3093        save_message(b, &mk("b0", 2000, false)).await.unwrap();
3094        save_message(b, &mk("b_mine", 2001, true)).await.unwrap();
3095        assert_eq!(compute_unread_anchor(b).await.unwrap(), UnreadMark::NoOp);
3096
3097        // (C) Same-second tail: the two newest share a second. The anchor must skip to a strictly
3098        // earlier second, so both same-second messages surface instead of snapping back to read.
3099        let c = "npub1anchorC";
3100        save_message(c, &mk("c0", 3000, false)).await.unwrap();
3101        save_message(c, &mk("c1", 3005, false)).await.unwrap();
3102        save_message(c, &mk("c2", 3005, false)).await.unwrap();
3103        assert_eq!(compute_unread_anchor(c).await.unwrap(), UnreadMark::Anchor("c0".into()));
3104        set_lr(c, "c0");
3105        assert_eq!(unread(c).await, 2, "C: same-second tail both count");
3106
3107        // (D) The newest contact message is the chat's first → Clear (never-read) → it still counts.
3108        let d = "npub1anchorD";
3109        save_message(d, &mk("d0", 4000, false)).await.unwrap();
3110        assert_eq!(compute_unread_anchor(d).await.unwrap(), UnreadMark::Clear);
3111        set_lr(d, "");
3112        assert_eq!(unread(d).await, 1, "D: lone contact message surfaces");
3113
3114        // (E) No contact message at all (only our own) → NoOp.
3115        let e = "npub1anchorE";
3116        save_message(e, &mk("e_mine", 5000, true)).await.unwrap();
3117        assert_eq!(compute_unread_anchor(e).await.unwrap(), UnreadMark::NoOp);
3118    }
3119
3120    // Regression: a "read to here" marker that lands on a system event (kind 30078, not a counted
3121    // kind, e.g. the windowed jump-reveal path marking off the raw tail) must still clear unread.
3122    // The anchor keys off the marker row's time whatever its kind, so it can't wedge at 99+.
3123    /// A blank conversation id is refused, never minted into a chat row. Left to
3124    /// `get_or_create_chat_id` it created a chat keyed by "" — and because the
3125    /// identifier is UNIQUE, presence from EVERY channel-less community collapsed
3126    /// into that one unopenable row (82 events across weeks, on a live account).
3127    #[tokio::test]
3128    async fn a_system_event_with_a_blank_conversation_id_is_refused() {
3129        let (_tmp, _guard) = init_test_db();
3130        let before = chat_row_count();
3131        for blank in ["", "   "] {
3132            assert!(
3133                save_system_event_at("ev", blank, SystemEventType::MemberJoined, "npubX", None, 100, None, None)
3134                    .await
3135                    .is_err(),
3136                "a blank conversation id must be refused, not minted"
3137            );
3138        }
3139        assert_eq!(chat_row_count(), before, "and no chat row is created");
3140        // A real id still works.
3141        assert!(
3142            save_system_event_at("ev2", "real-chat", SystemEventType::MemberJoined, "npubX", None, 100, None, None)
3143                .await
3144                .unwrap()
3145        );
3146    }
3147
3148    fn chat_row_count() -> i64 {
3149        let conn = crate::db::get_db_connection_guard_static().unwrap();
3150        conn.query_row("SELECT count(*) FROM chats", [], |r| r.get(0)).unwrap()
3151    }
3152
3153    #[tokio::test]
3154    async fn unread_clears_when_last_read_is_a_system_event() {
3155        let (_tmp, _guard) = init_test_db();
3156        let chat = "npub1sysevtdm";
3157        let mk = |id: &str, secs: u64| Message {
3158            id: id.into(), content: "x".into(), at: secs * 1000, mine: false,
3159            npub: Some("npub1sender".to_string()), ..Default::default()
3160        };
3161        let unread = || async { unread_counts().await.unwrap().get(chat).copied().unwrap_or(0) };
3162
3163        // 5 contact messages, never read → all unread. No own message, so the ONLY viable anchor
3164        // is last_read (this is the case that used to stick at a permanent count).
3165        for i in 0..5u64 {
3166            save_message(chat, &mk(&format!("m{i}"), 1000 + i)).await.unwrap();
3167        }
3168        assert_eq!(unread().await, 5, "never-read backlog");
3169
3170        // A system event is the newest row (a join notification, after every contact message).
3171        save_system_event_at("sysev", chat, SystemEventType::MemberJoined, "npubX", None, 2000, None, None).await.unwrap();
3172
3173        // last_read pinned to that system event (kind 30078) — the reported bad state.
3174        {
3175            let conn = crate::db::get_write_connection_guard_static().unwrap();
3176            conn.execute(
3177                "UPDATE chats SET last_read = ?1 WHERE chat_identifier = ?2",
3178                rusqlite::params!["sysev", chat],
3179            ).unwrap();
3180        }
3181        assert_eq!(unread().await, 0, "read marker on a system event still clears the badge");
3182    }
3183
3184    // Deleting a message adjusts unread correctly: removing an UNREAD message drops the count by
3185    // one, removing the read MARKER retreats it to the prior message (never collapses to 99+), and
3186    // removing the last read message clears the marker without over-counting.
3187    #[tokio::test]
3188    async fn deleting_a_message_adjusts_unread_without_wedging() {
3189        let (_tmp, _guard) = init_test_db();
3190        let chat = "npub1delunread";
3191        let mk = |id: &str, secs: u64| Message {
3192            id: id.into(), content: "x".into(), at: secs * 1000, mine: false,
3193            npub: Some("npub1sender".to_string()), ..Default::default()
3194        };
3195        let unread = || async { unread_counts().await.unwrap().get(chat).copied().unwrap_or(0) };
3196        let set_marker = |id: &str| {
3197            let conn = crate::db::get_write_connection_guard_static().unwrap();
3198            conn.execute("UPDATE chats SET last_read = ?1 WHERE chat_identifier = ?2",
3199                rusqlite::params![id, chat]).unwrap();
3200        };
3201        let marker = || -> String {
3202            let conn = crate::db::get_db_connection_guard_static().unwrap();
3203            conn.query_row("SELECT last_read FROM chats WHERE chat_identifier = ?1",
3204                rusqlite::params![chat], |r| r.get::<_, String>(0)).unwrap()
3205        };
3206
3207        // m0..m5, read up to m1 → m2,m3,m4,m5 unread.
3208        for i in 0..6u64 { save_message(chat, &mk(&format!("m{i}"), 1000 + i)).await.unwrap(); }
3209        set_marker("m1");
3210        assert_eq!(unread().await, 4, "m2..m5 unread");
3211
3212        // Delete an UNREAD mid-block message → badge drops by one, marker untouched.
3213        delete_event("m3").await.unwrap();
3214        assert_eq!(unread().await, 3, "one unread deleted → badge minus one");
3215        assert_eq!(marker(), "m1", "deleting an unread message leaves the marker alone");
3216
3217        // Delete the read MARKER → retreats to the prior surviving message (m0), unread unchanged.
3218        delete_event("m1").await.unwrap();
3219        assert_eq!(marker(), "m0", "marker retreats to the newest survivor before it");
3220        assert_eq!(unread().await, 3, "retreat keeps the count, no collapse to 99+");
3221
3222        // Delete the last surviving read message → marker clears, still exactly the unread block.
3223        delete_event("m0").await.unwrap();
3224        assert_eq!(marker(), "", "no earlier survivor → marker clears");
3225        assert_eq!(unread().await, 3, "cleared marker counts only the true unread survivors");
3226    }
3227
3228    // Edits are event-sourced for BOTH transports: a MESSAGE_EDIT event folds into the target's
3229    // history on reload (latest content + revisions + the edit's own emoji). Community used to
3230    // overwrite the row and lose all of this — this locks in the unified fold.
3231    #[tokio::test]
3232    async fn edit_event_folds_into_history_on_reload() {
3233        let (_tmp, _guard) = init_test_db();
3234        let chat = "channel_edit_fold";
3235        save_message(chat, &Message {
3236            id: "orig1".into(), content: "original".into(), at: 5_000_000,
3237            npub: Some("npub1author".into()), ..Default::default()
3238        }).await.unwrap();
3239
3240        let cid = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3241        let emoji = vec![crate::types::EmojiTag { shortcode: "wave".into(), url: "u/wave".into() }];
3242        save_edit_event("edit1", "orig1", "edited :wave:", &emoji, &[], cid, None, "npub1author").await.unwrap();
3243
3244        let m = get_message_views(cid, 50, 0).await.unwrap()
3245            .into_iter().find(|m| m.id == "orig1").expect("message reloaded");
3246        assert!(m.edited, "folded edit sets the edited flag");
3247        let h = m.edit_history.as_ref().expect("history reconstructed from the edit event");
3248        assert_eq!(h.len(), 2, "original + one edit");
3249        assert_eq!(h[0].content, "original");
3250        assert_eq!(h[1].content, "edited :wave:");
3251        assert_eq!(m.content, "edited :wave:", "latest revision is the displayed content");
3252        assert_eq!(m.emoji_tags.len(), 1, "the edit's own emoji folds onto the message");
3253        assert_eq!(m.emoji_tags[0].shortcode, "wave");
3254    }
3255
3256    // Colour spans persist in the tags column and fold like emoji: the newest edit's
3257    // spans win, on both the chat page and the boot last-message loaders.
3258    #[tokio::test]
3259    async fn text_spans_persist_and_follow_the_latest_edit() {
3260        use crate::text_color::{ColorSpan, Effect};
3261        use crate::text_spans::{TextSpan, TimeSpan};
3262        let (_tmp, _guard) = init_test_db();
3263        let chat = "npub1colourchat";
3264        let rainbow = TextSpan::Color(ColorSpan { from: 0, to: 5, effect: Effect::Rainbow, colors: vec![] });
3265        save_message(chat, &Message {
3266            id: "c1".into(), content: "hello world".into(), at: 6_000_000,
3267            npub: Some("npub1author".into()), text_spans: vec![rainbow.clone()], ..Default::default()
3268        }).await.unwrap();
3269        let cid = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3270
3271        let page = |m: Vec<Message>| m.into_iter().find(|m| m.id == "c1").expect("message reloaded");
3272        assert_eq!(page(get_message_views(cid, 50, 0).await.unwrap()).text_spans, vec![rainbow]);
3273
3274        let pink = TextSpan::Color(ColorSpan { from: 4, to: 8, effect: Effect::Solid, colors: vec!["#f472b6".into()] });
3275        let time = TextSpan::Time(TimeSpan { from: 13, to: 33, unix: 0, style: 'R' });
3276        let edited = "bye world at 1970-01-01 00:00 UTC";
3277        save_edit_event("c1e", "c1", edited, &[], &[pink.clone(), time.clone()], cid, None, "npub1author").await.unwrap();
3278        assert_eq!(page(get_message_views(cid, 50, 0).await.unwrap()).text_spans, vec![pink.clone(), time.clone()]);
3279        let boot = get_all_chats_last_messages().await.unwrap();
3280        assert_eq!(page(boot.get(chat).cloned().unwrap_or_default()).text_spans, vec![pink, time]);
3281
3282        // A span the content can't hold is dropped, never painted past the end.
3283        save_edit_event("c1f", "c1", "bye", &[], &[TextSpan::Color(ColorSpan { from: 0, to: 9, effect: Effect::Rainbow, colors: vec![] })], cid, None, "npub1author").await.unwrap();
3284        assert!(page(get_message_views(cid, 50, 0).await.unwrap()).text_spans.is_empty());
3285    }
3286
3287    /// Local Encryption on for one test, off again however it ends.
3288    struct SealedVault;
3289    impl SealedVault {
3290        fn on(key: [u8; 32]) -> Self {
3291            crate::state::ENCRYPTION_KEY.set(key, &[]);
3292            crate::state::set_encryption_enabled(true);
3293            SealedVault
3294        }
3295    }
3296    impl Drop for SealedVault {
3297        fn drop(&mut self) {
3298            crate::state::ENCRYPTION_KEY.clear(&[]);
3299            crate::state::set_encryption_enabled(false);
3300        }
3301    }
3302
3303    fn raw_row(id: &str) -> (String, String) {
3304        let conn = crate::db::get_db_connection_guard_static().unwrap();
3305        conn.query_row("SELECT content, tags FROM events WHERE id = ?1", [id], |r| Ok((r.get(0)?, r.get(1)?))).unwrap()
3306    }
3307
3308    /// Every later touch of a stored message re-saves the copy held in memory, which carries
3309    /// the latest edit (or whatever a failed open left): a reaction, a link preview, the send
3310    /// confirming, a re-delivery. None may replace the original as it was written.
3311    #[tokio::test]
3312    async fn touching_a_stored_message_never_rewrites_its_original_under_local_encryption() {
3313        let (_tmp, _guard) = init_test_db();
3314        let _vault = SealedVault::on([0x3c; 32]);
3315        let chat = "channel_touch";
3316        let emoji = |s: &str| vec![crate::types::EmojiTag { shortcode: s.into(), url: format!("u/{s}") }];
3317        save_message(chat, &Message {
3318            id: "touch1".into(), content: "original :wave:".into(), at: 5_000_000, pending: true,
3319            npub: Some("npub1author".into()), emoji_tags: emoji("wave"), ..Default::default()
3320        }).await.unwrap();
3321        let cid = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3322        save_edit_event("touch_edit", "touch1", "edited :cat:", &emoji("cat"), &[], cid, None, "npub1author").await.unwrap();
3323        let written = raw_row("touch1");
3324        assert_eq!(crate::crypto::maybe_decrypt_text(&written.0), "original :wave:");
3325
3326        let (_, mut live) = get_message_by_id("touch1").await.unwrap().unwrap();
3327        assert_eq!(live.content, "edited :cat:", "memory holds the latest edit");
3328        live.reactions.push(Reaction {
3329            id: "touch_react".into(), reference_id: "touch1".into(), author_id: "npub1reactor".into(),
3330            emoji: "🔥".into(), emoji_url: None,
3331        });
3332        save_message(chat, &live).await.unwrap();
3333        live.preview_metadata = Some(crate::types::SiteMetadata {
3334            domain: "example.com".into(), og_title: Some("Example".into()), og_description: None, og_image: None,
3335            og_url: None, og_type: None, title: None, description: None, favicon: None,
3336        });
3337        save_message(chat, &live).await.unwrap();
3338        live.pending = false;
3339        save_message(chat, &live).await.unwrap();
3340        live.content = "[Decryption failed]".into();
3341        save_message(chat, &live).await.unwrap();
3342        save_messages_batch(chat, &[&live]).await.unwrap();
3343
3344        assert_eq!(raw_row("touch1"), written, "the original's sealed text and tags are untouched");
3345        let (_, back) = get_message_by_id("touch1").await.unwrap().unwrap();
3346        assert_eq!(back.content, "edited :cat:");
3347        assert_eq!(back.edit_history.as_ref().unwrap()[0].content, "original :wave:", "history still starts at the original");
3348        assert_eq!(back.reactions.len(), 1, "the reaction landed");
3349        assert_eq!(back.preview_metadata.as_ref().map(|p| p.domain.as_str()), Some("example.com"), "the preview landed");
3350        assert!(!back.pending, "the status moved");
3351    }
3352
3353    /// A file message re-saved when its download completes: the download lands, the row stays.
3354    #[tokio::test]
3355    async fn a_download_resave_keeps_the_row_under_local_encryption() {
3356        let (_tmp, _guard) = init_test_db();
3357        let _vault = SealedVault::on([0x3d; 32]);
3358        let att = |downloaded: bool, path: &str| Attachment {
3359            id: "filehash".into(), url: "https://x/f".into(), name: "f.png".into(), extension: "png".into(),
3360            size: 1, downloaded, path: path.into(), ..Default::default()
3361        };
3362        let msg = |caption: &str, a: Attachment| Message {
3363            id: "file1".into(), content: caption.into(), at: 1_000_000, npub: Some("npub1s".into()),
3364            attachments: vec![a], ..Default::default()
3365        };
3366        save_message("npub1file", &msg("look at this", att(false, ""))).await.unwrap();
3367        let written = raw_row("file1");
3368        save_message("npub1file", &msg("[Decryption failed]", att(true, "/tmp/f.png"))).await.unwrap();
3369        assert_eq!(raw_row("file1"), written);
3370        let (_, back) = get_message_by_id("file1").await.unwrap().unwrap();
3371        assert!(back.attachments[0].downloaded && back.attachments[0].path == "/tmp/f.png");
3372    }
3373
3374    // The bulk-sync persist path: one transaction must land events + attachments + reactions
3375    // with the same shape save_message produces, and slice order must set rowid order (the
3376    // same-timestamp pagination tiebreak).
3377    #[tokio::test]
3378    async fn batched_save_matches_single_save_shape() {
3379        let (_tmp, _guard) = init_test_db();
3380        let chat = "channel_batch1";
3381        let att = crate::types::Attachment {
3382            id: "atthash1".into(), extension: "png".into(), name: "a.png".into(),
3383            url: "https://x/att".into(), downloaded: false, ..Default::default()
3384        };
3385        let reaction = Reaction {
3386            id: "react_b1".into(), reference_id: "b1".into(),
3387            author_id: "npub1reactor".into(), emoji: "👍".into(), emoji_url: None,
3388        };
3389        // Same `at` second across the batch — rowid is the only orderer.
3390        let msgs: Vec<Message> = (0..5u64).map(|i| Message {
3391            id: format!("b{i}"), content: format!("c{i}"), at: 7_000_000,
3392            npub: Some("npub1sender".into()),
3393            attachments: if i == 2 { vec![att.clone()] } else { Vec::new() },
3394            reactions: if i == 1 { vec![reaction.clone()] } else { Vec::new() },
3395            ..Default::default()
3396        }).collect();
3397        let refs: Vec<&Message> = msgs.iter().collect();
3398
3399        let saved = save_messages_batch(chat, &refs).await.unwrap();
3400        assert_eq!(saved, 5, "every message written");
3401
3402        for i in 0..5u64 {
3403            assert!(event_exists(&format!("b{i}")).unwrap(), "b{i} row exists");
3404        }
3405        assert!(event_exists("react_b1").unwrap(), "reaction landed as its own kind-7 row");
3406        let atts = crate::db::attachments::get_attachments_for_event("b2").unwrap();
3407        assert_eq!(atts.len(), 1, "attachment row committed with its event");
3408        assert_eq!(atts[0].id, "atthash1");
3409
3410        // rowid order == slice order despite identical timestamps.
3411        let conn = crate::db::get_db_connection_guard_static().unwrap();
3412        let ids: Vec<String> = conn
3413            .prepare("SELECT id FROM events WHERE id IN ('b0','b1','b2','b3','b4') ORDER BY rowid")
3414            .unwrap()
3415            .query_map([], |r| r.get(0)).unwrap()
3416            .flatten().collect();
3417        assert_eq!(ids, vec!["b0", "b1", "b2", "b3", "b4"], "insert order preserves the rowid tiebreak");
3418    }
3419
3420    /// Register `chat` as a channel of `community` so the ban filter can resolve it.
3421    fn link_channel_to_community(chat: &str, community: &str) {
3422        let conn = crate::db::get_write_connection_guard_static().unwrap();
3423        conn.execute(
3424            "INSERT OR REPLACE INTO community_channels \
3425             (channel_id, community_id, channel_key, epoch, name, created_at) \
3426             VALUES (?1, ?2, x'00', 0, 'general', 0)",
3427            rusqlite::params![chat, community],
3428        )
3429        .unwrap();
3430    }
3431
3432    /// The banlist speaks HEX and `events.npub` speaks bech32 — the store has to
3433    /// bridge them or the filter silently matches nothing in production.
3434    fn ban_pair() -> (String, String) {
3435        let k = nostr_sdk::prelude::Keys::generate();
3436        use nostr_sdk::prelude::ToBech32;
3437        (k.public_key().to_hex(), k.public_key().to_bech32().unwrap())
3438    }
3439
3440    /// A ban hides what the author already posted — not only their next message.
3441    #[tokio::test]
3442    async fn a_banned_authors_messages_are_not_returned() {
3443        let (_tmp, _guard) = init_test_db();
3444        let chat = "channel_ban_hide";
3445        link_channel_to_community(chat, "comm_hide");
3446        let (raider_hex, raider) = ban_pair();
3447        let (_, good) = ban_pair();
3448        for (id, npub, at) in [("keep1", &good, 1_000u64), ("spam1", &raider, 2_000), ("keep2", &good, 3_000)] {
3449            let msg = Message { id: id.into(), content: "hi".into(), at, npub: Some(npub.clone()), ..Default::default() };
3450            save_message(chat, &msg).await.unwrap();
3451        }
3452        crate::db::community::set_community_banlist("comm_hide", &[raider_hex], 1).unwrap();
3453
3454        let chat_id = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3455        let got = get_events(chat_id, None, 50, 0).await.unwrap();
3456        let ids: Vec<&str> = got.iter().map(|e| e.id.as_str()).collect();
3457        assert!(!ids.contains(&"spam1"), "a banned author's existing message must not be returned: {ids:?}");
3458        assert!(ids.contains(&"keep1") && ids.contains(&"keep2"), "everyone else survives: {ids:?}");
3459    }
3460
3461    /// THE pagination guard. Filtering after `LIMIT` returns a short page, which the
3462    /// caller reads as "end of history" — backscroll stops dead behind a wall of
3463    /// banned events. Excluding before `LIMIT` keeps a full page full.
3464    #[tokio::test]
3465    async fn a_wall_of_banned_events_does_not_shorten_the_page() {
3466        let (_tmp, _guard) = init_test_db();
3467        let chat = "channel_ban_page";
3468        link_channel_to_community(chat, "comm_page");
3469        // 40 banned interleaved with 20 real ones, banned strictly newer so a
3470        // naive newest-first page would be nothing but spam.
3471        let (raider_hex, raider) = ban_pair();
3472        let (_, good) = ban_pair();
3473        for i in 0..20u64 {
3474            let msg = Message { id: format!("real{i}"), content: "hi".into(), at: 1_000 + i, npub: Some(good.clone()), ..Default::default() };
3475            save_message(chat, &msg).await.unwrap();
3476        }
3477        for i in 0..40u64 {
3478            let msg = Message { id: format!("spam{i}"), content: "buy".into(), at: 5_000 + i, npub: Some(raider.clone()), ..Default::default() };
3479            save_message(chat, &msg).await.unwrap();
3480        }
3481        crate::db::community::set_community_banlist("comm_page", &[raider_hex], 1).unwrap();
3482
3483        let chat_id = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3484        let page = get_events(chat_id, None, 20, 0).await.unwrap();
3485        assert_eq!(page.len(), 20, "a page of 20 must return 20 real messages, not what is left after filtering");
3486        assert!(page.iter().all(|e| e.npub.as_deref() == Some(good.as_str())), "no banned author leaks into the page");
3487    }
3488
3489    /// The kind-filtered path is the one the app actually calls — a page of chat
3490    /// messages. Covering only the kindless branch left it unguarded.
3491    #[tokio::test]
3492    async fn the_kind_filtered_page_excludes_banned_authors_too() {
3493        let (_tmp, _guard) = init_test_db();
3494        let chat = "channel_ban_kinds";
3495        link_channel_to_community(chat, "comm_kinds");
3496        let (raider_hex, raider) = ban_pair();
3497        let (_, good) = ban_pair();
3498        for i in 0..12u64 {
3499            let msg = Message { id: format!("real{i}"), content: "hi".into(), at: 1_000 + i, npub: Some(good.clone()), ..Default::default() };
3500            save_message(chat, &msg).await.unwrap();
3501        }
3502        for i in 0..30u64 {
3503            let msg = Message { id: format!("spam{i}"), content: "buy".into(), at: 5_000 + i, npub: Some(raider.clone()), ..Default::default() };
3504            save_message(chat, &msg).await.unwrap();
3505        }
3506        crate::db::community::set_community_banlist("comm_kinds", &[raider_hex], 1).unwrap();
3507
3508        let chat_id = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3509        let kinds = [event_kind::PRIVATE_DIRECT_MESSAGE];
3510        let page = get_events(chat_id, Some(&kinds), 12, 0).await.unwrap();
3511        assert_eq!(page.len(), 12, "the kind-filtered page must fill with real messages");
3512        assert!(page.iter().all(|e| e.npub.as_deref() == Some(good.as_str())), "no banned author in a kind-filtered page");
3513    }
3514
3515    /// A ban erases their arrival too. The "has joined" row is a system event
3516    /// carrying the same author, so nothing about a banned account should remain
3517    /// on screen — not the spam, not the trace of them walking in.
3518    #[tokio::test]
3519    async fn a_banned_members_join_event_is_hidden_with_their_messages() {
3520        let (_tmp, _guard) = init_test_db();
3521        let chat = "channel_ban_join";
3522        link_channel_to_community(chat, "comm_join");
3523        let (raider_hex, raider) = ban_pair();
3524
3525        save_system_event_at("joined_evt", chat, SystemEventType::MemberJoined, &raider, None, 4_000, None, None)
3526            .await
3527            .unwrap();
3528        let msg = Message { id: "spam_after_join".into(), content: "buy".into(), at: 5_000, npub: Some(raider.clone()), ..Default::default() };
3529        save_message(chat, &msg).await.unwrap();
3530        let chat_id = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3531        // Present BEFORE the ban, or the assertions below prove nothing.
3532        assert_eq!(get_events(chat_id, None, 50, 0).await.unwrap().len(), 2, "both rows are on record first");
3533
3534        crate::db::community::set_community_banlist("comm_join", &[raider_hex], 1).unwrap();
3535
3536        let got = get_events(chat_id, None, 50, 0).await.unwrap();
3537        let ids: Vec<&str> = got.iter().map(|e| e.id.as_str()).collect();
3538        assert!(!ids.contains(&"joined_evt"), "the join row goes with them: {ids:?}");
3539        assert!(!ids.contains(&"spam_after_join"), "and so does what they said: {ids:?}");
3540    }
3541
3542    /// A badge that counts a banned author sends the reader hunting for a message
3543    /// the client will never render.
3544    #[tokio::test]
3545    async fn a_banned_authors_messages_do_not_badge_the_channel() {
3546        let (_tmp, _guard) = init_test_db();
3547        let chat = "channel_ban_unread";
3548        link_channel_to_community(chat, "comm_unread");
3549        let (raider_hex, raider) = ban_pair();
3550        let (_, good) = ban_pair();
3551
3552        let real = Message { id: "real_unread".into(), content: "hi".into(), at: 1_000, npub: Some(good.clone()), ..Default::default() };
3553        save_message(chat, &real).await.unwrap();
3554        for i in 0..5u64 {
3555            let spam = Message { id: format!("spam_unread{i}"), content: "buy".into(), at: 2_000 + i, npub: Some(raider.clone()), ..Default::default() };
3556            save_message(chat, &spam).await.unwrap();
3557        }
3558        assert_eq!(unread_count_for_chat(chat).await.unwrap(), 6, "before the ban everything counts");
3559
3560        crate::db::community::set_community_banlist("comm_unread", &[raider_hex], 1).unwrap();
3561
3562        assert_eq!(
3563            unread_count_for_chat(chat).await.unwrap(), 1,
3564            "only the message that still renders is counted"
3565        );
3566        let all = unread_counts().await.unwrap();
3567        assert_eq!(all.get(chat).copied().unwrap_or(0), 1, "and the all-chats sweep agrees");
3568    }
3569
3570    #[tokio::test]
3571    async fn a_held_post_is_stored_marked_and_never_badges_or_previews() {
3572        let (_tmp, _guard) = init_test_db();
3573        let chat = "channel_held_unread";
3574        link_channel_to_community(chat, "comm_held");
3575        let (_, good) = ban_pair();
3576        let (_, stranger) = ban_pair();
3577        let real = Message { id: "real_held".into(), content: "hi".into(), at: 1_000, npub: Some(good.clone()), ..Default::default() };
3578        save_message(chat, &real).await.unwrap();
3579        let held = Message { id: "held_post".into(), content: "spam".into(), at: 2_000, npub: Some(stranger), unauthorized: true, ..Default::default() };
3580        save_message(chat, &held).await.unwrap();
3581        assert!(get_message_by_id("held_post").await.unwrap().unwrap().1.unauthorized, "the mark survives a reload");
3582        assert_eq!(unread_count_for_chat(chat).await.unwrap(), 1, "a held post rings nothing");
3583        assert_eq!(unread_counts().await.unwrap().get(chat).copied().unwrap_or(0), 1);
3584        let last = get_all_chats_last_messages().await.unwrap();
3585        assert_eq!(last.get(chat).and_then(|m| m.last()).map(|m| m.id.as_str()), Some("real_held"), "nor previews the chat");
3586        assert!(set_event_unauthorized("held_post", false).unwrap());
3587        assert!(!get_message_by_id("held_post").await.unwrap().unwrap().1.unauthorized);
3588        assert_eq!(unread_count_for_chat(chat).await.unwrap(), 2, "standing, it counts");
3589        assert!(set_event_unauthorized("held_post", true).unwrap());
3590        assert!(get_message_by_id("held_post").await.unwrap().unwrap().1.unauthorized);
3591        assert!(!set_event_unauthorized("missing", true).unwrap());
3592    }
3593
3594    #[tokio::test]
3595    async fn the_held_store_keeps_what_is_dated_near_now_within_its_caps() {
3596        use crate::db::community::{hold_wrap, held_wraps_in, MAX_HELD_BYTES, MAX_HELD_WRAPS};
3597        let (_tmp, _guard) = init_test_db();
3598        let (cid, ch) = ("c".repeat(64), "chan_held_caps".to_string());
3599        link_channel_to_community(&ch, &cid);
3600        let now = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_millis() as u64;
3601        let id = |i: usize| format!("{i:064x}");
3602        assert!(!hold_wrap(&cid, &ch, &id(1), "w", "", now + 2 * 3_600_000).unwrap(), "dated past the horizon, it waits on the relay");
3603        assert!(held_wraps_in(&cid, &ch).unwrap().is_empty());
3604        assert!(community_wraps_settled(&[id(1)]).contains(&id(1)), "and a read leaves it there until its date nears");
3605        // A legitimate post half an hour old outlives a flood dated just inside the horizon.
3606        assert!(hold_wrap(&cid, &ch, &id(2), "legit", "", now - 30 * 60_000).unwrap());
3607        for i in 0..MAX_HELD_WRAPS {
3608            hold_wrap(&cid, &ch, &id(10 + i), "spam", "", now + 55 * 60_000).unwrap();
3609        }
3610        assert!(held_wraps_in(&cid, &ch).unwrap().iter().any(|(w, _)| *w == id(2)), "dated nearer now, it stays");
3611        // Bytes cap too: a few huge wraps can't crowd out the rest beyond the budget.
3612        let (cid2, ch2) = ("d".repeat(64), "chan_held_bytes".to_string());
3613        let big = "x".repeat(MAX_HELD_BYTES / 3);
3614        for i in 0..4 {
3615            hold_wrap(&cid2, &ch2, &id(900 + i), &big, "", now - (i as u64 + 1) * 1_000).unwrap();
3616        }
3617        let kept: Vec<String> = held_wraps_in(&cid2, &ch2).unwrap().into_iter().map(|(w, _)| w).collect();
3618        assert!(kept.len() < 4 && !kept.contains(&id(903)), "the furthest from now goes once the bytes run out: {kept:?}");
3619        // One author can't hold more than a share of a channel, nor a community more than its bytes.
3620        use crate::db::community::{MAX_HELD_COMMUNITY_BYTES, MAX_HELD_PER_AUTHOR};
3621        let (cid3, ch3) = ("e".repeat(64), "chan_held_share".to_string());
3622        assert!(hold_wrap(&cid3, &ch3, &id(1_000), "older, someone else", "bb", now - 20 * 60_000).unwrap());
3623        for i in 0..MAX_HELD_PER_AUTHOR + 5 {
3624            hold_wrap(&cid3, &ch3, &id(1_001 + i), "flood", "aa", now - i as u64).unwrap();
3625        }
3626        let kept = held_wraps_in(&cid3, &ch3).unwrap();
3627        assert_eq!(kept.len(), MAX_HELD_PER_AUTHOR + 1, "the flood keeps its share and no more");
3628        assert!(kept.iter().any(|(w, _)| *w == id(1_000)));
3629        let cid4 = "f".repeat(64);
3630        let fifth = "y".repeat(MAX_HELD_COMMUNITY_BYTES / 5);
3631        for i in 0..6 {
3632            hold_wrap(&cid4, &format!("chan_held_c{i}"), &id(2_000 + i), &fifth, "", now - (i as u64 + 1) * 60_000).unwrap();
3633        }
3634        assert!(held_wraps_in(&cid4, "chan_held_c5").unwrap().is_empty(), "the community's bytes run out on the furthest from now");
3635        assert!(!held_wraps_in(&cid4, "chan_held_c0").unwrap().is_empty());
3636        // A flood in one Channel gives up its own before another Channel loses anything.
3637        let cid5 = "9".repeat(64);
3638        let tenth = "z".repeat(MAX_HELD_COMMUNITY_BYTES / 10);
3639        hold_wrap(&cid5, "chan_held_quiet", &id(3_000), &tenth, "q", now - 50 * 60_000).unwrap();
3640        for i in 0..4 {
3641            for c in 0..5 {
3642                hold_wrap(&cid5, &format!("chan_held_flood{c}"), &id(3_100 + c * 10 + i), &tenth, &format!("f{i}"), now - i as u64).unwrap();
3643            }
3644        }
3645        assert_eq!(held_wraps_in(&cid5, "chan_held_quiet").unwrap().len(), 1, "the quiet channel keeps its one");
3646        let flood: usize = (0..5).map(|c| held_wraps_in(&cid5, &format!("chan_held_flood{c}")).unwrap().len()).sum();
3647        assert_eq!(flood, 9, "the floods give up one between them once the community's bytes run out");
3648        // What waits for its date is bounded, the furthest-dated dropped first.
3649        use crate::db::community::MAX_DEFERRED;
3650        for i in 0..=MAX_DEFERRED {
3651            hold_wrap(&cid, &ch, &id(10_000 + i), "w", "", now + 2 * 3_600_000 + i as u64).unwrap();
3652        }
3653        assert!(!community_wraps_settled(&[id(10_000 + MAX_DEFERRED)]).contains(&id(10_000 + MAX_DEFERRED)), "dropped, it is only read again");
3654        assert!(community_wraps_settled(&[id(10_000)]).contains(&id(10_000)));
3655        // A manager's flagged copy goes with its wrap.
3656        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() };
3657        save_message(&ch, &msg).await.unwrap();
3658        assert!(get_message_by_id("held_copy").await.unwrap().is_some());
3659        hold_wrap(&cid, &ch, &id(950), "spam", "", now + 58 * 60_000).unwrap();
3660        assert!(get_message_by_id("held_copy").await.unwrap().is_none(), "evicted at once, and its copy with it");
3661    }
3662
3663    /// Join/leave lines have their OWN query — the chat page never sees them — so
3664    /// filtering the message page alone left a wall of "has joined" from accounts
3665    /// whose every message the client already refused to render.
3666    #[tokio::test]
3667    async fn a_banned_members_join_line_is_dropped_from_the_system_feed() {
3668        let (_tmp, _guard) = init_test_db();
3669        let chat = "channel_ban_sysfeed";
3670        link_channel_to_community(chat, "comm_sysfeed");
3671        let (raider_hex, raider) = ban_pair();
3672        let (_, good) = ban_pair();
3673
3674        for (id, who) in [("join_good", &good), ("join_raider", &raider)] {
3675            save_system_event_at(id, chat, SystemEventType::MemberJoined, who, None, 1_000, None, None)
3676                .await
3677                .unwrap();
3678        }
3679        assert_eq!(get_system_events_for_chat(chat).unwrap().len(), 2, "both arrivals are on record");
3680
3681        crate::db::community::set_community_banlist("comm_sysfeed", &[raider_hex], 1).unwrap();
3682
3683        let feed = get_system_events_for_chat(chat).unwrap();
3684        let ids: Vec<&str> = feed.iter().map(|e| e.id.as_str()).collect();
3685        assert_eq!(ids, vec!["join_good"], "the banned member's arrival goes with their messages");
3686    }
3687
3688    /// A moderator's delete has to outlive the row it removed.
3689    ///
3690    /// Dropping the events row alone only hides the message until the next full
3691    /// sync re-serves the original from a relay: nothing recorded that it was
3692    /// removed, so it re-ingests cleanly and the deletion silently undoes itself.
3693    /// Observed live — an image Sentinel deleted for NSFW reappeared after a
3694    /// cold resync.
3695    #[tokio::test]
3696    async fn a_moderated_delete_survives_the_message_being_re_ingested() {
3697        let (_tmp, _guard) = init_test_db();
3698        let chat = "channel_delete_resync";
3699        let (_, author) = ban_pair();
3700        let msg = Message { id: "moderated_evt".into(), content: "nsfw".into(), at: 1_000, npub: Some(author.clone()), ..Default::default() };
3701        save_message(chat, &msg).await.unwrap();
3702
3703        // What the moderation path does on receiving the delete.
3704        crate::state::note_message_deleted("moderated_evt");
3705        add_message_tombstone("moderated_evt").unwrap();
3706        delete_event("moderated_evt").await.unwrap();
3707
3708        let chat_id = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3709        assert!(get_events(chat_id, None, 50, 0).await.unwrap().is_empty(), "removed on the spot");
3710
3711        // The relay re-serves the original on the next sync.
3712        assert!(
3713            crate::state::was_message_deleted("moderated_evt"),
3714            "the refusal outlives the row, so the re-ingest is dropped rather than resurrecting it"
3715        );
3716    }
3717
3718    /// Backscroll windows around an anchor, so a ban has to hold there too —
3719    /// otherwise jump-to-message walks straight back into the spam the chat page
3720    /// refuses to show.
3721    #[tokio::test]
3722    async fn the_backscroll_window_excludes_banned_authors() {
3723        let (_tmp, _guard) = init_test_db();
3724        let chat = "channel_ban_window";
3725        link_channel_to_community(chat, "comm_window");
3726        let (raider_hex, raider) = ban_pair();
3727        let (_, good) = ban_pair();
3728
3729        for i in 0..10u64 {
3730            let m = Message { id: format!("w_real{i}"), content: "hi".into(), at: 1_000 + i, npub: Some(good.clone()), ..Default::default() };
3731            save_message(chat, &m).await.unwrap();
3732            let s = Message { id: format!("w_spam{i}"), content: "buy".into(), at: 1_500 + i, npub: Some(raider.clone()), ..Default::default() };
3733            save_message(chat, &s).await.unwrap();
3734        }
3735        crate::db::community::set_community_banlist("comm_window", &[raider_hex], 1).unwrap();
3736
3737        let chat_id = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3738        let win = get_messages_around(chat_id, "w_real5", 20, 20).await.unwrap();
3739        assert!(!win.is_empty(), "the window still returns the real messages");
3740        assert!(
3741            win.iter().all(|m| m.npub.as_deref() == Some(good.as_str())),
3742            "no banned author reachable by jumping to a message near them",
3743        );
3744    }
3745
3746    #[tokio::test]
3747    async fn a_message_position_counts_what_sorts_after_it_without_banned_authors() {
3748        let (_tmp, _guard) = init_test_db();
3749        let chat = "channel_position";
3750        link_channel_to_community(chat, "comm_position");
3751        let (raider_hex, raider) = ban_pair();
3752        let (_, good) = ban_pair();
3753        for i in 0..10u64 {
3754            let m = Message { id: format!("p_real{i}"), content: "hi".into(), at: 1_000_000 + i * 1_000, npub: Some(good.clone()), ..Default::default() };
3755            save_message(chat, &m).await.unwrap();
3756        }
3757        let spam = Message { id: "p_spam".into(), content: "buy".into(), at: 1_009_500, npub: Some(raider.clone()), ..Default::default() };
3758        save_message(chat, &spam).await.unwrap();
3759        let chat_id = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3760
3761        assert_eq!(get_message_position(chat_id, "p_real3").unwrap(), Some(MessagePosition { newer: 7, total: 11 }));
3762        crate::db::community::set_community_banlist("comm_position", &[raider_hex], 1).unwrap();
3763        assert_eq!(get_message_position(chat_id, "p_real3").unwrap(), Some(MessagePosition { newer: 6, total: 10 }));
3764        assert_eq!(get_message_position(chat_id, "p_real9").unwrap(), Some(MessagePosition { newer: 0, total: 10 }));
3765        assert_eq!(get_message_position(chat_id, "missing").unwrap(), None);
3766
3767        assert_eq!(get_message_time_at(chat_id, 0).unwrap(), Some(1_009_000));
3768        assert_eq!(get_message_time_at(chat_id, 6).unwrap(), Some(1_003_000), "the spam row no longer counts");
3769        assert_eq!(get_message_time_at(chat_id, 10).unwrap(), None);
3770    }
3771
3772    /// A DM has no community, so the predicate must not exclude anything.
3773    #[tokio::test]
3774    async fn a_dm_is_unaffected_by_the_ban_filter() {
3775        let (_tmp, _guard) = init_test_db();
3776        let chat = "npub1peer_dm";
3777        let msg = Message { id: "dm1".into(), content: "hi".into(), at: 1_000, npub: Some("npub1peer".into()), ..Default::default() };
3778        save_message(chat, &msg).await.unwrap();
3779        let chat_id = crate::db::id_cache::get_chat_id_by_identifier(chat).unwrap();
3780        assert_eq!(get_events(chat_id, None, 50, 0).await.unwrap().len(), 1, "a DM resolves no community and filters nothing");
3781    }
3782
3783    // A batched re-save must keep save_message's upsert semantics: wrapper_event_id is
3784    // COALESCE-preserved, and a duplicate reaction in the batch never doubles its row.
3785    #[tokio::test]
3786    async fn batched_resave_preserves_wrapper_and_dedups_reactions() {
3787        let (_tmp, _guard) = init_test_db();
3788        let chat = "channel_batch2";
3789        let reaction = Reaction {
3790            id: "react_rs".into(), reference_id: "rs1".into(),
3791            author_id: "npub1reactor".into(), emoji: "🔥".into(), emoji_url: None,
3792        };
3793        let mut msg = Message {
3794            id: "rs1".into(), content: "hello".into(), at: 8_000_000,
3795            npub: Some("npub1sender".into()),
3796            wrapper_event_id: Some("wrap_original".into()),
3797            reactions: vec![reaction],
3798            ..Default::default()
3799        };
3800        save_message(chat, &msg).await.unwrap();
3801
3802        // Re-delivery re-save without a wrapper id, reaction still attached.
3803        msg.wrapper_event_id = None;
3804        let saved = save_messages_batch(chat, &[&msg]).await.unwrap();
3805        assert_eq!(saved, 1);
3806
3807        let conn = crate::db::get_db_connection_guard_static().unwrap();
3808        let wrapper: Option<String> = conn.query_row(
3809            "SELECT wrapper_event_id FROM events WHERE id = 'rs1'", [], |r| r.get(0),
3810        ).unwrap();
3811        assert_eq!(wrapper.as_deref(), Some("wrap_original"), "COALESCE keeps the known wrapper");
3812        let reaction_rows: i64 = conn.query_row(
3813            "SELECT COUNT(*) FROM events WHERE id = 'react_rs'", [], |r| r.get(0),
3814        ).unwrap();
3815        assert_eq!(reaction_rows, 1, "reaction row not duplicated by the re-save");
3816    }
3817
3818    // The DM stream's multi-chat flush: one call, one transaction, rows land under their own
3819    // chats with their gift-wrap ledger entries; a flush against a stale session drops the
3820    // buffer AND leaves the wrappers unledgered (that's what makes the drop recoverable).
3821    #[tokio::test]
3822    async fn batching_persist_flushes_multi_chat_and_drains_into_the_account_that_filled_it() {
3823        let (_tmp, _guard) = init_test_db();
3824        let handler = crate::event_handler::NoOpEventHandler;
3825        let batcher = crate::event_handler::BatchingPersist::new(&handler);
3826
3827        let mk = |id: &str, npub: &str| Message {
3828            id: id.into(), content: "x".into(), at: 9_000_000,
3829            npub: Some(npub.into()), ..Default::default()
3830        };
3831        // Mirror the commit path: buffering only ever happens AFTER the STATE add (the
3832        // flush drops anything not STATE-resident as deletion protection).
3833        let seed = |chat: &str, m: &Message| {
3834            let m = m.clone();
3835            let chat = chat.to_string();
3836            async move {
3837                let mut st = crate::state::STATE.lock().await;
3838                st.add_message_to_participant(&chat, &m);
3839            }
3840        };
3841        let wrap_a1 = ([0xA1u8; 32], 111u64);
3842        let wrap_b1 = ([0xB1u8; 32], 222u64);
3843        let a1 = mk("bp_a1", "npub1chata");
3844        let b1 = mk("bp_b1", "npub1chatb");
3845        let a2 = mk("bp_a2", "npub1chata");
3846        seed("npub1chata", &a1).await;
3847        seed("npub1chatb", &b1).await;
3848        seed("npub1chata", &a2).await;
3849
3850        use crate::event_handler::InboundEventHandler;
3851        assert!(batcher.buffer_persist("npub1chata", &a1, Some(wrap_a1)), "batcher owns the persist");
3852        assert!(batcher.buffer_persist("npub1chatb", &b1, Some(wrap_b1)));
3853        assert!(batcher.buffer_persist("npub1chata", &a2, None));
3854        assert_eq!(batcher.buffered(), 3);
3855
3856        let ledgered = |bytes: [u8; 32]| {
3857            let id = nostr_sdk::prelude::EventId::from_byte_array(bytes);
3858            crate::db::wrappers::load_negentropy_items().unwrap().iter().any(|(e, _)| *e == id)
3859        };
3860        assert!(!ledgered(wrap_a1.0), "wrapper unledgered while its message sits buffered");
3861
3862        assert_eq!(batcher.flush().await, 3, "all buffered messages written");
3863        assert_eq!(batcher.buffered(), 0);
3864        assert!(event_exists("bp_a1").unwrap() && event_exists("bp_b1").unwrap() && event_exists("bp_a2").unwrap());
3865        assert!(ledgered(wrap_a1.0) && ledgered(wrap_b1.0), "wrappers ledgered with the flush");
3866        let a = crate::db::id_cache::get_chat_id_by_identifier("npub1chata").unwrap();
3867        let b = crate::db::id_cache::get_chat_id_by_identifier("npub1chatb").unwrap();
3868        assert_ne!(a, b, "rows grouped under their own chats");
3869
3870        // A swap between buffering and flushing. The batcher holds the account
3871        // that filled it, so the drain lands there rather than in whoever is
3872        // live by the time it runs — the buffer is one account's inbox.
3873        let filled_under = crate::db::current_session();
3874        let late = mk("bp_late", "npub1chata");
3875        seed("npub1chata", &late).await;
3876        let wrap_late = ([0x5Eu8; 32], 333u64);
3877        batcher.buffer_persist("npub1chata", &late, Some(wrap_late));
3878
3879        let next = make_test_npub(TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
3880        std::fs::create_dir_all(crate::db::shared_test_data_dir().join(&next)).unwrap();
3881        crate::db::set_current_account(next.clone()).unwrap();
3882        crate::db::init_database(&next).unwrap();
3883
3884        assert_eq!(batcher.flush().await, 1, "the buffer still drains");
3885        assert!(
3886            crate::db::with_session(filled_under, async {
3887                event_exists("bp_late").unwrap() && ledgered(wrap_late.0)
3888            })
3889            .await,
3890            "written to the account that received it, and its wrapper ledgered there"
3891        );
3892        assert!(!event_exists("bp_late").unwrap(), "the account swapped in never sees it");
3893        assert_eq!(batcher.buffered(), 0, "and the buffer is empty either way");
3894    }
3895
3896    // A deletion landing while its target sits buffered must not resurrect the message:
3897    // the same-task path purges via on_message_deleted, and the cross-task path (live
3898    // subscription, different handler) is caught by the flush's deletion-tombstone filter.
3899    // The filter keys on the POSITIVE tombstone, never STATE absence — an LRU-evicted (but
3900    // not deleted) message MUST still persist and ledger, or archive sync could silently
3901    // drop the exact history it exists to persist.
3902    #[tokio::test]
3903    async fn role_mentions_survive_a_reload() {
3904        let (_tmp, _guard) = init_test_db();
3905        let ids = vec!["ab".repeat(32), "cd".repeat(32)];
3906        let msg = Message { id: "pings-a-role".into(), content: "@Raid Team go".into(), at: 1_000_000, role_mentions: ids.clone(), ..Default::default() };
3907        save_message("npub1roles", &msg).await.unwrap();
3908        let (_, back) = get_message_by_id("pings-a-role").await.unwrap().unwrap();
3909        assert_eq!(back.role_mentions, ids, "through the message view");
3910        let last = get_all_chats_last_messages().await.unwrap();
3911        let row = last.values().flatten().find(|m| m.id == "pings-a-role").unwrap();
3912        assert_eq!(row.role_mentions, ids, "and the chat list's last messages");
3913    }
3914
3915    #[tokio::test]
3916    async fn the_chat_lists_last_message_is_the_newest_to_the_millisecond() {
3917        let (_tmp, _guard) = init_test_db();
3918        let chat = "npub1samesecond";
3919        let later = Message { id: "sent-later".into(), content: "b".into(), at: 1_793_470_953_878, ..Default::default() };
3920        let earlier = Message { id: "sent-earlier".into(), content: "a".into(), at: 1_793_470_953_000, ..Default::default() };
3921        save_message(chat, &later).await.unwrap();
3922        save_message(chat, &earlier).await.unwrap();
3923        // The earlier one arrived last, as a catch-up batch can deliver them.
3924        crate::db::get_write_connection_guard_static().unwrap()
3925            .execute("UPDATE events SET received_at = received_at + 1000 WHERE id = 'sent-earlier'", [])
3926            .unwrap();
3927        let last = get_all_chats_last_messages().await.unwrap();
3928        let row = last.get(chat).and_then(|m| m.last()).unwrap();
3929        assert_eq!(row.id, "sent-later", "the newest by its ms, not by arrival");
3930        assert_eq!(row.at, 1_793_470_953_878, "and dated to the ms the chat view shows");
3931    }
3932
3933    #[tokio::test]
3934    async fn a_writer_posts_provenance_survives_a_reload() {
3935        let (_tmp, _guard) = init_test_db();
3936        let msg = Message { id: "from-a-writer".into(), content: "announced".into(), at: 1_000_000, writer: true, ..Default::default() };
3937        save_message("npub1writers", &msg).await.unwrap();
3938        let (_, back) = get_message_by_id("from-a-writer").await.unwrap().unwrap();
3939        assert!(back.writer, "through the message view");
3940        let last = get_all_chats_last_messages().await.unwrap();
3941        assert!(last.values().flatten().find(|m| m.id == "from-a-writer").unwrap().writer, "and the chat list's last messages");
3942        let plain = Message { id: "from-the-open".into(), content: "said".into(), at: 1_000_001, ..Default::default() };
3943        save_message("npub1writers", &plain).await.unwrap();
3944        assert!(!get_message_by_id("from-the-open").await.unwrap().unwrap().1.writer);
3945    }
3946
3947    #[tokio::test]
3948    async fn a_delete_tombstone_survives_a_restart() {
3949        // NIP-09 is best-effort: a relay that ignored it re-serves the wrap days
3950        // later. The events row is gone by then and the in-session tombstone set
3951        // died with the process — only the durable row lets ingest keep refusing.
3952        let (_tmp, _guard) = init_test_db();
3953        let msg = Message {
3954            id: "resurrect-me".into(), content: "note".into(), at: 1_000_000,
3955            mine: true, ..Default::default()
3956        };
3957        save_message("npub1notes", &msg).await.unwrap();
3958        add_message_tombstone("resurrect-me").unwrap();
3959        delete_event("resurrect-me").await.unwrap();
3960
3961        // Simulated restart/swap: the in-session set dies...
3962        crate::db::close_database();
3963        assert!(!crate::state::was_message_deleted("resurrect-me"), "session set cleared");
3964        // ...and account init re-seeds the refusal from the durable rows.
3965        crate::state::seed_message_tombstones(load_message_tombstones().unwrap());
3966        assert!(crate::state::was_message_deleted("resurrect-me"), "the durable tombstone re-seeds");
3967    }
3968
3969    #[tokio::test]
3970    async fn buffered_message_deleted_before_flush_never_persists() {
3971        let (_tmp, _guard) = init_test_db();
3972        let handler = crate::event_handler::NoOpEventHandler;
3973        let batcher = crate::event_handler::BatchingPersist::new(&handler);
3974        use crate::event_handler::InboundEventHandler;
3975
3976        let chat = "npub1delchat";
3977        let mk = |id: &str| Message {
3978            id: id.into(), content: "x".into(), at: 9_500_000,
3979            npub: Some(chat.into()), ..Default::default()
3980        };
3981        let ledgered = |bytes: [u8; 32]| {
3982            let id = nostr_sdk::prelude::EventId::from_byte_array(bytes);
3983            crate::db::wrappers::load_negentropy_items().unwrap().iter().any(|(e, _)| *e == id)
3984        };
3985
3986        // Same-task deletion (sync stream): commit_deletion fires on_message_deleted on
3987        // the batching handler → the buffered entry purges immediately.
3988        let m1 = mk("del_sametask");
3989        {
3990            let mut st = crate::state::STATE.lock().await;
3991            st.add_message_to_participant(chat, &m1);
3992        }
3993        batcher.buffer_persist(chat, &m1, Some(([0xD1u8; 32], 444)));
3994        {
3995            let mut st = crate::state::STATE.lock().await;
3996            st.remove_message("del_sametask");
3997        }
3998        batcher.on_message_deleted(chat, "del_sametask");
3999        assert_eq!(batcher.buffered(), 0, "deletion purges the buffered target");
4000
4001        // Cross-task deletion (live subscription, plain handler): no purge call — the
4002        // deletion tombstone (recorded by commit_deletion) drops it at flush time.
4003        let m2 = mk("del_crosstask");
4004        {
4005            let mut st = crate::state::STATE.lock().await;
4006            st.add_message_to_participant(chat, &m2);
4007        }
4008        batcher.buffer_persist(chat, &m2, Some(([0xD2u8; 32], 555)));
4009        crate::state::note_message_deleted("del_crosstask");
4010
4011        // LRU eviction is NOT deletion: gone from STATE, no tombstone → must persist.
4012        let m3 = mk("evicted_ok");
4013        let wrap_evicted = ([0xE0u8; 32], 666u64);
4014        {
4015            let mut st = crate::state::STATE.lock().await;
4016            st.add_message_to_participant(chat, &m3);
4017            st.remove_message("evicted_ok");
4018        }
4019        batcher.buffer_persist(chat, &m3, Some(wrap_evicted));
4020
4021        assert_eq!(batcher.flush().await, 1, "tombstoned target dropped, evicted message written");
4022        assert!(!event_exists("del_sametask").unwrap(), "purged message never persisted");
4023        assert!(!event_exists("del_crosstask").unwrap(), "tombstoned message never persisted");
4024        assert!(event_exists("evicted_ok").unwrap(), "evicted-but-not-deleted message persisted");
4025        assert!(ledgered(wrap_evicted.0), "evicted message's wrapper ledgered with it");
4026    }
4027}
4028
4029/// The stored context a pin proof needs to recover a message's wrap: its
4030/// `wrapper_event_id` and the rumor's stored tags (for the epoch binding).
4031/// `(wrapper_event_id, rumor tags)`.
4032type WrapContext = (Option<String>, Vec<Vec<String>>);
4033
4034pub fn get_event_wrap_context(event_id: &str) -> Result<Option<WrapContext>, String> {
4035    let conn = super::get_db_connection_guard_static()?;
4036    let row: Option<(Option<String>, String)> = conn
4037        .query_row(
4038            "SELECT wrapper_event_id, tags FROM events WHERE id = ?1",
4039            rusqlite::params![event_id],
4040            |r| Ok((r.get(0)?, r.get(1)?)),
4041        )
4042        .optional()
4043        .map_err(|e| format!("get wrap context: {e}"))?;
4044    Ok(row.map(|(wrap, tags_json)| {
4045        let tags: Vec<Vec<String>> = serde_json::from_str(&tags_json).unwrap_or_default();
4046        (wrap, tags)
4047    }))
4048}